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

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 (131) 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 +253 -0
  14. package/lib/api/bulk.js +678 -0
  15. package/lib/api/bulk2.d.ts +324 -0
  16. package/lib/api/bulk2.js +800 -0
  17. package/lib/api/chatter.d.ts +133 -0
  18. package/lib/api/chatter.js +248 -0
  19. package/lib/api/metadata/schema.d.ts +16117 -0
  20. package/lib/api/metadata/schema.js +9094 -0
  21. package/lib/api/metadata.d.ts +189 -0
  22. package/lib/api/metadata.js +406 -0
  23. package/lib/api/soap/schema.d.ts +3167 -0
  24. package/lib/api/soap/schema.js +1787 -0
  25. package/lib/api/soap.d.ts +76 -0
  26. package/lib/api/soap.js +155 -0
  27. package/lib/api/streaming/extension.d.ts +94 -0
  28. package/lib/api/streaming/extension.js +151 -0
  29. package/lib/api/streaming.d.ts +160 -0
  30. package/lib/api/streaming.js +252 -0
  31. package/lib/api/tooling.d.ts +284 -0
  32. package/lib/api/tooling.js +202 -0
  33. package/lib/api/wsdl/wsdl2schema.d.ts +1 -0
  34. package/lib/api/wsdl/wsdl2schema.js +354 -0
  35. package/lib/browser/canvas.d.ts +12 -0
  36. package/lib/browser/canvas.js +77 -0
  37. package/lib/browser/client.d.ts +82 -0
  38. package/lib/browser/client.js +244 -0
  39. package/lib/browser/jsonp.d.ts +12 -0
  40. package/lib/browser/jsonp.js +69 -0
  41. package/lib/browser/registry.d.ts +3 -0
  42. package/lib/browser/registry.js +5 -0
  43. package/lib/browser/request.d.ts +10 -0
  44. package/lib/browser/request.js +202 -0
  45. package/lib/cache.d.ts +74 -0
  46. package/lib/cache.js +159 -0
  47. package/lib/connection.d.ts +356 -0
  48. package/lib/connection.js +1153 -0
  49. package/lib/core.d.ts +17 -0
  50. package/lib/core.js +55 -0
  51. package/lib/csv.d.ts +23 -0
  52. package/lib/csv.js +35 -0
  53. package/lib/date.d.ts +82 -0
  54. package/lib/date.js +201 -0
  55. package/lib/http-api.d.ts +75 -0
  56. package/lib/http-api.js +295 -0
  57. package/lib/index.d.ts +13 -0
  58. package/lib/index.js +32 -0
  59. package/lib/jsforce.d.ts +26 -0
  60. package/lib/jsforce.js +67 -0
  61. package/lib/jwtOAuth2.d.ts +8 -0
  62. package/lib/jwtOAuth2.js +23 -0
  63. package/lib/oauth2.d.ts +92 -0
  64. package/lib/oauth2.js +245 -0
  65. package/lib/process.d.ts +157 -0
  66. package/lib/process.js +143 -0
  67. package/lib/query.d.ts +341 -0
  68. package/lib/query.js +817 -0
  69. package/lib/quick-action.d.ts +44 -0
  70. package/lib/quick-action.js +46 -0
  71. package/lib/record-reference.d.ts +46 -0
  72. package/lib/record-reference.js +65 -0
  73. package/lib/record-stream.d.ts +83 -0
  74. package/lib/record-stream.js +233 -0
  75. package/lib/registry/base.d.ts +43 -0
  76. package/lib/registry/base.js +96 -0
  77. package/lib/registry/empty.d.ts +7 -0
  78. package/lib/registry/empty.js +13 -0
  79. package/lib/registry/file.d.ts +11 -0
  80. package/lib/registry/file.js +51 -0
  81. package/lib/registry/index.d.ts +8 -0
  82. package/lib/registry/index.js +21 -0
  83. package/lib/registry/sfdx.d.ts +56 -0
  84. package/lib/registry/sfdx.js +133 -0
  85. package/lib/registry/types.d.ts +47 -0
  86. package/lib/registry/types.js +2 -0
  87. package/lib/request-helper.d.ts +23 -0
  88. package/lib/request-helper.js +102 -0
  89. package/lib/request.d.ts +11 -0
  90. package/lib/request.js +75 -0
  91. package/lib/session-refresh-delegate.d.ts +31 -0
  92. package/lib/session-refresh-delegate.js +69 -0
  93. package/lib/soap.d.ts +60 -0
  94. package/lib/soap.js +257 -0
  95. package/lib/sobject.d.ts +258 -0
  96. package/lib/sobject.js +376 -0
  97. package/lib/soql-builder.d.ts +25 -0
  98. package/lib/soql-builder.js +226 -0
  99. package/lib/transport.d.ts +63 -0
  100. package/lib/transport.js +175 -0
  101. package/lib/types/common.d.ts +560 -0
  102. package/lib/types/common.js +2 -0
  103. package/lib/types/index.d.ts +7 -0
  104. package/lib/types/index.js +23 -0
  105. package/lib/types/projection.d.ts +26 -0
  106. package/lib/types/projection.js +2 -0
  107. package/lib/types/record.d.ts +44 -0
  108. package/lib/types/record.js +2 -0
  109. package/lib/types/schema.d.ts +50 -0
  110. package/lib/types/schema.js +2 -0
  111. package/lib/types/soap.d.ts +43 -0
  112. package/lib/types/soap.js +2 -0
  113. package/lib/types/standard-schema.d.ts +16199 -0
  114. package/lib/types/standard-schema.js +2 -0
  115. package/lib/types/util.d.ts +7 -0
  116. package/lib/types/util.js +2 -0
  117. package/lib/util/formatter.d.ts +8 -0
  118. package/lib/util/formatter.js +24 -0
  119. package/lib/util/function.d.ts +32 -0
  120. package/lib/util/function.js +52 -0
  121. package/lib/util/get-body-size.d.ts +4 -0
  122. package/lib/util/get-body-size.js +39 -0
  123. package/lib/util/logger.d.ts +29 -0
  124. package/lib/util/logger.js +102 -0
  125. package/lib/util/promise.d.ts +19 -0
  126. package/lib/util/promise.js +25 -0
  127. package/lib/util/stream.d.ts +12 -0
  128. package/lib/util/stream.js +88 -0
  129. package/package.json +262 -6
  130. package/typings/faye/index.d.ts +16 -0
  131. package/typings/index.d.ts +1 -0
