UNPKG

11.1 kBTypeScriptView Raw
1/// <reference types="node" />
2/// <reference types="node" />
3import type { Agent } from 'node:http';
4import type { SecureContextOptions } from 'node:tls';
5import { type InternalAxiosRequestConfig, type AxiosAdapter } from 'axios';
6import { LogLevel, type Logger } from './logger';
7import { Methods } from './methods';
8import { type RetryOptions } from './retry-policies';
9import type { FilesUploadV2Arguments } from './types/request/files';
10import type { FilesCompleteUploadExternalResponse } from './types/response';
11export interface WebClientOptions {
12 slackApiUrl?: string;
13 logger?: Logger;
14 logLevel?: LogLevel;
15 maxRequestConcurrency?: number;
16 retryConfig?: RetryOptions;
17 agent?: Agent;
18 tls?: TLSOptions;
19 timeout?: number;
20 rejectRateLimitedCalls?: boolean;
21 headers?: Record<string, string>;
22 teamId?: string;
23 /**
24 * Indicates whether to attach the original error to a Web API request error.
25 * When set to true, the original error object will be attached to the Web API request error.
26 * @type {boolean}
27 * @default true
28 */
29 attachOriginalToWebAPIRequestError?: boolean;
30 /**
31 * Custom function to modify outgoing requests. See {@link https://axios-http.com/docs/interceptors Axios interceptor documentation} for more details.
32 * @type {Function | undefined}
33 * @default undefined
34 */
35 requestInterceptor?: RequestInterceptor;
36 /**
37 * Custom functions for modifing and handling outgoing requests.
38 * Useful if you would like to manage outgoing request with a custom http client.
39 * See {@link https://github.com/axios/axios/blob/v1.x/README.md?plain=1#L586 Axios adapter documentation} for more information.
40 * @type {Function | undefined}
41 * @default undefined
42 */
43 adapter?: AdapterConfig;
44}
45export type TLSOptions = Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>;
46export declare enum WebClientEvent {
47 RATE_LIMITED = "rate_limited"
48}
49export interface WebAPICallResult {
50 ok: boolean;
51 error?: string;
52 response_metadata?: {
53 warnings?: string[];
54 next_cursor?: string;
55 scopes?: string[];
56 acceptedScopes?: string[];
57 retryAfter?: number;
58 messages?: string[];
59 };
60}
61export type PaginatePredicate = (page: WebAPICallResult) => boolean | undefined | undefined;
62export type PageReducer<A = any> = (accumulator: A | undefined, page: WebAPICallResult, index: number) => A;
63export type PageAccumulator<R extends PageReducer> = R extends (accumulator: infer A | undefined, page: WebAPICallResult, index: number) => infer A ? A : never;
64/**
65 * An alias to {@link https://github.com/axios/axios/blob/v1.x/index.d.ts#L367 Axios' `InternalAxiosRequestConfig`} object,
66 * which is the main parameter type provided to Axios interceptors and adapters.
67 */
68export type RequestConfig = InternalAxiosRequestConfig;
69/**
70 * An alias to {@link https://github.com/axios/axios/blob/v1.x/index.d.ts#L489 Axios' `AxiosInterceptorManager<InternalAxiosRequestConfig>` onFufilled} method,
71 * which controls the custom request interceptor logic
72 */
73export type RequestInterceptor = (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;
74/**
75 * An alias to {@link https://github.com/axios/axios/blob/v1.x/index.d.ts#L112 Axios' `AxiosAdapter`} interface,
76 * which is the contract required to specify an adapter
77 */
78export type AdapterConfig = AxiosAdapter;
79/**
80 * A client for Slack's Web API
81 *
82 * This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is
83 * a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter.
84 */
85export declare class WebClient extends Methods {
86 /**
87 * The base URL for reaching Slack's Web API. Consider changing this value for testing purposes.
88 */
89 readonly slackApiUrl: string;
90 /**
91 * Authentication and authorization token for accessing Slack Web API (usually begins with `xoxp` or `xoxb`)
92 */
93 readonly token?: string;
94 /**
95 * Configuration for retry operations. See {@link https://github.com/tim-kos/node-retry|node-retry} for more details.
96 */
97 private retryConfig;
98 /**
99 * Queue of requests in which a maximum of {@link WebClientOptions.maxRequestConcurrency} can concurrently be
100 * in-flight.
101 */
102 private requestQueue;
103 /**
104 * Axios HTTP client instance used by this client
105 */
106 private axios;
107 /**
108 * Configuration for custom TLS handling
109 */
110 private tlsConfig;
111 /**
112 * Preference for immediately rejecting API calls which result in a rate-limited response
113 */
114 private rejectRateLimitedCalls;
115 /**
116 * The name used to prefix all logging generated from this object
117 */
118 private static loggerName;
119 /**
120 * This object's logger instance
121 */
122 private logger;
123 /**
124 * This object's teamId value
125 */
126 private teamId?;
127 /**
128 * Configuration to opt-out of attaching the original error
129 * (obtained from the HTTP client) to WebAPIRequestError.
130 */
131 private attachOriginalToWebAPIRequestError;
132 /**
133 * @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`)
134 * @param {Object} [webClientOptions] - Configuration options.
135 * @param {Function} [webClientOptions.requestInterceptor] - An interceptor to mutate outgoing requests. See {@link https://axios-http.com/docs/interceptors Axios interceptors}
136 * @param {Function} [webClientOptions.adapter] - An adapter to allow custom handling of requests. Useful if you would like to use a pre-configured http client. See {@link https://github.com/axios/axios/blob/v1.x/README.md?plain=1#L586 Axios adapter}
137 */
138 constructor(token?: string, { slackApiUrl, logger, logLevel, maxRequestConcurrency, retryConfig, agent, tls, timeout, rejectRateLimitedCalls, headers, teamId, attachOriginalToWebAPIRequestError, requestInterceptor, adapter, }?: WebClientOptions);
139 /**
140 * Generic method for calling a Web API method
141 * @param method - the Web API method to call {@link https://api.slack.com/methods}
142 * @param options - options
143 */
144 apiCall(method: string, options?: Record<string, unknown>): Promise<WebAPICallResult>;
145 /**
146 * Iterate over the result pages of a cursor-paginated Web API method. This method can return two types of values,
147 * depending on which arguments are used. When up to two parameters are used, the return value is an async iterator
148 * which can be used as the iterable in a for-await-of loop. When three or four parameters are used, the return
149 * value is a promise that resolves at the end of iteration. The third parameter, `shouldStop`, is a function that is
150 * called with each `page` and can end iteration by returning `true`. The fourth parameter, `reduce`, is a function
151 * that is called with three arguments: `accumulator`, `page`, and `index`. The `accumulator` is a value of any type
152 * you choose, but it will contain `undefined` when `reduce` is called for the first time. The `page` argument and
153 * `index` arguments are exactly what they say they are. The `reduce` function's return value will be passed in as
154 * `accumulator` the next time its called, and the returned promise will resolve to the last value of `accumulator`.
155 *
156 * The for-await-of syntax is part of ES2018. It is available natively in Node starting with v10.0.0. You may be able
157 * to use it in earlier JavaScript runtimes by transpiling your source with a tool like Babel. However, the
158 * transpiled code will likely sacrifice performance.
159 * @param method - the cursor-paginated Web API method to call {@link https://api.slack.com/docs/pagination}
160 * @param options - options
161 * @param shouldStop - a predicate that is called with each page, and should return true when pagination can end.
162 * @param reduce - a callback that can be used to accumulate a value that the return promise is resolved to
163 */
164 paginate(method: string, options?: Record<string, unknown>): AsyncIterable<WebAPICallResult>;
165 paginate(method: string, options: Record<string, unknown>, shouldStop: PaginatePredicate): Promise<void>;
166 paginate<R extends PageReducer, A extends PageAccumulator<R>>(method: string, options: Record<string, unknown>, shouldStop: PaginatePredicate, reduce?: PageReducer<A>): Promise<A>;
167 /**
168 * This wrapper method provides an easy way to upload files using the following endpoints:
169 *
170 * **#1**: For each file submitted with this method, submit filenames
171 * and file metadata to {@link https://api.slack.com/methods/files.getUploadURLExternal files.getUploadURLExternal} to request a URL to
172 * which to send the file data to and an id for the file
173 *
174 * **#2**: for each returned file `upload_url`, upload corresponding file to
175 * URLs returned from step 1 (e.g. https://files.slack.com/upload/v1/...\")
176 *
177 * **#3**: Complete uploads {@link https://api.slack.com/methods/files.completeUploadExternal files.completeUploadExternal}
178 * @param options
179 */
180 filesUploadV2(options: FilesUploadV2Arguments): Promise<WebAPICallResult & {
181 files: FilesCompleteUploadExternalResponse[];
182 }>;
183 /**
184 * For each file submitted with this method, submits filenames
185 * and file metadata to files.getUploadURLExternal to request a URL to
186 * which to send the file data to and an id for the file
187 * @param fileUploads
188 */
189 private fetchAllUploadURLExternal;
190 /**
191 * Complete uploads.
192 * @param fileUploads
193 * @returns
194 */
195 private completeFileUploads;
196 /**
197 * for each returned file upload URL, upload corresponding file
198 * @param fileUploads
199 * @returns
200 */
201 private postFileUploadsToExternalURL;
202 /**
203 * @param options All file uploads arguments
204 * @returns An array of file upload entries
205 */
206 private getAllFileUploads;
207 /**
208 * Low-level function to make a single API request. handles queuing, retries, and http-level errors
209 */
210 private makeRequest;
211 /**
212 * Transforms options (a simple key-value object) into an acceptable value for a body. This can be either
213 * a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used
214 * when the options contain a binary (a stream or a buffer) and the upload should be done with content-type
215 * multipart/form-data.
216 * @param config - The Axios request configuration object
217 */
218 private serializeApiCallData;
219 /**
220 * Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevant
221 * HTTP headers into the object.
222 * @param response - an http response
223 */
224 private buildResult;
225}
226export default WebClient;
227export declare function buildThreadTsWarningMessage(method: string): string;
228//# sourceMappingURL=WebClient.d.ts.map
\No newline at end of file