@runware/sdk-js 1.2.6 → 1.2.8-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +78 -7
- package/dist/index.d.ts +78 -7
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +9 -1
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";
|
|
@@ -821,6 +884,7 @@ type MediaUUID = {
|
|
|
821
884
|
text?: string;
|
|
822
885
|
};
|
|
823
886
|
|
|
887
|
+
declare const SDK_VERSION: string;
|
|
824
888
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
825
889
|
REQUEST_IMAGES = "REQUEST_IMAGES",
|
|
826
890
|
REQUEST_TEXT = "REQUEST_TEXT",
|
|
@@ -841,8 +905,14 @@ declare class RunwareBase {
|
|
|
841
905
|
_shouldReconnect: boolean;
|
|
842
906
|
_globalMaxRetries: number;
|
|
843
907
|
_timeoutDuration: number;
|
|
908
|
+
_heartbeatIntervalId: any;
|
|
909
|
+
_pongTimeoutId: any;
|
|
910
|
+
_heartbeatInterval: number;
|
|
911
|
+
_missedPongCount: number;
|
|
912
|
+
_maxMissedPongs: number;
|
|
844
913
|
ensureConnectionUUID: string | null;
|
|
845
|
-
|
|
914
|
+
_logger: RunwareLogger;
|
|
915
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
846
916
|
private getUniqueUUID;
|
|
847
917
|
/**
|
|
848
918
|
* Shared polling logic for async results.
|
|
@@ -854,6 +924,9 @@ declare class RunwareBase {
|
|
|
854
924
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
855
925
|
protected isWebsocketReadyState: () => boolean;
|
|
856
926
|
protected isInvalidAPIKey: () => boolean;
|
|
927
|
+
protected startHeartbeat(): void;
|
|
928
|
+
protected stopHeartbeat(): void;
|
|
929
|
+
protected handlePongMessage(data: any): boolean;
|
|
857
930
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
858
931
|
lis: (v: any) => any;
|
|
859
932
|
groupKey?: string;
|
|
@@ -862,7 +935,7 @@ declare class RunwareBase {
|
|
|
862
935
|
destroy: () => void;
|
|
863
936
|
};
|
|
864
937
|
protected connect(): void;
|
|
865
|
-
protected send: (msg: Object) => void
|
|
938
|
+
protected send: (msg: Object) => Promise<void>;
|
|
866
939
|
private destroy;
|
|
867
940
|
private uploadImage;
|
|
868
941
|
private listenToResponse;
|
|
@@ -938,16 +1011,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
938
1011
|
_instantiated: boolean;
|
|
939
1012
|
_listeners: any[];
|
|
940
1013
|
_reconnectingIntervalId: null | any;
|
|
941
|
-
|
|
942
|
-
_pongListener: any;
|
|
1014
|
+
private _connecting;
|
|
943
1015
|
constructor(props: RunwareBaseType);
|
|
944
1016
|
protected connect(): Promise<void>;
|
|
945
|
-
protected send: (msg: Object) => void
|
|
1017
|
+
protected send: (msg: Object) => Promise<void>;
|
|
946
1018
|
protected handleClose(): void;
|
|
947
1019
|
protected resetConnection: () => void;
|
|
948
|
-
protected heartBeat(): void;
|
|
949
1020
|
}
|
|
950
1021
|
|
|
951
1022
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
952
1023
|
|
|
953
|
-
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 };
|
|
1024
|
+
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, SDK_VERSION, 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";
|
|
@@ -821,6 +884,7 @@ type MediaUUID = {
|
|
|
821
884
|
text?: string;
|
|
822
885
|
};
|
|
823
886
|
|
|
887
|
+
declare const SDK_VERSION: string;
|
|
824
888
|
declare enum LISTEN_TO_MEDIA_KEY {
|
|
825
889
|
REQUEST_IMAGES = "REQUEST_IMAGES",
|
|
826
890
|
REQUEST_TEXT = "REQUEST_TEXT",
|
|
@@ -841,8 +905,14 @@ declare class RunwareBase {
|
|
|
841
905
|
_shouldReconnect: boolean;
|
|
842
906
|
_globalMaxRetries: number;
|
|
843
907
|
_timeoutDuration: number;
|
|
908
|
+
_heartbeatIntervalId: any;
|
|
909
|
+
_pongTimeoutId: any;
|
|
910
|
+
_heartbeatInterval: number;
|
|
911
|
+
_missedPongCount: number;
|
|
912
|
+
_maxMissedPongs: number;
|
|
844
913
|
ensureConnectionUUID: string | null;
|
|
845
|
-
|
|
914
|
+
_logger: RunwareLogger;
|
|
915
|
+
constructor({ apiKey, url, shouldReconnect, globalMaxRetries, timeoutDuration, heartbeatInterval, enableLogging, }: RunwareBaseType);
|
|
846
916
|
private getUniqueUUID;
|
|
847
917
|
/**
|
|
848
918
|
* Shared polling logic for async results.
|
|
@@ -854,6 +924,9 @@ declare class RunwareBase {
|
|
|
854
924
|
static initialize(props: RunwareBaseType): Promise<RunwareBase>;
|
|
855
925
|
protected isWebsocketReadyState: () => boolean;
|
|
856
926
|
protected isInvalidAPIKey: () => boolean;
|
|
927
|
+
protected startHeartbeat(): void;
|
|
928
|
+
protected stopHeartbeat(): void;
|
|
929
|
+
protected handlePongMessage(data: any): boolean;
|
|
857
930
|
protected addListener({ lis, groupKey, taskUUID, }: {
|
|
858
931
|
lis: (v: any) => any;
|
|
859
932
|
groupKey?: string;
|
|
@@ -862,7 +935,7 @@ declare class RunwareBase {
|
|
|
862
935
|
destroy: () => void;
|
|
863
936
|
};
|
|
864
937
|
protected connect(): void;
|
|
865
|
-
protected send: (msg: Object) => void
|
|
938
|
+
protected send: (msg: Object) => Promise<void>;
|
|
866
939
|
private destroy;
|
|
867
940
|
private uploadImage;
|
|
868
941
|
private listenToResponse;
|
|
@@ -938,16 +1011,14 @@ declare class RunwareServer extends RunwareBase {
|
|
|
938
1011
|
_instantiated: boolean;
|
|
939
1012
|
_listeners: any[];
|
|
940
1013
|
_reconnectingIntervalId: null | any;
|
|
941
|
-
|
|
942
|
-
_pongListener: any;
|
|
1014
|
+
private _connecting;
|
|
943
1015
|
constructor(props: RunwareBaseType);
|
|
944
1016
|
protected connect(): Promise<void>;
|
|
945
|
-
protected send: (msg: Object) => void
|
|
1017
|
+
protected send: (msg: Object) => Promise<void>;
|
|
946
1018
|
protected handleClose(): void;
|
|
947
1019
|
protected resetConnection: () => void;
|
|
948
|
-
protected heartBeat(): void;
|
|
949
1020
|
}
|
|
950
1021
|
|
|
951
1022
|
declare let Runware: typeof RunwareClient | typeof RunwareServer;
|
|
952
1023
|
|
|
953
|
-
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 };
|
|
1024
|
+
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, SDK_VERSION, 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=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var ze=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Be(e))!He.call(u,s)&&s!==t&&de(u,s,{get:()=>e[s],enumerable:!(n=Ve(e,s))||n.enumerable});return u};var je=(u,e,t)=>(t=u!=null?We(Ge(u)):{},ze(e||!u||!u.__esModule?de(t,"default",{value:u,enumerable:!0}):t,u));var we=Qe((bn,Se)=>{"use strict";var xe=u=>u&&u.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=(u,e,t)=>{Object.defineProperty(e,t,{get:()=>u[t],set:n=>{u[t]=n},enumerable:!0,configurable:!0})},_e=u=>u.minReconnectionDelay+Math.random()*u.minReconnectionDelay,it=(u,e)=>{let t=e*u.reconnectionDelayGrowFactor;return t>u.maxReconnectionDelay?u.maxReconnectionDelay:t},lt=["onopen","onclose","onmessage","onerror"],ut=(u,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([s,a])=>{u.addEventListener(n,s,a)})}),e&<.forEach(n=>{u[n]=e[n]})},ve=function(u,e,t={}){let n,s,a=0,r=0,o=!0,i={};if(!(this instanceof ve))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let d=at();if(Object.keys(d).filter(c=>t.hasOwnProperty(c)).forEach(c=>d[c]=t[c]),!xe(d.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let m=d.debug?(...c)=>console.log("RWS:",...c):()=>{},g=(c,y)=>setTimeout(()=>{let U=new Error(y);U.code=c,Array.isArray(i.error)&&i.error.forEach(([b])=>b(U)),n.onerror&&n.onerror(U)},0),p=()=>{if(m("close"),r++,m("retries count:",r),r>d.maxRetries){g("EHOSTDOWN","Too many failed connection attempts");return}a?a=it(d,a):a=_e(d),m("reconnectDelay:",a),o&&setTimeout(l,a)},l=()=>{m("connect");let c=n;n=new d.constructor(u,e),s=setTimeout(()=>{m("timeout"),n.close(),g("ETIMEDOUT","Connection timeout")},d.connectionTimeout),m("bypass properties");for(let y in n)["addEventListener","removeEventListener","close","send"].indexOf(y)<0&&ot(n,this,y);n.addEventListener("open",()=>{clearTimeout(s),m("open"),a=_e(d),m("reconnectDelay:",a),r=0}),n.addEventListener("close",p),ut(n,c,i)};m("init"),l(),this.close=(c=1e3,y="",{keepClosed:U=!1,fastClose:b=!0,delay:f=0}={})=>{if(f&&(a=f),o=!U,n.close(c,y),b){let h={code:c,reason:y,wasClean:!0};p(),Array.isArray(i.close)&&i.close.forEach(([k,I])=>{k(h),n.removeEventListener("close",k,I)}),n.onclose&&(n.onclose(h),n.onclose=null)}},this.send=c=>{n.send(c)},this.addEventListener=(c,y,U)=>{Array.isArray(i[c])?i[c].some(([b])=>b===y)||i[c].push([y,U]):i[c]=[[y,U]],n.addEventListener(c,y,U)},this.removeEventListener=(c,y,U)=>{Array.isArray(i[c])&&(i[c]=i[c].filter(([b])=>b!==y)),n.removeEventListener(c,y,U)}};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=(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||{}),ge=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(ge||{}),me=(p=>(p.canny="canny",p.depth="depth",p.mlsd="mlsd",p.normalbae="normalbae",p.openpose="openpose",p.tile="tile",p.seg="seg",p.lineart="lineart",p.lineart_anime="lineart_anime",p.shuffle="shuffle",p.scribble="scribble",p.softedge="softedge",p))(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=(a=>(a.openpose="openpose",a.openpose_face="openpose_face",a.openpose_faceonly="openpose_faceonly",a.openpose_full="openpose_full",a.openpose_hand="openpose_hand",a))(Xe||{}),Je=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(Je||{}),Ze=(l=>(l.flux1d="flux1d",l.flux1s="flux1s",l.pony="pony",l.sdhyper="sdhyper",l.sd1x="sd1x",l.sd1xlcm="sd1xlcm",l.sd3="sd3",l.sdxl="sdxl",l.sdxllcm="sdxllcm",l.sdxldistilled="sdxldistilled",l.sdxlhyper="sdxlhyper",l.sdxllightning="sdxllightning",l.sdxlturbo="sdxlturbo",l))(Ze||{}),Ye=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(Ye||{}),$e=(I=>(I.canny="canny",I.depth="depth",I.qrcode="qrcode",I.hed="hed",I.scrible="scrible",I.openpose="openpose",I.seg="segmentation",I.openmlsd="openmlsd",I.softedge="softedge",I.normal="normal bae",I.shuffle="shuffle",I.pix2pix="pix2pix",I.inpaint="inpaint",I.lineart="line art",I.sketch="sketch",I.inpaintdepth="inpaint depth",I.tile="tile",I.outfit="outfit",I.blur="blur",I.gray="gray",I.lowquality="low quality",I))($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=(u,e)=>{if(u==null)return;let t=u.indexOf(e);t!==-1&&u.splice(t,1)},M=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((a,r)=>{let o=setTimeout(()=>{i&&(clearInterval(i),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(o)},t),i=setInterval(async()=>{u({resolve:a,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(o))},s)})),Ue=u=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(u),t.onload=function(){e(t.result)}}),D=()=>tt(),Te=u=>nt(u);var be=({key:u,data:e,useZero:t=!0,shouldReturnString:n=!1})=>u.split(/\.|\[/).map(r=>r.replace(/\]$/,"")).reduce((r,o)=>{let i=t?0:void 0,d=r?.[o];if(!d)return i;if(Array.isArray(d)&&/^\d+$/.test(o)){let m=parseInt(o,10);return m>=0&&m<d.length?r[o]=d[m]:r[o]??i}else return r[o]??i},e||{})??{},fe=(u,e=1e3)=>new Promise(t=>setTimeout(t,u*e));var Re=(u,e)=>u.filter(t=>t.key!==e.key);var R=({key:u,value:e})=>e||e===0||e===!1?{[u]:e}:{},st=(u,e)=>Math.floor(Math.random()*(e-u+1))+u,ke=()=>st(1,Number.MAX_SAFE_INTEGER),De=(u,{debugKey:e="debugKey",timeoutDuration:t=K,shouldThrowError:n=!0,pollingInterval:s=ye})=>(t=t<q?q:t,new Promise((a,r)=>{let o=setTimeout(()=>{i&&(clearInterval(i),n&&r(`Response could not be received from server for ${e}`)),clearTimeout(o)},t),i=setInterval(async()=>{try{await u({resolve:a,reject:r,intervalId:i})&&(clearInterval(i),clearTimeout(o))}catch(d){clearInterval(i),clearTimeout(o),r(d)}},s)}));var x=async(u,e={})=>{let{delayInSeconds:t=1,callback:n}=e,s=e.maxRetries??1;for(;s;)try{return await u()}catch(a){if(n?.(),a?.error)throw a;if(s--,s>0)await fe(t),await x(u,{...e,maxRetries:s});else throw a}};var C=class{constructor({apiKey:e,url:t=Z.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:s=2,timeoutDuration:a=K}){this._listeners=[];this._globalMessages={};this._globalImages=[];this._globalErrors=[];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:a,outputFormat:r,highThresholdCanny:o,lowThresholdCanny:i,includeHandsAndFaceOpenPose:d,includeCost:m,outputQuality:g,customTaskUUID:p,taskUUID:l,retry:c,includeGenerationTime:y,includePayload:U})=>{let b=c||this._globalMaxRetries,f,h=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let I=l||p||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:I,preProcessorType:t,...R({key:"height",value:n}),...R({key:"width",value:s}),...R({key:"outputType",value:a}),...R({key:"outputFormat",value:r}),...R({key:"includeCost",value:m}),...R({key:"highThresholdCanny",value:o}),...R({key:"lowThresholdCanny",value:i}),...R({key:"includeHandsAndFaceOpenPose",value:d}),...g?{outputQuality:g}:{}};this.send({...w}),f=this.globalListener({taskUUID:I});let A=await M(({resolve:S,reject:B})=>{let v=this.getSingleMessage({taskUUID:I});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:U?w:void 0,startTime:y?h: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:a,retry:r,includePayload:o,includeGenerationTime:i,deliveryMethod:d,skipResponse:m,model:g})=>{try{let p;e&&(p=await this.uploadImage(e));let c={taskUUID:a||s||D(),taskType:"caption",model:g,inputImage:p?.imageUUID,inputs:t,...R({key:"includeCost",value:n}),retry:r,includePayload:o,includeGenerationTime:i},y=await this.baseSingleRequest({payload:{...c,taskType:"caption"},debugKey:"caption"});if(m)return y;if(d==="async"){let U=y?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return y}catch(p){throw p}};this.caption=async e=>this.requestImageToText(e);this.removeImageBackground=async e=>{let{skipResponse:t,...n}=e;try{let s=n.deliveryMethod,a=await this.baseSingleRequest({payload:{...n,taskType:"removeBackground"},debugKey:"remove-background"});if(t)return a;if(s==="async"){let r=a?.taskUUID;return(await this.pollForAsyncResults({taskUUID:r}))[0]}return a}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,...a}=e;try{let r=await this.baseSingleRequest({payload:{...a,...n?.length&&{inputAudios:n},...s?.length&&{referenceVideos:s},deliveryMethod:"async",taskType:"videoInference"},debugKey:"video-inference"});if(t)return r;let o=r?.taskUUID;return this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults})}catch(r){throw r}};this.audioInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=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 r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};this.threeDInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=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 r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};this.textInference=async e=>{let{skipResponse:t,deliveryMethod:n="sync",...s}=e;try{let r=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 r;let o=r?.taskUUID;return n==="async"?this.pollForAsyncResults({taskUUID:o,numberResults:e?.numberResults}):r}catch(a){throw a}};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 e=>{let{inputImage:t,skipResponse:n,deliveryMethod:s="sync",...a}=e;try{let r;t&&(r=await this.uploadImage(t));let o=await this.baseSingleRequest({payload:{...a,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:s},debugKey:"upscale"});if(n)return o;if(s==="async"){let i=o?.taskUUID;return(await this.pollForAsyncResults({taskUUID:i}))[0]}return o}catch(r){throw r}};this.upscale=async e=>this.upscaleGan(e);this.enhancePrompt=async({prompt:e,promptMaxLength:t=380,promptVersions:n=1,includeCost:s,customTaskUUID:a,taskUUID:r,retry:o,includeGenerationTime:i,includePayload:d})=>{let m=o||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=r||a||D(),c={prompt:e,taskUUID:l,promptMaxLength:t,promptVersions:n,...R({key:"includeCost",value:s}),taskType:"promptEnhance"};this.send(c),g=this.globalListener({taskUUID:l});let y=await M(({resolve:U,reject:b})=>{let f=this._globalMessages[l];if(f?.error)return b(f),!0;if(f?.length>=n)return delete this._globalMessages[l],U(f),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return g.destroy(),this.insertAdditionalResponse({response:y,payload:d?c:void 0,startTime:i?p:void 0}),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.promptEnhance=async e=>this.enhancePrompt(e);this.modelUpload=async e=>{let{onUploadStream:t,retry:n,customTaskUUID:s,taskUUID:a,...r}=e,o=n||this._globalMaxRetries,i;try{return await x(async()=>{await this.ensureConnection();let d=a||s||D();this.send({...r,taskUUID:d,taskType:"modelUpload"});let m,g;return i=this.listenToUpload({taskUUID:d,onUploadStream:(l,c)=>{t?.(l,c),l?.status==="ready"?m=l:c&&(g=c)}}),await M(({resolve:l,reject:c})=>{if(m)return l(m),!0;if(g)return c(g),!1},{shouldThrowError:!1,timeoutDuration:60*60*1e3})},{maxRetries:o,callback:()=>{i?.destroy()}})}catch(d){throw d}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:s,customTaskUUID:a,taskUUID:r,numberResults:o,includeGenerationTime:i,includePayload:d,...m}=e,g=s||this._globalMaxRetries,p,l=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>l.includes(I.taskUUID)),b=r||a||D();l.push(b);let f=o-U.length,h={...m,...m.seed?{seed:m.seed}:{seed:ke()},...t??{},taskUUID:b,taskType:"photoMaker",numberResults:o};this.send({...h,numberResults:f}),p=this.listenToResponse({onPartialImages:n,taskUUID:b,groupKey:"REQUEST_IMAGES",requestPayload:d?h:void 0,startTime:i?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:o,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(c>=g)return this.handleIncompleteImages({taskUUIDs:l,error:U})}};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:a,taskUUID:r,includePayload:o,includeGenerationTime:i,...d}=e,m=s||this._globalMaxRetries,g,p=Date.now();try{return await x(async()=>{await this.ensureConnection();let l=r||a||D(),c={...d,taskUUID:l};this.send(c),g=this.globalListener({taskUUID:l});let y=await M(({resolve:U,reject:b})=>{let f=n?this.getMultipleMessages({taskUUID:l}):this.getSingleMessage({taskUUID:l});if(f){if(f?.error)return b(f),!0;if(f)return delete this._globalMessages[l],U(f),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:y,payload:o?c:void 0,startTime:i?p:void 0}),g.destroy(),y},{maxRetries:m,callback:()=>{g?.destroy()}})}catch(l){throw l}};this.baseSyncRequest=async({payload:e,groupKey:t,skipResponse:n=!1})=>{let{retry:s,customTaskUUID:a,includePayload:r,numberResults:o=1,onPartialResponse:i,includeGenerationTime:d,...m}=e,g=s||this._globalMaxRetries,p,l=[],c=0,y=Date.now();try{return await x(async()=>{await this.ensureConnection(),c++;let U=this._globalImages.filter(I=>l.includes(I.taskUUID)),b=a||D();l.push(b);let f=o-U.length,h={...m,taskUUID:b,numberResults:f};if(this.send(h),n)return new Promise((I,w)=>{let A=this.addListener({taskUUID:b,groupKey:t,lis:S=>{A.destroy(),S.error?w(S.error):I(S[b])}})});p=this.listenToResponse({onPartialImages:i,taskUUID:b,groupKey:t,requestPayload:r?h:void 0,startTime:d?y:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:l,numberResults:o,lis:p});return p.destroy(),k},{maxRetries:g,callback:()=>{p?.destroy()}})}catch(U){throw U}};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=a}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:a})=>{try{let r=await this.getResponse({taskUUID:e});for(let i of r||[])if(i.status==="success"){let d=this.getUniqueUUID(i);d&&n.set(d,i)}return n.size===t?(s(Array.from(n.values())),!0):!1}catch(r){return a(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}}addListener({lis:e,groupKey:t,taskUUID:n}){let s=o=>{let i=Array.isArray(o?.data)?o.data:[o.data],d=o?.[0]?.errors?o?.[0]?.errors:Array.isArray(o?.errors)?o.errors:[o.errors],m=i.filter(p=>(p?.taskUUID||p?.taskType)===n);if(d.filter(p=>(p?.taskUUID||p?.taskType)===n).length){e({error:{...d[0]??{}}});return}if(m.length){e({[n]:i});return}},a={key:n||D(),listener:s,groupKey:t};return this._listeners.push(a),{destroy:()=>{this._listeners=Re(this._listeners,a)}}}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:a}){return this.addListener({taskUUID:t,lis:r=>{let o=r?.[t]?.filter(i=>i.taskUUID===t);r.error?(e?.(o,r?.error&&r),this._globalErrors.push(r)):(o=o.map(i=>(this.insertAdditionalResponse({response:i,payload:s||void 0,startTime:a||void 0}),{...i})),e?.(o,r?.error&&r),this._sdkType==="CLIENT"?this._globalImages=[...this._globalImages,...(r?.[t]??[]).map(i=>(this.insertAdditionalResponse({response:i,payload:s||void 0,startTime:a||void 0}),{...i}))]:this._globalImages=[...this._globalImages,...o])},groupKey:n})}listenToUpload({onUploadStream:e,taskUUID:t}){return this.addListener({taskUUID:t,lis:n=>{let s=n?.error,a=n?.[t]?.[0],r=a?.taskUUID===t?a:null;(r||s)&&e?.(r||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:a,negativePrompt:r,seedImage:o,maskImage:i,strength:d,height:m,width:g,model:p,steps:l,scheduler:c,seed:y,CFGScale:U,clipSkip:b,usePromptWeighting:f,promptWeighting:h,numberResults:k=1,onPartialImages:I,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(o){let _=await this.uploadImage(o);if(!_)return[];E=_.imageUUID}if(i){let _=await this.uploadImage(i);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:p,positivePrompt:a,...r?{negativePrompt:r}:{},...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:d}),...R({key:"CFGScale",value:U}),...R({key:"clipSkip",value:b}),...R({key:"maskMargin",value:T}),...R({key:"usePromptWeighting",value:f}),...R({key:"steps",value:l}),...h?{promptWeighting:h}:{},...y?{seed:y}:{},...c?{scheduler:c}:{},...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:I,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,a)=>{let r=0,o=30,i=D(),d,m,g=()=>{this.ensureConnectionUUID=null,clearInterval(d),clearInterval(m)};this._sdkType==="SERVER"&&(d=setInterval(async()=>{try{let p=this.connected(),l=!1;(!this.ensureConnectionUUID||i===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=i),l=!0);let c=r%10===0&&l;p?(g(),s(!0)):r>=o?(g(),a(new Error("Retry timed out"))):(c&&this.connect(),r++)}catch(p){g(),a(p)}},t)),m=setInterval(async()=>{if(this.connected()){g(),s(!0);return}if(this.isInvalidAPIKey()){g(),a(this._connectionError);return}},n)})}catch{throw this.ensureConnectionUUID=null,this._connectionError=void 0,this._connectionError??"Could not connect to server. Ensure your API key is correct"}}async getResponseWithSimilarTaskUUID({taskUUID:e,numberResults:t,shouldThrowError:n,lis:s,deliveryMethod:a}){return await M(({resolve:r,reject:o,intervalId:i})=>{let d=Array.isArray(e)?e:[e],m=this._globalImages.filter(l=>d.includes(l.taskUUID)),g=a==="async"&&m.length>0,p=this._globalErrors.filter(l=>d.includes(l.error.taskUUID));if(p.length>0){let l=p[0];return this._globalErrors=this._globalErrors.filter(c=>!d.includes(c.error.taskUUID)),clearInterval(i),o?.(l),!0}else if(m.length>=t||g)return clearInterval(i),this._globalImages=this._globalImages.filter(l=>!d.includes(l.taskUUID)),r([...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 a=JSON.parse(s);this._listeners.forEach(r=>{r.listener(a)})}))}handleClose(){this.isInvalidAPIKey()||(this._reconnectingIntervalId&&clearInterval(this._reconnectingIntervalId),this._shouldReconnect&&setTimeout(()=>this.connect(),1e3))}heartBeat(){clearTimeout(this._pingTimeout),this._pingTimeout=setTimeout(()=>{this.isWebsocketReadyState()&&this.send({ping:!0})},5e3)}};var 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 ze=Object.create;var Ie=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var et=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var tt=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xe(e))!Ze.call(a,o)&&o!==t&&Ie(a,o,{get:()=>e[o],enumerable:!(n=Ye(e,o))||n.enumerable});return a};var nt=(a,e,t)=>(t=a!=null?ze(Je(a)):{},tt(e||!a||!a.__esModule?Ie(t,"default",{value:a,enumerable:!0}):t,a));var Pe=et((Wn,Me)=>{"use strict";var Oe=a=>a&&a.CLOSING===2,bt=()=>typeof WebSocket<"u"&&Oe(WebSocket),Ut=()=>({constructor:bt()?WebSocket:null,maxReconnectionDelay:1e4,minReconnectionDelay:1500,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,debug:!1}),ft=(a,e,t)=>{Object.defineProperty(e,t,{get:()=>a[t],set:n=>{a[t]=n},enumerable:!0,configurable:!0})},Le=a=>a.minReconnectionDelay+Math.random()*a.minReconnectionDelay,Tt=(a,e)=>{let t=e*a.reconnectionDelayGrowFactor;return t>a.maxReconnectionDelay?a.maxReconnectionDelay:t},Rt=["onopen","onclose","onmessage","onerror"],_t=(a,e,t)=>{Object.keys(t).forEach(n=>{t[n].forEach(([o,s])=>{a.addEventListener(n,o,s)})}),e&&Rt.forEach(n=>{a[n]=e[n]})},Ne=function(a,e,t={}){let n,o,s=0,r=0,i=!0,l={};if(!(this instanceof Ne))throw new TypeError("Failed to construct 'ReconnectingWebSocket': Please use the 'new' operator");let g=Ut();if(Object.keys(g).filter(p=>t.hasOwnProperty(p)).forEach(p=>g[p]=t[p]),!Oe(g.constructor))throw new TypeError("Invalid WebSocket constructor. Set `options.constructor`");let c=g.debug?(...p)=>console.log("RWS:",...p):()=>{},m=(p,h)=>setTimeout(()=>{let U=new Error(h);U.code=p,Array.isArray(l.error)&&l.error.forEach(([f])=>f(U)),n.onerror&&n.onerror(U)},0),d=()=>{if(c("close"),r++,c("retries count:",r),r>g.maxRetries){m("EHOSTDOWN","Too many failed connection attempts");return}s?s=Tt(g,s):s=Le(g),c("reconnectDelay:",s),i&&setTimeout(u,s)},u=()=>{c("connect");let p=n;n=new g.constructor(a,e),o=setTimeout(()=>{c("timeout"),n.close(),m("ETIMEDOUT","Connection timeout")},g.connectionTimeout),c("bypass properties");for(let h in n)["addEventListener","removeEventListener","close","send"].indexOf(h)<0&&ft(n,this,h);n.addEventListener("open",()=>{clearTimeout(o),c("open"),s=Le(g),c("reconnectDelay:",s),r=0}),n.addEventListener("close",d),_t(n,p,l)};c("init"),u(),this.close=(p=1e3,h="",{keepClosed:U=!1,fastClose:f=!0,delay:R=0}={})=>{if(R&&(s=R),i=!U,n.close(p,h),f){let b={code:p,reason:h,wasClean:!0};d(),Array.isArray(l.close)&&l.close.forEach(([k,y])=>{k(b),n.removeEventListener("close",k,y)}),n.onclose&&(n.onclose(b),n.onclose=null)}},this.send=p=>{n.send(p)},this.addEventListener=(p,h,U)=>{Array.isArray(l[p])?l[p].some(([f])=>f===h)||l[p].push([h,U]):l[p]=[[h,U]],n.addEventListener(p,h,U)},this.removeEventListener=(p,h,U)=>{Array.isArray(l[p])&&(l[p]=l[p].filter(([f])=>f!==h)),n.removeEventListener(p,h,U)}};Me.exports=Ne});var ye=(n=>(n.PRODUCTION="PRODUCTION",n.DEVELOPMENT="DEVELOPMENT",n.TEST="TEST",n))(ye||{}),Z=(t=>(t.CLIENT="CLIENT",t.SERVER="SERVER",t))(Z||{}),ee=(b=>(b.IMAGE_INFERENCE="imageInference",b.IMAGE_UPLOAD="imageUpload",b.UPSCALE="upscale",b.REMOVE_BACKGROUND="removeBackground",b.VIDEO_INFERENCE="videoInference",b.CAPTION="caption",b.AUDIO_INFERENCE="audioInference",b.THREE_D_INFERENCE="3dInference",b.GET_RESPONSE="getResponse",b.PHOTO_MAKER="photoMaker",b.IMAGE_CONTROL_NET_PRE_PROCESS="imageControlNetPreProcess",b.IMAGE_MASKING="imageMasking",b.PROMPT_ENHANCE="promptEnhance",b.AUTHENTICATION="authentication",b.MODEL_UPLOAD="modelUpload",b.MODEL_SEARCH="modelSearch",b.MEDIA_STORAGE="mediaStorage",b.VECTORIZE="vectorize",b.TEXT_INFERENCE="textInference",b))(ee||{}),be=(n=>(n.BALANCED="balanced",n.PROMPT="prompt",n.CONTROL_NET="controlnet",n))(be||{}),Ue=(d=>(d.canny="canny",d.depth="depth",d.mlsd="mlsd",d.normalbae="normalbae",d.openpose="openpose",d.tile="tile",d.seg="seg",d.lineart="lineart",d.lineart_anime="lineart_anime",d.shuffle="shuffle",d.scribble="scribble",d.softedge="softedge",d))(Ue||{}),fe=(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))(fe||{}),st=(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))(st||{}),rt=(t=>(t.safetensors="safetensors",t.pickletensor="pickletensor",t))(rt||{}),ot=(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))(ot||{}),it=(n=>(n.base="base",n.inpainting="inpainting",n.pix2pix="pix2pix",n))(it||{}),at=(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))(at||{}),lt=(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))(lt||{});import{v4 as ct,validate as gt}from"uuid";var Te={name:"@runware/sdk-js",version:"1.2.8-beta.1",description:"The SDK is used to run image inference with the Runware API, powered by the RunWare inference platform. It can be used to generate imaged with text-to-image and image-to-image. It also allows the use of an existing gallery of models or selecting any model or LoRA from the CivitAI gallery. The API also supports upscaling, background removal, inpainting and outpainting, and a series of other ControlNet models.",main:"dist/index.js",module:"dist/index.js",types:"dist/index.d.ts",type:"module",exports:{".":{types:"./dist/index.d.ts",require:"./dist/index.cjs",import:"./dist/index.js"}},files:["dist/"],scripts:{build:"tsup",lint:"tsc",pkg:"npx pkgfiles","dev:test":"vitest --reporter verbose",test:"vitest run --reporter verbose","test:single":"vitest run --reporter verbose tests/Runware/upscale-gan.test.ts",debug:"tsx tests/script.ts","beta:tag":"npm publish --tag beta"},keywords:["runware","sdk","ai"],author:"",license:"ISC",devDependencies:{"@types/uuid":"^9.0.6","@types/ws":"^8.5.8",dotenv:"^16.4.5","mock-socket":"^9.3.1",tsup:"^8.3.5",typescript:"^5.2.2",vitest:"^0.34.6"},dependencies:{uuid:"^9.0.1",ws:"^8.18.0"},optionalDependencies:{bufferutil:"^4.0.8"},directories:{test:"tests"}};var V=Te.version;function B(a){let e=a.includes("?")?"&":"?";return`${a}${e}sdk=js&version=${V}`}var G=6e4,K=1e3,Re=100,te={PRODUCTION:"wss://ws-api.runware.ai/v1",TEST:"ws://localhost:8080"},_e=(a,e)=>{if(a==null)return;let t=a.indexOf(e);t!==-1&&a.splice(t,1)},L=(a,{debugKey:e="debugKey",timeoutDuration:t=G,shouldThrowError:n=!0,pollingInterval:o=Re})=>(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(g){clearInterval(l),clearTimeout(i),r(g)}},o)})),ke=a=>new Promise(e=>{let t=new FileReader;t.readAsDataURL(a),t.onload=function(){e(t.result)}}),D=()=>ct(),De=a=>gt(a);var ve=({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,g=r?.[i];if(!g)return l;if(Array.isArray(g)&&/^\d+$/.test(i)){let c=parseInt(i,10);return c>=0&&c<g.length?r[i]=g[c]:r[i]??l}else return r[i]??l},e||{})??{},xe=(a,e=1e3)=>new Promise(t=>setTimeout(t,a*e));var Se=(a,e)=>a.filter(t=>t.key!==e.key);var _=({key:a,value:e})=>e||e===0||e===!1?{[a]:e}:{},dt=(a,e)=>Math.floor(Math.random()*(e-a+1))+a,Ee=()=>dt(1,Number.MAX_SAFE_INTEGER),we=(a,{debugKey:e="debugKey",timeoutDuration:t=G,shouldThrowError:n=!0,pollingInterval:o=Re})=>(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(g){clearInterval(l),clearTimeout(i),r(g)}},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 xe(t),await x(a,{...e,maxRetries:s});throw o?.retryExhausted(r),i}};var I={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"},Ae=(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))(Ae||{}),Ce={CONNECTION:{bg:I.bgBlue,fg:I.blue,icon:"\u{1F50C}"},AUTH:{bg:I.bgGreen,fg:I.green,icon:"\u{1F511}"},HEARTBEAT:{bg:I.bgMagenta,fg:I.magenta,icon:"\u{1F493}"},SEND:{bg:I.bgCyan,fg:I.cyan,icon:"\u{1F4E4}"},RECEIVE:{bg:I.bgCyan,fg:I.cyan,icon:"\u{1F4E5}"},RETRY:{bg:I.bgYellow,fg:I.yellow,icon:"\u{1F504}"},REQUEST:{bg:I.bgBlue,fg:I.blue,icon:"\u{1F4E1}"},ERROR:{bg:I.bgRed,fg:I.red,icon:"\u274C"},WARN:{bg:I.bgYellow,fg:I.yellow,icon:"\u26A0\uFE0F"},INFO:{bg:I.bgWhite,fg:I.gray,icon:"\u2139\uFE0F"}},pt=`${I.bold}${I.magenta}[RUNWARE]${I.reset}`;function mt(){return`${I.dim}${new Date().toISOString()}${I.reset}`}function ht(a){return`${Ce[a].bg}${I.bold}${I.black} ${a} ${I.reset}`}function It(a){if(a==null)return"";if(typeof a=="string")return`${I.dim}${a}${I.reset}`;try{let e=JSON.stringify(a,null,2);return`${I.dim}${e}${I.reset}`}catch{return`${I.dim}[unserializable]${I.reset}`}}var P=class{constructor(e=!1){this.enabled=e}log(e,t,n){if(!this.enabled)return;let o=Ce[e],s=["",`${pt} ${ht(e)} ${o.icon} ${o.fg}${I.bold}${t}${I.reset}`,` ${mt()}`];n!==void 0&&s.push(` ${It(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)}},yt=new P(!1);function ne(a){return a?new P(!0):yt}var O=class{constructor({apiKey:e,url:t=te.PRODUCTION,shouldReconnect:n=!0,globalMaxRetries:o=2,timeoutDuration:s=G,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"&&De(e))return{imageURL:e,imageUUID:e,taskUUID:t,taskType:"imageUpload"};let n=typeof e=="string"?e:await ke(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:g,includeCost:c,outputQuality:m,customTaskUUID:d,taskUUID:u,retry:p,includeGenerationTime:h,includePayload:U})=>{let f=p||this._globalMaxRetries,R,b=Date.now();try{return await x(async()=>{await this.ensureConnection();let k=await this.uploadImage(e);if(!k?.imageUUID)return null;let y=u||d||D(),w={inputImage:k.imageUUID,taskType:"imageControlNetPreProcess",taskUUID:y,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:g}),...m?{outputQuality:m}:{}};await this.send({...w}),R=this.globalListener({taskUUID:y});let A=await L(({resolve:S,reject:Q})=>{let E=this.getSingleMessage({taskUUID:y});if(E){if(E?.error)return Q(E),!0;if(E)return S(E),!0}},{debugKey:"unprocessed-image",timeoutDuration:this._timeoutDuration});return R.destroy(),this.insertAdditionalResponse({response:A,payload:U?w:void 0,startTime:h?b:void 0}),A},{maxRetries:f,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:g,skipResponse:c,model:m})=>{try{let d;e&&(d=await this.uploadImage(e));let p={taskUUID:s||o||D(),taskType:"caption",model:m,inputImage:d?.imageUUID,inputs:t,..._({key:"includeCost",value:n}),retry:r,includePayload:i,includeGenerationTime:l},h=await this.baseSingleRequest({payload:{...p,taskType:"caption"},debugKey:"caption"});if(c)return h;if(g==="async"){let U=h?.taskUUID;return(await this.pollForAsyncResults({taskUUID:U}))[0]}return h}catch(d){throw d}};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 e=>{let{inputImage:t,skipResponse:n,deliveryMethod:o="sync",...s}=e;try{let r;t&&(r=await this.uploadImage(t));let i=await this.baseSingleRequest({payload:{...s,...r?.imageUUID?{inputImage:r.imageUUID}:{},taskType:"upscale",deliveryMethod:o},debugKey:"upscale"});if(n)return i;if(o==="async"){let l=i?.taskUUID;return(await this.pollForAsyncResults({taskUUID:l}))[0]}return i}catch(r){throw r}};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:g})=>{let c=i||this._globalMaxRetries,m,d=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 h=await L(({resolve:U,reject:f})=>{let R=this._globalMessages[u];if(R?.error)return f(R),!0;if(R?.length>=n)return delete this._globalMessages[u],U(R),!0},{debugKey:"enhance-prompt",timeoutDuration:this._timeoutDuration});return m.destroy(),this.insertAdditionalResponse({response:h,payload:g?p:void 0,startTime:l?d:void 0}),h},{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 g=s||o||D();await this.send({...r,taskUUID:g,taskType:"modelUpload"});let c,m;l=this.listenToUpload({taskUUID:g,onUploadStream:(u,p)=>{t?.(u,p),u?.status==="ready"?c=u:p&&(m=p)}});let d=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(),d},{maxRetries:i,callback:()=>{l?.destroy()}})}catch(g){throw g}};this.photoMaker=async(e,t)=>{let{onPartialImages:n,retry:o,customTaskUUID:s,taskUUID:r,numberResults:i,includeGenerationTime:l,includePayload:g,...c}=e,m=o||this._globalMaxRetries,d,u=[],p=0,h=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let U=this._globalImages.filter(y=>u.includes(y.taskUUID)),f=r||s||D();u.push(f);let R=i-U.length,b={...c,...c.seed?{seed:c.seed}:{seed:Ee()},...t??{},taskUUID:f,taskType:"photoMaker",numberResults:i};await this.send({...b,numberResults:R}),d=this.listenToResponse({onPartialImages:n,taskUUID:f,groupKey:"REQUEST_IMAGES",requestPayload:g?b:void 0,startTime:l?h:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:d});return d.destroy(),k},{maxRetries:m,callback:()=>{d?.destroy()}})}catch(U){if(U.taskUUID)throw U;if(p>=m)return this.handleIncompleteImages({taskUUIDs:u,error:U})}};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,...g}=e,c=o||this._globalMaxRetries,m,d=Date.now();try{return await x(async()=>{await this.ensureConnection();let u=r||s||D(),p={...g,taskUUID:u};this._logger.requestStart(t,u),await this.send(p),m=this.globalListener({taskUUID:u});let h=await L(({resolve:U,reject:f})=>{let R=n?this.getMultipleMessages({taskUUID:u}):this.getSingleMessage({taskUUID:u});if(R){if(R?.error)return this._logger.requestError(u,R),f(R),!0;if(R)return delete this._globalMessages[u],this._logger.requestComplete(t,u,Date.now()-d),U(R),!0}},{debugKey:t,timeoutDuration:this._timeoutDuration});return this.insertAdditionalResponse({response:h,payload:i?p:void 0,startTime:l?d:void 0}),m.destroy(),h},{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:g,...c}=e,m=o||this._globalMaxRetries,d,u=[],p=0,h=Date.now();try{return await x(async()=>{await this.ensureConnection(),p++;let U=this._globalImages.filter(y=>u.includes(y.taskUUID)),f=s||D();u.push(f);let R=i-U.length,b={...c,taskUUID:f,numberResults:R};if(this._logger.requestStart(c.taskType||t,f),await this.send(b),n)return this._logger.info("Async mode (skipResponse) \u2014 waiting for server acknowledgement",{taskUUID:f}),new Promise((y,w)=>{let A=this.addListener({taskUUID:f,groupKey:t,lis:S=>{A.destroy(),S.error?(this._logger.requestError(f,S.error),w(S.error)):(this._logger.requestComplete(c.taskType||t,f,Date.now()-h),y(S[f]))}})});d=this.listenToResponse({onPartialImages:l,taskUUID:f,groupKey:t,requestPayload:r?b:void 0,startTime:g?h:void 0});let k=await this.getResponseWithSimilarTaskUUID({taskUUID:u,numberResults:i,lis:d});return this._logger.requestComplete(c.taskType||t,f,Date.now()-h),d.destroy(),k},{maxRetries:m,callback:()=>{d?.destroy()},logger:this._logger})}catch(U){throw U}};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=ne(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 we(async({resolve:o,reject:s})=>{try{let r=await this.getResponse({taskUUID:e});for(let l of r||[])if(l.status==="success"){let g=this.getUniqueUUID(l);g&&n.set(g,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],g=i?.[0]?.errors?i?.[0]?.errors:Array.isArray(i?.errors)?i.errors:[i.errors],c=l.filter(d=>(d?.taskUUID||d?.taskType)===n);if(g.filter(d=>(d?.taskUUID||d?.taskType)===n).length){e({error:{...g[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=Se(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){_e(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=ve({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:g,height:c,width:m,model:d,steps:u,scheduler:p,seed:h,CFGScale:U,clipSkip:f,usePromptWeighting:R,promptWeighting:b,numberResults:k=1,onPartialImages:y,includeCost:w,customTaskUUID:A,taskUUID:S,retry:Q,refiner:E,maskMargin:T,outputQuality:se,controlNet:j,lora:re,embeddings:oe,ipAdapters:ie,providerSettings:ae,outpaint:le,acceleratorOptions:ue,advancedFeatures:ce,referenceImages:ge,includeGenerationTime:qe,includePayload:Ke,...de},Ve){let N,pe,F=[],me=0,he=Q||this._globalMaxRetries;try{await this.ensureConnection();let C=null,z=null,Y=[];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[];z=v.imageUUID}if(j?.length)for(let v=0;v<j.length;v++){let M=j[v],{endStep:X,startStep:W,weight:J,guideImage:q,controlMode:Ge,startStepPercentage:$e,endStepPercentage:He,model:Qe}=M,je=q?await this.uploadImage(q):null;Y.push({guideImage:je?.imageUUID,model:Qe,endStep:X,startStep:W,weight:J,..._({key:"startStepPercentage",value:$e}),..._({key:"endStepPercentage",value:He}),controlMode:Ge||"controlnet"})}pe={taskType:"imageInference",model:d,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:g}),..._({key:"CFGScale",value:U}),..._({key:"clipSkip",value:f}),..._({key:"maskMargin",value:T}),..._({key:"usePromptWeighting",value:R}),..._({key:"steps",value:u}),...b?{promptWeighting:b}:{},...h?{seed:h}:{},...p?{scheduler:p}:{},...E?{refiner:E}:{},...le?{outpaint:le}:{},..._({key:"includeCost",value:w}),...C?{seedImage:C}:{},...z?{maskImage:z}:{},...se?{outputQuality:se}:{},...Y.length?{controlNet:Y}:{},...re?.length?{lora:re}:{},...oe?.length?{embeddings:oe}:{},...ie?.length?{ipAdapters:ie}:{},...ae?{providerSettings:ae}:{},...ue?{acceleratorOptions:ue}:{},...ce?{advancedFeatures:ce}:{},...ge?.length?{referenceImages:ge}:{},...de,...Ve??{}};let Be=Date.now();return await x(async()=>{me++,N?.destroy();let v=this._globalImages.filter(q=>F.includes(q.taskUUID)),M=S||A||D();F.push(M);let X=k-v.length,W={...pe,taskUUID:M,numberResults:X};await this.send(W),N=this.listenToResponse({onPartialImages:y,taskUUID:M,groupKey:"REQUEST_IMAGES",requestPayload:Ke?W:void 0,startTime:qe?Be:void 0});let J=await this.getResponseWithSimilarTaskUUID({taskUUID:F,numberResults:k,lis:N,deliveryMethod:de.deliveryMethod});return N.destroy(),J},{maxRetries:he,callback:()=>{N?.destroy()}})}catch(C){if(me>=he)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===te.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(),g,c,m=()=>{this.ensureConnectionUUID=null,clearInterval(g),clearInterval(c)};this._sdkType==="SERVER"&&(g=setInterval(async()=>{try{let d=this.connected(),u=!1;(!this.ensureConnectionUUID||l===this.ensureConnectionUUID)&&(this.ensureConnectionUUID||(this.ensureConnectionUUID=l),u=!0);let p=r%10===0&&u;d?(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(d){m(),s(d)}},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 g=Array.isArray(e)?e:[e],c=this._globalImages.filter(u=>g.includes(u.taskUUID)),m=s==="async"&&c.length>0,d=this._globalErrors.filter(u=>g.includes(u.error.taskUUID));if(d.length>0){let u=d[0];return this._globalErrors=this._globalErrors.filter(p=>!g.includes(p.error.taskUUID)),clearInterval(l),i?.(u),!0}else if(c.length>=t||m)return clearInterval(l),this._globalImages=this._globalImages.filter(u=>!g.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 Fe=nt(Pe(),1);var $=class extends O{constructor(e){let{shouldReconnect:t,...n}=e;super(n);let o=B(this._url||"");this._ws=new Fe.default(o),this.connect()}};import kt from"ws";var H=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();try{let t=B(this._url);this._logger.connecting(t),this._ws=new kt(t,{perMessageDeflate:!1,headers:{"X-SDK-Name":"js","X-SDK-Version":V}})}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 We;typeof window>"u"?We=H:We=$;export{be as EControlMode,ot as EModelArchitecture,at as EModelConditioning,rt as EModelFormat,it as EModelType,st as EOpenPosePreProcessor,lt as EPhotoMakerEnum,fe as EPreProcessor,Ue as EPreProcessorGroup,ee as ETaskType,ye as Environment,Ae as LogLevel,We as Runware,$ as RunwareClient,P as RunwareLogger,H as RunwareServer,V as SDK_VERSION,Z as SdkType,ne as createLogger};
|
|
2
5
|
//# sourceMappingURL=index.js.map
|