Line data Source code
1 : import type {
2 : GetEmbeddingsResponse,
3 : GetExtensionsResponse,
4 : GetI18nResponse,
5 : ModelDownloadData,
6 : ModelFile,
7 : PostAssetsFromWorkflowResponse,
8 : PromptOutputsSkippedData
9 : } from '@comfyorg/ingest-types'
10 : import {
11 : zGetEmbeddingsResponse,
12 : zGetExtensionsResponse,
13 : zPostAssetsFromWorkflowResponse
14 : } from '@comfyorg/ingest-types/zod'
15 : import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types'
16 : import axios from 'axios'
17 : import { get } from 'es-toolkit/compat'
18 : import { trimEnd } from 'es-toolkit'
19 : import { ref } from 'vue'
20 :
21 : import { combineAbortSignals } from './abortSignal'
22 : import defaultClientFeatureFlags from './clientFeatureFlags.json' with { type: 'json' }
23 : import type { ApiAuthProvider } from './apiAuthProvider'
24 : import { anonymousApiAuthProvider } from './apiAuthProvider'
25 : import { authCredentialOf, notifyAuthCredential } from './authCredential'
26 : import { scopeMediaRoute } from './sessionMediaUrl'
27 : import { webSessionRequests } from './webSessionFetch'
28 : import { FETCH_RESPONSE_HEADERS_TIMEOUT_MS } from './apiTimeouts'
29 : import { addBreadcrumb } from '@sentry/vue'
30 : import { useTelemetry } from '@comfyorg/telemetry'
31 : import { reportError } from '@comfyorg/telemetry/reportError'
32 : import type { components as ManagerComponents } from './generatedManagerTypes'
33 : import type {
34 : AgentStatusWsMessage,
35 : AssetDownloadWsMessage,
36 : AssetExportWsMessage,
37 : AssetSeedCompletedWsMessage,
38 : ExecutedWsMessage,
39 : ExecutingWsMessage,
40 : ExecutionCachedWsMessage,
41 : ExecutionErrorWsMessage,
42 : ExecutionInterruptedWsMessage,
43 : ExecutionStartWsMessage,
44 : ExecutionSuccessWsMessage,
45 : FeatureFlagsWsMessage,
46 : LogsRawResponse,
47 : LogsWsMessage,
48 : NotificationWsMessage,
49 : ProgressStateWsMessage,
50 : ProgressTextWsMessage,
51 : ProgressWsMessage,
52 : StatusWsMessage,
53 : StatusWsMessageStatus
54 : } from './executionTypes'
55 : import type {
56 : ModelFolderInfo,
57 : PromptFailureResponse,
58 : PromptResponse,
59 : SystemStats,
60 : UserConfigResponse,
61 : UserDataFullInfo
62 : } from './types'
63 : import type { PreviewMethod, Settings } from '@comfyorg/settings-core/types'
64 : import type {
65 : TemplateIncludeOnDistributionEnum,
66 : WorkflowTemplates
67 : } from './templateTypes'
68 : import type {
69 : ComfyApiWorkflow,
70 : ComfyWorkflowJSON
71 : } from '@comfyorg/graph-model/workflowSchema'
72 : import type { SerializedNodeId } from '@comfyorg/graph-model/nodeId'
73 : import type { JobAssetsResult, JobDetail, JobListItem } from './jobTypes'
74 : import type { ComfyNodeDef } from '@comfyorg/object-info-parser'
75 : import type { AuthCredential, AuthScheme } from './authTypes'
76 : import type { NodeExecutionId } from '@comfyorg/graph-model/nodeIdentification'
77 : import { zeroUuid } from '@comfyorg/graph-model/uuid'
78 : import { getFetchRouteTemplate } from './fetchRouteTemplate'
79 : import { retryingSend } from './fetchWithRetry'
80 : import { NO_RETRY_POLICY } from './retryPolicy'
81 : import type { RetryPolicy } from './retryPolicy'
82 : import {
83 : fetchHistory,
84 : fetchJobAssets,
85 : fetchJobDetail,
86 : fetchQueue
87 : } from './fetchJobs'
88 :
89 2356 : const SERVER_FEATURE_FLAGS_TIMEOUT_MS = 5_000
90 :
91 : interface QueuePromptRequestBody {
92 : client_id: string
93 : prompt: ComfyApiWorkflow
94 : partial_execution_targets?: NodeExecutionId[]
95 : workflow_metadata?: Pick<PromptWorkflowMetadata, 'workflow_id'>
96 : extra_data: {
97 : extra_pnginfo: {
98 : workflow: ComfyWorkflowJSON
99 : }
100 : /**
101 : * The auth token for the comfy org account if the user is logged in.
102 : *
103 : * Backend node can access this token by specifying following input:
104 : * ```python
105 : @classmethod
106 : def INPUT_TYPES(s):
107 : return {
108 : "hidden": { "auth_token": "AUTH_TOKEN_COMFY_ORG"}
109 : }
110 :
111 : def execute(self, auth_token: str):
112 : print(f"Auth token: {auth_token}")
113 : * ```
114 : */
115 : auth_token_comfy_org?: string
116 : /**
117 : * The auth token for the comfy org account if the user is logged in.
118 : *
119 : * Backend node can access this token by specifying following input:
120 : * ```python
121 : * def INPUT_TYPES(s):
122 : * return {
123 : * "hidden": { "api_key": "API_KEY_COMFY_ORG" }
124 : * }
125 : *
126 : * def execute(self, api_key: str):
127 : * print(f"API Key: {api_key}")
128 : * ```
129 : */
130 : api_key_comfy_org?: string
131 : /**
132 : * Identifies the client submitting the prompt. Forwarded by the backend
133 : * to API nodes' upstream requests via the Comfy-Usage-Source header.
134 : */
135 : comfy_usage_source?: string
136 : /**
137 : * Override the preview method for this prompt execution.
138 : * 'default' uses the server's CLI setting.
139 : */
140 : preview_method?: PreviewMethod
141 : }
142 : front?: boolean
143 : number?: number
144 : }
145 :
146 : interface FetchApiOptions extends RequestInit {
147 : timeoutMs?: number | null
148 : onAuthHeader?: (attached: boolean) => void
149 : /** Reports which auth path was taken, independent of onAuthHeader's attached/not boolean. */
150 : onAuthScheme?: (scheme: AuthScheme) => void
151 : /** Reports the kind of credential sent, to tell a missing token from a wrong one. */
152 : onAuthCredential?: (credential: AuthCredential) => void
153 : /** Send once, for callers that already retry on their own backoff. */
154 : skipStatusRetry?: boolean
155 : }
156 :
157 : /**
158 : * Options for queuePrompt method
159 : */
160 : interface QueuePromptOptions {
161 : /**
162 : * Optional list of node execution IDs to execute (partial execution).
163 : * Each ID represents a node's position in nested subgraphs.
164 : * Format: Colon-separated path of node IDs (e.g., "123:456:789")
165 : */
166 : partialExecutionTargets?: NodeExecutionId[]
167 : /**
168 : * Override the preview method for this prompt execution.
169 : * 'default' uses the server's CLI setting and is not sent to backend.
170 : */
171 : previewMethod?: PreviewMethod
172 : }
173 :
174 : /** Dictionary of Frontend-generated API calls */
175 : interface FrontendApiCalls {
176 : graphChanged: ComfyWorkflowJSON
177 : /**
178 : * Signals that auto-queue should treat the active workflow as changed.
179 : * Local change-tracker edits are filtered through the prompt-relevant
180 : * projection and evaluated only while Run (on change) is active. For those
181 : * edits, position, size, title, collapse, group, viewport, and slot-label
182 : * changes do not trigger this signal.
183 : * Server-pushed `graphChanged` messages are forwarded unfiltered.
184 : * Third-party presentation-only nodes are treated as prompt-relevant.
185 : */
186 : autoQueueGraphChanged: never
187 : promptQueueing: { requestId: number; batchCount: number; number?: number }
188 : promptQueued: { number: number; batchCount: number; requestId?: number }
189 : graphCleared: never
190 : reconnecting: never
191 : reconnected: never
192 : }
193 :
194 : export type PromptQueueingEventPayload = FrontendApiCalls['promptQueueing']
195 : export type PromptQueuedEventPayload = FrontendApiCalls['promptQueued']
196 :
197 : /** Dictionary of calls originating from ComfyUI core */
198 : interface BackendApiCalls {
199 : progress: ProgressWsMessage
200 : executing: ExecutingWsMessage
201 : executed: ExecutedWsMessage
202 : status: StatusWsMessage
203 : notification: NotificationWsMessage
204 : execution_start: ExecutionStartWsMessage
205 : execution_success: ExecutionSuccessWsMessage
206 : execution_error: ExecutionErrorWsMessage
207 : execution_interrupted: ExecutionInterruptedWsMessage
208 : execution_cached: ExecutionCachedWsMessage
209 : prompt_outputs_skipped: PromptOutputsSkippedData
210 : logs: LogsWsMessage
211 : /** Binary preview/progress data */
212 : b_preview: Blob
213 : /** Binary preview with metadata (node_id, job_id) */
214 : b_preview_with_metadata: {
215 : blob: Blob
216 : nodeId: string
217 : parentNodeId: string
218 : displayNodeId: string
219 : realNodeId: string
220 : jobId: string
221 : workflowId?: string
222 : }
223 : progress_text: ProgressTextWsMessage
224 : progress_state: ProgressStateWsMessage
225 : feature_flags: FeatureFlagsWsMessage
226 : agent_status: AgentStatusWsMessage
227 : asset_download: AssetDownloadWsMessage
228 : model_download: ModelDownloadData
229 : asset_export: AssetExportWsMessage
230 : 'assets.seed.completed': AssetSeedCompletedWsMessage
231 : }
232 :
233 : /** Dictionary of all api calls */
234 : interface ApiCalls extends BackendApiCalls, FrontendApiCalls {
235 : 'cm-task-started': ManagerComponents['schemas']['MessageTaskStarted']
236 : 'cm-task-completed': ManagerComponents['schemas']['MessageTaskDone']
237 : }
238 :
239 : /** Used to create a discriminating union on type value. */
240 : interface ApiMessage<T extends keyof ApiCalls> {
241 : type: T
242 : data: ApiCalls[T]
243 : }
244 :
245 2356 : export class UnauthorizedError extends Error {}
246 :
247 2356 : const CLIENT_ID_STORAGE_KEY = 'clientId'
248 :
249 2356 : let reportedClientIdStorageFailure = false
250 :
251 4718 : function withClientIdStorage<T>(
252 : access: (storage: Storage) => T
253 : ): T | undefined {
254 4718 : try {
255 4718 : return access(window.sessionStorage)
256 : } catch (cause) {
257 0 : if (!reportedClientIdStorageFailure) {
258 0 : reportedClientIdStorageFailure = true
259 0 : reportError(cause, {
260 : errorType: 'failure_accessing_client_id_storage',
261 : surface: 'platform',
262 : level: 'warning'
263 : })
264 : }
265 0 : return undefined
266 : }
267 : }
268 :
269 : /** Ensures workers get a fair shake. */
270 : type Unionize<T> = T[keyof T]
271 :
272 : /**
273 : * Discriminated union of generic, i.e.:
274 : * ```ts
275 : * // Convert
276 : * type ApiMessageUnion = ApiMessage<'status' | 'executing' | ...>
277 : * // To
278 : * type ApiMessageUnion = ApiMessage<'status'> | ApiMessage<'executing'> | ...
279 : * ```
280 : */
281 : type ApiMessageUnion = Unionize<{
282 : [Key in keyof ApiCalls]: ApiMessage<Key>
283 : }>
284 :
285 : /** Wraps all properties in {@link CustomEvent}. */
286 : type AsCustomEvents<T> = {
287 : readonly [K in keyof T]: CustomEvent<T[K]>
288 : }
289 :
290 : /** Handles differing event and API signatures. */
291 : type ApiToEventType<T = ApiCalls> = {
292 : [K in keyof T]: K extends 'status'
293 : ? StatusWsMessageStatus
294 : : K extends 'executing'
295 : ? SerializedNodeId
296 : : T[K]
297 : }
298 :
299 : /** Dictionary of types used in the detail for a custom event */
300 : type ApiEventTypes = ApiToEventType
301 :
302 : /** Dictionary of API events: `[name]: CustomEvent<Type>` */
303 : type ApiEvents = AsCustomEvents<ApiEventTypes>
304 :
305 : /** {@link Omit} all properties that evaluate to `never`. */
306 : type NeverNever<T> = {
307 : [K in keyof T as T[K] extends never ? never : K]: T[K]
308 : }
309 :
310 : /** {@link Pick} only properties that evaluate to `never`. */
311 : type PickNevers<T> = {
312 : [K in keyof T as T[K] extends never ? K : never]: T[K]
313 : }
314 :
315 : /** Keys (names) of API events that _do not_ pass a {@link CustomEvent} `detail` object. */
316 : type SimpleApiEvents = keyof PickNevers<ApiEventTypes>
317 : /** Keys (names) of API events that pass a {@link CustomEvent} `detail` object. */
318 : type ComplexApiEvents = keyof NeverNever<ApiEventTypes>
319 :
320 : export type GlobalSubgraphData = {
321 : name: string
322 : info: {
323 : node_pack: string
324 : category?: string
325 : search_aliases?: string[]
326 : requiresCustomNodes?: string[]
327 : includeOnDistributions?: TemplateIncludeOnDistributionEnum[]
328 : }
329 : data: string | Promise<string>
330 : essentials_category?: string
331 : }
332 :
333 : type WebSessionSend = (url: string, init: RequestInit) => Promise<Response>
334 :
335 312936 : function addHeaderEntry(headers: HeadersInit, key: string, value: string) {
336 312936 : if (Array.isArray(headers)) {
337 0 : headers.push([key, value])
338 312936 : } else if (headers instanceof Headers) {
339 0 : headers.set(key, value)
340 : } else {
341 312936 : headers[key] = value
342 : }
343 : }
344 :
345 : /** EventTarget typing has no generic capability. */
346 : export interface ComfyApi extends EventTarget {
347 : addEventListener<TEvent extends keyof ApiEvents>(
348 : type: TEvent,
349 : callback: ((event: ApiEvents[TEvent]) => void) | EventListenerObject | null,
350 : options?: AddEventListenerOptions | boolean
351 : ): void
352 :
353 : removeEventListener<TEvent extends keyof ApiEvents>(
354 : type: TEvent,
355 : callback: ((event: ApiEvents[TEvent]) => void) | EventListenerObject | null,
356 : options?: EventListenerOptions | boolean
357 : ): void
358 : }
359 :
360 2356 : export class PromptExecutionError extends Error {
361 : response: PromptFailureResponse
362 : status?: number
363 :
364 : constructor(response: PromptFailureResponse, status?: number) {
365 35 : super('Prompt execution failed')
366 35 : this.response = response
367 35 : this.status = status
368 : }
369 :
370 : override toString() {
371 48 : let message = ''
372 48 : const error = this.response.error
373 48 : if (typeof error === 'string') {
374 0 : message += error
375 48 : } else if (typeof error === 'object' && error !== null) {
376 46 : const errorMessage = 'message' in error ? error.message : undefined
377 46 : const errorDetails = 'details' in error ? error.details : undefined
378 46 : if (typeof errorMessage === 'string') {
379 46 : message += errorMessage
380 46 : if (typeof errorDetails === 'string') {
381 46 : message += ': ' + errorDetails
382 : }
383 : }
384 : }
385 48 : if (!message && typeof this.response.message === 'string') {
386 0 : message += this.response.message
387 : }
388 :
389 48 : for (const [_, nodeError] of Object.entries(
390 : this.response.node_errors ?? []
391 : )) {
392 37 : message += '\n' + nodeError.class_type + ':'
393 37 : for (const errorReason of nodeError.errors) {
394 37 : message += '\n - ' + errorReason.message
395 37 : if (errorReason.details) message += ': ' + errorReason.details
396 : }
397 : }
398 :
399 48 : return message
400 : }
401 : }
402 :
403 : interface LaunchContext {
404 : host: string
405 : base: string
406 : initialClientId: string | null
407 : }
408 :
409 : export type FreeMemoryResult =
410 : | { ok: true; freedExecutionCache: boolean }
411 : | { ok: false; reason: 'rejected' | 'unreachable' }
412 :
413 : /** Host capabilities the composition root supplies to the client. */
414 : export interface ComfyApiPorts {
415 : readonly isCloud: boolean
416 : /** A session or developer override for a server feature flag; undefined when none applies. */
417 : readonly featureFlagOverride: <T>(
418 : featureName: string & { readonly valueType?: T }
419 : ) => T | undefined
420 : readonly onFreeMemory: (result: FreeMemoryResult) => void
421 : }
422 :
423 2356 : function readLaunchContext(isCloud: boolean): LaunchContext {
424 2356 : return {
425 : host: location.host,
426 : base: isCloud ? '' : location.pathname.split('/').slice(0, -1).join('/'),
427 : initialClientId:
428 : withClientIdStorage((storage) =>
429 : storage.getItem(CLIENT_ID_STORAGE_KEY)
430 : ) ?? null
431 : }
432 : }
433 :
434 2356 : export class ComfyApi extends EventTarget {
435 : private _registered = new Set()
436 : /**
437 : * Maps an original event listener to its error-guarded wrapper, so that
438 : * {@link removeEventListener} can match the wrapper installed by
439 : * {@link addEventListener}. Keyed weakly so wrappers are GC'd with listeners.
440 : */
441 : private _listenerWrappers = new WeakMap<
442 : EventListenerOrEventListenerObject,
443 : EventListener
444 : >()
445 : private launchContext?: LaunchContext
446 : /**
447 : * The current client id from websocket status updates.
448 : */
449 : clientId?: string
450 : /**
451 : * The current user id.
452 : */
453 : user: string
454 : socket: WebSocket | null = null
455 :
456 : /**
457 : * Monotonic id bumped by every createSocket() attempt. Because createSocket()
458 : * holds `this.socket === null` across its async token fetch, two attempts can
459 : * overlap (an identity reset racing the close-handler's reconnect, or two
460 : * resets in quick succession). Each attempt captures its generation and, once
461 : * its awaits settle, only proceeds if it is still the latest — so the newest
462 : * identity always wins and superseded attempts never open a leaked socket.
463 : */
464 : private socketGeneration = 0
465 : private socketRetryDelayMs = 1_000
466 :
467 : private authProvider: ApiAuthProvider = anonymousApiAuthProvider
468 :
469 : reportedUnknownMessageTypes = new Set<string>()
470 :
471 : /**
472 : * Get feature flags supported by this frontend client.
473 : * Returns a copy to prevent external modification.
474 : */
475 : getClientFeatureFlags(): Record<string, unknown> {
476 20762 : return { ...defaultClientFeatureFlags }
477 : }
478 :
479 : /**
480 : * Feature flags received from the backend server.
481 : */
482 : serverFeatureFlags = ref<Record<string, unknown>>({})
483 :
484 : /**
485 : * Whether feature-flag negotiation for the current socket has settled: the
486 : * server delivered a map, or delivery was abandoned (5s timeout, or the
487 : * socket closed first). Not monotonic: each replacement socket resets it to
488 : * false, so it can flip repeatedly while a connection is reconnecting. True
489 : * does not imply the map is non-empty, and after {@link resetSocket}
490 : * {@link serverFeatureFlags} still holds the previous identity's map until
491 : * the next `feature_flags` message replaces it.
492 : */
493 : serverFeatureFlagsSettled = ref(false)
494 :
495 : /**
496 : * The auth token for the comfy org account if the user is logged in.
497 : * This is only used for {@link queuePrompt} now. It is not directly
498 : * passed as parameter to the function because some custom nodes are hijacking
499 : * {@link queuePrompt} improperly, which causes extra parameters to be lost
500 : * in the function call chain.
501 : *
502 : * Ref: https://cs.comfy.org/search?q=context:global+%22api.queuePrompt+%3D%22&patternType=keyword&sm=0
503 : *
504 : * TODO: Move this field to parameter of {@link queuePrompt} once all
505 : * custom nodes are patched.
506 : */
507 : authToken?: string
508 : /**
509 : * The API key for the comfy org account if the user logged in via API key.
510 : */
511 : apiKey?: string
512 :
513 2356 : constructor(private readonly ports: ComfyApiPorts) {
514 2356 : super()
515 2356 : this.user = ''
516 : }
517 :
518 : /**
519 : * Snapshots the page host, base path, and stored client id. Runs on first
520 : * use; the bootstrap calls it before routing can change the location.
521 : */
522 : captureLaunchContext(): void {
523 2355 : this.launchContext ??= readLaunchContext(this.ports.isCloud)
524 : }
525 :
526 : private get capturedLaunchContext(): LaunchContext {
527 382806 : this.launchContext ??= readLaunchContext(this.ports.isCloud)
528 382806 : return this.launchContext
529 : }
530 :
531 : get api_host(): string {
532 2364 : return this.capturedLaunchContext.host
533 : }
534 :
535 : set api_host(host: string) {
536 0 : this.launchContext = { ...this.capturedLaunchContext, host }
537 : }
538 :
539 : get api_base(): string {
540 364021 : return this.capturedLaunchContext.base
541 : }
542 :
543 : set api_base(base: string) {
544 0 : this.launchContext = { ...this.capturedLaunchContext, base }
545 : }
546 :
547 : /** The client id from the initial session storage. */
548 : get initialClientId(): string | null {
549 16421 : return this.capturedLaunchContext.initialClientId
550 : }
551 :
552 : set initialClientId(initialClientId: string | null) {
553 0 : this.launchContext = { ...this.capturedLaunchContext, initialClientId }
554 : }
555 :
556 : internalURL(route: string): string {
557 5270 : return this.api_base + '/internal' + route
558 : }
559 :
560 : apiURL(route: string): string {
561 345286 : const requests = webSessionRequests()
562 345286 : return this.unscopedApiURL(
563 : requests ? scopeMediaRoute(route, requests.workspaceId()) : route
564 : )
565 : }
566 :
567 : /** For requests whose headers already name the workspace. */
568 : private unscopedApiURL(route: string): string {
569 345286 : if (route.startsWith('/api')) return this.api_base + route
570 344855 : return this.api_base + '/api' + route
571 : }
572 :
573 : fileURL(route: string): string {
574 11101 : return this.api_base + route
575 : }
576 :
577 : /**
578 : * Installs the credentials source for every request and socket connection.
579 : * Called once by the composition root; requests made before that are
580 : * anonymous.
581 : */
582 : setAuthProvider(provider: ApiAuthProvider): void {
583 0 : this.authProvider = provider
584 : }
585 :
586 : private async getWebSessionSend(
587 : retryPolicy?: RetryPolicy
588 : ): Promise<WebSessionSend | undefined> {
589 33 : const requests = webSessionRequests()
590 33 : if (!requests) return undefined
591 0 : const scope = await requests.scope()
592 33 : return (
593 : scope &&
594 : retryingSend((url, init) => requests.send(url, init, scope), retryPolicy)
595 : )
596 : }
597 :
598 : /** Sends a same-origin request on the web session; undefined when this tab is not on it. */
599 : async fetchOnWebSession(
600 : url: string,
601 : init: RequestInit
602 : ): Promise<Response | undefined> {
603 : const send = await this.getWebSessionSend()
604 33 : return send?.(url, init)
605 : }
606 :
607 : /**
608 : * Adds today's token header, reporting the scheme that was actually used and
609 : * whether a 401 may be re-minted.
610 : *
611 : * The scheme is returned rather than assumed by the caller because this helper
612 : * is the only place that knows whether a header was obtained: it reports
613 : * `authHeader !== null` through `onAuthHeader` and attaches nothing when auth
614 : * is unavailable. A caller that announced `cloud-auth-header` on entry to this
615 : * path would misreport exactly the unauthenticated case PM-1802 is about.
616 : */
617 : private async addCloudAuthHeader(
618 : headers: HeadersInit,
619 : onAuthHeader: FetchApiOptions['onAuthHeader']
620 : ): Promise<{
621 : scheme: AuthScheme
622 : credential: AuthCredential
623 : unifiedRetryOn401: boolean
624 : }> {
625 0 : const authHeader = await this.authProvider.getAuthHeader()
626 0 : onAuthHeader?.(authHeader !== null)
627 0 : if (!authHeader) {
628 0 : return { scheme: 'none', credential: 'none', unifiedRetryOn401: false }
629 : }
630 :
631 0 : for (const [key, value] of Object.entries(authHeader)) {
632 0 : addHeaderEntry(headers, key, value)
633 : }
634 0 : return {
635 : scheme: 'cloud-auth-header',
636 : credential: authCredentialOf(authHeader),
637 : unifiedRetryOn401: await this.authProvider.shouldRetryOn401()
638 : }
639 : }
640 :
641 : async fetchApi(route: string, options?: FetchApiOptions) {
642 312936 : const {
643 : timeoutMs = FETCH_RESPONSE_HEADERS_TIMEOUT_MS,
644 : onAuthHeader,
645 : onAuthScheme,
646 : onAuthCredential,
647 : skipStatusRetry,
648 : ...requestOptions
649 : } = options ?? {}
650 312936 : const retryPolicy = skipStatusRetry ? NO_RETRY_POLICY : undefined
651 312936 : const headers: HeadersInit = requestOptions.headers ?? {}
652 312936 : let unifiedRetryOn401 = false
653 312936 : let sendOnWebSession: WebSessionSend | undefined
654 :
655 312936 : if (this.ports.isCloud) {
656 0 : await this.authProvider.waitForInitialization()
657 0 : sendOnWebSession = await this.getWebSessionSend(retryPolicy)
658 0 : if (sendOnWebSession) {
659 0 : onAuthHeader?.(true)
660 0 : onAuthScheme?.('web-session')
661 0 : notifyAuthCredential(onAuthCredential, 'session-cookie')
662 : } else {
663 0 : const cloudAuth = await this.addCloudAuthHeader(headers, onAuthHeader)
664 0 : unifiedRetryOn401 = cloudAuth.unifiedRetryOn401
665 0 : onAuthScheme?.(cloudAuth.scheme)
666 0 : notifyAuthCredential(onAuthCredential, cloudAuth.credential)
667 : }
668 : } else {
669 312936 : onAuthHeader?.(false)
670 312936 : onAuthScheme?.('none')
671 312936 : notifyAuthCredential(onAuthCredential, 'none')
672 : }
673 :
674 312936 : addHeaderEntry(headers, 'Comfy-User', this.user)
675 :
676 312936 : const timeout =
677 : timeoutMs === null
678 : ? null
679 : : { controller: new AbortController(), duration: timeoutMs }
680 312936 : const timeoutId = timeout
681 : ? setTimeout(() => {
682 0 : const method = (requestOptions.method ?? 'GET').toUpperCase()
683 0 : const routeTemplate = getFetchRouteTemplate(route)
684 :
685 0 : addBreadcrumb({
686 : category: 'fetch',
687 : message: `Timeout on ${method} ${routeTemplate}`,
688 : level: 'warning',
689 : data: { timeout_ms: timeout.duration }
690 : })
691 :
692 0 : useTelemetry()?.trackFetchTimeout({
693 : route: routeTemplate,
694 : method,
695 : timeout_ms: timeout.duration
696 : })
697 :
698 0 : timeout.controller.abort(
699 : new DOMException('Fetch timeout', 'TimeoutError')
700 : )
701 : }, timeout.duration)
702 : : undefined
703 312936 : const signal =
704 : requestOptions.signal && timeout
705 : ? combineAbortSignals([
706 : requestOptions.signal,
707 : timeout.controller.signal
708 : ])
709 : : (requestOptions.signal ?? timeout?.controller.signal)
710 :
711 312936 : let retryTimeoutId: ReturnType<typeof setTimeout> | undefined
712 312936 : const retrySignalLifecycle = timeout
713 : ? {
714 : clearInitialTimeout: () => {
715 0 : if (timeoutId !== undefined) clearTimeout(timeoutId)
716 : },
717 : createSignal: () => {
718 0 : const retryController = new AbortController()
719 0 : retryTimeoutId = setTimeout(() => {
720 0 : const method = (requestOptions.method ?? 'GET').toUpperCase()
721 0 : const routeTemplate = getFetchRouteTemplate(route)
722 :
723 0 : addBreadcrumb({
724 : category: 'fetch',
725 : message: `Timeout on ${method} ${routeTemplate}`,
726 : level: 'warning',
727 : data: { timeout_ms: timeout.duration }
728 : })
729 :
730 0 : useTelemetry()?.trackFetchTimeout({
731 : route: routeTemplate,
732 : method,
733 : timeout_ms: timeout.duration
734 : })
735 :
736 0 : retryController.abort(
737 : new DOMException('Fetch timeout', 'TimeoutError')
738 : )
739 : }, timeout.duration)
740 :
741 0 : return requestOptions.signal
742 : ? combineAbortSignals([
743 : requestOptions.signal,
744 : retryController.signal
745 : ])
746 : : retryController.signal
747 : }
748 : }
749 : : undefined
750 :
751 312936 : const init: RequestInit = {
752 : cache: 'no-cache',
753 : ...requestOptions,
754 : headers,
755 : signal
756 : }
757 : const response = sendOnWebSession
758 : ? sendOnWebSession(this.unscopedApiURL(route), init)
759 : : this.authProvider.fetch(
760 : this.apiURL(route),
761 : init,
762 : unifiedRetryOn401,
763 : retrySignalLifecycle,
764 : retryPolicy
765 : )
766 312936 : return response.finally(() => {
767 305991 : if (timeoutId !== undefined) clearTimeout(timeoutId)
768 305991 : if (retryTimeoutId !== undefined) clearTimeout(retryTimeoutId)
769 : })
770 : }
771 :
772 : /**
773 : * Wraps an event listener so an exception thrown by it — most often from a
774 : * third-party custom node — is caught and logged instead of surfacing as an
775 : * unhandled error in global telemetry (which RUM captures as a high-volume,
776 : * non-actionable error). Native EventTarget already isolates listeners from
777 : * one another; this only changes where the error goes.
778 : *
779 : * The same original listener always maps to the same wrapper, so
780 : * {@link removeEventListener} still matches. Logged at `warn` level on
781 : * purpose: RUM collects `console.error` by default, which would re-introduce
782 : * the noise this guard removes.
783 : */
784 : private wrapListener(
785 : callback: EventListenerOrEventListenerObject | null
786 : ): EventListenerOrEventListenerObject | null {
787 133127 : if (!callback) return callback
788 133127 : let wrapped = this._listenerWrappers.get(callback)
789 133127 : if (!wrapped) {
790 118987 : const logError = (event: Event, error: unknown) =>
791 : console.warn(
792 : `[ComfyApi] Uncaught error in "${event.type}" event listener:`,
793 : error
794 : )
795 : // Regular function (not arrow) so the listener keeps the native
796 : // `this === currentTarget` binding that EventTarget provides.
797 118987 : wrapped = function (this: unknown, event: Event) {
798 24872 : try {
799 24872 : const result: unknown =
800 : typeof callback === 'function'
801 : ? callback.call(this, event)
802 : : callback.handleEvent(event)
803 : // Async listeners: route a rejected promise through the same guard so
804 : // it does not escape as an unhandled rejection (which RUM also logs).
805 24872 : if (
806 : result != null &&
807 : typeof (result as PromiseLike<unknown>).then === 'function'
808 : ) {
809 3954 : void Promise.resolve(result).catch((error: unknown) =>
810 : logError(event, error)
811 : )
812 : }
813 : } catch (error) {
814 0 : logError(event, error)
815 : }
816 : }
817 118987 : this._listenerWrappers.set(callback, wrapped)
818 : }
819 133127 : return wrapped
820 : }
821 :
822 : /**
823 : * Looks up the guarded wrapper for a listener without creating one — used on
824 : * the remove path so a never-registered callback does not leave a stray
825 : * WeakMap entry. Falls back to the original callback (a harmless no-op).
826 : */
827 : private getWrappedListener(
828 : callback: EventListenerOrEventListenerObject | null
829 : ): EventListenerOrEventListenerObject | null {
830 2693 : if (!callback) return callback
831 2693 : return this._listenerWrappers.get(callback) ?? callback
832 : }
833 :
834 : override addEventListener<TEvent extends keyof ApiEvents>(
835 : type: TEvent,
836 : callback: ((event: ApiEvents[TEvent]) => void) | EventListenerObject | null,
837 : options?: AddEventListenerOptions | boolean
838 : ) {
839 130772 : super.addEventListener(
840 : type,
841 : this.wrapListener(callback as EventListenerOrEventListenerObject | null),
842 : options
843 : )
844 130772 : this._registered.add(type)
845 : }
846 :
847 : override removeEventListener<TEvent extends keyof ApiEvents>(
848 : type: TEvent,
849 : callback: ((event: ApiEvents[TEvent]) => void) | EventListenerObject | null,
850 : options?: EventListenerOptions | boolean
851 : ): void {
852 2693 : super.removeEventListener(
853 : type,
854 : this.getWrappedListener(
855 : callback as EventListenerOrEventListenerObject | null
856 : ),
857 : options
858 : )
859 : }
860 :
861 : addCustomEventListener(
862 : type: string,
863 : callback: ((event: CustomEvent<unknown>) => void) | null,
864 : options?: AddEventListenerOptions | boolean
865 : ) {
866 2355 : super.addEventListener(
867 : type,
868 : this.wrapListener(callback as EventListener),
869 : options
870 : )
871 2355 : this._registered.add(type)
872 : }
873 :
874 : removeCustomEventListener(
875 : type: string,
876 : callback: ((event: CustomEvent<unknown>) => void) | null,
877 : options?: EventListenerOptions | boolean
878 : ) {
879 0 : super.removeEventListener(
880 : type,
881 : this.getWrappedListener(callback as EventListener),
882 : options
883 : )
884 : }
885 :
886 : /**
887 : * Dispatches a custom event.
888 : * Provides type safety for the contravariance issue with EventTarget (last checked TS 5.6).
889 : * @param type The type of event to emit
890 : * @param detail The detail property used for a custom event ({@link CustomEventInit.detail})
891 : */
892 : dispatchCustomEvent(type: SimpleApiEvents): boolean
893 : dispatchCustomEvent<T extends ComplexApiEvents>(
894 : type: T,
895 : detail: ApiEventTypes[T] | null
896 : ): boolean
897 : dispatchCustomEvent<T extends keyof ApiEventTypes>(
898 : type: T,
899 : detail?: ApiEventTypes[T]
900 : ): boolean {
901 7973 : const event =
902 : detail === undefined
903 : ? new CustomEvent(type)
904 : : new CustomEvent(type, { detail })
905 7973 : return super.dispatchEvent(event)
906 : }
907 :
908 : /** @deprecated Use {@link dispatchCustomEvent}. */
909 : override dispatchEvent(event: never): boolean {
910 0 : return super.dispatchEvent(event)
911 : }
912 :
913 : /**
914 : * Poll status for colab and other things that don't support websockets.
915 : */
916 : private _pollQueue() {
917 0 : setInterval(async () => {
918 0 : try {
919 : const resp = await this.fetchApi('/prompt')
920 0 : const status = (await resp.json()) as StatusWsMessageStatus
921 0 : this.dispatchCustomEvent('status', status)
922 : } catch {
923 0 : this.dispatchCustomEvent('status', null)
924 : }
925 : }, 1000)
926 : }
927 :
928 : /** False when the web session is on and no one is signed in to open it. */
929 : private async addSocketAuth(params: URLSearchParams): Promise<boolean> {
930 0 : const requests = webSessionRequests()
931 0 : const sessionScope = requests && (await requests.scope())
932 0 : if (sessionScope?.workspaceId) {
933 0 : params.set('workspace_id', sessionScope.workspaceId)
934 : }
935 0 : if (sessionScope) return true
936 :
937 0 : const authToken = await this.authProvider.getAuthToken()
938 0 : if (authToken) {
939 0 : params.set('token', authToken)
940 : }
941 0 : return !requests || params.has('token')
942 : }
943 :
944 : /** The cloud socket's auth params; null when no one is signed in to open it. */
945 : async socketAuthParams(): Promise<URLSearchParams | null> {
946 0 : const params = new URLSearchParams()
947 0 : return (await this.addSocketAuth(params)) ? params : null
948 : }
949 :
950 : private async createSocket(isReconnect?: boolean) {
951 2364 : if (this.socket) {
952 0 : return
953 : }
954 2364 : if (!isReconnect) this.socketRetryDelayMs = 1_000
955 2364 : const generation = ++this.socketGeneration
956 :
957 2364 : let opened = false
958 2364 : const existingSession = window.name
959 :
960 2364 : const params = new URLSearchParams()
961 :
962 2364 : if (existingSession) {
963 106 : params.set('clientId', existingSession)
964 : }
965 :
966 2364 : if (this.ports.isCloud && !(await this.addSocketAuth(params))) return
967 2364 : const sessionRequests =
968 : this.ports.isCloud && !params.has('token')
969 : ? webSessionRequests()
970 : : undefined
971 :
972 : const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
973 2364 : const baseUrl = `${protocol}://${this.api_host}${this.api_base}/ws`
974 2364 : const query = params.toString()
975 2364 : const wsUrl = query ? `${baseUrl}?${query}` : baseUrl
976 :
977 2364 : if (generation !== this.socketGeneration) return
978 :
979 2364 : const socket = new WebSocket(wsUrl)
980 2364 : this.socket = socket
981 2364 : this.serverFeatureFlagsSettled.value = false
982 2364 : socket.binaryType = 'arraybuffer'
983 :
984 2364 : const settleTimer = setTimeout(() => {
985 88 : if (this.socket === socket && !this.serverFeatureFlagsSettled.value) {
986 0 : this.serverFeatureFlagsSettled.value = true
987 : }
988 : }, SERVER_FEATURE_FLAGS_TIMEOUT_MS)
989 :
990 2364 : socket.addEventListener('open', () => {
991 2363 : if (this.socket !== socket) return
992 2363 : opened = true
993 2363 : this.socketRetryDelayMs = 1_000
994 :
995 2363 : socket.send(
996 : JSON.stringify({
997 : type: 'feature_flags',
998 : data: this.getClientFeatureFlags()
999 : })
1000 : )
1001 :
1002 2363 : if (isReconnect) {
1003 8 : this.dispatchCustomEvent('reconnected')
1004 : }
1005 : })
1006 :
1007 2364 : socket.addEventListener('error', () => {
1008 0 : if (this.socket !== socket) return
1009 0 : socket.close()
1010 0 : if (!sessionRequests && !isReconnect && !opened) {
1011 0 : this._pollQueue()
1012 : }
1013 : })
1014 :
1015 2364 : socket.addEventListener('close', () => {
1016 11 : if (this.socket !== socket) return
1017 11 : this.serverFeatureFlagsSettled.value = true
1018 11 : clearTimeout(settleTimer)
1019 11 : const recoverSession = sessionRequests && !opened
1020 11 : const delayMs = recoverSession ? this.socketRetryDelayMs : 300
1021 11 : if (recoverSession) {
1022 0 : this.socketRetryDelayMs = Math.min(delayMs * 2, 60_000)
1023 : }
1024 11 : setTimeout(async () => {
1025 8 : if (this.socket !== socket) return
1026 8 : if (recoverSession) {
1027 0 : await sessionRequests.refreshSession()
1028 0 : if (this.socket !== socket) return
1029 : }
1030 8 : this.socket = null
1031 8 : await this.createSocket(true)
1032 : }, delayMs)
1033 11 : if (opened) {
1034 11 : this.dispatchCustomEvent('status', null)
1035 11 : this.dispatchCustomEvent('reconnecting')
1036 : }
1037 : })
1038 :
1039 2364 : socket.addEventListener('message', (event) => {
1040 5885 : if (this.socket !== socket) return
1041 5885 : try {
1042 5885 : if (event.data instanceof ArrayBuffer) {
1043 16 : const view = new DataView(event.data)
1044 16 : const eventType = view.getUint32(0)
1045 :
1046 16 : switch (eventType) {
1047 : case 3: {
1048 12 : try {
1049 12 : const decoder3 = new TextDecoder()
1050 12 : const rawData = event.data.slice(4)
1051 12 : const rawView = new DataView(rawData)
1052 :
1053 12 : let offset = 0
1054 12 : let promptId: string | undefined
1055 :
1056 12 : if (
1057 : this.serverSupportsFeature('supports_progress_text_metadata')
1058 : ) {
1059 0 : const promptIdLength = rawView.getUint32(offset)
1060 0 : offset += 4
1061 0 : promptId = decoder3.decode(
1062 : rawData.slice(offset, offset + promptIdLength)
1063 : )
1064 0 : offset += promptIdLength
1065 : }
1066 :
1067 12 : const nodeIdLength = rawView.getUint32(offset)
1068 12 : offset += 4
1069 12 : const nodeId = decoder3.decode(
1070 : rawData.slice(offset, offset + nodeIdLength)
1071 : )
1072 12 : offset += nodeIdLength
1073 12 : const text = decoder3.decode(rawData.slice(offset))
1074 :
1075 12 : this.dispatchCustomEvent('progress_text', {
1076 : nodeId,
1077 : text,
1078 : ...(promptId !== undefined && { prompt_id: promptId })
1079 : })
1080 : } catch (e) {
1081 0 : console.warn('Failed to parse progress_text binary message', e)
1082 : }
1083 12 : break
1084 : }
1085 : case 1: {
1086 0 : const imageType = view.getUint32(4)
1087 0 : const imageData = event.data.slice(8)
1088 : const imageMime = imageType === 2 ? 'image/png' : 'image/jpeg'
1089 0 : const imageBlob = new Blob([imageData], {
1090 : type: imageMime
1091 : })
1092 0 : this.dispatchCustomEvent('b_preview', imageBlob)
1093 0 : break
1094 : }
1095 : case 4: {
1096 4 : const decoder4 = new TextDecoder()
1097 4 : const metadataLength = view.getUint32(4)
1098 4 : const metadataBytes = event.data.slice(8, 8 + metadataLength)
1099 4 : const metadata = JSON.parse(decoder4.decode(metadataBytes))
1100 4 : const imageData4 = event.data.slice(8 + metadataLength)
1101 :
1102 4 : const imageMime4 = metadata.image_type
1103 :
1104 4 : const imageBlob4 = new Blob([imageData4], {
1105 : type: imageMime4
1106 : })
1107 :
1108 4 : this.dispatchCustomEvent('b_preview_with_metadata', {
1109 : blob: imageBlob4,
1110 : nodeId: metadata.node_id,
1111 : displayNodeId: metadata.display_node_id,
1112 : parentNodeId: metadata.parent_node_id,
1113 : realNodeId: metadata.real_node_id,
1114 : jobId: metadata.prompt_id,
1115 : workflowId: metadata.workflow_id
1116 : })
1117 :
1118 4 : this.dispatchCustomEvent('b_preview', imageBlob4)
1119 4 : break
1120 : }
1121 : default:
1122 0 : console.error(
1123 : `Unknown binary websocket message of type ${eventType}`
1124 : )
1125 : break
1126 : }
1127 : } else {
1128 5869 : const msg = JSON.parse(event.data) as ApiMessageUnion
1129 5869 : switch (msg.type) {
1130 : case 'status':
1131 2628 : if (msg.data.sid) {
1132 2361 : const clientId = msg.data.sid
1133 2361 : this.clientId = clientId
1134 2361 : window.name = clientId
1135 2361 : withClientIdStorage((storage) =>
1136 : storage.setItem(CLIENT_ID_STORAGE_KEY, clientId)
1137 : )
1138 : }
1139 2628 : this.dispatchCustomEvent('status', msg.data.status ?? null)
1140 2628 : break
1141 : case 'executing':
1142 192 : this.dispatchCustomEvent(
1143 : 'executing',
1144 : msg.data.display_node || msg.data.node
1145 : )
1146 192 : break
1147 : case 'execution_start':
1148 : case 'execution_error':
1149 : case 'execution_interrupted':
1150 : case 'execution_cached':
1151 : case 'execution_success':
1152 : case 'prompt_outputs_skipped':
1153 : case 'progress':
1154 : case 'progress_state':
1155 : case 'executed':
1156 : case 'promptQueued':
1157 : case 'logs':
1158 : case 'b_preview':
1159 : case 'notification':
1160 702 : this.dispatchCustomEvent(msg.type, msg.data)
1161 702 : break
1162 : case 'graphChanged':
1163 0 : this.dispatchCustomEvent('graphChanged', msg.data)
1164 0 : this.dispatchCustomEvent('autoQueueGraphChanged')
1165 0 : break
1166 : case 'autoQueueGraphChanged':
1167 0 : this.dispatchCustomEvent('autoQueueGraphChanged')
1168 0 : break
1169 : case 'feature_flags':
1170 2344 : this.serverFeatureFlags.value = msg.data
1171 2344 : this.serverFeatureFlagsSettled.value = true
1172 2344 : this.dispatchCustomEvent('feature_flags', msg.data)
1173 2344 : break
1174 : case 'agent_status':
1175 2 : this.serverFeatureFlags.value = {
1176 : ...this.serverFeatureFlags.value,
1177 : agent: msg.data
1178 : }
1179 2 : this.dispatchCustomEvent('agent_status', msg.data)
1180 2 : break
1181 : default:
1182 1 : if (this._registered.has(msg.type)) {
1183 1 : super.dispatchEvent(
1184 : new CustomEvent(msg.type, { detail: msg.data })
1185 : )
1186 0 : } else if (!this.reportedUnknownMessageTypes.has(msg.type)) {
1187 0 : this.reportedUnknownMessageTypes.add(msg.type)
1188 0 : console.error(`Unknown message type ${msg.type}`)
1189 : }
1190 : }
1191 : }
1192 : } catch (error) {
1193 0 : console.warn('Unhandled message:', event.data, error)
1194 : }
1195 : })
1196 : }
1197 :
1198 : /**
1199 : * Initialises sockets and realtime updates
1200 : */
1201 : async init() {
1202 2355 : await this.createSocket()
1203 : }
1204 :
1205 : /**
1206 : * Tears down the active realtime socket and reconnects, re-authenticating
1207 : * with the currently active account's token. Invoked on a direct identity
1208 : * change so a tab cannot keep receiving the previous account's realtime
1209 : * events over a handshake that was authenticated as that account.
1210 : */
1211 : async resetSocket(): Promise<void> {
1212 1 : this.clientId = undefined
1213 1 : window.name = ''
1214 1 : withClientIdStorage((storage) => storage.removeItem(CLIENT_ID_STORAGE_KEY))
1215 1 : const { agent: _previousAgent, ...features } = this.serverFeatureFlags.value
1216 1 : this.serverFeatureFlags.value = features
1217 1 : await this.replaceSocket()
1218 : }
1219 :
1220 : /**
1221 : * Re-handshakes the socket for the same account, keeping its client id, so
1222 : * a new web session workspace takes effect. Does nothing before init().
1223 : */
1224 : async reconnectSocket(): Promise<void> {
1225 0 : if (this.socketGeneration === 0) return
1226 0 : await this.replaceSocket()
1227 : }
1228 :
1229 : private async replaceSocket(): Promise<void> {
1230 1 : const previous = this.socket
1231 : // serverFeatureFlags deliberately keeps the previous map (resetSocket drops
1232 : // only `agent`): clearing it would downgrade every serverSupportsFeature()
1233 : // caller until the next delivery.
1234 1 : this.serverFeatureFlagsSettled.value = false
1235 : // Detach before closing so the previous socket's close handler sees it is
1236 : // no longer the active socket and does not start a competing reconnect.
1237 1 : this.socket = null
1238 1 : if (previous && previous.readyState !== WebSocket.CLOSED) {
1239 1 : try {
1240 1 : previous.close()
1241 : } catch {
1242 : // Already-terminating socket; nothing to clean up.
1243 : }
1244 : }
1245 : // createSocket() bumps the generation; any overlapping reset or reconnect
1246 : // that is still awaiting its token will see it lost the race and bail,
1247 : // leaving this the sole owner of the reconnected socket.
1248 1 : await this.createSocket()
1249 : }
1250 :
1251 : /**
1252 : * Gets a list of extension urls
1253 : */
1254 : async getExtensions(): Promise<GetExtensionsResponse> {
1255 2355 : const resp = await this.fetchApi('/extensions', { cache: 'no-store' })
1256 2355 : return zGetExtensionsResponse.parse(await resp.json())
1257 : }
1258 :
1259 : /**
1260 : * Gets the available workflow templates from custom nodes.
1261 : * @returns A map of custom_node names and associated template workflow names.
1262 : */
1263 : async getWorkflowTemplates(): Promise<{
1264 : [customNodesName: string]: string[]
1265 : }> {
1266 : const res = await this.fetchApi('/workflow_templates')
1267 50 : return await res.json()
1268 : }
1269 :
1270 : /**
1271 : * Gets the index of core workflow templates.
1272 : * @param locale Optional locale code (e.g., 'en', 'fr', 'zh') to load localized templates
1273 : */
1274 : async getCoreWorkflowTemplates(
1275 : locale?: string
1276 : ): Promise<WorkflowTemplates[]> {
1277 52 : const fileName =
1278 : locale && locale !== 'en' ? `index.${locale}.json` : 'index.json'
1279 52 : try {
1280 52 : const res = await axios.get(this.fileURL(`/templates/${fileName}`))
1281 : const contentType = String(res.headers['content-type'] ?? '')
1282 52 : return contentType.includes('application/json') ? res.data : []
1283 : } catch (error) {
1284 : // Fallback to default English version if localized version doesn't exist
1285 2 : if (locale && locale !== 'en') {
1286 2 : console.warn(
1287 : `Localized templates for '${locale}' not found, falling back to English`
1288 : )
1289 2 : return this.getCoreWorkflowTemplates()
1290 : }
1291 0 : console.error('Error loading core workflow templates:', error)
1292 0 : return []
1293 : }
1294 : }
1295 :
1296 : /**
1297 : * Gets a list of embedding names
1298 : * @throws When the request fails or the response does not match the schema
1299 : */
1300 : async getEmbeddings(): Promise<GetEmbeddingsResponse> {
1301 0 : const resp = await this.fetchApi('/embeddings', { cache: 'no-store' })
1302 0 : if (!resp.ok) {
1303 0 : throw new Error(`Failed to fetch /embeddings: ${resp.status}`)
1304 : }
1305 0 : return zGetEmbeddingsResponse.parse(await resp.json())
1306 : }
1307 :
1308 : /**
1309 : * Loads node object definitions for the graph
1310 : * @returns The node definitions
1311 : */
1312 : private nodeDefsPrefetch?: Promise<Response>
1313 :
1314 : /** Start fetching `/object_info` so the next `getNodeDefs()` can reuse it. */
1315 : prefetchNodeDefs(): void {
1316 2355 : this.nodeDefsPrefetch ??= this.fetchApi('/object_info', {
1317 : cache: 'no-store'
1318 : })
1319 2355 : this.nodeDefsPrefetch.catch(() => undefined)
1320 : }
1321 :
1322 : /** The `/object_info` response, the prefetched one when there is one, whatever its HTTP status. */
1323 : async fetchNodeDefs(): Promise<Response> {
1324 2382 : const prefetched = this.nodeDefsPrefetch
1325 2382 : this.nodeDefsPrefetch = undefined
1326 2382 : const fetchFresh = () =>
1327 : this.fetchApi('/object_info', { cache: 'no-store' })
1328 2382 : return await (prefetched?.catch(fetchFresh) ?? fetchFresh())
1329 : }
1330 :
1331 : async getNodeDefs(): Promise<Record<string, ComfyNodeDef>> {
1332 2374 : return await (await this.fetchNodeDefs()).json()
1333 : }
1334 :
1335 : /**
1336 : * Queues a prompt to be executed
1337 : * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue
1338 : * @param {object} data The prompt data to queue
1339 : * @param {QueuePromptOptions} options Optional execution options
1340 : * @throws {PromptExecutionError} If the prompt fails to execute
1341 : */
1342 : async queuePrompt(
1343 : number: number,
1344 : data: { output: ComfyApiWorkflow; workflow: ComfyWorkflowJSON },
1345 : options?: QueuePromptOptions
1346 : ): Promise<PromptResponse> {
1347 190 : const { output: prompt, workflow } = data
1348 :
1349 190 : const body: QueuePromptRequestBody = {
1350 : client_id: this.clientId ?? '', // TODO: Unify clientId access
1351 : prompt,
1352 : ...(options?.partialExecutionTargets && {
1353 : partial_execution_targets: options.partialExecutionTargets
1354 : }),
1355 : ...(workflow.id &&
1356 : workflow.id !== zeroUuid && {
1357 : workflow_metadata: { workflow_id: workflow.id }
1358 : }),
1359 : extra_data: {
1360 : auth_token_comfy_org: this.authToken,
1361 : api_key_comfy_org: this.apiKey,
1362 : comfy_usage_source: 'comfyui-frontend',
1363 : extra_pnginfo: { workflow },
1364 : ...(options?.previewMethod &&
1365 : options.previewMethod !== 'default' && {
1366 : preview_method: options.previewMethod
1367 : })
1368 : }
1369 : }
1370 :
1371 190 : if (number === -1) {
1372 1 : body.front = true
1373 189 : } else if (number != 0) {
1374 0 : body.number = number
1375 : }
1376 :
1377 190 : const res = await this.fetchApi('/prompt', {
1378 : method: 'POST',
1379 : headers: {
1380 : 'Content-Type': 'application/json'
1381 : },
1382 : body: JSON.stringify(body)
1383 : })
1384 :
1385 188 : if (res.status !== 200) {
1386 38 : const text = await res.text()
1387 35 : let errorResponse
1388 35 : try {
1389 35 : errorResponse = JSON.parse(text)
1390 : } catch {
1391 0 : errorResponse = {
1392 : error: {
1393 : type: 'server_error',
1394 : message: `${res.status} ${res.statusText}`,
1395 : details: text
1396 : }
1397 : }
1398 : }
1399 35 : throw new PromptExecutionError(errorResponse, res.status)
1400 : }
1401 :
1402 150 : return await res.json()
1403 : }
1404 :
1405 : /**
1406 : * Gets the list of assets and models referenced by a prompt that would
1407 : * need user consent before sharing.
1408 : */
1409 : async getShareableAssets(
1410 : prompt: ComfyApiWorkflow,
1411 : options?: { owned?: boolean }
1412 : ): Promise<PostAssetsFromWorkflowResponse> {
1413 11 : const body: Record<string, unknown> = { workflow_api_json: prompt }
1414 11 : if (options?.owned !== undefined) {
1415 0 : body.owned = options.owned
1416 : }
1417 11 : const res = await this.fetchApi('/assets/from-workflow', {
1418 : method: 'POST',
1419 : headers: { 'Content-Type': 'application/json' },
1420 : body: JSON.stringify(body)
1421 : })
1422 11 : if (res.status !== 200) {
1423 0 : throw new Error(`Failed to fetch shareable assets: ${res.status}`)
1424 : }
1425 11 : const data = await res.json()
1426 11 : return zPostAssetsFromWorkflowResponse.parse(data)
1427 : }
1428 :
1429 : /**
1430 : * Gets a list of model folder keys (eg ['checkpoints', 'loras', ...])
1431 : * @returns The list of model folder keys
1432 : */
1433 : async getModelFolders(): Promise<ModelFolderInfo[]> {
1434 2325 : const res = await this.fetchApi(`/experiment/models`)
1435 2225 : if (res.status === 404) {
1436 0 : return []
1437 : }
1438 2222 : const folderBlacklist = ['configs', 'custom_nodes']
1439 2222 : return (await res.json()).filter(
1440 : (folder: ModelFolderInfo) => !folderBlacklist.includes(folder.name)
1441 : )
1442 : }
1443 :
1444 : /**
1445 : * Gets a list of models in the specified folder
1446 : * @param {string} folder The folder to list models from, such as 'checkpoints'
1447 : * @returns The list of model filenames within the specified folder
1448 : */
1449 : async getModels(folder: string): Promise<ModelFile[]> {
1450 20 : const res = await this.fetchApi(`/experiment/models/${folder}`)
1451 20 : if (res.status === 404) {
1452 0 : return []
1453 : }
1454 20 : return await res.json()
1455 : }
1456 :
1457 : /**
1458 : * Gets the metadata for a model
1459 : * @param {string} folder The folder containing the model
1460 : * @param {string} model The model to get metadata for
1461 : * @returns The metadata for the model
1462 : */
1463 : async viewMetadata(folder: string, model: string) {
1464 55 : const res = await this.fetchApi(
1465 : `/view_metadata/${folder}?filename=${encodeURIComponent(model)}`
1466 : )
1467 52 : const rawResponse = await res.text()
1468 52 : if (!rawResponse) {
1469 49 : return null
1470 : }
1471 3 : try {
1472 3 : return JSON.parse(rawResponse)
1473 : } catch (error) {
1474 0 : console.error(
1475 : 'Error viewing metadata',
1476 : res.status,
1477 : res.statusText,
1478 : rawResponse,
1479 : error
1480 : )
1481 0 : return null
1482 : }
1483 : }
1484 :
1485 : /**
1486 : * Loads a list of items (queue or history)
1487 : * @param {string} type The type of items to load, queue or history
1488 : * @returns The items of the specified type grouped by their status
1489 : */
1490 : async getItems(type: 'queue' | 'history') {
1491 0 : if (type === 'queue') {
1492 0 : return this.getQueue()
1493 : }
1494 0 : return this.getHistory()
1495 : }
1496 :
1497 : /**
1498 : * Gets the current state of the queue
1499 : * @returns The currently running and queued items
1500 : */
1501 : async getQueue(options?: { throwOnError?: boolean }): Promise<{
1502 : Running: JobListItem[]
1503 : Pending: JobListItem[]
1504 : }> {
1505 2618 : try {
1506 2618 : return await fetchQueue(this.fetchApi.bind(this), options)
1507 : } catch (error) {
1508 1 : if (options?.throwOnError) throw error
1509 0 : console.error('Failed to fetch queue:', error)
1510 0 : return { Running: [], Pending: [] }
1511 : }
1512 : }
1513 :
1514 : /**
1515 : * Gets the prompt execution history
1516 : * @returns Prompt history including node outputs
1517 : */
1518 : async getHistory(
1519 : max_items: number = 200,
1520 : options?: { offset?: number; throwOnError?: boolean }
1521 : ): Promise<JobListItem[]> {
1522 7660 : try {
1523 7660 : return await fetchHistory(
1524 : this.fetchApi.bind(this),
1525 : max_items,
1526 : options?.offset,
1527 : options
1528 : )
1529 : } catch (error) {
1530 0 : if (options?.throwOnError) throw error
1531 0 : console.error(error)
1532 0 : return []
1533 : }
1534 : }
1535 :
1536 : /**
1537 : * Gets detailed job info including outputs and workflow
1538 : * @param jobId The job ID
1539 : * @returns Full job details or undefined if not found
1540 : */
1541 : async getJobDetail(
1542 : jobId: string,
1543 : signal?: AbortSignal
1544 : ): Promise<JobDetail | undefined> {
1545 724 : return fetchJobDetail(this.fetchApi.bind(this), jobId, signal)
1546 : }
1547 :
1548 : /**
1549 : * Gets a job's output assets, each resolved to a real asset entity with
1550 : * per-output node context. Returns an empty list when the endpoint is
1551 : * unavailable (e.g. non-cloud distributions).
1552 : * @param jobId The job ID
1553 : * @returns The job's output assets and whether the list is exhaustive
1554 : */
1555 : async getJobAssets(jobId: string): Promise<JobAssetsResult> {
1556 0 : return fetchJobAssets(this.fetchApi.bind(this), jobId)
1557 : }
1558 :
1559 : /**
1560 : * Gets system & device stats
1561 : * @returns System stats such as python version, OS, per device info
1562 : */
1563 : async getSystemStats(): Promise<SystemStats> {
1564 : const res = await this.fetchApi('/system_stats')
1565 2355 : return await res.json()
1566 : }
1567 :
1568 : private async _postItem(
1569 : type: string,
1570 : body?: Record<string, unknown>
1571 : ): Promise<boolean> {
1572 9 : try {
1573 : const response = await this.fetchApi('/' + type, {
1574 : method: 'POST',
1575 : headers: {
1576 : 'Content-Type': 'application/json'
1577 : },
1578 : body: body ? JSON.stringify(body) : undefined
1579 : })
1580 9 : return response.ok
1581 : } catch (error) {
1582 0 : console.error(error)
1583 0 : return false
1584 : }
1585 : }
1586 :
1587 : async deleteItem(type: string, id: string): Promise<boolean> {
1588 2 : return this._postItem(type, { delete: [id] })
1589 : }
1590 :
1591 : /**
1592 : * Clears the specified list
1593 : * @param {string} type The type of list to clear, queue or history
1594 : */
1595 : async clearItems(type: string) {
1596 3 : await this._postItem(type, { clear: true })
1597 : }
1598 :
1599 : /**
1600 : * Interrupts the execution of the running job. If runningJobId is provided,
1601 : * it is included in the payload as a helpful hint to the backend.
1602 : * @param {string | null} [runningJobId] Optional Running Job ID to interrupt
1603 : */
1604 : async interrupt(runningJobId: string | null) {
1605 4 : await this._postItem(
1606 : 'interrupt',
1607 : runningJobId ? { prompt_id: runningJobId } : undefined
1608 : )
1609 : }
1610 :
1611 : /**
1612 : * Cancels a single job by id via `POST /api/jobs/{job_id}/cancel` (idempotent:
1613 : * already-terminal jobs are a no-op). Requires runtime parity — not every
1614 : * runtime exposes this endpoint yet; do not merge callers before parity lands.
1615 : *
1616 : * @param {string} jobId The id of the job to cancel
1617 : */
1618 : async cancelJob(jobId: string) {
1619 0 : const res = await this.fetchApi(
1620 : `/jobs/${encodeURIComponent(jobId)}/cancel`,
1621 : {
1622 : method: 'POST'
1623 : }
1624 : )
1625 0 : if (!res.ok) {
1626 0 : const body = await res.text().catch(() => '')
1627 0 : throw new Error(
1628 : `Failed to cancel job ${jobId}: ${res.status}${body ? ` — ${body}` : ''}`
1629 : )
1630 : }
1631 : }
1632 :
1633 : /**
1634 : * Cancels multiple jobs in a single request via `POST /api/jobs/cancel` with
1635 : * body `{ job_ids: [...] }`. Already-terminal jobs are no-ops. Same runtime
1636 : * parity requirement as {@link cancelJob}.
1637 : *
1638 : * @param {string[]} jobIds The ids of the jobs to cancel
1639 : */
1640 : async cancelJobs(jobIds: string[]) {
1641 0 : if (!jobIds.length) return
1642 0 : const res = await this.fetchApi('/jobs/cancel', {
1643 : method: 'POST',
1644 : headers: {
1645 : 'Content-Type': 'application/json'
1646 : },
1647 : body: JSON.stringify({ job_ids: jobIds })
1648 : })
1649 0 : if (!res.ok) {
1650 0 : const body = await res.text().catch(() => '')
1651 0 : throw new Error(
1652 : `Failed to cancel jobs: ${res.status}${body ? ` — ${body}` : ''}`
1653 : )
1654 : }
1655 : }
1656 :
1657 : /**
1658 : * Gets user configuration data and where data should be stored
1659 : */
1660 : async getUserConfig(): Promise<UserConfigResponse> {
1661 2355 : return (await this.fetchApi('/users')).json()
1662 : }
1663 :
1664 : /**
1665 : * Creates a new user
1666 : * @param { string } username
1667 : * @returns The fetch response
1668 : */
1669 : createUser(username: string) {
1670 0 : return this.fetchApi('/users', {
1671 : method: 'POST',
1672 : headers: {
1673 : 'Content-Type': 'application/json'
1674 : },
1675 : body: JSON.stringify({ username })
1676 : })
1677 : }
1678 :
1679 : /**
1680 : * Gets all setting values for the current user
1681 : * @returns { Promise<string, unknown> } A dictionary of id -> value
1682 : */
1683 : async getSettings(
1684 : options?: Pick<FetchApiOptions, 'skipStatusRetry'>
1685 : ): Promise<Settings> {
1686 2362 : const resp = await this.fetchApi('/settings', options)
1687 :
1688 2362 : if (resp.status == 401) {
1689 : // `statusText` is ALWAYS empty over HTTP/2 — the protocol carries no
1690 : // reason phrase — and cloud.comfy.org is HTTP/2. Passing it straight
1691 : // through produced `new UnauthorizedError('')`, which the global
1692 : // onerror handler reported to Sentry as the untitled group
1693 : // "Error: No error message": 165,890 events in 14 days across 25,417
1694 : // users, all of them unactionable because nothing in the event said
1695 : // which request had failed.
1696 0 : throw new UnauthorizedError(
1697 : `Failed to load settings: 401 ${resp.statusText || 'Unauthorized'}`
1698 : )
1699 : }
1700 2362 : return await resp.json()
1701 : }
1702 :
1703 : /**
1704 : * Gets a setting for the current user
1705 : * @param { string } id The id of the setting to fetch
1706 : * @returns { Promise<unknown> } The setting value
1707 : */
1708 : async getSetting(id: keyof Settings): Promise<Settings[keyof Settings]> {
1709 0 : return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json()
1710 : }
1711 :
1712 : /**
1713 : * Stores a dictionary of settings for the current user
1714 : */
1715 : async storeSettings(settings: Partial<Settings>) {
1716 51 : return this.fetchApi(`/settings`, {
1717 : method: 'POST',
1718 : body: JSON.stringify(settings)
1719 : })
1720 : }
1721 :
1722 : /**
1723 : * Stores a setting for the current user
1724 : */
1725 : async storeSetting(
1726 : id: keyof Settings,
1727 : value: Settings[keyof Settings],
1728 : options?: Pick<RequestInit, 'keepalive'>
1729 : ) {
1730 685 : return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {
1731 : method: 'POST',
1732 : body: JSON.stringify(value),
1733 : ...options
1734 : })
1735 : }
1736 :
1737 : /**
1738 : * Gets a user data file for the current user
1739 : */
1740 : async getUserData(file: string, options?: RequestInit) {
1741 2727 : return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options)
1742 : }
1743 :
1744 : /**
1745 : * Stores a user data file for the current user
1746 : * @param { string } file The name of the userdata file to save
1747 : * @param { unknown } data The data to save to the file
1748 : * @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]
1749 : * @returns { Promise<Response> }
1750 : */
1751 : async storeUserData(
1752 : file: string,
1753 : data: unknown,
1754 : options: RequestInit & {
1755 : overwrite?: boolean
1756 : stringify?: boolean
1757 : throwOnError?: boolean
1758 : full_info?: boolean
1759 : } = {
1760 : overwrite: true,
1761 : stringify: true,
1762 : throwOnError: true,
1763 : full_info: false
1764 : }
1765 : ): Promise<Response> {
1766 137 : const overwrite = options.overwrite ?? true
1767 137 : const fullInfo = options.full_info ?? false
1768 137 : const route = `/userdata/${encodeURIComponent(file)}?overwrite=${overwrite}&full_info=${fullInfo}`
1769 137 : const resp = await this.fetchApi(route, {
1770 : method: 'POST',
1771 : body: options.stringify ? JSON.stringify(data) : (data as BodyInit),
1772 : ...options
1773 : })
1774 137 : if (resp.status !== 200) {
1775 0 : const message = `Error storing user data file '${file}': ${resp.status} ${resp.statusText}`
1776 : // The reported message and route are file-independent: the literal file
1777 : // name (and `route`, which embeds it) is unbounded cardinality and
1778 : // would fragment Sentry grouping into one bucket per file instead of
1779 : // one for this failure mode — exactly what buried PM-1906's alerts.
1780 0 : reportError(
1781 : new Error(
1782 : `Error storing user data file: ${resp.status} ${resp.statusText}`
1783 : ),
1784 : {
1785 : errorType: 'userdata_store_failure',
1786 : surface: 'platform',
1787 : tags: {
1788 : status: resp.status,
1789 : overwrite,
1790 : full_info: fullInfo
1791 : },
1792 : context: {
1793 : file,
1794 : route: `/userdata/{file}?overwrite=${overwrite}&full_info=${fullInfo}`
1795 : }
1796 : }
1797 : )
1798 0 : if (options.throwOnError !== false) {
1799 0 : throw new Error(message)
1800 : }
1801 : }
1802 :
1803 136 : return resp
1804 : }
1805 :
1806 : /**
1807 : * Deletes a user data file for the current user
1808 : * @param { string } file The name of the userdata file to delete
1809 : */
1810 : async deleteUserData(file: string) {
1811 : const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {
1812 : method: 'DELETE'
1813 : })
1814 : return resp
1815 : }
1816 :
1817 : /**
1818 : * Move a user data file for the current user
1819 : * @param { string } source The userdata file to move
1820 : * @param { string } dest The destination for the file
1821 : */
1822 : async moveUserData(
1823 : source: string,
1824 : dest: string,
1825 : options = { overwrite: false }
1826 : ) {
1827 : const resp = await this.fetchApi(
1828 : `/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options.overwrite}`,
1829 : {
1830 : method: 'POST'
1831 : }
1832 : )
1833 : return resp
1834 : }
1835 :
1836 : async listUserDataFullInfo(dir: string): Promise<UserDataFullInfo[]> {
1837 7248 : const trimmedDir = trimEnd(dir, '/')
1838 7248 : const resp = await this.fetchApi(
1839 : `/userdata?dir=${encodeURIComponent(trimmedDir)}&recurse=true&split=false&full_info=true`
1840 : )
1841 7247 : if (resp.status === 404) return []
1842 7081 : if (resp.status !== 200) {
1843 0 : throw new Error(
1844 : `Error getting user data list '${trimmedDir}': ${resp.status} ${resp.statusText}`
1845 : )
1846 : }
1847 4501 : return resp.json()
1848 : }
1849 :
1850 : async getGlobalSubgraphData(id: string): Promise<string> {
1851 271557 : const resp = await this.fetchApi('/global_subgraphs/' + id)
1852 270153 : if (resp.status !== 200) {
1853 0 : throw new Error(
1854 : `Failed to fetch global subgraph '${id}': ${resp.status} ${resp.statusText}`
1855 : )
1856 : }
1857 264882 : const subgraph: unknown = await resp.json()
1858 271557 : if (
1859 : typeof subgraph !== 'object' ||
1860 : subgraph === null ||
1861 : !('data' in subgraph) ||
1862 : typeof subgraph.data !== 'string' ||
1863 : !subgraph.data
1864 : ) {
1865 0 : throw new Error(`Global subgraph '${id}' returned empty data`)
1866 : }
1867 262668 : return subgraph.data
1868 : }
1869 : async getGlobalSubgraphs(): Promise<Record<string, GlobalSubgraphData>> {
1870 2335 : const resp = await this.fetchApi('/global_subgraphs')
1871 2328 : if (resp.status !== 200) return {}
1872 2328 : const subgraphs: Record<string, GlobalSubgraphData> = await resp.json()
1873 2324 : for (const [k, v] of Object.entries(subgraphs)) {
1874 271558 : if (!v.data) v.data = this.getGlobalSubgraphData(k)
1875 : }
1876 2324 : return subgraphs
1877 : }
1878 :
1879 : async getLogs(): Promise<string> {
1880 37 : const url = this.ports.isCloud
1881 : ? this.apiURL('/logs')
1882 : : this.internalURL('/logs')
1883 37 : const { data } = await axios.get<unknown>(url)
1884 28 : if (typeof data === 'string') return data
1885 37 : return data === undefined ? '' : JSON.stringify(data, null, 2)
1886 : }
1887 :
1888 : async getRawLogs(): Promise<LogsRawResponse> {
1889 26 : const url = this.ports.isCloud
1890 : ? this.apiURL('/logs/raw')
1891 : : this.internalURL('/logs/raw')
1892 26 : return (await axios.get(url)).data
1893 : }
1894 :
1895 : async subscribeLogs(enabled: boolean): Promise<void> {
1896 29 : const url = this.ports.isCloud
1897 : ? this.apiURL('/logs/subscribe')
1898 : : this.internalURL('/logs/subscribe')
1899 29 : return await axios.patch(url, {
1900 : enabled,
1901 : clientId: this.clientId
1902 : })
1903 : }
1904 :
1905 : async getFolderPaths(): Promise<Record<string, string[]>> {
1906 2747 : const response = await axios
1907 : .get(this.internalURL('/folder_paths'))
1908 : .catch(() => null)
1909 2729 : if (!response) {
1910 0 : return {} // Fallback: no filesystem paths known when API unavailable
1911 : }
1912 2719 : return response.data
1913 : }
1914 :
1915 : /* Frees memory by unloading models and optionally freeing execution cache
1916 : * @param {Object} options - The options object
1917 : * @param {boolean} options.freeExecutionCache - If true, also frees execution cache
1918 : */
1919 : async freeMemory(options: { freeExecutionCache: boolean }) {
1920 0 : try {
1921 0 : let mode = ''
1922 0 : if (options.freeExecutionCache) {
1923 0 : mode = '{"unload_models": true, "free_memory": true}'
1924 : } else {
1925 0 : mode = '{"unload_models": true}'
1926 : }
1927 :
1928 0 : const res = await this.fetchApi(`/free`, {
1929 : method: 'POST',
1930 : headers: { 'Content-Type': 'application/json' },
1931 : body: mode
1932 : })
1933 :
1934 0 : this.ports.onFreeMemory(
1935 : res.status === 200
1936 : ? { ok: true, freedExecutionCache: options.freeExecutionCache }
1937 : : { ok: false, reason: 'rejected' }
1938 : )
1939 : } catch {
1940 0 : this.ports.onFreeMemory({ ok: false, reason: 'unreachable' })
1941 : }
1942 : }
1943 :
1944 : /**
1945 : * Gets the custom nodes i18n data from the server.
1946 : *
1947 : * @returns The custom nodes i18n data
1948 : */
1949 : async getCustomNodesI18n(): Promise<GetI18nResponse> {
1950 2355 : return (await axios.get(this.apiURL('/i18n'))).data
1951 : }
1952 :
1953 : /**
1954 : * Checks if the server supports a specific feature.
1955 : * @param featureName The name of the feature to check (supports dot notation for nested values)
1956 : * @returns true if the feature is supported, false otherwise
1957 : */
1958 : serverSupportsFeature(featureName: string): boolean {
1959 19 : const override = this.ports.featureFlagOverride<unknown>(featureName)
1960 19 : if (override !== undefined) return override === true
1961 19 : return get(this.serverFeatureFlags.value, featureName) === true
1962 : }
1963 :
1964 : /**
1965 : * Gets a server feature flag value.
1966 : * @param featureName The name of the feature to get (supports dot notation for nested values)
1967 : * @param defaultValue The default value if the feature is not found
1968 : * @returns The feature value or default
1969 : */
1970 : getServerFeature<T = unknown>(featureName: string, defaultValue?: T): T {
1971 3581347 : const override = this.ports.featureFlagOverride<T>(featureName)
1972 3581347 : if (override !== undefined) return override
1973 3581347 : return get(this.serverFeatureFlags.value, featureName, defaultValue) as T
1974 : }
1975 :
1976 : /**
1977 : * Gets all server feature flags.
1978 : * @returns Copy of all server feature flags
1979 : */
1980 : getServerFeatures(): Record<string, unknown> {
1981 8 : return { ...this.serverFeatureFlags.value }
1982 : }
1983 : }
|