@runware/sdk-js 1.1.26 → 1.1.28

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
@@ -97,6 +97,7 @@ interface IError {
97
97
  errorMessage: string;
98
98
  taskUUID: string;
99
99
  }
100
+ type TPromptWeighting = "compel" | "sdEmbeds";
100
101
  interface IRequestImage {
101
102
  outputType?: IOutputType;
102
103
  outputFormat?: IOutputFormat;
@@ -116,7 +117,11 @@ interface IRequestImage {
116
117
  maskMargin?: number;
117
118
  CFGScale?: number;
118
119
  clipSkip?: number;
120
+ /**
121
+ * @deprecated The usePromptWeighting should not be used, use promptWeighting instead
122
+ */
119
123
  usePromptWeighting?: boolean;
124
+ promptWeighting?: TPromptWeighting;
120
125
  numberResults?: number;
121
126
  controlNet?: IControlNet[];
122
127
  lora?: ILora[];
@@ -305,8 +310,8 @@ type TAddModelCheckPoint = {
305
310
  defaultCFGScale?: number;
306
311
  defaultStrength: number;
307
312
  defaultSteps?: number;
308
- defaultScheduler?: number;
309
- type?: EModelType;
313
+ defaultScheduler?: string;
314
+ type: EModelType;
310
315
  } & TAddModelBaseType;
311
316
  type TAddModelLora = {
312
317
  category: "lora";
@@ -524,7 +529,7 @@ declare class RunwareBase {
524
529
  private listenToImages;
525
530
  private listenToUpload;
526
531
  private globalListener;
527
- requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, }: IRequestImage): Promise<ITextToImage[] | undefined>;
532
+ requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, }: IRequestImage): Promise<ITextToImage[] | undefined>;
528
533
  controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
529
534
  requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
530
535
  removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
