@jsforce/jsforce-node 0.0.1 → 3.0.0-next.1

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.
Files changed (127) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +54 -0
  3. package/index.d.ts +4 -0
  4. package/index.js +1 -0
  5. package/lib/VERSION.d.ts +2 -0
  6. package/lib/VERSION.js +3 -0
  7. package/lib/api/analytics/types.d.ts +509 -0
  8. package/lib/api/analytics/types.js +2 -0
  9. package/lib/api/analytics.d.ts +163 -0
  10. package/lib/api/analytics.js +342 -0
  11. package/lib/api/apex.d.ts +44 -0
  12. package/lib/api/apex.js +86 -0
  13. package/lib/api/bulk.d.ts +444 -0
  14. package/lib/api/bulk.js +1372 -0
  15. package/lib/api/chatter.d.ts +133 -0
  16. package/lib/api/chatter.js +248 -0
  17. package/lib/api/metadata/schema.d.ts +16117 -0
  18. package/lib/api/metadata/schema.js +9094 -0
  19. package/lib/api/metadata.d.ts +189 -0
  20. package/lib/api/metadata.js +406 -0
  21. package/lib/api/soap/schema.d.ts +3167 -0
  22. package/lib/api/soap/schema.js +1787 -0
  23. package/lib/api/soap.d.ts +76 -0
  24. package/lib/api/soap.js +155 -0
  25. package/lib/api/streaming/extension.d.ts +94 -0
  26. package/lib/api/streaming/extension.js +151 -0
  27. package/lib/api/streaming.d.ts +160 -0
  28. package/lib/api/streaming.js +252 -0
  29. package/lib/api/tooling.d.ts +284 -0
  30. package/lib/api/tooling.js +202 -0
  31. package/lib/api/wsdl/wsdl2schema.d.ts +1 -0
  32. package/lib/api/wsdl/wsdl2schema.js +354 -0
  33. package/lib/browser/canvas.d.ts +12 -0
  34. package/lib/browser/canvas.js +77 -0
  35. package/lib/browser/client.d.ts +82 -0
  36. package/lib/browser/client.js +244 -0
  37. package/lib/browser/jsonp.d.ts +12 -0
  38. package/lib/browser/jsonp.js +69 -0
  39. package/lib/browser/registry.d.ts +3 -0
  40. package/lib/browser/registry.js +5 -0
  41. package/lib/browser/request.d.ts +10 -0
  42. package/lib/browser/request.js +202 -0
  43. package/lib/cache.d.ts +74 -0
  44. package/lib/cache.js +159 -0
  45. package/lib/connection.d.ts +355 -0
  46. package/lib/connection.js +1153 -0
  47. package/lib/core.d.ts +17 -0
  48. package/lib/core.js +55 -0
  49. package/lib/csv.d.ts +23 -0
  50. package/lib/csv.js +35 -0
  51. package/lib/date.d.ts +82 -0
  52. package/lib/date.js +201 -0
  53. package/lib/http-api.d.ts +75 -0
  54. package/lib/http-api.js +257 -0
  55. package/lib/index.d.ts +12 -0
  56. package/lib/index.js +31 -0
  57. package/lib/jsforce.d.ts +26 -0
  58. package/lib/jsforce.js +67 -0
  59. package/lib/jwtOAuth2.d.ts +8 -0
  60. package/lib/jwtOAuth2.js +23 -0
  61. package/lib/oauth2.d.ts +92 -0
  62. package/lib/oauth2.js +245 -0
  63. package/lib/process.d.ts +157 -0
  64. package/lib/process.js +143 -0
  65. package/lib/query.d.ts +341 -0
  66. package/lib/query.js +817 -0
  67. package/lib/quick-action.d.ts +44 -0
  68. package/lib/quick-action.js +46 -0
  69. package/lib/record-reference.d.ts +46 -0
  70. package/lib/record-reference.js +65 -0
  71. package/lib/record-stream.d.ts +83 -0
  72. package/lib/record-stream.js +233 -0
  73. package/lib/registry/base.d.ts +43 -0
  74. package/lib/registry/base.js +96 -0
  75. package/lib/registry/empty.d.ts +7 -0
  76. package/lib/registry/empty.js +13 -0
  77. package/lib/registry/file.d.ts +11 -0
  78. package/lib/registry/file.js +51 -0
  79. package/lib/registry/index.d.ts +8 -0
  80. package/lib/registry/index.js +21 -0
  81. package/lib/registry/sfdx.d.ts +56 -0
  82. package/lib/registry/sfdx.js +133 -0
  83. package/lib/registry/types.d.ts +47 -0
  84. package/lib/registry/types.js +2 -0
  85. package/lib/request-helper.d.ts +23 -0
  86. package/lib/request-helper.js +102 -0
  87. package/lib/request.d.ts +11 -0
  88. package/lib/request.js +75 -0
  89. package/lib/session-refresh-delegate.d.ts +31 -0
  90. package/lib/session-refresh-delegate.js +69 -0
  91. package/lib/soap.d.ts +60 -0
  92. package/lib/soap.js +246 -0
  93. package/lib/sobject.d.ts +258 -0
  94. package/lib/sobject.js +376 -0
  95. package/lib/soql-builder.d.ts +25 -0
  96. package/lib/soql-builder.js +226 -0
  97. package/lib/transport.d.ts +63 -0
  98. package/lib/transport.js +175 -0
  99. package/lib/types/common.d.ts +560 -0
  100. package/lib/types/common.js +2 -0
  101. package/lib/types/index.d.ts +7 -0
  102. package/lib/types/index.js +23 -0
  103. package/lib/types/projection.d.ts +26 -0
  104. package/lib/types/projection.js +2 -0
  105. package/lib/types/record.d.ts +44 -0
  106. package/lib/types/record.js +2 -0
  107. package/lib/types/schema.d.ts +50 -0
  108. package/lib/types/schema.js +2 -0
  109. package/lib/types/soap.d.ts +43 -0
  110. package/lib/types/soap.js +2 -0
  111. package/lib/types/standard-schema.d.ts +16199 -0
  112. package/lib/types/standard-schema.js +2 -0
  113. package/lib/types/util.d.ts +7 -0
  114. package/lib/types/util.js +2 -0
  115. package/lib/util/formatter.d.ts +8 -0
  116. package/lib/util/formatter.js +24 -0
  117. package/lib/util/function.d.ts +32 -0
  118. package/lib/util/function.js +52 -0
  119. package/lib/util/logger.d.ts +29 -0
  120. package/lib/util/logger.js +102 -0
  121. package/lib/util/promise.d.ts +19 -0
  122. package/lib/util/promise.js +25 -0
  123. package/lib/util/stream.d.ts +12 -0
  124. package/lib/util/stream.js +88 -0
  125. package/package.json +260 -6
  126. package/typings/faye/index.d.ts +16 -0
  127. package/typings/index.d.ts +1 -0
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.FileRegistry = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const base_1 = require("./base");
10
+ /**
11
+ *
12
+ */
13
+ function getDefaultConfigFilePath() {
14
+ const homeDir = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
15
+ if (!homeDir) {
16
+ throw new Error('cannot find user home directory to store configuration files');
17
+ }
18
+ return path_1.default.join(homeDir, '.jsforce', 'config.json');
19
+ }
20
+ /**
21
+ *
22
+ */
23
+ class FileRegistry extends base_1.BaseRegistry {
24
+ _configFilePath;
25
+ constructor({ configFilePath }) {
26
+ super();
27
+ this._configFilePath = configFilePath || getDefaultConfigFilePath();
28
+ try {
29
+ const data = fs_1.default.readFileSync(this._configFilePath, 'utf-8');
30
+ this._registryConfig = JSON.parse(data);
31
+ }
32
+ catch (e) {
33
+ //
34
+ }
35
+ }
36
+ _saveConfig() {
37
+ const data = JSON.stringify(this._registryConfig, null, 4);
38
+ try {
39
+ fs_1.default.writeFileSync(this._configFilePath, data);
40
+ fs_1.default.chmodSync(this._configFilePath, '600');
41
+ }
42
+ catch (e) {
43
+ const configDir = path_1.default.dirname(this._configFilePath);
44
+ fs_1.default.mkdirSync(configDir);
45
+ fs_1.default.chmodSync(configDir, '700');
46
+ fs_1.default.writeFileSync(this._configFilePath, data);
47
+ fs_1.default.chmodSync(this._configFilePath, '600');
48
+ }
49
+ }
50
+ }
51
+ exports.FileRegistry = FileRegistry;
@@ -0,0 +1,8 @@
1
+ import type { Registry } from './types';
2
+ import { FileRegistry } from './file';
3
+ import { SfdxRegistry } from './sfdx';
4
+ import { EmptyRegistry } from './empty';
5
+ declare let registry: Registry;
6
+ export default registry;
7
+ export type { Registry };
8
+ export { FileRegistry, SfdxRegistry, EmptyRegistry };
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EmptyRegistry = exports.SfdxRegistry = exports.FileRegistry = void 0;
4
+ const file_1 = require("./file");
5
+ Object.defineProperty(exports, "FileRegistry", { enumerable: true, get: function () { return file_1.FileRegistry; } });
6
+ const sfdx_1 = require("./sfdx");
7
+ Object.defineProperty(exports, "SfdxRegistry", { enumerable: true, get: function () { return sfdx_1.SfdxRegistry; } });
8
+ const empty_1 = require("./empty");
9
+ Object.defineProperty(exports, "EmptyRegistry", { enumerable: true, get: function () { return empty_1.EmptyRegistry; } });
10
+ let registry;
11
+ try {
12
+ registry =
13
+ process.env.JSFORCE_CONNECTION_REGISTRY === 'sfdx'
14
+ ? new sfdx_1.SfdxRegistry({})
15
+ : new file_1.FileRegistry({});
16
+ }
17
+ catch (e) {
18
+ console.error(e);
19
+ registry = new empty_1.EmptyRegistry();
20
+ }
21
+ exports.default = registry;
@@ -0,0 +1,56 @@
1
+ import Connection from '../connection';
2
+ import { Registry, ConnectionConfig, ClientConfig } from './types';
3
+ import { Schema } from '../types';
4
+ type SfdxOrgList = {
5
+ nonScratchOrgs: SfdxOrgInfo[];
6
+ scratchOrgs: SfdxOrgInfo[];
7
+ };
8
+ type SfdxOrgInfo = {
9
+ orgId: string;
10
+ accessToken: string;
11
+ instanceUrl: string;
12
+ loginUrl: string;
13
+ username: string;
14
+ clientId: string;
15
+ isDevHub: boolean;
16
+ connectedStatus: string;
17
+ lastUsed: string;
18
+ alias?: string;
19
+ };
20
+ /**
21
+ *
22
+ */
23
+ export declare class SfdxRegistry implements Registry {
24
+ _cliPath: string | undefined;
25
+ _orgList: Promise<SfdxOrgList> | undefined;
26
+ _orgInfoMap: {
27
+ [name: string]: Promise<SfdxOrgInfo>;
28
+ };
29
+ _defaultOrgInfo: Promise<SfdxOrgInfo> | undefined;
30
+ constructor({ cliPath }: {
31
+ cliPath?: string;
32
+ });
33
+ _createCommand(command: string, options?: {
34
+ [option: string]: any;
35
+ }, args?: string[]): string;
36
+ _execCommand<T>(command: string, options?: {
37
+ [option: string]: any;
38
+ }, args?: string[]): Promise<T>;
39
+ _getOrgList(): Promise<SfdxOrgList>;
40
+ getConnectionNames(): Promise<string[]>;
41
+ getConnection<S extends Schema = Schema>(name?: string): Promise<Connection<S> | null>;
42
+ _getOrgInfo(username?: string): Promise<SfdxOrgInfo>;
43
+ _memoOrgInfo(pOrgInfo: Promise<SfdxOrgInfo>, username?: string): void;
44
+ getConnectionConfig(name?: string): Promise<{
45
+ accessToken: string;
46
+ instanceUrl: string;
47
+ loginUrl: string;
48
+ } | null>;
49
+ saveConnectionConfig(_name: string, _connConfig: ConnectionConfig): Promise<void>;
50
+ setDefaultConnection(_name: string): Promise<void>;
51
+ removeConnectionConfig(name: string): Promise<void>;
52
+ getClientConfig(_name: string): Promise<null>;
53
+ getClientNames(): Promise<never[]>;
54
+ registerClientConfig(_name: string, _clientConfig: ClientConfig): Promise<void>;
55
+ }
56
+ export {};
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SfdxRegistry = void 0;
7
+ const child_process_1 = require("child_process");
8
+ const strip_ansi_1 = __importDefault(require("strip-ansi"));
9
+ const connection_1 = __importDefault(require("../connection"));
10
+ function isNotNullOrUndefined(v) {
11
+ return v != null;
12
+ }
13
+ /**
14
+ *
15
+ */
16
+ class SfdxRegistry {
17
+ _cliPath;
18
+ _orgList;
19
+ _orgInfoMap = {};
20
+ _defaultOrgInfo;
21
+ constructor({ cliPath }) {
22
+ this._cliPath = cliPath;
23
+ }
24
+ _createCommand(command, options = {}, args = []) {
25
+ return `${this._cliPath ? this._cliPath + '/' : ''}sfdx ${command} ${Object.keys(options)
26
+ .map((option) => `${option.length > 1 ? '--' : '-'}${option}${options[option] != null ? ' ' + options[option] : ''}`)
27
+ .join(' ')} --json ${args.join(' ')}`;
28
+ }
29
+ async _execCommand(command, options = {}, args = []) {
30
+ const cmd = this._createCommand(command, options, args);
31
+ const buf = await new Promise((resolve, reject) => {
32
+ (0, child_process_1.exec)(cmd, (err, ret) => {
33
+ if (err && !ret) {
34
+ reject(err);
35
+ }
36
+ else {
37
+ resolve(ret);
38
+ }
39
+ });
40
+ });
41
+ const body = (0, strip_ansi_1.default)(buf.toString());
42
+ let ret;
43
+ try {
44
+ ret = JSON.parse(body);
45
+ }
46
+ catch (e) {
47
+ throw new Error(`Unexpectedd output from Sfdx cli: ${body}`);
48
+ }
49
+ if (ret.status === 0 && ret.result) {
50
+ return ret.result;
51
+ }
52
+ else {
53
+ const err = new Error(ret.message);
54
+ err.name = ret.name;
55
+ throw err;
56
+ }
57
+ }
58
+ async _getOrgList() {
59
+ if (!this._orgList) {
60
+ this._orgList = this._execCommand('force:org:list');
61
+ }
62
+ return this._orgList;
63
+ }
64
+ async getConnectionNames() {
65
+ const { nonScratchOrgs, scratchOrgs } = await this._getOrgList();
66
+ return [
67
+ ...nonScratchOrgs.map((o) => o.alias).filter(isNotNullOrUndefined),
68
+ ...scratchOrgs.map((o) => o.alias).filter(isNotNullOrUndefined),
69
+ ...nonScratchOrgs.map((o) => o.username),
70
+ ...scratchOrgs.map((o) => o.username),
71
+ ];
72
+ }
73
+ async getConnection(name) {
74
+ const config = await this.getConnectionConfig(name);
75
+ return config ? new connection_1.default(config) : null;
76
+ }
77
+ async _getOrgInfo(username) {
78
+ const options = username ? { u: username } : {};
79
+ if (!username || !this._orgInfoMap[username]) {
80
+ const pOrgInfo = this._execCommand('force:org:display', options);
81
+ this._memoOrgInfo(pOrgInfo, username);
82
+ }
83
+ const orgInfo = username
84
+ ? this._orgInfoMap[username]
85
+ : this._defaultOrgInfo;
86
+ if (!orgInfo) {
87
+ throw new Error('no orginfo found');
88
+ }
89
+ return orgInfo;
90
+ }
91
+ _memoOrgInfo(pOrgInfo, username) {
92
+ const pOrgInfo_ = pOrgInfo.then((orgInfo) => {
93
+ this._orgInfoMap[orgInfo.username] = pOrgInfo_;
94
+ if (orgInfo.alias) {
95
+ this._orgInfoMap[orgInfo.alias] = pOrgInfo_;
96
+ }
97
+ return orgInfo;
98
+ });
99
+ if (username) {
100
+ this._orgInfoMap[username] = pOrgInfo_;
101
+ }
102
+ else {
103
+ this._defaultOrgInfo = pOrgInfo_;
104
+ }
105
+ }
106
+ async getConnectionConfig(name) {
107
+ const orgInfo = await this._getOrgInfo(name);
108
+ if (!orgInfo) {
109
+ return null;
110
+ }
111
+ const { accessToken, instanceUrl, loginUrl } = orgInfo;
112
+ return { accessToken, instanceUrl, loginUrl };
113
+ }
114
+ async saveConnectionConfig(_name, _connConfig) {
115
+ // nothing to do
116
+ }
117
+ async setDefaultConnection(_name) {
118
+ // nothing to do
119
+ }
120
+ async removeConnectionConfig(name) {
121
+ await this._execCommand('force:org:delete', { u: name });
122
+ }
123
+ async getClientConfig(_name) {
124
+ return null;
125
+ }
126
+ async getClientNames() {
127
+ return [];
128
+ }
129
+ async registerClientConfig(_name, _clientConfig) {
130
+ // nothing to do
131
+ }
132
+ }
133
+ exports.SfdxRegistry = SfdxRegistry;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @file Registry for connection information, cached in local file system
3
+ * @author Shinichi Tomita <shinichi.tomita@gmail.com>
4
+ */
5
+ import { Connection } from '..';
6
+ import { Schema } from '../types';
7
+ export type ConnectionConfig = {
8
+ instanceUrl?: string;
9
+ accessToken?: string;
10
+ refreshToken?: string;
11
+ loginUrl?: string;
12
+ oauth2?: ClientConfig;
13
+ };
14
+ export type PersistConnectionConfig = {
15
+ client?: string;
16
+ instanceUrl?: string;
17
+ accessToken?: string;
18
+ };
19
+ export type ClientConfig = {
20
+ clientId?: string;
21
+ clientSecret?: string;
22
+ redirectUri?: string;
23
+ loginUrl?: string;
24
+ };
25
+ export type RegistryConfig = {
26
+ default?: string;
27
+ clients?: {
28
+ [name: string]: ClientConfig;
29
+ };
30
+ connections?: {
31
+ [name: string]: PersistConnectionConfig;
32
+ };
33
+ };
34
+ /**
35
+ *
36
+ */
37
+ export interface Registry {
38
+ getConnectionNames(): Promise<string[]>;
39
+ getConnection<S extends Schema = Schema>(name?: string): Promise<Connection<S> | null>;
40
+ getConnectionConfig(name?: string): Promise<ConnectionConfig | null>;
41
+ saveConnectionConfig(name: string, connConfig: ConnectionConfig): Promise<void>;
42
+ setDefaultConnection(name: string): Promise<void>;
43
+ removeConnectionConfig(name: string): Promise<void>;
44
+ getClientConfig(name: string): Promise<ClientConfig | null>;
45
+ getClientNames(): Promise<string[]>;
46
+ registerClientConfig(name: string, clientConfig: ClientConfig): Promise<void>;
47
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ import { PassThrough } from 'stream';
3
+ import { HttpRequest, HttpRequestOptions, HttpResponse } from './types';
4
+ /**
5
+ *
6
+ */
7
+ export declare function createHttpRequestHandlerStreams(req: HttpRequest, options?: HttpRequestOptions): {
8
+ input: PassThrough;
9
+ output: PassThrough;
10
+ stream: import("stream").Duplex;
11
+ };
12
+ /**
13
+ *
14
+ */
15
+ export declare function isRedirect(status: number): boolean;
16
+ /**
17
+ *
18
+ */
19
+ export declare function performRedirectRequest(req: HttpRequest, res: Omit<HttpResponse, 'body'>, followRedirect: NonNullable<HttpRequestOptions['followRedirect']>, counter: number, redirectCallback: (req: HttpRequest) => void): void;
20
+ /**
21
+ *
22
+ */
23
+ export declare function executeWithTimeout<T>(execFn: () => Promise<T>, msec: number | undefined, cancelCallback?: () => void): Promise<T>;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.executeWithTimeout = exports.performRedirectRequest = exports.isRedirect = exports.createHttpRequestHandlerStreams = void 0;
7
+ const stream_1 = require("stream");
8
+ const stream_2 = require("./util/stream");
9
+ const form_data_1 = __importDefault(require("form-data"));
10
+ /**
11
+ *
12
+ */
13
+ function createHttpRequestHandlerStreams(req, options = {}) {
14
+ const { body: reqBody } = req;
15
+ const input = new stream_1.PassThrough();
16
+ const output = new stream_1.PassThrough();
17
+ const duplex = (0, stream_2.concatStreamsAsDuplex)(input, output);
18
+ if (typeof reqBody !== 'undefined') {
19
+ setTimeout(() => {
20
+ if (reqBody instanceof form_data_1.default) {
21
+ duplex.end(reqBody.getBuffer());
22
+ }
23
+ else {
24
+ duplex.end(reqBody, 'utf8');
25
+ }
26
+ }, 0);
27
+ }
28
+ duplex.on('response', async (res) => {
29
+ if (duplex.listenerCount('complete') > 0) {
30
+ const resBody = await (0, stream_2.readAll)(duplex, options.encoding);
31
+ duplex.emit('complete', {
32
+ ...res,
33
+ body: resBody,
34
+ });
35
+ }
36
+ });
37
+ return { input, output, stream: duplex };
38
+ }
39
+ exports.createHttpRequestHandlerStreams = createHttpRequestHandlerStreams;
40
+ const redirectStatuses = new Set([301, 302, 303, 307, 308]);
41
+ /**
42
+ *
43
+ */
44
+ function isRedirect(status) {
45
+ return redirectStatuses.has(status);
46
+ }
47
+ exports.isRedirect = isRedirect;
48
+ /**
49
+ *
50
+ */
51
+ const MAX_REDIRECT_COUNT = 10;
52
+ /**
53
+ *
54
+ */
55
+ function performRedirectRequest(req, res, followRedirect, counter, redirectCallback) {
56
+ if (counter >= MAX_REDIRECT_COUNT) {
57
+ throw new Error('Reached to maximum redirect count');
58
+ }
59
+ const redirectUrl = res.headers['location'];
60
+ if (!redirectUrl) {
61
+ throw new Error('No redirect URI found');
62
+ }
63
+ const getRedirectRequest = typeof followRedirect === 'function'
64
+ ? followRedirect
65
+ : () => ({
66
+ method: 'GET',
67
+ url: redirectUrl,
68
+ headers: req.headers,
69
+ });
70
+ const nextReqParams = getRedirectRequest(redirectUrl);
71
+ if (!nextReqParams) {
72
+ throw new Error('Cannot handle redirect for ' + redirectUrl);
73
+ }
74
+ redirectCallback(nextReqParams);
75
+ }
76
+ exports.performRedirectRequest = performRedirectRequest;
77
+ /**
78
+ *
79
+ */
80
+ async function executeWithTimeout(execFn, msec, cancelCallback) {
81
+ let timeout = false;
82
+ const pid = msec != null
83
+ ? setTimeout(() => {
84
+ timeout = true;
85
+ cancelCallback?.();
86
+ }, msec)
87
+ : undefined;
88
+ let res;
89
+ try {
90
+ res = await execFn();
91
+ }
92
+ finally {
93
+ if (pid) {
94
+ clearTimeout(pid);
95
+ }
96
+ }
97
+ if (timeout) {
98
+ throw new Error('Request Timeout');
99
+ }
100
+ return res;
101
+ }
102
+ exports.executeWithTimeout = executeWithTimeout;
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" />
2
+ import { Duplex } from 'stream';
3
+ import { HttpRequest, HttpRequestOptions } from './types';
4
+ /**
5
+ *
6
+ */
7
+ export declare function setDefaults(defaults_: HttpRequestOptions): void;
8
+ /**
9
+ *
10
+ */
11
+ export default function request(req: HttpRequest, options_?: HttpRequestOptions): Duplex;
package/lib/request.js ADDED
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.setDefaults = void 0;
7
+ const node_fetch_1 = __importDefault(require("node-fetch"));
8
+ const abort_controller_1 = __importDefault(require("abort-controller"));
9
+ const https_proxy_agent_1 = __importDefault(require("https-proxy-agent"));
10
+ const request_helper_1 = require("./request-helper");
11
+ /**
12
+ *
13
+ */
14
+ let defaults = {};
15
+ /**
16
+ *
17
+ */
18
+ function setDefaults(defaults_) {
19
+ defaults = defaults_;
20
+ }
21
+ exports.setDefaults = setDefaults;
22
+ /**
23
+ *
24
+ */
25
+ async function startFetchRequest(request, options, input, output, emitter, counter = 0) {
26
+ const { httpProxy, followRedirect } = options;
27
+ const agent = httpProxy ? (0, https_proxy_agent_1.default)(httpProxy) : undefined;
28
+ const { url, body, ...rrequest } = request;
29
+ const controller = new abort_controller_1.default();
30
+ let res;
31
+ try {
32
+ res = await (0, request_helper_1.executeWithTimeout)(() => (0, node_fetch_1.default)(url, {
33
+ ...rrequest,
34
+ ...(input && /^(post|put|patch)$/i.test(request.method)
35
+ ? { body: input }
36
+ : {}),
37
+ redirect: 'manual',
38
+ signal: controller.signal,
39
+ agent,
40
+ }), options.timeout, () => controller.abort());
41
+ }
42
+ catch (err) {
43
+ emitter.emit('error', err);
44
+ return;
45
+ }
46
+ const headers = {};
47
+ for (const headerName of res.headers.keys()) {
48
+ headers[headerName.toLowerCase()] = res.headers.get(headerName);
49
+ }
50
+ const response = {
51
+ statusCode: res.status,
52
+ headers,
53
+ };
54
+ if (followRedirect && (0, request_helper_1.isRedirect)(response.statusCode)) {
55
+ try {
56
+ (0, request_helper_1.performRedirectRequest)(request, response, followRedirect, counter, (req) => startFetchRequest(req, options, undefined, output, emitter, counter + 1));
57
+ }
58
+ catch (err) {
59
+ emitter.emit('error', err);
60
+ }
61
+ return;
62
+ }
63
+ emitter.emit('response', response);
64
+ res.body.pipe(output);
65
+ }
66
+ /**
67
+ *
68
+ */
69
+ function request(req, options_ = {}) {
70
+ const options = { ...defaults, ...options_ };
71
+ const { input, output, stream } = (0, request_helper_1.createHttpRequestHandlerStreams)(req, options);
72
+ startFetchRequest(req, options, input, output, stream);
73
+ return stream;
74
+ }
75
+ exports.default = request;
@@ -0,0 +1,31 @@
1
+ /**
2
+ *
3
+ */
4
+ import { Logger } from './util/logger';
5
+ import { Callback, Schema } from './types';
6
+ import Connection from './connection';
7
+ import { TokenResponse } from './oauth2';
8
+ /**
9
+ *
10
+ */
11
+ export type SessionRefreshFunc<S extends Schema> = (conn: Connection<S>, callback: Callback<string, TokenResponse>) => void;
12
+ /**
13
+ *
14
+ */
15
+ export declare class SessionRefreshDelegate<S extends Schema> {
16
+ static _logger: Logger;
17
+ private _refreshFn;
18
+ private _conn;
19
+ private _logger;
20
+ private _lastRefreshedAt;
21
+ private _refreshPromise;
22
+ constructor(conn: Connection<S>, refreshFn: SessionRefreshFunc<S>);
23
+ /**
24
+ * Refresh access token
25
+ * @private
26
+ */
27
+ refresh(since: number): Promise<void>;
28
+ isRefreshing(): boolean;
29
+ waitRefresh(): Promise<void>;
30
+ }
31
+ export default SessionRefreshDelegate;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionRefreshDelegate = void 0;
4
+ /**
5
+ *
6
+ */
7
+ const logger_1 = require("./util/logger");
8
+ /**
9
+ *
10
+ */
11
+ class SessionRefreshDelegate {
12
+ static _logger = (0, logger_1.getLogger)('session-refresh-delegate');
13
+ _refreshFn;
14
+ _conn;
15
+ _logger;
16
+ _lastRefreshedAt = undefined;
17
+ _refreshPromise = undefined;
18
+ constructor(conn, refreshFn) {
19
+ this._conn = conn;
20
+ this._logger = conn._logLevel
21
+ ? SessionRefreshDelegate._logger.createInstance(conn._logLevel)
22
+ : SessionRefreshDelegate._logger;
23
+ this._refreshFn = refreshFn;
24
+ }
25
+ /**
26
+ * Refresh access token
27
+ * @private
28
+ */
29
+ async refresh(since) {
30
+ // Callback immediately When refreshed after designated time
31
+ if (this._lastRefreshedAt && this._lastRefreshedAt > since) {
32
+ return;
33
+ }
34
+ if (this._refreshPromise) {
35
+ await this._refreshPromise;
36
+ return;
37
+ }
38
+ try {
39
+ this._logger.info('<refresh token>');
40
+ this._refreshPromise = new Promise((resolve, reject) => {
41
+ this._refreshFn(this._conn, (err, accessToken, res) => {
42
+ if (!err) {
43
+ this._logger.debug('Connection refresh completed.');
44
+ this._conn.accessToken = accessToken;
45
+ this._conn.emit('refresh', accessToken, res);
46
+ resolve();
47
+ }
48
+ else {
49
+ reject(err);
50
+ }
51
+ });
52
+ });
53
+ await this._refreshPromise;
54
+ this._logger.info('<refresh complete>');
55
+ }
56
+ finally {
57
+ this._refreshPromise = undefined;
58
+ this._lastRefreshedAt = Date.now();
59
+ }
60
+ }
61
+ isRefreshing() {
62
+ return !!this._refreshPromise;
63
+ }
64
+ async waitRefresh() {
65
+ return this._refreshPromise;
66
+ }
67
+ }
68
+ exports.SessionRefreshDelegate = SessionRefreshDelegate;
69
+ exports.default = SessionRefreshDelegate;