@runware/sdk-js 1.2.0 → 1.2.1-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -13,9 +13,9 @@ declare enum ETaskType {
13
13
  UPSCALE = "upscale",
14
14
  REMOVE_BACKGROUND = "removeBackground",
15
15
  VIDEO_INFERENCE = "videoInference",
16
+ CAPTION = "caption",
16
17
  GET_RESPONSE = "getResponse",
17
18
  PHOTO_MAKER = "photoMaker",
18
- IMAGE_CAPTION = "imageCaption",
19
19
  IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
20
20
  IMAGE_MASKING = "imageMasking",
21
21
  PROMPT_ENHANCE = "promptEnhance",
@@ -203,11 +203,19 @@ interface IRefiner {
203
203
  startStepPercentage?: number;
204
204
  }
205
205
  interface IRequestImageToText extends IAdditionalResponsePayload {
206
+ model?: string;
206
207
  inputImage?: File | string;
208
+ inputs?: {
209
+ video?: InputsValue;
210
+ } & {
211
+ [key: string]: unknown;
212
+ };
207
213
  includeCost?: boolean;
208
214
  customTaskUUID?: string;
209
215
  taskUUID?: string;
210
216
  retry?: number;
217
+ deliveryMethod?: string;
218
+ skipResponse?: boolean;
211
219
  }
212
220
  interface IImageToText {
213
221
  taskType: ETaskType;
@@ -697,7 +705,15 @@ declare class RunwareBase {
697
705
  _timeoutDuration: number;
698
706
  ensureConnectionUUID: string | null;
699
707
  constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
700
- private getResultUUID;
708
+ /**
709
+ * Returns the first string value found in the result object for the given keys.
710
+ * Used to extract a value (such as a UUID, text, or other result parameter) from a result object.
711
+ * The keys provided in resultKeys may refer to UUIDs (e.g., mediaUUID, imageUUID, videoUUID) or other string fields (e.g., text for captioning).
712
+ * @param result - The result object to search for a string value.
713
+ * @param resultKeys - The list of keys to check in order of priority.
714
+ * @returns The first string value found for the specified keys, or undefined if none found.
715
+ */
716
+ private getResultValue;
701
717
  /**
702
718
  * Shared polling logic for async results.
703
719
  * @param taskUUID - The task UUID to poll for.
@@ -726,7 +742,7 @@ declare class RunwareBase {
726
742
  imageInference(params: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
727
743
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
728
744
  controlNetPreprocess: (params: IControlNetPreprocess) => Promise<IControlNetImage | null>;
729
- requestImageToText: ({ inputImage, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
745
+ requestImageToText: ({ inputImage, inputs, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includePayload, includeGenerationTime, deliveryMethod, skipResponse, model, }: IRequestImageToText) => Promise<IImageToText>;
730
746
  caption: (params: IRequestImageToText) => Promise<IImageToText>;
731
747
  /**
732
748
  * Remove the background from an image or video.
package/dist/index.d.ts CHANGED
@@ -13,9 +13,9 @@ declare enum ETaskType {
13
13
  UPSCALE = "upscale",
14
14
  REMOVE_BACKGROUND = "removeBackground",
15
15
  VIDEO_INFERENCE = "videoInference",
16
+ CAPTION = "caption",
16
17
  GET_RESPONSE = "getResponse",
17
18
  PHOTO_MAKER = "photoMaker",
18
- IMAGE_CAPTION = "imageCaption",
19
19
  IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
20
20
  IMAGE_MASKING = "imageMasking",
21
21
  PROMPT_ENHANCE = "promptEnhance",
@@ -203,11 +203,19 @@ interface IRefiner {
203
203
  startStepPercentage?: number;
204
204
  }
205
205
  interface IRequestImageToText extends IAdditionalResponsePayload {
206
+ model?: string;
206
207
  inputImage?: File | string;
208
+ inputs?: {
209
+ video?: InputsValue;
210
+ } & {
211
+ [key: string]: unknown;
212
+ };
207
213
  includeCost?: boolean;
208
214
  customTaskUUID?: string;
209
215
  taskUUID?: string;
210
216
  retry?: number;
217
+ deliveryMethod?: string;
218
+ skipResponse?: boolean;
211
219
  }
212
220
  interface IImageToText {
213
221
  taskType: ETaskType;
@@ -697,7 +705,15 @@ declare class RunwareBase {
697
705
  _timeoutDuration: number;
698
706
  ensureConnectionUUID: string | null;
699
707
  constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
700
- private getResultUUID;
708
+ /**
709
+ * Returns the first string value found in the result object for the given keys.
710
+ * Used to extract a value (such as a UUID, text, or other result parameter) from a result object.
711
+ * The keys provided in resultKeys may refer to UUIDs (e.g., mediaUUID, imageUUID, videoUUID) or other string fields (e.g., text for captioning).
712
+ * @param result - The result object to search for a string value.
713
+ * @param resultKeys - The list of keys to check in order of priority.
714
+ * @returns The first string value found for the specified keys, or undefined if none found.
715
+ */
716
+ private getResultValue;
701
717
  /**
702
718
  * Shared polling logic for async results.
703
719
  * @param taskUUID - The task UUID to poll for.
@@ -726,7 +742,7 @@ declare class RunwareBase {
726
742
  imageInference(params: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
727
743
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, taskUUID: _taskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
728
744
  controlNetPreprocess: (params: IControlNetPreprocess) => Promise<IControlNetImage | null>;
729
- requestImageToText: ({ inputImage, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
745
+ requestImageToText: ({ inputImage, inputs, includeCost, customTaskUUID, taskUUID: _taskUUID, retry, includePayload, includeGenerationTime, deliveryMethod, skipResponse, model, }: IRequestImageToText) => Promise<IImageToText>;
730
746
  caption: (params: IRequestImageToText) => Promise<IImageToText>;
731
747
  /**
732
748
  * Remove the background from an image or video.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ve=Object.create;var ce=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var ze=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var je=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ge(e))!He.call(l,s)&&s!==t&&ce(l,s,{get:()=>e[s],enumerable:!(n=Be(e,s))||n.enumerable});return l};var Qe=(l,e,t)=>(t=l!=null?Ve(qe(l)):{},je(e||!l||!l.__esModule?ce(t,"default",{value:l,enumerable:!0}):t,l));var Se=ze((gn,ve)=>{"use strict";var De=l=>l&&l.CLOSING===2,rt=()=>typeof WebSocket<"u"&&De(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},_e=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,it=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&&lt.forEach(n=>{l[n]=e[n]})},xe=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof xe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=at();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!De(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let I=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let p=new Error(y);p.code=c,Array.isArray(o.error)&&o.error.forEach(([f])=>f(p)),n.onerror&&n.onerror(p)},0),m=()=>{if(I("close"),a++,I("retries count:",a),a>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(d,r):r=_e(d),I("reconnectDelay:",r),i&&setTimeout(u,r)},u=()=>{I("connect");let c=n;n=new d.constructor(l,e),s=setTimeout(()=>{I("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),I("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),I("open"),r=_e(d),I("reconnectDelay:",r),a=0}),n.addEventListener("close",m),ut(n,c,o)};I("init"),u(),this.close=(c=1e3,y="",{keepClosed:p=!1,fastClose:f=!0,delay:b=0}={})=>{if(b&&(r=b),i=!p,n.close(c,y),f){let k={code:c,reason:y,wasClean:!0};m(),Array.isArray(o.close)&&o.close.forEach(([R,h])=>{R(k),n.removeEventListener("close",R,h)}),n.onclose&&(n.onclose(k),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,p)=>{Array.isArray(o[c])?o[c].some(([f])=>f===y)||o[c].push([y,p]):o[c]=[[y,p]],n.addEventListener(c,y,p)},this.removeEventListener=(c,y,p)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([f])=>f!==y)),n.removeEventListener(c,y,p)}};ve.exports=xe});var de=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(de||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Z=(p=>(p.IMAGE_INFERENCE="imageInference",p.IMAGE_UPLOAD="imageUpload",p.UPSCALE="upscale",p.REMOVE_BACKGROUND="removeBackground",p.VIDEO_INFERENCE="videoInference",p.GET_RESPONSE="getResponse",p.PHOTO_MAKER="photoMaker",p.IMAGE_CAPTION="imageCaption",p.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",p.IMAGE_MASKING="imageMasking",p.PROMPT_ENHANCE="promptEnhance",p.AUTHENTICATION="authentication",p.MODEL_UPLOAD="modelUpload",p.MODEL_SEARCH="modelSearch",p.MEDIA_STORAGE="mediaStorage",p.VECTORIZE="vectorize",p))(Z||{}),pe=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(pe||{}),ge=(m=>(m.canny="canny",m.depth="depth",m.mlsd="mlsd",m.normalbae="normalbae",m.openpose="openpose",m.tile="tile",m.seg="seg",m.lineart="lineart",m.lineart_anime="lineart_anime",m.shuffle="shuffle",m.scribble="scribble",m.softedge="softedge",m))(ge||{}),me=(U=>(U.canny="canny",U.depth_leres="depth_leres",U.depth_midas="depth_midas",U.depth_zoe="depth_zoe",U.inpaint_global_harmonious="inpaint_global_harmonious",U.lineart_anime="lineart_anime",U.lineart_coarse="lineart_coarse",U.lineart_realistic="lineart_realistic",U.lineart_standard="lineart_standard",U.mlsd="mlsd",U.normal_bae="normal_bae",U.scribble_hed="scribble_hed",U.scribble_pidinet="scribble_pidinet",U.seg_ofade20k="seg_ofade20k",U.seg_ofcoco="seg_ofcoco",U.seg_ufade20k="seg_ufade20k",U.shuffle="shuffle",U.softedge_hed="softedge_hed",U.softedge_hedsafe="softedge_hedsafe",U.softedge_pidinet="softedge_pidinet",U.softedge_pidisafe="softedge_pidisafe",U.tile_gaussian="tile_gaussian",U.openpose="openpose",U.openpose_face="openpose_face",U.openpose_faceonly="openpose_faceonly",U.openpose_full="openpose_full",U.openpose_hand="openpose_hand",U))(me||{}),Je=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Je||{}),Ze=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ze||{}),Ye=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(Ye||{}),$e=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))($e||{}),Xe=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(Xe||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var W=6e4,K=1e3,Ie=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ye=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},S=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),he=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),_=()=>tt(),Ue=l=>nt(l);var fe=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,d=a?.[i];if(!d)return o;if(Array.isArray(d)&&/^\d+$/.test(i)){let I=parseInt(i,10);return I>=0&&I<d.length?a[i]=d[I]:a[i]??o}else return a[i]??o},e||{})??{},be=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var Te=(l,e)=>l.filter(t=>t.key!==e.key);var T=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},st=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,Re=()=>st(1,Number.MAX_SAFE_INTEGER),ke=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(d){clearInterval(o),clearTimeout(i),a(d)}},s)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await be(t),await x(l,{...e,maxRetries:s});else throw r}};var A=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=W}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=_();if(typeof e=="string"&&Ue(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await he(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:d,includeCost:I,outputQuality:g,customTaskUUID:m,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:p})=>{let f=c||this._globalMaxRetries,b,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let R=await this.uploadImage(e);if(!R?.imageUUID)return null;let h=u||m||_(),M={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:h,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:r}),...T({key:"outputFormat",value:a}),...T({key:"includeCost",value:I}),...T({key:"highThresholdCanny",value:i}),...T({key:"lowThresholdCanny",value:o}),...T({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...M}),b=this.globalListener({taskUUID:h});let O=await S(({resolve:B,reject:G})=>{let v=this.getSingleMessage({taskUUID:h});if(v){if(v?.error)return G(v),!0;if(v)return B(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:O,payload:p?M:void 0,startTime:y?k:void 0}),O},{maxRetries:f,callback:()=>{b?.destroy()}})}catch(R){throw R}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,includeCost:t,customTaskUUID:n,taskUUID:s,retry:r,includePayload:a,includeGenerationTime:i})=>{let o=r||this._globalMaxRetries,d,I=Date.now();try{return await x(async()=>{await this.ensureConnection();let g=e?await this.uploadImage(e):null,m=s||n||_(),u={taskUUID:m,taskType:"imageCaption",inputImage:g?.imageUUID,...T({key:"includeCost",value:t})};this.send(u),d=this.globalListener({taskUUID:m});let c=await S(({resolve:y,reject:p})=>{let f=this.getSingleMessage({taskUUID:m});if(f){if(f?.error)return p(f),!0;if(f)return delete this._globalMessages[m],y(f),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:c,payload:a?u:void 0,startTime:i?I:void 0}),c},{maxRetries:o,callback:()=>{d?.destroy()}})}catch(g){throw g}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:d,taskUUID:I,retry:g,includeGenerationTime:m,includePayload:u,skipResponse:c,deliveryMethod:y})=>{try{let p;e&&(p=await this.uploadImage(e));let b={taskUUID:I||d||_(),inputImage:p?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...T({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:u,includeGenerationTime:m,retry:g,deliveryMethod:y},k=await this.baseSingleRequest({payload:{...b,taskType:"upscale"},debugKey:"upscale"});if(c)return k;if(y==="async"){let R=k?.taskUUID;return(await this.pollForAsyncResults({taskUUID:R}))[0]}return k}catch(p){throw p}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:d})=>{let I=i||this._globalMaxRetries,g,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:u});let y=await S(({resolve:p,reject:f})=>{let b=this._globalMessages[u];if(b?.error)return f(b),!0;if(b?.length>=n)return delete this._globalMessages[u],p(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:o?m:void 0}),y},{maxRetries:I,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let d=r||s||_();this.send({...a,taskUUID:d,taskType:"modelUpload"});let I,g;return o=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?I=u:c&&(g=c)}}),await S(({resolve:u,reject:c})=>{if(I)return u(I),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:d,...I}=e,g=s||this._globalMaxRetries,m,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let p=this._globalImages.filter(h=>u.includes(h.taskUUID)),f=a||r||_();u.push(f);let b=i-p.length,k={...I,...I.seed?{seed:I.seed}:{seed:Re()},...t??{},taskUUID:f,taskType:"photoMaker",numberResults:i};this.send({...k,numberResults:b}),m=this.listenToImages({onPartialImages:n,taskUUID:f,groupKey:"REQUEST_IMAGES",requestPayload:d?k:void 0,startTime:o?y:void 0});let R=await this.getSimilarImages({taskUUID:u,numberResults:i,lis:m});return m.destroy(),R},{maxRetries:g,callback:()=>{m?.destroy()}})}catch(p){if(p.taskUUID)throw p;if(c>=g)return this.handleIncompleteImages({taskUUIDs:u,error:p})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...d}=e,I=s||this._globalMaxRetries,g,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={...d,taskUUID:u};this.send(c),g=this.globalListener({taskUUID:u});let y=await S(({resolve:p,reject:f})=>{let b=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(b){if(b?.error)return f(b),!0;if(b)return delete this._globalMessages[u],p(b),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:i?c:void 0,startTime:o?m:void 0}),g.destroy(),y},{maxRetries:I,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getResultUUID(e){for(let t of["mediaUUID","imageUUID","videoUUID"])if(typeof e[t]=="string")return e[t]}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await ke(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[]){let d=this.getResultUUID(o);d&&n.set(d,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],I=o.filter(m=>(m?.taskUUID||m?.taskType)===n);if(d.filter(m=>(m?.taskUUID||m?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(I.length){e({[n]:o});return}},r={key:n||_(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Te(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){ye(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=fe({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:d,height:I,width:g,model:m,steps:u,scheduler:c,seed:y,CFGScale:p,clipSkip:f,usePromptWeighting:b,promptWeighting:k,numberResults:R=1,onPartialImages:h,includeCost:M,customTaskUUID:O,taskUUID:B,retry:G,refiner:v,maskMargin:U,outputQuality:$,controlNet:q,lora:X,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Ce,includePayload:Ee,...Me},Oe){let C,ie,N=[],le=0,ue=G||this._globalMaxRetries;try{await this.ensureConnection();let w=null,H=null,z=[];if(i){let D=await this.uploadImage(i);if(!D)return[];w=D.imageUUID}if(o){let D=await this.uploadImage(o);if(!D)return[];H=D.imageUUID}if(q?.length)for(let D=0;D<q.length;D++){let E=q[D],{endStep:j,startStep:L,weight:Q,guideImage:P,controlMode:Le,startStepPercentage:Pe,endStepPercentage:Ke,model:We}=E,Fe=P?await this.uploadImage(P):null;z.push({guideImage:Fe?.imageUUID,model:We,endStep:j,startStep:L,weight:Q,...T({key:"startStepPercentage",value:Pe}),...T({key:"endStepPercentage",value:Ke}),controlMode:Le||"controlnet"})}ie={taskType:"imageInference",model:m,positivePrompt:r,...a?{negativePrompt:a}:{},...I?{height:I}:{},...g?{width:g}:{},numberResults:R,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:d}),...T({key:"CFGScale",value:p}),...T({key:"clipSkip",value:f}),...T({key:"maskMargin",value:U}),...T({key:"usePromptWeighting",value:b}),...T({key:"steps",value:u}),...k?{promptWeighting:k}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...T({key:"includeCost",value:M}),...w?{seedImage:w}:{},...H?{maskImage:H}:{},...$?{outputQuality:$}:{},...z.length?{controlNet:z}:{},...X?.length?{lora:X}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...Me,...Oe??{}};let Ne=Date.now();return await x(async()=>{le++,C?.destroy();let D=this._globalImages.filter(P=>N.includes(P.taskUUID)),E=B||O||_();N.push(E);let j=R-D.length,L={...ie,taskUUID:E,numberResults:j};this.send(L),C=this.listenToImages({onPartialImages:h,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ee?L:void 0,startTime:Ce?Ne:void 0});let Q=await this.getSimilarImages({taskUUID:N,numberResults:R,lis:C});return C.destroy(),Q},{maxRetries:ue,callback:()=>{C?.destroy()}})}catch(w){if(le>=ue)return this.handleIncompleteImages({taskUUIDs:N,error:w});throw w}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=_(),d,I,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(I)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let m=this.connected(),u=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),u=!0);let c=a%10===0&&u;m?(g(),s(!0)):a>=i?(g(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(m){g(),r(m)}},t)),I=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await S(({resolve:r,reject:a,intervalId:i})=>{let o=Array.isArray(e)?e:[e],d=this._globalImages.filter(I=>o.includes(I.taskUUID));if(this._globalError){let I=this._globalError;return this._globalError=void 0,clearInterval(i),a?.(I),!0}else if(d.length>=t)return clearInterval(i),this._globalImages=this._globalImages.filter(I=>!o.includes(I.taskUUID)),r([...d].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var we=Qe(Se(),1),F=class extends A{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new we.default(this._url),this.connect()}};import ct from"ws";var V=class extends A{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ae;typeof window>"u"?Ae=V:Ae=F;export{pe as EControlMode,Ye as EModelArchitecture,Xe as EModelConditioning,Ze as EModelFormat,$e as EModelType,Je as EOpenPosePreProcessor,et as EPhotoMakerEnum,me as EPreProcessor,ge as EPreProcessorGroup,Z as ETaskType,de as Environment,Ae as Runware,F as RunwareClient,V as RunwareServer,J as SdkType};
1
+ var Ve=Object.create;var ce=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var ze=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var je=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ge(e))!He.call(l,s)&&s!==t&&ce(l,s,{get:()=>e[s],enumerable:!(n=Be(e,s))||n.enumerable});return l};var Qe=(l,e,t)=>(t=l!=null?Ve(qe(l)):{},je(e||!l||!l.__esModule?ce(t,"default",{value:l,enumerable:!0}):t,l));var Se=ze((gn,ve)=>{"use strict";var De=l=>l&&l.CLOSING===2,rt=()=>typeof WebSocket<"u"&&De(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},_e=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,it=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&&lt.forEach(n=>{l[n]=e[n]})},xe=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof xe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=at();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!De(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=d.debug?(...c)=>console.log("RWS:",...c):()=>{},I=(c,y)=>setTimeout(()=>{let p=new Error(y);p.code=c,Array.isArray(o.error)&&o.error.forEach(([b])=>b(p)),n.onerror&&n.onerror(p)},0),m=()=>{if(g("close"),a++,g("retries count:",a),a>d.maxRetries){I("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(d,r):r=_e(d),g("reconnectDelay:",r),i&&setTimeout(u,r)},u=()=>{g("connect");let c=n;n=new d.constructor(l,e),s=setTimeout(()=>{g("timeout"),n.close(),I("ETIMEDOUT","Connection timeout")},d.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),g("open"),r=_e(d),g("reconnectDelay:",r),a=0}),n.addEventListener("close",m),ut(n,c,o)};g("init"),u(),this.close=(c=1e3,y="",{keepClosed:p=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(r=f),i=!p,n.close(c,y),b){let k={code:c,reason:y,wasClean:!0};m(),Array.isArray(o.close)&&o.close.forEach(([R,h])=>{R(k),n.removeEventListener("close",R,h)}),n.onclose&&(n.onclose(k),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,p)=>{Array.isArray(o[c])?o[c].some(([b])=>b===y)||o[c].push([y,p]):o[c]=[[y,p]],n.addEventListener(c,y,p)},this.removeEventListener=(c,y,p)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([b])=>b!==y)),n.removeEventListener(c,y,p)}};ve.exports=xe});var de=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(de||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Z=(p=>(p.IMAGE_INFERENCE="imageInference",p.IMAGE_UPLOAD="imageUpload",p.UPSCALE="upscale",p.REMOVE_BACKGROUND="removeBackground",p.VIDEO_INFERENCE="videoInference",p.CAPTION="caption",p.GET_RESPONSE="getResponse",p.PHOTO_MAKER="photoMaker",p.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",p.IMAGE_MASKING="imageMasking",p.PROMPT_ENHANCE="promptEnhance",p.AUTHENTICATION="authentication",p.MODEL_UPLOAD="modelUpload",p.MODEL_SEARCH="modelSearch",p.MEDIA_STORAGE="mediaStorage",p.VECTORIZE="vectorize",p))(Z||{}),pe=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(pe||{}),ge=(m=>(m.canny="canny",m.depth="depth",m.mlsd="mlsd",m.normalbae="normalbae",m.openpose="openpose",m.tile="tile",m.seg="seg",m.lineart="lineart",m.lineart_anime="lineart_anime",m.shuffle="shuffle",m.scribble="scribble",m.softedge="softedge",m))(ge||{}),me=(U=>(U.canny="canny",U.depth_leres="depth_leres",U.depth_midas="depth_midas",U.depth_zoe="depth_zoe",U.inpaint_global_harmonious="inpaint_global_harmonious",U.lineart_anime="lineart_anime",U.lineart_coarse="lineart_coarse",U.lineart_realistic="lineart_realistic",U.lineart_standard="lineart_standard",U.mlsd="mlsd",U.normal_bae="normal_bae",U.scribble_hed="scribble_hed",U.scribble_pidinet="scribble_pidinet",U.seg_ofade20k="seg_ofade20k",U.seg_ofcoco="seg_ofcoco",U.seg_ufade20k="seg_ufade20k",U.shuffle="shuffle",U.softedge_hed="softedge_hed",U.softedge_hedsafe="softedge_hedsafe",U.softedge_pidinet="softedge_pidinet",U.softedge_pidisafe="softedge_pidisafe",U.tile_gaussian="tile_gaussian",U.openpose="openpose",U.openpose_face="openpose_face",U.openpose_faceonly="openpose_faceonly",U.openpose_full="openpose_full",U.openpose_hand="openpose_hand",U))(me||{}),Je=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Je||{}),Ze=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ze||{}),Ye=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(Ye||{}),$e=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))($e||{}),Xe=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(Xe||{}),et=(I=>(I.NoStyle="No style",I.Cinematic="Cinematic",I.DisneyCharacter="Disney Character",I.DigitalArt="Digital Art",I.Photographic="Photographic",I.FantasyArt="Fantasy art",I.Neonpunk="Neonpunk",I.Enhance="Enhance",I.ComicBook="Comic book",I.Lowpoly="Lowpoly",I.LineArt="Line art",I))(et||{});import{v4 as tt,validate as nt}from"uuid";var W=6e4,K=1e3,Ie=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ye=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},w=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),he=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),_=()=>tt(),Ue=l=>nt(l);var fe=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,d=a?.[i];if(!d)return o;if(Array.isArray(d)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<d.length?a[i]=d[g]:a[i]??o}else return a[i]??o},e||{})??{},Te=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var be=(l,e)=>l.filter(t=>t.key!==e.key);var T=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},st=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,Re=()=>st(1,Number.MAX_SAFE_INTEGER),ke=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(d){clearInterval(o),clearTimeout(i),a(d)}},s)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await Te(t),await x(l,{...e,maxRetries:s});else throw r}};var A=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=W}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=_();if(typeof e=="string"&&Ue(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await he(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:d,includeCost:g,outputQuality:I,customTaskUUID:m,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:p})=>{let b=c||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let R=await this.uploadImage(e);if(!R?.imageUUID)return null;let h=u||m||_(),O={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:h,preProcessorType:t,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:r}),...T({key:"outputFormat",value:a}),...T({key:"includeCost",value:g}),...T({key:"highThresholdCanny",value:i}),...T({key:"lowThresholdCanny",value:o}),...T({key:"includeHandsAndFaceOpenPose",value:d}),...I?{outputQuality:I}:{}};this.send({...O}),f=this.globalListener({taskUUID:h});let M=await w(({resolve:B,reject:G})=>{let v=this.getSingleMessage({taskUUID:h});if(v){if(v?.error)return G(v),!0;if(v)return B(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:M,payload:p?O:void 0,startTime:y?k:void 0}),M},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(R){throw R}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:d,skipResponse:g,model:I})=>{try{let m;e&&(m=await this.uploadImage(e));let c={taskUUID:r||s||_(),taskType:"caption",model:I,inputImage:m?.imageUUID,inputs:t,...T({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(g)return y;if(d==="async"){let p=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:p,resultKeys:["text"]}))[0]}return y}catch(m){throw m}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:d,taskUUID:g,retry:I,includeGenerationTime:m,includePayload:u,skipResponse:c,deliveryMethod:y})=>{try{let p;e&&(p=await this.uploadImage(e));let f={taskUUID:g||d||_(),inputImage:p?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...T({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:u,includeGenerationTime:m,retry:I,deliveryMethod:y},k=await this.baseSingleRequest({payload:{...f,taskType:"upscale"},debugKey:"upscale"});if(c)return k;if(y==="async"){let R=k?.taskUUID;return(await this.pollForAsyncResults({taskUUID:R}))[0]}return k}catch(p){throw p}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:d})=>{let g=i||this._globalMaxRetries,I,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),I=this.globalListener({taskUUID:u});let y=await w(({resolve:p,reject:b})=>{let f=this._globalMessages[u];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[u],p(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return I.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:o?m:void 0}),y},{maxRetries:g,callback:()=>{I?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let d=r||s||_();this.send({...a,taskUUID:d,taskType:"modelUpload"});let g,I;return o=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?g=u:c&&(I=c)}}),await w(({resolve:u,reject:c})=>{if(g)return u(g),!0;if(I)return c(I),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:d,...g}=e,I=s||this._globalMaxRetries,m,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let p=this._globalImages.filter(h=>u.includes(h.taskUUID)),b=a||r||_();u.push(b);let f=i-p.length,k={...g,...g.seed?{seed:g.seed}:{seed:Re()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:i};this.send({...k,numberResults:f}),m=this.listenToImages({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?k:void 0,startTime:o?y:void 0});let R=await this.getSimilarImages({taskUUID:u,numberResults:i,lis:m});return m.destroy(),R},{maxRetries:I,callback:()=>{m?.destroy()}})}catch(p){if(p.taskUUID)throw p;if(c>=I)return this.handleIncompleteImages({taskUUIDs:u,error:p})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...d}=e,g=s||this._globalMaxRetries,I,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={...d,taskUUID:u};this.send(c),I=this.globalListener({taskUUID:u});let y=await w(({resolve:p,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[u],p(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:i?c:void 0,startTime:o?m:void 0}),I.destroy(),y},{maxRetries:g,callback:()=>{I?.destroy()}})}catch(u){throw u}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getResultValue(e,t=["mediaUUID","imageUUID","videoUUID"]){for(let n of t)if(typeof e[n]=="string")return e[n]}async pollForAsyncResults({taskUUID:e,resultKeys:t,numberResults:n=1}){let s=new Map;return await ke(async({resolve:r,reject:a})=>{try{let i=await this.getResponse({taskUUID:e});for(let d of i||[]){let g=this.getResultValue(d,t);g&&s.set(g,d)}return s.size===n?(r(Array.from(s.values())),!0):!1}catch(i){return a(i),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(s.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=o.filter(m=>(m?.taskUUID||m?.taskType)===n);if(d.filter(m=>(m?.taskUUID||m?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(g.length){e({[n]:o});return}},r={key:n||_(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=be(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){ye(this._listeners,e)}listenToImages({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=fe({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:d,height:g,width:I,model:m,steps:u,scheduler:c,seed:y,CFGScale:p,clipSkip:b,usePromptWeighting:f,promptWeighting:k,numberResults:R=1,onPartialImages:h,includeCost:O,customTaskUUID:M,taskUUID:B,retry:G,refiner:v,maskMargin:U,outputQuality:$,controlNet:q,lora:X,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Ce,includePayload:Ee,...Oe},Me){let C,ie,N=[],le=0,ue=G||this._globalMaxRetries;try{await this.ensureConnection();let S=null,H=null,z=[];if(i){let D=await this.uploadImage(i);if(!D)return[];S=D.imageUUID}if(o){let D=await this.uploadImage(o);if(!D)return[];H=D.imageUUID}if(q?.length)for(let D=0;D<q.length;D++){let E=q[D],{endStep:j,startStep:L,weight:Q,guideImage:P,controlMode:Le,startStepPercentage:Pe,endStepPercentage:Ke,model:We}=E,Fe=P?await this.uploadImage(P):null;z.push({guideImage:Fe?.imageUUID,model:We,endStep:j,startStep:L,weight:Q,...T({key:"startStepPercentage",value:Pe}),...T({key:"endStepPercentage",value:Ke}),controlMode:Le||"controlnet"})}ie={taskType:"imageInference",model:m,positivePrompt:r,...a?{negativePrompt:a}:{},...g?{height:g}:{},...I?{width:I}:{},numberResults:R,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:d}),...T({key:"CFGScale",value:p}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:U}),...T({key:"usePromptWeighting",value:f}),...T({key:"steps",value:u}),...k?{promptWeighting:k}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...T({key:"includeCost",value:O}),...S?{seedImage:S}:{},...H?{maskImage:H}:{},...$?{outputQuality:$}:{},...z.length?{controlNet:z}:{},...X?.length?{lora:X}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...Oe,...Me??{}};let Ne=Date.now();return await x(async()=>{le++,C?.destroy();let D=this._globalImages.filter(P=>N.includes(P.taskUUID)),E=B||M||_();N.push(E);let j=R-D.length,L={...ie,taskUUID:E,numberResults:j};this.send(L),C=this.listenToImages({onPartialImages:h,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ee?L:void 0,startTime:Ce?Ne:void 0});let Q=await this.getSimilarImages({taskUUID:N,numberResults:R,lis:C});return C.destroy(),Q},{maxRetries:ue,callback:()=>{C?.destroy()}})}catch(S){if(le>=ue)return this.handleIncompleteImages({taskUUIDs:N,error:S});throw S}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=_(),d,g,I=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(g)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let m=this.connected(),u=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),u=!0);let c=a%10===0&&u;m?(I(),s(!0)):a>=i?(I(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(m){I(),r(m)}},t)),g=setInterval(async()=>{if(this.connected()){I(),s(!0);return}if(this.isInvalidAPIKey()){I(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await w(({resolve:r,reject:a,intervalId:i})=>{let o=Array.isArray(e)?e:[e],d=this._globalImages.filter(g=>o.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),a?.(g),!0}else if(d.length>=t)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!o.includes(g.taskUUID)),r([...d].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var we=Qe(Se(),1),F=class extends A{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new we.default(this._url),this.connect()}};import ct from"ws";var V=class extends A{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ae;typeof window>"u"?Ae=V:Ae=F;export{pe as EControlMode,Ye as EModelArchitecture,Xe as EModelConditioning,Ze as EModelFormat,$e as EModelType,Je as EOpenPosePreProcessor,et as EPhotoMakerEnum,me as EPreProcessor,ge as EPreProcessorGroup,Z as ETaskType,de as Environment,Ae as Runware,F as RunwareClient,V as RunwareServer,J as SdkType};
2
2
  //# sourceMappingURL=index.js.map