UNPKG

@saintno/comfyui-sdk

Version:
1,532 lines (1,529 loc) 46.3 kB
// Generated by dts-bundle-generator v9.5.1 declare enum OSType { /** * Unix-like operating systems */ POSIX = "posix", /** * Windows operating systems */ NT = "nt", /** * Java virtual machine */ JAVA = "java" } export interface BasicCredentials { type: "basic"; username: string; password: string; } export interface BearerTokenCredentials { type: "bearer_token"; token: string; } export interface CustomCredentials { type: "custom"; headers: Record<string, string>; } export interface HistoryResponse { [key: string]: HistoryEntry; } export interface HistoryEntry { prompt: PromptData; outputs: OutputData; status: StatusData; } export interface PromptData { [index: number]: number | string | NodeData | MetadataData; } export interface NodeData { [key: string]: { inputs: { [key: string]: any; }; class_type: string; _meta: { title: string; }; }; } export interface MetadataData { [key: string]: any; } export interface ImageInfo { filename: string; subfolder: string; type: string; } export interface OutputData { [key: string]: { width?: number[]; height?: number[]; ratio?: number[]; images?: ImageInfo[]; }; } export interface StatusData { status_str: string; completed: boolean; messages: [ string, { [key: string]: any; } ][]; } export interface QueueResponse { queue_running: QueueItem[]; queue_pending: QueueItem[]; } export interface QueueItem { [index: number]: number | string | NodeData | MetadataData; } export interface QueuePromptResponse { prompt_id: string; number: number; node_errors: { [key: string]: any; }; } export interface SystemStatsResponse { system: { os: OSType; python_version: string; embedded_python: boolean; }; devices: DeviceStats[]; } export interface DeviceStats { name: string; type: string; index: number; vram_total: number; vram_free: number; torch_vram_total: number; torch_vram_free: number; } export interface QueueStatus { exec_info: { queue_remaining: number; }; } export interface NodeDefsResponse { [key: string]: NodeDef; } export interface NodeDef { input: { required: { [key: string]: [ string[], { tooltip?: string; } ] | [ string, { tooltip?: string; } ] | TStringInput | TBoolInput | TNumberInput; }; optional?: { [key: string]: [ string[], { tooltip?: string; } ] | [ string, { tooltip?: string; } ] | TStringInput | TBoolInput | TNumberInput; }; hidden: { [key: string]: string; }; }; input_order: { required: string[]; optional?: string[]; hidden: string[]; }; output: string[]; output_is_list: boolean[]; output_name: string[]; name: string; display_name: string; description: string; category: string; python_module: string; output_node: boolean; output_tooltips: string[]; } export interface NodeProgress { value: number; max: number; prompt_id: string; node: string; } export interface IInputNumberConfig { default: number; min: number; max: number; step?: number; round?: number; tooltip?: string; } export interface IInputStringConfig { default?: string; multiline?: boolean; dynamicPrompts?: boolean; tooltip?: string; } export type TStringInput = [ "STRING", IInputStringConfig ]; export type TBoolInput = [ "BOOLEAN", { default: boolean; tooltip?: string; } ]; export type TNumberInput = [ "INT" | "FLOAT", IInputNumberConfig ]; /** * Represents a model folder in the ComfyUI system * @experimental API that may change in future versions */ export interface ModelFolder { name: string; folders: string[]; } /** * Represents a model file in the ComfyUI system * @experimental API that may change in future versions */ export interface ModelFile { name: string; pathIndex: number; } /** * Response format for model preview images * @experimental API that may change in future versions */ export interface ModelPreviewResponse { body: ArrayBuffer; contentType: string; } /** * Represents the mode for picking clients from a queue. * * - "PICK_ZERO": Picks the client which has zero queue remaining. This is the default mode. (For who using along with ComfyUI web interface) * - "PICK_LOWEST": Picks the client which has the lowest queue remaining. * - "PICK_ROUTINE": Picks the client in a round-robin manner. */ export declare enum EQueueMode { /** * Picks the client which has zero queue remaining. This is the default mode. (For who using along with ComfyUI web interface) */ "PICK_ZERO" = 0, /** * Picks the client which has the lowest queue remaining. */ "PICK_LOWEST" = 1, /** * Picks the client in a round-robin manner. */ "PICK_ROUTINE" = 2 } export declare class ComfyPool extends EventTarget { clients: ComfyApi[]; private clientStates; private mode; private jobQueue; private routineIdx; private listeners; private maxQueueSize; constructor(clients: ComfyApi[], /** * The mode for picking clients from the queue. Defaults to "PICK_ZERO". */ mode?: EQueueMode, opts?: { /** * The maximum size of the job queue. Defaults to 1000. */ maxQueueSize?: number; }); on<K extends keyof TComfyPoolEventMap>(type: K, callback: (event: TComfyPoolEventMap[K]) => void, options?: AddEventListenerOptions | boolean): this; off<K extends keyof TComfyPoolEventMap>(type: K, callback: (event: TComfyPoolEventMap[K]) => void, options?: EventListenerOptions | boolean): this; /** * Removes all event listeners from the pool. */ removeAllListeners(): void; /** * Adds a client to the pool. * * @param client - The client to be added. * @returns Promise<void> */ addClient(client: ComfyApi): Promise<void>; destroy(): void; /** * Removes a client from the pool. * * @param client - The client to be removed. * @returns void */ removeClient(client: ComfyApi): void; /** * Removes a client from the pool by its index. * * @param index - The index of the client to remove. * @returns void * @fires removed - Fires a "removed" event with the removed client and its index as detail. */ removeClientByIndex(index: number): void; /** * Changes the mode of the queue. * * @param mode - The new mode to set for the queue. * @returns void */ changeMode(mode: EQueueMode): void; /** * Picks a ComfyApi client from the pool based on the given index. * * @param idx - The index of the client to pick. Defaults to 0 if not provided. * @returns The picked ComfyApi client. */ pick(idx?: number): ComfyApi; /** * Retrieves a `ComfyApi` object from the pool based on the provided ID. * @param id - The ID of the `ComfyApi` object to retrieve. * @returns The `ComfyApi` object with the matching ID, or `undefined` if not found. */ pickById(id: string): ComfyApi | undefined; /** * Executes a job using the provided client and optional client index. * * @template T The type of the result returned by the job. * @param {Function} job The job to be executed. * @param {number} [weight] The weight of the job. * @param {Object} [clientFilter] An object containing client filtering options. * @returns {Promise<T>} A promise that resolves with the result of the job. */ run<T>(job: (client: ComfyApi, clientIdx?: number) => Promise<T>, weight?: number, clientFilter?: { /** * Only one of the following clientIds will be picked. */ includeIds?: string[]; /** * The following clientIds will be excluded from the picking list. */ excludeIds?: string[]; }): Promise<T>; /** * Executes a batch of asynchronous jobs concurrently and returns an array of results. * * @template T - The type of the result returned by each job. * @param jobs - An array of functions that represent the asynchronous jobs to be executed. * @param weight - An optional weight value to assign to each job. * @param clientFilter - An optional object containing client filtering options. * @returns A promise that resolves to an array of results, in the same order as the jobs array. */ batch<T>(jobs: Array<(client: ComfyApi, clientIdx?: number) => Promise<T>>, weight?: number, clientFilter?: { /** * Only one of the following clientIds will be picked. */ includeIds?: string[]; /** * The following clientIds will be excluded from the picking list. */ excludeIds?: string[]; }): Promise<T[]>; private initializeClient; private bindClientSystemMonitor; private pushJobByWeight; private claim; private getAvailableClient; private pickJob; } declare abstract class AbstractFeature extends EventTarget { protected client: ComfyApi; protected supported: boolean; constructor(client: ComfyApi); get isSupported(): boolean; on(type: string, callback: (event: any) => void, options?: AddEventListenerOptions | boolean): () => void; off(type: string, callback: (event: any) => void, options?: EventListenerOptions | boolean): void; abstract destroy(): void; /** * Check if this feature is supported by the current client */ abstract checkSupported(): Promise<boolean>; } export type TMonitorEvent = { cpu_utilization: number; ram_total: number; ram_used: number; ram_used_percent: number; hdd_total: number; hdd_used: number; hdd_used_percent: number; device_type: "cuda"; gpus: Array<{ gpu_utilization: number; gpu_temperature: number; vram_total: number; vram_used: number; vram_used_percent: number; }>; }; export type TMonitorEventMap = { system_monitor: CustomEvent<TMonitorEvent>; }; declare class MonitoringFeature extends AbstractFeature { private resources?; private listeners; private binded; checkSupported(): Promise<boolean>; destroy(): void; private fetchApi; on<K extends keyof TMonitorEventMap>(type: K, callback: (event: TMonitorEventMap[K]) => void, options?: AddEventListenerOptions | boolean): () => void; off<K extends keyof TMonitorEventMap>(type: K, callback: (event: TMonitorEventMap[K]) => void, options?: EventListenerOptions | boolean): void; /** * Gets the monitor data. * * @returns The monitor data if supported, otherwise false. */ get monitorData(): false | TMonitorEvent | undefined; /** * Sets the monitor configuration. */ setConfig(config?: Partial<{ /** * Refresh per second (Default 0.5) */ rate: number; /** * Switch to enable/disable CPU monitoring */ switchCPU: boolean; /** * Switch to enable/disable GPU monitoring */ switchHDD: boolean; /** * Switch to enable/disable RAM monitoring */ switchRAM: boolean; /** * Path of HDD to monitor HDD usage (use getHddList to get the pick-able list) */ whichHDD: string; }>): Promise<false | Response>; /** * Switches the monitor on or off. */ switch(active: boolean): Promise<false | Response>; /** * Gets the list of HDDs. */ getHddList(): Promise<null | Array<string>>; /** * Gets the list of GPUs. */ getGpuList(): Promise<null | Array<{ index: number; name: string; }>>; /** * Config gpu monitoring * @param index Index of the GPU * @param config Configuration of monitoring, set to `true` to enable monitoring */ setGpuConfig(index: number, config: Partial<{ utilization: boolean; vram: boolean; temperature: boolean; }>): Promise<false | Response>; private bind; } export type TEventStatus = { status: { exec_info: { queue_remaining: number; }; }; sid: string; }; export type TExecution = { prompt_id: string; }; export type TExecuting = TExecution & { node: string | null; }; export type TProgress = TExecuting & { value: number; max: number; }; export type TExecuted<T = unknown> = TExecution & { node: string; output: T; }; export type TExecutionCached = TExecution & { nodes: string[]; }; export type TExecutionError = TExecution & { node_id: string; node_type: string; exception_message: string; exception_type: string; traceback: string[]; }; export type TExecutionInterrupted = TExecution & { node_id: string; node_type: string; executed: string[]; }; export type TComfyAPIEventMap = { all: CustomEvent<{ type: string; data: any; }>; auth_error: CustomEvent<Response>; auth_success: CustomEvent<null>; connection_error: CustomEvent<Error>; execution_success: CustomEvent<TExecution>; status: CustomEvent<TEventStatus>; disconnected: CustomEvent<null>; reconnecting: CustomEvent<null>; connected: CustomEvent<null>; reconnected: CustomEvent<null>; b_preview: CustomEvent<Blob>; log: CustomEvent<{ msg: string; data: any; }>; terminal: CustomEvent<{ m: string; t: string; }>; execution_start: CustomEvent<TExecution>; executing: CustomEvent<TExecuting>; progress: CustomEvent<TProgress>; executed: CustomEvent<TExecuted>; queue_error: CustomEvent<Error>; execution_error: CustomEvent<TExecutionError>; execution_interrupted: CustomEvent<TExecutionInterrupted>; execution_cached: CustomEvent<TExecutionCached>; }; export type TComfyPoolEventMap = { init: CustomEvent<null>; auth_error: CustomEvent<{ client: ComfyApi; clientIdx: number; res: Response; }>; connection_error: CustomEvent<{ client: ComfyApi; clientIdx: number; error: Error; }>; terminal: CustomEvent<{ clientIdx: number; m: string; t: string; }>; ready: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; auth_success: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; loading_client: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; change_mode: CustomEvent<{ mode: EQueueMode; }>; added: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; removed: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; connected: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; disconnected: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; reconnected: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; add_job: CustomEvent<{ jobIdx: number; weight: number; }>; have_job: CustomEvent<{ client: ComfyApi; remain: number; }>; idle: CustomEvent<{ client: ComfyApi; }>; execution_interrupted: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; executing: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; executed: CustomEvent<{ client: ComfyApi; clientIdx: number; }>; execution_error: CustomEvent<{ client: ComfyApi; clientIdx: number; error: Error; }>; system_monitor: CustomEvent<{ client: ComfyApi; clientIdx: number; data: TMonitorEvent; }>; }; export type TDefaultUI = "none" | "history" | "queue"; export type TExtensionActive = "Enabled" | "Disabled"; export type TPreviewMethod = "auto" | "latent2rgb" | "taesd" | "none"; declare enum EInstallationState { NOT_INSTALLED = "not-installed", INSTALLED = "installed" } declare enum EModelType { CHECKPOINT = "checkpoint", UNCLIP = "unclip", CLIP = "clip", VAE = "VAE", LORA = "lora", T2I_ADAPTER = "T2I-Adapter", T2I_STYLE = "T2I-Style", CONTROLNET = "controlnet", CLIP_VISION = "clip_vision", GLIGEN = "gligen", UPSCALE = "upscale", EMBEDDINGS = "embeddings", ETC = "etc" } declare enum EInstallType { GIT_CLONE = "git-clone", COPY = "copy", CNR = "cnr", UNZIP = "unzip" } declare enum EExtensionUpdateCheckResult { NO_UPDATE = 0, UPDATE_AVAILABLE = 1, FAILED = 2 } declare enum EUpdateResult { UNCHANGED = 0, SUCCESS = 1, FAILED = 2 } export interface IExtensionInfo { author: string; title: string; id: string; reference: string; repository: string; files: string[]; install_type: EInstallType; description: string; stars: number; last_update: string; trust: boolean; state: EInstallationState; /** * @deprecated Use `state` instead */ installed: boolean; version: string; updatable: boolean; } export interface IExtensionBaseRequest { /** * Custom Node name */ title?: string; /** * Install method */ install_type: EInstallType; /** * Files to download, clone or copy (can be git url, file url or file path) */ files: string[]; } export interface IInstallExtensionRequest extends IExtensionBaseRequest { /** * Destination path for copying files when install_type is "copy", default is custom_node folder */ js_path?: string; /** * Python packages to be installed */ pip?: string[]; } export interface IExtensionUninstallRequest extends IExtensionBaseRequest { /** * Install method */ install_type: EInstallType.GIT_CLONE | EInstallType.COPY; /** * Destination path for remove files when install_type is "copy", default is custom_node folder */ js_path?: string; } export interface IExtensionUpdateRequest extends IExtensionBaseRequest { /** * Install method */ install_type: EInstallType.GIT_CLONE; } export interface IExtensionActiveRequest extends IExtensionBaseRequest { /** * Install method */ install_type: EInstallType.GIT_CLONE | EInstallType.COPY; /** * Active status */ installed: TExtensionActive; /** * Destination path of extension when install_type is "copy". Default is custom_node folder */ js_path?: string; } export interface IModelInstallRequest { /** * Model name */ name?: string; /** * Place to save the model, set to `default` to use type instead */ save_path: string; /** * Type of model */ type: EModelType; /** * Model filename */ filename: string; /** * Model url to be downloaded */ url: string; } export interface INodeMapItem { url: string; nodeNames: Array<string>; title_aux: string; title?: string; author?: string; nickname?: string; description?: string; } declare class ManagerFeature extends AbstractFeature { checkSupported(): Promise<boolean>; destroy(): void; private fetchApi; /** * Set the default state to be displayed in the main menu when the browser starts. * * We use this api to checking if the manager feature is supported. * * Default will return the current state. * @deprecated Not working anymore */ defaultUi(setUi?: TDefaultUI): Promise<boolean>; getVersion(): Promise<string>; /** * Retrieves a list of extension's nodes based on the specified mode. * * Usefull to find the node suitable for the current workflow. * * @param mode - The mode to determine the source of the nodes. Defaults to "local". * @returns A promise that resolves to an array of extension nodes. * @throws An error if the retrieval fails. */ getNodeMapList(mode?: "local" | "nickname"): Promise<Array<INodeMapItem>>; /** * Checks for extension updates. * * @param mode - The mode to use for checking updates. Defaults to "local". * @returns The result of the extension update check. */ checkExtensionUpdate(mode?: "local" | "cache"): Promise<EExtensionUpdateCheckResult>; /** * Updates all extensions. * @param mode - The update mode. Can be "local" or "cache". Defaults to "local". * @returns An object representing the result of the extension update. */ updataAllExtensions(mode?: "local" | "cache"): Promise<{ type: EUpdateResult; readonly data?: undefined; } | { readonly type: EUpdateResult.SUCCESS; readonly data: { updated: number; failed: number; }; }>; /** * Updates the ComfyUI. * * @returns The result of the update operation. */ updateComfyUI(): Promise<EUpdateResult>; /** * Retrieves the list of extensions. * * @param mode - The mode to retrieve the extensions from. Can be "local" or "cache". Defaults to "local". * @param skipUpdate - Indicates whether to skip updating the extensions. Defaults to true. * @returns A promise that resolves to an object containing the channel and custom nodes, or false if the retrieval fails. * @throws An error if the retrieval fails. */ getExtensionList(mode?: "local" | "cache", skipUpdate?: boolean): Promise<{ channel: "local" | "default"; custom_nodes: IExtensionInfo[]; } | false>; /** * Reboots the instance. * * @returns A promise that resolves to `true` if the instance was successfully rebooted, or `false` otherwise. */ rebootInstance(): Promise<boolean>; /** * Return the current preview method. Will set to `mode` if provided. * * @param mode - The preview method mode. * @returns The result of the preview method. * @throws An error if the preview method fails to set. */ previewMethod(mode?: TPreviewMethod): Promise<TPreviewMethod | undefined>; /** * Installs an extension based on the provided configuration. * * @param config - The configuration for the extension installation. * @returns A boolean indicating whether the installation was successful. * @throws An error if the installation fails. */ installExtension(config: IInstallExtensionRequest): Promise<boolean>; /** * Try to fix installation of an extension by re-install it again with fixes. * * @param config - The configuration object for fixing the extension. * @returns A boolean indicating whether the extension was fixed successfully. * @throws An error if the fix fails. */ fixInstallExtension(config: Omit<IInstallExtensionRequest, "js_path" | "install_type"> & { install_type: EInstallType.GIT_CLONE; }): Promise<boolean>; /** * Install an extension from a Git URL. * * @param url - The URL of the Git repository. * @returns A boolean indicating whether the installation was successful. * @throws An error if the installation fails. */ installExtensionFromGit(url: string): Promise<boolean>; /** * Installs pip packages. * * @param packages - An array of packages to install. * @returns A boolean indicating whether the installation was successful. * @throws An error if the installation fails. */ installPipPackages(packages: string[]): Promise<boolean>; /** * Uninstalls an extension. * * @param config - The configuration for uninstalling the extension. * @returns A boolean indicating whether the uninstallation was successful. * @throws An error if the uninstallation fails. */ uninstallExtension(config: IExtensionUninstallRequest): Promise<boolean>; /** * Updates the extension with the provided configuration. Only work with git-clone method * * @param config - The configuration object for the extension update. * @returns A boolean indicating whether the extension update was successful. * @throws An error if the extension update fails. */ updateExtension(config: IExtensionUpdateRequest): Promise<boolean>; /** * Set the activation of extension. * * @param config - The configuration for the active extension. * @returns A boolean indicating whether the active extension was set successfully. * @throws An error if setting the active extension fails. */ setActiveExtension(config: IExtensionActiveRequest): Promise<boolean>; /** * Install a model from given info. * * @param info - The model installation request information. * @returns A boolean indicating whether the model installation was successful. * @throws An error if the model installation fails. */ installModel(info: IModelInstallRequest): Promise<boolean>; } export interface FetchOptions extends RequestInit { headers?: { [key: string]: string; }; } export declare class ComfyApi extends EventTarget { apiHost: string; osType: OSType; isReady: boolean; listenTerminal: boolean; lastActivity: number; private wsTimeout; private wsTimer; private _pollingTimer; private apiBase; private clientId; private socket; private listeners; private credentials; ext: { /** * Interact with ComfyUI-Manager Extension */ manager: ManagerFeature; /** * Interact with ComfyUI-Crystools Extension for track system resouces */ monitor: MonitoringFeature; }; static generateId(): string; on<K extends keyof TComfyAPIEventMap>(type: K, callback: (event: TComfyAPIEventMap[K]) => void, options?: AddEventListenerOptions | boolean): () => void; off<K extends keyof TComfyAPIEventMap>(type: K, callback: (event: TComfyAPIEventMap[K]) => void, options?: EventListenerOptions | boolean): void; removeAllListeners(): void; get id(): string; /** * Retrieves the available features of the client. * * @returns An object containing the available features, where each feature is a key-value pair. */ get availableFeatures(): {}; constructor(host: string, clientId?: string, opts?: { /** * Do not fallback to HTTP if WebSocket is not available. * This will retry to connect to WebSocket on error. */ forceWs?: boolean; /** * Timeout for WebSocket connection. * Default is 10000ms. */ wsTimeout?: number; /** * Listen to terminal logs from the server. Default (false) */ listenTerminal?: boolean; credentials?: BasicCredentials | BearerTokenCredentials | CustomCredentials; }); /** * Destroys the client instance. */ destroy(): void; private log; private apiURL; private getCredentialHeaders; private testCredentials; private testFeatures; /** * Fetches data from the API. * * @param route - The route to fetch data from. * @param options - The options for the fetch request. * @returns A promise that resolves to the response from the API. */ fetchApi(route: string, options?: FetchOptions): Promise<Response>; /** * Polls the status for colab and other things that don't support websockets. * @returns {Promise<QueueStatus>} The status information. */ pollStatus(timeout?: number): Promise<QueueStatus>; /** * Queues a prompt for processing. * @param {number} number The index at which to queue the prompt. using NULL will append to the end of the queue. * @param {object} workflow Additional workflow data. * @returns {Promise<QueuePromptResponse>} The response from the API. */ queuePrompt(number: number | null, workflow: object): Promise<QueuePromptResponse>; /** * Appends a prompt to the workflow queue. * * @param {object} workflow Additional workflow data. * @returns {Promise<QueuePromptResponse>} The response from the API. */ appendPrompt(workflow: object): Promise<QueuePromptResponse>; /** * Retrieves the current state of the queue. * @returns {Promise<QueueResponse>} The queue state. */ getQueue(): Promise<QueueResponse>; /** * Retrieves the prompt execution history. * @param {number} [maxItems=200] The maximum number of items to retrieve. * @returns {Promise<HistoryResponse>} The prompt execution history. */ getHistories(maxItems?: number): Promise<HistoryResponse>; /** * Retrieves the history entry for a given prompt ID. * @param promptId - The ID of the prompt. * @returns A Promise that resolves to the HistoryEntry object. */ getHistory(promptId: string): Promise<HistoryEntry | undefined>; /** * Retrieves system and device stats. * @returns {Promise<SystemStatsResponse>} The system stats. */ getSystemStats(): Promise<SystemStatsResponse>; /** * Retrieves the terminal logs from the server. */ getTerminalLogs(): Promise<{ entries: Array<{ t: string; m: string; }>; size: { cols: number; rows: number; }; }>; /** * Sets the terminal subscription status. * Enable will subscribe to terminal logs from websocket. */ setTerminalSubscription(subscribe: boolean): Promise<void>; /** * Retrieves a list of extension URLs. * @returns {Promise<string[]>} A list of extension URLs. */ getExtensions(): Promise<string[]>; /** * Retrieves a list of embedding names. * @returns {Promise<string[]>} A list of embedding names. */ getEmbeddings(): Promise<string[]>; /** * Retrieves the checkpoints from the server. * @returns A promise that resolves to an array of strings representing the checkpoints. */ getCheckpoints(): Promise<string[]>; /** * Retrieves the Loras from the node definitions. * @returns A Promise that resolves to an array of strings representing the Loras. */ getLoras(): Promise<string[]>; /** * Retrieves the sampler information. * @returns An object containing the sampler and scheduler information. */ getSamplerInfo(): Promise<{ sampler?: undefined; scheduler?: undefined; } | { sampler: [ string[], { tooltip?: string; } ] | [ string, { tooltip?: string; } ] | TStringInput | TBoolInput | TNumberInput; scheduler: [ string[], { tooltip?: string; } ] | [ string, { tooltip?: string; } ] | TStringInput | TBoolInput | TNumberInput; }>; /** * Retrieves node object definitions for the graph. * @returns {Promise<NodeDefsResponse>} The node definitions. */ getNodeDefs(nodeName?: string): Promise<NodeDefsResponse | null>; /** * Retrieves user configuration data. * @returns {Promise<any>} The user configuration data. */ getUserConfig(): Promise<any>; /** * Creates a new user. * @param {string} username The username of the new user. * @returns {Promise<Response>} The response from the API. */ createUser(username: string): Promise<Response>; /** * Retrieves all setting values for the current user. * @returns {Promise<any>} A dictionary of setting id to value. */ getSettings(): Promise<any>; /** * Retrieves a specific setting for the current user. * @param {string} id The id of the setting to fetch. * @returns {Promise<any>} The setting value. */ getSetting(id: string): Promise<any>; /** * Stores a dictionary of settings for the current user. * @param {Record<string, unknown>} settings Dictionary of setting id to value to save. * @returns {Promise<void>} */ storeSettings(settings: Record<string, unknown>): Promise<void>; /** * Stores a specific setting for the current user. * @param {string} id The id of the setting to update. * @param {unknown} value The value of the setting. * @returns {Promise<void>} */ storeSetting(id: string, value: unknown): Promise<void>; /** * Uploads an image file to the server. * @param file - The image file to upload. * @param fileName - The name of the image file. * @param override - Optional. Specifies whether to override an existing file with the same name. Default is true. * @returns A Promise that resolves to an object containing the image information and the URL of the uploaded image, * or false if the upload fails. */ uploadImage(file: Buffer | Blob, fileName: string, config?: { override?: boolean; subfolder?: string; }): Promise<{ info: ImageInfo; url: string; } | false>; /** * Uploads a mask file to the server. * * @param file - The mask file to upload, can be a Buffer or Blob. * @param originalRef - The original reference information for the file. * @returns A Promise that resolves to an object containing the image info and URL if the upload is successful, or false if the upload fails. */ uploadMask(file: Buffer | Blob, originalRef: ImageInfo): Promise<{ info: ImageInfo; url: string; } | false>; /** * Frees memory by unloading models and freeing memory. * * @param unloadModels - A boolean indicating whether to unload models. * @param freeMemory - A boolean indicating whether to free memory. * @returns A promise that resolves to a boolean indicating whether the memory was successfully freed. */ freeMemory(unloadModels: boolean, freeMemory: boolean): Promise<boolean>; /** * Returns the path to an image based on the provided image information. * @param imageInfo - The information of the image. * @returns The path to the image. */ getPathImage(imageInfo: ImageInfo): string; /** * Get blob of image based on the provided image information. Use when the server have credential. */ getImage(imageInfo: ImageInfo): Promise<Blob>; /** * Retrieves a user data file for the current user. * @param {string} file The name of the userdata file to load. * @returns {Promise<Response>} The fetch response object. */ getUserData(file: string): Promise<Response>; /** * Stores a user data file for the current user. * @param {string} file The name of the userdata file to save. * @param {unknown} data The data to save to the file. * @param {RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean }} [options] Additional options for storing the file. * @returns {Promise<Response>} */ storeUserData(file: string, data: unknown, options?: RequestInit & { overwrite?: boolean; stringify?: boolean; throwOnError?: boolean; }): Promise<Response>; /** * Deletes a user data file for the current user. * @param {string} file The name of the userdata file to delete. * @returns {Promise<void>} */ deleteUserData(file: string): Promise<void>; /** * Moves a user data file for the current user. * @param {string} source The userdata file to move. * @param {string} dest The destination for the file. * @param {RequestInit & { overwrite?: boolean }} [options] Additional options for moving the file. * @returns {Promise<Response>} */ moveUserData(source: string, dest: string, options?: RequestInit & { overwrite?: boolean; }): Promise<Response>; /** * Lists user data files for the current user. * @param {string} dir The directory in which to list files. * @param {boolean} [recurse] If the listing should be recursive. * @param {boolean} [split] If the paths should be split based on the OS path separator. * @returns {Promise<string[]>} The list of files. */ listUserData(dir: string, recurse?: boolean, split?: boolean): Promise<string[]>; /** * Interrupts the execution of the running prompt. * @returns {Promise<void>} */ interrupt(): Promise<void>; /** * Initializes the client. * * @param maxTries - The maximum number of ping tries. * @param delayTime - The delay time between ping tries in milliseconds. * @returns The initialized client instance. */ init(maxTries?: number, delayTime?: number): this; private pingSuccess; waitForReady(): Promise<this>; private pullOsType; /** * Sends a ping request to the server and returns a boolean indicating whether the server is reachable. * @returns A promise that resolves to `true` if the server is reachable, or `false` otherwise. */ ping(): Promise<{ readonly status: true; readonly time: number; } | { readonly status: false; }>; /** * Attempts to reconnect the WebSocket with an exponential backoff strategy * @param triggerEvent Whether to trigger disconnect/reconnect events */ reconnectWs(triggerEvent?: boolean): Promise<void>; private resetLastActivity; /** * Creates and connects a WebSocket for real-time updates. * @param {boolean} isReconnect If the socket connection is a reconnect attempt. */ /** * Creates and connects a WebSocket for real-time updates. * Falls back to polling if WebSocket is unavailable. * @param {boolean} isReconnect If the socket connection is a reconnect attempt. */ private createSocket; /** * Sets up a polling mechanism as a fallback when WebSockets are unavailable * Polls the server every 2 seconds for status updates */ /** * Sets up a polling mechanism as a fallback when WebSockets are unavailable * Polls the server every 2 seconds for status updates */ private setupPollingFallback; /** * Retrieves a list of all available model folders. * @experimental API that may change in future versions * @returns A promise that resolves to an array of ModelFolder objects. */ getModelFolders(): Promise<ModelFolder[]>; /** * Retrieves a list of all model files in a specific folder. * @experimental API that may change in future versions * @param folder - The name of the model folder. * @returns A promise that resolves to an array of ModelFile objects. */ getModelFiles(folder: string): Promise<ModelFile[]>; /** * Retrieves a preview image for a specific model file. * @experimental API that may change in future versions * @param folder - The name of the model folder. * @param pathIndex - The index of the folder path where the file is stored. * @param filename - The name of the model file. * @returns A promise that resolves to a ModelPreviewResponse object containing the preview image data. */ getModelPreview(folder: string, pathIndex: number, filename: string): Promise<ModelPreviewResponse>; /** * Creates a URL for a model preview image. * @experimental API that may change in future versions * @param folder - The name of the model folder. * @param pathIndex - The index of the folder path where the file is stored. * @param filename - The name of the model file. * @returns The URL string for the model preview. */ getModelPreviewUrl(folder: string, pathIndex: number, filename: string): string; } export type FixArr<T> = T extends readonly any[] ? Omit<T, Exclude<keyof any[], number>> : T; export type DropInitDot<T> = T extends `.${infer U}` ? U : T; export type _DeepKeys<T> = T extends object ? { [K in (string | number) & keyof T]: `${`.${K}`}${"" | _DeepKeys<FixArr<T[K]>>}`; }[(string | number) & keyof T] : never; export type DeepKeys<T> = DropInitDot<_DeepKeys<FixArr<T>>>; export type Simplify<T> = { [K in keyof T]: T[K]; } & {}; export declare class PromptBuilder<I extends string, O extends string, T extends NodeData> { prompt: T; mapInputKeys: Partial<Record<I, string | string[]>>; mapOutputKeys: Partial<Record<O, string>>; bypassNodes: (keyof T)[]; constructor(prompt: T, inputKeys: I[], outputKeys: O[]); /** * Creates a new instance of the PromptBuilder with the same prompt, input keys, and output keys. * * @returns A new instance of the PromptBuilder. */ clone(): PromptBuilder<I, O, T>; /** * Marks a node to be bypassed at generation. * * @param node Node which will be bypassed. */ bypass(node: keyof T): PromptBuilder<I, O, T>; /** * Marks multiple nodes to be bypassed at generation. * * @param nodes Array of nodes which will be bypassed. */ bypass(nodes: (keyof T)[]): PromptBuilder<I, O, T>; /** * Unmarks a node from bypass at generation. * * @param node Node to reverse bypass on. */ reinstate(node: keyof T): PromptBuilder<I, O, T>; /** * Unmarks a collection of nodes from bypass at generation. * * @param nodes Array of nodes to reverse bypass on. */ reinstate(nodes: (keyof T)[]): PromptBuilder<I, O, T>; /** * Sets the input node for a given key. Can be map multiple keys to the same input. * * @param input - The input node to set. * @param key - The key(s) to associate with the input node. Can be array of keys. * @returns This builder instance. */ setInputNode(input: I, key: DeepKeys<T> | Array<DeepKeys<T>>): PromptBuilder<I, O, T>; /** * Sets the raw input node for the given input and key. This will bypass the typing check. Use for dynamic nodes. * * @param input - The input node to be set. * @param key - The key associated with the input node. * @returns The current instance for method chaining. */ setRawInputNode(input: I, key: string | string[]): PromptBuilder<I, O, T>; /** * Appends raw input node keys to the map of input keys. This will bypass the typing check. Use for dynamic nodes. * * @param input - The input node to which the keys will be appended. * @param key - The key or array of keys to append to the input node. * @returns A clone of the current instance with the updated input keys. */ appendRawInputNode(input: I, key: string | string[]): PromptBuilder<I, O, T>; /** * Appends mapped key into the input node. * * @param input - The input node to append. * @param key - The key(s) to associate with the input node. Can be array of keys. * @returns The updated prompt builder. */ appendInputNode(input: I, key: DeepKeys<T> | Array<DeepKeys<T>>): PromptBuilder<I, O, T>; /** * Sets the output node for a given key. This will bypass the typing check. Use for dynamic nodes. * * @param output - The output node to set. * @param key - The key to associate with the output node. * @returns This builder instance. */ setRawOutputNode(output: O, key: string): PromptBuilder<I, O, T>; /** * Sets the output node for a given key. * * @param output - The output node to set. * @param key - The key to associate with the output node. * @returns This builder instance. */ setOutputNode(output: O, key: DeepKeys<T>): PromptBuilder<I, O, T>; /** * Sets the value for a specific input key in the prompt builder. * * @template V - The type of the value being set. * @param {I} key - The input key. * @param {V} value - The value to set. * @param {OSType} [encodeOs] - The OS type to encode the path. * @returns A new prompt builder with the updated value. * @throws {Error} - If the key is not found. */ input<V = string | number | undefined>(key: I, value: V, encodeOs?: OSType): Simplify<PromptBuilder<I, O, T>>; /** * Sets the value for a any input key in the prompt builder. * * @template V - The type of the value being set. * @param {string} key - The input key. * @param {V} value - The value to set. * @param {OSType} [encodeOs] - The OS type to encode the path. * @returns A new prompt builder with the updated value. * @throws {Error} - If the key is not found. */ inputRaw<V = string | number | undefined>(key: string, value: V, encodeOs?: OSType): Simplify<PromptBuilder<I, O, T>>; /** * @deprecated Please call `input` directly instead */ get caller(): this; /** * Gets the workflow object of the prompt builder. */ get workflow(): Simplify<T>; } /** * Represents a wrapper class for making API calls using the ComfyApi client. * Provides methods for setting callback functions and executing the job. */ export declare class CallWrapper<I extends string, O extends string, T extends NodeData> { private client; private prompt; private started; private promptId?; private output; private onPreviewFn?; private onPendingFn?; private onStartFn?; private onOutputFn?; private onFinishedFn?; private onFailedFn?; private onProgressFn?; private onDisconnectedHandlerOffFn; private checkExecutingOffFn; private checkExecutedOffFn; private progressHandlerOffFn; private previewHandlerOffFn; private executionHandlerOffFn; private errorHandlerOffFn; private executionEndSuccessOffFn; private statusHandlerOffFn; private interruptionHandlerOffFn; /** * Constructs a new CallWrapper instance. * @param client The ComfyApi client. * @param workflow The workflow object. */ constructor(client: ComfyApi, workflow: PromptBuilder<I, O, T>); /** * Set the callback function to be called when a preview event occurs. * * @param fn - The callback function to be called. It receives a Blob object representing the event and an optional promptId string. * @returns The current instance of the CallWrapper. */ onPreview(fn: (ev: Blob, promptId?: string) => void): this; /** * Set a callback function to be executed when the job is queued. * @param {Function} fn - The callback function to be executed. * @returns The current instance of the CallWrapper. */ onPending(fn: (promptId?: string) => void): this; /** * Set the callback function to be executed when the job start. * * @param fn - The callback function to be executed. It can optionally receive a `promptId` parameter. * @returns The current instance of the CallWrapper. */ onStart(fn: (promptId?: string) => void): this; /** * Sets the callback function to handle the output node when the workflow is executing. This is * useful when you want to handle the output of each nodes as they are being processed. * * All the nodes defined in the `mapOutputKeys` will be passed to this function when node is executed. * * @param fn - The callback function to handle the output. * @returns The current instance of the class. */ onOutput(fn: (key: keyof PromptBuilder<I, O, T>["mapOutputKeys"] | "_raw", data: any, promptId?: string) => void): this; /** * Set the callback function to be executed when the asynchronous operation is finished. * * @param fn - The callback function to be executed. It receives the data returned by the operation * and an optional promptId parameter. * @returns The current instance of the CallWrapper. */ onFinished(fn: (data: Record<keyof PromptBuilder<I, O, T>["mapOutputKeys"], any> & { /** * The raw output data from the workflow execution. * Key is node_id, value is node output. */ _raw?: Record<string, any>; }, promptId?: string) => void): this; /** * Set the callback function to be executed when the API call fails. * * @param fn - The callback function to be executed when the API call fails. * It receives an `Error` object as the first parameter and an optional `promptId` as the second parameter. * @returns The current instance of the CallWrapper. */ onFailed(fn: (err: Error, promptId?: string) => void): this; /** * Set a callback function to be called when progress information is available. * @param fn - The callback function to be called with the progress information. * @returns The current instance of the CallWrapper. */ onProgress(fn: (info: NodeProgress, promptId?: string) => void): this; /** * Run the call wrapper and returns the output of the executed job. * If the job is already cached, it returns the cached output. * If the job is not cached, it executes the job and returns the output. * * @returns A promise that resolves to the output of the executed job, * or `undefined` if the job is not found, * or `false` if the job execution fails. */ run(): Promise<Record<keyof PromptBuilder<I, O, T>["mapOutputKeys"] | "_raw", any> | undefined | false>; private bypassWorkflowNodes; private enqueueJob; private handleCachedOutput; private mapOutput; private handleJobExecution; private reverseMapOutputKeys; private handleProgress; private handleError; private cleanupListeners; } export type TSamplerName = "euler" | "euler_cfg_pp" | "euler_ancestral" | "euler_ancestral_cfg_pp" | "heun" | "heunpp2" | "dpm_2" | "dpm_2_ancestral" | "lms" | "dpm_fast" | "dpm_adaptive" | "dpmpp_2s_ancestral" | "dpmpp_sde" | "dpmpp_sde_gpu" | "dpmpp_2m" | "dpmpp_2m_sde" | "dpmpp_2m_sde_gpu" | "dpmpp_3m_sde" | "dpmpp_3m_sde_gpu" | "ddpm" | "lcm" | "ipndm" | "ipndm_v" | "deis" | "ddim" | "uni_pc" | "uni_pc_bh2"; export type TSchedulerName = "normal" | "karras" | "exponential" | "sgm_uniform" | "simple" | "ddim_uniform"; export {};