@runware/sdk-js 1.2.5-beta.1 → 1.2.5-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 +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +81 -11
- package/dist/index.d.ts +81 -11
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +1 -0
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runware SDK Telemetry Logger
|
|
3
|
+
*
|
|
4
|
+
* Beautiful colored console output for debugging SDK internals.
|
|
5
|
+
* Only active when `enableLogging: true` is passed during instantiation.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
|
|
9
|
+
*/
|
|
10
|
+
declare enum LogLevel {
|
|
11
|
+
CONNECTION = "CONNECTION",
|
|
12
|
+
AUTH = "AUTH",
|
|
13
|
+
HEARTBEAT = "HEARTBEAT",
|
|
14
|
+
SEND = "SEND",
|
|
15
|
+
RECEIVE = "RECEIVE",
|
|
16
|
+
RETRY = "RETRY",
|
|
17
|
+
REQUEST = "REQUEST",
|
|
18
|
+
ERROR = "ERROR",
|
|
19
|
+
WARN = "WARN",
|
|
20
|
+
INFO = "INFO"
|
|
21
|
+
}
|
|
22
|
+
declare class RunwareLogger {
|
|
23
|
+
private enabled;
|
|
24
|
+
constructor(enabled?: boolean);
|
|
25
|
+
private log;
|
|
26
|
+
connecting(url: string): void;
|
|
27
|
+
connected(sessionUUID: string): void;
|
|
28
|
+
reconnecting(attempt: number): void;
|
|
29
|
+
reconnectScheduled(delayMs: number): void;
|
|
30
|
+
disconnected(reason?: string): void;
|
|
31
|
+
connectionClosed(code?: number): void;
|
|
32
|
+
connectionError(error?: any): void;
|
|
33
|
+
ensureConnectionStart(): void;
|
|
34
|
+
ensureConnectionSuccess(): void;
|
|
35
|
+
ensureConnectionTimeout(): void;
|
|
36
|
+
authenticating(hasSession: boolean): void;
|
|
37
|
+
authenticated(sessionUUID: string): void;
|
|
38
|
+
authError(error: any): void;
|
|
39
|
+
heartbeatStarted(intervalMs: number): void;
|
|
40
|
+
heartbeatPingSent(): void;
|
|
41
|
+
heartbeatPongReceived(): void;
|
|
42
|
+
heartbeatPongMissed(count: number, max: number): void;
|
|
43
|
+
heartbeatStopped(): void;
|
|
44
|
+
messageSent(taskType: string, taskUUID?: string): void;
|
|
45
|
+
messageReceived(taskType?: string, taskUUID?: string): void;
|
|
46
|
+
sendReconnecting(): void;
|
|
47
|
+
sendFailed(error: string): void;
|
|
48
|
+
requestStart(taskType: string, taskUUID: string): void;
|
|
49
|
+
requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
|
|
50
|
+
requestTimeout(taskUUID: string, timeoutMs: number): void;
|
|
51
|
+
requestError(taskUUID: string, error: any): void;
|
|
52
|
+
retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
|
|
53
|
+
retrySuccess(attempt: number): void;
|
|
54
|
+
retryExhausted(maxRetries: number): void;
|
|
55
|
+
retrySkippedApiError(code: string): void;
|
|
56
|
+
info(message: string, data?: any): void;
|
|
57
|
+
warn(message: string, data?: any): void;
|
|
58
|
+
error(message: string, data?: any): void;
|
|
59
|
+
}
|
|
60
|
+
declare function createLogger(enabled: boolean): RunwareLogger;
|
|
61
|
+
|
|
1
62
|
declare enum Environment {
|
|
2
63
|
PRODUCTION = "PRODUCTION",
|
|
3
64
|
DEVELOPMENT = "DEVELOPMENT",
|
|
@@ -34,6 +95,8 @@ type RunwareBaseType = {
|
|
|
34
95
|
shouldReconnect?: boolean;
|
|
35
96
|
globalMaxRetries?: number;
|
|
36
97
|
timeoutDuration?: number;
|
|
98
|
+
heartbeatInterval?: number;
|
|
99
|
+
enableLogging?: boolean;
|
|
37
100
|
};
|
|
38
101
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
39
102
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
@@ -137,9 +200,7 @@ type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
|
137
200
|
guideImage?: string;
|
|
138
201
|
};
|
|
139
202
|
interface IError {
|
|
140
|
-
error:
|
|
141
|
-
errorMessage: string;
|
|
142
|
-
taskUUID: string;
|
|
203
|
+
error: IErrorResponse;
|
|
143
204
|
}
|
|
144
205
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
145
206
|
interface IRequestImage extends IAdditionalResponsePayload {
|
|
@@ -304,6 +365,8 @@ interface IRequestVideo extends IRequestImageToText {
|
|
|
304
365
|
speech?: {
|
|
305
366
|
voice: string;
|
|
306
367
|
text: string;
|
|
368
|
+
} & {
|
|
369
|
+
[key: string]: unknown;
|
|
307
370
|
};
|
|
308
371
|
skipResponse?: boolean;
|
|
309
372
|
customTaskUUID?: string;
|
|
@@ -833,15 +896,21 @@ declare class RunwareBase {
|
|
|
833
896
|
_url?: string;
|
|
834
897
|
_globalMessages: Record<string, any>;
|
|
835
898
|
_globalImages: IImage[];
|
|
836
|
-
|
|
899
|
+
_globalErrors: IError[];
|
|
837
900
|
_connectionSessionUUID: string | undefined;
|
|
838
901
|
_connectionError: TServerError | undefined;
|
|
839
902
|
_sdkType: SdkType;
|
|
840
903
|
_shouldReconnect: boolean;
|
|
841
904
|
_globalMaxRetries: number;
|
|
842
905
|
_timeoutDuration: number;
|
|
906
|
+
_heartbeatIntervalId: any;
|
|
907
|
+
_pongTimeoutId: any;
|
|
908
|
+
_heartbeatInterval: number;
|
|
909
|
+
_missedPongCount: number;
|
|
910
|
+
_maxMissedPongs: number;
|
|
843
911
|
ensureConnectionUUID: string | null;
|
|
844
|
-
|
|
912
|
+
_logger: RunwareLogger;
|
|
913
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
845
914
|
private getUniqueUUID;
|
|
846
915
|
/**
|
|
847
916
|
* Shared polling logic for async results.
|
|
@@ -853,6 +922,9 @@ declare class RunwareBase {
|
|
|
853
922
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
854
923
|
protected isWebsocketReadyState: () => boolean;
|
|
855
924
|
protected isInvalidAPIKey: () => boolean;
|
|
925
|
+
protected startHeartbeat(): void;
|
|
926
|
+
protected stopHeartbeat(): void;
|
|
927
|
+
protected handlePongMessage(data: any): boolean;
|
|
856
928
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
857
929
|
lis: (v: any) => any;
|
|
858
930
|
groupKey?: string;
|
|
@@ -861,7 +933,7 @@ declare class RunwareBase {
|
|
|
861
933
|
destroy: () => void;
|
|
862
934
|
};
|
|
863
935
|
protected connect(): void;
|
|
864
|
-
protected send: (msg: Object) => void
|
|
936
|
+
protected send: (msg: Object) => Promise<void>;
|
|
865
937
|
private destroy;
|
|
866
938
|
private uploadImage;
|
|
867
939
|
private listenToResponse;
|
|
@@ -937,16 +1009,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
937
1009
|
_instantiated: boolean;
|
|
938
1010
|
_listeners: any[];
|
|
939
1011
|
_reconnectingIntervalId: null | any;
|
|
940
|
-
|
|
941
|
-
_pongListener: any;
|
|
1012
|
+
private _connecting;
|
|
942
1013
|
constructor(props: RunwareBaseType);
|
|
943
1014
|
protected connect(): Promise<void>;
|
|
944
|
-
protected send: (msg: Object) => void
|
|
1015
|
+
protected send: (msg: Object) => Promise<void>;
|
|
945
1016
|
protected handleClose(): void;
|
|
946
1017
|
protected resetConnection: () => void;
|
|
947
|
-
protected heartBeat(): void;
|
|
948
1018
|
}
|
|
949
1019
|
|
|
950
1020
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
951
1021
|
|
|
952
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
1022
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runware SDK Telemetry Logger
|
|
3
|
+
*
|
|
4
|
+
* Beautiful colored console output for debugging SDK internals.
|
|
5
|
+
* Only active when `enableLogging: true` is passed during instantiation.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* const runware = new RunwareServer({ apiKey: "...", enableLogging: true });
|
|
9
|
+
*/
|
|
10
|
+
declare enum LogLevel {
|
|
11
|
+
CONNECTION = "CONNECTION",
|
|
12
|
+
AUTH = "AUTH",
|
|
13
|
+
HEARTBEAT = "HEARTBEAT",
|
|
14
|
+
SEND = "SEND",
|
|
15
|
+
RECEIVE = "RECEIVE",
|
|
16
|
+
RETRY = "RETRY",
|
|
17
|
+
REQUEST = "REQUEST",
|
|
18
|
+
ERROR = "ERROR",
|
|
19
|
+
WARN = "WARN",
|
|
20
|
+
INFO = "INFO"
|
|
21
|
+
}
|
|
22
|
+
declare class RunwareLogger {
|
|
23
|
+
private enabled;
|
|
24
|
+
constructor(enabled?: boolean);
|
|
25
|
+
private log;
|
|
26
|
+
connecting(url: string): void;
|
|
27
|
+
connected(sessionUUID: string): void;
|
|
28
|
+
reconnecting(attempt: number): void;
|
|
29
|
+
reconnectScheduled(delayMs: number): void;
|
|
30
|
+
disconnected(reason?: string): void;
|
|
31
|
+
connectionClosed(code?: number): void;
|
|
32
|
+
connectionError(error?: any): void;
|
|
33
|
+
ensureConnectionStart(): void;
|
|
34
|
+
ensureConnectionSuccess(): void;
|
|
35
|
+
ensureConnectionTimeout(): void;
|
|
36
|
+
authenticating(hasSession: boolean): void;
|
|
37
|
+
authenticated(sessionUUID: string): void;
|
|
38
|
+
authError(error: any): void;
|
|
39
|
+
heartbeatStarted(intervalMs: number): void;
|
|
40
|
+
heartbeatPingSent(): void;
|
|
41
|
+
heartbeatPongReceived(): void;
|
|
42
|
+
heartbeatPongMissed(count: number, max: number): void;
|
|
43
|
+
heartbeatStopped(): void;
|
|
44
|
+
messageSent(taskType: string, taskUUID?: string): void;
|
|
45
|
+
messageReceived(taskType?: string, taskUUID?: string): void;
|
|
46
|
+
sendReconnecting(): void;
|
|
47
|
+
sendFailed(error: string): void;
|
|
48
|
+
requestStart(taskType: string, taskUUID: string): void;
|
|
49
|
+
requestComplete(taskType: string, taskUUID: string, durationMs: number): void;
|
|
50
|
+
requestTimeout(taskUUID: string, timeoutMs: number): void;
|
|
51
|
+
requestError(taskUUID: string, error: any): void;
|
|
52
|
+
retryAttempt(attempt: number, maxRetries: number, delayMs: number): void;
|
|
53
|
+
retrySuccess(attempt: number): void;
|
|
54
|
+
retryExhausted(maxRetries: number): void;
|
|
55
|
+
retrySkippedApiError(code: string): void;
|
|
56
|
+
info(message: string, data?: any): void;
|
|
57
|
+
warn(message: string, data?: any): void;
|
|
58
|
+
error(message: string, data?: any): void;
|
|
59
|
+
}
|
|
60
|
+
declare function createLogger(enabled: boolean): RunwareLogger;
|
|
61
|
+
|
|
1
62
|
declare enum Environment {
|
|
2
63
|
PRODUCTION = "PRODUCTION",
|
|
3
64
|
DEVELOPMENT = "DEVELOPMENT",
|
|
@@ -34,6 +95,8 @@ type RunwareBaseType = {
|
|
|
34
95
|
shouldReconnect?: boolean;
|
|
35
96
|
globalMaxRetries?: number;
|
|
36
97
|
timeoutDuration?: number;
|
|
98
|
+
heartbeatInterval?: number;
|
|
99
|
+
enableLogging?: boolean;
|
|
37
100
|
};
|
|
38
101
|
type IOutputType = "base64Data" | "dataURI" | "URL";
|
|
39
102
|
type IOutputFormat = "JPG" | "PNG" | "WEBP";
|
|
@@ -137,9 +200,7 @@ type IControlNetWithUUID = Omit<IControlNet, "guideImage"> & {
|
|
|
137
200
|
guideImage?: string;
|
|
138
201
|
};
|
|
139
202
|
interface IError {
|
|
140
|
-
error:
|
|
141
|
-
errorMessage: string;
|
|
142
|
-
taskUUID: string;
|
|
203
|
+
error: IErrorResponse;
|
|
143
204
|
}
|
|
144
205
|
type TPromptWeighting = "compel" | "sdEmbeds";
|
|
145
206
|
interface IRequestImage extends IAdditionalResponsePayload {
|
|
@@ -304,6 +365,8 @@ interface IRequestVideo extends IRequestImageToText {
|
|
|
304
365
|
speech?: {
|
|
305
366
|
voice: string;
|
|
306
367
|
text: string;
|
|
368
|
+
} & {
|
|
369
|
+
[key: string]: unknown;
|
|
307
370
|
};
|
|
308
371
|
skipResponse?: boolean;
|
|
309
372
|
customTaskUUID?: string;
|
|
@@ -833,15 +896,21 @@ declare class RunwareBase {
|
|
|
833
896
|
_url?: string;
|
|
834
897
|
_globalMessages: Record<string, any>;
|
|
835
898
|
_globalImages: IImage[];
|
|
836
|
-
|
|
899
|
+
_globalErrors: IError[];
|
|
837
900
|
_connectionSessionUUID: string | undefined;
|
|
838
901
|
_connectionError: TServerError | undefined;
|
|
839
902
|
_sdkType: SdkType;
|
|
840
903
|
_shouldReconnect: boolean;
|
|
841
904
|
_globalMaxRetries: number;
|
|
842
905
|
_timeoutDuration: number;
|
|
906
|
+
_heartbeatIntervalId: any;
|
|
907
|
+
_pongTimeoutId: any;
|
|
908
|
+
_heartbeatInterval: number;
|
|
909
|
+
_missedPongCount: number;
|
|
910
|
+
_maxMissedPongs: number;
|
|
843
911
|
ensureConnectionUUID: string | null;
|
|
844
|
-
|
|
912
|
+
_logger: RunwareLogger;
|
|
913
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
845
914
|
private getUniqueUUID;
|
|
846
915
|
/**
|
|
847
916
|
* Shared polling logic for async results.
|
|
@@ -853,6 +922,9 @@ declare class RunwareBase {
|
|
|
853
922
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
854
923
|
protected isWebsocketReadyState: () => boolean;
|
|
855
924
|
protected isInvalidAPIKey: () => boolean;
|
|
925
|
+
protected startHeartbeat(): void;
|
|
926
|
+
protected stopHeartbeat(): void;
|
|
927
|
+
protected handlePongMessage(data: any): boolean;
|
|
856
928
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
857
929
|
lis: (v: any) => any;
|
|
858
930
|
groupKey?: string;
|
|
@@ -861,7 +933,7 @@ declare class RunwareBase {
|
|
|
861
933
|
destroy: () => void;
|
|
862
934
|
};
|
|
863
935
|
protected connect(): void;
|
|
864
|
-
protected send: (msg: Object) => void
|
|
936
|
+
protected send: (msg: Object) => Promise<void>;
|
|
865
937
|
private destroy;
|
|
866
938
|
private uploadImage;
|
|
867
939
|
private listenToResponse;
|
|
@@ -937,16 +1009,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
937
1009
|
_instantiated: boolean;
|
|
938
1010
|
_listeners: any[];
|
|
939
1011
|
_reconnectingIntervalId: null | any;
|
|
940
|
-
|
|
941
|
-
_pongListener: any;
|
|
1012
|
+
private _connecting;
|
|
942
1013
|
constructor(props: RunwareBaseType);
|
|
943
1014
|
protected connect(): Promise<void>;
|
|
944
|
-
protected send: (msg: Object) => void
|
|
1015
|
+
protected send: (msg: Object) => Promise<void>;
|
|
945
1016
|
protected handleClose(): void;
|
|
946
1017
|
protected resetConnection: () => void;
|
|
947
|
-
protected heartBeat(): void;
|
|
948
1018
|
}
|
|
949
1019
|
|
|
950
1020
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
951
1021
|
|
|
952
|
-
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType };
|
|
1022
|
+
export { EControlMode, EModelArchitecture, EModelConditioning, EModelFormat, EModelType, EOpenPosePreProcessor, EPhotoMakerEnum, EPreProcessor, EPreProcessorGroup, ETaskType, Environment, type GetWithPromiseAsyncCallBackType, type GetWithPromiseCallBackType, type IAddModelResponse, type IAdditionalResponsePayload, type IAsyncResults, type IAudio, type IAudioOutputFormat, type IBflProviderSettings, type IControlNet, type IControlNetGeneral, type IControlNetImage, type IControlNetPreprocess, type IControlNetWithUUID, type IEmbedding, type IEnhancedPrompt, type IError, type IErrorResponse, type IImage, type IImageToText, type IOutpaint, type IOutputFormat, type IOutputType, type IPromptEnhancer, type IProviderSettings, type IRefiner, type IRemoveImage, type IRemoveImageBackground, type IRequestAudio, type IRequestImage, type IRequestImageToText, type IRequestTextInference, type IRequestThreeD, type IRequestVideo, type ITextMessage, type ITextResponse, type ITextToImage, type IThreeDImage, type IThreeDOutputFormat, type IUpscaleGan, type IVideoOutputFormat, type IVideoToImage, type IipAdapter, type ListenerType, LogLevel, type MediaUUID, type ProviderSettings, type ReconnectingWebsocketProps, type RequireAtLeastOne, type RequireOnlyOne, Runware, type RunwareBaseType, RunwareClient, RunwareLogger, RunwareServer, SdkType, type TAcceleratorOptions, type TAddModel, type TAddModelBaseType, type TAddModelCheckPoint, type TAddModelControlNet, type TAddModelLora, type TImageMasking, type TImageMaskingResponse, type TImageUpload, type TImageUploadResponse, type TMediaStorage, type TMediaStorageResponse, type TModel, type TModelSearch, type TModelSearchResponse, type TPhotoMaker, type TPhotoMakerResponse, type TPromptWeighting, type TServerError, type TVectorize, type TVectorizeResponse, type UploadImageType, createLogger };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
var We=Object.create;var de=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var Qe=(l,e)=>()=>(e||l((e={exports:{}}).exports,e),e.exports);var ze=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(l,s)&&s!==t&&de(l,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return l};var je=(l,e,t)=>(t=l!=null?We(Ge(l)):{},ze(e||!l||!l.__esModule?de(t,"default",{value:l,enumerable:!0}):t,l));var we=Qe((bn,Se)=>{"use strict";var xe=l=>l&&l.CLOSING===2,rt=()=>typeof WebSocket<"u"&&xe(WebSocket),at=()=>({constructor:rt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ot=(l,e,t)=>{Object.defineProperty(e,t,{get:()=>l[t],set:n=>{l[t]=n},enumerable:!0,configurable:!0})},_e=l=>l.minReconnectionDelay+Math.random()*l.minReconnectionDelay,it=(l,e)=>{let t=e*l.reconnectionDelayGrowFactor;return t>l.maxReconnectionDelay?l.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(l,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,r])=>{l.addEventListener(n,s,r)})}),e&<.forEach(n=>{l[n]=e[n]})},ve=function(l,e,t={}){let n,s,r=0,a=0,i=!0,o={};if(!(this instanceof ve))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let p=at();if(Object.keys(p).filter(d=>t.hasOwnProperty(d)).forEach(d=>p[d]=t[d]),!xe(p.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=p.debug?(...d)=>console.log("RWS:",...d):()=>{},g=(d,I)=>setTimeout(()=>{let h=new Error(I);h.code=d,Array.isArray(o.error)&&o.error.forEach(([b])=>b(h)),n.onerror&&n.onerror(h)},0),u=()=>{if(m("close"),a++,m("retries count:",a),a>p.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}r?r=it(p,r):r=_e(p),m("reconnectDelay:",r),i&&setTimeout(c,r)},c=()=>{m("connect");let d=n;n=new p.constructor(l,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},p.connectionTimeout),m("bypass properties");for(let I in n)["addEventListener","removeEventListener","close","send"].indexOf(I)<0&&ot(n,this,I);n.addEventListener("open",()=>{clearTimeout(s),m("open"),r=_e(p),m("reconnectDelay:",r),a=0}),n.addEventListener("close",u),ut(n,d,o)};m("init"),c(),this.close=(d=1e3,I="",{keepClosed:h=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(r=f),i=!h,n.close(d,I),b){let y={code:d,reason:I,wasClean:!0};u(),Array.isArray(o.close)&&o.close.forEach(([k,U])=>{k(y),n.removeEventListener("close",k,U)}),n.onclose&&(n.onclose(y),n.onclose=null)}},this.send=d=>{n.send(d)},this.addEventListener=(d,I,h)=>{Array.isArray(o[d])?o[d].some(([b])=>b===I)||o[d].push([I,h]):o[d]=[[I,h]],n.addEventListener(d,I,h)},this.removeEventListener=(d,I,h)=>{Array.isArray(o[d])&&(o[d]=o[d].filter(([b])=>b!==I)),n.removeEventListener(d,I,h)}};Se.exports=ve});var pe=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(pe||{}),X=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(X||{}),J=(y=>(y.IMAGE_INFERENCE="imageInference",y.IMAGE_UPLOAD="imageUpload",y.UPSCALE="upscale",y.REMOVE_BACKGROUND="removeBackground",y.VIDEO_INFERENCE="videoInference",y.CAPTION="caption",y.AUDIO_INFERENCE="audioInference",y.THREE_D_INFERENCE="3dInference",y.GET_RESPONSE="getResponse",y.PHOTO_MAKER="photoMaker",y.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",y.IMAGE_MASKING="imageMasking",y.PROMPT_ENHANCE="promptEnhance",y.AUTHENTICATION="authentication",y.MODEL_UPLOAD="modelUpload",y.MODEL_SEARCH="modelSearch",y.MEDIA_STORAGE="mediaStorage",y.VECTORIZE="vectorize",y.TEXT_INFERENCE="textInference",y))(J||{}),ge=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ge||{}),me=(u=>(u.canny="canny",u.depth="depth",u.mlsd="mlsd",u.normalbae="normalbae",u.openpose="openpose",u.tile="tile",u.seg="seg",u.lineart="lineart",u.lineart_anime="lineart_anime",u.shuffle="shuffle",u.scribble="scribble",u.softedge="softedge",u))(me||{}),Ie=(T=>(T.canny="canny",T.depth_leres="depth_leres",T.depth_midas="depth_midas",T.depth_zoe="depth_zoe",T.inpaint_global_harmonious="inpaint_global_harmonious",T.lineart_anime="lineart_anime",T.lineart_coarse="lineart_coarse",T.lineart_realistic="lineart_realistic",T.lineart_standard="lineart_standard",T.mlsd="mlsd",T.normal_bae="normal_bae",T.scribble_hed="scribble_hed",T.scribble_pidinet="scribble_pidinet",T.seg_ofade20k="seg_ofade20k",T.seg_ofcoco="seg_ofcoco",T.seg_ufade20k="seg_ufade20k",T.shuffle="shuffle",T.softedge_hed="softedge_hed",T.softedge_hedsafe="softedge_hedsafe",T.softedge_pidinet="softedge_pidinet",T.softedge_pidisafe="softedge_pidisafe",T.tile_gaussian="tile_gaussian",T.openpose="openpose",T.openpose_face="openpose_face",T.openpose_faceonly="openpose_faceonly",T.openpose_full="openpose_full",T.openpose_hand="openpose_hand",T))(Ie||{}),Xe=(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))(Xe||{}),Je=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Je||{}),Ze=(c=>(c.flux1d="flux1d",c.flux1s="flux1s",c.pony="pony",c.sdhyper="sdhyper",c.sd1x="sd1x",c.sd1xlcm="sd1xlcm",c.sd3="sd3",c.sdxl="sdxl",c.sdxllcm="sdxllcm",c.sdxldistilled="sdxldistilled",c.sdxlhyper="sdxlhyper",c.sdxllightning="sdxllightning",c.sdxlturbo="sdxlturbo",c))(Ze||{}),Ye=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ye||{}),$e=(U=>(U.canny="canny",U.depth="depth",U.qrcode="qrcode",U.hed="hed",U.scrible="scrible",U.openpose="openpose",U.seg="segmentation",U.openmlsd="openmlsd",U.softedge="softedge",U.normal="normal bae",U.shuffle="shuffle",U.pix2pix="pix2pix",U.inpaint="inpaint",U.lineart="line art",U.sketch="sketch",U.inpaintdepth="inpaint depth",U.tile="tile",U.outfit="outfit",U.blur="blur",U.gray="gray",U.lowquality="low quality",U))($e||{}),et=(g=>(g.NoStyle="No style",g.Cinematic="Cinematic",g.DisneyCharacter="Disney Character",g.DigitalArt="Digital Art",g.Photographic="Photographic",g.FantasyArt="Fantasy art",g.Neonpunk="Neonpunk",g.Enhance="Enhance",g.ComicBook="Comic book",g.Lowpoly="Lowpoly",g.LineArt="Line art",g))(et||{});import{v4 as tt,validate as nt}from"uuid";var K=6e4,q=1e3,ye=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},he=(l,e)=>{if(l==null)return;let t=l.indexOf(e);t!==-1&&l.splice(t,1)},M=(l,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))},s)})),Ue=l=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(l),t.onload=function(){e(t.result)}}),D=()=>tt(),Te=l=>nt(l);var be=({key:l,data:e,useZero:t=!0,shouldReturnString:n=!1})=>l.split(/\.|\[/).map(a=>a.replace(/\]$/,"")).reduce((a,i)=>{let o=t?0:void 0,p=a?.[i];if(!p)return o;if(Array.isArray(p)&&/^\d+$/.test(i)){let m=parseInt(i,10);return m>=0&&m<p.length?a[i]=p[m]:a[i]??o}else return a[i]??o},e||{})??{},fe=(l,e=1e3)=>new Promise(t=>setTimeout(t,l*e));var Re=(l,e)=>l.filter(t=>t.key!==e.key);var R=({key:l,value:e})=>e||e===0||e===!1?{[l]:e}:{},st=(l,e)=>Math.floor(Math.random()*(e-l+1))+l,ke=()=>st(1,Number.MAX_SAFE_INTEGER),De=(l,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((r,a)=>{let i=setTimeout(()=>{o&&(clearInterval(o),n&&a(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),o=setInterval(async()=>{try{await l({resolve:r,reject:a,intervalId:o})&&(clearInterval(o),clearTimeout(i))}catch(p){clearInterval(o),clearTimeout(i),a(p)}},s)}));var x=async(l,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await l()}catch(r){if(n?.(),r?.error)throw r;if(s--,s>0)await fe(t),await x(l,{...e,maxRetries:s});else throw r}};var C=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:r=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=e=>{this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Te(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await Ue(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:s,outputType:r,outputFormat:a,highThresholdCanny:i,lowThresholdCanny:o,includeHandsAndFaceOpenPose:p,includeCost:m,outputQuality:g,customTaskUUID:u,taskUUID:c,retry:d,includeGenerationTime:I,includePayload:h})=>{let b=d||this._globalMaxRetries,f,y=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let U=c||u||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:U,preProcessorType:t,...R({key:"height",value:n}),...R({key:"width",value:s}),...R({key:"outputType",value:r}),...R({key:"outputFormat",value:a}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:i}),...R({key:"lowThresholdCanny",value:o}),...R({key:"includeHandsAndFaceOpenPose",value:p}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:U});let A=await M(({resolve:S,reject:B})=>{let v=this.getSingleMessage({taskUUID:U});if(v){if(v?.error)return B(v),!0;if(v)return S(v),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return f.destroy(),this.insertAdditionalResponse({response:A,payload:h?w:void 0,startTime:I?y:void 0}),A},{maxRetries:b,callback:()=>{f?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:s,taskUUID:r,retry:a,includePayload:i,includeGenerationTime:o,deliveryMethod:p,skipResponse:m,model:g})=>{try{let u;e&&(u=await this.uploadImage(e));let d={taskUUID:r||s||D(),taskType:"caption",model:g,inputImage:u?.imageUUID,inputs:t,...R({key:"includeCost",value:n}),retry:a,includePayload:i,includeGenerationTime:o},I=await this.baseSingleRequest({payload:{...d,taskType:"caption"},debugKey:"caption"});if(m)return I;if(p==="async"){let h=I?.taskUUID;return(await this.pollForAsyncResults({taskUUID:h}))[0]}return I}catch(u){throw u}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,r=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return r;if(s==="async"){let a=r?.taskUUID;return(await this.pollForAsyncResults({taskUUID:a}))[0]}return r}catch(s){throw s}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:s,...r}=e;try{let a=await this.baseSingleRequest({payload:{...r,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return a;let i=a?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(a){throw a}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let a=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...s,numberResults:s.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return a;let i=a?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):a}catch(r){throw r}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:s,outputType:r,outputFormat:a,includeCost:i,outputQuality:o,customTaskUUID:p,taskUUID:m,retry:g,includeGenerationTime:u,includePayload:c,skipResponse:d,deliveryMethod:I})=>{try{let h;e&&(h=await this.uploadImage(e));let f={taskUUID:m||p||D(),inputImage:h?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:s,...R({key:"includeCost",value:i}),...r?{outputType:r}:{},...o?{outputQuality:o}:{},...a?{outputFormat:a}:{},includePayload:c,includeGenerationTime:u,retry:g,deliveryMethod:I},y=await this.baseSingleRequest({payload:{...f,taskType:"upscale"},debugKey:"upscale"});if(d)return y;if(I==="async"){let k=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return y}catch(h){throw h}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:r,taskUUID:a,retry:i,includeGenerationTime:o,includePayload:p})=>{let m=i||this._globalMaxRetries,g,u=Date.now();try{return await x(async()=>{await this.ensureConnection();let c=a||r||D(),d={prompt:e,taskUUID:c,promptMaxLength:t,promptVersions:n,...R({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(d),g=this.globalListener({taskUUID:c});let I=await M(({resolve:h,reject:b})=>{let f=this._globalMessages[c];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[c],h(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:I,payload:p?d:void 0,startTime:o?u:void 0}),I},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(c){throw c}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:r,...a}=e,i=n||this._globalMaxRetries,o;try{return await x(async()=>{await this.ensureConnection();let p=r||s||D();this.send({...a,taskUUID:p,taskType:"modelUpload"});let m,g;return o=this.listenToUpload({taskUUID:p,onUploadStream:(c,d)=>{t?.(c,d),c?.status==="ready"?m=c:d&&(g=d)}}),await M(({resolve:c,reject:d})=>{if(m)return c(m),!0;if(g)return d(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:i,callback:()=>{o?.destroy()}})}catch(p){throw p}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:r,taskUUID:a,numberResults:i,includeGenerationTime:o,includePayload:p,...m}=e,g=s||this._globalMaxRetries,u,c=[],d=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),d++;let h=this._globalImages.filter(U=>c.includes(U.taskUUID)),b=a||r||D();c.push(b);let f=i-h.length,y={...m,...m.seed?{seed:m.seed}:{seed:ke()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:i};this.send({...y,numberResults:f}),u=this.listenToResponse({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:p?y:void 0,startTime:o?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:c,numberResults:i,lis:u});return u.destroy(),k},{maxRetries:g,callback:()=>{u?.destroy()}})}catch(h){if(h.taskUUID)throw h;if(d>=g)return this.handleIncompleteImages({taskUUIDs:c,error:h})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:s,customTaskUUID:r,taskUUID:a,includePayload:i,includeGenerationTime:o,...p}=e,m=s||this._globalMaxRetries,g,u=Date.now();try{return await x(async()=>{await this.ensureConnection();let c=a||r||D(),d={...p,taskUUID:c};this.send(d),g=this.globalListener({taskUUID:c});let I=await M(({resolve:h,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:c}):this.getSingleMessage({taskUUID:c});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[c],h(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:I,payload:i?d:void 0,startTime:o?u:void 0}),g.destroy(),I},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(c){throw c}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:r,includePayload:a,numberResults:i=1,onPartialResponse:o,includeGenerationTime:p,...m}=e,g=s||this._globalMaxRetries,u,c=[],d=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),d++;let h=this._globalImages.filter(U=>c.includes(U.taskUUID)),b=r||D();c.push(b);let f=i-h.length,y={...m,taskUUID:b,numberResults:f};if(this.send(y),n)return new Promise((U,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):U(S[b])}})});u=this.listenToResponse({onPartialImages:o,taskUUID:b,groupKey:t,requestPayload:a?y:void 0,startTime:p?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:c,numberResults:i,lis:u});return u.destroy(),k},{maxRetries:g,callback:()=>{u?.destroy()}})}catch(h){throw h}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let s=e;s.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._shouldReconnect=!1,this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=s,this._timeoutDuration=r}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await De(async({resolve:s,reject:r})=>{try{let a=await this.getResponse({taskUUID:e});for(let o of a||[])if(o.status==="success"){let p=this.getUniqueUUID(o);p&&n.set(p,o)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(a){return r(a),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=i=>{let o=Array.isArray(i?.data)?i.data:[i.data],p=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],m=o.filter(u=>(u?.taskUUID||u?.taskType)===n);if(p.filter(u=>(u?.taskUUID||u?.taskType)===n).length){e({error:{...p[0]??{}}});return}if(m.length){e({[n]:o});return}},r={key:n||D(),listener:s,groupKey:t};return this._listeners.push(r),{destroy:()=>{this._listeners=Re(this._listeners,r)}}}connect(){this._ws.onopen=e=>{this._connectionSessionUUID?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})},this._ws.onmessage=e=>{let t=JSON.parse(e.data);for(let n of this._listeners)if(n?.listener?.(t))return},this._ws.onclose=e=>{this.isInvalidAPIKey()}}destroy(e){he(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:s,startTime:r}){return this.addListener({taskUUID:t,lis:a=>{let i=a?.[t]?.filter(o=>o.taskUUID===t);a.error?(e?.(i,a?.error&&a),this._globalError=a):(i=i.map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o})),e?.(i,a?.error&&a),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(a?.[t]??[]).map(o=>(this.insertAdditionalResponse({response:o,payload:s||void 0,startTime:r||void 0}),{...o}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,r=n?.[t]?.[0],a=r?.taskUUID===t?r:null;(a||s)&&e?.(a||void 0,s)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=be({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(s=>{this._globalMessages[s.taskUUID]=[...this._globalMessages[s.taskUUID]??[],s]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:s,positivePrompt:r,negativePrompt:a,seedImage:i,maskImage:o,strength:p,height:m,width:g,model:u,steps:c,scheduler:d,seed:I,CFGScale:h,clipSkip:b,usePromptWeighting:f,promptWeighting:y,numberResults:k=1,onPartialImages:U,includeCost:w,customTaskUUID:A,taskUUID:S,retry:B,refiner:v,maskMargin:T,outputQuality:Y,controlNet:G,lora:$,embeddings:ee,ipAdapters:te,providerSettings:ne,outpaint:se,acceleratorOptions:re,advancedFeatures:ae,referenceImages:oe,includeGenerationTime:Me,includePayload:Ce,...ie},Oe){let O,le,P=[],ue=0,ce=B||this._globalMaxRetries;try{await this.ensureConnection();let E=null,H=null,Q=[];if(i){let _=await this.uploadImage(i);if(!_)return[];E=_.imageUUID}if(o){let _=await this.uploadImage(o);if(!_)return[];H=_.imageUUID}if(G?.length)for(let _=0;_<G.length;_++){let N=G[_],{endStep:z,startStep:L,weight:j,guideImage:F,controlMode:Pe,startStepPercentage:Le,endStepPercentage:Fe,model:qe}=N,Ke=F?await this.uploadImage(F):null;Q.push({guideImage:Ke?.imageUUID,model:qe,endStep:z,startStep:L,weight:j,...R({key:"startStepPercentage",value:Le}),...R({key:"endStepPercentage",value:Fe}),controlMode:Pe||"controlnet"})}le={taskType:"imageInference",model:u,positivePrompt:r,...a?{negativePrompt:a}:{},...m?{height:m}:{},...g?{width:g}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},...R({key:"checkNSFW",value:s}),...R({key:"strength",value:p}),...R({key:"CFGScale",value:h}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:c}),...y?{promptWeighting:y}:{},...I?{seed:I}:{},...d?{scheduler:d}:{},...v?{refiner:v}:{},...se?{outpaint:se}:{},...R({key:"includeCost",value:w}),...E?{seedImage:E}:{},...H?{maskImage:H}:{},...Y?{outputQuality:Y}:{},...Q.length?{controlNet:Q}:{},...$?.length?{lora:$}:{},...ee?.length?{embeddings:ee}:{},...te?.length?{ipAdapters:te}:{},...ne?{providerSettings:ne}:{},...re?{acceleratorOptions:re}:{},...ae?{advancedFeatures:ae}:{},...oe?.length?{referenceImages:oe}:{},...ie,...Oe??{}};let Ne=Date.now();return await x(async()=>{ue++,O?.destroy();let _=this._globalImages.filter(F=>P.includes(F.taskUUID)),N=S||A||D();P.push(N);let z=k-_.length,L={...le,taskUUID:N,numberResults:z};this.send(L),O=this.listenToResponse({onPartialImages:U,taskUUID:N,groupKey:"REQUEST_IMAGES",requestPayload:Ce?L:void 0,startTime:Me?Ne:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:P,numberResults:k,lis:O,deliveryMethod:ie.deliveryMethod});return O.destroy(),j},{maxRetries:ce,callback:()=>{O?.destroy()}})}catch(E){if(ue>=ce)return this.handleIncompleteImages({taskUUIDs:P,error:E});throw E}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((s,r)=>{let a=0,i=30,o=D(),p,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(p),clearInterval(m)};this._sdkType==="SERVER"&&(p=setInterval(async()=>{try{let u=this.connected(),c=!1;(!this.ensureConnectionUUID||o===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=o),c=!0);let d=a%10===0&&c;u?(g(),s(!0)):a>=i?(g(),r(new Error("Retry timed out"))):(d&&this.connect(),a++)}catch(u){g(),r(u)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),r(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s,deliveryMethod:r}){return await M(({resolve:a,reject:i,intervalId:o})=>{let p=Array.isArray(e)?e:[e],m=this._globalImages.filter(u=>p.includes(u.taskUUID)),g=r==="async"&&m.length>0;if(this._globalError){let u=this._globalError;return this._globalError=void 0,clearInterval(o),i?.(u),!0}else if(m.length>=t||g)return clearInterval(o),this._globalImages=this._globalImages.filter(u=>!p.includes(u.taskUUID)),a([...m].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(s=>e.includes(s.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(s=>!e.includes(s.taskUUID)),n;throw t}};var Ae=je(we(),1),W=class extends C{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ae.default(this._url),this.connect()}};import ct from"ws";var V=class extends C{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this.send=t=>{this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){this._url&&(this.resetConnection(),this._ws=new ct(this._url,{perMessageDeflate:!1}),this._ws.on("error",()=>{}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._connectionSessionUUID&&this.isWebsocketReadyState()?this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&this.send({apiKey:this._apiKey,taskType:"authentication"}),this.addListener({taskUUID:"authentication",lis:t=>{if(t?.error){this._connectionError=t;return}this._connectionSessionUUID=t?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0}})}),this._ws.on("message",(t,n)=>{let s=n?t:t?.toString();if(!s)return;let r=JSON.parse(s);this._listeners.forEach(a=>{a.listener(r)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var Ee;typeof window>"u"?Ee=V:Ee=W;export{ge as EControlMode,Ze as EModelArchitecture,$e as EModelConditioning,Je as EModelFormat,Ye as EModelType,Xe as EOpenPosePreProcessor,et as EPhotoMakerEnum,Ie as EPreProcessor,me as EPreProcessorGroup,J as ETaskType,pe as Environment,Ee as Runware,W as RunwareClient,V as RunwareServer,X as SdkType};
|
|
1
|
+
var He=Object.create;var me=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Xe=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Je=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ze(e))!je.call(a,o)&&o!==t&&me(a,o,{get:()=>e[o],enumerable:!(n=Qe(e,o))||n.enumerable});return a};var Ze=(a,e,t)=>(t=a!=null?He(Ye(a)):{},Je(e||!a||!a.__esModule?me(t,"default",{value:a,enumerable:!0}):t,a));var Oe=Xe((Ln,Le)=>{"use strict";var Ae=a=>a&&a.CLOSING===2,mt=()=>typeof WebSocket<"u"&&Ae(WebSocket),It=()=>({constructor:mt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ht=(a,e,t)=>{Object.defineProperty(e,t,{get:()=>a[t],set:n=>{a[t]=n},enumerable:!0,configurable:!0})},we=a=>a.minReconnectionDelay+Math.random()*a.minReconnectionDelay,yt=(a,e)=>{let t=e*a.reconnectionDelayGrowFactor;return t>a.maxReconnectionDelay?a.maxReconnectionDelay:t},bt=["onopen","onclose","onmessage","onerror"],Ut=(a,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([o,s])=>{a.addEventListener(n,o,s)})}),e&&bt.forEach(n=>{a[n]=e[n]})},Ce=function(a,e,t={}){let n,o,s=0,r=0,i=!0,l={};if(!(this instanceof Ce))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=It();if(Object.keys(d).filter(p=>t.hasOwnProperty(p)).forEach(p=>d[p]=t[p]),!Ae(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let c=d.debug?(...p)=>console.log("RWS:",...p):()=>{},m=(p,I)=>setTimeout(()=>{let y=new Error(I);y.code=p,Array.isArray(l.error)&&l.error.forEach(([T])=>T(y)),n.onerror&&n.onerror(y)},0),g=()=>{if(c("close"),r++,c("retries count:",r),r>d.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}s?s=yt(d,s):s=we(d),c("reconnectDelay:",s),i&&setTimeout(u,s)},u=()=>{c("connect");let p=n;n=new d.constructor(a,e),o=setTimeout(()=>{c("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},d.connectionTimeout),c("bypass properties");for(let I in n)["addEventListener","removeEventListener","close","send"].indexOf(I)<0&&ht(n,this,I);n.addEventListener("open",()=>{clearTimeout(o),c("open"),s=we(d),c("reconnectDelay:",s),r=0}),n.addEventListener("close",g),Ut(n,p,l)};c("init"),u(),this.close=(p=1e3,I="",{keepClosed:y=!1,fastClose:T=!0,delay:R=0}={})=>{if(R&&(s=R),i=!y,n.close(p,I),T){let h={code:p,reason:I,wasClean:!0};g(),Array.isArray(l.close)&&l.close.forEach(([k,b])=>{k(h),n.removeEventListener("close",k,b)}),n.onclose&&(n.onclose(h),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,I,y)=>{Array.isArray(l[p])?l[p].some(([T])=>T===I)||l[p].push([I,y]):l[p]=[[I,y]],n.addEventListener(p,I,y)},this.removeEventListener=(p,I,y)=>{Array.isArray(l[p])&&(l[p]=l[p].filter(([T])=>T!==I)),n.removeEventListener(p,I,y)}};Le.exports=Ce});var Ie=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(Ie||{}),X=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(X||{}),J=(h=>(h.IMAGE_INFERENCE="imageInference",h.IMAGE_UPLOAD="imageUpload",h.UPSCALE="upscale",h.REMOVE_BACKGROUND="removeBackground",h.VIDEO_INFERENCE="videoInference",h.CAPTION="caption",h.AUDIO_INFERENCE="audioInference",h.THREE_D_INFERENCE="3dInference",h.GET_RESPONSE="getResponse",h.PHOTO_MAKER="photoMaker",h.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",h.IMAGE_MASKING="imageMasking",h.PROMPT_ENHANCE="promptEnhance",h.AUTHENTICATION="authentication",h.MODEL_UPLOAD="modelUpload",h.MODEL_SEARCH="modelSearch",h.MEDIA_STORAGE="mediaStorage",h.VECTORIZE="vectorize",h.TEXT_INFERENCE="textInference",h))(J||{}),he=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(he||{}),ye=(g=>(g.canny="canny",g.depth="depth",g.mlsd="mlsd",g.normalbae="normalbae",g.openpose="openpose",g.tile="tile",g.seg="seg",g.lineart="lineart",g.lineart_anime="lineart_anime",g.shuffle="shuffle",g.scribble="scribble",g.softedge="softedge",g))(ye||{}),be=(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))(be||{}),et=(s=>(s.openpose="openpose",s.openpose_face="openpose_face",s.openpose_faceonly="openpose_faceonly",s.openpose_full="openpose_full",s.openpose_hand="openpose_hand",s))(et||{}),tt=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(tt||{}),nt=(u=>(u.flux1d="flux1d",u.flux1s="flux1s",u.pony="pony",u.sdhyper="sdhyper",u.sd1x="sd1x",u.sd1xlcm="sd1xlcm",u.sd3="sd3",u.sdxl="sdxl",u.sdxllcm="sdxllcm",u.sdxldistilled="sdxldistilled",u.sdxlhyper="sdxlhyper",u.sdxllightning="sdxllightning",u.sdxlturbo="sdxlturbo",u))(nt||{}),st=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(st||{}),rt=(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))(rt||{}),ot=(m=>(m.NoStyle="No style",m.Cinematic="Cinematic",m.DisneyCharacter="Disney Character",m.DigitalArt="Digital Art",m.Photographic="Photographic",m.FantasyArt="Fantasy art",m.Neonpunk="Neonpunk",m.Enhance="Enhance",m.ComicBook="Comic book",m.Lowpoly="Lowpoly",m.LineArt="Line art",m))(ot||{});import{v4 as it,validate as at}from"uuid";var B=6e4,K=1e3,Ue=100,Z={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},Te=(a,e)=>{if(a==null)return;let t=a.indexOf(e);t!==-1&&a.splice(t,1)},L=(a,{debugKey:e="debugKey",timeoutDuration:t=B,shouldThrowError:n=!0,pollingInterval:o=Ue})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&clearInterval(l),clearTimeout(i),n?r(`Response could not be received from server for ${e}`):s(void 0)},t),l=setInterval(async()=>{try{a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(d){clearInterval(l),clearTimeout(i),r(d)}},o)})),fe=a=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(a),t.onload=function(){e(t.result)}}),D=()=>it(),Re=a=>at(a);var _e=({key:a,data:e,useZero:t=!0,shouldReturnString:n=!1})=>a.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,i)=>{let l=t?0:void 0,d=r?.[i];if(!d)return l;if(Array.isArray(d)&&/^\d+$/.test(i)){let c=parseInt(i,10);return c>=0&&c<d.length?r[i]=d[c]:r[i]??l}else return r[i]??l},e||{})??{},ke=(a,e=1e3)=>new Promise(t=>setTimeout(t,a*e));var De=(a,e)=>a.filter(t=>t.key!==e.key);var _=({key:a,value:e})=>e||e===0||e===!1?{[a]:e}:{},lt=(a,e)=>Math.floor(Math.random()*(e-a+1))+a,ve=()=>lt(1,Number.MAX_SAFE_INTEGER),xe=(a,{debugKey:e="debugKey",timeoutDuration:t=B,shouldThrowError:n=!0,pollingInterval:o=Ue})=>(t=t<K?K:t,new Promise((s,r)=>{let i=setTimeout(()=>{l&&(clearInterval(l),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(i)},t),l=setInterval(async()=>{try{await a({resolve:s,reject:r,intervalId:l})&&(clearInterval(l),clearTimeout(i))}catch(d){clearInterval(l),clearTimeout(i),r(d)}},o)}));var x=async(a,e={})=>{let{delayInSeconds:t=1,callback:n,logger:o}=e,s=e.maxRetries??1,r=s;if(s<=0)return await a();for(;s;)try{let i=await a();return s<r&&o?.retrySuccess(r-s+1),i}catch(i){if(i?.error)throw o?.retrySkippedApiError(i.error?.code||"unknown"),i;if(n?.(),s--,s>0)return o?.retryAttempt(r-s,r,t*1e3),await ke(t),await x(a,{...e,maxRetries:s});throw o?.retryExhausted(r),i}};var U={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",black:"\x1B[30m",white:"\x1B[37m",gray:"\x1B[90m",green:"\x1B[92m",yellow:"\x1B[93m",blue:"\x1B[94m",magenta:"\x1B[95m",cyan:"\x1B[96m",red:"\x1B[91m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgRed:"\x1B[41m",bgWhite:"\x1B[47m"},Ee=(c=>(c.CONNECTION="CONNECTION",c.AUTH="AUTH",c.HEARTBEAT="HEARTBEAT",c.SEND="SEND",c.RECEIVE="RECEIVE",c.RETRY="RETRY",c.REQUEST="REQUEST",c.ERROR="ERROR",c.WARN="WARN",c.INFO="INFO",c))(Ee||{}),Se={CONNECTION:{bg:U.bgBlue,fg:U.blue,icon:"\u{1F50C}"},AUTH:{bg:U.bgGreen,fg:U.green,icon:"\u{1F511}"},HEARTBEAT:{bg:U.bgMagenta,fg:U.magenta,icon:"\u{1F493}"},SEND:{bg:U.bgCyan,fg:U.cyan,icon:"\u{1F4E4}"},RECEIVE:{bg:U.bgCyan,fg:U.cyan,icon:"\u{1F4E5}"},RETRY:{bg:U.bgYellow,fg:U.yellow,icon:"\u{1F504}"},REQUEST:{bg:U.bgBlue,fg:U.blue,icon:"\u{1F4E1}"},ERROR:{bg:U.bgRed,fg:U.red,icon:"\u274C"},WARN:{bg:U.bgYellow,fg:U.yellow,icon:"\u26A0\uFE0F"},INFO:{bg:U.bgWhite,fg:U.gray,icon:"\u2139\uFE0F"}},ut=`${U.bold}${U.magenta}[RUNWARE]${U.reset}`;function ct(){return`${U.dim}${new Date().toISOString()}${U.reset}`}function gt(a){return`${Se[a].bg}${U.bold}${U.black} ${a} ${U.reset}`}function dt(a){if(a==null)return"";if(typeof a=="string")return`${U.dim}${a}${U.reset}`;try{let e=JSON.stringify(a,null,2);return`${U.dim}${e}${U.reset}`}catch{return`${U.dim}[unserializable]${U.reset}`}}var P=class{constructor(e=!1){this.enabled=e}log(e,t,n){if(!this.enabled)return;let o=Se[e],s=["",`${ut} ${gt(e)} ${o.icon} ${o.fg}${U.bold}${t}${U.reset}`,` ${ct()}`];n!==void 0&&s.push(` ${dt(n)}`),s.push(""),e==="ERROR"?console.error(s.join(`
|
|
2
|
+
`)):e==="WARN"?console.warn(s.join(`
|
|
3
|
+
`)):console.log(s.join(`
|
|
4
|
+
`))}connecting(e){this.log("CONNECTION","Connecting to WebSocket",{url:e})}connected(e){this.log("CONNECTION","WebSocket connection established",{connectionSessionUUID:e})}reconnecting(e){this.log("CONNECTION",`Reconnecting... attempt #${e}`)}reconnectScheduled(e){this.log("CONNECTION",`Reconnect scheduled in ${e}ms`)}disconnected(e){this.log("CONNECTION",`WebSocket disconnected${e?`: ${e}`:""}`)}connectionClosed(e){this.log("CONNECTION","WebSocket closed",{code:e})}connectionError(e){this.log("ERROR","WebSocket error",e)}ensureConnectionStart(){this.log("CONNECTION","Connection lost \u2014 waiting for reconnection...")}ensureConnectionSuccess(){this.log("CONNECTION","Reconnection successful")}ensureConnectionTimeout(){this.log("ERROR","Reconnection timed out after max retries")}authenticating(e){this.log("AUTH",e?"Re-authenticating with existing session":"Authenticating with API key")}authenticated(e){this.log("AUTH","Authentication successful",{connectionSessionUUID:e})}authError(e){this.log("ERROR","Authentication failed",e)}heartbeatStarted(e){this.log("HEARTBEAT",`Heartbeat started \u2014 ping every ${e/1e3}s, 3 missed pongs before close`)}heartbeatPingSent(){this.log("HEARTBEAT","Ping sent")}heartbeatPongReceived(){this.log("HEARTBEAT","Pong received \u2014 connection alive")}heartbeatPongMissed(e,t){this.log("WARN",`Pong missed (${e}/${t}) \u2014 ${e>=t?"connection dead, terminating":"will retry next cycle"}`)}heartbeatStopped(){this.log("HEARTBEAT","Heartbeat stopped")}messageSent(e,t){this.log("SEND","Message sent",{taskType:e,...t?{taskUUID:t}:{}})}messageReceived(e,t){this.log("RECEIVE","Message received",{...e?{taskType:e}:{},...t?{taskUUID:t}:{}})}sendReconnecting(){this.log("WARN","Send failed \u2014 WebSocket not ready, attempting reconnection before retry")}sendFailed(e){this.log("ERROR",`Send failed \u2014 ${e}`)}requestStart(e,t){this.log("REQUEST","Request started",{taskType:e,taskUUID:t})}requestComplete(e,t,n){this.log("REQUEST",`Request complete in ${n}ms`,{taskType:e,taskUUID:t})}requestTimeout(e,t){this.log("ERROR",`Request timed out after ${t}ms`,{taskUUID:e})}requestError(e,t){this.log("ERROR","Request failed",{taskUUID:e,error:t?.message||t?.error||t})}retryAttempt(e,t,n){this.log("RETRY",`Retry ${e}/${t} \u2014 waiting ${n}ms before next attempt`)}retrySuccess(e){this.log("RETRY",`Retry succeeded on attempt #${e}`)}retryExhausted(e){this.log("ERROR",`All ${e} retries exhausted \u2014 giving up`)}retrySkippedApiError(e){this.log("ERROR","API error \u2014 skipping retry (not retryable)",{code:e})}info(e,t){this.log("INFO",e,t)}warn(e,t){this.log("WARN",e,t)}error(e,t){this.log("ERROR",e,t)}},pt=new P(!1);function ee(a){return a?new P(!0):pt}var O=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:o=2,timeoutDuration:s=B,heartbeatInterval:r=45e3,enableLogging:i=!1}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];this._heartbeatIntervalId=null;this._pongTimeoutId=null;this._missedPongCount=0;this._maxMissedPongs=3;this.ensureConnectionUUID=null;this.isWebsocketReadyState=()=>this._ws?.readyState===1;this.isInvalidAPIKey=()=>this._connectionError?.error?.code==="invalidApiKey";this.send=async e=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let t=e?.taskType,n=e?.taskUUID;this._logger.messageSent(t,n),this._ws.send(JSON.stringify([e]))};this.uploadImage=async e=>{try{return await x(async()=>{let t=D();if(typeof e=="string"&&Re(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await fe(e);return{imageURL:n,imageUUID:n,taskUUID:t,taskType:"imageUpload"}})}catch(t){throw t}};this.controlNetPreProcess=async({inputImage:e,preProcessorType:t,height:n,width:o,outputType:s,outputFormat:r,highThresholdCanny:i,lowThresholdCanny:l,includeHandsAndFaceOpenPose:d,includeCost:c,outputQuality:m,customTaskUUID:g,taskUUID:u,retry:p,includeGenerationTime:I,includePayload:y})=>{let T=p||this._globalMaxRetries,R,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let b=u||g||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:b,preProcessorType:t,..._({key:"height",value:n}),..._({key:"width",value:o}),..._({key:"outputType",value:s}),..._({key:"outputFormat",value:r}),..._({key:"includeCost",value:c}),..._({key:"highThresholdCanny",value:i}),..._({key:"lowThresholdCanny",value:l}),..._({key:"includeHandsAndFaceOpenPose",value:d}),...m?{outputQuality:m}:{}};await this.send({...w}),R=this.globalListener({taskUUID:b});let A=await L(({resolve:E,reject:$})=>{let S=this.getSingleMessage({taskUUID:b});if(S){if(S?.error)return $(S),!0;if(S)return E(S),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return R.destroy(),this.insertAdditionalResponse({response:A,payload:y?w:void 0,startTime:I?h:void 0}),A},{maxRetries:T,callback:()=>{R?.destroy()}})}catch(k){throw k}};this.controlNetPreprocess=async e=>this.controlNetPreProcess(e);this.requestImageToText=async({inputImage:e,inputs:t,includeCost:n,customTaskUUID:o,taskUUID:s,retry:r,includePayload:i,includeGenerationTime:l,deliveryMethod:d,skipResponse:c,model:m})=>{try{let g;e&&(g=await this.uploadImage(e));let p={taskUUID:s||o||D(),taskType:"caption",model:m,inputImage:g?.imageUUID,inputs:t,..._({key:"includeCost",value:n}),retry:r,includePayload:i,includeGenerationTime:l},I=await this.baseSingleRequest({payload:{...p,taskType:"caption"},debugKey:"caption"});if(c)return I;if(d==="async"){let y=I?.taskUUID;return(await this.pollForAsyncResults({taskUUID:y}))[0]}return I}catch(g){throw g}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let o=n.deliveryMethod,s=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return s;if(o==="async"){let r=s?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return s}catch(o){throw o}};this.removeBackground=async e=>this.removeImageBackground(e);this.vectorize=async e=>this.baseSingleRequest({payload:{...e,taskType:"vectorize"},debugKey:"vectorize"});this.videoInference=async e=>{let{skipResponse:t,inputAudios:n,referenceVideos:o,...s}=e;try{let r=await this.baseSingleRequest({payload:{...s,...n?.length&&{inputAudios:n},...o?.length&&{referenceVideos:o},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let i=r?.taskUUID;return this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"audioInference",deliveryMethod:n},groupKey:"REQUEST_AUDIO",debugKey:"audio-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"3dInference",deliveryMethod:n},groupKey:"REQUEST_IMAGES",debugKey:"three-d-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...o}=e;try{let r=await(n==="sync"?this.baseSyncRequest:this.baseSingleRequest)({payload:{...o,numberResults:o.numberResults||1,taskType:"textInference",deliveryMethod:n},groupKey:"REQUEST_TEXT",debugKey:"text-inference",skipResponse:t});if(t)return r;let i=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:i,numberResults:e?.numberResults}):r}catch(s){throw s}};this.getResponse=async e=>{let t=e.taskUUID;return this.baseSingleRequest({payload:{...e,customTaskUUID:t,taskType:"getResponse"},isMultiple:!0,debugKey:"async-results"})};this.upscaleGan=async({inputImage:e,inputs:t,model:n,upscaleFactor:o,outputType:s,outputFormat:r,includeCost:i,outputQuality:l,customTaskUUID:d,taskUUID:c,retry:m,includeGenerationTime:g,includePayload:u,skipResponse:p,deliveryMethod:I})=>{try{let y;e&&(y=await this.uploadImage(e));let R={taskUUID:c||d||D(),inputImage:y?.imageUUID,taskType:"upscale",inputs:t,model:n,upscaleFactor:o,..._({key:"includeCost",value:i}),...s?{outputType:s}:{},...l?{outputQuality:l}:{},...r?{outputFormat:r}:{},includePayload:u,includeGenerationTime:g,retry:m,deliveryMethod:I},h=await this.baseSingleRequest({payload:{...R,taskType:"upscale"},debugKey:"upscale"});if(p)return h;if(I==="async"){let k=h?.taskUUID;return(await this.pollForAsyncResults({taskUUID:k}))[0]}return h}catch(y){throw y}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:o,customTaskUUID:s,taskUUID:r,retry:i,includeGenerationTime:l,includePayload:d})=>{let c=i||this._globalMaxRetries,m,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={prompt:e,taskUUID:u,promptMaxLength:t,promptVersions:n,..._({key:"includeCost",value:o}),taskType:"promptEnhance"};await this.send(p),m=this.globalListener({taskUUID:u});let I=await L(({resolve:y,reject:T})=>{let R=this._globalMessages[u];if(R?.error)return T(R),!0;if(R?.length>=n)return delete this._globalMessages[u],y(R),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:I,payload:d?p:void 0,startTime:l?g:void 0}),I},{maxRetries:c,callback:()=>{m?.destroy()}})}catch(u){throw u}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:o,taskUUID:s,...r}=e,i=n||this._globalMaxRetries,l;try{return await x(async()=>{await this.ensureConnection();let d=s||o||D();await this.send({...r,taskUUID:d,taskType:"modelUpload"});let c,m;l=this.listenToUpload({taskUUID:d,onUploadStream:(u,p)=>{t?.(u,p),u?.status==="ready"?c=u:p&&(m=p)}});let g=await L(({resolve:u,reject:p})=>{if(c)return u(c),!0;if(m)return p(m),!0},{shouldThrowError:!1,timeoutDuration:60*60*1e3});return l?.destroy(),g},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:o,customTaskUUID:s,taskUUID:r,numberResults:i,includeGenerationTime:l,includePayload:d,...c}=e,m=o||this._globalMaxRetries,g,u=[],p=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let y=this._globalImages.filter(b=>u.includes(b.taskUUID)),T=r||s||D();u.push(T);let R=i-y.length,h={...c,...c.seed?{seed:c.seed}:{seed:ve()},...t??{},taskUUID:T,taskType:"photoMaker",numberResults:i};await this.send({...h,numberResults:R}),g=this.listenToResponse({onPartialImages:n,taskUUID:T,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:l?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:g});return g.destroy(),k},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(y){if(y.taskUUID)throw y;if(p>=m)return this.handleIncompleteImages({taskUUIDs:u,error:y})}};this.modelSearch=async e=>this.baseSingleRequest({payload:{...e,taskType:"modelSearch"},debugKey:"model-search"});this.imageMasking=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageMasking"},debugKey:"image-masking"});this.imageUpload=async e=>this.baseSingleRequest({payload:{...e,taskType:"imageUpload"},debugKey:"image-upload"});this.mediaStorage=async e=>this.baseSingleRequest({payload:{...e,operation:e.operation||"upload",taskType:"mediaStorage"},debugKey:"media-storage"});this.baseSingleRequest=async({payload:e,debugKey:t,isMultiple:n})=>{let{retry:o,customTaskUUID:s,taskUUID:r,includePayload:i,includeGenerationTime:l,...d}=e,c=o||this._globalMaxRetries,m,g=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={...d,taskUUID:u};this._logger.requestStart(t,u),await this.send(p),m=this.globalListener({taskUUID:u});let I=await L(({resolve:y,reject:T})=>{let R=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(R){if(R?.error)return this._logger.requestError(u,R),T(R),!0;if(R)return delete this._globalMessages[u],this._logger.requestComplete(t,u,Date.now()-g),y(R),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:I,payload:i?p:void 0,startTime:l?g:void 0}),m.destroy(),I},{maxRetries:c,callback:()=>{m?.destroy()},logger:this._logger})}catch(u){throw u}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:o,customTaskUUID:s,includePayload:r,numberResults:i=1,onPartialResponse:l,includeGenerationTime:d,...c}=e,m=o||this._globalMaxRetries,g,u=[],p=0,I=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let y=this._globalImages.filter(b=>u.includes(b.taskUUID)),T=s||D();u.push(T);let R=i-y.length,h={...c,taskUUID:T,numberResults:R};if(this._logger.requestStart(c.taskType||t,T),await this.send(h),n)return this._logger.info("Async mode (skipResponse) \u2014 waiting for server acknowledgement",{taskUUID:T}),new Promise((b,w)=>{let A=this.addListener({taskUUID:T,groupKey:t,lis:E=>{A.destroy(),E.error?(this._logger.requestError(T,E.error),w(E.error)):(this._logger.requestComplete(c.taskType||t,T,Date.now()-I),b(E[T]))}})});g=this.listenToResponse({onPartialImages:l,taskUUID:T,groupKey:t,requestPayload:r?h:void 0,startTime:d?I:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:g});return this._logger.requestComplete(c.taskType||t,T,Date.now()-I),g.destroy(),k},{maxRetries:m,callback:()=>{g?.destroy()},logger:this._logger})}catch(y){throw y}};this.getSingleMessage=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n?.error?n:t};this.getMultipleMessages=({taskUUID:e})=>{let t=this._globalMessages[e]?.[0],n=this._globalMessages[e];return!t&&!n?null:n};this.insertAdditionalResponse=({response:e,payload:t,startTime:n})=>{if(!t&&!n)return;let o=e;o.additionalResponse={},t&&(e.additionalResponse.payload=t),n&&(e.additionalResponse.generationTime=Date.now()-n)};this.disconnect=async()=>{this._logger.disconnected("user initiated"),this._shouldReconnect=!1,this._connectionSessionUUID=void 0,this.stopHeartbeat(),this._ws?.terminate?.(),this._ws?.close?.()};this.connected=()=>this.isWebsocketReadyState()&&!!this._connectionSessionUUID;this._apiKey=e,this._url=t,this._sdkType="CLIENT",this._shouldReconnect=n,this._globalMaxRetries=o,this._timeoutDuration=s,this._heartbeatInterval=Math.max(1e4,Math.min(12e4,r)),this._logger=ee(i)}getUniqueUUID(e){return e.mediaUUID||e.audioUUID||e.imageUUID||e.videoUUID||e.outputs?.files?.map(t=>t.uuid).join("-")||e.text}async pollForAsyncResults({taskUUID:e,numberResults:t=1}){let n=new Map;return await xe(async({resolve:o,reject:s})=>{try{let r=await this.getResponse({taskUUID:e});for(let l of r||[])if(l.status==="success"){let d=this.getUniqueUUID(l);d&&n.set(d,l)}return n.size===t?(o(Array.from(n.values())),!0):!1}catch(r){return s(r),!0}},{debugKey:"async-response",pollingInterval:2*1e3,timeoutDuration:10*60*1e3}),Array.from(n.values())}static async initialize(e){try{let t=new this(e);return await t.ensureConnection(),t}catch(t){throw t}}startHeartbeat(){this.stopHeartbeat(),this._logger.heartbeatStarted(this._heartbeatInterval),this._heartbeatIntervalId=setInterval(()=>{if(!this.isWebsocketReadyState()){this.stopHeartbeat();return}try{this._ws.send(JSON.stringify([{taskType:"ping",ping:!0}])),this._logger.heartbeatPingSent()}catch{this.stopHeartbeat();return}this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._pongTimeoutId=setTimeout(()=>{this._missedPongCount++,this._logger.heartbeatPongMissed(this._missedPongCount,this._maxMissedPongs),this._missedPongCount>=this._maxMissedPongs&&this._ws&&(typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close())},1e4)},this._heartbeatInterval)}stopHeartbeat(){this._heartbeatIntervalId&&(clearInterval(this._heartbeatIntervalId),this._heartbeatIntervalId=null,this._logger.heartbeatStopped()),this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._missedPongCount=0}handlePongMessage(e){let t=Array.isArray(e?.data)?e.data:[];for(let n of t)if(n?.taskType==="ping"&&n?.pong===!0)return this._missedPongCount=0,this._pongTimeoutId&&(clearTimeout(this._pongTimeoutId),this._pongTimeoutId=null),this._logger.heartbeatPongReceived(),!0;return!1}addListener({lis:e,groupKey:t,taskUUID:n}){let o=i=>{let l=Array.isArray(i?.data)?i.data:[i.data],d=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],c=l.filter(g=>(g?.taskUUID||g?.taskType)===n);if(d.filter(g=>(g?.taskUUID||g?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(c.length){e({[n]:l});return}},s={key:n||D(),listener:o,groupKey:t};return this._listeners.push(s),{destroy:()=>{this._listeners=De(this._listeners,s)}}}connect(){this._logger.connecting(this._url||"unknown"),this._ws.onopen=async e=>{this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})},this._ws.onmessage=e=>{let t;try{t=JSON.parse(e.data)}catch(n){this._logger.error("Failed to parse WebSocket message",n);return}if(!this.handlePongMessage(t)){for(let n of this._listeners)if(n?.listener?.(t))return}},this._ws.onclose=e=>{this._logger.connectionClosed(e?.code),this._connectionSessionUUID=void 0,this.stopHeartbeat(),this.isInvalidAPIKey()},this._ws.onerror=e=>{this._logger.connectionError(e?.message||e)}}destroy(e){Te(this._listeners,e)}listenToResponse({onPartialImages:e,taskUUID:t,groupKey:n,requestPayload:o,startTime:s}){return this.addListener({taskUUID:t,lis:r=>{let i=r?.[t]?.filter(l=>l.taskUUID===t);r.error?(e?.(i,r?.error&&r),this._globalErrors.push(r)):(i=i.map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l})),e?.(i,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(l=>(this.insertAdditionalResponse({response:l,payload:o||void 0,startTime:s||void 0}),{...l}))]:this._globalImages=[...this._globalImages,...i])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let o=n?.error,s=n?.[t]?.[0],r=s?.taskUUID===t?s:null;(r||o)&&e?.(r||void 0,o)}})}globalListener({taskUUID:e}){return this.addListener({taskUUID:e,lis:t=>{if(t.error){this._globalMessages[e]=t;return}let n=_e({key:e,data:t,useZero:!1});Array.isArray(n)?n.forEach(o=>{this._globalMessages[o.taskUUID]=[...this._globalMessages[o.taskUUID]??[],o]}):this._globalMessages[n.taskUUID]=n}})}async requestImages({outputType:e,outputFormat:t,uploadEndpoint:n,checkNSFW:o,positivePrompt:s,negativePrompt:r,seedImage:i,maskImage:l,strength:d,height:c,width:m,model:g,steps:u,scheduler:p,seed:I,CFGScale:y,clipSkip:T,usePromptWeighting:R,promptWeighting:h,numberResults:k=1,onPartialImages:b,includeCost:w,customTaskUUID:A,taskUUID:E,retry:$,refiner:S,maskMargin:f,outputQuality:te,controlNet:H,lora:ne,embeddings:se,ipAdapters:re,providerSettings:oe,outpaint:ie,acceleratorOptions:ae,advancedFeatures:le,referenceImages:ue,includeGenerationTime:Pe,includePayload:Fe,...ce},We){let N,ge,F=[],de=0,pe=$||this._globalMaxRetries;try{await this.ensureConnection();let C=null,Q=null,z=[];if(i){let v=await this.uploadImage(i);if(!v)return[];C=v.imageUUID}if(l){let v=await this.uploadImage(l);if(!v)return[];Q=v.imageUUID}if(H?.length)for(let v=0;v<H.length;v++){let M=H[v],{endStep:Y,startStep:W,weight:j,guideImage:q,controlMode:Ke,startStepPercentage:Be,endStepPercentage:Ve,model:Ge}=M,$e=q?await this.uploadImage(q):null;z.push({guideImage:$e?.imageUUID,model:Ge,endStep:Y,startStep:W,weight:j,..._({key:"startStepPercentage",value:Be}),..._({key:"endStepPercentage",value:Ve}),controlMode:Ke||"controlnet"})}ge={taskType:"imageInference",model:g,positivePrompt:s,...r?{negativePrompt:r}:{},...c?{height:c}:{},...m?{width:m}:{},numberResults:k,...e?{outputType:e}:{},...t?{outputFormat:t}:{},...n?{uploadEndpoint:n}:{},..._({key:"checkNSFW",value:o}),..._({key:"strength",value:d}),..._({key:"CFGScale",value:y}),..._({key:"clipSkip",value:T}),..._({key:"maskMargin",value:f}),..._({key:"usePromptWeighting",value:R}),..._({key:"steps",value:u}),...h?{promptWeighting:h}:{},...I?{seed:I}:{},...p?{scheduler:p}:{},...S?{refiner:S}:{},...ie?{outpaint:ie}:{},..._({key:"includeCost",value:w}),...C?{seedImage:C}:{},...Q?{maskImage:Q}:{},...te?{outputQuality:te}:{},...z.length?{controlNet:z}:{},...ne?.length?{lora:ne}:{},...se?.length?{embeddings:se}:{},...re?.length?{ipAdapters:re}:{},...oe?{providerSettings:oe}:{},...ae?{acceleratorOptions:ae}:{},...le?{advancedFeatures:le}:{},...ue?.length?{referenceImages:ue}:{},...ce,...We??{}};let qe=Date.now();return await x(async()=>{de++,N?.destroy();let v=this._globalImages.filter(q=>F.includes(q.taskUUID)),M=E||A||D();F.push(M);let Y=k-v.length,W={...ge,taskUUID:M,numberResults:Y};await this.send(W),N=this.listenToResponse({onPartialImages:b,taskUUID:M,groupKey:"REQUEST_IMAGES",requestPayload:Fe?W:void 0,startTime:Pe?qe:void 0});let j=await this.getResponseWithSimilarTaskUUID({taskUUID:F,numberResults:k,lis:N,deliveryMethod:ce.deliveryMethod});return N.destroy(),j},{maxRetries:pe,callback:()=>{N?.destroy()}})}catch(C){if(de>=pe)return this.handleIncompleteImages({taskUUIDs:F,error:C});throw C}}async imageInference(e,t){return this.requestImages(e,t)}async ensureConnection(){if(this.connected()||this._url===Z.TEST)return;this._logger.ensureConnectionStart();let t=2e3,n=200;try{if(this.isInvalidAPIKey())throw this._connectionError;return new Promise((o,s)=>{let r=0,i=30,l=D(),d,c,m=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(c)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let g=this.connected(),u=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),u=!0);let p=r%10===0&&u;g?(m(),this._logger.ensureConnectionSuccess(),o(!0)):r>=i?(m(),this._logger.ensureConnectionTimeout(),s(new Error("Retry timed out"))):(p&&(this._logger.reconnecting(r+1),this.connect()),r++)}catch(g){m(),s(g)}},t)),c=setInterval(async()=>{if(this.connected()){m(),this._logger.ensureConnectionSuccess(),o(!0);return}if(this.isInvalidAPIKey()){m(),this._logger.error("Connection failed \u2014 invalid API key"),s(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:o,deliveryMethod:s}){return await L(({resolve:r,reject:i,intervalId:l})=>{let d=Array.isArray(e)?e:[e],c=this._globalImages.filter(u=>d.includes(u.taskUUID)),m=s==="async"&&c.length>0,g=this._globalErrors.filter(u=>d.includes(u.error.taskUUID));if(g.length>0){let u=g[0];return this._globalErrors=this._globalErrors.filter(p=>!d.includes(p.error.taskUUID)),clearInterval(l),i?.(u),!0}else if(c.length>=t||m)return clearInterval(l),this._globalImages=this._globalImages.filter(u=>!d.includes(u.taskUUID)),r([...c].slice(0,t)),!0},{debugKey:"getting images",shouldThrowError:n,timeoutDuration:this._timeoutDuration})}handleIncompleteImages({taskUUIDs:e,error:t}){let n=this._globalImages.filter(o=>e.includes(o.taskUUID));if(n.length>1)return this._globalImages=this._globalImages.filter(o=>!e.includes(o.taskUUID)),n;throw t}};var Ne=Ze(Oe(),1),V=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n),this._ws=new Ne.default(this._url),this.connect()}};import Tt from"ws";var G=class extends O{constructor(t){super(t);this._instantiated=!1;this._listeners=[];this._reconnectingIntervalId=null;this._connecting=!1;this.send=async t=>{if(!this.isWebsocketReadyState()){if(this._logger.sendReconnecting(),this._ws)try{typeof this._ws.terminate=="function"?this._ws.terminate():this._ws.close()}catch{}this._connectionSessionUUID=void 0,await this.ensureConnection()}let n=t?.taskType,o=t?.taskUUID;this._logger.messageSent(n,o),this._ws.send(JSON.stringify([t]))};this.resetConnection=()=>{this.stopHeartbeat(),this._ws&&(this._listeners.forEach(t=>{t?.destroy?.()}),this._ws.removeAllListeners(),this._ws.readyState===1&&(this._ws.terminate(),this._ws.close()),this._ws=null,this._listeners=[])};this._sdkType="SERVER",this.connect()}async connect(){if(this._url&&!this._connecting){this._connecting=!0,this.resetConnection(),this._logger.connecting(this._url);try{this._ws=new Tt(this._url,{perMessageDeflate:!1})}catch(t){this._connecting=!1,this._logger.connectionError(t);return}this._ws.on("error",t=>{this._connecting=!1,this._logger.connectionError(t?.message||t)}),this._ws.on("close",()=>{this.handleClose()}),this._ws.on("open",async()=>{this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._logger.authenticating(!!this._connectionSessionUUID);try{this._connectionSessionUUID&&this.isWebsocketReadyState()?await this.send({taskType:"authentication",apiKey:this._apiKey,connectionSessionUUID:this._connectionSessionUUID}):this.isWebsocketReadyState()&&await this.send({apiKey:this._apiKey,taskType:"authentication"})}catch(n){this._connecting=!1,this._logger.error("Failed to send auth message",n);return}let t=this.addListener({taskUUID:"authentication",lis:n=>{if(this._connecting=!1,n?.error){this._connectionError=n,this._logger.authError(n),t?.destroy?.();return}this._connectionSessionUUID=n?.authentication?.[0]?.connectionSessionUUID,this._connectionError=void 0,this._logger.authenticated(this._connectionSessionUUID||""),t?.destroy?.(),this.startHeartbeat()}})}),this._ws.on("message",(t,n)=>{let o=n?t:t?.toString();if(!o)return;let s;try{s=JSON.parse(o)}catch(r){this._logger.error("Failed to parse WebSocket message",r);return}this.handlePongMessage(s)||this._listeners.forEach(r=>{r.listener(s)})})}}handleClose(){this._connecting=!1,this._logger.connectionClosed(),this._connectionSessionUUID=void 0,this.stopHeartbeat(),!this.isInvalidAPIKey()&&(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&(this._logger.reconnectScheduled(1e3),setTimeout(()=>this.connect(),1e3)))}};var Me;typeof window>"u"?Me=G:Me=V;export{he as EControlMode,nt as EModelArchitecture,rt as EModelConditioning,tt as EModelFormat,st as EModelType,et as EOpenPosePreProcessor,ot as EPhotoMakerEnum,be as EPreProcessor,ye as EPreProcessorGroup,J as ETaskType,Ie as Environment,Ee as LogLevel,Me as Runware,V as RunwareClient,P as RunwareLogger,G as RunwareServer,X as SdkType,ee as createLogger};
|
|
2
5
|
//# sourceMappingURL=index.js.map
|