request-got-adapter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,106 @@
1
+ import { type RequestJar, jar as createJar, cookie as parseCookieString } from './cookies';
2
+ import { RequestError as RequestErrorClass, StatusCodeError as StatusCodeErrorClass, TransformError as TransformErrorClass } from './errors';
3
+ import type { FullResponse as FullResponseShape } from './response';
4
+ import type { AuthOptions, OAuthOptions } from './rp-options';
5
+ declare function requestGotAdapter(uriOrOptions: string | requestGotAdapter.Options, optionsOrCallback?: requestGotAdapter.RequestPromiseOptions | requestGotAdapter.RequestCallback, callback?: requestGotAdapter.RequestCallback): requestGotAdapter.RequestPromise;
6
+ declare namespace requestGotAdapter {
7
+ type RequestCallback = (error: unknown, response: FullResponse, body: unknown) => void;
8
+ type FullResponse = FullResponseShape;
9
+ interface RequestPromise<T = any> extends Promise<T> {
10
+ promise(): Promise<T>;
11
+ }
12
+ interface RequestPromiseOptions {
13
+ baseUrl?: string;
14
+ method?: string;
15
+ headers?: Record<string, any>;
16
+ qs?: any;
17
+ qsParseOptions?: any;
18
+ qsStringifyOptions?: any;
19
+ useQuerystring?: boolean;
20
+ body?: any;
21
+ json?: any;
22
+ form?: Record<string, any> | string;
23
+ formData?: Record<string, any>;
24
+ auth?: AuthOptions;
25
+ oauth?: OAuthOptions;
26
+ gzip?: boolean;
27
+ encoding?: string | null;
28
+ timeout?: number;
29
+ time?: boolean;
30
+ simple?: boolean;
31
+ resolveWithFullResponse?: boolean;
32
+ followRedirect?: boolean;
33
+ followAllRedirects?: boolean;
34
+ followOriginalHttpMethod?: boolean;
35
+ maxRedirects?: number;
36
+ strictSSL?: boolean;
37
+ rejectUnauthorized?: boolean;
38
+ ca?: string | Buffer | Array<string | Buffer>;
39
+ cert?: string | Buffer;
40
+ key?: string | Buffer;
41
+ pfx?: string | Buffer;
42
+ passphrase?: string;
43
+ agent?: any;
44
+ agentOptions?: Record<string, any>;
45
+ forever?: boolean;
46
+ jar?: CookieJar | boolean;
47
+ transform?: (body: any, response: FullResponse, resolveWithFullResponse?: boolean) => any;
48
+ transform2xxOnly?: boolean;
49
+ localAddress?: string;
50
+ family?: 4 | 6;
51
+ lookup?: any;
52
+ callback?: RequestCallback;
53
+ }
54
+ interface OptionsWithUri extends RequestPromiseOptions {
55
+ uri: string | {
56
+ href: string;
57
+ };
58
+ }
59
+ interface OptionsWithUrl extends RequestPromiseOptions {
60
+ url: string | {
61
+ href: string;
62
+ };
63
+ }
64
+ type Options = OptionsWithUri | OptionsWithUrl;
65
+ type CookieJar = RequestJar;
66
+ interface RequestPromiseCall {
67
+ (options: Options, callback?: RequestCallback): RequestPromise;
68
+ (uri: string, options?: RequestPromiseOptions, callback?: RequestCallback): RequestPromise;
69
+ (uri: string, callback?: RequestCallback): RequestPromise;
70
+ }
71
+ interface RequestPromiseAPI extends RequestPromiseCall {
72
+ get: RequestPromiseCall;
73
+ head: RequestPromiseCall;
74
+ options: RequestPromiseCall;
75
+ post: RequestPromiseCall;
76
+ put: RequestPromiseCall;
77
+ patch: RequestPromiseCall;
78
+ del: RequestPromiseCall;
79
+ delete: RequestPromiseCall;
80
+ defaults: (options: RequestPromiseOptions) => RequestPromiseAPI;
81
+ forever: (agentOptions?: Record<string, any>) => RequestPromiseAPI;
82
+ jar: typeof createJar;
83
+ cookie: typeof parseCookieString;
84
+ StatusCodeError: typeof StatusCodeErrorClass;
85
+ RequestError: typeof RequestErrorClass;
86
+ TransformError: typeof TransformErrorClass;
87
+ }
88
+ const get: RequestPromiseCall;
89
+ const head: RequestPromiseCall;
90
+ const options: RequestPromiseCall;
91
+ const post: RequestPromiseCall;
92
+ const put: RequestPromiseCall;
93
+ const patch: RequestPromiseCall;
94
+ const del: RequestPromiseCall;
95
+ const defaults: (options: RequestPromiseOptions) => RequestPromiseAPI;
96
+ const forever: (agentOptions?: Record<string, any>) => RequestPromiseAPI;
97
+ const jar: typeof createJar;
98
+ const cookie: typeof parseCookieString;
99
+ const StatusCodeError: typeof StatusCodeErrorClass;
100
+ const RequestError: typeof RequestErrorClass;
101
+ const TransformError: typeof TransformErrorClass;
102
+ type StatusCodeError = StatusCodeErrorClass;
103
+ type RequestError = RequestErrorClass;
104
+ type TransformError = TransformErrorClass;
105
+ }
106
+ export = requestGotAdapter;
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ const args_1 = require("./args");
3
+ const cookies_1 = require("./cookies");
4
+ const core_1 = require("./core");
5
+ const errors_1 = require("./errors");
6
+ function buildApi(defaultOptions) {
7
+ const invoke = (method, args) => {
8
+ const { options, callback } = (0, args_1.normalizeArgs)(args[0], args[1], args[2]);
9
+ const merged = (0, args_1.mergeDefaults)(defaultOptions, options);
10
+ if (method !== undefined)
11
+ merged.method = method;
12
+ return (0, core_1.doRequest)(merged, callback);
13
+ };
14
+ const api = ((...args) => invoke(undefined, args));
15
+ api.get = (...args) => invoke('GET', args);
16
+ api.head = (...args) => invoke('HEAD', args);
17
+ api.options = (...args) => invoke('OPTIONS', args);
18
+ api.post = (...args) => invoke('POST', args);
19
+ api.put = (...args) => invoke('PUT', args);
20
+ api.patch = (...args) => invoke('PATCH', args);
21
+ api.del = (...args) => invoke('DELETE', args);
22
+ api.delete = (...args) => invoke('DELETE', args);
23
+ api.defaults = (options) => buildApi(defaultOptions ? (0, args_1.mergeDefaults)(defaultOptions, options) : options);
24
+ api.forever = (agentOptions) => buildApi({ ...defaultOptions, forever: true, ...(agentOptions !== undefined ? { agentOptions } : {}) });
25
+ api.jar = cookies_1.jar;
26
+ api.cookie = cookies_1.cookie;
27
+ api.StatusCodeError = errors_1.StatusCodeError;
28
+ api.RequestError = errors_1.RequestError;
29
+ api.TransformError = errors_1.TransformError;
30
+ return api;
31
+ }
32
+ const baseApi = buildApi();
33
+ function requestGotAdapter(uriOrOptions, optionsOrCallback, callback) {
34
+ return baseApi(uriOrOptions, optionsOrCallback, callback);
35
+ }
36
+ // Mirrors @types/request-promise-native's export= namespace shape
37
+ (function (requestGotAdapter) {
38
+ requestGotAdapter.get = baseApi.get;
39
+ requestGotAdapter.head = baseApi.head;
40
+ requestGotAdapter.options = baseApi.options;
41
+ requestGotAdapter.post = baseApi.post;
42
+ requestGotAdapter.put = baseApi.put;
43
+ requestGotAdapter.patch = baseApi.patch;
44
+ requestGotAdapter.del = baseApi.del;
45
+ requestGotAdapter.defaults = baseApi.defaults;
46
+ requestGotAdapter.forever = baseApi.forever;
47
+ requestGotAdapter.jar = baseApi.jar;
48
+ requestGotAdapter.cookie = baseApi.cookie;
49
+ requestGotAdapter.StatusCodeError = errors_1.StatusCodeError;
50
+ requestGotAdapter.RequestError = errors_1.RequestError;
51
+ requestGotAdapter.TransformError = errors_1.TransformError;
52
+ })(requestGotAdapter || (requestGotAdapter = {}));
53
+ // `delete` is a reserved word and cannot be a namespace export — TS callers use
54
+ // .del; runtime .delete still works for JS consumers.
55
+ ;
56
+ requestGotAdapter.delete = baseApi.delete;
57
+ module.exports = requestGotAdapter;
@@ -0,0 +1,5 @@
1
+ import type { OAuthOptions } from './rp-options';
2
+ export declare function buildOAuthParams(oauth: OAuthOptions, method: string, urlString: string, formBody?: string, rawBodyForHash?: string | Buffer): Record<string, string>;
3
+ export declare function orderedOAuthKeys(params: Record<string, string>): string[];
4
+ export declare function toOAuthHeader(params: Record<string, string>): string;
5
+ export declare function toOAuthQuery(params: Record<string, string>): string;
package/dist/oauth.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildOAuthParams = buildOAuthParams;
4
+ exports.orderedOAuthKeys = orderedOAuthKeys;
5
+ exports.toOAuthHeader = toOAuthHeader;
6
+ exports.toOAuthQuery = toOAuthQuery;
7
+ const node_crypto_1 = require("node:crypto");
8
+ // RFC 3986 percent-encoding as OAuth 1.0 requires (RFC 5849 §3.6)
9
+ const encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
10
+ const NON_PARAM_FIELDS = new Set([
11
+ 'consumer_secret',
12
+ 'private_key',
13
+ 'token_secret',
14
+ 'realm',
15
+ 'transport_method',
16
+ 'body_hash'
17
+ ]);
18
+ function buildOAuthParams(oauth, method, urlString, formBody, rawBodyForHash) {
19
+ const url = new URL(urlString);
20
+ const oauthParams = {};
21
+ for (const [key, value] of Object.entries(oauth)) {
22
+ if (value === undefined || NON_PARAM_FIELDS.has(key))
23
+ continue;
24
+ oauthParams[key.startsWith('oauth_') ? key : `oauth_${key}`] = String(value);
25
+ }
26
+ oauthParams.oauth_version ??= '1.0';
27
+ oauthParams.oauth_timestamp ??= String(Math.floor(Date.now() / 1000));
28
+ oauthParams.oauth_nonce ??= (0, node_crypto_1.randomBytes)(16).toString('hex');
29
+ oauthParams.oauth_signature_method ??= 'HMAC-SHA1';
30
+ if (oauth.body_hash !== undefined) {
31
+ oauthParams.oauth_body_hash =
32
+ oauth.body_hash === true
33
+ ? (0, node_crypto_1.createHash)('sha1')
34
+ .update(rawBodyForHash ?? '')
35
+ .digest('base64')
36
+ : oauth.body_hash;
37
+ }
38
+ const pairs = [];
39
+ for (const [key, value] of new URLSearchParams(url.search))
40
+ pairs.push([key, value]);
41
+ if (formBody !== undefined)
42
+ for (const [key, value] of new URLSearchParams(formBody))
43
+ pairs.push([key, value]);
44
+ for (const [key, value] of Object.entries(oauthParams))
45
+ pairs.push([key, value]);
46
+ const parameterString = pairs
47
+ .map(([key, value]) => [encode(key), encode(value)])
48
+ .sort(([aKey, aValue], [bKey, bValue]) => {
49
+ if (aKey === bKey)
50
+ return aValue < bValue ? -1 : 1;
51
+ return aKey < bKey ? -1 : 1;
52
+ })
53
+ .map(([key, value]) => `${key}=${value}`)
54
+ .join('&');
55
+ const baseUrl = `${url.protocol}//${url.host}${url.pathname}`;
56
+ const baseString = [method.toUpperCase(), encode(baseUrl), encode(parameterString)].join('&');
57
+ const signingKey = `${encode(oauth.consumer_secret ?? '')}&${encode(oauth.token_secret ?? '')}`;
58
+ const signatureMethod = oauthParams.oauth_signature_method;
59
+ let signature;
60
+ switch (signatureMethod) {
61
+ case 'HMAC-SHA1':
62
+ signature = (0, node_crypto_1.createHmac)('sha1', signingKey).update(baseString).digest('base64');
63
+ break;
64
+ case 'HMAC-SHA256':
65
+ signature = (0, node_crypto_1.createHmac)('sha256', signingKey).update(baseString).digest('base64');
66
+ break;
67
+ case 'RSA-SHA1':
68
+ signature = (0, node_crypto_1.createSign)('RSA-SHA1')
69
+ .update(baseString)
70
+ .sign(oauth.private_key ?? '', 'base64');
71
+ break;
72
+ case 'PLAINTEXT':
73
+ signature = signingKey;
74
+ break;
75
+ default:
76
+ throw new Error(`Invalid signature method: ${signatureMethod}`);
77
+ }
78
+ oauthParams.oauth_signature = signature;
79
+ if (oauth.realm !== undefined)
80
+ oauthParams.realm = oauth.realm;
81
+ return oauthParams;
82
+ }
83
+ // request's concatParams ordering: realm first, params sorted, oauth_signature last
84
+ function orderedOAuthKeys(params) {
85
+ const keys = Object.keys(params)
86
+ .filter((key) => key !== 'realm' && key !== 'oauth_signature')
87
+ .sort();
88
+ if (params.realm !== undefined)
89
+ keys.unshift('realm');
90
+ keys.push('oauth_signature');
91
+ return keys;
92
+ }
93
+ function toOAuthHeader(params) {
94
+ const parts = orderedOAuthKeys(params).map((key) => `${key}="${encode(params[key])}"`);
95
+ return `OAuth ${parts.join(',')}`;
96
+ }
97
+ function toOAuthQuery(params) {
98
+ return orderedOAuthKeys(params)
99
+ .map((key) => `${key}=${encode(params[key])}`)
100
+ .join('&');
101
+ }
@@ -0,0 +1,45 @@
1
+ import { parse as parseLegacyUrl } from 'node:url';
2
+ import type { Prepared } from './translate';
3
+ interface GotResponseLike {
4
+ statusCode: number;
5
+ statusMessage?: string;
6
+ headers: Record<string, unknown>;
7
+ rawHeaders?: string[];
8
+ httpVersion?: string;
9
+ url?: string;
10
+ timings?: {
11
+ response?: number;
12
+ phases: {
13
+ wait?: number;
14
+ dns?: number;
15
+ tcp?: number;
16
+ firstByte?: number;
17
+ download?: number;
18
+ total?: number;
19
+ };
20
+ };
21
+ request?: {
22
+ options?: {
23
+ method?: string;
24
+ };
25
+ };
26
+ }
27
+ export interface FullResponse {
28
+ statusCode: number;
29
+ statusMessage?: string;
30
+ headers: Record<string, unknown>;
31
+ rawHeaders?: string[];
32
+ httpVersion?: string;
33
+ body: unknown;
34
+ request: {
35
+ uri: ReturnType<typeof parseLegacyUrl>;
36
+ method: string;
37
+ headers: Record<string, unknown>;
38
+ };
39
+ toJSON: () => unknown;
40
+ elapsedTime?: number;
41
+ responseStartTime?: number;
42
+ timingPhases?: Record<string, number | undefined>;
43
+ }
44
+ export declare function buildFullResponse(gotResponse: GotResponseLike, prepared: Prepared, body: unknown): FullResponse;
45
+ export {};
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFullResponse = buildFullResponse;
4
+ const node_url_1 = require("node:url");
5
+ function buildFullResponse(gotResponse, prepared, body) {
6
+ const finalMethod = gotResponse.request?.options?.method ?? prepared.method;
7
+ const requestPart = {
8
+ uri: (0, node_url_1.parse)(gotResponse.url ?? prepared.url),
9
+ method: finalMethod,
10
+ headers: prepared.requestHeaders
11
+ };
12
+ const response = {
13
+ statusCode: gotResponse.statusCode,
14
+ statusMessage: gotResponse.statusMessage,
15
+ headers: gotResponse.headers,
16
+ rawHeaders: gotResponse.rawHeaders,
17
+ httpVersion: gotResponse.httpVersion,
18
+ body,
19
+ request: requestPart,
20
+ toJSON() {
21
+ return {
22
+ statusCode: this.statusCode,
23
+ body: this.body,
24
+ headers: this.headers,
25
+ request: { uri: requestPart.uri, method: requestPart.method, headers: requestPart.headers }
26
+ };
27
+ }
28
+ };
29
+ if (prepared.time && gotResponse.timings) {
30
+ const phases = gotResponse.timings.phases;
31
+ response.elapsedTime = phases.total;
32
+ response.responseStartTime = gotResponse.timings.response;
33
+ response.timingPhases = {
34
+ wait: phases.wait,
35
+ dns: phases.dns,
36
+ tcp: phases.tcp,
37
+ firstByte: phases.firstByte,
38
+ download: phases.download,
39
+ total: phases.total
40
+ };
41
+ }
42
+ return response;
43
+ }
@@ -0,0 +1,81 @@
1
+ import type { IParseOptions, IStringifyOptions } from 'qs';
2
+ export interface AuthOptions {
3
+ user?: string;
4
+ username?: string;
5
+ pass?: string;
6
+ password?: string;
7
+ bearer?: string | (() => string);
8
+ sendImmediately?: boolean;
9
+ }
10
+ export interface OAuthOptions {
11
+ consumer_key?: string;
12
+ consumer_secret?: string;
13
+ private_key?: string;
14
+ token?: string;
15
+ token_secret?: string;
16
+ verifier?: string;
17
+ version?: string;
18
+ signature_method?: string;
19
+ realm?: string;
20
+ transport_method?: 'header' | 'query' | 'body';
21
+ body_hash?: true | string;
22
+ timestamp?: string;
23
+ nonce?: string;
24
+ }
25
+ export type Callback = (error: unknown, response: unknown, body: unknown) => void;
26
+ export type TransformFunction = (body: unknown, response: unknown, resolveWithFullResponse?: boolean) => unknown;
27
+ export interface CookieJarLike {
28
+ setCookie(cookieOrString: unknown, uri: string, options?: unknown): unknown;
29
+ getCookieString(uri: string): string;
30
+ getCookies(uri: string): unknown[];
31
+ _jar?: unknown;
32
+ }
33
+ export interface RpOptions {
34
+ uri?: string | {
35
+ href: string;
36
+ };
37
+ url?: string | {
38
+ href: string;
39
+ };
40
+ baseUrl?: string;
41
+ method?: string;
42
+ headers?: Record<string, unknown>;
43
+ qs?: Record<string, unknown>;
44
+ qsParseOptions?: IParseOptions;
45
+ qsStringifyOptions?: IStringifyOptions;
46
+ useQuerystring?: boolean;
47
+ body?: unknown;
48
+ json?: unknown;
49
+ form?: Record<string, unknown> | string;
50
+ formData?: Record<string, unknown>;
51
+ auth?: AuthOptions;
52
+ oauth?: OAuthOptions;
53
+ gzip?: boolean;
54
+ encoding?: string | null;
55
+ timeout?: number;
56
+ time?: boolean;
57
+ simple?: boolean;
58
+ resolveWithFullResponse?: boolean;
59
+ followRedirect?: boolean | ((response: unknown) => boolean);
60
+ followAllRedirects?: boolean;
61
+ followOriginalHttpMethod?: boolean;
62
+ maxRedirects?: number;
63
+ strictSSL?: boolean;
64
+ rejectUnauthorized?: boolean;
65
+ ca?: string | Buffer | Array<string | Buffer>;
66
+ cert?: string | Buffer;
67
+ key?: string | Buffer;
68
+ pfx?: string | Buffer;
69
+ passphrase?: string;
70
+ agent?: unknown;
71
+ agentOptions?: Record<string, unknown>;
72
+ forever?: boolean;
73
+ jar?: boolean | CookieJarLike;
74
+ transform?: TransformFunction;
75
+ transform2xxOnly?: boolean;
76
+ localAddress?: string;
77
+ family?: 4 | 6;
78
+ lookup?: unknown;
79
+ callback?: Callback;
80
+ [key: string]: unknown;
81
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,18 @@
1
+ import { type Headers } from './headers';
2
+ import type { AuthOptions, RpOptions, TransformFunction } from './rp-options';
3
+ export interface Prepared {
4
+ url: string;
5
+ method: string;
6
+ gotOptions: Record<string, unknown>;
7
+ requestHeaders: Headers;
8
+ simple: boolean;
9
+ resolveWithFullResponse: boolean;
10
+ jsonMode: boolean;
11
+ encoding: string | null | undefined;
12
+ transform?: TransformFunction;
13
+ transform2xxOnly: boolean;
14
+ time: boolean;
15
+ deferredAuth?: AuthOptions;
16
+ rpOptions: RpOptions;
17
+ }
18
+ export declare function prepare(rpOptions: RpOptions): Prepared;