@runware/sdk-js 1.1.40 → 1.1.41-beta.2
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 +57 -15
- package/dist/index.d.ts +57 -15
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -12,6 +12,8 @@ declare enum ETaskType {
|
|
|
12
12
|
IMAGE_UPLOAD = "imageUpload",
|
|
13
13
|
IMAGE_UPSCALE = "imageUpscale",
|
|
14
14
|
IMAGE_BACKGROUND_REMOVAL = "imageBackgroundRemoval",
|
|
15
|
+
VIDEO_INFERENCE = "videoInference",
|
|
16
|
+
ASYNC_RESULTS = "asyncResults",
|
|
15
17
|
PHOTO_MAKER = "photoMaker",
|
|
16
18
|
IMAGE_CAPTION = "imageCaption",
|
|
17
19
|
IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
|
|
@@ -30,6 +32,10 @@ type RunwareBaseType = {
|
|
|
30
32
|
};
|
|
31
33
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
32
34
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
35
|
+
interface IAdditionalResponsePayload {
|
|
36
|
+
includePayload?: boolean;
|
|
37
|
+
includeGenerationTime?: boolean;
|
|
38
|
+
}
|
|
33
39
|
interface IImage {
|
|
34
40
|
taskType: ETaskType;
|
|
35
41
|
imageUUID: string;
|
|
@@ -46,6 +52,15 @@ interface ITextToImage extends IImage {
|
|
|
46
52
|
positivePrompt?: string;
|
|
47
53
|
negativePrompt?: string;
|
|
48
54
|
}
|
|
55
|
+
interface IVideoToImage {
|
|
56
|
+
taskUUID: string;
|
|
57
|
+
taskType: string;
|
|
58
|
+
status: string;
|
|
59
|
+
videoUUID?: string;
|
|
60
|
+
cost?: number;
|
|
61
|
+
seed?: number;
|
|
62
|
+
videoURL?: string;
|
|
63
|
+
}
|
|
49
64
|
interface IControlNetImage {
|
|
50
65
|
taskUUID: string;
|
|
51
66
|
inputImageUUID: string;
|
|
@@ -88,7 +103,7 @@ type IControlNetPreprocess = {
|
|
|
88
103
|
outputQuality?: number;
|
|
89
104
|
customTaskUUID?: string;
|
|
90
105
|
retry?: number;
|
|
91
|
-
};
|
|
106
|
+
} & IAdditionalResponsePayload;
|
|
92
107
|
type IControlNet = IControlNetGeneral;
|
|
93
108
|
type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
94
109
|
guideImage?: string;
|
|
@@ -99,7 +114,7 @@ interface IError {
|
|
|
99
114
|
taskUUID: string;
|
|
100
115
|
}
|
|
101
116
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
102
|
-
interface IRequestImage {
|
|
117
|
+
interface IRequestImage extends IAdditionalResponsePayload {
|
|
103
118
|
outputType?: IOutputType;
|
|
104
119
|
outputFormat?: IOutputFormat;
|
|
105
120
|
uploadEndpoint?: string;
|
|
@@ -170,7 +185,7 @@ interface IRefiner {
|
|
|
170
185
|
startStep?: number;
|
|
171
186
|
startStepPercentage?: number;
|
|
172
187
|
}
|
|
173
|
-
interface IRequestImageToText {
|
|
188
|
+
interface IRequestImageToText extends IAdditionalResponsePayload {
|
|
174
189
|
inputImage?: File | string;
|
|
175
190
|
includeCost?: boolean;
|
|
176
191
|
customTaskUUID?: string;
|
|
@@ -199,6 +214,29 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
199
214
|
outputQuality?: number;
|
|
200
215
|
retry?: number;
|
|
201
216
|
}
|
|
217
|
+
interface IRequestVideo extends IRequestImageToText {
|
|
218
|
+
outputType?: IOutputType;
|
|
219
|
+
outputFormat?: IOutputFormat;
|
|
220
|
+
outputQuality?: number;
|
|
221
|
+
uploadEndpoint?: string;
|
|
222
|
+
checkNSFW?: boolean;
|
|
223
|
+
includeCost?: boolean;
|
|
224
|
+
positivePrompt: string;
|
|
225
|
+
negativePrompt?: string;
|
|
226
|
+
model: string;
|
|
227
|
+
steps?: number;
|
|
228
|
+
CFGScale?: number;
|
|
229
|
+
seed?: number;
|
|
230
|
+
duration?: number;
|
|
231
|
+
fps?: number;
|
|
232
|
+
width?: number;
|
|
233
|
+
height?: number;
|
|
234
|
+
numberResults?: number;
|
|
235
|
+
retry?: number;
|
|
236
|
+
}
|
|
237
|
+
interface IAsyncResults {
|
|
238
|
+
taskUUID: string;
|
|
239
|
+
}
|
|
202
240
|
interface IRemoveImage {
|
|
203
241
|
taskType: ETaskType;
|
|
204
242
|
taskUUID: string;
|
|
@@ -209,7 +247,7 @@ interface IRemoveImage {
|
|
|
209
247
|
imageDataURI?: string;
|
|
210
248
|
cost?: number;
|
|
211
249
|
}
|
|
212
|
-
interface IPromptEnhancer {
|
|
250
|
+
interface IPromptEnhancer extends IAdditionalResponsePayload {
|
|
213
251
|
promptMaxLength?: number;
|
|
214
252
|
promptVersions?: number;
|
|
215
253
|
prompt: string;
|
|
@@ -219,7 +257,7 @@ interface IPromptEnhancer {
|
|
|
219
257
|
}
|
|
220
258
|
interface IEnhancedPrompt extends IImageToText {
|
|
221
259
|
}
|
|
222
|
-
interface IUpscaleGan {
|
|
260
|
+
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
223
261
|
inputImage: File | string;
|
|
224
262
|
upscaleFactor: number;
|
|
225
263
|
outputType?: IOutputType;
|
|
@@ -326,12 +364,12 @@ interface IErrorResponse {
|
|
|
326
364
|
type TAddModelBaseType = {
|
|
327
365
|
air: string;
|
|
328
366
|
name: string;
|
|
329
|
-
|
|
367
|
+
downloadURL: string;
|
|
330
368
|
uniqueIdentifier: string;
|
|
331
369
|
version: string;
|
|
332
370
|
format: EModelFormat;
|
|
333
371
|
architecture: EModelArchitecture;
|
|
334
|
-
|
|
372
|
+
heroImageURL?: string;
|
|
335
373
|
tags?: string[];
|
|
336
374
|
shortDescription?: string;
|
|
337
375
|
comment?: string;
|
|
@@ -382,7 +420,7 @@ type TPhotoMaker = {
|
|
|
382
420
|
customTaskUUID?: string;
|
|
383
421
|
retry?: number;
|
|
384
422
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
385
|
-
};
|
|
423
|
+
} & IAdditionalResponsePayload;
|
|
386
424
|
type TPhotoMakerResponse = {
|
|
387
425
|
taskType: string;
|
|
388
426
|
taskUUID: string;
|
|
@@ -581,24 +619,28 @@ declare class RunwareBase {
|
|
|
581
619
|
private listenToImages;
|
|
582
620
|
private listenToUpload;
|
|
583
621
|
private globalListener;
|
|
584
|
-
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, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
585
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
586
|
-
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
622
|
+
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>;
|
|
623
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
624
|
+
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
587
625
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
588
|
-
|
|
589
|
-
|
|
626
|
+
videoInference: (payload: IRequestVideo) => Promise<IVideoToImage>;
|
|
627
|
+
getAsyncResults: (payload: IAsyncResults) => Promise<IVideoToImage>;
|
|
628
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
|
|
629
|
+
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
590
630
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
591
631
|
photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
592
632
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
593
633
|
imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
|
|
594
634
|
imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
|
|
595
|
-
protected baseSingleRequest: <T>({ payload, debugKey, }: {
|
|
635
|
+
protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, }: {
|
|
596
636
|
payload: Record<string, any>;
|
|
597
637
|
debugKey: string;
|
|
638
|
+
mockResponse?: any;
|
|
598
639
|
}) => Promise<T>;
|
|
599
640
|
ensureConnection(): Promise<unknown>;
|
|
600
641
|
private getSimilarImages;
|
|
601
642
|
private getSingleMessage;
|
|
643
|
+
private insertAdditionalResponse;
|
|
602
644
|
private handleIncompleteImages;
|
|
603
645
|
disconnect: () => Promise<void>;
|
|
604
646
|
private connected;
|
|
@@ -624,4 +666,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
624
666
|
|
|
625
667
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
626
668
|
|
|
627
|
-
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 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 ITextToImage, type IUpscaleGan, 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 };
|
|
669
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, 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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ declare enum ETaskType {
|
|
|
12
12
|
IMAGE_UPLOAD = "imageUpload",
|
|
13
13
|
IMAGE_UPSCALE = "imageUpscale",
|
|
14
14
|
IMAGE_BACKGROUND_REMOVAL = "imageBackgroundRemoval",
|
|
15
|
+
VIDEO_INFERENCE = "videoInference",
|
|
16
|
+
ASYNC_RESULTS = "asyncResults",
|
|
15
17
|
PHOTO_MAKER = "photoMaker",
|
|
16
18
|
IMAGE_CAPTION = "imageCaption",
|
|
17
19
|
IMAGE_CONTROL_NET_PRE_PROCESS = "imageControlNetPreProcess",
|
|
@@ -30,6 +32,10 @@ type RunwareBaseType = {
|
|
|
30
32
|
};
|
|
31
33
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
32
34
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
35
|
+
interface IAdditionalResponsePayload {
|
|
36
|
+
includePayload?: boolean;
|
|
37
|
+
includeGenerationTime?: boolean;
|
|
38
|
+
}
|
|
33
39
|
interface IImage {
|
|
34
40
|
taskType: ETaskType;
|
|
35
41
|
imageUUID: string;
|
|
@@ -46,6 +52,15 @@ interface ITextToImage extends IImage {
|
|
|
46
52
|
positivePrompt?: string;
|
|
47
53
|
negativePrompt?: string;
|
|
48
54
|
}
|
|
55
|
+
interface IVideoToImage {
|
|
56
|
+
taskUUID: string;
|
|
57
|
+
taskType: string;
|
|
58
|
+
status: string;
|
|
59
|
+
videoUUID?: string;
|
|
60
|
+
cost?: number;
|
|
61
|
+
seed?: number;
|
|
62
|
+
videoURL?: string;
|
|
63
|
+
}
|
|
49
64
|
interface IControlNetImage {
|
|
50
65
|
taskUUID: string;
|
|
51
66
|
inputImageUUID: string;
|
|
@@ -88,7 +103,7 @@ type IControlNetPreprocess = {
|
|
|
88
103
|
outputQuality?: number;
|
|
89
104
|
customTaskUUID?: string;
|
|
90
105
|
retry?: number;
|
|
91
|
-
};
|
|
106
|
+
} & IAdditionalResponsePayload;
|
|
92
107
|
type IControlNet = IControlNetGeneral;
|
|
93
108
|
type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
94
109
|
guideImage?: string;
|
|
@@ -99,7 +114,7 @@ interface IError {
|
|
|
99
114
|
taskUUID: string;
|
|
100
115
|
}
|
|
101
116
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
102
|
-
interface IRequestImage {
|
|
117
|
+
interface IRequestImage extends IAdditionalResponsePayload {
|
|
103
118
|
outputType?: IOutputType;
|
|
104
119
|
outputFormat?: IOutputFormat;
|
|
105
120
|
uploadEndpoint?: string;
|
|
@@ -170,7 +185,7 @@ interface IRefiner {
|
|
|
170
185
|
startStep?: number;
|
|
171
186
|
startStepPercentage?: number;
|
|
172
187
|
}
|
|
173
|
-
interface IRequestImageToText {
|
|
188
|
+
interface IRequestImageToText extends IAdditionalResponsePayload {
|
|
174
189
|
inputImage?: File | string;
|
|
175
190
|
includeCost?: boolean;
|
|
176
191
|
customTaskUUID?: string;
|
|
@@ -199,6 +214,29 @@ interface IRemoveImageBackground extends IRequestImageToText {
|
|
|
199
214
|
outputQuality?: number;
|
|
200
215
|
retry?: number;
|
|
201
216
|
}
|
|
217
|
+
interface IRequestVideo extends IRequestImageToText {
|
|
218
|
+
outputType?: IOutputType;
|
|
219
|
+
outputFormat?: IOutputFormat;
|
|
220
|
+
outputQuality?: number;
|
|
221
|
+
uploadEndpoint?: string;
|
|
222
|
+
checkNSFW?: boolean;
|
|
223
|
+
includeCost?: boolean;
|
|
224
|
+
positivePrompt: string;
|
|
225
|
+
negativePrompt?: string;
|
|
226
|
+
model: string;
|
|
227
|
+
steps?: number;
|
|
228
|
+
CFGScale?: number;
|
|
229
|
+
seed?: number;
|
|
230
|
+
duration?: number;
|
|
231
|
+
fps?: number;
|
|
232
|
+
width?: number;
|
|
233
|
+
height?: number;
|
|
234
|
+
numberResults?: number;
|
|
235
|
+
retry?: number;
|
|
236
|
+
}
|
|
237
|
+
interface IAsyncResults {
|
|
238
|
+
taskUUID: string;
|
|
239
|
+
}
|
|
202
240
|
interface IRemoveImage {
|
|
203
241
|
taskType: ETaskType;
|
|
204
242
|
taskUUID: string;
|
|
@@ -209,7 +247,7 @@ interface IRemoveImage {
|
|
|
209
247
|
imageDataURI?: string;
|
|
210
248
|
cost?: number;
|
|
211
249
|
}
|
|
212
|
-
interface IPromptEnhancer {
|
|
250
|
+
interface IPromptEnhancer extends IAdditionalResponsePayload {
|
|
213
251
|
promptMaxLength?: number;
|
|
214
252
|
promptVersions?: number;
|
|
215
253
|
prompt: string;
|
|
@@ -219,7 +257,7 @@ interface IPromptEnhancer {
|
|
|
219
257
|
}
|
|
220
258
|
interface IEnhancedPrompt extends IImageToText {
|
|
221
259
|
}
|
|
222
|
-
interface IUpscaleGan {
|
|
260
|
+
interface IUpscaleGan extends IAdditionalResponsePayload {
|
|
223
261
|
inputImage: File | string;
|
|
224
262
|
upscaleFactor: number;
|
|
225
263
|
outputType?: IOutputType;
|
|
@@ -326,12 +364,12 @@ interface IErrorResponse {
|
|
|
326
364
|
type TAddModelBaseType = {
|
|
327
365
|
air: string;
|
|
328
366
|
name: string;
|
|
329
|
-
|
|
367
|
+
downloadURL: string;
|
|
330
368
|
uniqueIdentifier: string;
|
|
331
369
|
version: string;
|
|
332
370
|
format: EModelFormat;
|
|
333
371
|
architecture: EModelArchitecture;
|
|
334
|
-
|
|
372
|
+
heroImageURL?: string;
|
|
335
373
|
tags?: string[];
|
|
336
374
|
shortDescription?: string;
|
|
337
375
|
comment?: string;
|
|
@@ -382,7 +420,7 @@ type TPhotoMaker = {
|
|
|
382
420
|
customTaskUUID?: string;
|
|
383
421
|
retry?: number;
|
|
384
422
|
onPartialImages?: (images: IImage[], error?: IError) => void;
|
|
385
|
-
};
|
|
423
|
+
} & IAdditionalResponsePayload;
|
|
386
424
|
type TPhotoMakerResponse = {
|
|
387
425
|
taskType: string;
|
|
388
426
|
taskUUID: string;
|
|
@@ -581,24 +619,28 @@ declare class RunwareBase {
|
|
|
581
619
|
private listenToImages;
|
|
582
620
|
private listenToUpload;
|
|
583
621
|
private globalListener;
|
|
584
|
-
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, }: IRequestImage, moreOptions?: Record<string, any>): Promise<ITextToImage[] | undefined>;
|
|
585
|
-
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
586
|
-
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, }: IRequestImageToText) => Promise<IImageToText>;
|
|
622
|
+
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>;
|
|
623
|
+
controlNetPreProcess: ({ inputImage, preProcessorType, height, width, outputType, outputFormat, highThresholdCanny, lowThresholdCanny, includeHandsAndFaceOpenPose, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IControlNetPreprocess) => Promise<IControlNetImage | null>;
|
|
624
|
+
requestImageToText: ({ inputImage, includeCost, customTaskUUID, retry, includePayload, includeGenerationTime, }: IRequestImageToText) => Promise<IImageToText>;
|
|
587
625
|
removeImageBackground: (payload: IRemoveImageBackground) => Promise<IRemoveImage>;
|
|
588
|
-
|
|
589
|
-
|
|
626
|
+
videoInference: (payload: IRequestVideo) => Promise<IVideoToImage>;
|
|
627
|
+
getAsyncResults: (payload: IAsyncResults) => Promise<IVideoToImage>;
|
|
628
|
+
upscaleGan: ({ inputImage, upscaleFactor, outputType, outputFormat, includeCost, outputQuality, customTaskUUID, retry, includeGenerationTime, includePayload, }: IUpscaleGan) => Promise<IImage>;
|
|
629
|
+
enhancePrompt: ({ prompt, promptMaxLength, promptVersions, includeCost, customTaskUUID, retry, includeGenerationTime, includePayload, }: IPromptEnhancer) => Promise<IEnhancedPrompt[]>;
|
|
590
630
|
modelUpload: (payload: TAddModel) => Promise<any>;
|
|
591
631
|
photoMaker: (payload: TPhotoMaker, moreOptions?: Record<string, any>) => Promise<TPhotoMakerResponse[] | undefined>;
|
|
592
632
|
modelSearch: (payload: TModelSearch) => Promise<TModelSearchResponse>;
|
|
593
633
|
imageMasking: (payload: TImageMasking) => Promise<TImageMaskingResponse>;
|
|
594
634
|
imageUpload: (payload: TImageUpload) => Promise<TImageUploadResponse>;
|
|
595
|
-
protected baseSingleRequest: <T>({ payload, debugKey, }: {
|
|
635
|
+
protected baseSingleRequest: <T>({ payload, debugKey, mockResponse, }: {
|
|
596
636
|
payload: Record<string, any>;
|
|
597
637
|
debugKey: string;
|
|
638
|
+
mockResponse?: any;
|
|
598
639
|
}) => Promise<T>;
|
|
599
640
|
ensureConnection(): Promise<unknown>;
|
|
600
641
|
private getSimilarImages;
|
|
601
642
|
private getSingleMessage;
|
|
643
|
+
private insertAdditionalResponse;
|
|
602
644
|
private handleIncompleteImages;
|
|
603
645
|
disconnect: () => Promise<void>;
|
|
604
646
|
private connected;
|
|
@@ -624,4 +666,4 @@ declare class RunwareServer extends RunwareBase {
|
|
|
624
666
|
|
|
625
667
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
626
668
|
|
|
627
|
-
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 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 ITextToImage, type IUpscaleGan, 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 };
|
|
669
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, 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 };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Oe=Object.create;var se=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var We=(l,t)=>()=>(t||l((t={exports:{}}).exports,t),t.exports);var Fe=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Me(t))!Ke.call(l,a)&&a!==e&&se(l,a,{get:()=>t[a],enumerable:!(n=Ne(t,a))||n.enumerable});return l};var Pe=(l,t,e)=>(e=l!=null?Oe(Le(l)):{},Fe(t||!l||!l.__esModule?se(e,"default",{value:l,enumerable:!0}):e,l));var Ue=We((zt,fe)=>{"use strict";var he=l=>l&&l.CLOSING===2,Ze=()=>typeof WebSocket<"u"&&he(WebSocket),$e=()=>({constructor:Ze()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),Xe=(l,t,e)=>{Object.defineProperty(t,e,{get:()=>l[e],set:n=>{l[e]=n},enumerable:!0,configurable:!0})},Ie=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,et=(l,t)=>{let e=t*l.reconnectionDelayGrowFactor;return e>l.maxReconnectionDelay?l.maxReconnectionDelay:e},tt=["onopen","onclose","onmessage","onerror"],nt=(l,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([a,o])=>{l.addEventListener(n,a,o)})}),t&&tt.forEach(n=>{l[n]=t[n]})},be=function(l,t,e={}){let n,a,o=0,c=0,i=!0,s={};if(!(this instanceof be))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let u=$e();if(Object.keys(u).filter(m=>e.hasOwnProperty(m)).forEach(m=>u[m]=e[m]),!he(u.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let g=u.debug?(...m)=>console.log("RWS:",...m):()=>{},p=(m,h)=>setTimeout(()=>{let b=new Error(h);b.code=m,Array.isArray(s.error)&&s.error.forEach(([U])=>U(b)),n.onerror&&n.onerror(b)},0),r=()=>{if(g("close"),c++,g("retries count:",c),c>u.maxRetries){p("EHOSTDOWN","Too many failed connection attempts");return}o?o=et(u,o):o=Ie(u),g("reconnectDelay:",o),i&&setTimeout(d,o)},d=()=>{g("connect");let m=n;n=new u.constructor(l,t),a=setTimeout(()=>{g("timeout"),n.close(),p("ETIMEDOUT","Connection timeout")},u.connectionTimeout),g("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&Xe(n,this,h);n.addEventListener("open",()=>{clearTimeout(a),g("open"),o=Ie(u),g("reconnectDelay:",o),c=0}),n.addEventListener("close",r),nt(n,m,s)};g("init"),d(),this.close=(m=1e3,h="",{keepClosed:b=!1,fastClose:U=!0,delay:S=0}={})=>{if(S&&(o=S),i=!b,n.close(m,h),U){let D={code:m,reason:h,wasClean:!0};r(),Array.isArray(s.close)&&s.close.forEach(([k,y])=>{k(D),n.removeEventListener("close",k,y)}),n.onclose&&(n.onclose(D),n.onclose=null)}},this.send=m=>{n.send(m)},this.addEventListener=(m,h,b)=>{Array.isArray(s[m])?s[m].some(([U])=>U===h)||s[m].push([h,b]):s[m]=[[h,b]],n.addEventListener(m,h,b)},this.removeEventListener=(m,h,b)=>{Array.isArray(s[m])&&(s[m]=s[m].filter(([U])=>U!==h)),n.removeEventListener(m,h,b)}};fe.exports=be});var ae=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ae||{}),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.PHOTO_MAKER="photoMaker",r.IMAGE_CAPTION="imageCaption",r.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",r.IMAGE_MASKING="imageMasking",r.PROMPT_ENHANCE="promptEnhance",r.AUTHENTICATION="authentication",r.MODEL_UPLOAD="modelUpload",r.MODEL_SEARCH="modelSearch",r))(q||{}),oe=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(oe||{}),ie=(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))(ie||{}),le=(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))(le||{}),Ge=(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))(Ge||{}),Be=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Be||{}),qe=(d=>(d.flux1d="flux1d",d.flux1s="flux1s",d.pony="pony",d.sdhyper="sdhyper",d.sd1x="sd1x",d.sd1xlcm="sd1xlcm",d.sd3="sd3",d.sdxl="sdxl",d.sdxllcm="sdxllcm",d.sdxldistilled="sdxldistilled",d.sdxlhyper="sdxlhyper",d.sdxllightning="sdxllightning",d.sdxlturbo="sdxlturbo",d))(qe||{}),He=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(He||{}),Ve=(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))(Ve||{}),je=(p=>(p.NoStyle="No style",p.Cinematic="Cinematic",p.DisneyCharacter="Disney Character",p.DigitalArt="Digital Art",p.Photographic="Photographic",p.FantasyArt="Fantasy art",p.Neonpunk="Neonpunk",p.Enhance="Enhance",p.ComicBook="Comic book",p.Lowpoly="Lowpoly",p.LineArt="Line art",p))(je||{});import{v4 as Qe,validate as Je}from"uuid";var H=6e4,ce=1e3,Ye=100,V={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},ue=(l,t)=>{if(l==null)return;let e=l.indexOf(t);e!==-1&&l.splice(e,1)},x=(l,{debugKey:t="debugKey",timeoutDuration:e=H,shouldThrowError:n=!0})=>(e=e<ce?ce:e,new Promise((a,o)=>{let c=setTimeout(()=>{i&&(clearInterval(i),n&&o(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),i=setInterval(async()=>{l({resolve:a,reject:o,intervalId:i})&&(clearInterval(i),clearTimeout(c))},Ye)})),ge=l=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(l),e.onload=function(){t(e.result)}}),T=()=>Qe(),pe=l=>Je(l);var de=({key:l,data:t,useZero:e=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,i)=>{let s=e?0:void 0,u=c?.[i];if(!u)return s;if(Array.isArray(u)&&/^\d+$/.test(i)){let g=parseInt(i,10);return g>=0&&g<u.length?c[i]=u[g]:c[i]??s}else return c[i]??s},t||{})??{},me=(l,t=1e3)=>new Promise(e=>setTimeout(e,l*t));var ye=(l,t)=>l.filter(e=>e.key!==t.key);var f=({key:l,value:t})=>t||t===0||t===!1?{[l]:t}:{},ze=(l,t)=>Math.floor(Math.random()*(t-l+1))+l,j=()=>ze(1,Number.MAX_SAFE_INTEGER);var R=async(l,t={})=>{let{delayInSeconds:e=1,callback:n}=t,a=t.maxRetries??1;for(;a;)try{return await l()}catch(o){if(n?.(),a--,a>0)await me(e),await R(l,{...t,maxRetries:a});else throw o}};var w=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 R(async()=>{let e=T();if(typeof t=="string"&&pe(t))return{imageURL:t,imageUUID:t,taskUUID:e,taskType:"imageUpload"};let n=typeof t=="string"?t:await ge(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:c,highThresholdCanny:i,lowThresholdCanny:s,includeHandsAndFaceOpenPose:u,includeCost:g,outputQuality:p,customTaskUUID:r,retry:d})=>{let m=d||this._globalMaxRetries,h;try{return await R(async()=>{await this.ensureConnection();let b=await this.uploadImage(t);if(!b?.imageUUID)return null;let U=r||T();this.send({inputImage:b.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:e,...f({key:"height",value:n}),...f({key:"width",value:a}),...f({key:"outputType",value:o}),...f({key:"outputFormat",value:c}),...f({key:"includeCost",value:g}),...f({key:"highThresholdCanny",value:i}),...f({key:"lowThresholdCanny",value:s}),...f({key:"includeHandsAndFaceOpenPose",value:u}),...p?{outputQuality:p}:{}}),h=this.globalListener({taskUUID:U});let S=await x(({resolve:D,reject:k})=>{let y=this.getSingleMessage({taskUUID:U});if(y){if(y?.error)return k(y),!0;if(y)return D(y),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return h.destroy(),S},{maxRetries:m,callback:()=>{h?.destroy()}})}catch(b){throw b}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:a})=>{let o=a||this._globalMaxRetries,c;try{return await R(async()=>{await this.ensureConnection();let i=t?await this.uploadImage(t):null,s=n||T();this.send({taskUUID:s,taskType:"imageCaption",inputImage:i?.imageUUID,...f({key:"includeCost",value:e})}),c=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return c.destroy(),u},{maxRetries:o,callback:()=>{c?.destroy()}})}catch(i){throw i}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:a,includeCost:o,outputQuality:c,customTaskUUID:i,retry:s})=>{let u=s||this._globalMaxRetries,g;try{return await R(async()=>{await this.ensureConnection();let p;p=await this.uploadImage(t);let r=i||T();this.send({taskUUID:r,inputImage:p?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...f({key:"includeCost",value:o}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...a?{outputFormat:a}:{}}),g=this.globalListener({taskUUID:r});let d=await x(({resolve:m,reject:h})=>{let b=this.getSingleMessage({taskUUID:r});if(b){if(b?.error)return h(b),!0;if(b)return delete this._globalMessages[r],m(b),!0}},{debugKey:"upscale-gan",timeoutDuration:this._timeoutDuration});return g.destroy(),d},{maxRetries:u,callback:()=>{g?.destroy()}})}catch(p){throw p}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:a,customTaskUUID:o,retry:c})=>{let i=c||this._globalMaxRetries,s;try{return await R(async()=>{await this.ensureConnection();let u=o||T();this.send({prompt:t,taskUUID:u,promptMaxLength:e,promptVersions:n,...f({key:"includeCost",value:a}),taskType:"promptEnhance"}),s=this.globalListener({taskUUID:u});let g=await x(({resolve:p,reject:r})=>{let d=this._globalMessages[u];if(d?.error)return r(d),!0;if(d?.length>=n)return delete this._globalMessages[u],p(d),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return s.destroy(),g},{maxRetries:i,callback:()=>{s?.destroy()}})}catch(u){throw u}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s,taskType:"modelUpload"});let u,g;return i=this.listenToUpload({taskUUID:s,onUploadStream:(r,d)=>{e?.(r,d),r?.status==="ready"?u=r:d&&(g=d)}}),await x(({resolve:r,reject:d})=>{if(u)return r(u),!0;if(g)return d(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:c,callback:()=>{i?.destroy()}})}catch(s){throw s}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:a,customTaskUUID:o,numberResults:c,...i}=t,s=a||this._globalMaxRetries,u,g=[],p=0;try{return await R(async()=>{await this.ensureConnection(),p++;let r=this._globalImages.filter(b=>g.includes(b.taskUUID)),d=o||T();g.push(d);let m=c-r.length;this.send({...i,...i.seed?{seed:i.seed}:{seed:j()},...e??{},numberResults:m,taskUUID:d,taskType:"photoMaker"}),u=this.listenToImages({onPartialImages:n,taskUUID:d,groupKey:"REQUEST_IMAGES",positivePrompt:i.positivePrompt});let h=await this.getSimilarImages({taskUUID:g,numberResults:c,lis:u});return u.destroy(),h},{maxRetries:s,callback:()=>{u?.destroy()}})}catch(r){if(r.taskUUID)throw r;if(p>=s)return this.handleIncompleteImages({taskUUIDs:g,error:r})}};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})=>{let{retry:n,customTaskUUID:a,...o}=t,c=n||this._globalMaxRetries,i;try{return await R(async()=>{await this.ensureConnection();let s=a||T();this.send({...o,taskUUID:s}),i=this.globalListener({taskUUID:s});let u=await x(({resolve:g,reject:p})=>{let r=this.getSingleMessage({taskUUID:s});if(r){if(r?.error)return p(r),!0;if(r)return delete this._globalMessages[s],g(r),!0}},{debugKey:e,timeoutDuration:this._timeoutDuration});return i.destroy(),u},{maxRetries:c,callback:()=>{i?.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=i=>{let s=Array.isArray(i?.data)?i.data:[i.data],u=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.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||T(),listener:a,groupKey:e};return this._listeners.push(o),{destroy:()=>{this._listeners=ye(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){ue(this._listeners,t)}listenToImages({onPartialImages:t,taskUUID:e,groupKey:n,positivePrompt:a,negativePrompt:o}){return this.addListener({taskUUID:e,lis:c=>{let i=c?.[e]?.filter(s=>s.taskUUID===e);c.error?(t?.(i,c?.error&&c),this._globalError=c):(i=i.map(s=>({...s,positivePrompt:a,negativePrompt:o})),t?.(i,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(s=>({...s,positivePrompt:a,negativePrompt:o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let a=n?.error,o=n?.[e]?.[0],c=o?.taskUUID===e?o:null;(c||a)&&t?.(c||void 0,a)}})}globalListener({taskUUID:t}){return this.addListener({taskUUID:t,lis:e=>{if(e.error){this._globalMessages[t]=e;return}let n=de({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:c,seedImage:i,maskImage:s,strength:u,height:g,width:p,model:r,steps:d,scheduler:m,seed:h,CFGScale:b,clipSkip:U,usePromptWeighting:S,promptWeighting:D,numberResults:k=1,onPartialImages:y,includeCost:Re,customTaskUUID:ke,retry:xe,refiner:Q,maskMargin:De,outputQuality:I,controlNet:L,lora:J,embeddings:Y,ipAdapters:z,outpaint:Z,acceleratorOptions:$,advancedFeatures:X,referenceImages:ee},Se){let A,te,E=[],ne=0,re=xe||this._globalMaxRetries;try{await this.ensureConnection();let v=null,K=null,W=[];if(i){let _=await this.uploadImage(i);if(!_)return[];v=_.imageUUID}if(s){let _=await this.uploadImage(s);if(!_)return[];K=_.imageUUID}if(L?.length)for(let _=0;_<L.length;_++){let C=L[_],{endStep:F,startStep:P,weight:G,guideImage:O,controlMode:ve,startStepPercentage:we,endStepPercentage:Ae,model:Ce}=C,Ee=O?await this.uploadImage(O):null;W.push({guideImage:Ee?.imageUUID,model:Ce,endStep:F,startStep:P,weight:G,...f({key:"startStepPercentage",value:we}),...f({key:"endStepPercentage",value:Ae}),controlMode:ve||"controlnet"})}return te={taskType:"imageInference",model:r,positivePrompt:o,...c?{negativePrompt:c}:{},...g?{height:g}:{},...p?{width:p}:{},numberResults:k,...t?{outputType:t}:{},...e?{outputFormat:e}:{},...n?{uploadEndpoint:n}:{},...f({key:"checkNSFW",value:a}),...f({key:"strength",value:u}),...f({key:"CFGScale",value:b}),...f({key:"clipSkip",value:U}),...f({key:"maskMargin",value:De}),...f({key:"usePromptWeighting",value:S}),...f({key:"steps",value:d}),...D?{promptWeighting:D}:{},...h?{seed:h}:{seed:j()},...m?{scheduler:m}:{},...Q?{refiner:Q}:{},...Z?{outpaint:Z}:{},...f({key:"includeCost",value:Re}),...v?{seedImage:v}:{},...K?{maskImage:K}:{},...I?{outputQuality:I}:{},...W.length?{controlNet:W}:{},...J?.length?{lora:J}:{},...Y?.length?{embeddings:Y}:{},...z?.length?{ipAdapters:z}:{},...$?{acceleratorOptions:$}:{},...X?{advancedFeatures:X}:{},...ee?.length?{referenceImages:ee}:{},...Se??{}},await R(async()=>{ne++,A?.destroy();let _=this._globalImages.filter(O=>E.includes(O.taskUUID)),C=ke||T();E.push(C);let F=k-_.length,P={...te,taskUUID:C,numberResults:F};this.send(P),A=this.listenToImages({onPartialImages:y,taskUUID:C,groupKey:"REQUEST_IMAGES",positivePrompt:o,negativePrompt:c});let G=await this.getSimilarImages({taskUUID:E,numberResults:k,lis:A});return A.destroy(),G},{maxRetries:re,callback:()=>{A?.destroy()}})}catch(v){if(ne>=re)return this.handleIncompleteImages({taskUUIDs:E,error:v});throw v}}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 c=0,i=30,s=T(),u,g,p=()=>{this.ensureConnectionUUID=null,clearInterval(u),clearInterval(g)};this._sdkType==="SERVER"&&(u=setInterval(async()=>{try{let r=this.connected(),d=!1;(!this.ensureConnectionUUID||s===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=s),d=!0);let m=c%10===0&&d;r?(p(),a(!0)):c>=i?(p(),o(new Error("Retry timed out"))):(m&&this.connect(),c++)}catch(r){p(),o(r)}},e)),g=setInterval(async()=>{if(this.connected()){p(),a(!0);return}if(this.isInvalidAPIKey()){p(),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 x(({resolve:o,reject:c,intervalId:i})=>{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(i),c?.(g),!0}else if(u.length>=e)return clearInterval(i),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 Te=Pe(Ue(),1),N=class extends w{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new Te.default(this._url),this.connect()}};import rt from"ws";var M=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 rt(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 a=n?e:e?.toString();if(!a)return;let o=JSON.parse(a);this._listeners.forEach(c=>{c.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 _e;typeof window>"u"?_e=M:_e=N;export{oe as EControlMode,qe as EModelArchitecture,Ve as EModelConditioning,Be as EModelFormat,He as EModelType,Ge as EOpenPosePreProcessor,je as EPhotoMakerEnum,le as EPreProcessor,ie as EPreProcessorGroup,q as ETaskType,ae as Environment,_e as Runware,N as RunwareClient,M as RunwareServer,B as SdkType};
|
|
1
|
+
var Pe=Object.create;var ie=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var qe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var Ve=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of We(t))!Be.call(i,s)&&s!==e&&ie(i,s,{get:()=>t[s],enumerable:!(n=Fe(t,s))||n.enumerable});return i};var He=(i,t,e)=>(e=i!=null?Pe(Ge(i)):{},Ve(t||!i||!i.__esModule?ie(e,"default",{value:i,enumerable:!0}):e,i));var De=qe((an,ke)=>{"use strict";var _e=i=>i&&i.CLOSING===2,st=()=>typeof WebSocket<"u"&&_e(WebSocket),rt=()=>({constructor:st()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),at=(i,t,e)=>{Object.defineProperty(t,e,{get:()=>i[e],set:n=>{i[e]=n},enumerable:!0,configurable:!0})},Ue=i=>i.minReconnectionDelay+Math.random()*i.minReconnectionDelay,ot=(i,t)=>{let e=t*i.reconnectionDelayGrowFactor;return e>i.maxReconnectionDelay?i.maxReconnectionDelay:e},it=["onopen","onclose","onmessage","onerror"],lt=(i,t,e)=>{Object.keys(e).forEach(n=>{e[n].forEach(([s,r])=>{i.addEventListener(n,s,r)})}),t&&it.forEach(n=>{i[n]=t[n]})},Re=function(i,t,e={}){let n,s,r=0,c=0,u=!0,l={};if(!(this instanceof Re))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=rt();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):()=>{},g=(o,y)=>setTimeout(()=>{let I=new Error(y);I.code=o,Array.isArray(l.error)&&l.error.forEach(([f])=>f(I)),n.onerror&&n.onerror(I)},0),a=()=>{if(d("close"),c++,d("retries count:",c),c>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=ot(p,r):r=Ue(p),d("reconnectDelay:",r),u&&setTimeout(m,r)},m=()=>{d("connect");let o=n;n=new p.constructor(i,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"),r=Ue(p),d("reconnectDelay:",r),c=0}),n.addEventListener("close",a),lt(n,o,l)};d("init"),m(),this.close=(o=1e3,y="",{keepClosed:I=!1,fastClose:f=!0,delay:k=0}={})=>{if(k&&(r=k),u=!I,n.close(o,y),f){let _={code:o,reason:y,wasClean:!0};a(),Array.isArray(l.close)&&l.close.forEach(([U,b])=>{U(_),n.removeEventListener("close",U,b)}),n.onclose&&(n.onclose(_),n.onclose=null)}},this.send=o=>{n.send(o)},this.addEventListener=(o,y,I)=>{Array.isArray(l[o])?l[o].some(([f])=>f===y)||l[o].push([y,I]):l[o]=[[y,I]],n.addEventListener(o,y,I)},this.removeEventListener=(o,y,I)=>{Array.isArray(l[o])&&(l[o]=l[o].filter(([f])=>f!==y)),n.removeEventListener(o,y,I)}};ke.exports=Re});var le=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(le||{}),j=(e=>(e.CLIENT="CLIENT",e.SERVER="SERVER",e))(j||{}),Q=(o=>(o.IMAGE_INFERENCE="imageInference",o.IMAGE_UPLOAD="imageUpload",o.IMAGE_UPSCALE="imageUpscale",o.IMAGE_BACKGROUND_REMOVAL="imageBackgroundRemoval",o.VIDEO_INFERENCE="videoInference",o.ASYNC_RESULTS="asyncResults",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))(Q||{}),ce=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ce||{}),ue=(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))(ue||{}),de=(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))(de||{}),je=(r=>(r.openpose="openpose",r.openpose_face="openpose_face",r.openpose_faceonly="openpose_faceonly",r.openpose_full="openpose_full",r.openpose_hand="openpose_hand",r))(je||{}),Qe=(e=>(e.safetensors="safetensors",e.pickletensor="pickletensor",e))(Qe||{}),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||{}),Je=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Je||{}),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||{}),Ze=(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))(Ze||{});import{v4 as $e,validate as Xe}from"uuid";var Y=6e4,pe=1e3,et=100,J={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},me=(i,t)=>{if(i==null)return;let e=i.indexOf(t);e!==-1&&i.splice(e,1)},S=(i,{debugKey:t="debugKey",timeoutDuration:e=Y,shouldThrowError:n=!0})=>(e=e<pe?pe:e,new Promise((s,r)=>{let c=setTimeout(()=>{u&&(clearInterval(u),n&&r(`Response could not be received from server for ${t}`)),clearTimeout(c)},e),u=setInterval(async()=>{i({resolve:s,reject:r,intervalId:u})&&(clearInterval(u),clearTimeout(c))},et)})),ye=i=>new Promise(t=>{let e=new FileReader;e.readAsDataURL(i),e.onload=function(){t(e.result)}}),R=()=>$e(),Ie=i=>Xe(i);var he=({key:i,data:t,useZero:e=!0,shouldReturnString:n=!1})=>i.split(/\.|\[/).map(c=>c.replace(/\]$/,"")).reduce((c,u)=>{let l=e?0:void 0,p=c?.[u];if(!p)return l;if(Array.isArray(p)&&/^\d+$/.test(u)){let d=parseInt(u,10);return d>=0&&d<p.length?c[u]=p[d]:c[u]??l}else return c[u]??l},t||{})??{},fe=(i,t=1e3)=>new Promise(e=>setTimeout(e,i*t));var be=(i,t)=>i.filter(e=>e.key!==t.key);var T=({key:i,value:t})=>t||t===0||t===!1?{[i]:t}:{},tt=(i,t)=>Math.floor(Math.random()*(t-i+1))+i,z=()=>tt(1,Number.MAX_SAFE_INTEGER),Te=({count:i,taskUUID:t})=>{let e=[];for(let n=0;n<i;n++){let s=Math.random()<.5,r={taskUUID:t,taskType:"videoInference"};s?e.push({...r,status:"succeeded",videoUUID:crypto.randomUUID(),cost:parseFloat((Math.random()*10).toFixed(2)),seed:Math.floor(Math.random()*100),videoURL:nt()}):e.push({...r,status:"pending"})}return e},ge=["https://vm.runware.dev/video/ws/2/vi/032dd763-4082-4fa4-aa7c-ca2e0d272c08.mp4","https://vm.runware.dev/video/ws/2/vi/4f809a60-47bb-49e7-9a31-c8834a8bf143.mp4","https://vm.runware.dev/video/ws/2/vi/3a146615-5ba6-4844-9d54-6455617554f8.mp4","https://www.w3schools.com/html/mov_bbb.mp4","https://filesamples.com/samples/video/mp4/sample_640x360.mp4","https://media.w3.org/2010/05/sintel/trailer.mp4","https://samplelib.com/lib/preview/mp4/sample-5s.mp4","https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_1MB.mp4"];function nt(){let i=Math.floor(Math.random()*ge.length);return ge[i]}var x=async(i,t={})=>{let{delayInSeconds:e=1,callback:n}=t,s=t.maxRetries??1;for(;s;)try{return await i()}catch(r){if(n?.(),s--,s>0)await fe(e),await x(i,{...t,maxRetries:s});else throw r}};var A=class{constructor({apiKey:t,url:e=J.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=Y}){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:r,outputFormat:c,highThresholdCanny:u,lowThresholdCanny:l,includeHandsAndFaceOpenPose:p,includeCost:d,outputQuality:g,customTaskUUID:a,retry:m,includeGenerationTime:o,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:r}),...T({key:"outputFormat",value:c}),...T({key:"includeCost",value:d}),...T({key:"highThresholdCanny",value:u}),...T({key:"lowThresholdCanny",value:l}),...T({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...b}),f=this.globalListener({taskUUID:U});let N=await S(({resolve:F,reject:W})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return W(v),!0;if(v)return F(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:N,payload:y?b:void 0,startTime:o?k:void 0}),N},{maxRetries:I,callback:()=>{f?.destroy()}})}catch(_){throw _}};this.requestImageToText=async({inputImage:t,includeCost:e,customTaskUUID:n,retry:s,includePayload:r,includeGenerationTime:c})=>{let u=s||this._globalMaxRetries,l,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),l=this.globalListener({taskUUID:g});let m=await S(({resolve:o,reject:y})=>{let I=this.getSingleMessage({taskUUID:g});if(I){if(I?.error)return y(I),!0;if(I)return delete this._globalMessages[g],o(I),!0}},{debugKey:"remove-image-background",timeoutDuration:this._timeoutDuration});return l.destroy(),this.insertAdditionalResponse({response:m,payload:r?a:void 0,startTime:c?p:void 0}),m},{maxRetries:u,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.removeImageBackground=async t=>this.baseSingleRequest({payload:{...t,taskType:"imageBackgroundRemoval"},debugKey:"remove-image-background"});this.videoInference=async t=>this.baseSingleRequest({payload:{...t,deliveryMethod:"async",taskType:"videoInference"},mockResponse:[{taskType:"videoInference",taskUUID:R(),status:"pending"}],debugKey:"video-inference"});this.getAsyncResults=async t=>{let e=t.taskUUID,n=Te({count:2,taskUUID:e});return this.baseSingleRequest({payload:{...t,customTaskUUID:e,taskType:"asyncResults"},mockResponse:n,debugKey:"async-results"})};this.upscaleGan=async({inputImage:t,upscaleFactor:e,outputType:n,outputFormat:s,includeCost:r,outputQuality:c,customTaskUUID:u,retry:l,includeGenerationTime:p,includePayload:d})=>{let g=l||this._globalMaxRetries,a,m=Date.now();try{return await x(async()=>{await this.ensureConnection();let o;o=await this.uploadImage(t);let y=u||R(),I={taskUUID:y,inputImage:o?.imageUUID,taskType:"imageUpscale",upscaleFactor:e,...T({key:"includeCost",value:r}),...n?{outputType:n}:{},...c?{outputQuality:c}:{},...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(o){throw o}};this.enhancePrompt=async({prompt:t,promptMaxLength:e=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,retry:c,includeGenerationTime:u,includePayload:l})=>{let p=c||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let a=r||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 o=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:o,payload:l?m:void 0,startTime:u?g:void 0}),o},{maxRetries:p,callback:()=>{d?.destroy()}})}catch(a){throw a}};this.modelUpload=async t=>{let{onUploadStream:e,retry:n,customTaskUUID:s,...r}=t,c=n||this._globalMaxRetries,u;try{return await x(async()=>{await this.ensureConnection();let l=s||R();this.send({...r,taskUUID:l,taskType:"modelUpload"});let p,d;return u=this.listenToUpload({taskUUID:l,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:c,callback:()=>{u?.destroy()}})}catch(l){throw l}};this.photoMaker=async(t,e)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,numberResults:c,includeGenerationTime:u,includePayload:l,...p}=t,d=s||this._globalMaxRetries,g,a=[],m=0,o=Date.now();try{return await x(async()=>{await this.ensureConnection(),m++;let y=this._globalImages.filter(U=>a.includes(U.taskUUID)),I=r||R();a.push(I);let f=c-y.length,k={...p,...p.seed?{seed:p.seed}:{seed:z()},...e??{},taskUUID:I,taskType:"photoMaker",numberResults:c};this.send({...k,numberResults:f}),g=this.listenToImages({onPartialImages:n,taskUUID:I,groupKey:"REQUEST_IMAGES",requestPayload:l?k:void 0,startTime:u?o:void 0});let _=await this.getSimilarImages({taskUUID:a,numberResults:c,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,mockResponse:n})=>{let{retry:s,customTaskUUID:r,includePayload:c,includeGenerationTime:u,...l}=t,p=s||this._globalMaxRetries,d,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let a=r||R(),m={...l,taskUUID:a};n?setTimeout(()=>{this._globalMessages[a]=n},1e3):this.send(m),d=this.globalListener({taskUUID:a});let o=await S(({resolve:y,reject:I})=>{let f=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:o,payload:c?m:void 0,startTime:u?g:void 0}),d.destroy(),o},{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.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=r}static async initialize(t){try{let e=new this(t);return await e.ensureConnection(),e}catch(e){throw e}}addListener({lis:t,groupKey:e,taskUUID:n}){let s=u=>{let l=Array.isArray(u?.data)?u.data:[u.data],p=u?.[0]?.errors?u?.[0]?.errors:Array.isArray(u?.errors)?u.errors:[u.errors],d=l.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]:l});return}},r={key:n||R(),listener:s,groupKey:e};return this._listeners.push(r),{destroy:()=>{this._listeners=be(this._listeners,r)}}}connect(){this._ws.onopen=t=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:e=>{if(e?.error){this._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:r}){return this.addListener({taskUUID:e,lis:c=>{let u=c?.[e]?.filter(l=>l.taskUUID===e);c.error?(t?.(u,c?.error&&c),this._globalError=c):(u=u.map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:r||void 0}),{...l})),t?.(u,c?.error&&c),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(c?.[e]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:s||void 0,startTime:r||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...u])},groupKey:n})}listenToUpload({onUploadStream:t,taskUUID:e}){return this.addListener({taskUUID:e,lis:n=>{let s=n?.error,r=n?.[e]?.[0],c=r?.taskUUID===e?r:null;(c||s)&&t?.(c||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:r,negativePrompt:c,seedImage:u,maskImage:l,strength:p,height:d,width:g,model:a,steps:m,scheduler:o,seed:y,CFGScale:I,clipSkip:f,usePromptWeighting:k,promptWeighting:_,numberResults:U=1,onPartialImages:b,includeCost:N,customTaskUUID:F,retry:W,refiner:v,maskMargin:Se,outputQuality:h,controlNet:G,lora:Z,embeddings:$,ipAdapters:X,outpaint:ee,acceleratorOptions:te,advancedFeatures:ne,referenceImages:se,includeGenerationTime:we,includePayload:Ae},Ce){let C,re,O=[],ae=0,oe=W||this._globalMaxRetries;try{await this.ensureConnection();let w=null,B=null,q=[];if(u){let D=await this.uploadImage(u);if(!D)return[];w=D.imageUUID}if(l){let D=await this.uploadImage(l);if(!D)return[];B=D.imageUUID}if(G?.length)for(let D=0;D<G.length;D++){let E=G[D],{endStep:V,startStep:M,weight:H,guideImage:L,controlMode:Ne,startStepPercentage:Oe,endStepPercentage:Me,model:Le}=E,Ke=L?await this.uploadImage(L):null;q.push({guideImage:Ke?.imageUUID,model:Le,endStep:V,startStep:M,weight:H,...T({key:"startStepPercentage",value:Oe}),...T({key:"endStepPercentage",value:Me}),controlMode:Ne||"controlnet"})}re={taskType:"imageInference",model:a,positivePrompt:r,...c?{negativePrompt:c}:{},...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:Se}),...T({key:"usePromptWeighting",value:k}),...T({key:"steps",value:m}),..._?{promptWeighting:_}:{},...y?{seed:y}:{seed:z()},...o?{scheduler:o}:{},...v?{refiner:v}:{},...ee?{outpaint:ee}:{},...T({key:"includeCost",value:N}),...w?{seedImage:w}:{},...B?{maskImage:B}:{},...h?{outputQuality:h}:{},...q.length?{controlNet:q}:{},...Z?.length?{lora:Z}:{},...$?.length?{embeddings:$}:{},...X?.length?{ipAdapters:X}:{},...te?{acceleratorOptions:te}:{},...ne?{advancedFeatures:ne}:{},...se?.length?{referenceImages:se}:{},...Ce??{}};let Ee=Date.now();return await x(async()=>{ae++,C?.destroy();let D=this._globalImages.filter(L=>O.includes(L.taskUUID)),E=F||R();O.push(E);let V=U-D.length,M={...re,taskUUID:E,numberResults:V};this.send(M),C=this.listenToImages({onPartialImages:b,taskUUID:E,groupKey:"REQUEST_IMAGES",requestPayload:Ae?M:void 0,startTime:we?Ee:void 0});let H=await this.getSimilarImages({taskUUID:O,numberResults:U,lis:C});return C.destroy(),H},{maxRetries:oe,callback:()=>{C?.destroy()}})}catch(w){if(ae>=oe)return this.handleIncompleteImages({taskUUIDs:O,error:w});throw w}}async ensureConnection(){if(this.connected()||this._url===J.TEST)return;let e=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let c=0,u=30,l=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||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),m=!0);let o=c%10===0&&m;a?(g(),s(!0)):c>=u?(g(),r(new Error("Retry timed out"))):(o&&this.connect(),c++)}catch(a){g(),r(a)}},e)),d=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getSimilarImages({taskUUID:t,numberResults:e,shouldThrowError:n,lis:s}){return await S(({resolve:r,reject:c,intervalId:u})=>{let l=Array.isArray(t)?t:[t],p=this._globalImages.filter(d=>l.includes(d.taskUUID));if(this._globalError){let d=this._globalError;return this._globalError=void 0,clearInterval(u),c?.(d),!0}else if(p.length>=e)return clearInterval(u),this._globalImages=this._globalImages.filter(d=>!l.includes(d.taskUUID)),r([...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 xe=He(De(),1),K=class extends A{constructor(t){let{shouldReconnect:e,...n}=t;super(n),this._ws=new xe.default(this._url),this.connect()}};import ct from"ws";var P=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 ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis: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 r=JSON.parse(s);this._listeners.forEach(c=>{c.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var ve;typeof window>"u"?ve=P:ve=K;export{ce as EControlMode,Ye as EModelArchitecture,ze as EModelConditioning,Qe as EModelFormat,Je as EModelType,je as EOpenPosePreProcessor,Ze as EPhotoMakerEnum,de as EPreProcessor,ue as EPreProcessorGroup,Q as ETaskType,le as Environment,ve as Runware,K as RunwareClient,P as RunwareServer,j as SdkType};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|