import { WorkloadCredentials, injectedWorkloadIdentityReader, workloadTokenFileReader, workloadTokenReader, type WorkloadIdentityReader, type WorkloadToken, } from './lib/workload-credentials'; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. import type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types'; import type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types'; import { uuid4 } from './internal/utils/uuid'; import { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values'; import { sleep } from './internal/utils/sleep'; export type { Logger, LogLevel } from './internal/utils/log'; import { castToError, isAbortError } from './internal/errors'; import type { APIResponseProps } from './internal/parse'; import { getPlatformHeaders } from './internal/detect-platform'; import * as Shims from './internal/shims'; import * as Opts from './internal/request-options'; import { stringifyQuery } from './internal/utils/query'; import { VERSION } from './version'; import * as Errors from './core/error'; import * as Pagination from './core/pagination'; import { AbstractPage, type ItemsParams, ItemsResponse } from './core/pagination'; import * as Uploads from './core/uploads'; import * as API from './resources/index'; import { APIPromise } from './core/api-promise'; import { Analytics, AnalyticsGetInstancesParams, AnalyticsGetParams, AnalyticsTimeFilter, AnalyticsInstancesResponse, AnalyticsResponse, } from './resources/analytics'; import { AndroidInstance, AndroidInstanceUpdateParams, AndroidInstanceCreateParams, AndroidInstanceListParams, AndroidInstancesItems, } from './resources/android-instances'; import { AndroidInstances } from './resources/android-instances-helpers'; import { Asset, AssetGetOrCreateParams, AssetGetOrCreateResponse, AssetListParams, AssetListResponse, } from './resources/assets'; import { Assets, AssetGetOrUploadParams, AssetGetOrUploadResponse } from './resources/assets-helpers'; import { GradleInstance, GradleInstanceUpdateParams, GradleInstanceCreateParams, GradleInstanceListParams, GradleInstances, GradleInstancesItems, } from './resources/gradle-instances'; import { MacosInstance, MacosInstanceUpdateParams, MacosInstanceCreateParams, MacosInstanceListParams, MacosInstances, MacosInstancesItems, } from './resources/macos-instances'; import { IosInstance, IosInstanceUpdateParams, IosInstanceCreateParams, IosInstanceListParams, IosInstancesItems, } from './resources/ios-instances'; import { IosInstances } from './resources/ios-instances-helpers'; import { SessionArtifact } from './resources/session-artifacts'; import { AccessToken, AccessTokenCreateParams, AccessTokenRevokeResponse, AccessTokens, } from './resources/access-tokens'; import { ScopedToken, ScopedTokenCreateParams, ScopedTokens } from './resources/scoped-tokens'; import { XcodeInstance, XcodeInstanceUpdateParams, XcodeInstanceCreateParams, XcodeInstanceListParams, XcodeInstancesItems, } from './resources/xcode-instances'; import { XcodeInstances, XcodeCreateClientParams, XcodeClient, XcodeProjectConfig, XcodeBuildOptions, XcodeRunOptions, ReactNativeBuildConfig, SimulatorAttachResult, SimulatorStatus, SimulatorBuildStatus, SimulatorAttachment, SimulatorDeviceInfo, SimulatorInstallState, XcodeInfo, XcodeStatus, XcodeSelectResult, SandboxInfo, XcodeBuildLog, BazelBuildLog, } from './resources/xcode-instances-helpers'; import { type Fetch } from './internal/builtin-types'; import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers'; import { FinalRequestOptions, RequestOptions } from './internal/request-options'; import { readEnv } from './internal/utils/env'; import { type LogLevel, type Logger, formatRequestDetails, loggerFor, parseLogLevel, } from './internal/utils/log'; import { isEmptyObj } from './internal/utils/values'; /** * Picks the workload identity source: explicit options before environment variables, and a token * before a file. Null on either option turns off discovery of its environment variable. */ function workloadIdentity(opts: { workloadToken?: WorkloadToken | null | undefined; workloadTokenFile?: string | null | undefined; workloadTokenInjected?: boolean | null | undefined; }): WorkloadIdentityReader | undefined { const reader = workloadTokenSource(opts); const injected = opts.workloadTokenInjected === null ? false : opts.workloadTokenInjected ?? /^(1|true)$/i.test(readEnv('LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED') ?? ''); if (!injected) return reader; // The proxy decides which JWT the exchange carries, so a second source would be ignored. if (reader) throw new Error( 'workloadTokenInjected cannot be combined with workloadToken, workloadTokenFile, or their environment variables', ); return injectedWorkloadIdentityReader; } function workloadTokenSource(opts: { workloadToken?: WorkloadToken | null | undefined; workloadTokenFile?: string | null | undefined; }): WorkloadIdentityReader | undefined { if (opts.workloadToken) return workloadTokenReader(opts.workloadToken); if (opts.workloadTokenFile) return workloadTokenFileReader(opts.workloadTokenFile); const token = opts.workloadToken === null ? undefined : readEnv('LIMRUN_WORKLOAD_IDENTITY_TOKEN'); if (token) return workloadTokenReader(token); const file = opts.workloadTokenFile === null ? undefined : readEnv('LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE'); return file ? workloadTokenFileReader(file) : undefined; } export interface ClientOptions { /** * Workload JWT from your identity provider, or a function that returns the current one. A string is * exchanged as is on every renewal, so pass a function when the JWT expires before the client is done. * Takes precedence over workloadTokenFile. Defaults to LIMRUN_WORKLOAD_IDENTITY_TOKEN. Null disables discovery. */ workloadToken?: WorkloadToken | null; /** Projected workload JWT file. Defaults to LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE. Null disables discovery. */ workloadTokenFile?: string | null; /** * Exchange without sending a JWT, for platforms whose egress proxy adds it to requests for the token * service in the X-Limrun-Subject-Token header, so the workload never handles it. Requires bindingId * and cannot be combined with workloadToken or workloadTokenFile. * Defaults to LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED=true. Null disables discovery. */ workloadTokenInjected?: boolean | null; /** Customer federation binding ID. Defaults to LIMRUN_WORKLOAD_IDENTITY_BINDING_ID. */ bindingId?: string | null; /** Token service base URL. Federation defaults to https://sts.limrun.com. */ stsBaseURL?: string; /** * Defaults to process.env['LIM_API_KEY']. */ apiKey?: string | null | undefined; /** * Identify your application before the SDK's default User-Agent, for example "my-app/1.0". * Explicit User-Agent headers in defaultHeaders or request options override this value. */ userAgent?: string | undefined; /** * Override the default base URL for the API, e.g., "https://api.example.com/v2/" * * Defaults to process.env['LIMRUN_BASE_URL']. */ baseURL?: string | null | undefined; /** * The maximum amount of time (in milliseconds) that the client should wait for a response * from the server before timing out a single request. * * Note that request timeouts are retried by default, so in a worst-case scenario you may wait * much longer than this timeout before the promise succeeds or fails. * * @unit milliseconds */ timeout?: number | undefined; /** * Additional `RequestInit` options to be passed to `fetch` calls. * Properties will be overridden by per-request `fetchOptions`. */ fetchOptions?: MergedRequestInit | undefined; /** * Specify a custom `fetch` function implementation. * * If not provided, we expect that `fetch` is defined globally. */ fetch?: Fetch | undefined; /** * The maximum number of times that the client will retry a request in case of a * temporary failure, like a network error or a 5XX error from the server. * * @default 2 */ maxRetries?: number | undefined; /** * Default headers to include with every request to the API. * * These can be removed in individual requests by explicitly setting the * header to `null` in request options. */ defaultHeaders?: HeadersLike | undefined; /** * Default query parameters to include with every request to the API. * * These can be removed in individual requests by explicitly setting the * param to `undefined` in request options. */ defaultQuery?: Record | undefined; /** * Set the log level. * * Defaults to process.env['LIMRUN_LOG'] or 'warn' if it isn't set. */ logLevel?: LogLevel | undefined; /** * Set the logger. * * Defaults to globalThis.console. */ logger?: Logger | undefined; } /** * API Client for interfacing with the Limrun API. */ export class Limrun { apiKey: string | null; baseURL: string; maxRetries: number; timeout: number; logger: Logger; logLevel: LogLevel | undefined; fetchOptions: MergedRequestInit | undefined; private fetch: Fetch; private workloadCredentials?: WorkloadCredentials; #encoder: Opts.RequestEncoder; protected idempotencyHeader?: string; private _options: ClientOptions; /** * API Client for interfacing with the Limrun API. * * @param {string | null | undefined} [opts.apiKey=process.env['LIM_API_KEY'] ?? null] * @param {string} [opts.userAgent] - Application identifier prepended to the SDK's default User-Agent. * @param {string} [opts.baseURL=process.env['LIMRUN_BASE_URL'] ?? https://api.limrun.com] - Override the default base URL for the API. * @param {number} [opts.timeout=5 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. */ constructor({ baseURL = readEnv('LIMRUN_BASE_URL'), apiKey = readEnv('LIM_API_KEY') ?? null, ...opts }: ClientOptions = {}) { // An API key wins, so workload identity settings it overrides cannot fail construction. const identity = apiKey ? undefined : workloadIdentity(opts); const bindingId = opts.bindingId === null ? undefined : opts.bindingId ?? readEnv('LIMRUN_WORKLOAD_IDENTITY_BINDING_ID'); if (!apiKey && identity === injectedWorkloadIdentityReader && !bindingId) throw new Error('workloadTokenInjected requires bindingId or LIMRUN_WORKLOAD_IDENTITY_BINDING_ID'); if (!apiKey && bindingId && !identity) throw new Error( 'Federation requires workloadToken, workloadTokenFile, LIMRUN_WORKLOAD_IDENTITY_TOKEN, or LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE', ); const options: ClientOptions = { apiKey, ...opts, baseURL: baseURL || (!apiKey && identity && !bindingId ? readEnv('DIRECTOR_URL') : undefined) || `https://api.limrun.com`, }; this.baseURL = options.baseURL!; this.timeout = options.timeout ?? Limrun.DEFAULT_TIMEOUT /* 5 minutes */; this.logger = options.logger ?? console; const defaultLogLevel = 'warn'; // Set default logLevel early so that we can log a warning in parseLogLevel. this.logLevel = defaultLogLevel; this.logLevel = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? parseLogLevel(readEnv('LIMRUN_LOG'), "process.env['LIMRUN_LOG']", this) ?? defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; this.fetch = options.fetch ?? Shims.getDefaultFetch(); this.#encoder = Opts.FallbackEncoder; const customHeadersEnv = readEnv('LIMRUN_CUSTOM_HEADERS'); if (customHeadersEnv) { const parsed: Record = {}; for (const line of customHeadersEnv.split('\n')) { const colon = line.indexOf(':'); if (colon >= 0) { parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); } } options.defaultHeaders = { ...parsed, ...options.defaultHeaders }; } this._options = options; this.apiKey = apiKey; if (!apiKey && identity) this.workloadCredentials = new WorkloadCredentials( opts.stsBaseURL ?? readEnv('LIMRUN_STS_BASE_URL') ?? (bindingId ? 'https://sts.limrun.com' : this.baseURL), identity, this.fetch, this.fetchOptions, bindingId, ); } /** * Create a new client instance re-using the same options given to the current client with optional overriding. */ withOptions(options: Partial): this { const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({ ...this._options, baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, ...options, }); return client; } /** * Check whether the base URL is set to its default. */ #baseURLOverridden(): boolean { return this.baseURL !== 'https://api.limrun.com'; } protected defaultQuery(): Record | undefined { return this._options.defaultQuery; } protected validateHeaders({ values, nulls }: NullableHeaders) { if ((this.apiKey || this.workloadCredentials) && values.get('authorization')) { return; } if (nulls.has('authorization')) { return; } throw new Error( 'Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted', ); } protected async authHeaders(opts: FinalRequestOptions): Promise { if (this.apiKey == null) { const explicit = buildHeaders([this._options.defaultHeaders, opts.headers]); if (explicit.values.has('authorization') || explicit.nulls.has('authorization')) return undefined; if (this.workloadCredentials) return buildHeaders([{ Authorization: `Bearer ${await this.workloadCredentials.get()}` }]); return undefined; } return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); } /** * Basic re-implementation of `qs.stringify` for primitive types. */ protected stringifyQuery(query: object | Record): string { return stringifyQuery(query); } private getUserAgent(): string { const sdkUserAgent = `${this.constructor.name}/JS ${VERSION}`; const userAgent = this._options.userAgent?.trim(); return userAgent ? `${userAgent} ${sdkUserAgent}` : sdkUserAgent; } protected defaultIdempotencyKey(): string { return `stainless-node-retry-${uuid4()}`; } protected makeStatusError( status: number, error: Object, message: string | undefined, headers: Headers, ): Errors.APIError { return Errors.APIError.generate(status, error, message, headers); } buildURL( path: string, query: Record | null | undefined, defaultBaseURL?: string | undefined, ): string { const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL; const url = isAbsoluteURL(path) ? new URL(path) : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); const pathQuery = Object.fromEntries(url.searchParams); if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) { query = { ...pathQuery, ...defaultQuery, ...query }; } if (typeof query === 'object' && query && !Array.isArray(query)) { url.search = this.stringifyQuery(query); } return url.toString(); } /** * Used as a callback for mutating the given `FinalRequestOptions` object. */ protected async prepareOptions(options: FinalRequestOptions): Promise {} /** * Used as a callback for mutating the given `RequestInit` object. * * This is useful for cases where you want to add certain headers based off of * the request properties, e.g. `method` or `url`. */ protected async prepareRequest( request: RequestInit, { url, options }: { url: string; options: FinalRequestOptions }, ): Promise {} get(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('get', path, opts); } post(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('post', path, opts); } patch(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('patch', path, opts); } put(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('put', path, opts); } delete(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('delete', path, opts); } private methodRequest( method: HTTPMethod, path: string, opts?: PromiseOrValue, ): APIPromise { return this.request( Promise.resolve(opts).then((opts) => { return { method, path, ...opts }; }), ); } request( options: PromiseOrValue, remainingRetries: number | null = null, ): APIPromise { return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); } private async makeRequest( optionsInput: PromiseOrValue, retriesRemaining: number | null, retryOfRequestLogID: string | undefined, ): Promise { const options = await optionsInput; const maxRetries = options.maxRetries ?? this.maxRetries; if (retriesRemaining == null) { retriesRemaining = maxRetries; } await this.prepareOptions(options); const { req, url, timeout } = await this.buildRequest(options, { retryCount: maxRetries - retriesRemaining, }); await this.prepareRequest(req, { url, options }); /** Not an API request ID, just for correlating local log entries. */ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; const startTime = Date.now(); loggerFor(this).debug( `[${requestLogID}] sending request`, formatRequestDetails({ retryOfRequestLogID, method: options.method, url, options, headers: req.headers, }), ); if (options.signal?.aborted) { throw new Errors.APIUserAbortError(); } const controller = new AbortController(); const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); const headersTime = Date.now(); if (response instanceof globalThis.Error) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; if (options.signal?.aborted) { throw new Errors.APIUserAbortError(); } // detect native connection timeout errors // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" // others do not provide enough information to distinguish timeouts from other connection errors const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); if (retriesRemaining) { loggerFor(this).info( `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`, ); loggerFor(this).debug( `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message, }), ); return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } loggerFor(this).info( `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`, ); loggerFor(this).debug( `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, message: response.message, }), ); if (isTimeout) { throw new Errors.APIConnectionTimeoutError(); } throw new Errors.APIConnectionError({ cause: response }); } const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${ response.ok ? 'succeeded' : 'failed' } with status ${response.status} in ${headersTime - startTime}ms`; if (!response.ok) { const shouldRetry = await this.shouldRetry(response); if (retriesRemaining && shouldRetry) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; // We don't need the body of this response. await Shims.CancelReadableStream(response.body); loggerFor(this).info(`${responseInfo} - ${retryMessage}`); loggerFor(this).debug( `[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime, }), ); return this.retryRequest( options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers, ); } const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; loggerFor(this).info(`${responseInfo} - ${retryMessage}`); const errText = await response.text().catch((err: any) => castToError(err).message); const errJSON = safeJSON(errText) as any; const errMessage = errJSON ? undefined : errText; loggerFor(this).debug( `[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, message: errMessage, durationMs: Date.now() - startTime, }), ); const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); throw err; } loggerFor(this).info(responseInfo); loggerFor(this).debug( `[${requestLogID}] response start`, formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, headers: response.headers, durationMs: headersTime - startTime, }), ); return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; } getAPIList = Pagination.AbstractPage>( path: string, Page: new (...args: any[]) => PageClass, opts?: PromiseOrValue, ): Pagination.PagePromise { return this.requestAPIList( Page, opts && 'then' in opts ? opts.then((opts) => ({ method: 'get', path, ...opts })) : { method: 'get', path, ...opts }, ); } requestAPIList< Item = unknown, PageClass extends Pagination.AbstractPage = Pagination.AbstractPage, >( Page: new (...args: ConstructorParameters) => PageClass, options: PromiseOrValue, ): Pagination.PagePromise { const request = this.makeRequest(options, null, undefined); return new Pagination.PagePromise(this as any as Limrun, request, Page); } async fetchWithTimeout( url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController, ): Promise { const { signal, method, ...options } = init || {}; const abort = this._makeAbort(controller); if (signal) signal.addEventListener('abort', abort, { once: true }); const timeout = setTimeout(abort, ms); const isReadableBody = ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); const fetchOptions: RequestInit = { signal: controller.signal as any, ...(isReadableBody ? { duplex: 'half' } : {}), method: 'GET', ...options, }; if (method) { // Custom methods like 'patch' need to be uppercased // See https://github.com/nodejs/undici/issues/2294 fetchOptions.method = method.toUpperCase(); } try { // use undefined this binding; fetch errors if bound to something else in browser/cloudflare return await this.fetch.call(undefined, url, fetchOptions); } finally { clearTimeout(timeout); } } private async shouldRetry(response: Response): Promise { // Note this is not a standard header. const shouldRetryHeader = response.headers.get('x-should-retry'); // If the server explicitly says whether or not to retry, obey. if (shouldRetryHeader === 'true') return true; if (shouldRetryHeader === 'false') return false; // Retry on request timeouts. if (response.status === 408) return true; // Retry on lock timeouts. if (response.status === 409) return true; // Retry on rate limits. if (response.status === 429) return true; // Retry internal errors. if (response.status >= 500) return true; return false; } private async retryRequest( options: FinalRequestOptions, retriesRemaining: number, requestLogID: string, responseHeaders?: Headers | undefined, ): Promise { let timeoutMillis: number | undefined; // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After const retryAfterHeader = responseHeaders?.get('retry-after'); if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1000; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } // If the API asks us to wait a certain amount of time, just do what it // says, but otherwise calculate a default if (timeoutMillis === undefined) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } await sleep(timeoutMillis); return this.makeRequest(options, retriesRemaining - 1, requestLogID); } private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number { const initialRetryDelay = 0.5; const maxRetryDelay = 8.0; const numRetries = maxRetries - retriesRemaining; // Apply exponential backoff, but not more than the max. const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); // Apply some jitter, take up to at most 25 percent of the retry time. const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1000; } async buildRequest( inputOptions: FinalRequestOptions, { retryCount = 0 }: { retryCount?: number } = {}, ): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> { const options = { ...inputOptions }; const { method, path, query, defaultBaseURL } = options; const url = this.buildURL(path!, query as Record, defaultBaseURL); if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); options.timeout = options.timeout ?? this.timeout; const { bodyHeaders, body } = this.buildBody({ options }); const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); const req: FinalizedRequestInit = { method, headers: reqHeaders, ...(options.signal && { signal: options.signal }), ...((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }), ...(body && { body }), ...((this.fetchOptions as any) ?? {}), ...((options.fetchOptions as any) ?? {}), }; return { req, url, timeout: options.timeout }; } private async buildHeaders({ options, method, bodyHeaders, retryCount, }: { options: FinalRequestOptions; method: HTTPMethod; bodyHeaders: HeadersLike; retryCount: number; }): Promise { let idempotencyHeaders: HeadersLike = {}; if (this.idempotencyHeader && method !== 'get') { if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; } const headers = buildHeaders([ idempotencyHeaders, { Accept: 'application/json', 'User-Agent': this.getUserAgent(), 'X-Stainless-Retry-Count': String(retryCount), ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), ...getPlatformHeaders(), }, await this.authHeaders(options), this._options.defaultHeaders, bodyHeaders, options.headers, ]); this.validateHeaders(headers); return headers.values; } private _makeAbort(controller: AbortController) { // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure // would capture all request options, and cause a memory leak. return () => controller.abort(); } private buildBody({ options }: { options: FinalRequestOptions }): { bodyHeaders: HeadersLike; body: BodyInit | undefined; } { const { body, headers: rawHeaders } = options; if (!body) { // A resource method always passes a `body` key when its operation defines a // request body, even if the caller omitted an optional body param. Keep the // content-type for those, and only elide it for operations with no body at // all (e.g. GET/DELETE). if (body == null && 'body' in options) { return this.#encoder({ body, headers: buildHeaders([rawHeaders]) }); } return { bodyHeaders: undefined, body: undefined }; } const headers = buildHeaders([rawHeaders]); if ( // Pass raw type verbatim ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || (typeof body === 'string' && // Preserve legacy string encoding behavior for now headers.values.has('content-type')) || // `Blob` is superset of `File` ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) || // `FormData` -> `multipart/form-data` body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) ((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream) ) { return { bodyHeaders: undefined, body: body as BodyInit }; } else if ( typeof body === 'object' && (Symbol.asyncIterator in body || (Symbol.iterator in body && 'next' in body && typeof body.next === 'function')) ) { return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable) }; } else if ( typeof body === 'object' && headers.values.get('content-type') === 'application/x-www-form-urlencoded' ) { return { bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' }, body: this.stringifyQuery(body), }; } else { return this.#encoder({ body, headers }); } } static Limrun = this; static DEFAULT_TIMEOUT = 300000; // 5 minutes static LimrunError = Errors.LimrunError; static APIError = Errors.APIError; static APIConnectionError = Errors.APIConnectionError; static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; static APIUserAbortError = Errors.APIUserAbortError; static NotFoundError = Errors.NotFoundError; static ConflictError = Errors.ConflictError; static RateLimitError = Errors.RateLimitError; static BadRequestError = Errors.BadRequestError; static AuthenticationError = Errors.AuthenticationError; static InternalServerError = Errors.InternalServerError; static PermissionDeniedError = Errors.PermissionDeniedError; static UnprocessableEntityError = Errors.UnprocessableEntityError; static toFile = Uploads.toFile; androidInstances: API.AndroidInstances = new API.AndroidInstances(this); assets: API.Assets = new API.Assets(this); secrets: API.Secrets = new API.Secrets(this); iosInstances: API.IosInstances = new API.IosInstances(this); xcodeInstances: API.XcodeInstances = new API.XcodeInstances(this); xcodeSnapshots: API.XcodeSnapshots = new API.XcodeSnapshots(this); iosSnapshots: API.IOSSnapshots = new API.IOSSnapshots(this); gradleSnapshots: API.GradleSnapshots = new API.GradleSnapshots(this); gradleInstances: API.GradleInstances = new API.GradleInstances(this); supportTickets: API.SupportTickets = new API.SupportTickets(this); macosInstances: API.MacosInstances = new API.MacosInstances(this); analytics: API.Analytics = new API.Analytics(this); accessTokens: API.AccessTokens = new API.AccessTokens(this); /** @deprecated Use accessTokens. */ scopedTokens: API.ScopedTokens = new API.ScopedTokens(this); } Limrun.AndroidInstances = AndroidInstances; Limrun.Assets = Assets; Limrun.IosInstances = IosInstances; Limrun.XcodeInstances = XcodeInstances; Limrun.GradleInstances = GradleInstances; Limrun.MacosInstances = MacosInstances; Limrun.Analytics = Analytics; Limrun.AccessTokens = AccessTokens; Limrun.ScopedTokens = ScopedTokens; export declare namespace Limrun { export type RequestOptions = Opts.RequestOptions; export import Items = Pagination.Items; export { type ItemsParams as ItemsParams, type ItemsResponse as ItemsResponse }; export { AndroidInstances as AndroidInstances, type AndroidInstance as AndroidInstance, type AndroidInstancesItems as AndroidInstancesItems, type AndroidInstanceUpdateParams as AndroidInstanceUpdateParams, type AndroidInstanceCreateParams as AndroidInstanceCreateParams, type AndroidInstanceListParams as AndroidInstanceListParams, }; export { Assets as Assets, type Asset as Asset, type AssetListResponse as AssetListResponse, type AssetGetOrCreateResponse as AssetGetOrCreateResponse, type AssetListParams as AssetListParams, type AssetGetOrCreateParams as AssetGetOrCreateParams, type AssetGetOrUploadParams as AssetGetOrUploadParams, type AssetGetOrUploadResponse as AssetGetOrUploadResponse, }; export { IosInstances as IosInstances, type IosInstance as IosInstance, type IosInstancesItems as IosInstancesItems, type IosInstanceUpdateParams as IosInstanceUpdateParams, type IosInstanceCreateParams as IosInstanceCreateParams, type IosInstanceListParams as IosInstanceListParams, type SessionArtifact as SessionArtifact, }; export { XcodeInstances as XcodeInstances, type XcodeInstance as XcodeInstance, type XcodeInstancesItems as XcodeInstancesItems, type XcodeInstanceUpdateParams as XcodeInstanceUpdateParams, type XcodeInstanceCreateParams as XcodeInstanceCreateParams, type XcodeInstanceListParams as XcodeInstanceListParams, type XcodeCreateClientParams as XcodeCreateClientParams, type XcodeClient as XcodeClient, type XcodeProjectConfig as XcodeProjectConfig, type XcodeBuildOptions as XcodeBuildOptions, type XcodeRunOptions as XcodeRunOptions, type ReactNativeBuildConfig as ReactNativeBuildConfig, type SimulatorAttachResult as SimulatorAttachResult, type SimulatorStatus as SimulatorStatus, type SimulatorBuildStatus as SimulatorBuildStatus, type SimulatorAttachment as SimulatorAttachment, type SimulatorDeviceInfo as SimulatorDeviceInfo, type XcodeInfo as XcodeInfo, type XcodeStatus as XcodeStatus, type XcodeSelectResult as XcodeSelectResult, type SandboxInfo as SandboxInfo, type SimulatorInstallState as SimulatorInstallState, type XcodeBuildLog as XcodeBuildLog, type BazelBuildLog as BazelBuildLog, }; export { GradleInstances as GradleInstances, type GradleInstance as GradleInstance, type GradleInstancesItems as GradleInstancesItems, type GradleInstanceUpdateParams as GradleInstanceUpdateParams, type GradleInstanceCreateParams as GradleInstanceCreateParams, type GradleInstanceListParams as GradleInstanceListParams, }; export { MacosInstances as MacosInstances, type MacosInstance as MacosInstance, type MacosInstancesItems as MacosInstancesItems, type MacosInstanceUpdateParams as MacosInstanceUpdateParams, type MacosInstanceCreateParams as MacosInstanceCreateParams, type MacosInstanceListParams as MacosInstanceListParams, }; export { Analytics as Analytics, type AnalyticsInstancesResponse as AnalyticsInstancesResponse, type AnalyticsResponse as AnalyticsResponse, type AnalyticsTimeFilter as AnalyticsTimeFilter, type AnalyticsGetParams as AnalyticsGetParams, type AnalyticsGetInstancesParams as AnalyticsGetInstancesParams, }; export { AccessTokens as AccessTokens, type AccessToken as AccessToken, type AccessTokenCreateParams as AccessTokenCreateParams, type AccessTokenRevokeResponse, ScopedTokens as ScopedTokens, type ScopedToken as ScopedToken, type ScopedTokenCreateParams as ScopedTokenCreateParams, }; }