UNPKG

13.6 kBTypeScriptView Raw
1/*!
2 * Copyright 2022 Google LLC. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16/// <reference types="node" />
17import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
18import { CredentialBody } from 'google-auth-library';
19import * as r from 'teeny-request';
20import { Duplex, DuplexOptions, Readable, Writable } from 'stream';
21import { Interceptor } from './service-object.js';
22/**
23 * A unique symbol for providing a `gccl-gcs-cmd` value
24 * for the `X-Goog-API-Client` header.
25 *
26 * E.g. the `V` in `X-Goog-API-Client: gccl-gcs-cmd/V`
27 **/
28export declare const GCCL_GCS_CMD_KEY: unique symbol;
29export type ResponseBody = any;
30export interface DuplexifyOptions extends DuplexOptions {
31 autoDestroy?: boolean;
32 end?: boolean;
33}
34export interface Duplexify extends Duplex {
35 readonly destroyed: boolean;
36 setWritable(writable: Writable | false | null): void;
37 setReadable(readable: Readable | false | null): void;
38}
39export interface DuplexifyConstructor {
40 obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
41 new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
42 (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
43}
44export interface ParsedHttpRespMessage {
45 resp: r.Response;
46 err?: ApiError;
47}
48export interface MakeAuthenticatedRequest {
49 (reqOpts: DecorateRequestOptions): Duplexify;
50 (reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable;
51 (reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable;
52 (reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify;
53 getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void;
54 authClient: GoogleAuth<AuthClient>;
55}
56export interface Abortable {
57 abort(): void;
58}
59export type AbortableDuplex = Duplexify & Abortable;
60export interface PackageJson {
61 name: string;
62 version: string;
63}
64export interface MakeAuthenticatedRequestFactoryConfig extends Omit<GoogleAuthOptions, 'authClient'> {
65 /**
66 * Automatically retry requests if the response is related to rate limits or
67 * certain intermittent server errors. We will exponentially backoff
68 * subsequent requests by default. (default: true)
69 */
70 autoRetry?: boolean;
71 /**
72 * If true, just return the provided request options. Default: false.
73 */
74 customEndpoint?: boolean;
75 /**
76 * If true, will authenticate when using a custom endpoint. Default: false.
77 */
78 useAuthWithCustomEndpoint?: boolean;
79 /**
80 * Account email address, required for PEM/P12 usage.
81 */
82 email?: string;
83 /**
84 * Maximum number of automatic retries attempted before returning the error.
85 * (default: 3)
86 */
87 maxRetries?: number;
88 stream?: Duplexify;
89 /**
90 * A pre-instantiated `AuthClient` or `GoogleAuth` client that should be used.
91 * A new client will be created if this is not set.
92 */
93 authClient?: AuthClient | GoogleAuth;
94 /**
95 * Determines if a projectId is required for authenticated requests. Defaults to `true`.
96 */
97 projectIdRequired?: boolean;
98}
99export interface MakeAuthenticatedRequestOptions {
100 onAuthenticated: OnAuthenticatedCallback;
101}
102export interface OnAuthenticatedCallback {
103 (err: Error | null, reqOpts?: DecorateRequestOptions): void;
104}
105export interface GoogleErrorBody {
106 code: number;
107 errors?: GoogleInnerError[];
108 response: r.Response;
109 message?: string;
110}
111export interface GoogleInnerError {
112 reason?: string;
113 message?: string;
114}
115export interface MakeWritableStreamOptions {
116 /**
117 * A connection instance used to get a token with and send the request
118 * through.
119 */
120 connection?: {};
121 /**
122 * Metadata to send at the head of the request.
123 */
124 metadata?: {
125 contentType?: string;
126 };
127 /**
128 * Request object, in the format of a standard Node.js http.request() object.
129 */
130 request?: r.Options;
131 makeAuthenticatedRequest(reqOpts: r.OptionsWithUri & {
132 [GCCL_GCS_CMD_KEY]?: string;
133 }, fnobj: {
134 onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void;
135 }): void;
136}
137export interface DecorateRequestOptions extends r.CoreOptions {
138 autoPaginate?: boolean;
139 autoPaginateVal?: boolean;
140 objectMode?: boolean;
141 maxRetries?: number;
142 uri: string;
143 interceptors_?: Interceptor[];
144 shouldReturnStream?: boolean;
145 projectId?: string;
146 [GCCL_GCS_CMD_KEY]?: string;
147}
148export interface ParsedHttpResponseBody {
149 body: ResponseBody;
150 err?: Error;
151}
152/**
153 * Custom error type for API errors.
154 *
155 * @param {object} errorBody - Error object.
156 */
157export declare class ApiError extends Error {
158 code?: number;
159 errors?: GoogleInnerError[];
160 response?: r.Response;
161 constructor(errorMessage: string);
162 constructor(errorBody: GoogleErrorBody);
163 /**
164 * Pieces together an error message by combining all unique error messages
165 * returned from a single GoogleError
166 *
167 * @private
168 *
169 * @param {GoogleErrorBody} err The original error.
170 * @param {GoogleInnerError[]} [errors] Inner errors, if any.
171 * @returns {string}
172 */
173 static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string;
174}
175/**
176 * Custom error type for partial errors returned from the API.
177 *
178 * @param {object} b - Error object.
179 */
180export declare class PartialFailureError extends Error {
181 errors?: GoogleInnerError[];
182 response?: r.Response;
183 constructor(b: GoogleErrorBody);
184}
185export interface BodyResponseCallback {
186 (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void;
187}
188export interface RetryOptions {
189 retryDelayMultiplier?: number;
190 totalTimeout?: number;
191 maxRetryDelay?: number;
192 autoRetry?: boolean;
193 maxRetries?: number;
194 retryableErrorFn?: (err: ApiError) => boolean;
195}
196export interface MakeRequestConfig {
197 /**
198 * Automatically retry requests if the response is related to rate limits or
199 * certain intermittent server errors. We will exponentially backoff
200 * subsequent requests by default. (default: true)
201 */
202 autoRetry?: boolean;
203 /**
204 * Maximum number of automatic retries attempted before returning the error.
205 * (default: 3)
206 */
207 maxRetries?: number;
208 retries?: number;
209 retryOptions?: RetryOptions;
210 stream?: Duplexify;
211 shouldRetryFn?: (response?: r.Response) => boolean;
212}
213export declare class Util {
214 ApiError: typeof ApiError;
215 PartialFailureError: typeof PartialFailureError;
216 /**
217 * No op.
218 *
219 * @example
220 * function doSomething(callback) {
221 * callback = callback || noop;
222 * }
223 */
224 noop(): void;
225 /**
226 * Uniformly process an API response.
227 *
228 * @param {*} err - Error value.
229 * @param {*} resp - Response value.
230 * @param {*} body - Body value.
231 * @param {function} callback - The callback function.
232 */
233 handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void;
234 /**
235 * Sniff an incoming HTTP response message for errors.
236 *
237 * @param {object} httpRespMessage - An incoming HTTP response message from `request`.
238 * @return {object} parsedHttpRespMessage - The parsed response.
239 * @param {?error} parsedHttpRespMessage.err - An error detected.
240 * @param {object} parsedHttpRespMessage.resp - The original response object.
241 */
242 parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage;
243 /**
244 * Parse the response body from an HTTP request.
245 *
246 * @param {object} body - The response body.
247 * @return {object} parsedHttpRespMessage - The parsed response.
248 * @param {?error} parsedHttpRespMessage.err - An error detected.
249 * @param {object} parsedHttpRespMessage.body - The original body value provided
250 * will try to be JSON.parse'd. If it's successful, the parsed value will
251 * be returned here, otherwise the original value and an error will be returned.
252 */
253 parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody;
254 /**
255 * Take a Duplexify stream, fetch an authenticated connection header, and
256 * create an outgoing writable stream.
257 *
258 * @param {Duplexify} dup - Duplexify stream.
259 * @param {object} options - Configuration object.
260 * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through.
261 * @param {object} options.metadata - Metadata to send at the head of the request.
262 * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object.
263 * @param {string=} options.request.method - Default: "POST".
264 * @param {string=} options.request.qs.uploadType - Default: "multipart".
265 * @param {string=} options.streamContentType - Default: "application/octet-stream".
266 * @param {function} onComplete - Callback, executed after the writable Request stream has completed.
267 */
268 makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void;
269 /**
270 * Returns true if the API request should be retried, given the error that was
271 * given the first time the request was attempted. This is used for rate limit
272 * related errors as well as intermittent server errors.
273 *
274 * @param {error} err - The API error to check if it is appropriate to retry.
275 * @return {boolean} True if the API request should be retried, false otherwise.
276 */
277 shouldRetryRequest(err?: ApiError): boolean;
278 /**
279 * Get a function for making authenticated requests.
280 *
281 * @param {object} config - Configuration object.
282 * @param {boolean=} config.autoRetry - Automatically retry requests if the
283 * response is related to rate limits or certain intermittent server
284 * errors. We will exponentially backoff subsequent requests by default.
285 * (default: true)
286 * @param {object=} config.credentials - Credentials object.
287 * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false.
288 * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false.
289 * @param {string=} config.email - Account email address, required for PEM/P12 usage.
290 * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3)
291 * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile.
292 * @param {array} config.scopes - Array of scopes required for the API.
293 */
294 makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest;
295 /**
296 * Make a request through the `retryRequest` module with built-in error
297 * handling and exponential back off.
298 *
299 * @param {object} reqOpts - Request options in the format `request` expects.
300 * @param {object=} config - Configuration object.
301 * @param {boolean=} config.autoRetry - Automatically retry requests if the
302 * response is related to rate limits or certain intermittent server
303 * errors. We will exponentially backoff subsequent requests by default.
304 * (default: true)
305 * @param {number=} config.maxRetries - Maximum number of automatic retries
306 * attempted before returning the error. (default: 3)
307 * @param {object=} config.request - HTTP module for request calls.
308 * @param {function} callback - The callback function.
309 */
310 makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable;
311 /**
312 * Decorate the options about to be made in a request.
313 *
314 * @param {object} reqOpts - The options to be passed to `request`.
315 * @param {string} projectId - The project ID.
316 * @return {object} reqOpts - The decorated reqOpts.
317 */
318 decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions;
319 isCustomType(unknown: any, module: string): boolean;
320 /**
321 * Given two parameters, figure out if this is either:
322 * - Just a callback function
323 * - An options object, and then a callback function
324 * @param optionsOrCallback An options object or callback.
325 * @param cb A potentially undefined callback.
326 */
327 maybeOptionsOrCallback<T = {}, C = (err?: Error) => void>(optionsOrCallback?: T | C, cb?: C): [T, C];
328 _getDefaultHeaders(gcclGcsCmd?: string): {
329 'User-Agent': string;
330 'x-goog-api-client': string;
331 };
332}
333declare const util: Util;
334export { util };