@runware/sdk-js 1.2.2 → 1.2.4-beta.1
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.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -1
- package/dist/index.d.ts +43 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +8 -2
package/dist/index.d.cts
CHANGED
|
@@ -15,6 +15,7 @@ declare enum ETaskType {
|
|
|
15
15
|
VIDEO_INFERENCE = "videoInference",
|
|
16
16
|
CAPTION = "caption",
|
|
17
17
|
AUDIO_INFERENCE = "audioInference",
|
|
18
|
+
THREE_D_INFERENCE = "3dInference",
|
|
18
19
|
GET_RESPONSE = "getResponse",
|
|
19
20
|
PHOTO_MAKER = "photoMaker",
|
|
20
21
|
IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
|
|
@@ -37,6 +38,7 @@ type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
|
37
38
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
38
39
|
type IVideoOutputFormat = "MP4" | "WEBM" | "MOV";
|
|
39
40
|
type IAudioOutputFormat = "MP3";
|
|
41
|
+
type IThreeDOutputFormat = "GLB" | "PLY";
|
|
40
42
|
interface IAdditionalResponsePayload {
|
|
41
43
|
includePayload?: boolean;
|
|
42
44
|
includeGenerationTime?: boolean;
|
|
@@ -69,6 +71,22 @@ interface IVideoToImage {
|
|
|
69
71
|
seed?: number;
|
|
70
72
|
videoURL?: string;
|
|
71
73
|
}
|
|
74
|
+
interface TOutputFile {
|
|
75
|
+
uuid: string;
|
|
76
|
+
url: string;
|
|
77
|
+
}
|
|
78
|
+
interface TOutputFiles {
|
|
79
|
+
files: TOutputFile[];
|
|
80
|
+
}
|
|
81
|
+
interface IThreeDImage {
|
|
82
|
+
taskType: ETaskType;
|
|
83
|
+
taskUUID: string;
|
|
84
|
+
status: string;
|
|
85
|
+
NSFWContent?: boolean;
|
|
86
|
+
cost?: number;
|
|
87
|
+
seed: number;
|
|
88
|
+
outputs?: TOutputFiles;
|
|
89
|
+
}
|
|
72
90
|
interface IControlNetImage {
|
|
73
91
|
taskUUID: string;
|
|
74
92
|
inputImageUUID: string;
|
|
@@ -328,6 +346,28 @@ interface IRequestAudio {
|
|
|
328
346
|
retry?: number;
|
|
329
347
|
[key: string]: unknown;
|
|
330
348
|
}
|
|
349
|
+
interface IRequestThreeD {
|
|
350
|
+
model: string;
|
|
351
|
+
numberResults?: number;
|
|
352
|
+
outputType?: IOutputType;
|
|
353
|
+
outputFormat?: IThreeDOutputFormat;
|
|
354
|
+
uploadEndpoint?: string;
|
|
355
|
+
includeCost?: boolean;
|
|
356
|
+
positivePrompt?: string;
|
|
357
|
+
onPartialResponse?: (results: IThreeDImage[], error?: IError) => void;
|
|
358
|
+
inputs?: {
|
|
359
|
+
image?: InputsValue;
|
|
360
|
+
mask?: InputsValue;
|
|
361
|
+
} & {
|
|
362
|
+
[key: string]: unknown;
|
|
363
|
+
};
|
|
364
|
+
deliveryMethod?: string;
|
|
365
|
+
taskUUID?: string;
|
|
366
|
+
customTaskUUID?: string;
|
|
367
|
+
skipResponse?: boolean;
|
|
368
|
+
retry?: number;
|
|
369
|
+
[key: string]: unknown;
|
|
370
|
+
}
|
|
331
371
|
interface IAsyncResults {
|
|
332
372
|
taskUUID: string;
|
|
333
373
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
@@ -736,6 +776,7 @@ type MediaUUID = {
|
|
|
736
776
|
audioUUID?: string;
|
|
737
777
|
imageUUID?: string;
|
|
738
778
|
videoUUID?: string;
|
|
779
|
+
outputs?: TOutputFiles;
|
|
739
780
|
};
|
|
740
781
|
|
|
741
782
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
@@ -804,6 +845,7 @@ declare class RunwareBase {
|
|
|
804
845
|
vectorize: (payload: TVectorize) => Promise<TVectorizeResponse>;
|
|
805
846
|
videoInference: (payload: IRequestVideo) => Promise<IVideoToImage[] | IVideoToImage>;
|
|
806
847
|
audioInference: (payload: IRequestAudio) => Promise<IAudio[] | IAudio>;
|
|
848
|
+
threeDInference: (payload: IRequestThreeD) => Promise<IThreeDImage[] | IThreeDImage>;
|
|
807
849
|
getResponse: <T>(payload: IAsyncResults) => Promise<T[]>;
|
|
808
850
|
/**
|
|
809
851
|
* Upscale an image or video
|
|
@@ -864,4 +906,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
864
906
|
|
|
865
907
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
866
908
|
|
|
867
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
909
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestThreeD, type IRequestVideo, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
package/dist/index.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ declare enum ETaskType {
|
|
|
15
15
|
VIDEO_INFERENCE = "videoInference",
|
|
16
16
|
CAPTION = "caption",
|
|
17
17
|
AUDIO_INFERENCE = "audioInference",
|
|
18
|
+
THREE_D_INFERENCE = "3dInference",
|
|
18
19
|
GET_RESPONSE = "getResponse",
|
|
19
20
|
PHOTO_MAKER = "photoMaker",
|
|
20
21
|
IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
|
|
@@ -37,6 +38,7 @@ type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
|
37
38
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
38
39
|
type IVideoOutputFormat = "MP4" | "WEBM" | "MOV";
|
|
39
40
|
type IAudioOutputFormat = "MP3";
|
|
41
|
+
type IThreeDOutputFormat = "GLB" | "PLY";
|
|
40
42
|
interface IAdditionalResponsePayload {
|
|
41
43
|
includePayload?: boolean;
|
|
42
44
|
includeGenerationTime?: boolean;
|
|
@@ -69,6 +71,22 @@ interface IVideoToImage {
|
|
|
69
71
|
seed?: number;
|
|
70
72
|
videoURL?: string;
|
|
71
73
|
}
|
|
74
|
+
interface TOutputFile {
|
|
75
|
+
uuid: string;
|
|
76
|
+
url: string;
|
|
77
|
+
}
|
|
78
|
+
interface TOutputFiles {
|
|
79
|
+
files: TOutputFile[];
|
|
80
|
+
}
|
|
81
|
+
interface IThreeDImage {
|
|
82
|
+
taskType: ETaskType;
|
|
83
|
+
taskUUID: string;
|
|
84
|
+
status: string;
|
|
85
|
+
NSFWContent?: boolean;
|
|
86
|
+
cost?: number;
|
|
87
|
+
seed: number;
|
|
88
|
+
outputs?: TOutputFiles;
|
|
89
|
+
}
|
|
72
90
|
interface IControlNetImage {
|
|
73
91
|
taskUUID: string;
|
|
74
92
|
inputImageUUID: string;
|
|
@@ -328,6 +346,28 @@ interface IRequestAudio {
|
|
|
328
346
|
retry?: number;
|
|
329
347
|
[key: string]: unknown;
|
|
330
348
|
}
|
|
349
|
+
interface IRequestThreeD {
|
|
350
|
+
model: string;
|
|
351
|
+
numberResults?: number;
|
|
352
|
+
outputType?: IOutputType;
|
|
353
|
+
outputFormat?: IThreeDOutputFormat;
|
|
354
|
+
uploadEndpoint?: string;
|
|
355
|
+
includeCost?: boolean;
|
|
356
|
+
positivePrompt?: string;
|
|
357
|
+
onPartialResponse?: (results: IThreeDImage[], error?: IError) => void;
|
|
358
|
+
inputs?: {
|
|
359
|
+
image?: InputsValue;
|
|
360
|
+
mask?: InputsValue;
|
|
361
|
+
} & {
|
|
362
|
+
[key: string]: unknown;
|
|
363
|
+
};
|
|
364
|
+
deliveryMethod?: string;
|
|
365
|
+
taskUUID?: string;
|
|
366
|
+
customTaskUUID?: string;
|
|
367
|
+
skipResponse?: boolean;
|
|
368
|
+
retry?: number;
|
|
369
|
+
[key: string]: unknown;
|
|
370
|
+
}
|
|
331
371
|
interface IAsyncResults {
|
|
332
372
|
taskUUID: string;
|
|
333
373
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
@@ -736,6 +776,7 @@ type MediaUUID = {
|
|
|
736
776
|
audioUUID?: string;
|
|
737
777
|
imageUUID?: string;
|
|
738
778
|
videoUUID?: string;
|
|
779
|
+
outputs?: TOutputFiles;
|
|
739
780
|
};
|
|
740
781
|
|
|
741
782
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
@@ -804,6 +845,7 @@ declare class RunwareBase {
|
|
|
804
845
|
vectorize: (payload: TVectorize) => Promise<TVectorizeResponse>;
|
|
805
846
|
videoInference: (payload: IRequestVideo) => Promise<IVideoToImage[] | IVideoToImage>;
|
|
806
847
|
audioInference: (payload: IRequestAudio) => Promise<IAudio[] | IAudio>;
|
|
848
|
+
threeDInference: (payload: IRequestThreeD) => Promise<IThreeDImage[] | IThreeDImage>;
|
|
807
849
|
getResponse: <T>(payload: IAsyncResults) => Promise<T[]>;
|
|
808
850
|
/**
|
|
809
851
|
* Upscale an image or video
|
|
@@ -864,4 +906,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
864
906
|
|
|
865
907
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
866
908
|
|
|
867
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
909
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestThreeD, type IRequestVideo, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var qe=Object.create;var ce=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var ze=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var Qe=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(l,s)&&s!==t&&ce(l,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return l};var je=(l,e,t)=>(t=l!=null?qe(Ge(l)):{},Qe(e||!l||!l.__esModule?ce(t,"default",{value:l,enumerable:!0}):t,l));var Se=ze((yn,ve)=>{"use strict";var De=l=>l&&l.CLOSING===2,rt=()=>typeof WebSocket<"u"&&De(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},_e=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,it=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&<.forEach(n=>{l[n]=e[n]})},xe=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof xe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=at();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!De(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let h=new Error(y);h.code=c,Array.isArray(o.error)&&o.error.forEach(([I])=>I(h)),n.onerror&&n.onerror(h)},0),p=()=>{if(m("close"),a++,m("retries count:",a),a>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(d,r):r=_e(d),m("reconnectDelay:",r),i&&setTimeout(u,r)},u=()=>{m("connect");let c=n;n=new d.constructor(l,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),m("open"),r=_e(d),m("reconnectDelay:",r),a=0}),n.addEventListener("close",p),ut(n,c,o)};m("init"),u(),this.close=(c=1e3,y="",{keepClosed:h=!1,fastClose:I=!0,delay:T=0}={})=>{if(T&&(r=T),i=!h,n.close(c,y),I){let R={code:c,reason:y,wasClean:!0};p(),Array.isArray(o.close)&&o.close.forEach(([k,U])=>{k(R),n.removeEventListener("close",k,U)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,h)=>{Array.isArray(o[c])?o[c].some(([I])=>I===y)||o[c].push([y,h]):o[c]=[[y,h]],n.addEventListener(c,y,h)},this.removeEventListener=(c,y,h)=>{Array.isArray(o[c])&&(o[c]=o[c].filter(([I])=>I!==y)),n.removeEventListener(c,y,h)}};ve.exports=xe});var de=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(de||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Z=(I=>(I.IMAGE_INFERENCE="imageInference",I.IMAGE_UPLOAD="imageUpload",I.UPSCALE="upscale",I.REMOVE_BACKGROUND="removeBackground",I.VIDEO_INFERENCE="videoInference",I.CAPTION="caption",I.AUDIO_INFERENCE="audioInference",I.GET_RESPONSE="getResponse",I.PHOTO_MAKER="photoMaker",I.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",I.IMAGE_MASKING="imageMasking",I.PROMPT_ENHANCE="promptEnhance",I.AUTHENTICATION="authentication",I.MODEL_UPLOAD="modelUpload",I.MODEL_SEARCH="modelSearch",I.MEDIA_STORAGE="mediaStorage",I.VECTORIZE="vectorize",I))(Z||{}),pe=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(pe||{}),ge=(p=>(p.canny="canny",p.depth="depth",p.mlsd="mlsd",p.normalbae="normalbae",p.openpose="openpose",p.tile="tile",p.seg="seg",p.lineart="lineart",p.lineart_anime="lineart_anime",p.shuffle="shuffle",p.scribble="scribble",p.softedge="softedge",p))(ge||{}),me=(b=>(b.canny="canny",b.depth_leres="depth_leres",b.depth_midas="depth_midas",b.depth_zoe="depth_zoe",b.inpaint_global_harmonious="inpaint_global_harmonious",b.lineart_anime="lineart_anime",b.lineart_coarse="lineart_coarse",b.lineart_realistic="lineart_realistic",b.lineart_standard="lineart_standard",b.mlsd="mlsd",b.normal_bae="normal_bae",b.scribble_hed="scribble_hed",b.scribble_pidinet="scribble_pidinet",b.seg_ofade20k="seg_ofade20k",b.seg_ofcoco="seg_ofcoco",b.seg_ufade20k="seg_ufade20k",b.shuffle="shuffle",b.softedge_hed="softedge_hed",b.softedge_hedsafe="softedge_hedsafe",b.softedge_pidinet="softedge_pidinet",b.softedge_pidisafe="softedge_pidisafe",b.tile_gaussian="tile_gaussian",b.openpose="openpose",b.openpose_face="openpose_face",b.openpose_faceonly="openpose_faceonly",b.openpose_full="openpose_full",b.openpose_hand="openpose_hand",b))(me||{}),Je=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Je||{}),Ze=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ze||{}),Ye=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(Ye||{}),$e=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))($e||{}),Xe=(U=>(U.canny="canny",U.depth="depth",U.qrcode="qrcode",U.hed="hed",U.scrible="scrible",U.openpose="openpose",U.seg="segmentation",U.openmlsd="openmlsd",U.softedge="softedge",U.normal="normal bae",U.shuffle="shuffle",U.pix2pix="pix2pix",U.inpaint="inpaint",U.lineart="line art",U.sketch="sketch",U.inpaintdepth="inpaint depth",U.tile="tile",U.outfit="outfit",U.blur="blur",U.gray="gray",U.lowquality="low quality",U))(Xe||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var F=6e4,W=1e3,Ie=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ye=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},C=(l,{debugKey:e="debugKey",timeoutDuration:t=F,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<W?W:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),he=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),_=()=>tt(),Ue=l=>nt(l);var be=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,d=a?.[i];if(!d)return o;if(Array.isArray(d)&&/^\d+$/.test(i)){let m=parseInt(i,10);return m>=0&&m<d.length?a[i]=d[m]:a[i]??o}else return a[i]??o},e||{})??{},Te=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var fe=(l,e)=>l.filter(t=>t.key!==e.key);var f=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},st=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,Re=()=>st(1,Number.MAX_SAFE_INTEGER),ke=(l,{debugKey:e="debugKey",timeoutDuration:t=F,shouldThrowError:n=!0,pollingInterval:s=Ie})=>(t=t<W?W:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(d){clearInterval(o),clearTimeout(i),a(d)}},s)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await Te(t),await x(l,{...e,maxRetries:s});else throw r}};var O=class{constructor({apiKey:e,url:t=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=F}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=_();if(typeof e=="string"&&Ue(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await he(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:g,customTaskUUID:p,taskUUID:u,retry:c,includeGenerationTime:y,includePayload:h})=>{let I=c||this._globalMaxRetries,T,R=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let U=u||p||_(),A={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...f({key:"height",value:n}),...f({key:"width",value:s}),...f({key:"outputType",value:r}),...f({key:"outputFormat",value:a}),...f({key:"includeCost",value:m}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:o}),...f({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...A}),T=this.globalListener({taskUUID:U});let w=await C(({resolve:S,reject:B})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return B(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return T.destroy(),this.insertAdditionalResponse({response:w,payload:h?A:void 0,startTime:y?R:void 0}),w},{maxRetries:I,callback:()=>{T?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:d,skipResponse:m,model:g})=>{try{let p;e&&(p=await this.uploadImage(e));let c={taskUUID:r||s||_(),taskType:"caption",model:g,inputImage:p?.imageUUID,inputs:t,...f({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let h=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:h}))[0]}return y}catch(p){throw p}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:d,taskUUID:m,retry:g,includeGenerationTime:p,includePayload:u,skipResponse:c,deliveryMethod:y})=>{try{let h;e&&(h=await this.uploadImage(e));let T={taskUUID:m||d||_(),inputImage:h?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...f({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:u,includeGenerationTime:p,retry:g,deliveryMethod:y},R=await this.baseSingleRequest({payload:{...T,taskType:"upscale"},debugKey:"upscale"});if(c)return R;if(y==="async"){let k=R?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return R}catch(h){throw h}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:d})=>{let m=i||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,...f({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:u});let y=await C(({resolve:h,reject:I})=>{let T=this._globalMessages[u];if(T?.error)return I(T),!0;if(T?.length>=n)return delete this._globalMessages[u],h(T),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:o?p:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let d=r||s||_();this.send({...a,taskUUID:d,taskType:"modelUpload"});let m,g;return o=this.listenToUpload({taskUUID:d,onUploadStream:(u,c)=>{t?.(u,c),u?.status==="ready"?m=u:c&&(g=c)}}),await C(({resolve:u,reject:c})=>{if(m)return u(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:d,...m}=e,g=s||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let h=this._globalImages.filter(U=>u.includes(U.taskUUID)),I=a||r||_();u.push(I);let T=i-h.length,R={...m,...m.seed?{seed:m.seed}:{seed:Re()},...t??{},taskUUID:I,taskType:"photoMaker",numberResults:i};this.send({...R,numberResults:T}),p=this.listenToResponse({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:d?R:void 0,startTime:o?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(h){if(h.taskUUID)throw h;if(c>=g)return this.handleIncompleteImages({taskUUIDs:u,error:h})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...d}=e,m=s||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=a||r||_(),c={...d,taskUUID:u};this.send(c),g=this.globalListener({taskUUID:u});let y=await C(({resolve:h,reject:I})=>{let T=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(T){if(T?.error)return I(T),!0;if(T)return delete this._globalMessages[u],h(T),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:i?c:void 0,startTime:o?p:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:r,includePayload:a,numberResults:i=1,onPartialResponse:o,includeGenerationTime:d,...m}=e,g=s||this._globalMaxRetries,p,u=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let h=this._globalImages.filter(U=>u.includes(U.taskUUID)),I=r||_();u.push(I);let T=i-h.length,R={...m,taskUUID:I,numberResults:T};if(this.send(R),n)return new Promise((U,A)=>{let w=this.addListener({taskUUID:I,groupKey:t,lis:S=>{w.destroy(),S.error?A(S.error):U(S[I])}})});p=this.listenToResponse({onPartialImages:o,taskUUID:I,groupKey:t,requestPayload:a?R:void 0,startTime:d?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(h){throw h}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await ke(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[])if(o.status==="success"){let d=this.getUniqueUUID(o);d&&n.set(d,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],m=o.filter(p=>(p?.taskUUID||p?.taskType)===n);if(d.filter(p=>(p?.taskUUID||p?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(m.length){e({[n]:o});return}},r={key:n||_(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=fe(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){ye(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=be({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:d,height:m,width:g,model:p,steps:u,scheduler:c,seed:y,CFGScale:h,clipSkip:I,usePromptWeighting:T,promptWeighting:R,numberResults:k=1,onPartialImages:U,includeCost:A,customTaskUUID:w,taskUUID:S,retry:B,refiner:v,maskMargin:b,outputQuality:$,controlNet:G,lora:X,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Ee,includePayload:Ce,...Oe},Me){let M,ie,P=[],le=0,ue=B||this._globalMaxRetries;try{await this.ensureConnection();let E=null,H=null,z=[];if(i){let D=await this.uploadImage(i);if(!D)return[];E=D.imageUUID}if(o){let D=await this.uploadImage(o);if(!D)return[];H=D.imageUUID}if(G?.length)for(let D=0;D<G.length;D++){let N=G[D],{endStep:Q,startStep:L,weight:j,guideImage:K,controlMode:Pe,startStepPercentage:Le,endStepPercentage:Ke,model:We}=N,Fe=K?await this.uploadImage(K):null;z.push({guideImage:Fe?.imageUUID,model:We,endStep:Q,startStep:L,weight:j,...f({key:"startStepPercentage",value:Le}),...f({key:"endStepPercentage",value:Ke}),controlMode:Pe||"controlnet"})}ie={taskType:"imageInference",model:p,positivePrompt:r,...a?{negativePrompt:a}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNSFW",value:s}),...f({key:"strength",value:d}),...f({key:"CFGScale",value:h}),...f({key:"clipSkip",value:I}),...f({key:"maskMargin",value:b}),...f({key:"usePromptWeighting",value:T}),...f({key:"steps",value:u}),...R?{promptWeighting:R}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...f({key:"includeCost",value:A}),...E?{seedImage:E}:{},...H?{maskImage:H}:{},...$?{outputQuality:$}:{},...z.length?{controlNet:z}:{},...X?.length?{lora:X}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...Oe,...Me??{}};let Ne=Date.now();return await x(async()=>{le++,M?.destroy();let D=this._globalImages.filter(K=>P.includes(K.taskUUID)),N=S||w||_();P.push(N);let Q=k-D.length,L={...ie,taskUUID:N,numberResults:Q};this.send(L),M=this.listenToResponse({onPartialImages:U,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Ce?L:void 0,startTime:Ee?Ne:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:M});return M.destroy(),j},{maxRetries:ue,callback:()=>{M?.destroy()}})}catch(E){if(le>=ue)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=_(),d,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let p=this.connected(),u=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),u=!0);let c=a%10===0&&u;p?(g(),s(!0)):a>=i?(g(),r(new Error("Retry timed out"))):(c&&this.connect(),a++)}catch(p){g(),r(p)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s}){return await C(({resolve:r,reject:a,intervalId:i})=>{let o=Array.isArray(e)?e:[e],d=this._globalImages.filter(m=>o.includes(m.taskUUID));if(this._globalError){let m=this._globalError;return this._globalError=void 0,clearInterval(i),a?.(m),!0}else if(d.length>=t)return clearInterval(i),this._globalImages=this._globalImages.filter(m=>!o.includes(m.taskUUID)),r([...d].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var Ae=je(Se(),1),q=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ae.default(this._url),this.connect()}};import ct from"ws";var V=class extends O{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var we;typeof window>"u"?we=V:we=q;export{pe as EControlMode,Ye as EModelArchitecture,Xe as EModelConditioning,Ze as EModelFormat,$e as EModelType,Je as EOpenPosePreProcessor,et as EPhotoMakerEnum,me as EPreProcessor,ge as EPreProcessorGroup,Z as ETaskType,de as Environment,we as Runware,q as RunwareClient,V as RunwareServer,J as SdkType};
|
|
1
|
+
var qe=Object.create;var de=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var ze=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var Qe=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(l,s)&&s!==t&&de(l,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return l};var je=(l,e,t)=>(t=l!=null?qe(Ge(l)):{},Qe(e||!l||!l.__esModule?de(t,"default",{value:l,enumerable:!0}):t,l));var Ae=ze((Un,Se)=>{"use strict";var ve=l=>l&&l.CLOSING===2,rt=()=>typeof WebSocket<"u"&&ve(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},_e=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,it=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&<.forEach(n=>{l[n]=e[n]})},xe=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof xe))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=at();if(Object.keys(p).filter(d=>t.hasOwnProperty(d)).forEach(d=>p[d]=t[d]),!ve(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=p.debug?(...d)=>console.log("RWS:",...d):()=>{},g=(d,y)=>setTimeout(()=>{let h=new Error(y);h.code=d,Array.isArray(o.error)&&o.error.forEach(([b])=>b(h)),n.onerror&&n.onerror(h)},0),u=()=>{if(m("close"),a++,m("retries count:",a),a>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(p,r):r=_e(p),m("reconnectDelay:",r),i&&setTimeout(c,r)},c=()=>{m("connect");let d=n;n=new p.constructor(l,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),m("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),m("open"),r=_e(p),m("reconnectDelay:",r),a=0}),n.addEventListener("close",u),ut(n,d,o)};m("init"),c(),this.close=(d=1e3,y="",{keepClosed:h=!1,fastClose:b=!0,delay:I=0}={})=>{if(I&&(r=I),i=!h,n.close(d,y),b){let R={code:d,reason:y,wasClean:!0};u(),Array.isArray(o.close)&&o.close.forEach(([k,U])=>{k(R),n.removeEventListener("close",k,U)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=d=>{n.send(d)},this.addEventListener=(d,y,h)=>{Array.isArray(o[d])?o[d].some(([b])=>b===y)||o[d].push([y,h]):o[d]=[[y,h]],n.addEventListener(d,y,h)},this.removeEventListener=(d,y,h)=>{Array.isArray(o[d])&&(o[d]=o[d].filter(([b])=>b!==y)),n.removeEventListener(d,y,h)}};Se.exports=xe});var pe=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(pe||{}),J=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(J||{}),Y=(I=>(I.IMAGE_INFERENCE="imageInference",I.IMAGE_UPLOAD="imageUpload",I.UPSCALE="upscale",I.REMOVE_BACKGROUND="removeBackground",I.VIDEO_INFERENCE="videoInference",I.CAPTION="caption",I.AUDIO_INFERENCE="audioInference",I.THREE_D_INFERENCE="3dInference",I.GET_RESPONSE="getResponse",I.PHOTO_MAKER="photoMaker",I.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",I.IMAGE_MASKING="imageMasking",I.PROMPT_ENHANCE="promptEnhance",I.AUTHENTICATION="authentication",I.MODEL_UPLOAD="modelUpload",I.MODEL_SEARCH="modelSearch",I.MEDIA_STORAGE="mediaStorage",I.VECTORIZE="vectorize",I))(Y||{}),ge=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ge||{}),me=(u=>(u.canny="canny",u.depth="depth",u.mlsd="mlsd",u.normalbae="normalbae",u.openpose="openpose",u.tile="tile",u.seg="seg",u.lineart="lineart",u.lineart_anime="lineart_anime",u.shuffle="shuffle",u.scribble="scribble",u.softedge="softedge",u))(me||{}),Ie=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(Ie||{}),Je=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(Je||{}),Ye=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Ye||{}),Ze=(c=>(c.flux1d="flux1d",c.flux1s="flux1s",c.pony="pony",c.sdhyper="sdhyper",c.sd1x="sd1x",c.sd1xlcm="sd1xlcm",c.sd3="sd3",c.sdxl="sdxl",c.sdxllcm="sdxllcm",c.sdxldistilled="sdxldistilled",c.sdxlhyper="sdxlhyper",c.sdxllightning="sdxllightning",c.sdxlturbo="sdxlturbo",c))(Ze||{}),$e=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))($e||{}),Xe=(U=>(U.canny="canny",U.depth="depth",U.qrcode="qrcode",U.hed="hed",U.scrible="scrible",U.openpose="openpose",U.seg="segmentation",U.openmlsd="openmlsd",U.softedge="softedge",U.normal="normal bae",U.shuffle="shuffle",U.pix2pix="pix2pix",U.inpaint="inpaint",U.lineart="line art",U.sketch="sketch",U.inpaintdepth="inpaint depth",U.tile="tile",U.outfit="outfit",U.blur="blur",U.gray="gray",U.lowquality="low quality",U))(Xe||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var W=6e4,K=1e3,ye=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},he=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},C=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),Ue=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),D=()=>tt(),Te=l=>nt(l);var be=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,p=a?.[i];if(!p)return o;if(Array.isArray(p)&&/^\d+$/.test(i)){let m=parseInt(i,10);return m>=0&&m<p.length?a[i]=p[m]:a[i]??o}else return a[i]??o},e||{})??{},fe=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var Re=(l,e)=>l.filter(t=>t.key!==e.key);var f=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},st=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,ke=()=>st(1,Number.MAX_SAFE_INTEGER),De=(l,{debugKey:e="debugKey",timeoutDuration:t=W,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<K?K:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(p){clearInterval(o),clearTimeout(i),a(p)}},s)}));var v=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await fe(t),await v(l,{...e,maxRetries:s});else throw r}};var O=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=W}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await v(async()=>{let t=D();if(typeof e=="string"&&Te(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await Ue(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:p,includeCost:m,outputQuality:g,customTaskUUID:u,taskUUID:c,retry:d,includeGenerationTime:y,includePayload:h})=>{let b=d||this._globalMaxRetries,I,R=Date.now();try{return await v(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let U=c||u||D(),A={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...f({key:"height",value:n}),...f({key:"width",value:s}),...f({key:"outputType",value:r}),...f({key:"outputFormat",value:a}),...f({key:"includeCost",value:m}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:o}),...f({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...A}),I=this.globalListener({taskUUID:U});let w=await C(({resolve:S,reject:B})=>{let x=this.getSingleMessage({taskUUID:U});if(x){if(x?.error)return B(x),!0;if(x)return S(x),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return I.destroy(),this.insertAdditionalResponse({response:w,payload:h?A:void 0,startTime:y?R:void 0}),w},{maxRetries:b,callback:()=>{I?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:p,skipResponse:m,model:g})=>{try{let u;e&&(u=await this.uploadImage(e));let d={taskUUID:r||s||D(),taskType:"caption",model:g,inputImage:u?.imageUUID,inputs:t,...f({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},y=await this.baseSingleRequest({payload:{...d,taskType:"caption"},debugKey:"caption"});if(m)return y;if(p==="async"){let h=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:h}))[0]}return y}catch(u){throw u}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:p,taskUUID:m,retry:g,includeGenerationTime:u,includePayload:c,skipResponse:d,deliveryMethod:y})=>{try{let h;e&&(h=await this.uploadImage(e));let I={taskUUID:m||p||D(),inputImage:h?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...f({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:c,includeGenerationTime:u,retry:g,deliveryMethod:y},R=await this.baseSingleRequest({payload:{...I,taskType:"upscale"},debugKey:"upscale"});if(d)return R;if(y==="async"){let k=R?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return R}catch(h){throw h}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:p})=>{let m=i||this._globalMaxRetries,g,u=Date.now();try{return await v(async()=>{await this.ensureConnection();let c=a||r||D(),d={prompt:e,taskUUID:c,promptMaxLength:t,promptVersions:n,...f({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(d),g=this.globalListener({taskUUID:c});let y=await C(({resolve:h,reject:b})=>{let I=this._globalMessages[c];if(I?.error)return b(I),!0;if(I?.length>=n)return delete this._globalMessages[c],h(I),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:p?d:void 0,startTime:o?u:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(c){throw c}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await v(async()=>{await this.ensureConnection();let p=r||s||D();this.send({...a,taskUUID:p,taskType:"modelUpload"});let m,g;return o=this.listenToUpload({taskUUID:p,onUploadStream:(c,d)=>{t?.(c,d),c?.status==="ready"?m=c:d&&(g=d)}}),await C(({resolve:c,reject:d})=>{if(m)return c(m),!0;if(g)return d(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(p){throw p}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:p,...m}=e,g=s||this._globalMaxRetries,u,c=[],d=0,y=Date.now();try{return await v(async()=>{await this.ensureConnection(),d++;let h=this._globalImages.filter(U=>c.includes(U.taskUUID)),b=a||r||D();c.push(b);let I=i-h.length,R={...m,...m.seed?{seed:m.seed}:{seed:ke()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:i};this.send({...R,numberResults:I}),u=this.listenToResponse({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:p?R:void 0,startTime:o?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:c,numberResults:i,lis:u});return u.destroy(),k},{maxRetries:g,callback:()=>{u?.destroy()}})}catch(h){if(h.taskUUID)throw h;if(d>=g)return this.handleIncompleteImages({taskUUIDs:c,error:h})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...p}=e,m=s||this._globalMaxRetries,g,u=Date.now();try{return await v(async()=>{await this.ensureConnection();let c=a||r||D(),d={...p,taskUUID:c};this.send(d),g=this.globalListener({taskUUID:c});let y=await C(({resolve:h,reject:b})=>{let I=n?this.getMultipleMessages({taskUUID:c}):this.getSingleMessage({taskUUID:c});if(I){if(I?.error)return b(I),!0;if(I)return delete this._globalMessages[c],h(I),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:i?d:void 0,startTime:o?u:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(c){throw c}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:r,includePayload:a,numberResults:i=1,onPartialResponse:o,includeGenerationTime:p,...m}=e,g=s||this._globalMaxRetries,u,c=[],d=0,y=Date.now();try{return await v(async()=>{await this.ensureConnection(),d++;let h=this._globalImages.filter(U=>c.includes(U.taskUUID)),b=r||D();c.push(b);let I=i-h.length,R={...m,taskUUID:b,numberResults:I};if(this.send(R),n)return new Promise((U,A)=>{let w=this.addListener({taskUUID:b,groupKey:t,lis:S=>{w.destroy(),S.error?A(S.error):U(S[b])}})});u=this.listenToResponse({onPartialImages:o,taskUUID:b,groupKey:t,requestPayload:a?R:void 0,startTime:p?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:c,numberResults:i,lis:u});return u.destroy(),k},{maxRetries:g,callback:()=>{u?.destroy()}})}catch(h){throw h}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await De(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[])if(o.status==="success"){let p=this.getUniqueUUID(o);p&&n.set(p,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],p=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],m=o.filter(u=>(u?.taskUUID||u?.taskType)===n);if(p.filter(u=>(u?.taskUUID||u?.taskType)===n).length){e({error:{...p[0]??{}}});return}if(m.length){e({[n]:o});return}},r={key:n||D(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Re(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){he(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=be({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:p,height:m,width:g,model:u,steps:c,scheduler:d,seed:y,CFGScale:h,clipSkip:b,usePromptWeighting:I,promptWeighting:R,numberResults:k=1,onPartialImages:U,includeCost:A,customTaskUUID:w,taskUUID:S,retry:B,refiner:x,maskMargin:T,outputQuality:$,controlNet:G,lora:X,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Ce,includePayload:Oe,...ie},Me){let M,le,P=[],ue=0,ce=B||this._globalMaxRetries;try{await this.ensureConnection();let E=null,H=null,z=[];if(i){let _=await this.uploadImage(i);if(!_)return[];E=_.imageUUID}if(o){let _=await this.uploadImage(o);if(!_)return[];H=_.imageUUID}if(G?.length)for(let _=0;_<G.length;_++){let N=G[_],{endStep:Q,startStep:L,weight:j,guideImage:F,controlMode:Pe,startStepPercentage:Le,endStepPercentage:Fe,model:Ke}=N,We=F?await this.uploadImage(F):null;z.push({guideImage:We?.imageUUID,model:Ke,endStep:Q,startStep:L,weight:j,...f({key:"startStepPercentage",value:Le}),...f({key:"endStepPercentage",value:Fe}),controlMode:Pe||"controlnet"})}le={taskType:"imageInference",model:u,positivePrompt:r,...a?{negativePrompt:a}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNSFW",value:s}),...f({key:"strength",value:p}),...f({key:"CFGScale",value:h}),...f({key:"clipSkip",value:b}),...f({key:"maskMargin",value:T}),...f({key:"usePromptWeighting",value:I}),...f({key:"steps",value:c}),...R?{promptWeighting:R}:{},...y?{seed:y}:{},...d?{scheduler:d}:{},...x?{refiner:x}:{},...se?{outpaint:se}:{},...f({key:"includeCost",value:A}),...E?{seedImage:E}:{},...H?{maskImage:H}:{},...$?{outputQuality:$}:{},...z.length?{controlNet:z}:{},...X?.length?{lora:X}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...ie,...Me??{}};let Ne=Date.now();return await v(async()=>{ue++,M?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||w||D();P.push(N);let Q=k-_.length,L={...le,taskUUID:N,numberResults:Q};this.send(L),M=this.listenToResponse({onPartialImages:U,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Oe?L:void 0,startTime:Ce?Ne:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:M,deliveryMethod:ie.deliveryMethod});return M.destroy(),j},{maxRetries:ce,callback:()=>{M?.destroy()}})}catch(E){if(ue>=ce)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=D(),p,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(m)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let u=this.connected(),c=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),c=!0);let d=a%10===0&&c;u?(g(),s(!0)):a>=i?(g(),r(new Error("Retry timed out"))):(d&&this.connect(),a++)}catch(u){g(),r(u)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s,deliveryMethod:r}){return await C(({resolve:a,reject:i,intervalId:o})=>{let p=Array.isArray(e)?e:[e],m=this._globalImages.filter(u=>p.includes(u.taskUUID)),g=r==="async"&&m.length>0;if(this._globalError){let u=this._globalError;return this._globalError=void 0,clearInterval(o),i?.(u),!0}else if(m.length>=t||g)return clearInterval(o),this._globalImages=this._globalImages.filter(u=>!p.includes(u.taskUUID)),a([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var we=je(Ae(),1),q=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new we.default(this._url),this.connect()}};import ct from"ws";var V=class extends O{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);console.log("response",JSON.stringify(r,null,4)),this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ee;typeof window>"u"?Ee=V:Ee=q;export{ge as EControlMode,Ze as EModelArchitecture,Xe as EModelConditioning,Ye as EModelFormat,$e as EModelType,Je as EOpenPosePreProcessor,et as EPhotoMakerEnum,Ie as EPreProcessor,me as EPreProcessorGroup,Y as ETaskType,pe as Environment,Ee as Runware,q as RunwareClient,V as RunwareServer,J as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|