@@ -566,4 +571,4 @@ declare class RunwareServer extends RunwareBase {
566
571
 
567
572
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
568
573
 
569
- 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 IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, 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 UploadImageType };
574
+ 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 IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, 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 UploadImageType };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var ke=Object.create;var Q=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var we=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Se=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of xe(t))!ve.call(c,a)&&a!==e&&Q(c,a,{get:()=>t[a],enumerable:!(n=Re(t,a))||n.enumerable});return c};var Ae=(c,t,e)=>(e=c!=null?ke(De(c)):{},Se(t||!c||!c.__esModule?Q(e,"default",{value:c,enumerable:!0}):e,c));var ge=we((Et,ue)=>{"use strict";var le=c=>c&&c.CLOSING===2,Fe=()=>typeof WebSocket<"u"&&le(WebSocket),Ge=()=>({constructor:Fe()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Be=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},ie=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,qe=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},He=["onopen","onclose","onmessage","onerror"],Ve=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&He.forEach(n=>{c[n]=t[n]})},ce=function(c,t,e={}){let n,a,o=0,l=0,i=!0,r={};if(!(this instanceof ce))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Ge();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!le(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...p)=>console.log("RWS:",...p):()=>{},d=(p,y)=>setTimeout(()=>{let b=new Error(y);b.code=p,Array.isArray(r.error)&&r.error.forEach(([T])=>T(b)),n.onerror&&n.onerror(b)},0),s=()=>{if(g("close"),l++,g("retries count:",l),l>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=qe(u,o):o=ie(u),g("reconnectDelay:",o),i&&setTimeout(m,o)},m=()=>{g("connect");let p=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&Be(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=ie(u),g("reconnectDelay:",o),l=0}),n.addEventListener("close",s),Ve(n,p,r)};g("init"),m(),this.close=(p=1e3,y="",{keepClosed:b=!1,fastClose:T=!0,delay:v=0}={})=>{if(v&&(o=v),i=!b,n.close(p,y),T){let x={code:p,reason:y,wasClean:!0};s(),Array.isArray(r.close)&&r.close.forEach(([U,I])=>{U(x),n.removeEventListener("close",U,I)}),n.onclose&&(n.onclose(x),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,b)=>{Array.isArray(r[p])?r[p].some(([T])=>T===y)||r[p].push([y,b]):r[p]=[[y,b]],n.addEventListener(p,y,b)},this.removeEventListener=(p,y,b)=>{Array.isArray(r[p])&&(r[p]=r[p].filter(([T])=>T!==y)),n.removeEventListener(p,y,b)}};ue.exports=ce});var Y=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Y||{}),G=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(G||{}),B=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.PHOTO_MAKER="photoMaker",s.MODEL_SEARCH="modelSearch",s.IMAGE_MASKING="imageMasking",s))(B||{}),Z=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Z||{}),$=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))($||{}),X=(f=>(f.canny="canny",f.depth_leres="depth_leres",f.depth_midas="depth_midas",f.depth_zoe="depth_zoe",f.inpaint_global_harmonious="inpaint_global_harmonious",f.lineart_anime="lineart_anime",f.lineart_coarse="lineart_coarse",f.lineart_realistic="lineart_realistic",f.lineart_standard="lineart_standard",f.mlsd="mlsd",f.normal_bae="normal_bae",f.scribble_hed="scribble_hed",f.scribble_pidinet="scribble_pidinet",f.seg_ofade20k="seg_ofade20k",f.seg_ofcoco="seg_ofcoco",f.seg_ufade20k="seg_ufade20k",f.shuffle="shuffle",f.softedge_hed="softedge_hed",f.softedge_hedsafe="softedge_hedsafe",f.softedge_pidinet="softedge_pidinet",f.softedge_pidisafe="softedge_pidisafe",f.tile_gaussian="tile_gaussian",f.openpose="openpose",f.openpose_face="openpose_face",f.openpose_faceonly="openpose_faceonly",f.openpose_full="openpose_full",f.openpose_hand="openpose_hand",f))(X||{}),Ce=(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))(Ce||{}),Me=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Me||{}),Oe=(m=>(m.flux1d="flux1d",m.flux1s="flux1s",m.pony="pony",m.sdhyper="sdhyper",m.sd1x="sd1x",m.sd1xlcm="sd1xlcm",m.sd3="sd3",m.sdxl="sdxl",m.sdxllcm="sdxllcm",m.sdxldistilled="sdxldistilled",m.sdxlhyper="sdxlhyper",m.sdxllightning="sdxllightning",m.sdxlturbo="sdxlturbo",m))(Oe||{}),Ne=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ne||{}),Le=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(Le||{}),Ee=(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))(Ee||{});import{v4 as Ke,validate as Pe}from"uuid";var q=6e4,ee=1e3,We=100,H={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},te=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},D=(c,{debugKey:t="debugKey",timeoutDuration:e=q,shouldThrowError:n=!0})=>(e=e<ee?ee:e,new Promise((a,o)=>{let l=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(l)},e),i=setInterval(async()=>{c({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(l))},We)})),ne=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),_=()=>Ke(),se=c=>Pe(c);var re=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,i)=>{let r=e?0:void 0,u=l?.[i];if(!u)return r;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?l[i]=u[g]:l[i]??r}else return l[i]??r},t||{})??{},ae=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var oe=(c,t)=>c.filter(e=>e.key!==t.key);var h=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{};var k=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await ae(e),await k(c,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=H.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=q}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=_();if(typeof t=="string"&&se(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ne(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:l,highThresholdCanny:i,lowThresholdCanny:r,includeHandsAndFaceOpenPose:u,includeCost:g,customTaskUUID:d,retry:s})=>{let m=s||this._globalMaxRetries,p;try{return await k(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let b=d||_();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:l}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:i}),...h({key:"lowThresholdCanny",value:r}),...h({key:"includeHandsAndFaceOpenPose",value:u})}),p=this.globalListener({taskUUID:b});let T=await D(({resolve:v,reject:x})=>{let U=this.getSingleMessage({taskUUID:b});if(U){if(U?.error)return x(U),!0;if(U)return v(U),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return p.destroy(),T},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,l;try{return await k(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,r=n||_();this.send({taskUUID:r,taskType:"imageCaption",inputImage:i?.imageUUID,...h({key:"includeCost",value:e})}),l=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:o,callback:()=>{l?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:l,alphaMatting:i,alphaMattingForegroundThreshold:r,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,includeCost:d,customTaskUUID:s,retry:m})=>{let p=m||this._globalMaxRetries,y;try{return await k(async()=>{await this.ensureConnection();let b=t?await this.uploadImage(t):null,T=s||_();this.send({taskType:"imageBackgroundRemoval",taskUUID:T,inputImage:b?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:l}),...h({key:"alphaMatting",value:i}),...h({key:"includeCost",value:d}),...h({key:"alphaMattingForegroundThreshold",value:r}),...h({key:"alphaMattingBackgroundThreshold",value:u}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:U})=>{let I=this.getSingleMessage({taskUUID:T});if(I){if(I?.error)return U(I),!0;if(I)return delete this._globalMessages[T],x(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),v},{maxRetries:p,callback:()=>{y?.destroy()}})}catch(b){throw b}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,customTaskUUID:l,retry:i})=>{let r=i||this._globalMaxRetries,u;try{return await k(async()=>{await this.ensureConnection();let g;g=await this.uploadImage(t);let d=l||_();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...a?{outputFormat:a}:{}}),u=this.globalListener({taskUUID:d});let s=await D(({resolve:m,reject:p})=>{let y=this.getSingleMessage({taskUUID:d});if(y){if(y?.error)return p(y),!0;if(y)return delete this._globalMessages[d],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return u.destroy(),s},{maxRetries:r,callback:()=>{u?.destroy()}})}catch(g){throw g}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:l})=>{let i=l||this._globalMaxRetries,r;try{return await k(async()=>{await this.ensureConnection();let u=o||_();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),r=this.globalListener({taskUUID:u});let g=await D(({resolve:d,reject:s})=>{let m=this._globalMessages[u];if(m?.error)return s(m),!0;if(m?.length>=n)return delete this._globalMessages[u],d(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return r.destroy(),g},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,l=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:r,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?u=s:m&&(g=m)}}),await D(({resolve:s,reject:m})=>{if(u)return s(u),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...l}=t,i=n||this._globalMaxRetries,r,u=[],g=0;try{return await k(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(y=>u.includes(y.taskUUID)),s=a||_();u.push(s);let m=o-d.length;this.send({...l,numberResults:m,taskUUID:s,taskType:"photoMaker"}),r=this.listenToImages({onPartialImages:e,taskUUID:s,groupKey:"REQUEST_IMAGES",positivePrompt:l.positivePrompt});let p=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:r});return r.destroy(),p},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=i)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,extra:!0,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,l=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r}),i=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(r){throw r}};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 r=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=r.filter(s=>(s?.taskUUID||s?.taskType)===n);if(u.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:r});return}},o={key:n||_(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=oe(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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._invalidAPIkey}}destroy(t){te(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:l=>{let i=l?.[e]?.filter(r=>r.taskUUID===e);l.error?(t?.(i,l?.error&&l),this._globalError=l):(i=i.map(r=>({...r,positivePrompt:a,negativePrompt:o})),t?.(i,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(r=>({...r,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],l=o?.taskUUID===e?o:null;(l||a)&&t?.(l||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=re({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:l,seedImage:i,maskImage:r,strength:u,height:g,width:d,model:s,steps:m,scheduler:p,seed:y,CFGScale:b,clipSkip:T,usePromptWeighting:v,numberResults:x=1,controlNet:U,lora:I,onPartialImages:me,includeCost:ye,customTaskUUID:Ie,retry:he,refiner:V,maskMargin:f}){let A,j,M=[],z=0,J=he||this._globalMaxRetries;try{await this.ensureConnection();let w=null,E=null,K=[];if(i){let R=await this.uploadImage(i);if(!R)return[];w=R.imageUUID}if(r){let R=await this.uploadImage(r);if(!R)return[];E=R.imageUUID}if(U?.length)for(let R=0;R<U.length;R++){let C=U[R],{endStep:P,startStep:W,weight:F,guideImage:O,controlMode:fe,startStepPercentage:be,endStepPercentage:Te,model:Ue}=C,_e=O?await this.uploadImage(O):null;K.push({guideImage:_e?.imageUUID,model:Ue,endStep:P,startStep:W,weight:F,...h({key:"startStepPercentage",value:be}),...h({key:"endStepPercentage",value:Te}),controlMode:fe||"controlnet"})}return j={taskType:"imageInference",model:s,positivePrompt:o,...l?{negativePrompt:l}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...I?.length?{lora:I}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:u}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:T}),...h({key:"maskMargin",value:f}),...h({key:"usePromptWeighting",value:v}),...h({key:"steps",value:m}),...K.length?{controlNet:K}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...V?{refiner:V}:{},...h({key:"includeCost",value:ye}),...w?{seedImage:w}:{},...E?{maskImage:E}:{}},await k(async()=>{z++,A?.destroy();let R=this._globalImages.filter(O=>M.includes(O.taskUUID)),C=Ie||_();M.push(C);let P=x-R.length,W={...j,taskUUID:C,numberResults:P};this.send(W),A=this.listenToImages({onPartialImages:me,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:l});let F=await this.getSimilarImages({taskUUID:M,numberResults:x,lis:A});return A.destroy(),F},{maxRetries:J,callback:()=>{A?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(z>=J)return this.handleIncompleteImages({taskUUIDs:M,error:w})}}async ensureConnection(){if(this.connected()||this._url===H.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((a,o)=>{let l=0,i=30,r=l%10===0,u,g,d=()=>{clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{this.connected()?(d(),a(!0)):l>=i?(d(),o(new Error("Retry timed out"))):(r&&this.connect(),l++)}catch(s){d(),o(s)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this._invalidAPIkey){d(),o(this._invalidAPIkey);return}},n)})}catch{throw this._invalidAPIkey??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await D(({resolve:o,reject:l,intervalId:i})=>{let r=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>r.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),l?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!r.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 de=Ae(ge(),1),N=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new de.default(this._url),this.connect()}};import je from"ws";var L=class extends S{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 je(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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(l=>{l.listener(o)})}))}handleClose(){this._invalidAPIkey||(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 pe;typeof window>"u"?pe=L:pe=N;export{Z as EControlMode,Oe as EModelArchitecture,Le as EModelConditioning,Me as EModelFormat,Ne as EModelType,Ce as EOpenPosePreProcessor,Ee as EPhotoMakerEnum,X as EPreProcessor,$ as EPreProcessorGroup,B as ETaskType,Y as Environment,pe as Runware,N as RunwareClient,L as RunwareServer,G as SdkType};
1
+ var Re=Object.create;var Q=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Se=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Ae=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of De(t))!we.call(c,a)&&a!==e&&Q(c,a,{get:()=>t[a],enumerable:!(n=xe(t,a))||n.enumerable});return c};var Ce=(c,t,e)=>(e=c!=null?Re(ve(c)):{},Ae(t||!c||!c.__esModule?Q(e,"default",{value:c,enumerable:!0}):e,c));var ge=Se((Kt,ue)=>{"use strict";var le=c=>c&&c.CLOSING===2,Ge=()=>typeof WebSocket<"u"&&le(WebSocket),Be=()=>({constructor:Ge()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),qe=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},ie=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,He=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},Ve=["onopen","onclose","onmessage","onerror"],je=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&Ve.forEach(n=>{c[n]=t[n]})},ce=function(c,t,e={}){let n,a,o=0,l=0,i=!0,r={};if(!(this instanceof ce))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Be();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!le(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...p)=>console.log("RWS:",...p):()=>{},d=(p,y)=>setTimeout(()=>{let b=new Error(y);b.code=p,Array.isArray(r.error)&&r.error.forEach(([T])=>T(b)),n.onerror&&n.onerror(b)},0),s=()=>{if(g("close"),l++,g("retries count:",l),l>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=He(u,o):o=ie(u),g("reconnectDelay:",o),i&&setTimeout(m,o)},m=()=>{g("connect");let p=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&qe(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=ie(u),g("reconnectDelay:",o),l=0}),n.addEventListener("close",s),je(n,p,r)};g("init"),m(),this.close=(p=1e3,y="",{keepClosed:b=!1,fastClose:T=!0,delay:v=0}={})=>{if(v&&(o=v),i=!b,n.close(p,y),T){let x={code:p,reason:y,wasClean:!0};s(),Array.isArray(r.close)&&r.close.forEach(([U,I])=>{U(x),n.removeEventListener("close",U,I)}),n.onclose&&(n.onclose(x),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,b)=>{Array.isArray(r[p])?r[p].some(([T])=>T===y)||r[p].push([y,b]):r[p]=[[y,b]],n.addEventListener(p,y,b)},this.removeEventListener=(p,y,b)=>{Array.isArray(r[p])&&(r[p]=r[p].filter(([T])=>T!==y)),n.removeEventListener(p,y,b)}};ue.exports=ce});var Y=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Y||{}),G=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(G||{}),B=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.PHOTO_MAKER="photoMaker",s.MODEL_SEARCH="modelSearch",s.IMAGE_MASKING="imageMasking",s))(B||{}),Z=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Z||{}),$=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))($||{}),X=(f=>(f.canny="canny",f.depth_leres="depth_leres",f.depth_midas="depth_midas",f.depth_zoe="depth_zoe",f.inpaint_global_harmonious="inpaint_global_harmonious",f.lineart_anime="lineart_anime",f.lineart_coarse="lineart_coarse",f.lineart_realistic="lineart_realistic",f.lineart_standard="lineart_standard",f.mlsd="mlsd",f.normal_bae="normal_bae",f.scribble_hed="scribble_hed",f.scribble_pidinet="scribble_pidinet",f.seg_ofade20k="seg_ofade20k",f.seg_ofcoco="seg_ofcoco",f.seg_ufade20k="seg_ufade20k",f.shuffle="shuffle",f.softedge_hed="softedge_hed",f.softedge_hedsafe="softedge_hedsafe",f.softedge_pidinet="softedge_pidinet",f.softedge_pidisafe="softedge_pidisafe",f.tile_gaussian="tile_gaussian",f.openpose="openpose",f.openpose_face="openpose_face",f.openpose_faceonly="openpose_faceonly",f.openpose_full="openpose_full",f.openpose_hand="openpose_hand",f))(X||{}),Me=(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))(Me||{}),Oe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Oe||{}),Ne=(m=>(m.flux1d="flux1d",m.flux1s="flux1s",m.pony="pony",m.sdhyper="sdhyper",m.sd1x="sd1x",m.sd1xlcm="sd1xlcm",m.sd3="sd3",m.sdxl="sdxl",m.sdxllcm="sdxllcm",m.sdxldistilled="sdxldistilled",m.sdxlhyper="sdxlhyper",m.sdxllightning="sdxllightning",m.sdxlturbo="sdxlturbo",m))(Ne||{}),Le=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Le||{}),Ee=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(Ee||{}),Ke=(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))(Ke||{});import{v4 as Pe,validate as We}from"uuid";var q=6e4,ee=1e3,Fe=100,H={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},te=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},D=(c,{debugKey:t="debugKey",timeoutDuration:e=q,shouldThrowError:n=!0})=>(e=e<ee?ee:e,new Promise((a,o)=>{let l=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(l)},e),i=setInterval(async()=>{c({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(l))},Fe)})),ne=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),_=()=>Pe(),se=c=>We(c);var re=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,i)=>{let r=e?0:void 0,u=l?.[i];if(!u)return r;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?l[i]=u[g]:l[i]??r}else return l[i]??r},t||{})??{},ae=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var oe=(c,t)=>c.filter(e=>e.key!==t.key);var h=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{};var k=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await ae(e),await k(c,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=H.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=q}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=_();if(typeof t=="string"&&se(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ne(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:l,highThresholdCanny:i,lowThresholdCanny:r,includeHandsAndFaceOpenPose:u,includeCost:g,customTaskUUID:d,retry:s})=>{let m=s||this._globalMaxRetries,p;try{return await k(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let b=d||_();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:l}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:i}),...h({key:"lowThresholdCanny",value:r}),...h({key:"includeHandsAndFaceOpenPose",value:u})}),p=this.globalListener({taskUUID:b});let T=await D(({resolve:v,reject:x})=>{let U=this.getSingleMessage({taskUUID:b});if(U){if(U?.error)return x(U),!0;if(U)return v(U),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return p.destroy(),T},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,l;try{return await k(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,r=n||_();this.send({taskUUID:r,taskType:"imageCaption",inputImage:i?.imageUUID,...h({key:"includeCost",value:e})}),l=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:o,callback:()=>{l?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:l,alphaMatting:i,alphaMattingForegroundThreshold:r,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,includeCost:d,customTaskUUID:s,retry:m})=>{let p=m||this._globalMaxRetries,y;try{return await k(async()=>{await this.ensureConnection();let b=t?await this.uploadImage(t):null,T=s||_();this.send({taskType:"imageBackgroundRemoval",taskUUID:T,inputImage:b?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:l}),...h({key:"alphaMatting",value:i}),...h({key:"includeCost",value:d}),...h({key:"alphaMattingForegroundThreshold",value:r}),...h({key:"alphaMattingBackgroundThreshold",value:u}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:U})=>{let I=this.getSingleMessage({taskUUID:T});if(I){if(I?.error)return U(I),!0;if(I)return delete this._globalMessages[T],x(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),v},{maxRetries:p,callback:()=>{y?.destroy()}})}catch(b){throw b}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,customTaskUUID:l,retry:i})=>{let r=i||this._globalMaxRetries,u;try{return await k(async()=>{await this.ensureConnection();let g;g=await this.uploadImage(t);let d=l||_();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...a?{outputFormat:a}:{}}),u=this.globalListener({taskUUID:d});let s=await D(({resolve:m,reject:p})=>{let y=this.getSingleMessage({taskUUID:d});if(y){if(y?.error)return p(y),!0;if(y)return delete this._globalMessages[d],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return u.destroy(),s},{maxRetries:r,callback:()=>{u?.destroy()}})}catch(g){throw g}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:l})=>{let i=l||this._globalMaxRetries,r;try{return await k(async()=>{await this.ensureConnection();let u=o||_();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),r=this.globalListener({taskUUID:u});let g=await D(({resolve:d,reject:s})=>{let m=this._globalMessages[u];if(m?.error)return s(m),!0;if(m?.length>=n)return delete this._globalMessages[u],d(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return r.destroy(),g},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,l=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:r,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?u=s:m&&(g=m)}}),await D(({resolve:s,reject:m})=>{if(u)return s(u),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(r){throw r}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...l}=t,i=n||this._globalMaxRetries,r,u=[],g=0;try{return await k(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(y=>u.includes(y.taskUUID)),s=a||_();u.push(s);let m=o-d.length;this.send({...l,numberResults:m,taskUUID:s,taskType:"photoMaker"}),r=this.listenToImages({onPartialImages:e,taskUUID:s,groupKey:"REQUEST_IMAGES",positivePrompt:l.positivePrompt});let p=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:r});return r.destroy(),p},{maxRetries:i,callback:()=>{r?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=i)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,extra:!0,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,l=n||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r}),i=this.globalListener({taskUUID:r});let u=await D(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:l,callback:()=>{i?.destroy()}})}catch(r){throw r}};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 r=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],g=r.filter(s=>(s?.taskUUID||s?.taskType)===n);if(u.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:r});return}},o={key:n||_(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=oe(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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._invalidAPIkey}}destroy(t){te(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:l=>{let i=l?.[e]?.filter(r=>r.taskUUID===e);l.error?(t?.(i,l?.error&&l),this._globalError=l):(i=i.map(r=>({...r,positivePrompt:a,negativePrompt:o})),t?.(i,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(r=>({...r,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],l=o?.taskUUID===e?o:null;(l||a)&&t?.(l||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=re({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:l,seedImage:i,maskImage:r,strength:u,height:g,width:d,model:s,steps:m,scheduler:p,seed:y,CFGScale:b,clipSkip:T,usePromptWeighting:v,promptWeighting:x,numberResults:U=1,controlNet:I,lora:V,onPartialImages:me,includeCost:ye,customTaskUUID:Ie,retry:he,refiner:f,maskMargin:fe}){let A,j,M=[],z=0,J=he||this._globalMaxRetries;try{await this.ensureConnection();let w=null,E=null,K=[];if(i){let R=await this.uploadImage(i);if(!R)return[];w=R.imageUUID}if(r){let R=await this.uploadImage(r);if(!R)return[];E=R.imageUUID}if(I?.length)for(let R=0;R<I.length;R++){let C=I[R],{endStep:P,startStep:W,weight:F,guideImage:O,controlMode:be,startStepPercentage:Te,endStepPercentage:Ue,model:_e}=C,ke=O?await this.uploadImage(O):null;K.push({guideImage:ke?.imageUUID,model:_e,endStep:P,startStep:W,weight:F,...h({key:"startStepPercentage",value:Te}),...h({key:"endStepPercentage",value:Ue}),controlMode:be||"controlnet"})}return j={taskType:"imageInference",model:s,positivePrompt:o,...l?{negativePrompt:l}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:U,...V?.length?{lora:V}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:u}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:T}),...h({key:"maskMargin",value:fe}),...h({key:"usePromptWeighting",value:v}),...h({key:"steps",value:m}),...x?{promptWeighting:x}:{},...K.length?{controlNet:K}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...f?{refiner:f}:{},...h({key:"includeCost",value:ye}),...w?{seedImage:w}:{},...E?{maskImage:E}:{}},await k(async()=>{z++,A?.destroy();let R=this._globalImages.filter(O=>M.includes(O.taskUUID)),C=Ie||_();M.push(C);let P=U-R.length,W={...j,taskUUID:C,numberResults:P};this.send(W),A=this.listenToImages({onPartialImages:me,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:l});let F=await this.getSimilarImages({taskUUID:M,numberResults:U,lis:A});return A.destroy(),F},{maxRetries:J,callback:()=>{A?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(z>=J)return this.handleIncompleteImages({taskUUIDs:M,error:w})}}async ensureConnection(){if(this.connected()||this._url===H.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((a,o)=>{let l=0,i=30,r=l%10===0,u,g,d=()=>{clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{this.connected()?(d(),a(!0)):l>=i?(d(),o(new Error("Retry timed out"))):(r&&this.connect(),l++)}catch(s){d(),o(s)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this._invalidAPIkey){d(),o(this._invalidAPIkey);return}},n)})}catch{throw this._invalidAPIkey??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await D(({resolve:o,reject:l,intervalId:i})=>{let r=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>r.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(i),l?.(g),!0}else if(u.length>=e)return clearInterval(i),this._globalImages=this._globalImages.filter(g=>!r.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 de=Ce(ge(),1),N=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new de.default(this._url),this.connect()}};import ze from"ws";var L=class extends S{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 ze(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._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=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(l=>{l.listener(o)})}))}handleClose(){this._invalidAPIkey||(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 pe;typeof window>"u"?pe=L:pe=N;export{Z as EControlMode,Ne as EModelArchitecture,Ee as EModelConditioning,Oe as EModelFormat,Le as EModelType,Me as EOpenPosePreProcessor,Ke as EPhotoMakerEnum,X as EPreProcessor,$ as EPreProcessorGroup,B as ETaskType,Y as Environment,pe as Runware,N as RunwareClient,L as RunwareServer,G as SdkType};
2
2
  //# sourceMappingURL=index.js.map