@runware/sdk-js 1.1.42 → 1.1.44
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 +16 -5
- package/dist/index.d.ts +16 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +14 -0
package/dist/index.d.cts
CHANGED
|
@@ -32,6 +32,7 @@ type RunwareBaseType = {
|
|
|
32
32
|
};
|
|
33
33
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
34
34
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
35
|
+
type IVideoOutputFormat = "MP4" | "WEBM" | "MOV";
|
|
35
36
|
interface IAdditionalResponsePayload {
|
|
36
37
|
includePayload?: boolean;
|
|
37
38
|
includeGenerationTime?: boolean;
|
|
@@ -145,6 +146,7 @@ interface IRequestImage extends IAdditionalResponsePayload {
|
|
|
145
146
|
lora?: ILora[];
|
|
146
147
|
embeddings?: IEmbedding[];
|
|
147
148
|
ipAdapters?: IipAdapter[];
|
|
149
|
+
providerSettings?: IProviderSettings;
|
|
148
150
|
outpaint?: IOutpaint;
|
|
149
151
|
refiner?: IRefiner;
|
|
150
152
|
acceleratorOptions?: TAcceleratorOptions;
|
|
@@ -155,6 +157,7 @@ interface IRequestImage extends IAdditionalResponsePayload {
|
|
|
155
157
|
customTaskUUID?: string;
|
|
156
158
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
157
159
|
retry?: number;
|
|
160
|
+
[key: string]: any;
|
|
158
161
|
}
|
|
159
162
|
type TAcceleratorOptions = {
|
|
160
163
|
teaCache: boolean;
|
|
@@ -180,6 +183,15 @@ interface IipAdapter {
|
|
|
180
183
|
weight: number;
|
|
181
184
|
guideImage: string;
|
|
182
185
|
}
|
|
186
|
+
interface IBflProviderSettings {
|
|
187
|
+
promptUpsampling?: boolean;
|
|
188
|
+
safetyTolerance?: number;
|
|
189
|
+
raw?: boolean;
|
|
190
|
+
}
|
|
191
|
+
type ProviderSettings = {
|
|
192
|
+
bfl: IBflProviderSettings;
|
|
193
|
+
};
|
|
194
|
+
type IProviderSettings = RequireOnlyOne<ProviderSettings, keyof ProviderSettings>;
|
|
183
195
|
interface IRefiner {
|
|
184
196
|
model: string;
|
|
185
197
|
startStep?: number;
|
|
@@ -216,7 +228,7 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
216
228
|
}
|
|
217
229
|
interface IRequestVideo extends IRequestImageToText {
|
|
218
230
|
outputType?: IOutputType;
|
|
219
|
-
outputFormat?:
|
|
231
|
+
outputFormat?: IVideoOutputFormat;
|
|
220
232
|
outputQuality?: number;
|
|
221
233
|
uploadEndpoint?: string;
|
|
222
234
|
checkNSFW?: boolean;
|
|
@@ -628,7 +640,7 @@ declare class RunwareBase {
|
|
|
628
640
|
private listenToImages;
|
|
629
641
|
private listenToUpload;
|
|
630
642
|
private globalListener;
|
|
631
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
643
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, providerSettings, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, ...rest }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
632
644
|
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
633
645
|
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
634
646
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
@@ -641,10 +653,9 @@ declare class RunwareBase {
|
|
|
641
653
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
642
654
|
imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
|
|
643
655
|
imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
|
|
644
|
-
protected baseSingleRequest: <T>({ payload, debugKey,
|
|
656
|
+
protected baseSingleRequest: <T>({ payload, debugKey, isMultiple, }: {
|
|
645
657
|
payload: Record<string, any>;
|
|
646
658
|
debugKey: string;
|
|
647
|
-
mockResponse?: any;
|
|
648
659
|
isMultiple?: boolean | undefined;
|
|
649
660
|
}) => Promise<T>;
|
|
650
661
|
ensureConnection(): Promise<unknown>;
|
|
@@ -677,4 +688,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
677
688
|
|
|
678
689
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
679
690
|
|
|
680
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
|
691
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.d.ts
CHANGED
|
@@ -32,6 +32,7 @@ type RunwareBaseType = {
|
|
|
32
32
|
};
|
|
33
33
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
34
34
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
35
|
+
type IVideoOutputFormat = "MP4" | "WEBM" | "MOV";
|
|
35
36
|
interface IAdditionalResponsePayload {
|
|
36
37
|
includePayload?: boolean;
|
|
37
38
|
includeGenerationTime?: boolean;
|
|
@@ -145,6 +146,7 @@ interface IRequestImage extends IAdditionalResponsePayload {
|
|
|
145
146
|
lora?: ILora[];
|
|
146
147
|
embeddings?: IEmbedding[];
|
|
147
148
|
ipAdapters?: IipAdapter[];
|
|
149
|
+
providerSettings?: IProviderSettings;
|
|
148
150
|
outpaint?: IOutpaint;
|
|
149
151
|
refiner?: IRefiner;
|
|
150
152
|
acceleratorOptions?: TAcceleratorOptions;
|
|
@@ -155,6 +157,7 @@ interface IRequestImage extends IAdditionalResponsePayload {
|
|
|
155
157
|
customTaskUUID?: string;
|
|
156
158
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
157
159
|
retry?: number;
|
|
160
|
+
[key: string]: any;
|
|
158
161
|
}
|
|
159
162
|
type TAcceleratorOptions = {
|
|
160
163
|
teaCache: boolean;
|
|
@@ -180,6 +183,15 @@ interface IipAdapter {
|
|
|
180
183
|
weight: number;
|
|
181
184
|
guideImage: string;
|
|
182
185
|
}
|
|
186
|
+
interface IBflProviderSettings {
|
|
187
|
+
promptUpsampling?: boolean;
|
|
188
|
+
safetyTolerance?: number;
|
|
189
|
+
raw?: boolean;
|
|
190
|
+
}
|
|
191
|
+
type ProviderSettings = {
|
|
192
|
+
bfl: IBflProviderSettings;
|
|
193
|
+
};
|
|
194
|
+
type IProviderSettings = RequireOnlyOne<ProviderSettings, keyof ProviderSettings>;
|
|
183
195
|
interface IRefiner {
|
|
184
196
|
model: string;
|
|
185
197
|
startStep?: number;
|
|
@@ -216,7 +228,7 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
216
228
|
}
|
|
217
229
|
interface IRequestVideo extends IRequestImageToText {
|
|
218
230
|
outputType?: IOutputType;
|
|
219
|
-
outputFormat?:
|
|
231
|
+
outputFormat?: IVideoOutputFormat;
|
|
220
232
|
outputQuality?: number;
|
|
221
233
|
uploadEndpoint?: string;
|
|
222
234
|
checkNSFW?: boolean;
|
|
@@ -628,7 +640,7 @@ declare class RunwareBase {
|
|
|
628
640
|
private listenToImages;
|
|
629
641
|
private listenToUpload;
|
|
630
642
|
private globalListener;
|
|
631
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
643
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, controlNet, lora, embeddings, ipAdapters, providerSettings, outpaint, acceleratorOptions, advancedFeatures, referenceImages, includeGenerationTime, includePayload, ...rest }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
632
644
|
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
633
645
|
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
634
646
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
@@ -641,10 +653,9 @@ declare class RunwareBase {
|
|
|
641
653
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
642
654
|
imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
|
|
643
655
|
imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
|
|
644
|
-
protected baseSingleRequest: <T>({ payload, debugKey,
|
|
656
|
+
protected baseSingleRequest: <T>({ payload, debugKey, isMultiple, }: {
|
|
645
657
|
payload: Record<string, any>;
|
|
646
658
|
debugKey: string;
|
|
647
|
-
mockResponse?: any;
|
|
648
659
|
isMultiple?: boolean | undefined;
|
|
649
660
|
}) => Promise<T>;
|
|
650
661
|
ensureConnection(): Promise<unknown>;
|
|
@@ -677,4 +688,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
677
688
|
|
|
678
689
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
679
690
|
|
|
680
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoToImage, type IipAdapter, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
|
691
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, 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 IRequestImage, type IRequestImageToText, type IRequestVideo, type ITextToImage, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, 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 TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ke=Object.create;var le=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var qe=(u,t)=>()=>(t||u((t={exports:{}}).exports,t),t.exports);var Ve=(u,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fe(t))!Be.call(u,s)&&s!==e&&le(u,s,{get:()=>t[s],enumerable:!(n=We(t,s))||n.enumerable});return u};var He=(u,t,e)=>(e=u!=null?Ke(Ge(u)):{},Ve(t||!u||!u.__esModule?le(e,"default",{value:u,enumerable:!0}):e,u));var De=qe((rn,ke)=>{"use strict";var _e=u=>u&&u.CLOSING===2,tt=()=>typeof WebSocket<"u"&&_e(WebSocket),nt=()=>({constructor:tt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),st=(u,t,e)=>{Object.defineProperty(t,e,{get:()=>u[e],set:n=>{u[e]=n},enumerable:!0,configurable:!0})},Ue=u=>u.minReconnectionDelay+Math.random()*u.minReconnectionDelay,rt=(u,t)=>{let e=t*u.reconnectionDelayGrowFactor;return e>u.maxReconnectionDelay?u.maxReconnectionDelay:e},at=["onopen","onclose","onmessage","onerror"],ot=(u,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,a])=>{u.addEventListener(n,s,a)})}),t&&at.forEach(n=>{u[n]=t[n]})},Re=function(u,t,e={}){let n,s,a=0,i=0,c=!0,r={};if(!(this instanceof Re))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=nt();if(Object.keys(p).filter(o=>e.hasOwnProperty(o)).forEach(o=>p[o]=e[o]),!_e(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...o)=>console.log("RWS:",...o):()=>{},m=(o,y)=>setTimeout(()=>{let I=new Error(y);I.code=o,Array.isArray(r.error)&&r.error.forEach(([b])=>b(I)),n.onerror&&n.onerror(I)},0),l=()=>{if(d("close"),i++,d("retries count:",i),i>p.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}a?a=rt(p,a):a=Ue(p),d("reconnectDelay:",a),c&&setTimeout(g,a)},g=()=>{d("connect");let o=n;n=new p.constructor(u,t),s=setTimeout(()=>{d("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&st(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),a=Ue(p),d("reconnectDelay:",a),i=0}),n.addEventListener("close",l),ot(n,o,r)};d("init"),g(),this.close=(o=1e3,y="",{keepClosed:I=!1,fastClose:b=!0,delay:_=0}={})=>{if(_&&(a=_),c=!I,n.close(o,y),b){let R={code:o,reason:y,wasClean:!0};l(),Array.isArray(r.close)&&r.close.forEach(([U,f])=>{U(R),n.removeEventListener("close",U,f)}),n.onclose&&(n.onclose(R),n.onclose=null)}},this.send=o=>{n.send(o)},this.addEventListener=(o,y,I)=>{Array.isArray(r[o])?r[o].some(([b])=>b===y)||r[o].push([y,I]):r[o]=[[y,I]],n.addEventListener(o,y,I)},this.removeEventListener=(o,y,I)=>{Array.isArray(r[o])&&(r[o]=r[o].filter(([b])=>b!==y)),n.removeEventListener(o,y,I)}};ke.exports=Re});var ce=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ce||{}),J=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(J||{}),z=(o=>(o.IMAGE_INFERENCE="imageInference",o.IMAGE_UPLOAD="imageUpload",o.IMAGE_UPSCALE="imageUpscale",o.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",o.VIDEO_INFERENCE="videoInference",o.GET_RESPONSE="getResponse",o.PHOTO_MAKER="photoMaker",o.IMAGE_CAPTION="imageCaption",o.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",o.IMAGE_MASKING="imageMasking",o.PROMPT_ENHANCE="promptEnhance",o.AUTHENTICATION="authentication",o.MODEL_UPLOAD="modelUpload",o.MODEL_SEARCH="modelSearch",o))(z||{}),ue=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ue||{}),de=(l=>(l.canny="canny",l.depth="depth",l.mlsd="mlsd",l.normalbae="normalbae",l.openpose="openpose",l.tile="tile",l.seg="seg",l.lineart="lineart",l.lineart_anime="lineart_anime",l.shuffle="shuffle",l.scribble="scribble",l.softedge="softedge",l))(de||{}),pe=(h=>(h.canny="canny",h.depth_leres="depth_leres",h.depth_midas="depth_midas",h.depth_zoe="depth_zoe",h.inpaint_global_harmonious="inpaint_global_harmonious",h.lineart_anime="lineart_anime",h.lineart_coarse="lineart_coarse",h.lineart_realistic="lineart_realistic",h.lineart_standard="lineart_standard",h.mlsd="mlsd",h.normal_bae="normal_bae",h.scribble_hed="scribble_hed",h.scribble_pidinet="scribble_pidinet",h.seg_ofade20k="seg_ofade20k",h.seg_ofcoco="seg_ofcoco",h.seg_ufade20k="seg_ufade20k",h.shuffle="shuffle",h.softedge_hed="softedge_hed",h.softedge_hedsafe="softedge_hedsafe",h.softedge_pidinet="softedge_pidinet",h.softedge_pidisafe="softedge_pidisafe",h.tile_gaussian="tile_gaussian",h.openpose="openpose",h.openpose_face="openpose_face",h.openpose_faceonly="openpose_faceonly",h.openpose_full="openpose_full",h.openpose_hand="openpose_hand",h))(pe||{}),je=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(je||{}),Qe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Qe||{}),Je=(g=>(g.flux1d="flux1d",g.flux1s="flux1s",g.pony="pony",g.sdhyper="sdhyper",g.sd1x="sd1x",g.sd1xlcm="sd1xlcm",g.sd3="sd3",g.sdxl="sdxl",g.sdxllcm="sdxllcm",g.sdxldistilled="sdxldistilled",g.sdxlhyper="sdxlhyper",g.sdxllightning="sdxllightning",g.sdxlturbo="sdxlturbo",g))(Je||{}),ze=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(ze||{}),Ye=(f=>(f.canny="canny",f.depth="depth",f.qrcode="qrcode",f.hed="hed",f.scrible="scrible",f.openpose="openpose",f.seg="segmentation",f.openmlsd="openmlsd",f.softedge="softedge",f.normal="normal bae",f.shuffle="shuffle",f.pix2pix="pix2pix",f.inpaint="inpaint",f.lineart="line art",f.sketch="sketch",f.inpaintdepth="inpaint depth",f.tile="tile",f.outfit="outfit",f.blur="blur",f.gray="gray",f.lowquality="low quality",f))(Ye||{}),$e=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))($e||{});import{v4 as Ze,validate as Xe}from"uuid";var K=6e4,P=1e3,ge=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},me=(u,t)=>{if(u==null)return;let e=u.indexOf(t);e!==-1&&u.splice(e,1)},w=(u,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((a,i)=>{let c=setTimeout(()=>{r&&(clearInterval(r),n&&i(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),r=setInterval(async()=>{u({resolve:a,reject:i,intervalId:r})&&(clearInterval(r),clearTimeout(c))},s)})),ye=u=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(u),e.onload=function(){t(e.result)}}),k=()=>Ze(),Ie=u=>Xe(u);var he=({key:u,data:t,useZero:e=!0,shouldReturnString:n=!1})=>u.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,c)=>{let r=e?0:void 0,p=i?.[c];if(!p)return r;if(Array.isArray(p)&&/^\d+$/.test(c)){let d=parseInt(c,10);return d>=0&&d<p.length?i[c]=p[d]:i[c]??r}else return i[c]??r},t||{})??{},fe=(u,t=1e3)=>new Promise(e=>setTimeout(e,u*t));var be=(u,t)=>u.filter(e=>e.key!==t.key);var T=({key:u,value:t})=>t||t===0||t===!1?{[u]:t}:{},et=(u,t)=>Math.floor(Math.random()*(t-u+1))+u,$=()=>et(1,Number.MAX_SAFE_INTEGER);var Te=(u,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((a,i)=>{let c=setTimeout(()=>{r&&(clearInterval(r),n&&i(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),r=setInterval(async()=>{try{await u({resolve:a,reject:i,intervalId:r})&&(clearInterval(r),clearTimeout(c))}catch(p){clearInterval(r),clearTimeout(c),i(p)}},s)}));var v=async(u,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await u()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await fe(e),await v(u,{...t,maxRetries:s});else throw a}};var A=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await v(async()=>{let e=k();if(typeof t=="string"&&Ie(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ye(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:a,outputFormat:i,highThresholdCanny:c,lowThresholdCanny:r,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:m,customTaskUUID:l,retry:g,includeGenerationTime:o,includePayload:y})=>{let I=g||this._globalMaxRetries,b,_=Date.now();try{return await v(async()=>{await this.ensureConnection();let R=await this.uploadImage(t);if(!R?.imageUUID)return null;let U=l||k(),f={inputImage:R.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:a}),...T({key:"outputFormat",value:i}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:c}),...T({key:"lowThresholdCanny",value:r}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...m?{outputQuality:m}:{}};this.send({...f}),b=this.globalListener({taskUUID:U});let M=await w(({resolve:G,reject:B})=>{let x=this.getSingleMessage({taskUUID:U});if(x){if(x?.error)return B(x),!0;if(x)return G(x),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return b.destroy(),this.insertAdditionalResponse({response:M,payload:y?f:void 0,startTime:o?_:void 0}),M},{maxRetries:I,callback:()=>{b?.destroy()}})}catch(R){throw R}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:a,includeGenerationTime:i})=>{let c=s||this._globalMaxRetries,r,p=Date.now();try{return await v(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,m=n||k(),l={taskUUID:m,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(l),r=this.globalListener({taskUUID:m});let g=await w(({resolve:o,reject:y})=>{let I=this.getSingleMessage({taskUUID:m});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[m],o(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:g,payload:a?l:void 0,startTime:i?p:void 0}),g},{maxRetries:c,callback:()=>{r?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>{let{skipResponse:e,...n}=t;try{let s=await this.baseSingleRequest({payload:{...n,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(e)return s;let a=s?.taskUUID,i=t?.numberResults??1,c=new Map;return await Te(async({resolve:r,reject:p})=>{try{let d=await this.getResponse({taskUUID:a});for(let l of d||[])l.videoUUID&&c.set(l.videoUUID,l);return c.size===i?(r(Array.from(c.values())),!0):!1}catch(d){return p(d),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(c.values())}catch(s){throw s}};this.getResponse=async t=>{let e=t.taskUUID;return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:a,outputQuality:i,customTaskUUID:c,retry:r,includeGenerationTime:p,includePayload:d})=>{let m=r||this._globalMaxRetries,l,g=Date.now();try{return await v(async()=>{await this.ensureConnection();let o;o=await this.uploadImage(t);let y=c||k(),I={taskUUID:y,inputImage:o?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:a}),...n?{outputType:n}:{},...i?{outputQuality:i}:{},...s?{outputFormat:s}:{}};this.send(I),l=this.globalListener({taskUUID:y});let b=await w(({resolve:_,reject:R})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return R(U),!0;if(U)return delete this._globalMessages[y],_(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:b,payload:d?I:void 0,startTime:p?g:void 0}),b},{maxRetries:m,callback:()=>{l?.destroy()}})}catch(o){throw o}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,retry:i,includeGenerationTime:c,includePayload:r})=>{let p=i||this._globalMaxRetries,d,m=Date.now();try{return await v(async()=>{await this.ensureConnection();let l=a||k(),g={prompt:t,taskUUID:l,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(g),d=this.globalListener({taskUUID:l});let o=await w(({resolve:y,reject:I})=>{let b=this._globalMessages[l];if(b?.error)return I(b),!0;if(b?.length>=n)return delete this._globalMessages[l],y(b),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:o,payload:r?g:void 0,startTime:c?m:void 0}),o},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(l){throw l}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...a}=t,i=n||this._globalMaxRetries,c;try{return await v(async()=>{await this.ensureConnection();let r=s||k();this.send({...a,taskUUID:r,taskType:"modelUpload"});let p,d;return c=this.listenToUpload({taskUUID:r,onUploadStream:(l,g)=>{e?.(l,g),l?.status==="ready"?p=l:g&&(d=g)}}),await w(({resolve:l,reject:g})=>{if(p)return l(p),!0;if(d)return g(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{c?.destroy()}})}catch(r){throw r}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,numberResults:i,includeGenerationTime:c,includePayload:r,...p}=t,d=s||this._globalMaxRetries,m,l=[],g=0,o=Date.now();try{return await v(async()=>{await this.ensureConnection(),g++;let y=this._globalImages.filter(U=>l.includes(U.taskUUID)),I=a||k();l.push(I);let b=i-y.length,_={...p,...p.seed?{seed:p.seed}:{seed:$()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:i};this.send({..._,numberResults:b}),m=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:r?_:void 0,startTime:c?o:void 0});let R=await this.getSimilarImages({taskUUID:l,numberResults:i,lis:m});return m.destroy(),R},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(g>=d)return this.handleIncompleteImages({taskUUIDs:l,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,mockResponse:n,isMultiple:s})=>{let{retry:a,customTaskUUID:i,includePayload:c,includeGenerationTime:r,...p}=t,d=a||this._globalMaxRetries,m,l=Date.now();try{return await v(async()=>{await this.ensureConnection();let g=i||k(),o={...p,taskUUID:g};n?setTimeout(()=>{this._globalMessages[g]=n},1e3):this.send(o),m=this.globalListener({taskUUID:g});let y=await w(({resolve:I,reject:b})=>{let _=s?this.getMultipleMessages({taskUUID:g}):this.getSingleMessage({taskUUID:g});if(_){if(_?.error)return b(_),!0;if(_)return delete this._globalMessages[g],I(_),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:c?o:void 0,startTime:r?l:void 0}),m.destroy(),y},{maxRetries:d,callback:()=>{m?.destroy()}})}catch(g){throw g}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.getMultipleMessages=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.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=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=a}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=c=>{let r=Array.isArray(c?.data)?c.data:[c.data],p=c?.[0]?.errors?c?.[0]?.errors:Array.isArray(c?.errors)?c.errors:[c.errors],d=r.filter(l=>(l?.taskUUID||l?.taskType)===n);if(p.filter(l=>(l?.taskUUID||l?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:r});return}},a={key:n||k(),listener:s,groupKey:e};return this._listeners.push(a),{destroy:()=>{this._listeners=be(this._listeners,a)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){me(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:a}){return this.addListener({taskUUID:e,lis:i=>{let c=i?.[e]?.filter(r=>r.taskUUID===e);i.error?(t?.(c,i?.error&&i),this._globalError=i):(c=c.map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r})),t?.(c,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:a||void 0}),{...r}))]:this._globalImages=[...this._globalImages,...c])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,a=n?.[e]?.[0],i=a?.taskUUID===e?a: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=he({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:a,negativePrompt:i,seedImage:c,maskImage:r,strength:p,height:d,width:m,model:l,steps:g,scheduler:o,seed:y,CFGScale:I,clipSkip:b,usePromptWeighting:_,promptWeighting:R,numberResults:U=1,onPartialImages:f,includeCost:M,customTaskUUID:G,retry:B,refiner:x,maskMargin:we,outputQuality:h,controlNet:q,lora:Z,embeddings:X,ipAdapters:ee,outpaint:te,acceleratorOptions:ne,advancedFeatures:se,referenceImages:re,includeGenerationTime:Se,includePayload:Ae},Ce){let C,ae,O=[],oe=0,ie=B||this._globalMaxRetries;try{await this.ensureConnection();let S=null,V=null,H=[];if(c){let D=await this.uploadImage(c);if(!D)return[];S=D.imageUUID}if(r){let D=await this.uploadImage(r);if(!D)return[];V=D.imageUUID}if(q?.length)for(let D=0;D<q.length;D++){let E=q[D],{endStep:j,startStep:N,weight:Q,guideImage:L,controlMode:Me,startStepPercentage:Oe,endStepPercentage:Ne,model:Le}=E,Pe=L?await this.uploadImage(L):null;H.push({guideImage:Pe?.imageUUID,model:Le,endStep:j,startStep:N,weight:Q,...T({key:"startStepPercentage",value:Oe}),...T({key:"endStepPercentage",value:Ne}),controlMode:Me||"controlnet"})}ae={taskType:"imageInference",model:l,positivePrompt:a,...i?{negativePrompt:i}:{},...d?{height:d}:{},...m?{width:m}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:b}),...T({key:"maskMargin",value:we}),...T({key:"usePromptWeighting",value:_}),...T({key:"steps",value:g}),...R?{promptWeighting:R}:{},...y?{seed:y}:{seed:$()},...o?{scheduler:o}:{},...x?{refiner:x}:{},...te?{outpaint:te}:{},...T({key:"includeCost",value:M}),...S?{seedImage:S}:{},...V?{maskImage:V}:{},...h?{outputQuality:h}:{},...H.length?{controlNet:H}:{},...Z?.length?{lora:Z}:{},...X?.length?{embeddings:X}:{},...ee?.length?{ipAdapters:ee}:{},...ne?{acceleratorOptions:ne}:{},...se?{advancedFeatures:se}:{},...re?.length?{referenceImages:re}:{},...Ce??{}};let Ee=Date.now();return await v(async()=>{oe++,C?.destroy();let D=this._globalImages.filter(L=>O.includes(L.taskUUID)),E=G||k();O.push(E);let j=U-D.length,N={...ae,taskUUID:E,numberResults:j};this.send(N),C=this.listenToImages({onPartialImages:f,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ae?N:void 0,startTime:Se?Ee:void 0});let Q=await this.getSimilarImages({taskUUID:O,numberResults:U,lis:C});return C.destroy(),Q},{maxRetries:ie,callback:()=>{C?.destroy()}})}catch(S){if(oe>=ie)return this.handleIncompleteImages({taskUUIDs:O,error:S});throw S}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,a)=>{let i=0,c=30,r=k(),p,d,m=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let l=this.connected(),g=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),g=!0);let o=i%10===0&&g;l?(m(),s(!0)):i>=c?(m(),a(new Error("Retry timed out"))):(o&&this.connect(),i++)}catch(l){m(),a(l)}},e)),d=setInterval(async()=>{if(this.connected()){m(),s(!0);return}if(this.isInvalidAPIKey()){m(),a(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await w(({resolve:a,reject:i,intervalId:c})=>{let r=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>r.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(c),i?.(d),!0}else if(p.length>=e)return clearInterval(c),this._globalImages=this._globalImages.filter(d=>!r.includes(d.taskUUID)),a([...p].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 ve=He(De(),1),W=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new ve.default(this._url),this.connect()}};import it from"ws";var F=class extends A{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 it(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let a=JSON.parse(s);this._listeners.forEach(i=>{i.listener(a)})}))}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 xe;typeof window>"u"?xe=F:xe=W;export{ue as EControlMode,Je as EModelArchitecture,Ye as EModelConditioning,Qe as EModelFormat,ze as EModelType,je as EOpenPosePreProcessor,$e as EPhotoMakerEnum,pe as EPreProcessor,de as EPreProcessorGroup,z as ETaskType,ce as Environment,xe as Runware,W as RunwareClient,F as RunwareServer,J as SdkType};
|
|
1
|
+
var Fe=Object.create;var le=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var He=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var je=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Be(t))!Ve.call(c,s)&&s!==e&&le(c,s,{get:()=>t[s],enumerable:!(n=Ge(t,s))||n.enumerable});return c};var Qe=(c,t,e)=>(e=c!=null?Fe(qe(c)):{},je(t||!c||!c.__esModule?le(e,"default",{value:c,enumerable:!0}):e,c));var xe=He((on,De)=>{"use strict";var Re=c=>c&&c.CLOSING===2,st=()=>typeof WebSocket<"u"&&Re(WebSocket),rt=()=>({constructor:st()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),at=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},_e=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,ot=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},it=["onopen","onclose","onmessage","onerror"],lt=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,o])=>{c.addEventListener(n,s,o)})}),t&&it.forEach(n=>{c[n]=t[n]})},ke=function(c,t,e={}){let n,s,o=0,l=0,u=!0,r={};if(!(this instanceof ke))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=rt();if(Object.keys(p).filter(i=>e.hasOwnProperty(i)).forEach(i=>p[i]=e[i]),!Re(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let d=p.debug?(...i)=>console.log("RWS:",...i):()=>{},g=(i,y)=>setTimeout(()=>{let I=new Error(y);I.code=i,Array.isArray(r.error)&&r.error.forEach(([f])=>f(I)),n.onerror&&n.onerror(I)},0),a=()=>{if(d("close"),l++,d("retries count:",l),l>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}o?o=ot(p,o):o=_e(p),d("reconnectDelay:",o),u&&setTimeout(m,o)},m=()=>{d("connect");let i=n;n=new p.constructor(c,t),s=setTimeout(()=>{d("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),d("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&at(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),d("open"),o=_e(p),d("reconnectDelay:",o),l=0}),n.addEventListener("close",a),lt(n,i,r)};d("init"),m(),this.close=(i=1e3,y="",{keepClosed:I=!1,fastClose:f=!0,delay:k=0}={})=>{if(k&&(o=k),u=!I,n.close(i,y),f){let _={code:i,reason:y,wasClean:!0};a(),Array.isArray(r.close)&&r.close.forEach(([U,b])=>{U(_),n.removeEventListener("close",U,b)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=i=>{n.send(i)},this.addEventListener=(i,y,I)=>{Array.isArray(r[i])?r[i].some(([f])=>f===y)||r[i].push([y,I]):r[i]=[[y,I]],n.addEventListener(i,y,I)},this.removeEventListener=(i,y,I)=>{Array.isArray(r[i])&&(r[i]=r[i].filter(([f])=>f!==y)),n.removeEventListener(i,y,I)}};De.exports=ke});var ue=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ue||{}),J=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(J||{}),z=(i=>(i.IMAGE_INFERENCE="imageInference",i.IMAGE_UPLOAD="imageUpload",i.IMAGE_UPSCALE="imageUpscale",i.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",i.VIDEO_INFERENCE="videoInference",i.GET_RESPONSE="getResponse",i.PHOTO_MAKER="photoMaker",i.IMAGE_CAPTION="imageCaption",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))(z||{}),ce=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ce||{}),de=(a=>(a.canny="canny",a.depth="depth",a.mlsd="mlsd",a.normalbae="normalbae",a.openpose="openpose",a.tile="tile",a.seg="seg",a.lineart="lineart",a.lineart_anime="lineart_anime",a.shuffle="shuffle",a.scribble="scribble",a.softedge="softedge",a))(de||{}),pe=(h=>(h.canny="canny",h.depth_leres="depth_leres",h.depth_midas="depth_midas",h.depth_zoe="depth_zoe",h.inpaint_global_harmonious="inpaint_global_harmonious",h.lineart_anime="lineart_anime",h.lineart_coarse="lineart_coarse",h.lineart_realistic="lineart_realistic",h.lineart_standard="lineart_standard",h.mlsd="mlsd",h.normal_bae="normal_bae",h.scribble_hed="scribble_hed",h.scribble_pidinet="scribble_pidinet",h.seg_ofade20k="seg_ofade20k",h.seg_ofcoco="seg_ofcoco",h.seg_ufade20k="seg_ufade20k",h.shuffle="shuffle",h.softedge_hed="softedge_hed",h.softedge_hedsafe="softedge_hedsafe",h.softedge_pidinet="softedge_pidinet",h.softedge_pidisafe="softedge_pidisafe",h.tile_gaussian="tile_gaussian",h.openpose="openpose",h.openpose_face="openpose_face",h.openpose_faceonly="openpose_faceonly",h.openpose_full="openpose_full",h.openpose_hand="openpose_hand",h))(pe||{}),Je=(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))(Je||{}),ze=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(ze||{}),Ye=(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))(Ye||{}),$e=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))($e||{}),Ze=(b=>(b.canny="canny",b.depth="depth",b.qrcode="qrcode",b.hed="hed",b.scrible="scrible",b.openpose="openpose",b.seg="segmentation",b.openmlsd="openmlsd",b.softedge="softedge",b.normal="normal bae",b.shuffle="shuffle",b.pix2pix="pix2pix",b.inpaint="inpaint",b.lineart="line art",b.sketch="sketch",b.inpaintdepth="inpaint depth",b.tile="tile",b.outfit="outfit",b.blur="blur",b.gray="gray",b.lowquality="low quality",b))(Ze||{}),Xe=(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))(Xe||{});import{v4 as et,validate as tt}from"uuid";var K=6e4,P=1e3,ge=100,Y={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},me=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},S=(c,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((o,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{c({resolve:o,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))},s)})),ye=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),R=()=>et(),Ie=c=>tt(c);var he=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(l=>l.replace(/\]$/,"")).reduce((l,u)=>{let r=e?0:void 0,p=l?.[u];if(!p)return r;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?l[u]=p[d]:l[u]??r}else return l[u]??r},t||{})??{},fe=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var be=(c,t)=>c.filter(e=>e.key!==t.key);var T=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{},nt=(c,t)=>Math.floor(Math.random()*(t-c+1))+c,Te=()=>nt(1,Number.MAX_SAFE_INTEGER),Ue=(c,{debugKey:t="debugKey",timeoutDuration:e=K,shouldThrowError:n=!0,pollingInterval:s=ge})=>(e=e<P?P:e,new Promise((o,l)=>{let u=setTimeout(()=>{r&&(clearInterval(r),n&&l(`Response could not be received from server for ${t}`)),clearTimeout(u)},e),r=setInterval(async()=>{try{await c({resolve:o,reject:l,intervalId:r})&&(clearInterval(r),clearTimeout(u))}catch(p){clearInterval(r),clearTimeout(u),l(p)}},s)}));var x=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await c()}catch(o){if(n?.(),o?.error)throw o;if(s--,s>0)await fe(e),await x(c,{...t,maxRetries:s});else throw o}};var A=class{constructor({apiKey:t,url:e=Y.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:o=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await x(async()=>{let e=R();if(typeof t=="string"&&Ie(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ye(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:o,outputFormat:l,highThresholdCanny:u,lowThresholdCanny:r,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:g,customTaskUUID:a,retry:m,includeGenerationTime:i,includePayload:y})=>{let I=m||this._globalMaxRetries,f,k=Date.now();try{return await x(async()=>{await this.ensureConnection();let _=await this.uploadImage(t);if(!_?.imageUUID)return null;let U=a||R(),b={inputImage:_.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...T({key:"height",value:n}),...T({key:"width",value:s}),...T({key:"outputType",value:o}),...T({key:"outputFormat",value:l}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:r}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...b}),f=this.globalListener({taskUUID:U});let O=await S(({resolve:G,reject:B})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return B(v),!0;if(v)return G(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:O,payload:y?b:void 0,startTime:i?k:void 0}),O},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:o,includeGenerationTime:l})=>{let u=s||this._globalMaxRetries,r,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let d=t?await this.uploadImage(t):null,g=n||R(),a={taskUUID:g,taskType:"imageCaption",inputImage:d?.imageUUID,...T({key:"includeCost",value:e})};this.send(a),r=this.globalListener({taskUUID:g});let m=await S(({resolve:i,reject:y})=>{let I=this.getSingleMessage({taskUUID:g});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[g],i(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return r.destroy(),this.insertAdditionalResponse({response:m,payload:o?a:void 0,startTime:l?p:void 0}),m},{maxRetries:u,callback:()=>{r?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>{let{skipResponse:e,...n}=t;try{let s=await this.baseSingleRequest({payload:{...n,deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(e)return s;let o=s?.taskUUID,l=t?.numberResults??1,u=new Map;return await Ue(async({resolve:r,reject:p})=>{try{let d=await this.getResponse({taskUUID:o});for(let a of d||[])a.videoUUID&&u.set(a.videoUUID,a);return u.size===l?(r(Array.from(u.values())),!0):!1}catch(d){return p(d),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(u.values())}catch(s){throw s}};this.getResponse=async t=>{let e=t.taskUUID;return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:o,outputQuality:l,customTaskUUID:u,retry:r,includeGenerationTime:p,includePayload:d})=>{let g=r||this._globalMaxRetries,a,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let i;i=await this.uploadImage(t);let y=u||R(),I={taskUUID:y,inputImage:i?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:o}),...n?{outputType:n}:{},...l?{outputQuality:l}:{},...s?{outputFormat:s}:{}};this.send(I),a=this.globalListener({taskUUID:y});let f=await S(({resolve:k,reject:_})=>{let U=this.getSingleMessage({taskUUID:y});if(U){if(U?.error)return _(U),!0;if(U)return delete this._globalMessages[y],k(U),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return a.destroy(),this.insertAdditionalResponse({response:f,payload:d?I:void 0,startTime:p?m:void 0}),f},{maxRetries:g,callback:()=>{a?.destroy()}})}catch(i){throw i}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:o,retry:l,includeGenerationTime:u,includePayload:r})=>{let p=l||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let a=o||R(),m={prompt:t,taskUUID:a,promptMaxLength:e,promptVersions:n,...T({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(m),d=this.globalListener({taskUUID:a});let i=await S(({resolve:y,reject:I})=>{let f=this._globalMessages[a];if(f?.error)return I(f),!0;if(f?.length>=n)return delete this._globalMessages[a],y(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return d.destroy(),this.insertAdditionalResponse({response:i,payload:r?m:void 0,startTime:u?g:void 0}),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(a){throw a}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...o}=t,l=n||this._globalMaxRetries,u;try{return await x(async()=>{await this.ensureConnection();let r=s||R();this.send({...o,taskUUID:r,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:r,onUploadStream:(a,m)=>{e?.(a,m),a?.status==="ready"?p=a:m&&(d=m)}}),await S(({resolve:a,reject:m})=>{if(p)return a(p),!0;if(d)return m(d),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:l,callback:()=>{u?.destroy()}})}catch(r){throw r}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:o,numberResults:l,includeGenerationTime:u,includePayload:r,...p}=t,d=s||this._globalMaxRetries,g,a=[],m=0,i=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>a.includes(U.taskUUID)),I=o||R();a.push(I);let f=l-y.length,k={...p,...p.seed?{seed:p.seed}:{seed:Te()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:l};this.send({...k,numberResults:f}),g=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:r?k:void 0,startTime:u?i:void 0});let _=await this.getSimilarImages({taskUUID:a,numberResults:l,lis:g});return g.destroy(),_},{maxRetries:d,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(m>=d)return this.handleIncompleteImages({taskUUIDs:a,error:y})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageUpload"},debugKey:"image-upload"});this.baseSingleRequest=async({payload:t,debugKey:e,isMultiple:n})=>{let{retry:s,customTaskUUID:o,includePayload:l,includeGenerationTime:u,...r}=t,p=s||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let a=o||R(),m={...r,taskUUID:a};this.send(m),d=this.globalListener({taskUUID:a});let i=await S(({resolve:y,reject:I})=>{let f=n?this.getMultipleMessages({taskUUID:a}):this.getSingleMessage({taskUUID:a});if(f){if(f?.error)return I(f),!0;if(f)return delete this._globalMessages[a],y(f),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:i,payload:l?m:void 0,startTime:u?g:void 0}),d.destroy(),i},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(a){throw a}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.getMultipleMessages=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n};this.insertAdditionalResponse=({response:t,payload:e,startTime:n})=>{if(!e&&!n)return;let s=t;s.additionalResponse={},e&&(t.additionalResponse.payload=e),n&&(t.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=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,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 s=u=>{let r=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=r.filter(a=>(a?.taskUUID||a?.taskType)===n);if(p.filter(a=>(a?.taskUUID||a?.taskType)===n).length){t({error:{...p[0]??{}}});return}if(d.length){t({[n]:r});return}},o={key:n||R(),listener:s,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=be(this._listeners,o)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this.isInvalidAPIKey()}}destroy(t){me(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,requestPayload:s,startTime:o}){return this.addListener({taskUUID:e,lis:l=>{let u=l?.[e]?.filter(r=>r.taskUUID===e);l.error?(t?.(u,l?.error&&l),this._globalError=l):(u=u.map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:o||void 0}),{...r})),t?.(u,l?.error&&l),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(l?.[e]??[]).map(r=>(this.insertAdditionalResponse({response:r,payload:s||void 0,startTime:o||void 0}),{...r}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,o=n?.[e]?.[0],l=o?.taskUUID===e?o:null;(l||s)&&t?.(l||void 0,s)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=he({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:o,negativePrompt:l,seedImage:u,maskImage:r,strength:p,height:d,width:g,model:a,steps:m,scheduler:i,seed:y,CFGScale:I,clipSkip:f,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:b,includeCost:O,customTaskUUID:G,retry:B,refiner:v,maskMargin:we,outputQuality:h,controlNet:q,lora:$,embeddings:Z,ipAdapters:X,providerSettings:ee,outpaint:te,acceleratorOptions:ne,advancedFeatures:se,referenceImages:re,includeGenerationTime:Ae,includePayload:Ce,...Ee},Oe){let C,ae,M=[],oe=0,ie=B||this._globalMaxRetries;try{await this.ensureConnection();let w=null,V=null,H=[];if(u){let D=await this.uploadImage(u);if(!D)return[];w=D.imageUUID}if(r){let D=await this.uploadImage(r);if(!D)return[];V=D.imageUUID}if(q?.length)for(let D=0;D<q.length;D++){let E=q[D],{endStep:j,startStep:N,weight:Q,guideImage:L,controlMode:Ne,startStepPercentage:Le,endStepPercentage:Pe,model:Ke}=E,We=L?await this.uploadImage(L):null;H.push({guideImage:We?.imageUUID,model:Ke,endStep:j,startStep:N,weight:Q,...T({key:"startStepPercentage",value:Le}),...T({key:"endStepPercentage",value:Pe}),controlMode:Ne||"controlnet"})}ae={taskType:"imageInference",model:a,positivePrompt:o,...l?{negativePrompt:l}:{},...d?{height:d}:{},...g?{width:g}:{},numberResults:U,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...T({key:"checkNSFW",value:s}),...T({key:"strength",value:p}),...T({key:"CFGScale",value:I}),...T({key:"clipSkip",value:f}),...T({key:"maskMargin",value:we}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{},...i?{scheduler:i}:{},...v?{refiner:v}:{},...te?{outpaint:te}:{},...T({key:"includeCost",value:O}),...w?{seedImage:w}:{},...V?{maskImage:V}:{},...h?{outputQuality:h}:{},...H.length?{controlNet:H}:{},...$?.length?{lora:$}:{},...Z?.length?{embeddings:Z}:{},...X?.length?{ipAdapters:X}:{},...ee?{providerSettings:ee}:{},...ne?{acceleratorOptions:ne}:{},...se?{advancedFeatures:se}:{},...re?.length?{referenceImages:re}:{},...Ee,...Oe??{}};let Me=Date.now();return await x(async()=>{oe++,C?.destroy();let D=this._globalImages.filter(L=>M.includes(L.taskUUID)),E=G||R();M.push(E);let j=U-D.length,N={...ae,taskUUID:E,numberResults:j};this.send(N),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ce?N:void 0,startTime:Ae?Me:void 0});let Q=await this.getSimilarImages({taskUUID:M,numberResults:U,lis:C});return C.destroy(),Q},{maxRetries:ie,callback:()=>{C?.destroy()}})}catch(w){if(oe>=ie)return this.handleIncompleteImages({taskUUIDs:M,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===Y.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,o)=>{let l=0,u=30,r=R(),p,d,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(d)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let a=this.connected(),m=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),m=!0);let i=l%10===0&&m;a?(g(),s(!0)):l>=u?(g(),o(new Error("Retry timed out"))):(i&&this.connect(),l++)}catch(a){g(),o(a)}},e)),d=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),o(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await S(({resolve:o,reject:l,intervalId:u})=>{let r=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>r.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),l?.(d),!0}else if(p.length>=e)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!r.includes(d.taskUUID)),o([...p].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 ve=Qe(xe(),1),W=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new ve.default(this._url),this.connect()}};import ut from"ws";var F=class extends A{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 ut(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let s=n?e:e?.toString();if(!s)return;let o=JSON.parse(s);this._listeners.forEach(l=>{l.listener(o)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Se;typeof window>"u"?Se=F:Se=W;export{ce as EControlMode,Ye as EModelArchitecture,Ze as EModelConditioning,ze as EModelFormat,$e as EModelType,Je as EOpenPosePreProcessor,Xe as EPhotoMakerEnum,pe as EPreProcessor,de as EPreProcessorGroup,z as ETaskType,ue as Environment,Se as Runware,W as RunwareClient,F as RunwareServer,J as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|