@runware/sdk-js 1.1.20 → 1.1.21

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
@@ -17,7 +17,9 @@ declare enum ETaskType {
17
17
  PROMPT_ENHANCE = "promptEnhance",
18
18
  AUTHENTICATION = "authentication",
19
19
  MODEL_UPLOAD = "modelUpload",
20
- PHOTO_MAKER = "photoMaker"
20
+ PHOTO_MAKER = "photoMaker",
21
+ MODEL_SEARCH = "modelSearch",
22
+ IMAGE_MASKING = "imageMasking"
21
23
  }
22
24
  type RunwareBaseType = {
23
25
  apiKey: string;
@@ -401,6 +403,92 @@ declare enum EPhotoMakerEnum {
401
403
  Lowpoly = "Lowpoly",
402
404
  LineArt = "Line art"
403
405
  }
406
+ type TModelSearch = {
407
+ search: string;
408
+ tags?: string[];
409
+ category?: "checkpoint" | "lora" | "controlnet";
410
+ architecture?: EModelArchitecture;
411
+ limit?: number;
412
+ offset?: number;
413
+ owned?: boolean;
414
+ featured: boolean;
415
+ type: string;
416
+ conditioning: string;
417
+ private: boolean;
418
+ customTaskUUID?: string;
419
+ retry?: number;
420
+ };
421
+ type TModel = {
422
+ name: string;
423
+ air: string;
424
+ downloadUrl: string;
425
+ tags: string[];
426
+ heroImage: string;
427
+ category: string;
428
+ floatingPoint: string;
429
+ private: boolean;
430
+ shortDescription: string;
431
+ comment: string;
432
+ positiveTriggerWords: string;
433
+ defaultSteps: number;
434
+ defaultGuidanceScale: number;
435
+ defaultStrength: number;
436
+ defaultVaeId: number;
437
+ updatedDateUnixTimestamp: number;
438
+ version: string;
439
+ conditioning: string;
440
+ defaultScheduler: string;
441
+ defaultCFG: number;
442
+ format: string;
443
+ uniqueIdentifier: string;
444
+ architecture: string;
445
+ type: string;
446
+ nsfw: boolean;
447
+ sourceUrl: string;
448
+ downloadCount: number;
449
+ nsfwLevel: number;
450
+ rating: number;
451
+ ratingCount: number;
452
+ thumbsUpCount: number;
453
+ thumbsDownCount: number;
454
+ defaultEmaEnable: boolean;
455
+ defaultImageSizeId: string;
456
+ compatibleSizeIds: number[];
457
+ };
458
+ type TModelSearchResponse = {
459
+ results: TModel[];
460
+ taskUUID: string;
461
+ taskType: string;
462
+ totalResults: number;
463
+ };
464
+ type TImageMasking = {
465
+ model: string;
466
+ inputImage: string;
467
+ confidence?: number;
468
+ maskPadding?: number;
469
+ maskBlur?: number;
470
+ outputFormat?: string;
471
+ outputType?: string;
472
+ includeCost?: boolean;
473
+ uploadEndpoint?: string;
474
+ customTaskUUID?: string;
475
+ retry?: number;
476
+ };
477
+ type TImageMaskingResponse = {
478
+ taskType: string;
479
+ taskUUID: string;
480
+ imageUUID: string;
481
+ detections: [
482
+ {
483
+ x_min: number;
484
+ y_min: number;
485
+ x_max: number;
486
+ y_max: number;
487
+ }
488
+ ];
489
+ maskImageURL: string;
490
+ cost: number;
491
+ };
404
492
 
405
493
  declare class RunwareBase {
406
494
  _ws: ReconnectingWebsocketProps | any;
@@ -441,6 +529,12 @@ declare class RunwareBase {
441
529
  enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
442
530
  modelUpload: (payload: TAddModel) => Promise<any>;
443
531
  photoMaker: (payload: TPhotoMaker) => Promise<TPhotoMakerResponse[] | undefined>;
532
+ modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
533
+ imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
534
+ protected baseSingleRequest: <T>({ payload, debugKey, }: {
535
+ payload: Record<string, any>;
536
+ debugKey: string;
537
+ }) => Promise<T>;
444
538
  ensureConnection(): Promise<unknown>;
445
539
  private getSimilarImages;
446
540
  private getSingleMessage;
@@ -469,4 +563,4 @@ declare class RunwareServer extends RunwareBase {
469
563
 
470
564
  declare let Runware: typeof RunwareClient | typeof RunwareServer;
471
565
 
472
- 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 TPhotoMaker, type TPhotoMakerResponse, type UploadImageType };
566
+ 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 };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ue=Object.create;var Q=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var ve=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var we=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Re(t))!De.call(c,s)&&s!==e&&Q(c,s,{get:()=>t[s],enumerable:!(n=ke(t,s))||n.enumerable});return c};var Se=(c,t,e)=>(e=c!=null?Ue(xe(c)):{},we(t||!c||!c.__esModule?Q(e,"default",{value:c,enumerable:!0}):e,c));var ue=ve((Ct,ce)=>{"use strict";var ie=c=>c&&c.CLOSING===2,Fe=()=>typeof WebSocket<"u"&&ie(WebSocket),Pe=()=>({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})},oe=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Ge=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},qe=["onopen","onclose","onmessage","onerror"],He=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,r])=>{c.addEventListener(n,s,r)})}),t&&qe.forEach(n=>{c[n]=t[n]})},le=function(c,t,e={}){let n,s,r=0,i=0,l=!0,a={};if(!(this instanceof le))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Pe();if(Object.keys(u).filter(g=>e.hasOwnProperty(g)).forEach(g=>u[g]=e[g]),!ie(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let o=u.debug?(...g)=>console.log("RWS:",...g):()=>{},p=(g,y)=>setTimeout(()=>{let _=new Error(y);_.code=g,Array.isArray(a.error)&&a.error.forEach(([b])=>b(_)),n.onerror&&n.onerror(_)},0),d=()=>{if(o("close"),i++,o("retries count:",i),i>u.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}r?r=Ge(u,r):r=oe(u),o("reconnectDelay:",r),l&&setTimeout(m,r)},m=()=>{o("connect");let g=n;n=new u.constructor(c,t),s=setTimeout(()=>{o("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},u.connectionTimeout),o("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&Be(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),o("open"),r=oe(u),o("reconnectDelay:",r),i=0}),n.addEventListener("close",d),He(n,g,a)};o("init"),m(),this.close=(g=1e3,y="",{keepClosed:_=!1,fastClose:b=!0,delay:D=0}={})=>{if(D&&(r=D),l=!_,n.close(g,y),b){let x={code:g,reason:y,wasClean:!0};d(),Array.isArray(a.close)&&a.close.forEach(([T,h])=>{T(x),n.removeEventListener("close",T,h)}),n.onclose&&(n.onclose(x),n.onclose=null)}},this.send=g=>{n.send(g)},this.addEventListener=(g,y,_)=>{Array.isArray(a[g])?a[g].some(([b])=>b===y)||a[g].push([y,_]):a[g]=[[y,_]],n.addEventListener(g,y,_)},this.removeEventListener=(g,y,_)=>{Array.isArray(a[g])&&(a[g]=a[g].filter(([b])=>b!==y)),n.removeEventListener(g,y,_)}};ce.exports=le});var z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(z||{}),P=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(P||{}),B=(o=>(o.IMAGE_INFERENCE="imageInference",o.IMAGE_UPLOAD="imageUpload",o.IMAGE_UPSCALE="imageUpscale",o.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",o.IMAGE_CAPTION="imageCaption",o.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",o.PROMPT_ENHANCE="promptEnhance",o.AUTHENTICATION="authentication",o.MODEL_UPLOAD="modelUpload",o.PHOTO_MAKER="photoMaker",o))(B||{}),Y=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Y||{}),Z=(d=>(d.canny="canny",d.depth="depth",d.mlsd="mlsd",d.normalbae="normalbae",d.openpose="openpose",d.tile="tile",d.seg="seg",d.lineart="lineart",d.lineart_anime="lineart_anime",d.shuffle="shuffle",d.scribble="scribble",d.softedge="softedge",d))(Z||{}),$=(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=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Ae||{}),Ce=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Ce||{}),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=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(Le||{}),Ee=(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))(Ee||{});import{v4 as Me,validate as Ke}from"uuid";var G=6e4,X=1e3,We=100,q={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ee=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},v=(c,{debugKey:t="debugKey",timeoutDuration:e=G,shouldThrowError:n=!0})=>(e=e<X?X:e,new Promise((s,r)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&r(`Response could not be received from server for ${t}`)),clearTimeout(i)},e),l=setInterval(async()=>{c({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))},We)})),te=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),k=()=>Me(),ne=c=>Ke(c);var se=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,l)=>{let a=e?0:void 0,u=i?.[l];if(!u)return a;if(Array.isArray(u)&&/^\d+$/.test(l)){let o=parseInt(l,10);return o>=0&&o<u.length?i[l]=u[o]:i[l]??a}else return i[l]??a},t||{})??{},re=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var ae=(c,t)=>c.filter(e=>e.key!==t.key);var f=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{};var R=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await c()}catch(r){if(n?.(),s--,s>0)await re(e),await R(c,{...t,maxRetries:s});else throw r}};var S=class{constructor({apiKey:t,url:e=q.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=G}){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 R(async()=>{let e=k();if(typeof t=="string"&&ne(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await te(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:s,outputType:r,outputFormat:i,highThresholdCanny:l,lowThresholdCanny:a,includeHandsAndFaceOpenPose:u,includeCost:o,customTaskUUID:p,retry:d})=>{let m=d||this._globalMaxRetries,g;try{return await R(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let _=p||k();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:_,preProcessorType:e,...f({key:"height",value:n}),...f({key:"width",value:s}),...f({key:"outputType",value:r}),...f({key:"outputFormat",value:i}),...f({key:"includeCost",value:o}),...f({key:"highThresholdCanny",value:l}),...f({key:"lowThresholdCanny",value:a}),...f({key:"includeHandsAndFaceOpenPose",value:u})}),g=this.globalListener({taskUUID:_});let b=await v(({resolve:D,reject:x})=>{let T=this.getSingleMessage({taskUUID:_});if(T){if(T?.error)return x(T),!0;if(T)return D(T),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return g.destroy(),b},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s})=>{let r=s||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let l=t?await this.uploadImage(t):null,a=n||k();this.send({taskUUID:a,taskType:"imageCaption",inputImage:l?.imageUUID,...f({key:"includeCost",value:e})}),i=this.globalListener({taskUUID:a});let u=await v(({resolve:o,reject:p})=>{let d=this.getSingleMessage({taskUUID:a});if(d){if(d?.error)return p(d),!0;if(d)return delete this._globalMessages[a],o(d),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:r,callback:()=>{i?.destroy()}})}catch(l){throw l}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:s,postProcessMask:r,returnOnlyMask:i,alphaMatting:l,alphaMattingForegroundThreshold:a,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:o,includeCost:p,customTaskUUID:d,retry:m})=>{let g=m||this._globalMaxRetries,y;try{return await R(async()=>{await this.ensureConnection();let _=t?await this.uploadImage(t):null,b=d||k();this.send({taskType:"imageBackgroundRemoval",taskUUID:b,inputImage:_?.imageUUID,...f({key:"rgba",value:s}),...f({key:"postProcessMask",value:r}),...f({key:"returnOnlyMask",value:i}),...f({key:"alphaMatting",value:l}),...f({key:"includeCost",value:p}),...f({key:"alphaMattingForegroundThreshold",value:a}),...f({key:"alphaMattingBackgroundThreshold",value:u}),...f({key:"alphaMattingErodeSize",value:o}),...f({key:"outputType",value:e}),...f({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:b});let D=await v(({resolve:x,reject:T})=>{let h=this.getSingleMessage({taskUUID:b});if(h){if(h?.error)return T(h),!0;if(h)return delete this._globalMessages[b],x(h),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),D},{maxRetries:g,callback:()=>{y?.destroy()}})}catch(_){throw _}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:r,customTaskUUID:i,retry:l})=>{let a=l||this._globalMaxRetries,u;try{return await R(async()=>{await this.ensureConnection();let o;o=await this.uploadImage(t);let p=i||k();this.send({taskUUID:p,inputImage:o?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...f({key:"includeCost",value:r}),...n?{outputType:n}:{},...s?{outputFormat:s}:{}}),u=this.globalListener({taskUUID:p});let d=await v(({resolve:m,reject:g})=>{let y=this.getSingleMessage({taskUUID:p});if(y){if(y?.error)return g(y),!0;if(y)return delete this._globalMessages[p],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return u.destroy(),d},{maxRetries:a,callback:()=>{u?.destroy()}})}catch(o){throw o}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,retry:i})=>{let l=i||this._globalMaxRetries,a;try{return await R(async()=>{await this.ensureConnection();let u=r||k();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...f({key:"includeCost",value:s}),taskType:"promptEnhance"}),a=this.globalListener({taskUUID:u});let o=await v(({resolve:p,reject:d})=>{let m=this._globalMessages[u];if(m?.error)return d(m),!0;if(m?.length>=n)return delete this._globalMessages[u],p(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return a.destroy(),o},{maxRetries:l,callback:()=>{a?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...r}=t,i=n||this._globalMaxRetries,l;try{return await R(async()=>{await this.ensureConnection();let a=s||k();this.send({...r,taskUUID:a,taskType:"modelUpload"});let u,o;return l=this.listenToUpload({taskUUID:a,onUploadStream:(d,m)=>{e?.(d,m),d?.status==="ready"?u=d:m&&(o=m)}}),await v(({resolve:d,reject:m})=>{if(u)return d(u),!0;if(o)return m(o),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(a){throw a}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:s,numberResults:r,...i}=t,l=n||this._globalMaxRetries,a,u=[],o=0;try{return await R(async()=>{await this.ensureConnection(),o++;let p=this._globalImages.filter(y=>u.includes(y.taskUUID)),d=s||k();u.push(d);let m=r-p.length;this.send({...i,numberResults:m,taskUUID:d,taskType:"photoMaker"}),a=this.listenToImages({onPartialImages:e,taskUUID:d,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let g=await this.getSimilarImages({taskUUID:u,numberResults:r,lis:a});return a.destroy(),g},{maxRetries:l,callback:()=>{a?.destroy()}})}catch(p){if(p.taskUUID)throw p;if(o>=l)return this.handleIncompleteImages({taskUUIDs:u,error:p})}};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=s,this._timeoutDuration=r}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 s=l=>{let a=Array.isArray(l?.data)?l.data:[l.data],u=l?.[0]?.errors?l?.[0]?.errors:Array.isArray(l?.errors)?l.errors:[l.errors],o=a.filter(d=>(d?.taskUUID||d?.taskType)===n);if(u.filter(d=>(d?.taskUUID||d?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(o.length){t({[n]:a});return}},r={key:n||k(),listener:s,groupKey:e};return this._listeners.push(r),{destroy:()=>{this._listeners=ae(this._listeners,r)}}}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){ee(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:s,negativePrompt:r}){return this.addListener({taskUUID:e,lis:i=>{let l=i?.[e]?.filter(a=>a.taskUUID===e);i.error?(t?.(l,i?.error&&i),this._globalError=i):(l=l.map(a=>({...a,positivePrompt:s,negativePrompt:r})),t?.(l,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(a=>({...a,positivePrompt:s,negativePrompt:r}))]:this._globalImages=[...this._globalImages,...l])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,r=n?.[e]?.[0],i=r?.taskUUID===e?r:null;(i||s)&&t?.(i||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=se({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNsfw:s,positivePrompt:r,negativePrompt:i,seedImage:l,maskImage:a,strength:u,height:o,width:p,model:d,steps:m,scheduler:g,seed:y,CFGScale:_,clipSkip:b,usePromptWeighting:D,numberResults:x=1,controlNet:T,lora:h,onPartialImages:ge,includeCost:me,customTaskUUID:ye,retry:Ie,refiner:H}){let I,V,C=[],j=0,J=Ie||this._globalMaxRetries;try{await this.ensureConnection();let w=null,E=null,M=[];if(l){let U=await this.uploadImage(l);if(!U)return[];w=U.imageUUID}if(a){let U=await this.uploadImage(a);if(!U)return[];E=U.imageUUID}if(T?.length)for(let U=0;U<T.length;U++){let A=T[U],{endStep:K,startStep:W,weight:F,guideImage:O,controlMode:he,startStepPercentage:fe,endStepPercentage:_e,model:be}=A,Te=O?await this.uploadImage(O):null;M.push({guideImage:Te?.imageUUID,model:be,endStep:K,startStep:W,weight:F,...f({key:"startStepPercentage",value:fe}),...f({key:"endStepPercentage",value:_e}),controlMode:he||"controlnet"})}return V={taskType:"imageInference",model:d,positivePrompt:r,...i?{negativePrompt:i}:{},...o?{height:o}:{},...p?{width:p}:{},numberResults:x,...h?.length?{lora:h}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNsfw",value:s}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:_}),...f({key:"clipSkip",value:b}),...f({key:"usePromptWeighting",value:D}),...f({key:"steps",value:m}),...M.length?{controlNet:M}:{},...y?{seed:y}:{},...g?{scheduler:g}:{},...H?{refiner:H}:{},...f({key:"includeCost",value:me}),...w?{seedImage:w}:{},...E?{maskImage:E}:{}},await R(async()=>{j++,I?.destroy();let U=this._globalImages.filter(O=>C.includes(O.taskUUID)),A=ye||k();C.push(A);let K=x-U.length,W={...V,taskUUID:A,numberResults:K};this.send(W),I=this.listenToImages({onPartialImages:ge,taskUUID:A,groupKey:"REQUEST_IMAGES",positivePrompt:r,negativePrompt:i});let F=await this.getSimilarImages({taskUUID:C,numberResults:x,lis:I});return I.destroy(),F},{maxRetries:J,callback:()=>{I?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(j>=J)return this.handleIncompleteImages({taskUUIDs:C,error:w})}}async ensureConnection(){if(this.connected()||this._url===q.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((s,r)=>{let i=0,l=30,a=i%10===0,u,o,p=()=>{clearInterval(u),clearInterval(o)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{this.connected()?(p(),s(!0)):i>=l?(p(),r(new Error("Retry timed out"))):(a&&this.connect(),i++)}catch(d){p(),r(d)}},e)),o=setInterval(async()=>{if(this.connected()){p(),s(!0);return}if(this._invalidAPIkey){p(),r(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:s}){return await v(({resolve:r,reject:i,intervalId:l})=>{let a=Array.isArray(t)?t:[t],u=this._globalImages.filter(o=>a.includes(o.taskUUID));if(this._globalError){let o=this._globalError;return this._globalError=void 0,clearInterval(l),i?.(o),!0}else if(u.length>=e)return clearInterval(l),this._globalImages=this._globalImages.filter(o=>!a.includes(o.taskUUID)),r([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(s=>t.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!t.includes(s.taskUUID)),n;throw e}};var de=Se(ue(),1),N=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new de.default(this._url),this.connect()}};import Ve 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=>{let n;(n=e?.destroy)==null||n.call(e)}),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 Ve(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 s=n?e:e?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(i=>{i.listener(r)})}))}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{Y as EControlMode,Oe as EModelArchitecture,Le as EModelConditioning,Ce as EModelFormat,Ne as EModelType,Ae as EOpenPosePreProcessor,Ee as EPhotoMakerEnum,$ as EPreProcessor,Z as EPreProcessorGroup,B as ETaskType,z as Environment,pe as Runware,N as RunwareClient,L as RunwareServer,P as SdkType};
1
+ var _e=Object.create;var J=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var ve=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var we=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Re(t))!De.call(c,a)&&a!==e&&J(c,a,{get:()=>t[a],enumerable:!(n=ke(t,a))||n.enumerable});return c};var Se=(c,t,e)=>(e=c!=null?_e(xe(c)):{},we(t||!c||!c.__esModule?J(e,"default",{value:c,enumerable:!0}):e,c));var ue=ve((Lt,ce)=>{"use strict";var ie=c=>c&&c.CLOSING===2,We=()=>typeof WebSocket<"u"&&ie(WebSocket),Fe=()=>({constructor:We()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Ge=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},oe=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Be=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},qe=["onopen","onclose","onmessage","onerror"],He=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&qe.forEach(n=>{c[n]=t[n]})},le=function(c,t,e={}){let n,a,o=0,l=0,i=!0,r={};if(!(this instanceof le))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Fe();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!ie(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=Be(u,o):o=oe(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&&Ge(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=oe(u),g("reconnectDelay:",o),l=0}),n.addEventListener("close",s),He(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,h])=>{U(x),n.removeEventListener("close",U,h)}),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)}};ce.exports=le});var Q=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Q||{}),F=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(F||{}),G=(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))(G||{}),Y=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(Y||{}),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))(Z||{}),$=(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=(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))(Ae||{}),Ce=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Ce||{}),Me=(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))(Me||{}),Oe=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Oe||{}),Ne=(h=>(h.canny="canny",h.depth="depth",h.qrcode="qrcode",h.hed="hed",h.scrible="scrible",h.openpose="openpose",h.seg="segmentation",h.openmlsd="openmlsd",h.softedge="softedge",h.normal="normal bae",h.shuffle="shuffle",h.pix2pix="pix2pix",h.inpaint="inpaint",h.lineart="line art",h.sketch="sketch",h.inpaintdepth="inpaint depth",h.tile="tile",h.outfit="outfit",h.blur="blur",h.gray="gray",h.lowquality="low quality",h))(Ne||{}),Le=(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))(Le||{});import{v4 as Ee,validate as Ke}from"uuid";var B=6e4,X=1e3,Pe=100,q={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ee=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},D=(c,{debugKey:t="debugKey",timeoutDuration:e=B,shouldThrowError:n=!0})=>(e=e<X?X: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))},Pe)})),te=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),_=()=>Ee(),ne=c=>Ke(c);var se=({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||{})??{},re=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var ae=(c,t)=>c.filter(e=>e.key!==t.key);var f=({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 re(e),await k(c,{...t,maxRetries:a});else throw o}};var S=class{constructor({apiKey:t,url:e=q.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=B}){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"&&ne(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await te(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,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:l}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:r}),...f({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,...f({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,...f({key:"rgba",value:a}),...f({key:"postProcessMask",value:o}),...f({key:"returnOnlyMask",value:l}),...f({key:"alphaMatting",value:i}),...f({key:"includeCost",value:d}),...f({key:"alphaMattingForegroundThreshold",value:r}),...f({key:"alphaMattingBackgroundThreshold",value:u}),...f({key:"alphaMattingErodeSize",value:g}),...f({key:"outputType",value:e}),...f({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:T});let v=await D(({resolve:x,reject:U})=>{let h=this.getSingleMessage({taskUUID:T});if(h){if(h?.error)return U(h),!0;if(h)return delete this._globalMessages[T],x(h),!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,...f({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,...f({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=ae(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){ee(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=se({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:h,onPartialImages:pe,includeCost:me,customTaskUUID:ye,retry:Ie,refiner:H}){let I,V,C=[],j=0,z=Ie||this._globalMaxRetries;try{await this.ensureConnection();let w=null,L=null,E=[];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[];L=R.imageUUID}if(U?.length)for(let R=0;R<U.length;R++){let A=U[R],{endStep:K,startStep:P,weight:W,guideImage:M,controlMode:he,startStepPercentage:fe,endStepPercentage:be,model:Te}=A,Ue=M?await this.uploadImage(M):null;E.push({guideImage:Ue?.imageUUID,model:Te,endStep:K,startStep:P,weight:W,...f({key:"startStepPercentage",value:fe}),...f({key:"endStepPercentage",value:be}),controlMode:he||"controlnet"})}return V={taskType:"imageInference",model:s,positivePrompt:o,...l?{negativePrompt:l}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:x,...h?.length?{lora:h}:{},...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:T}),...f({key:"usePromptWeighting",value:v}),...f({key:"steps",value:m}),...E.length?{controlNet:E}:{},...y?{seed:y}:{},...p?{scheduler:p}:{},...H?{refiner:H}:{},...f({key:"includeCost",value:me}),...w?{seedImage:w}:{},...L?{maskImage:L}:{}},await k(async()=>{j++,I?.destroy();let R=this._globalImages.filter(M=>C.includes(M.taskUUID)),A=ye||_();C.push(A);let K=x-R.length,P={...V,taskUUID:A,numberResults:K};this.send(P),I=this.listenToImages({onPartialImages:pe,taskUUID:A,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:l});let W=await this.getSimilarImages({taskUUID:C,numberResults:x,lis:I});return I.destroy(),W},{maxRetries:z,callback:()=>{I?.destroy()}})}catch(w){if(w.taskUUID)throw w;if(j>=z)return this.handleIncompleteImages({taskUUIDs:C,error:w})}}async ensureConnection(){if(this.connected()||this._url===q.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 ge=Se(ue(),1),O=class extends S{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new ge.default(this._url),this.connect()}};import Ve from"ws";var N=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 Ve(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 de;typeof window>"u"?de=N:de=O;export{Y as EControlMode,Me as EModelArchitecture,Ne as EModelConditioning,Ce as EModelFormat,Oe as EModelType,Ae as EOpenPosePreProcessor,Le as EPhotoMakerEnum,$ as EPreProcessor,Z as EPreProcessorGroup,G as ETaskType,Q as Environment,de as Runware,O as RunwareClient,N as RunwareServer,F as SdkType};
2
2
  //# sourceMappingURL=index.js.map