@@ -0,0 +1,189 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ /**
5
+ * @file Manages Salesforce Metadata API
6
+ * @author Shinichi Tomita <shinichi.tomita@gmail.com>
7
+ */
8
+ import { EventEmitter } from 'events';
9
+ import { Readable } from 'stream';
10
+ import Connection from '../connection';
11
+ import { Schema, SoapSchemaDef, SoapSchema } from '../types';
12
+ import { Metadata, SaveResult, UpsertResult, ListMetadataQuery, FileProperties, DescribeMetadataResult, RetrieveRequest, DeployOptions, RetrieveResult, DeployResult, AsyncResult, ApiSchemaTypes } from './metadata/schema';
13
+ export * from './metadata/schema';
14
+ /**
15
+ *
16
+ */
17
+ type MetadataType_<K extends keyof ApiSchemaTypes = keyof ApiSchemaTypes> = K extends keyof ApiSchemaTypes ? ApiSchemaTypes[K] extends Metadata ? K : never : never;
18
+ export type MetadataType = MetadataType_;
19
+ export type MetadataDefinition<T extends string, M extends Metadata = Metadata> = Metadata extends M ? T extends keyof ApiSchemaTypes & MetadataType ? ApiSchemaTypes[T] extends Metadata ? ApiSchemaTypes[T] : Metadata : Metadata : M;
20
+ type DeepPartial<T> = T extends any[] ? DeepPartial<T[number]>[] : T extends object ? {
21
+ [K in keyof T]?: DeepPartial<T[K]>;
22
+ } : T;
23
+ export type InputMetadataDefinition<T extends string, M extends Metadata = Metadata> = DeepPartial<MetadataDefinition<T, M>>;
24
+ /**
25
+ * Class for Salesforce Metadata API
26
+ */
27
+ export declare class MetadataApi<S extends Schema> {
28
+ _conn: Connection<S>;
29
+ /**
30
+ * Polling interval in milliseconds
31
+ */
32
+ pollInterval: number;
33
+ /**
34
+ * Polling timeout in milliseconds
35
+ */
36
+ pollTimeout: number;
37
+ /**
38
+ *
39
+ */
40
+ constructor(conn: Connection<S>);
41
+ /**
42
+ * Call Metadata API SOAP endpoint
43
+ *
44
+ * @private
45
+ */
46
+ _invoke(method: string, message: object, schema?: SoapSchema | SoapSchemaDef): Promise<any>;
47
+ /**
48
+ * Add one or more new metadata components to the organization.
49
+ */
50
+ create<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD[]): Promise<SaveResult[]>;
51
+ create<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD): Promise<SaveResult>;
52
+ create<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD | MD[]): Promise<SaveResult | SaveResult[]>;
53
+ /**
54
+ * Read specified metadata components in the organization.
55
+ */
56
+ read<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends MetadataDefinition<T, M> = MetadataDefinition<T, M>>(type: T, fullNames: string[]): Promise<MD[]>;
57
+ read<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends MetadataDefinition<T, M> = MetadataDefinition<T, M>>(type: T, fullNames: string): Promise<MD>;
58
+ read<M extends Metadata = Metadata, T extends MetadataType = MetadataType, MD extends MetadataDefinition<T, M> = MetadataDefinition<T, M>>(type: T, fullNames: string | string[]): Promise<MD | MD[]>;
59
+ /**
60
+ * Update one or more metadata components in the organization.
61
+ */
62
+ update<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: Partial<MD>[]): Promise<SaveResult[]>;
63
+ update<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: Partial<MD>): Promise<SaveResult>;
64
+ update<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: Partial<MD> | Partial<MD>[]): Promise<SaveResult | SaveResult[]>;
65
+ /**
66
+ * Upsert one or more components in your organization's data.
67
+ */
68
+ upsert<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD[]): Promise<UpsertResult[]>;
69
+ upsert<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD): Promise<UpsertResult>;
70
+ upsert<M extends Metadata = Metadata, T extends string = string, MD extends InputMetadataDefinition<T, M> = InputMetadataDefinition<T, M>>(type: T, metadata: MD | MD[]): Promise<UpsertResult | UpsertResult[]>;
71
+ /**
72
+ * Deletes specified metadata components in the organization.
73
+ */
74
+ delete(type: string, fullNames: string[]): Promise<SaveResult[]>;
75
+ delete(type: string, fullNames: string): Promise<SaveResult>;
76
+ delete(type: string, fullNames: string | string[]): Promise<SaveResult | SaveResult[]>;
77
+ /**
78
+ * Rename fullname of a metadata component in the organization
79
+ */
80
+ rename(type: string, oldFullName: string, newFullName: string): Promise<SaveResult>;
81
+ /**
82
+ * Retrieves the metadata which describes your organization, including Apex classes and triggers,
83
+ * custom objects, custom fields on standard objects, tab sets that define an app,
84
+ * and many other components.
85
+ */
86
+ describe(asOfVersion?: string): Promise<DescribeMetadataResult>;
87
+ /**
88
+ * Retrieves property information about metadata components in your organization
89
+ */
90
+ list(queries: ListMetadataQuery | ListMetadataQuery[], asOfVersion?: string): Promise<FileProperties[]>;
91
+ /**
92
+ * Checks the status of asynchronous metadata calls
93
+ */
94
+ checkStatus(asyncProcessId: string): AsyncResultLocator<S, AsyncResult>;
95
+ /**
96
+ * Retrieves XML file representations of components in an organization
97
+ */
98
+ retrieve(request: Partial<RetrieveRequest>): RetrieveResultLocator<S>;
99
+ /**
100
+ * Checks the status of declarative metadata call retrieve() and returns the zip file contents
101
+ */
102
+ checkRetrieveStatus(asyncProcessId: string): Promise<RetrieveResult>;
103
+ /**
104
+ * Will deploy a recently validated deploy request
105
+ *
106
+ * @param options.id = the deploy ID that's been validated already from a previous checkOnly deploy request
107
+ * @param options.rest = a boolean whether or not to use the REST API
108
+ * @returns the deploy ID of the recent validation request
109
+ */
110
+ deployRecentValidation(options: {
111
+ id: string;
112
+ rest?: boolean;
113
+ }): Promise<string>;
114
+ /**
115
+ * Deploy components into an organization using zipped file representations
116
+ * using the REST Metadata API instead of SOAP
117
+ */
118
+ deployRest(zipInput: Buffer, options?: Partial<DeployOptions>): DeployResultLocator<S>;
119
+ /**
120
+ * Deploy components into an organization using zipped file representations
121
+ */
122
+ deploy(zipInput: Readable | Buffer | string, options?: Partial<DeployOptions>): DeployResultLocator<S>;
123
+ /**
124
+ * Checks the status of declarative metadata call deploy()
125
+ */
126
+ checkDeployStatus(asyncProcessId: string, includeDetails?: boolean): Promise<DeployResult>;
127
+ }
128
+ /**
129
+ * The locator class for Metadata API asynchronous call result
130
+ */
131
+ export declare class AsyncResultLocator<S extends Schema, R extends {} = AsyncResult> extends EventEmitter {
132
+ _meta: MetadataApi<S>;
133
+ _promise: Promise<AsyncResult>;
134
+ _id: string | undefined;
135
+ /**
136
+ *
137
+ */
138
+ constructor(meta: MetadataApi<S>, promise: Promise<AsyncResult>);
139
+ /**
140
+ * Promise/A+ interface
141
+ * http://promises-aplus.github.io/promises-spec/
142
+ *
143
+ * @method Metadata~AsyncResultLocator#then
144
+ */
145
+ then<U, V>(onResolve?: ((result: AsyncResult) => U | Promise<U>) | null | undefined, onReject?: ((err: Error) => V | Promise<V>) | null | undefined): Promise<U | V>;
146
+ /**
147
+ * Check the status of async request
148
+ */
149
+ check(): Promise<AsyncResult>;
150
+ /**
151
+ * Polling until async call status becomes complete or error
152
+ */
153
+ poll(interval: number, timeout: number): void;
154
+ /**
155
+ * Check and wait until the async requests become in completed status
156
+ */
157
+ complete(): Promise<R>;
158
+ }
159
+ /**
160
+ * The locator class to track retreive() Metadata API call result
161
+ */
162
+ export declare class RetrieveResultLocator<S extends Schema> extends AsyncResultLocator<S, RetrieveResult> {
163
+ /**
164
+ * Check and wait until the async request becomes in completed status,
165
+ * and retrieve the result data.
166
+ */
167
+ complete(): Promise<RetrieveResult>;
168
+ /**
169
+ * Change the retrieved result to Node.js readable stream
170
+ */
171
+ stream(): Readable;
172
+ }
173
+ /**
174
+ * The locator class to track deploy() Metadata API call result
175
+ *
176
+ * @protected
177
+ * @class Metadata~DeployResultLocator
178
+ * @extends Metadata~AsyncResultLocator
179
+ * @param {Metadata} meta - Metadata API object
180
+ * @param {Promise.<Metadata~AsyncResult>} result - Promise object for async result of deploy() call
181
+ */
182
+ export declare class DeployResultLocator<S extends Schema> extends AsyncResultLocator<S, DeployResult> {
183
+ /**
184
+ * Check and wait until the async request becomes in completed status,
185
+ * and retrieve the result data.
186
+ */
187
+ complete(includeDetails?: boolean): Promise<DeployResult>;
188
+ }
189
+ export default MetadataApi;
@@ -0,0 +1,406 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.DeployResultLocator = exports.RetrieveResultLocator = exports.AsyncResultLocator = exports.MetadataApi = void 0;
21
+ /**
22
+ * @file Manages Salesforce Metadata API
23
+ * @author Shinichi Tomita <shinichi.tomita@gmail.com>
24
+ */
25
+ const events_1 = require("events");
26
+ const stream_1 = require("stream");
27
+ const form_data_1 = __importDefault(require("form-data"));
28
+ const jsforce_1 = require("../jsforce");
29
+ const soap_1 = __importDefault(require("../soap"));
30
+ const function_1 = require("../util/function");
31
+ const schema_1 = require("./metadata/schema");
32
+ __exportStar(require("./metadata/schema"), exports);
33
+ /**
34
+ *
35
+ */
36
+ function deallocateTypeWithMetadata(metadata) {
37
+ const { $, ...md } = metadata;
38
+ return md;
39
+ }
40
+ function assignTypeWithMetadata(metadata, type) {
41
+ const convert = (md) => ({ ['@xsi:type']: type, ...md });
42
+ return Array.isArray(metadata) ? metadata.map(convert) : convert(metadata);
43
+ }
44
+ /**
45
+ * Class for Salesforce Metadata API
46
+ */
47
+ class MetadataApi {
48
+ _conn;
49
+ /**
50
+ * Polling interval in milliseconds
51
+ */
52
+ pollInterval = 1000;
53
+ /**
54
+ * Polling timeout in milliseconds
55
+ */
56
+ pollTimeout = 10000;
57
+ /**
58
+ *
59
+ */
60
+ constructor(conn) {
61
+ this._conn = conn;
62
+ }
63
+ /**
64
+ * Call Metadata API SOAP endpoint
65
+ *
66
+ * @private
67
+ */
68
+ async _invoke(method, message, schema) {
69
+ const soapEndpoint = new soap_1.default(this._conn, {
70
+ xmlns: 'http://soap.sforce.com/2006/04/metadata',
71
+ endpointUrl: `${this._conn.instanceUrl}/services/Soap/m/${this._conn.version}`,
72
+ });
73
+ const res = await soapEndpoint.invoke(method, message, schema ? { result: schema } : undefined, schema_1.ApiSchemas);
74
+ return res.result;
75
+ }
76
+ create(type, metadata) {
77
+ const isArray = Array.isArray(metadata);
78
+ metadata = assignTypeWithMetadata(metadata, type);
79
+ const schema = isArray ? [schema_1.ApiSchemas.SaveResult] : schema_1.ApiSchemas.SaveResult;
80
+ return this._invoke('createMetadata', { metadata }, schema);
81
+ }
82
+ async read(type, fullNames) {
83
+ const ReadResultSchema = type in schema_1.ApiSchemas
84
+ ? {
85
+ type: schema_1.ApiSchemas.ReadResult.type,
86
+ props: {
87
+ records: [type],
88
+ },
89
+ }
90
+ : schema_1.ApiSchemas.ReadResult;
91
+ const res = await this._invoke('readMetadata', { type, fullNames }, ReadResultSchema);
92
+ return Array.isArray(fullNames)
93
+ ? res.records.map(deallocateTypeWithMetadata)
94
+ : deallocateTypeWithMetadata(res.records[0]);
95
+ }
96
+ update(type, metadata) {
97
+ const isArray = Array.isArray(metadata);
98
+ metadata = assignTypeWithMetadata(metadata, type);
99
+ const schema = isArray ? [schema_1.ApiSchemas.SaveResult] : schema_1.ApiSchemas.SaveResult;
100
+ return this._invoke('updateMetadata', { metadata }, schema);
101
+ }
102
+ upsert(type, metadata) {
103
+ const isArray = Array.isArray(metadata);
104
+ metadata = assignTypeWithMetadata(metadata, type);
105
+ const schema = isArray
106
+ ? [schema_1.ApiSchemas.UpsertResult]
107
+ : schema_1.ApiSchemas.UpsertResult;
108
+ return this._invoke('upsertMetadata', { metadata }, schema);
109
+ }
110
+ delete(type, fullNames) {
111
+ const schema = Array.isArray(fullNames)
112
+ ? [schema_1.ApiSchemas.SaveResult]
113
+ : schema_1.ApiSchemas.SaveResult;
114
+ return this._invoke('deleteMetadata', { type, fullNames }, schema);
115
+ }
116
+ /**
117
+ * Rename fullname of a metadata component in the organization
118
+ */
119
+ rename(type, oldFullName, newFullName) {
120
+ return this._invoke('renameMetadata', { type, oldFullName, newFullName }, schema_1.ApiSchemas.SaveResult);
121
+ }
122
+ /**
123
+ * Retrieves the metadata which describes your organization, including Apex classes and triggers,
124
+ * custom objects, custom fields on standard objects, tab sets that define an app,
125
+ * and many other components.
126
+ */
127
+ describe(asOfVersion) {
128
+ if (!asOfVersion) {
129
+ asOfVersion = this._conn.version;
130
+ }
131
+ return this._invoke('describeMetadata', { asOfVersion }, schema_1.ApiSchemas.DescribeMetadataResult);
132
+ }
133
+ /**
134
+ * Retrieves property information about metadata components in your organization
135
+ */
136
+ list(queries, asOfVersion) {
137
+ if (!asOfVersion) {
138
+ asOfVersion = this._conn.version;
139
+ }
140
+ return this._invoke('listMetadata', { queries, asOfVersion }, [
141
+ schema_1.ApiSchemas.FileProperties,
142
+ ]);
143
+ }
144
+ /**
145
+ * Checks the status of asynchronous metadata calls
146
+ */
147
+ checkStatus(asyncProcessId) {
148
+ const res = this._invoke('checkStatus', { asyncProcessId }, schema_1.ApiSchemas.AsyncResult);
149
+ return new AsyncResultLocator(this, res);
150
+ }
151
+ /**
152
+ * Retrieves XML file representations of components in an organization
153
+ */
154
+ retrieve(request) {
155
+ const res = this._invoke('retrieve', { request }, schema_1.ApiSchemas.RetrieveResult);
156
+ return new RetrieveResultLocator(this, res);
157
+ }
158
+ /**
159
+ * Checks the status of declarative metadata call retrieve() and returns the zip file contents
160
+ */
161
+ checkRetrieveStatus(asyncProcessId) {
162
+ return this._invoke('checkRetrieveStatus', { asyncProcessId }, schema_1.ApiSchemas.RetrieveResult);
163
+ }
164
+ /**
165
+ * Will deploy a recently validated deploy request
166
+ *
167
+ * @param options.id = the deploy ID that's been validated already from a previous checkOnly deploy request
168
+ * @param options.rest = a boolean whether or not to use the REST API
169
+ * @returns the deploy ID of the recent validation request
170
+ */
171
+ async deployRecentValidation(options) {
172
+ const { id, rest } = options;
173
+ let response;
174
+ if (rest) {
175
+ const messageBody = JSON.stringify({
176
+ validatedDeployRequestId: id,
177
+ });
178
+ const requestInfo = {
179
+ method: 'POST',
180
+ url: `${this._conn._baseUrl()}/metadata/deployRequest`,
181
+ body: messageBody,
182
+ headers: {
183
+ 'content-type': 'application/json',
184
+ },
185
+ };
186
+ const requestOptions = { headers: 'json' };
187
+ // This is the deploy ID of the deployRecentValidation response, not
188
+ // the already validated deploy ID (i.e., validateddeployrequestid).
189
+ // REST returns an object with an id property, SOAP returns the id as a string directly.
190
+ response = (await this._conn.request(requestInfo, requestOptions)).id;
191
+ }
192
+ else {
193
+ response = await this._invoke('deployRecentValidation', {
194
+ validationId: id,
195
+ });
196
+ }
197
+ return response;
198
+ }
199
+ /**
200
+ * Deploy components into an organization using zipped file representations
201
+ * using the REST Metadata API instead of SOAP
202
+ */
203
+ deployRest(zipInput, options = {}) {
204
+ const form = new form_data_1.default();
205
+ form.append('file', zipInput, {
206
+ contentType: 'application/zip',
207
+ filename: 'package.xml',
208
+ });
209
+ // Add the deploy options
210
+ form.append('entity_content', JSON.stringify({ deployOptions: options }), {
211
+ contentType: 'application/json',
212
+ });
213
+ const request = {
214
+ url: '/metadata/deployRequest',
215
+ method: 'POST',
216
+ headers: { ...form.getHeaders() },
217
+ body: form.getBuffer(),
218
+ };
219
+ const res = this._conn.request(request);
220
+ return new DeployResultLocator(this, res);
221
+ }
222
+ /**
223
+ * Deploy components into an organization using zipped file representations
224
+ */
225
+ deploy(zipInput, options = {}) {
226
+ const res = (async () => {
227
+ const zipContentB64 = await new Promise((resolve, reject) => {
228
+ if ((0, function_1.isObject)(zipInput) &&
229
+ 'pipe' in zipInput &&
230
+ typeof zipInput.pipe === 'function') {
231
+ const bufs = [];
232
+ zipInput.on('data', (d) => bufs.push(d));
233
+ zipInput.on('error', reject);
234
+ zipInput.on('end', () => {
235
+ resolve(Buffer.concat(bufs).toString('base64'));
236
+ });
237
+ // zipInput.resume();
238
+ }
239
+ else if (zipInput instanceof Buffer) {
240
+ resolve(zipInput.toString('base64'));
241
+ }
242
+ else if (zipInput instanceof String || typeof zipInput === 'string') {
243
+ resolve(zipInput);
244
+ }
245
+ else {
246
+ throw 'Unexpected zipInput type';
247
+ }
248
+ });
249
+ return this._invoke('deploy', {
250
+ ZipFile: zipContentB64,
251
+ DeployOptions: options,
252
+ }, schema_1.ApiSchemas.DeployResult);
253
+ })();
254
+ return new DeployResultLocator(this, res);
255
+ }
256
+ /**
257
+ * Checks the status of declarative metadata call deploy()
258
+ */
259
+ checkDeployStatus(asyncProcessId, includeDetails = false) {
260
+ return this._invoke('checkDeployStatus', {
261
+ asyncProcessId,
262
+ includeDetails,
263
+ }, schema_1.ApiSchemas.DeployResult);
264
+ }
265
+ }
266
+ exports.MetadataApi = MetadataApi;
267
+ /*--------------------------------------------*/
268
+ /**
269
+ * The locator class for Metadata API asynchronous call result
270
+ */
271
+ class AsyncResultLocator extends events_1.EventEmitter {
272
+ _meta;
273
+ _promise;
274
+ _id;
275
+ /**
276
+ *
277
+ */
278
+ constructor(meta, promise) {
279
+ super();
280
+ this._meta = meta;
281
+ this._promise = promise;
282
+ }
283
+ /**
284
+ * Promise/A+ interface
285
+ * http://promises-aplus.github.io/promises-spec/
286
+ *
287
+ * @method Metadata~AsyncResultLocator#then
288
+ */
289
+ then(onResolve, onReject) {
290
+ return this._promise.then(onResolve, onReject);
291
+ }
292
+ /**
293
+ * Check the status of async request
294
+ */
295
+ async check() {
296
+ const result = await this._promise;
297
+ this._id = result.id;
298
+ return await this._meta.checkStatus(result.id);
299
+ }
300
+ /**
301
+ * Polling until async call status becomes complete or error
302
+ */
303
+ poll(interval, timeout) {
304
+ const startTime = new Date().getTime();
305
+ const poll = async () => {
306
+ try {
307
+ const now = new Date().getTime();
308
+ if (startTime + timeout < now) {
309
+ let errMsg = 'Polling time out.';
310
+ if (this._id) {
311
+ errMsg += ' Process Id = ' + this._id;
312
+ }
313
+ this.emit('error', new Error(errMsg));
314
+ return;
315
+ }
316
+ const result = await this.check();
317
+ if (result.done) {
318
+ this.emit('complete', result);
319
+ }
320
+ else {
321
+ this.emit('progress', result);
322
+ setTimeout(poll, interval);
323
+ }
324
+ }
325
+ catch (err) {
326
+ this.emit('error', err);
327
+ }
328
+ };
329
+ setTimeout(poll, interval);
330
+ }
331
+ /**
332
+ * Check and wait until the async requests become in completed status
333
+ */
334
+ complete() {
335
+ return new Promise((resolve, reject) => {
336
+ this.on('complete', resolve);
337
+ this.on('error', reject);
338
+ this.poll(this._meta.pollInterval, this._meta.pollTimeout);
339
+ });
340
+ }
341
+ }
342
+ exports.AsyncResultLocator = AsyncResultLocator;
343
+ /*--------------------------------------------*/
344
+ /**
345
+ * The locator class to track retreive() Metadata API call result
346
+ */
347
+ class RetrieveResultLocator extends AsyncResultLocator {
348
+ /**
349
+ * Check and wait until the async request becomes in completed status,
350
+ * and retrieve the result data.
351
+ */
352
+ async complete() {
353
+ const result = await super.complete();
354
+ return this._meta.checkRetrieveStatus(result.id);
355
+ }
356
+ /**
357
+ * Change the retrieved result to Node.js readable stream
358
+ */
359
+ stream() {
360
+ const resultStream = new stream_1.Readable();
361
+ let reading = false;
362
+ resultStream._read = async () => {
363
+ if (reading) {
364
+ return;
365
+ }
366
+ reading = true;
367
+ try {
368
+ const result = await this.complete();
369
+ resultStream.push(Buffer.from(result.zipFile, 'base64'));
370
+ resultStream.push(null);
371
+ }
372
+ catch (e) {
373
+ resultStream.emit('error', e);
374
+ }
375
+ };
376
+ return resultStream;
377
+ }
378
+ }
379
+ exports.RetrieveResultLocator = RetrieveResultLocator;
380
+ /*--------------------------------------------*/
381
+ /**
382
+ * The locator class to track deploy() Metadata API call result
383
+ *
384
+ * @protected
385
+ * @class Metadata~DeployResultLocator
386
+ * @extends Metadata~AsyncResultLocator
387
+ * @param {Metadata} meta - Metadata API object
388
+ * @param {Promise.<Metadata~AsyncResult>} result - Promise object for async result of deploy() call
389
+ */
390
+ class DeployResultLocator extends AsyncResultLocator {
391
+ /**
392
+ * Check and wait until the async request becomes in completed status,
393
+ * and retrieve the result data.
394
+ */
395
+ async complete(includeDetails) {
396
+ const result = await super.complete();
397
+ return this._meta.checkDeployStatus(result.id, includeDetails);
398
+ }
399
+ }
400
+ exports.DeployResultLocator = DeployResultLocator;
401
+ /*--------------------------------------------*/
402
+ /*
403
+ * Register hook in connection instantiation for dynamically adding this API module features
404
+ */
405
+ (0, jsforce_1.registerModule)('metadata', (conn) => new MetadataApi(conn));
406
+ exports.default = MetadataApi;