@runware/sdk-js 1.1.34 → 1.1.35-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 +22 -6
- package/dist/index.d.ts +22 -6
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +12 -0
package/dist/index.d.cts
CHANGED
|
@@ -85,6 +85,7 @@ type IControlNetPreprocess = {
|
|
|
85
85
|
lowThresholdCanny?: number;
|
|
86
86
|
includeHandsAndFaceOpenPose?: boolean;
|
|
87
87
|
includeCost?: boolean;
|
|
88
|
+
outputQuality?: number;
|
|
88
89
|
customTaskUUID?: string;
|
|
89
90
|
retry?: number;
|
|
90
91
|
};
|
|
@@ -127,6 +128,7 @@ interface IRequestImage {
|
|
|
127
128
|
lora?: ILora[];
|
|
128
129
|
includeCost?: boolean;
|
|
129
130
|
customTaskUUID?: string;
|
|
131
|
+
outputQuality?: number;
|
|
130
132
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
131
133
|
retry?: number;
|
|
132
134
|
refiner?: IRefiner;
|
|
@@ -159,6 +161,7 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
159
161
|
alphaMattingBackgroundThreshold?: number;
|
|
160
162
|
alphaMattingErodeSize?: number;
|
|
161
163
|
includeCost?: boolean;
|
|
164
|
+
outputQuality?: number;
|
|
162
165
|
retry?: number;
|
|
163
166
|
}
|
|
164
167
|
interface IRemoveImage {
|
|
@@ -187,6 +190,7 @@ interface IUpscaleGan {
|
|
|
187
190
|
outputType?: IOutputType;
|
|
188
191
|
outputFormat?: IOutputFormat;
|
|
189
192
|
includeCost?: boolean;
|
|
193
|
+
outputQuality?: number;
|
|
190
194
|
customTaskUUID?: string;
|
|
191
195
|
retry?: number;
|
|
192
196
|
}
|
|
@@ -335,6 +339,7 @@ type TPhotoMaker = {
|
|
|
335
339
|
includeCost?: boolean;
|
|
336
340
|
numberResults: number;
|
|
337
341
|
seed?: number;
|
|
342
|
+
outputQuality?: number;
|
|
338
343
|
customTaskUUID?: string;
|
|
339
344
|
retry?: number;
|
|
340
345
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
@@ -464,6 +469,7 @@ type TImageMasking = {
|
|
|
464
469
|
includeCost?: boolean;
|
|
465
470
|
uploadEndpoint?: string;
|
|
466
471
|
maxDetections?: number;
|
|
472
|
+
outputQuality?: number;
|
|
467
473
|
customTaskUUID?: string;
|
|
468
474
|
retry?: number;
|
|
469
475
|
};
|
|
@@ -482,6 +488,15 @@ type TImageMaskingResponse = {
|
|
|
482
488
|
maskImageURL: string;
|
|
483
489
|
cost: number;
|
|
484
490
|
};
|
|
491
|
+
type TServerError = {
|
|
492
|
+
error: {
|
|
493
|
+
code: string;
|
|
494
|
+
message: string;
|
|
495
|
+
parameter: string;
|
|
496
|
+
type: string;
|
|
497
|
+
taskType: string;
|
|
498
|
+
};
|
|
499
|
+
};
|
|
485
500
|
|
|
486
501
|
declare class RunwareBase {
|
|
487
502
|
_ws: ReconnectingWebsocketProps | any;
|
|
@@ -492,7 +507,7 @@ declare class RunwareBase {
|
|
|
492
507
|
_globalImages: IImage[];
|
|
493
508
|
_globalError: IError | undefined;
|
|
494
509
|
_connectionSessionUUID: string | undefined;
|
|
495
|
-
|
|
510
|
+
_connectionError: TServerError | undefined;
|
|
496
511
|
_sdkType: SdkType;
|
|
497
512
|
_shouldReconnect: boolean;
|
|
498
513
|
_globalMaxRetries: number;
|
|
@@ -501,6 +516,7 @@ declare class RunwareBase {
|
|
|
501
516
|
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
|
|
502
517
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
503
518
|
protected isWebsocketReadyState: () => boolean;
|
|
519
|
+
protected isInvalidAPIKey: () => boolean;
|
|
504
520
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
505
521
|
lis: (v: any) => any;
|
|
506
522
|
groupKey?: string;
|
|
@@ -515,11 +531,11 @@ declare class RunwareBase {
|
|
|
515
531
|
private listenToImages;
|
|
516
532
|
private listenToUpload;
|
|
517
533
|
private globalListener;
|
|
518
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
519
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
534
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
535
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
520
536
|
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
521
|
-
removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
522
|
-
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
537
|
+
removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, outputQuality, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
538
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
523
539
|
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
524
540
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
525
541
|
photoMaker: (payload: TPhotoMaker) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
@@ -557,4 +573,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
557
573
|
|
|
558
574
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
559
575
|
|
|
560
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type UploadImageType };
|
|
576
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ type IControlNetPreprocess = {
|
|
|
85
85
|
lowThresholdCanny?: number;
|
|
86
86
|
includeHandsAndFaceOpenPose?: boolean;
|
|
87
87
|
includeCost?: boolean;
|
|
88
|
+
outputQuality?: number;
|
|
88
89
|
customTaskUUID?: string;
|
|
89
90
|
retry?: number;
|
|
90
91
|
};
|
|
@@ -127,6 +128,7 @@ interface IRequestImage {
|
|
|
127
128
|
lora?: ILora[];
|
|
128
129
|
includeCost?: boolean;
|
|
129
130
|
customTaskUUID?: string;
|
|
131
|
+
outputQuality?: number;
|
|
130
132
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
131
133
|
retry?: number;
|
|
132
134
|
refiner?: IRefiner;
|
|
@@ -159,6 +161,7 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
159
161
|
alphaMattingBackgroundThreshold?: number;
|
|
160
162
|
alphaMattingErodeSize?: number;
|
|
161
163
|
includeCost?: boolean;
|
|
164
|
+
outputQuality?: number;
|
|
162
165
|
retry?: number;
|
|
163
166
|
}
|
|
164
167
|
interface IRemoveImage {
|
|
@@ -187,6 +190,7 @@ interface IUpscaleGan {
|
|
|
187
190
|
outputType?: IOutputType;
|
|
188
191
|
outputFormat?: IOutputFormat;
|
|
189
192
|
includeCost?: boolean;
|
|
193
|
+
outputQuality?: number;
|
|
190
194
|
customTaskUUID?: string;
|
|
191
195
|
retry?: number;
|
|
192
196
|
}
|
|
@@ -335,6 +339,7 @@ type TPhotoMaker = {
|
|
|
335
339
|
includeCost?: boolean;
|
|
336
340
|
numberResults: number;
|
|
337
341
|
seed?: number;
|
|
342
|
+
outputQuality?: number;
|
|
338
343
|
customTaskUUID?: string;
|
|
339
344
|
retry?: number;
|
|
340
345
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
@@ -464,6 +469,7 @@ type TImageMasking = {
|
|
|
464
469
|
includeCost?: boolean;
|
|
465
470
|
uploadEndpoint?: string;
|
|
466
471
|
maxDetections?: number;
|
|
472
|
+
outputQuality?: number;
|
|
467
473
|
customTaskUUID?: string;
|
|
468
474
|
retry?: number;
|
|
469
475
|
};
|
|
@@ -482,6 +488,15 @@ type TImageMaskingResponse = {
|
|
|
482
488
|
maskImageURL: string;
|
|
483
489
|
cost: number;
|
|
484
490
|
};
|
|
491
|
+
type TServerError = {
|
|
492
|
+
error: {
|
|
493
|
+
code: string;
|
|
494
|
+
message: string;
|
|
495
|
+
parameter: string;
|
|
496
|
+
type: string;
|
|
497
|
+
taskType: string;
|
|
498
|
+
};
|
|
499
|
+
};
|
|
485
500
|
|
|
486
501
|
declare class RunwareBase {
|
|
487
502
|
_ws: ReconnectingWebsocketProps | any;
|
|
@@ -492,7 +507,7 @@ declare class RunwareBase {
|
|
|
492
507
|
_globalImages: IImage[];
|
|
493
508
|
_globalError: IError | undefined;
|
|
494
509
|
_connectionSessionUUID: string | undefined;
|
|
495
|
-
|
|
510
|
+
_connectionError: TServerError | undefined;
|
|
496
511
|
_sdkType: SdkType;
|
|
497
512
|
_shouldReconnect: boolean;
|
|
498
513
|
_globalMaxRetries: number;
|
|
@@ -501,6 +516,7 @@ declare class RunwareBase {
|
|
|
501
516
|
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, }: RunwareBaseType);
|
|
502
517
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
503
518
|
protected isWebsocketReadyState: () => boolean;
|
|
519
|
+
protected isInvalidAPIKey: () => boolean;
|
|
504
520
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
505
521
|
lis: (v: any) => any;
|
|
506
522
|
groupKey?: string;
|
|
@@ -515,11 +531,11 @@ declare class RunwareBase {
|
|
|
515
531
|
private listenToImages;
|
|
516
532
|
private listenToUpload;
|
|
517
533
|
private globalListener;
|
|
518
|
-
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
519
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
534
|
+
requestImages({ outputType, outputFormat, uploadEndpoint, checkNSFW, positivePrompt, negativePrompt, seedImage, maskImage, strength, height, width, model, steps, scheduler, seed, CFGScale, clipSkip, usePromptWeighting, promptWeighting, numberResults, controlNet, lora, onPartialImages, includeCost, customTaskUUID, retry, refiner, maskMargin, outputQuality, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
535
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
520
536
|
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
521
|
-
removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
522
|
-
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
537
|
+
removeImageBackground: ({ inputImage, outputType, outputFormat, rgba, postProcessMask, returnOnlyMask, alphaMatting, alphaMattingForegroundThreshold, alphaMattingBackgroundThreshold, alphaMattingErodeSize, outputQuality, includeCost, customTaskUUID, retry, }: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
538
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, }: IUpscaleGan) => Promise<IImage>;
|
|
523
539
|
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
524
540
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
525
541
|
photoMaker: (payload: TPhotoMaker) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
@@ -557,4 +573,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
557
573
|
|
|
558
574
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
559
575
|
|
|
560
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type UploadImageType };
|
|
576
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseCallBackType, type IAddModelResponse, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestImage, type IRequestImageToText, type ITextToImage, type IUpscaleGan, type ListenerType, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type UploadImageType };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var xe=Object.create;var Y=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var Ce=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Me=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Se(t))!Ae.call(c,a)&&a!==e&&Y(c,a,{get:()=>t[a],enumerable:!(n=ve(t,a))||n.enumerable});return c};var Ne=(c,t,e)=>(e=c!=null?xe(we(c)):{},Me(t||!c||!c.__esModule?Y(e,"default",{value:c,enumerable:!0}):e,c));var de=Ce((Ft,ge)=>{"use strict";var ce=c=>c&&c.CLOSING===2,He=()=>typeof WebSocket<"u"&&ce(WebSocket),Ve=()=>({constructor:He()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),je=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},le=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Je=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},Qe=["onopen","onclose","onmessage","onerror"],ze=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&Qe.forEach(n=>{c[n]=t[n]})},ue=function(c,t,e={}){let n,a,o=0,i=0,l=!0,r={};if(!(this instanceof ue))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=Ve();if(Object.keys(u).filter(p=>e.hasOwnProperty(p)).forEach(p=>u[p]=e[p]),!ce(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...p)=>console.log("RWS:",...p):()=>{},d=(p,y)=>setTimeout(()=>{let b=new Error(y);b.code=p,Array.isArray(r.error)&&r.error.forEach(([U])=>U(b)),n.onerror&&n.onerror(b)},0),s=()=>{if(g("close"),i++,g("retries count:",i),i>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=Je(u,o):o=le(u),g("reconnectDelay:",o),l&&setTimeout(m,o)},m=()=>{g("connect");let p=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&je(n,this,y);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=le(u),g("reconnectDelay:",o),i=0}),n.addEventListener("close",s),ze(n,p,r)};g("init"),m(),this.close=(p=1e3,y="",{keepClosed:b=!1,fastClose:U=!0,delay:v=0}={})=>{if(v&&(o=v),l=!b,n.close(p,y),U){let D={code:p,reason:y,wasClean:!0};s(),Array.isArray(r.close)&&r.close.forEach(([T,I])=>{T(D),n.removeEventListener("close",T,I)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,y,b)=>{Array.isArray(r[p])?r[p].some(([U])=>U===y)||r[p].push([y,b]):r[p]=[[y,b]],n.addEventListener(p,y,b)},this.removeEventListener=(p,y,b)=>{Array.isArray(r[p])&&(r[p]=r[p].filter(([U])=>U!==y)),n.removeEventListener(p,y,b)}};ge.exports=ue});var Z=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Z||{}),G=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(G||{}),B=(s=>(s.IMAGE_INFERENCE="imageInference",s.IMAGE_UPLOAD="imageUpload",s.IMAGE_UPSCALE="imageUpscale",s.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",s.IMAGE_CAPTION="imageCaption",s.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",s.PROMPT_ENHANCE="promptEnhance",s.AUTHENTICATION="authentication",s.MODEL_UPLOAD="modelUpload",s.PHOTO_MAKER="photoMaker",s.MODEL_SEARCH="modelSearch",s.IMAGE_MASKING="imageMasking",s))(B||{}),$=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))($||{}),X=(s=>(s.canny="canny",s.depth="depth",s.mlsd="mlsd",s.normalbae="normalbae",s.openpose="openpose",s.tile="tile",s.seg="seg",s.lineart="lineart",s.lineart_anime="lineart_anime",s.shuffle="shuffle",s.scribble="scribble",s.softedge="softedge",s))(X||{}),ee=(f=>(f.canny="canny",f.depth_leres="depth_leres",f.depth_midas="depth_midas",f.depth_zoe="depth_zoe",f.inpaint_global_harmonious="inpaint_global_harmonious",f.lineart_anime="lineart_anime",f.lineart_coarse="lineart_coarse",f.lineart_realistic="lineart_realistic",f.lineart_standard="lineart_standard",f.mlsd="mlsd",f.normal_bae="normal_bae",f.scribble_hed="scribble_hed",f.scribble_pidinet="scribble_pidinet",f.seg_ofade20k="seg_ofade20k",f.seg_ofcoco="seg_ofcoco",f.seg_ufade20k="seg_ufade20k",f.shuffle="shuffle",f.softedge_hed="softedge_hed",f.softedge_hedsafe="softedge_hedsafe",f.softedge_pidinet="softedge_pidinet",f.softedge_pidisafe="softedge_pidisafe",f.tile_gaussian="tile_gaussian",f.openpose="openpose",f.openpose_face="openpose_face",f.openpose_faceonly="openpose_faceonly",f.openpose_full="openpose_full",f.openpose_hand="openpose_hand",f))(ee||{}),Oe=(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))(Oe||{}),Le=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Le||{}),Ee=(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))(Ee||{}),Ke=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ke||{}),We=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))(We||{}),Pe=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(Pe||{});import{v4 as Fe,validate as Ge}from"uuid";var q=6e4,te=1e3,Be=100,H={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ne=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},x=(c,{debugKey:t="debugKey",timeoutDuration:e=q,shouldThrowError:n=!0})=>(e=e<te?te:e,new Promise((a,o)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(i)},e),l=setInterval(async()=>{c({resolve:a,reject:o,intervalId:l})&&(clearInterval(l),clearTimeout(i))},Be)})),se=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),_=()=>Fe(),re=c=>Ge(c);var ae=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,l)=>{let r=e?0:void 0,u=i?.[l];if(!u)return r;if(Array.isArray(u)&&/^\d+$/.test(l)){let g=parseInt(l,10);return g>=0&&g<u.length?i[l]=u[g]:i[l]??r}else return i[l]??r},t||{})??{},oe=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var ie=(c,t)=>c.filter(e=>e.key!==t.key);var h=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{},qe=(c,t)=>Math.floor(Math.random()*(t-c+1))+c,V=()=>qe(1,Number.MAX_SAFE_INTEGER);var k=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await oe(e),await k(c,{...t,maxRetries:a});else throw o}};var w=class{constructor({apiKey:t,url:e=H.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=q}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await k(async()=>{let e=_();if(typeof t=="string"&&re(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await se(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:i,highThresholdCanny:l,lowThresholdCanny:r,includeHandsAndFaceOpenPose:u,includeCost:g,customTaskUUID:d,retry:s})=>{let m=s||this._globalMaxRetries,p;try{return await k(async()=>{await this.ensureConnection();let y=await this.uploadImage(t);if(!y?.imageUUID)return null;let b=d||_();this.send({inputImage:y.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:i}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:l}),...h({key:"lowThresholdCanny",value:r}),...h({key:"includeHandsAndFaceOpenPose",value:u})}),p=this.globalListener({taskUUID:b});let U=await x(({resolve:v,reject:D})=>{let T=this.getSingleMessage({taskUUID:b});if(T){if(T?.error)return D(T),!0;if(T)return v(T),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return p.destroy(),U},{maxRetries:m,callback:()=>{p?.destroy()}})}catch(y){throw y}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,i;try{return await k(async()=>{await this.ensureConnection();let l=t?await this.uploadImage(t):null,r=n||_();this.send({taskUUID:r,taskType:"imageCaption",inputImage:l?.imageUUID,...h({key:"includeCost",value:e})}),i=this.globalListener({taskUUID:r});let u=await x(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:o,callback:()=>{i?.destroy()}})}catch(l){throw l}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:i,alphaMatting:l,alphaMattingForegroundThreshold:r,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,includeCost:d,customTaskUUID:s,retry:m})=>{let p=m||this._globalMaxRetries,y;try{return await k(async()=>{await this.ensureConnection();let b=t?await this.uploadImage(t):null,U=s||_();this.send({taskType:"imageBackgroundRemoval",taskUUID:U,inputImage:b?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:i}),...h({key:"alphaMatting",value:l}),...h({key:"includeCost",value:d}),...h({key:"alphaMattingForegroundThreshold",value:r}),...h({key:"alphaMattingBackgroundThreshold",value:u}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n})}),y=this.globalListener({taskUUID:U});let v=await x(({resolve:D,reject:T})=>{let I=this.getSingleMessage({taskUUID:U});if(I){if(I?.error)return T(I),!0;if(I)return delete this._globalMessages[U],D(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return y.destroy(),v},{maxRetries:p,callback:()=>{y?.destroy()}})}catch(b){throw b}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,customTaskUUID:i,retry:l})=>{let r=l||this._globalMaxRetries,u;try{return await k(async()=>{await this.ensureConnection();let g;g=await this.uploadImage(t);let d=i||_();this.send({taskUUID:d,inputImage:g?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...a?{outputFormat:a}:{}}),u=this.globalListener({taskUUID:d});let s=await x(({resolve:m,reject:p})=>{let y=this.getSingleMessage({taskUUID:d});if(y){if(y?.error)return p(y),!0;if(y)return delete this._globalMessages[d],m(y),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return u.destroy(),s},{maxRetries:r,callback:()=>{u?.destroy()}})}catch(g){throw g}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:i})=>{let l=i||this._globalMaxRetries,r;try{return await k(async()=>{await this.ensureConnection();let u=o||_();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),r=this.globalListener({taskUUID:u});let g=await x(({resolve:d,reject:s})=>{let m=this._globalMessages[u];if(m?.error)return s(m),!0;if(m?.length>=n)return delete this._globalMessages[u],d(m),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return r.destroy(),g},{maxRetries:l,callback:()=>{r?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r,taskType:"modelUpload"});let u,g;return l=this.listenToUpload({taskUUID:r,onUploadStream:(s,m)=>{e?.(s,m),s?.status==="ready"?u=s:m&&(g=m)}}),await x(({resolve:s,reject:m})=>{if(u)return s(u),!0;if(g)return m(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(r){throw r}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...i}=t,l=n||this._globalMaxRetries,r,u=[],g=0;try{return await k(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(y=>u.includes(y.taskUUID)),s=a||_();u.push(s);let m=o-d.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:V()},numberResults:m,taskUUID:s,taskType:"photoMaker"}),r=this.listenToImages({onPartialImages:e,taskUUID:s,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let p=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:r});return r.destroy(),p},{maxRetries:l,callback:()=>{r?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=l)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await k(async()=>{await this.ensureConnection();let r=a||_();this.send({...o,taskUUID:r}),l=this.globalListener({taskUUID:r});let u=await x(({resolve:g,reject:d})=>{let s=this.getSingleMessage({taskUUID:r});if(s){if(s?.error)return d(s),!0;if(s)return delete this._globalMessages[r],g(s),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(r){throw r}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=a,this._timeoutDuration=o}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let a=l=>{let r=Array.isArray(l?.data)?l.data:[l.data],u=l?.[0]?.errors?l?.[0]?.errors:Array.isArray(l?.errors)?l.errors:[l.errors],g=r.filter(s=>(s?.taskUUID||s?.taskType)===n);if(u.filter(s=>(s?.taskUUID||s?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:r});return}},o={key:n||_(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=ie(this._listeners,o)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=void 0}})},this._ws.onmessage=t=>{let e=JSON.parse(t.data);for(let n of this._listeners)if(n?.listener?.(e))return},this._ws.onclose=t=>{this._invalidAPIkey}}destroy(t){ne(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:i=>{let l=i?.[e]?.filter(r=>r.taskUUID===e);i.error?(t?.(l,i?.error&&i),this._globalError=i):(l=l.map(r=>({...r,positivePrompt:a,negativePrompt:o})),t?.(l,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(r=>({...r,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...l])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],i=o?.taskUUID===e?o:null;(i||a)&&t?.(i||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=ae({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:i,seedImage:l,maskImage:r,strength:u,height:g,width:d,model:s,steps:m,scheduler:p,seed:y,CFGScale:b,clipSkip:U,usePromptWeighting:v,promptWeighting:D,numberResults:T=1,controlNet:I,lora:j,onPartialImages:ye,includeCost:Ie,customTaskUUID:he,retry:fe,refiner:f,maskMargin:be},Ue){let A,J,M=[],Q=0,z=fe||this._globalMaxRetries;try{await this.ensureConnection();let S=null,E=null,K=[];if(l){let R=await this.uploadImage(l);if(!R)return[];S=R.imageUUID}if(r){let R=await this.uploadImage(r);if(!R)return[];E=R.imageUUID}if(I?.length)for(let R=0;R<I.length;R++){let C=I[R],{endStep:W,startStep:P,weight:F,guideImage:N,controlMode:Te,startStepPercentage:_e,endStepPercentage:ke,model:Re}=C,De=N?await this.uploadImage(N):null;K.push({guideImage:De?.imageUUID,model:Re,endStep:W,startStep:P,weight:F,...h({key:"startStepPercentage",value:_e}),...h({key:"endStepPercentage",value:ke}),controlMode:Te||"controlnet"})}return J={taskType:"imageInference",model:s,positivePrompt:o,...i?{negativePrompt:i}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:T,...j?.length?{lora:j}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:u}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:U}),...h({key:"maskMargin",value:be}),...h({key:"usePromptWeighting",value:v}),...h({key:"steps",value:m}),...D?{promptWeighting:D}:{},...K.length?{controlNet:K}:{},...y?{seed:y}:{seed:V()},...p?{scheduler:p}:{},...f?{refiner:f}:{},...h({key:"includeCost",value:Ie}),...S?{seedImage:S}:{},...E?{maskImage:E}:{},...Ue??{}},await k(async()=>{Q++,A?.destroy();let R=this._globalImages.filter(N=>M.includes(N.taskUUID)),C=he||_();M.push(C);let W=T-R.length,P={...J,taskUUID:C,numberResults:W};this.send(P),A=this.listenToImages({onPartialImages:ye,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:i});let F=await this.getSimilarImages({taskUUID:M,numberResults:T,lis:A});return A.destroy(),F},{maxRetries:z,callback:()=>{A?.destroy()}})}catch(S){if(Q>=z)return this.handleIncompleteImages({taskUUIDs:M,error:S});throw S}}async ensureConnection(){if(this.connected()||this._url===H.TEST)return;let e=2e3,n=200;try{if(this._invalidAPIkey)throw this._invalidAPIkey;return new Promise((a,o)=>{let i=0,l=30,r=_(),u,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let s=this.connected(),m=!1;(!this.ensureConnectionUUID||r===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=r),m=!0);let p=i%10===0&&m;s?(d(),a(!0)):i>=l?(d(),o(new Error("Retry timed out"))):(p&&this.connect(),i++)}catch(s){d(),o(s)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this._invalidAPIkey){d(),o(this._invalidAPIkey);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._invalidAPIkey??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await x(({resolve:o,reject:i,intervalId:l})=>{let r=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>r.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(l),i?.(g),!0}else if(u.length>=e)return clearInterval(l),this._globalImages=this._globalImages.filter(g=>!r.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var pe=Ne(de(),1),O=class extends w{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new pe.default(this._url),this.connect()}};import Ye from"ws";var L=class extends w{constructor(e){super(e);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=e=>{this._ws.send(JSON.stringify([e]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(e=>{e?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new Ye(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._invalidAPIkey=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._invalidAPIkey=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(i=>{i.listener(o)})}))}handleClose(){this._invalidAPIkey||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var me;typeof window>"u"?me=L:me=O;export{$ as EControlMode,Ee as EModelArchitecture,We as EModelConditioning,Le as EModelFormat,Ke as EModelType,Oe as EOpenPosePreProcessor,Pe as EPhotoMakerEnum,ee as EPreProcessor,X as EPreProcessorGroup,B as ETaskType,Z as Environment,me as Runware,O as RunwareClient,L as RunwareServer,G as SdkType};
|
|
1
|
+
var ve=Object.create;var Z=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var Me=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var Ee=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of we(t))!Ce.call(c,a)&&a!==e&&Z(c,a,{get:()=>t[a],enumerable:!(n=Se(t,a))||n.enumerable});return c};var Ne=(c,t,e)=>(e=c!=null?ve(Ae(c)):{},Ee(t||!c||!c.__esModule?Z(e,"default",{value:c,enumerable:!0}):e,c));var pe=Me((Bt,de)=>{"use strict";var ue=c=>c&&c.CLOSING===2,Ve=()=>typeof WebSocket<"u"&&ue(WebSocket),je=()=>({constructor:Ve()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Qe=(c,t,e)=>{Object.defineProperty(t,e,{get:()=>c[e],set:n=>{c[e]=n},enumerable:!0,configurable:!0})},ce=c=>c.minReconnectionDelay+Math.random()*c.minReconnectionDelay,Je=(c,t)=>{let e=t*c.reconnectionDelayGrowFactor;return e>c.maxReconnectionDelay?c.maxReconnectionDelay:e},ze=["onopen","onclose","onmessage","onerror"],Ye=(c,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{c.addEventListener(n,a,o)})}),t&&ze.forEach(n=>{c[n]=t[n]})},ge=function(c,t,e={}){let n,a,o=0,i=0,l=!0,s={};if(!(this instanceof ge))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=je();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!ue(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},d=(m,f)=>setTimeout(()=>{let b=new Error(f);b.code=m,Array.isArray(s.error)&&s.error.forEach(([T])=>T(b)),n.onerror&&n.onerror(b)},0),r=()=>{if(g("close"),i++,g("retries count:",i),i>u.maxRetries){d("EHOSTDOWN","Too many failed connection attempts");return}o?o=Je(u,o):o=ce(u),g("reconnectDelay:",o),l&&setTimeout(p,o)},p=()=>{g("connect");let m=n;n=new u.constructor(c,t),a=setTimeout(()=>{g("timeout"),n.close(),d("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let f in n)["addEventListener","removeEventListener","close","send"].indexOf(f)<0&&Qe(n,this,f);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=ce(u),g("reconnectDelay:",o),i=0}),n.addEventListener("close",r),Ye(n,m,s)};g("init"),p(),this.close=(m=1e3,f="",{keepClosed:b=!1,fastClose:T=!0,delay:k=0}={})=>{if(k&&(o=k),l=!b,n.close(m,f),T){let x={code:m,reason:f,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([D,y])=>{D(x),n.removeEventListener("close",D,y)}),n.onclose&&(n.onclose(x),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,f,b)=>{Array.isArray(s[m])?s[m].some(([T])=>T===f)||s[m].push([f,b]):s[m]=[[f,b]],n.addEventListener(m,f,b)},this.removeEventListener=(m,f,b)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([T])=>T!==f)),n.removeEventListener(m,f,b)}};de.exports=ge});var $=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))($||{}),B=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(B||{}),q=(r=>(r.IMAGE_INFERENCE="imageInference",r.IMAGE_UPLOAD="imageUpload",r.IMAGE_UPSCALE="imageUpscale",r.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.PHOTO_MAKER="photoMaker",r.MODEL_SEARCH="modelSearch",r.IMAGE_MASKING="imageMasking",r))(q||{}),X=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(X||{}),ee=(r=>(r.canny="canny",r.depth="depth",r.mlsd="mlsd",r.normalbae="normalbae",r.openpose="openpose",r.tile="tile",r.seg="seg",r.lineart="lineart",r.lineart_anime="lineart_anime",r.shuffle="shuffle",r.scribble="scribble",r.softedge="softedge",r))(ee||{}),te=(I=>(I.canny="canny",I.depth_leres="depth_leres",I.depth_midas="depth_midas",I.depth_zoe="depth_zoe",I.inpaint_global_harmonious="inpaint_global_harmonious",I.lineart_anime="lineart_anime",I.lineart_coarse="lineart_coarse",I.lineart_realistic="lineart_realistic",I.lineart_standard="lineart_standard",I.mlsd="mlsd",I.normal_bae="normal_bae",I.scribble_hed="scribble_hed",I.scribble_pidinet="scribble_pidinet",I.seg_ofade20k="seg_ofade20k",I.seg_ofcoco="seg_ofcoco",I.seg_ufade20k="seg_ufade20k",I.shuffle="shuffle",I.softedge_hed="softedge_hed",I.softedge_hedsafe="softedge_hedsafe",I.softedge_pidinet="softedge_pidinet",I.softedge_pidisafe="softedge_pidisafe",I.tile_gaussian="tile_gaussian",I.openpose="openpose",I.openpose_face="openpose_face",I.openpose_faceonly="openpose_faceonly",I.openpose_full="openpose_full",I.openpose_hand="openpose_hand",I))(te||{}),Oe=(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))(Oe||{}),Le=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Le||{}),Ke=(p=>(p.flux1d="flux1d",p.flux1s="flux1s",p.pony="pony",p.sdhyper="sdhyper",p.sd1x="sd1x",p.sd1xlcm="sd1xlcm",p.sd3="sd3",p.sdxl="sdxl",p.sdxllcm="sdxllcm",p.sdxldistilled="sdxldistilled",p.sdxlhyper="sdxlhyper",p.sdxllightning="sdxllightning",p.sdxlturbo="sdxlturbo",p))(Ke||{}),We=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(We||{}),Fe=(y=>(y.canny="canny",y.depth="depth",y.qrcode="qrcode",y.hed="hed",y.scrible="scrible",y.openpose="openpose",y.seg="segmentation",y.openmlsd="openmlsd",y.softedge="softedge",y.normal="normal bae",y.shuffle="shuffle",y.pix2pix="pix2pix",y.inpaint="inpaint",y.lineart="line art",y.sketch="sketch",y.inpaintdepth="inpaint depth",y.tile="tile",y.outfit="outfit",y.blur="blur",y.gray="gray",y.lowquality="low quality",y))(Fe||{}),Pe=(d=>(d.NoStyle="No style",d.Cinematic="Cinematic",d.DisneyCharacter="Disney Character",d.DigitalArt="Digital Art",d.Photographic="Photographic",d.FantasyArt="Fantasy art",d.Neonpunk="Neonpunk",d.Enhance="Enhance",d.ComicBook="Comic book",d.Lowpoly="Lowpoly",d.LineArt="Line art",d))(Pe||{});import{v4 as Ge,validate as Be}from"uuid";var H=6e4,ne=1e3,qe=100,V={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},re=(c,t)=>{if(c==null)return;let e=c.indexOf(t);e!==-1&&c.splice(e,1)},v=(c,{debugKey:t="debugKey",timeoutDuration:e=H,shouldThrowError:n=!0})=>(e=e<ne?ne:e,new Promise((a,o)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(i)},e),l=setInterval(async()=>{c({resolve:a,reject:o,intervalId:l})&&(clearInterval(l),clearTimeout(i))},qe)})),se=c=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(c),e.onload=function(){t(e.result)}}),U=()=>Ge(),ae=c=>Be(c);var oe=({key:c,data:t,useZero:e=!0,shouldReturnString:n=!1})=>c.split(/\.|\[/).map(i=>i.replace(/\]$/,"")).reduce((i,l)=>{let s=e?0:void 0,u=i?.[l];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(l)){let g=parseInt(l,10);return g>=0&&g<u.length?i[l]=u[g]:i[l]??s}else return i[l]??s},t||{})??{},ie=(c,t=1e3)=>new Promise(e=>setTimeout(e,c*t));var le=(c,t)=>c.filter(e=>e.key!==t.key);var h=({key:c,value:t})=>t||t===0||t===!1?{[c]:t}:{},He=(c,t)=>Math.floor(Math.random()*(t-c+1))+c,j=()=>He(1,Number.MAX_SAFE_INTEGER);var _=async(c,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await c()}catch(o){if(n?.(),a--,a>0)await ie(e),await _(c,{...t,maxRetries:a});else throw o}};var A=class{constructor({apiKey:t,url:e=V.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:a=2,timeoutDuration:o=H}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=t=>{this._ws.send(JSON.stringify([t]))};this.uploadImage=async t=>{try{return await _(async()=>{let e=U();if(typeof t=="string"&&ae(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await se(t);return{imageURL:n,imageUUID:n,taskUUID:e,taskType:"imageUpload"}})}catch(e){throw e}};this.controlNetPreProcess=async({inputImage:t,preProcessorType:e,height:n,width:a,outputType:o,outputFormat:i,highThresholdCanny:l,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:d,customTaskUUID:r,retry:p})=>{let m=p||this._globalMaxRetries,f;try{return await _(async()=>{await this.ensureConnection();let b=await this.uploadImage(t);if(!b?.imageUUID)return null;let T=r||U();this.send({inputImage:b.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:T,preProcessorType:e,...h({key:"height",value:n}),...h({key:"width",value:a}),...h({key:"outputType",value:o}),...h({key:"outputFormat",value:i}),...h({key:"includeCost",value:g}),...h({key:"highThresholdCanny",value:l}),...h({key:"lowThresholdCanny",value:s}),...h({key:"includeHandsAndFaceOpenPose",value:u}),...d?{outputQuality:d}:{}}),f=this.globalListener({taskUUID:T});let k=await v(({resolve:x,reject:D})=>{let y=this.getSingleMessage({taskUUID:T});if(y){if(y?.error)return D(y),!0;if(y)return x(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),k},{maxRetries:m,callback:()=>{f?.destroy()}})}catch(b){throw b}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,i;try{return await _(async()=>{await this.ensureConnection();let l=t?await this.uploadImage(t):null,s=n||U();this.send({taskUUID:s,taskType:"imageCaption",inputImage:l?.imageUUID,...h({key:"includeCost",value:e})}),i=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:o,callback:()=>{i?.destroy()}})}catch(l){throw l}};this.removeImageBackground=async({inputImage:t,outputType:e,outputFormat:n,rgba:a,postProcessMask:o,returnOnlyMask:i,alphaMatting:l,alphaMattingForegroundThreshold:s,alphaMattingBackgroundThreshold:u,alphaMattingErodeSize:g,outputQuality:d,includeCost:r,customTaskUUID:p,retry:m})=>{let f=m||this._globalMaxRetries,b;try{return await _(async()=>{await this.ensureConnection();let T=t?await this.uploadImage(t):null,k=p||U();this.send({taskType:"imageBackgroundRemoval",taskUUID:k,inputImage:T?.imageUUID,...h({key:"rgba",value:a}),...h({key:"postProcessMask",value:o}),...h({key:"returnOnlyMask",value:i}),...h({key:"alphaMatting",value:l}),...h({key:"includeCost",value:r}),...h({key:"alphaMattingForegroundThreshold",value:s}),...h({key:"alphaMattingBackgroundThreshold",value:u}),...h({key:"alphaMattingErodeSize",value:g}),...h({key:"outputType",value:e}),...h({key:"outputFormat",value:n}),...d?{outputQuality:d}:{}}),b=this.globalListener({taskUUID:k});let x=await v(({resolve:D,reject:y})=>{let S=this.getSingleMessage({taskUUID:k});if(S){if(S?.error)return y(S),!0;if(S)return delete this._globalMessages[k],D(S),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return b.destroy(),x},{maxRetries:f,callback:()=>{b?.destroy()}})}catch(T){throw T}};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:i,customTaskUUID:l,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await _(async()=>{await this.ensureConnection();let d;d=await this.uploadImage(t);let r=l||U();this.send({taskUUID:r,inputImage:d?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...h({key:"includeCost",value:o}),...n?{outputType:n}:{},...i?{outputQuality:i}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let p=await v(({resolve:m,reject:f})=>{let b=this.getSingleMessage({taskUUID:r});if(b){if(b?.error)return f(b),!0;if(b)return delete this._globalMessages[r],m(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),p},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(d){throw d}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:i})=>{let l=i||this._globalMaxRetries,s;try{return await _(async()=>{await this.ensureConnection();let u=o||U();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...h({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await v(({resolve:d,reject:r})=>{let p=this._globalMessages[u];if(p?.error)return r(p),!0;if(p?.length>=n)return delete this._globalMessages[u],d(p),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:l,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return l=this.listenToUpload({taskUUID:s,onUploadStream:(r,p)=>{e?.(r,p),r?.status==="ready"?u=r:p&&(g=p)}}),await v(({resolve:r,reject:p})=>{if(u)return r(u),!0;if(g)return p(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(s){throw s}};this.photoMaker=async t=>{let{onPartialImages:e,retry:n,customTaskUUID:a,numberResults:o,...i}=t,l=n||this._globalMaxRetries,s,u=[],g=0;try{return await _(async()=>{await this.ensureConnection(),g++;let d=this._globalImages.filter(f=>u.includes(f.taskUUID)),r=a||U();u.push(r);let p=o-d.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:j()},numberResults:p,taskUUID:r,taskType:"photoMaker"}),s=this.listenToImages({onPartialImages:e,taskUUID:r,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let m=await this.getSimilarImages({taskUUID:u,numberResults:o,lis:s});return s.destroy(),m},{maxRetries:l,callback:()=>{s?.destroy()}})}catch(d){if(d.taskUUID)throw d;if(g>=l)return this.handleIncompleteImages({taskUUIDs:u,error:d})}};this.modelSearch=async t=>this.baseSingleRequest({payload:{...t,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageMasking"},debugKey:"image-masking"});this.baseSingleRequest=async({payload:t,debugKey:e})=>{let{retry:n,customTaskUUID:a,...o}=t,i=n||this._globalMaxRetries,l;try{return await _(async()=>{await this.ensureConnection();let s=a||U();this.send({...o,taskUUID:s}),l=this.globalListener({taskUUID:s});let u=await v(({resolve:g,reject:d})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return d(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return l.destroy(),u},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(s){throw s}};this.getSingleMessage=({taskUUID:t})=>{let e=this._globalMessages[t]?.[0],n=this._globalMessages[t];return!e&&!n?null:n?.error?n:e};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=t,this._url=e,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=a,this._timeoutDuration=o}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let a=l=>{let s=Array.isArray(l?.data)?l.data:[l.data],u=l?.[0]?.errors?l?.[0]?.errors:Array.isArray(l?.errors)?l.errors:[l.errors],g=s.filter(r=>(r?.taskUUID||r?.taskType)===n);if(u.filter(r=>(r?.taskUUID||r?.taskType)===n).length){t({error:{...u[0]??{}}});return}if(g.length){t({[n]:s});return}},o={key:n||U(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=le(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){re(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:i=>{let l=i?.[e]?.filter(s=>s.taskUUID===e);i.error?(t?.(l,i?.error&&i),this._globalError=i):(l=l.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(l,i?.error&&i),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(i?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...l])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],i=o?.taskUUID===e?o:null;(i||a)&&t?.(i||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=oe({key:t,data:e,useZero:!1});Array.isArray(n)?n.forEach(a=>{this._globalMessages[a.taskUUID]=[...this._globalMessages[a.taskUUID]??[],a]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:t,outputFormat:e,uploadEndpoint:n,checkNSFW:a,positivePrompt:o,negativePrompt:i,seedImage:l,maskImage:s,strength:u,height:g,width:d,model:r,steps:p,scheduler:m,seed:f,CFGScale:b,clipSkip:T,usePromptWeighting:k,promptWeighting:x,numberResults:D=1,controlNet:y,lora:S,onPartialImages:he,includeCost:Ie,customTaskUUID:fe,retry:be,refiner:I,maskMargin:Te,outputQuality:Q},Ue){let C,J,E=[],z=0,Y=be||this._globalMaxRetries;try{await this.ensureConnection();let w=null,K=null,W=[];if(l){let R=await this.uploadImage(l);if(!R)return[];w=R.imageUUID}if(s){let R=await this.uploadImage(s);if(!R)return[];K=R.imageUUID}if(y?.length)for(let R=0;R<y.length;R++){let M=y[R],{endStep:F,startStep:P,weight:G,guideImage:N,controlMode:_e,startStepPercentage:ke,endStepPercentage:Re,model:De}=M,xe=N?await this.uploadImage(N):null;W.push({guideImage:xe?.imageUUID,model:De,endStep:F,startStep:P,weight:G,...h({key:"startStepPercentage",value:ke}),...h({key:"endStepPercentage",value:Re}),controlMode:_e||"controlnet"})}return J={taskType:"imageInference",model:r,positivePrompt:o,...i?{negativePrompt:i}:{},...g?{height:g}:{},...d?{width:d}:{},numberResults:D,...S?.length?{lora:S}:{},...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...h({key:"checkNSFW",value:a}),...h({key:"strength",value:u}),...h({key:"CFGScale",value:b}),...h({key:"clipSkip",value:T}),...h({key:"maskMargin",value:Te}),...h({key:"usePromptWeighting",value:k}),...h({key:"steps",value:p}),...x?{promptWeighting:x}:{},...W.length?{controlNet:W}:{},...f?{seed:f}:{seed:j()},...m?{scheduler:m}:{},...I?{refiner:I}:{},...h({key:"includeCost",value:Ie}),...w?{seedImage:w}:{},...K?{maskImage:K}:{},...Q?{outputQuality:Q}:{},...Ue??{}},await _(async()=>{z++,C?.destroy();let R=this._globalImages.filter(N=>E.includes(N.taskUUID)),M=fe||U();E.push(M);let F=D-R.length,P={...J,taskUUID:M,numberResults:F};this.send(P),C=this.listenToImages({onPartialImages:he,taskUUID:M,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:i});let G=await this.getSimilarImages({taskUUID:E,numberResults:D,lis:C});return C.destroy(),G},{maxRetries:Y,callback:()=>{C?.destroy()}})}catch(w){if(z>=Y)return this.handleIncompleteImages({taskUUIDs:E,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===V.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((a,o)=>{let i=0,l=30,s=U(),u,g,d=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),p=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),p=!0);let m=i%10===0&&p;r?(d(),a(!0)):i>=l?(d(),o(new Error("Retry timed out"))):(m&&this.connect(),i++)}catch(r){d(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){d(),a(!0);return}if(this.isInvalidAPIKey()){d(),o(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:a}){return await v(({resolve:o,reject:i,intervalId:l})=>{let s=Array.isArray(t)?t:[t],u=this._globalImages.filter(g=>s.includes(g.taskUUID));if(this._globalError){let g=this._globalError;return this._globalError=void 0,clearInterval(l),i?.(g),!0}else if(u.length>=e)return clearInterval(l),this._globalImages=this._globalImages.filter(g=>!s.includes(g.taskUUID)),o([...u].slice(0,e)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:t,error:e}){let n=this._globalImages.filter(a=>t.includes(a.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(a=>!t.includes(a.taskUUID)),n;throw e}};var me=Ne(pe(),1),O=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new me.default(this._url),this.connect()}};import Ze from"ws";var L=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 Ze(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID,triggerAuthServerError:!0}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication",triggerAuthServerError:!0}),this.addListener({taskUUID:"authentication",lis:e=>{if(console.log("mserver",e),e?.error){this._connectionError=e;return}this._connectionSessionUUID=e?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(e,n)=>{let a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(i=>{i.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 ye;typeof window>"u"?ye=L:ye=O;export{X as EControlMode,Ke as EModelArchitecture,Fe as EModelConditioning,Le as EModelFormat,We as EModelType,Oe as EOpenPosePreProcessor,Pe as EPhotoMakerEnum,te as EPreProcessor,ee as EPreProcessorGroup,q as ETaskType,$ as Environment,ye as Runware,O as RunwareClient,L as RunwareServer,B as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|