@runware/sdk-js 1.1.38 → 1.1.39

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.ts CHANGED
@@ -132,10 +132,22 @@ interface IRequestImage {
132
132
  ipAdapters?: IipAdapter[];
133
133
  outpaint?: IOutpaint;
134
134
  refiner?: IRefiner;
135
+ acceleratorOptions?: TAcceleratorOptions;
136
+ advancedFeatures?: {
137
+ layerDiffuse: boolean;
138
+ };
135
139
  customTaskUUID?: string;
136
140
  onPartialImages?: (images: IImage[], error?: IError) => void;
137
141
  retry?: number;
138
142
  }
143
+ type TAcceleratorOptions = {
144
+ teaCache: boolean;
145
+ teaCacheDistance: number;
146
+ } | {
147
+ deepCache: boolean;
148
+ deepCacheInterval: number;
149
+ deepCacheBranchId: number;
150
+ };
139
151
  interface IOutpaint {
140
152
  top?: number;
141
153
  bottom?: number;
@@ -499,6 +511,17 @@ type TImageMasking = {
499
511
  customTaskUUID?: string;
500
512
  retry?: number;
501
513
  };
514
+ type TImageUpload = {
515
+ image: string;
516
+ customTaskUUID?: string;
517
+ retry?: number;
518
+ };
519
+ type TImageUploadResponse = {
520
+ image: string;
521
+ taskUUID: string;
522
+ imageUUID: number;
523
+ imageURL: string;
524
+ };
502
525
  type TImageMaskingResponse = {
503
526
  taskType: string;
504
527
  taskUUID: string;
@@ -557,7 +580,7 @@ declare class RunwareBase {
557
580
  private listenToImages;
558
581
  private listenToUpload;
559
582
  private globalListener;
560
- requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
583
+ requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
561
584
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
562
585
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
563
586
  removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
@@ -567,6 +590,7 @@ declare class RunwareBase {
567
590
  photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
568
591
  modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
569
592
  imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
593
+ imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
570
594
  protected baseSingleRequest: <T>({ payload, debugKey, }: {
571
595
  payload: Record<string, any>;
572
596
  debugKey: string;
@@ -599,4 +623,4 @@ declare class RunwareServer extends RunwareBase {
599
623
 
600
624
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
601
625
 
602
- export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
626
+ export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ae=Object.create;var te=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Me=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports);var Le=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ee(t))!Oe.call(l,a)&&a!==e&&te(l,a,{get:()=>t[a],enumerable:!(n=Ce(t,a))||n.enumerable});return l};var Ke=(l,t,e)=>(e=l!=null?Ae(Ne(l)):{},Le(t||!l||!l.__esModule?te(e,"default",{value:l,enumerable:!0}):e,l));var he=Me((Vt,Ie)=>{"use strict";var me=l=>l&&l.CLOSING===2,Je=()=>typeof WebSocket<"u"&&me(WebSocket),Ye=()=>({constructor:Je()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ze=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},pe=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,Ze=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},$e=["onopen","onclose","onmessage","onerror"],Xe=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&$e.forEach(n=>{l[n]=t[n]})},ye=function(l,t,e={}){let n,a,o=0,c=0,i=!0,s={};if(!(this instanceof ye))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Ye();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!me(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},d=(m,h)=>setTimeout(()=>{let f=new Error(h);f.code=m,Array.isArray(s.error)&&s.error.forEach(([T])=>T(f)),n.onerror&&n.onerror(f)},0),r=()=>{if(g("close"),c++,g("retries count:",c),c>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=Ze(u,o):o=pe(u),g("reconnectDelay:",o),i&&setTimeout(p,o)},p=()=>{g("connect");let m=n;n=new u.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&ze(n,this,h);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=pe(u),g("reconnectDelay:",o),c=0}),n.addEventListener("close",r),Xe(n,m,s)};g("init"),p(),this.close=(m=1e3,h="",{keepClosed:f=!1,fastClose:T=!0,delay:S=0}={})=>{if(S&&(o=S),i=!f,n.close(m,h),T){let D={code:m,reason:h,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([R,y])=>{R(D),n.removeEventListener("close",R,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,h,f)=>{Array.isArray(s[m])?s[m].some(([T])=>T===h)||s[m].push([h,f]):s[m]=[[h,f]],n.addEventListener(m,h,f)},this.removeEventListener=(m,h,f)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([T])=>T!==h)),n.removeEventListener(m,h,f)}};Ie.exports=ye});var ne=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ne||{}),B=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(B||{}),q=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.PHOTO_MAKER="photoMaker",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.IMAGE_MASKING="imageMasking",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.MODEL_SEARCH="modelSearch",r))(q||{}),re=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(re||{}),se=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))(se||{}),ae=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(ae||{}),We=(o=>(o.openpose="openpose",o.openpose_face="openpose_face",o.openpose_faceonly="openpose_faceonly",o.openpose_full="openpose_full",o.openpose_hand="openpose_hand",o))(We||{}),Fe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Fe||{}),Ge=(p=>(p.flux1d="flux1d",p.flux1s="flux1s",p.pony="pony",p.sdhyper="sdhyper",p.sd1x="sd1x",p.sd1xlcm="sd1xlcm",p.sd3="sd3",p.sdxl="sdxl",p.sdxllcm="sdxllcm",p.sdxldistilled="sdxldistilled",p.sdxlhyper="sdxlhyper",p.sdxllightning="sdxllightning",p.sdxlturbo="sdxlturbo",p))(Ge||{}),Pe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Pe||{}),Be=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(Be||{}),qe=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(qe||{});import{v4 as He,validate as Ve}from"uuid";var H=6e4,oe=1e3,je=100,V={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ie=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},x=(l,{debugKey:t="debugKey",timeoutDuration:e=H,shouldThrowError:n=!0})=>(e=e<oe?oe:e,new Promise((a,o)=>{let c=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(c))},je)})),le=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),U=()=>He(),ce=l=>Ve(l);var ue=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,i)=>{let s=e?0:void 0,u=c?.[i];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?c[i]=u[g]:c[i]??s}else return c[i]??s},t||{})??{},ge=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var de=(l,t)=>l.filter(e=>e.key!==t.key);var b=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{},Qe=(l,t)=>Math.floor(Math.random()*(t-l+1))+l,j=()=>Qe(1,Number.MAX_SAFE_INTEGER);var k=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await ge(e),await k(l,{...t,maxRetries:a});else throw o}};var w=class{constructor({apiKey:t,url:e=V.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=H}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=U();if(typeof t=="string"&&ce(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await le(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:c,highThresholdCanny:i,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:d,customTaskUUID:r,retry:p})=>{let m=p||this._globalMaxRetries,h;try{return await k(async()=>{await this.ensureConnection();let f=await this.uploadImage(t);if(!f?.imageUUID)return null;let T=r||U();this.send({inputImage:f.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:T,preProcessorType:e,...b({key:"height",value:n}),...b({key:"width",value:a}),...b({key:"outputType",value:o}),...b({key:"outputFormat",value:c}),...b({key:"includeCost",value:g}),...b({key:"highThresholdCanny",value:i}),...b({key:"lowThresholdCanny",value:s}),...b({key:"includeHandsAndFaceOpenPose",value:u}),...d?{outputQuality:d}:{}}),h=this.globalListener({taskUUID:T});let S=await x(({resolve:D,reject:R})=>{let y=this.getSingleMessage({taskUUID:T});if(y){if(y?.error)return R(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return h.destroy(),S},{maxRetries:m,callback:()=>{h?.destroy()}})}catch(f){throw f}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,c;try{return await k(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,s=n||U();this.send({taskUUID:s,taskType:"imageCaption",inputImage:i?.imageUUID,...b({key:"includeCost",value:e})}),c=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return c.destroy(),u},{maxRetries:o,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:c,customTaskUUID:i,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await k(async()=>{await this.ensureConnection();let d;d=await this.uploadImage(t);let r=i||U();this.send({taskUUID:r,inputImage:d?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...b({key:"includeCost",value:o}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let p=await x(({resolve:m,reject:h})=>{let f=this.getSingleMessage({taskUUID:r});if(f){if(f?.error)return h(f),!0;if(f)return delete this._globalMessages[r],m(f),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),p},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(d){throw d}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:c})=>{let i=c||this._globalMaxRetries,s;try{return await k(async()=>{await this.ensureConnection();let u=o||U();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...b({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await x(({resolve:d,reject:r})=>{let p=this._globalMessages[u];if(p?.error)return r(p),!0;if(p?.length>=n)return delete this._globalMessages[u],d(p),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:i,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:s,onUploadStream:(r,p)=>{e?.(r,p),r?.status==="ready"?u=r:p&&(g=p)}}),await x(({resolve:r,reject:p})=>{if(u)return r(u),!0;if(g)return p(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:a,customTaskUUID:o,numberResults:c,...i}=t,s=a||this._globalMaxRetries,u,g=[],d=0;try{return await k(async()=>{await this.ensureConnection(),d++;let r=this._globalImages.filter(f=>g.includes(f.taskUUID)),p=o||U();g.push(p);let m=c-r.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:j()},...e??{},numberResults:m,taskUUID:p,taskType:"photoMaker"}),u=this.listenToImages({onPartialImages:n,taskUUID:p,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let h=await this.getSimilarImages({taskUUID:g,numberResults:c,lis:u});return u.destroy(),h},{maxRetries:s,callback:()=>{u?.destroy()}})}catch(r){if(r.taskUUID)throw r;if(d>=s)return this.handleIncompleteImages({taskUUIDs:g,error:r})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s}),i=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=a,this._timeoutDuration=o}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let a=i=>{let s=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||U(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=de(this._listeners,o)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ie(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:c=>{let i=c?.[e]?.filter(s=>s.taskUUID===e);c.error?(t?.(i,c?.error&&c),this._globalError=c):(i=i.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(i,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],c=o?.taskUUID===e?o:null;(c||a)&&t?.(c||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=ue({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:c,seedImage:i,maskImage:s,strength:u,height:g,width:d,model:r,steps:p,scheduler:m,seed:h,CFGScale:f,clipSkip:T,usePromptWeighting:S,promptWeighting:D,numberResults:R=1,onPartialImages:y,includeCost:Te,customTaskUUID:Ue,retry:_e,refiner:Q,maskMargin:ke,outputQuality:I,controlNet:L,lora:J,embeddings:Y,ipAdapters:z,outpaint:Z},Re){let A,$,E=[],X=0,ee=_e||this._globalMaxRetries;try{await this.ensureConnection();let v=null,K=null,W=[];if(i){let _=await this.uploadImage(i);if(!_)return[];v=_.imageUUID}if(s){let _=await this.uploadImage(s);if(!_)return[];K=_.imageUUID}if(L?.length)for(let _=0;_<L.length;_++){let C=L[_],{endStep:F,startStep:G,weight:P,guideImage:N,controlMode:xe,startStepPercentage:De,endStepPercentage:Se,model:ve}=C,we=N?await this.uploadImage(N):null;W.push({guideImage:we?.imageUUID,model:ve,endStep:F,startStep:G,weight:P,...b({key:"startStepPercentage",value:De}),...b({key:"endStepPercentage",value:Se}),controlMode:xe||"controlnet"})}return $={taskType:"imageInference",model:r,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:R,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...b({key:"checkNSFW",value:a}),...b({key:"strength",value:u}),...b({key:"CFGScale",value:f}),...b({key:"clipSkip",value:T}),...b({key:"maskMargin",value:ke}),...b({key:"usePromptWeighting",value:S}),...b({key:"steps",value:p}),...D?{promptWeighting:D}:{},...h?{seed:h}:{seed:j()},...m?{scheduler:m}:{},...Q?{refiner:Q}:{},...Z?{outpaint:Z}:{},...b({key:"includeCost",value:Te}),...v?{seedImage:v}:{},...K?{maskImage:K}:{},...I?{outputQuality:I}:{},...W.length?{controlNet:W}:{},...J?.length?{lora:J}:{},...Y?.length?{embeddings:Y}:{},...z?.length?{ipAdapters:z}:{},...Re??{}},await k(async()=>{X++,A?.destroy();let _=this._globalImages.filter(N=>E.includes(N.taskUUID)),C=Ue||U();E.push(C);let F=R-_.length,G={...$,taskUUID:C,numberResults:F};this.send(G),A=this.listenToImages({onPartialImages:y,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let P=await this.getSimilarImages({taskUUID:E,numberResults:R,lis:A});return A.destroy(),P},{maxRetries:ee,callback:()=>{A?.destroy()}})}catch(v){if(X>=ee)return this.handleIncompleteImages({taskUUIDs:E,error:v});throw v}}async ensureConnection(){if(this.connected()||this._url===V.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let c=0,i=30,s=U(),u,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),p=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),p=!0);let m=c%10===0&&p;r?(d(),a(!0)):c>=i?(d(),o(new Error("Retry timed out"))):(m&&this.connect(),c++)}catch(r){d(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this.isInvalidAPIKey()){d(),o(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:t,numberResults:e,shouldThrowError:n,lis:a}){return await x(({resolve:o,reject:c,intervalId:i})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),c?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var fe=Ke(he(),1),O=class extends w{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new fe.default(this._url),this.connect()}};import et from"ws";var M=class extends w{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.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 et(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:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(c=>{c.listener(o)})}))}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 be;typeof window>"u"?be=M:be=O;export{re as EControlMode,Ge as EModelArchitecture,Be as EModelConditioning,Fe as EModelFormat,Pe as EModelType,We as EOpenPosePreProcessor,qe as EPhotoMakerEnum,ae as EPreProcessor,se as EPreProcessorGroup,q as ETaskType,ne as Environment,be as Runware,O as RunwareClient,M as RunwareServer,B as SdkType};
1
+ var Ee=Object.create;var re=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var Ke=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports);var We=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ne(t))!Le.call(l,a)&&a!==e&&re(l,a,{get:()=>t[a],enumerable:!(n=Oe(t,a))||n.enumerable});return l};var Fe=(l,t,e)=>(e=l!=null?Ee(Me(l)):{},We(t||!l||!l.__esModule?re(e,"default",{value:l,enumerable:!0}):e,l));var fe=Ke((Yt,be)=>{"use strict";var Ie=l=>l&&l.CLOSING===2,ze=()=>typeof WebSocket<"u"&&Ie(WebSocket),Ze=()=>({constructor:ze()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),$e=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},ye=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,Xe=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},et=["onopen","onclose","onmessage","onerror"],tt=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&et.forEach(n=>{l[n]=t[n]})},he=function(l,t,e={}){let n,a,o=0,c=0,i=!0,s={};if(!(this instanceof he))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Ze();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!Ie(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},p=(m,h)=>setTimeout(()=>{let b=new Error(h);b.code=m,Array.isArray(s.error)&&s.error.forEach(([U])=>U(b)),n.onerror&&n.onerror(b)},0),r=()=>{if(g("close"),c++,g("retries count:",c),c>u.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}o?o=Xe(u,o):o=ye(u),g("reconnectDelay:",o),i&&setTimeout(d,o)},d=()=>{g("connect");let m=n;n=new u.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&$e(n,this,h);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=ye(u),g("reconnectDelay:",o),c=0}),n.addEventListener("close",r),tt(n,m,s)};g("init"),d(),this.close=(m=1e3,h="",{keepClosed:b=!1,fastClose:U=!0,delay:S=0}={})=>{if(S&&(o=S),i=!b,n.close(m,h),U){let D={code:m,reason:h,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([k,y])=>{k(D),n.removeEventListener("close",k,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,h,b)=>{Array.isArray(s[m])?s[m].some(([U])=>U===h)||s[m].push([h,b]):s[m]=[[h,b]],n.addEventListener(m,h,b)},this.removeEventListener=(m,h,b)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([U])=>U!==h)),n.removeEventListener(m,h,b)}};be.exports=he});var se=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(se||{}),B=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(B||{}),q=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.PHOTO_MAKER="photoMaker",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.IMAGE_MASKING="imageMasking",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.MODEL_SEARCH="modelSearch",r))(q||{}),ae=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ae||{}),oe=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))(oe||{}),ie=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(ie||{}),Pe=(o=>(o.openpose="openpose",o.openpose_face="openpose_face",o.openpose_faceonly="openpose_faceonly",o.openpose_full="openpose_full",o.openpose_hand="openpose_hand",o))(Pe||{}),Ge=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Ge||{}),Be=(d=>(d.flux1d="flux1d",d.flux1s="flux1s",d.pony="pony",d.sdhyper="sdhyper",d.sd1x="sd1x",d.sd1xlcm="sd1xlcm",d.sd3="sd3",d.sdxl="sdxl",d.sdxllcm="sdxllcm",d.sdxldistilled="sdxldistilled",d.sdxlhyper="sdxlhyper",d.sdxllightning="sdxllightning",d.sdxlturbo="sdxlturbo",d))(Be||{}),qe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(qe||{}),He=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(He||{}),Ve=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(Ve||{});import{v4 as je,validate as Qe}from"uuid";var H=6e4,le=1e3,Je=100,V={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ce=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},x=(l,{debugKey:t="debugKey",timeoutDuration:e=H,shouldThrowError:n=!0})=>(e=e<le?le:e,new Promise((a,o)=>{let c=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(c))},Je)})),ue=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),T=()=>je(),ge=l=>Qe(l);var pe=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,i)=>{let s=e?0:void 0,u=c?.[i];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?c[i]=u[g]:c[i]??s}else return c[i]??s},t||{})??{},de=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var me=(l,t)=>l.filter(e=>e.key!==t.key);var f=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{},Ye=(l,t)=>Math.floor(Math.random()*(t-l+1))+l,j=()=>Ye(1,Number.MAX_SAFE_INTEGER);var R=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await de(e),await R(l,{...t,maxRetries:a});else throw o}};var w=class{constructor({apiKey:t,url:e=V.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=H}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await R(async()=>{let e=T();if(typeof t=="string"&&ge(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ue(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:c,highThresholdCanny:i,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:p,customTaskUUID:r,retry:d})=>{let m=d||this._globalMaxRetries,h;try{return await R(async()=>{await this.ensureConnection();let b=await this.uploadImage(t);if(!b?.imageUUID)return null;let U=r||T();this.send({inputImage:b.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:c}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:s}),...f({key:"includeHandsAndFaceOpenPose",value:u}),...p?{outputQuality:p}:{}}),h=this.globalListener({taskUUID:U});let S=await x(({resolve:D,reject:k})=>{let y=this.getSingleMessage({taskUUID:U});if(y){if(y?.error)return k(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return h.destroy(),S},{maxRetries:m,callback:()=>{h?.destroy()}})}catch(b){throw b}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,c;try{return await R(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,s=n||T();this.send({taskUUID:s,taskType:"imageCaption",inputImage:i?.imageUUID,...f({key:"includeCost",value:e})}),c=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return c.destroy(),u},{maxRetries:o,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:c,customTaskUUID:i,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await R(async()=>{await this.ensureConnection();let p;p=await this.uploadImage(t);let r=i||T();this.send({taskUUID:r,inputImage:p?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...f({key:"includeCost",value:o}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let d=await x(({resolve:m,reject:h})=>{let b=this.getSingleMessage({taskUUID:r});if(b){if(b?.error)return h(b),!0;if(b)return delete this._globalMessages[r],m(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),d},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(p){throw p}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:c})=>{let i=c||this._globalMaxRetries,s;try{return await R(async()=>{await this.ensureConnection();let u=o||T();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...f({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await x(({resolve:p,reject:r})=>{let d=this._globalMessages[u];if(d?.error)return r(d),!0;if(d?.length>=n)return delete this._globalMessages[u],p(d),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:i,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:s,onUploadStream:(r,d)=>{e?.(r,d),r?.status==="ready"?u=r:d&&(g=d)}}),await x(({resolve:r,reject:d})=>{if(u)return r(u),!0;if(g)return d(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:a,customTaskUUID:o,numberResults:c,...i}=t,s=a||this._globalMaxRetries,u,g=[],p=0;try{return await R(async()=>{await this.ensureConnection(),p++;let r=this._globalImages.filter(b=>g.includes(b.taskUUID)),d=o||T();g.push(d);let m=c-r.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:j()},...e??{},numberResults:m,taskUUID:d,taskType:"photoMaker"}),u=this.listenToImages({onPartialImages:n,taskUUID:d,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let h=await this.getSimilarImages({taskUUID:g,numberResults:c,lis:u});return u.destroy(),h},{maxRetries:s,callback:()=>{u?.destroy()}})}catch(r){if(r.taskUUID)throw r;if(p>=s)return this.handleIncompleteImages({taskUUIDs:g,error:r})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s}),i=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=a,this._timeoutDuration=o}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let a=i=>{let s=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||T(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=me(this._listeners,o)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){ce(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:c=>{let i=c?.[e]?.filter(s=>s.taskUUID===e);c.error?(t?.(i,c?.error&&c),this._globalError=c):(i=i.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(i,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],c=o?.taskUUID===e?o:null;(c||a)&&t?.(c||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=pe({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:c,seedImage:i,maskImage:s,strength:u,height:g,width:p,model:r,steps:d,scheduler:m,seed:h,CFGScale:b,clipSkip:U,usePromptWeighting:S,promptWeighting:D,numberResults:k=1,onPartialImages:y,includeCost:_e,customTaskUUID:Re,retry:ke,refiner:Q,maskMargin:xe,outputQuality:I,controlNet:L,lora:J,embeddings:Y,ipAdapters:z,outpaint:Z,acceleratorOptions:$,advancedFeatures:X},De){let A,ee,E=[],te=0,ne=ke||this._globalMaxRetries;try{await this.ensureConnection();let v=null,K=null,W=[];if(i){let _=await this.uploadImage(i);if(!_)return[];v=_.imageUUID}if(s){let _=await this.uploadImage(s);if(!_)return[];K=_.imageUUID}if(L?.length)for(let _=0;_<L.length;_++){let C=L[_],{endStep:F,startStep:P,weight:G,guideImage:O,controlMode:Se,startStepPercentage:ve,endStepPercentage:we,model:Ae}=C,Ce=O?await this.uploadImage(O):null;W.push({guideImage:Ce?.imageUUID,model:Ae,endStep:F,startStep:P,weight:G,...f({key:"startStepPercentage",value:ve}),...f({key:"endStepPercentage",value:we}),controlMode:Se||"controlnet"})}return ee={taskType:"imageInference",model:r,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...p?{width:p}:{},numberResults:k,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNSFW",value:a}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:b}),...f({key:"clipSkip",value:U}),...f({key:"maskMargin",value:xe}),...f({key:"usePromptWeighting",value:S}),...f({key:"steps",value:d}),...D?{promptWeighting:D}:{},...h?{seed:h}:{seed:j()},...m?{scheduler:m}:{},...Q?{refiner:Q}:{},...Z?{outpaint:Z}:{},...f({key:"includeCost",value:_e}),...v?{seedImage:v}:{},...K?{maskImage:K}:{},...I?{outputQuality:I}:{},...W.length?{controlNet:W}:{},...J?.length?{lora:J}:{},...Y?.length?{embeddings:Y}:{},...z?.length?{ipAdapters:z}:{},...$?{acceleratorOptions:$}:{},...X?{advancedFeatures:X}:{},...De??{}},await R(async()=>{te++,A?.destroy();let _=this._globalImages.filter(O=>E.includes(O.taskUUID)),C=Re||T();E.push(C);let F=k-_.length,P={...ee,taskUUID:C,numberResults:F};this.send(P),A=this.listenToImages({onPartialImages:y,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let G=await this.getSimilarImages({taskUUID:E,numberResults:k,lis:A});return A.destroy(),G},{maxRetries:ne,callback:()=>{A?.destroy()}})}catch(v){if(te>=ne)return this.handleIncompleteImages({taskUUIDs:E,error:v});throw v}}async ensureConnection(){if(this.connected()||this._url===V.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let c=0,i=30,s=T(),u,g,p=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),d=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),d=!0);let m=c%10===0&&d;r?(p(),a(!0)):c>=i?(p(),o(new Error("Retry timed out"))):(m&&this.connect(),c++)}catch(r){p(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){p(),a(!0);return}if(this.isInvalidAPIKey()){p(),o(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:t,numberResults:e,shouldThrowError:n,lis:a}){return await x(({resolve:o,reject:c,intervalId:i})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),c?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var Ue=Fe(fe(),1),N=class extends w{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Ue.default(this._url),this.connect()}};import nt from"ws";var M=class extends w{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.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 nt(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:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(c=>{c.listener(o)})}))}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 Te;typeof window>"u"?Te=M:Te=N;export{ae as EControlMode,Be as EModelArchitecture,He as EModelConditioning,Ge as EModelFormat,qe as EModelType,Pe as EOpenPosePreProcessor,Ve as EPhotoMakerEnum,ie as EPreProcessor,oe as EPreProcessorGroup,q as ETaskType,se as Environment,Te as Runware,N as RunwareClient,M as RunwareServer,B as SdkType};
2
2
  //# sourceMappingURL=index.js.map