@salesforce/core 4.0.0 → 4.0.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 (153) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/aliasesConfig.d.ts +12 -0
  4. package/lib/config/aliasesConfig.js +28 -0
  5. package/lib/config/authInfoConfig.d.ts +19 -0
  6. package/lib/config/authInfoConfig.js +35 -0
  7. package/lib/config/config.d.ts +87 -22
  8. package/lib/config/config.js +117 -65
  9. package/lib/config/configAggregator.d.ts +41 -35
  10. package/lib/config/configAggregator.js +102 -73
  11. package/lib/config/configFile.d.ts +2 -2
  12. package/lib/config/configFile.js +38 -29
  13. package/lib/config/configGroup.d.ts +141 -0
  14. package/lib/config/configGroup.js +225 -0
  15. package/lib/config/configStore.d.ts +9 -9
  16. package/lib/config/configStore.js +17 -15
  17. package/lib/config/envVars.d.ts +15 -9
  18. package/lib/config/envVars.js +71 -47
  19. package/lib/config/orgUsersConfig.js +2 -0
  20. package/lib/config/sandboxOrgConfig.js +2 -0
  21. package/lib/config/sandboxProcessCache.d.ts +16 -0
  22. package/lib/config/sandboxProcessCache.js +38 -0
  23. package/lib/config/tokensConfig.d.ts +10 -0
  24. package/lib/config/tokensConfig.js +29 -0
  25. package/lib/config/ttlConfig.d.ts +34 -0
  26. package/lib/config/ttlConfig.js +50 -0
  27. package/lib/crypto/crypto.js +15 -22
  28. package/lib/crypto/keyChain.js +2 -3
  29. package/lib/crypto/keyChainImpl.d.ts +5 -3
  30. package/lib/crypto/keyChainImpl.js +58 -61
  31. package/lib/crypto/secureBuffer.d.ts +1 -1
  32. package/lib/deviceOauthService.d.ts +3 -3
  33. package/lib/deviceOauthService.js +27 -25
  34. package/lib/exported.d.ts +15 -12
  35. package/lib/exported.js +28 -16
  36. package/lib/global.d.ts +11 -3
  37. package/lib/global.js +39 -12
  38. package/lib/lifecycleEvents.d.ts +1 -1
  39. package/lib/lifecycleEvents.js +3 -0
  40. package/lib/logger.d.ts +19 -9
  41. package/lib/logger.js +112 -86
  42. package/lib/messages.d.ts +53 -36
  43. package/lib/messages.js +81 -91
  44. package/lib/org/authInfo.d.ts +56 -20
  45. package/lib/org/authInfo.js +232 -131
  46. package/lib/org/authRemover.d.ts +8 -7
  47. package/lib/org/authRemover.js +32 -28
  48. package/lib/org/connection.d.ts +13 -37
  49. package/lib/org/connection.js +78 -124
  50. package/lib/org/index.js +5 -1
  51. package/lib/org/org.d.ts +151 -48
  52. package/lib/org/org.js +466 -220
  53. package/lib/org/orgConfigProperties.d.ts +64 -3
  54. package/lib/org/orgConfigProperties.js +96 -4
  55. package/lib/org/permissionSetAssignment.js +4 -13
  56. package/lib/org/scratchOrgCache.d.ts +20 -0
  57. package/lib/org/scratchOrgCache.js +33 -0
  58. package/lib/org/scratchOrgCreate.d.ts +28 -17
  59. package/lib/org/scratchOrgCreate.js +125 -53
  60. package/lib/org/scratchOrgErrorCodes.d.ts +9 -3
  61. package/lib/org/scratchOrgErrorCodes.js +34 -17
  62. package/lib/org/scratchOrgFeatureDeprecation.js +1 -6
  63. package/lib/org/scratchOrgInfoApi.d.ts +21 -47
  64. package/lib/org/scratchOrgInfoApi.js +129 -63
  65. package/lib/org/scratchOrgInfoGenerator.d.ts +6 -5
  66. package/lib/org/scratchOrgInfoGenerator.js +76 -62
  67. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  68. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  69. package/lib/org/scratchOrgSettingsGenerator.d.ts +44 -21
  70. package/lib/org/scratchOrgSettingsGenerator.js +165 -98
  71. package/lib/org/scratchOrgTypes.d.ts +43 -0
  72. package/lib/org/scratchOrgTypes.js +9 -0
  73. package/lib/org/user.d.ts +1 -1
  74. package/lib/org/user.js +25 -34
  75. package/lib/schema/printer.d.ts +6 -0
  76. package/lib/schema/printer.js +34 -31
  77. package/lib/schema/validator.d.ts +12 -10
  78. package/lib/schema/validator.js +56 -76
  79. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -20
  80. package/lib/{sfdxError.js → sfError.js} +40 -30
  81. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  82. package/lib/sfProject.js +651 -0
  83. package/lib/{globalInfo → stateAggregator}/accessors/aliasAccessor.d.ts +27 -12
  84. package/lib/{globalInfo → stateAggregator}/accessors/aliasAccessor.js +47 -31
  85. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  86. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  87. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  88. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  89. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  90. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  91. package/lib/stateAggregator/index.d.ts +4 -0
  92. package/lib/stateAggregator/index.js +27 -0
  93. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  94. package/lib/stateAggregator/stateAggregator.js +46 -0
  95. package/lib/status/myDomainResolver.d.ts +1 -1
  96. package/lib/status/myDomainResolver.js +4 -4
  97. package/lib/status/pollingClient.js +4 -4
  98. package/lib/status/streamingClient.d.ts +2 -2
  99. package/lib/status/streamingClient.js +58 -63
  100. package/lib/status/types.d.ts +2 -2
  101. package/lib/testSetup.d.ts +206 -75
  102. package/lib/testSetup.js +463 -165
  103. package/lib/util/cache.d.ts +2 -2
  104. package/lib/util/cache.js +6 -6
  105. package/lib/util/checkLightningDomain.js +3 -4
  106. package/lib/util/directoryWriter.d.ts +12 -0
  107. package/lib/util/directoryWriter.js +54 -0
  108. package/lib/util/getJwtAudienceUrl.js +1 -1
  109. package/lib/util/internal.d.ts +28 -2
  110. package/lib/util/internal.js +65 -8
  111. package/lib/util/jsonXmlTools.js +2 -4
  112. package/lib/util/mapKeys.d.ts +9 -9
  113. package/lib/util/mapKeys.js +13 -9
  114. package/lib/util/sfdc.d.ts +51 -51
  115. package/lib/util/sfdc.js +74 -79
  116. package/lib/util/sfdcUrl.d.ts +5 -19
  117. package/lib/util/sfdcUrl.js +40 -49
  118. package/lib/util/structuredWriter.d.ts +9 -0
  119. package/lib/util/structuredWriter.js +3 -0
  120. package/lib/util/zipWriter.d.ts +8 -6
  121. package/lib/util/zipWriter.js +13 -13
  122. package/lib/webOAuthServer.d.ts +20 -6
  123. package/lib/webOAuthServer.js +102 -56
  124. package/messageTransformer/messageTransformer.ts +93 -0
  125. package/messages/auth.md +9 -1
  126. package/messages/config.md +42 -6
  127. package/messages/connection.md +8 -0
  128. package/messages/core.md +10 -0
  129. package/messages/envVars.md +37 -3
  130. package/messages/org.md +21 -1
  131. package/messages/scratchOrgCreate.md +2 -6
  132. package/messages/scratchOrgErrorCodes.md +17 -1
  133. package/messages/scratchOrgInfoApi.md +9 -0
  134. package/messages/scratchOrgInfoGenerator.md +9 -1
  135. package/package.json +121 -46
  136. package/CHANGELOG.md +0 -1244
  137. package/lib/config/keychainConfig.d.ts +0 -19
  138. package/lib/config/keychainConfig.js +0 -43
  139. package/lib/globalInfo/accessors/orgAccessor.d.ts +0 -13
  140. package/lib/globalInfo/accessors/orgAccessor.js +0 -45
  141. package/lib/globalInfo/accessors/tokenAccessor.d.ts +0 -13
  142. package/lib/globalInfo/accessors/tokenAccessor.js +0 -35
  143. package/lib/globalInfo/globalInfoConfig.d.ts +0 -36
  144. package/lib/globalInfo/globalInfoConfig.js +0 -105
  145. package/lib/globalInfo/index.d.ts +0 -6
  146. package/lib/globalInfo/index.js +0 -29
  147. package/lib/globalInfo/sfdxDataHandler.d.ts +0 -43
  148. package/lib/globalInfo/sfdxDataHandler.js +0 -217
  149. package/lib/globalInfo/types.d.ts +0 -39
  150. package/lib/globalInfo/types.js +0 -10
  151. package/lib/sfdxProject.js +0 -557
  152. package/lib/util/fs.d.ts +0 -201
  153. package/lib/util/fs.js +0 -378
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.SingleRecordQueryErrors = exports.Connection = exports.DNS_ERROR_NAME = exports.SFDX_HTTP_HEADERS = void 0;
10
10
  /* eslint-disable @typescript-eslint/ban-ts-comment */
11
11
  const url_1 = require("url");
12
- const FormData = require("form-data");
13
12
  const kit_1 = require("@salesforce/kit");
14
13
  const ts_types_1 = require("@salesforce/ts-types");
15
14
  const jsforce_1 = require("jsforce");
@@ -17,17 +16,13 @@ const tooling_1 = require("jsforce/lib/api/tooling");
17
16
  const myDomainResolver_1 = require("../status/myDomainResolver");
18
17
  const configAggregator_1 = require("../config/configAggregator");
19
18
  const logger_1 = require("../logger");
20
- const sfdxError_1 = require("../sfdxError");
19
+ const sfError_1 = require("../sfError");
21
20
  const sfdc_1 = require("../util/sfdc");
22
21
  const messages_1 = require("../messages");
23
22
  const lifecycleEvents_1 = require("../lifecycleEvents");
24
- messages_1.Messages.importMessagesDirectory(__dirname);
25
- const messages = messages_1.Messages.load('@salesforce/core', 'connection', [
26
- 'incorrectAPIVersionError',
27
- 'domainNotFoundError',
28
- 'noInstanceUrlError',
29
- ]);
30
- const clientId = `sfdx toolbelt:${process.env.SFDX_SET_CLIENT_IDS || ''}`;
23
+ const orgConfigProperties_1 = require("./orgConfigProperties");
24
+ const messages = new messages_1.Messages('@salesforce/core', 'connection', new Map([["incorrectAPIVersionError", "Invalid API version %s. Expecting format \"[1-9][0-9].0\", i.e. 42.0"], ["domainNotFoundError", "The org cannot be found"], ["domainNotFoundError.actions", ["Verify that the org still exists',", "If your org is newly created, wait a minute and run your command again',", "If you deployed or updated the org's My Domain, logout from the CLI and authenticate again\",", "If you are running in a CI environment with a DNS that blocks external IPs, try setting SFDX_DISABLE_DNS_CHECK=true'"]], ["noInstanceUrlError", "Connection has no instanceUrl."], ["noInstanceUrlError.actions", "Make sure the instanceUrl is set in your command or config."], ["noApiVersionsError", "Org failed to respond with its list of API versions. This is usually the result of domain changes like activating MyDomain or Enhanced Domains"], ["noApiVersionsError.actions", "Re-authenticate to the org."]]));
25
+ const clientId = `sfdx toolbelt:${process.env.SFDX_SET_CLIENT_IDS ?? ''}`;
31
26
  exports.SFDX_HTTP_HEADERS = {
32
27
  'content-type': 'application/json',
33
28
  'user-agent': clientId,
@@ -57,13 +52,12 @@ class Connection extends jsforce_1.Connection {
57
52
  * @ignore
58
53
  */
59
54
  constructor(options) {
60
- super(options.connectionOptions || {});
61
- // eslint-disable-next-line @typescript-eslint/unbound-method
62
- this.tooling.autoFetchQuery = Connection.prototype.autoFetchQuery;
55
+ super(options.connectionOptions ?? {});
56
+ // Save whether we've successfully resolved this connection's instance URL.
57
+ this.hasResolved = false;
63
58
  this.options = options;
64
59
  this.username = options.authInfo.getUsername();
65
60
  }
66
- // The following are all initialized in either this constructor or the super constructor, sometimes conditionally...
67
61
  /**
68
62
  * Tooling api reference.
69
63
  */
@@ -76,17 +70,16 @@ class Connection extends jsforce_1.Connection {
76
70
  * @param options Constructor options.
77
71
  */
78
72
  static async create(options) {
79
- var _a, _b;
80
73
  const baseOptions = {
81
- version: (_a = options.connectionOptions) === null || _a === void 0 ? void 0 : _a.version,
74
+ version: options.connectionOptions?.version,
82
75
  callOptions: {
83
76
  client: clientId,
84
77
  },
85
78
  };
86
79
  if (!baseOptions.version) {
87
80
  // Set the API version obtained from the config aggregator.
88
- const configAggregator = options.configAggregator || (await configAggregator_1.ConfigAggregator.create());
89
- baseOptions.version = (0, ts_types_1.asString)(configAggregator.getInfo('apiVersion').value);
81
+ const configAggregator = options.configAggregator ?? (await configAggregator_1.ConfigAggregator.create());
82
+ baseOptions.version = (0, ts_types_1.asString)(configAggregator.getInfo('org-api-version').value);
90
83
  }
91
84
  const providedOptions = options.authInfo.getConnectionOptions();
92
85
  // Get connection options from auth info and create a new jsForce connection
@@ -96,13 +89,10 @@ class Connection extends jsforce_1.Connection {
96
89
  try {
97
90
  // No version passed in or in the config, so load one.
98
91
  if (!baseOptions.version) {
99
- const cachedVersion = await conn.loadInstanceApiVersion();
100
- if (cachedVersion) {
101
- conn.setApiVersion(cachedVersion);
102
- }
92
+ await conn.useLatestApiVersion();
103
93
  }
104
94
  else {
105
- conn.logger.debug(`The apiVersion ${baseOptions.version} was found from ${((_b = options.connectionOptions) === null || _b === void 0 ? void 0 : _b.version) ? 'passed in options' : 'config'}`);
95
+ conn.logger.debug(`The org-api-version ${baseOptions.version} was found from ${options.connectionOptions?.version ? 'passed in options' : 'config'}`);
106
96
  }
107
97
  }
108
98
  catch (err) {
@@ -112,7 +102,7 @@ class Connection extends jsforce_1.Connection {
112
102
  }
113
103
  conn.logger.debug(`Error trying to load the API version: ${e.name} - ${e.message}`);
114
104
  }
115
- conn.logger.debug(`Using apiVersion ${conn.getApiVersion()}`);
105
+ conn.logger.debug(`Connection created with apiVersion ${conn.getApiVersion()}`);
116
106
  return conn;
117
107
  }
118
108
  /**
@@ -123,14 +113,10 @@ class Connection extends jsforce_1.Connection {
123
113
  this.logger = this.tooling._logger = await logger_1.Logger.child('connection');
124
114
  }
125
115
  /**
126
- * TODO: This should be moved into JSForce V2 once ready
127
- * this is only a temporary solution to support both REST and SOAP APIs
128
- *
129
116
  * deploy a zipped buffer from the SDRL with REST or SOAP
130
117
  *
131
118
  * @param zipInput data to deploy
132
119
  * @param options JSForce deploy options + a boolean for rest
133
- * @param callback
134
120
  */
135
121
  async deploy(zipInput, options) {
136
122
  const rest = options.rest;
@@ -139,27 +125,7 @@ class Connection extends jsforce_1.Connection {
139
125
  if (rest) {
140
126
  this.logger.debug('deploy with REST');
141
127
  await this.refreshAuth();
142
- const headers = {
143
- Authorization: this && `OAuth ${this.accessToken}`,
144
- 'Sforce-Call-Options': 'client=sfdx-core',
145
- };
146
- const client = this.oauth2 && this.oauth2.clientId;
147
- if (client) {
148
- headers.clientId = client;
149
- }
150
- const form = new FormData();
151
- // Add the zip file
152
- form.append('file', zipInput, {
153
- contentType: 'application/zip',
154
- filename: 'package.xml',
155
- });
156
- // Add the deploy options
157
- form.append('entity_content', JSON.stringify({ deployOptions: options }), {
158
- contentType: 'application/json',
159
- });
160
- const url = `${this.baseUrl()}/metadata/deployRequest`;
161
- const httpRequest = { method: 'POST', url, headers, body: form };
162
- return this.request(httpRequest);
128
+ return this.metadata.deployRest(zipInput, options);
163
129
  }
164
130
  else {
165
131
  this.logger.debug('deploy with SOAP');
@@ -175,9 +141,15 @@ class Connection extends jsforce_1.Connection {
175
141
  */
176
142
  request(request, options) {
177
143
  const httpRequest = (0, ts_types_1.isString)(request) ? { method: 'GET', url: request } : request;
178
- httpRequest.headers = Object.assign({}, exports.SFDX_HTTP_HEADERS, httpRequest.headers);
144
+ // prevent duplicate headers by lowercasing the keys on the incoming request
145
+ const lowercasedHeaders = httpRequest.headers
146
+ ? Object.fromEntries(Object.entries(httpRequest.headers).map(([key, value]) => [key.toLowerCase(), value]))
147
+ : {};
148
+ httpRequest.headers = {
149
+ ...exports.SFDX_HTTP_HEADERS,
150
+ ...lowercasedHeaders,
151
+ };
179
152
  this.logger.debug(`request: ${JSON.stringify(httpRequest)}`);
180
- // The "as" is a workaround for the jsforce typings.
181
153
  return super.request(httpRequest, options);
182
154
  }
183
155
  /**
@@ -185,50 +157,35 @@ class Connection extends jsforce_1.Connection {
185
157
  */
186
158
  baseUrl() {
187
159
  // essentially the same as pathJoin(super.instanceUrl, 'services', 'data', `v${super.version}`);
160
+ // eslint-disable-next-line no-underscore-dangle
188
161
  return super._baseUrl();
189
162
  }
190
- /**
191
- * TODO: This should be moved into JSForce V2 once ready
192
- * this is only a temporary solution to support both REST and SOAP APIs
193
- *
194
- * Will deploy a recently validated deploy request
195
- *
196
- * @param options.id = the deploy ID that's been validated already from a previous checkOnly deploy request
197
- * @param options.rest = a boolean whether or not to use the REST API
198
- */
199
- async deployRecentValidation(options) {
200
- const rest = options.rest;
201
- delete options.rest;
202
- if (rest) {
203
- const url = `${this.baseUrl()}/metadata/deployRequest`;
204
- const messageBody = JSON.stringify({
205
- validatedDeployRequestId: options.id,
206
- });
207
- const requestInfo = {
208
- method: 'POST',
209
- url,
210
- body: messageBody,
211
- };
212
- const requestOptions = { headers: 'json' };
213
- return this.request(requestInfo, requestOptions);
214
- }
215
- else {
216
- // the _invoke is private in jsforce, we can call the SOAP deployRecentValidation like this
217
- // @ts-ignore
218
- return this.metadata['_invoke']('deployRecentValidation', {
219
- validationId: options.id,
220
- });
221
- }
222
- }
223
163
  /**
224
164
  * Retrieves the highest api version that is supported by the target server instance.
225
165
  */
226
166
  async retrieveMaxApiVersion() {
167
+ // Check saved value first, then cache.
168
+ if ((this.maxApiVersion ??= this.getCachedApiVersion())) {
169
+ return this.maxApiVersion;
170
+ }
227
171
  await this.isResolvable();
172
+ this.logger.debug(`Fetching API versions supported for org: ${this.getUsername()}`);
228
173
  const versions = await this.request(`${this.instanceUrl}/services/data`);
174
+ // if the server doesn't return a list of versions, it's possibly a instanceUrl issue where the local file is out of date.
175
+ if (!Array.isArray(versions)) {
176
+ this.logger.debug(`server response for retrieveMaxApiVersion: ${versions}`);
177
+ throw messages.createError('noApiVersionsError');
178
+ }
229
179
  this.logger.debug(`response for org versions: ${versions.map((item) => item.version).join(',')}`);
230
- const max = (0, ts_types_1.ensure)((0, kit_1.maxBy)(versions, (version) => version.version));
231
- return max.version;
180
+ this.maxApiVersion = (0, ts_types_1.ensure)((0, kit_1.maxBy)(versions, (version) => version.version)).version;
181
+ // cache the max API version just fetched
182
+ await this.options.authInfo.save({
183
+ instanceApiVersion: this.maxApiVersion,
184
+ // This will get messed up if the user changes their local time on their machine.
185
+ // Not a big deal since it will just get updated sooner/later.
186
+ instanceApiVersionLastRetrieved: new Date().toLocaleString(),
187
+ });
188
+ return this.maxApiVersion;
232
189
  }
233
190
  /**
234
191
  * Use the latest API version available on `this.instanceUrl`.
@@ -250,8 +207,10 @@ class Connection extends jsforce_1.Connection {
250
207
  * Verify that instance has a reachable DNS entry, otherwise will throw error
251
208
  */
252
209
  async isResolvable() {
253
- var _a;
254
- if (!((_a = this.options.connectionOptions) === null || _a === void 0 ? void 0 : _a.instanceUrl)) {
210
+ if (this.hasResolved) {
211
+ return this.hasResolved;
212
+ }
213
+ if (!this.options.connectionOptions?.instanceUrl) {
255
214
  throw messages.createError('noInstanceUrlError');
256
215
  }
257
216
  const resolver = await myDomainResolver_1.MyDomainResolver.create({
@@ -259,6 +218,7 @@ class Connection extends jsforce_1.Connection {
259
218
  });
260
219
  try {
261
220
  await resolver.resolve();
221
+ this.hasResolved = true;
262
222
  return true;
263
223
  }
264
224
  catch (e) {
@@ -274,12 +234,12 @@ class Connection extends jsforce_1.Connection {
274
234
  /**
275
235
  * Set the API version for all connection requests.
276
236
  *
277
- * **Throws** *{@link SfdxError}{ name: 'IncorrectAPIVersionError' }* Incorrect API version.
237
+ * **Throws** *{@link SfError}{ name: 'IncorrectAPIVersionError' }* Incorrect API version.
278
238
  *
279
239
  * @param version The API version.
280
240
  */
281
241
  setApiVersion(version) {
282
- if (!sfdc_1.sfdc.validateApiVersion(version)) {
242
+ if (!(0, sfdc_1.validateApiVersion)(version)) {
283
243
  throw messages.createError('incorrectAPIVersionError', [version]);
284
244
  }
285
245
  this.version = version;
@@ -294,7 +254,7 @@ class Connection extends jsforce_1.Connection {
294
254
  * Getter for the AuthInfo fields.
295
255
  */
296
256
  getAuthInfoFields() {
297
- // If the GlobalInfo.unsetOrg is called, the AuthFields are no longer accessible.
257
+ // If the StateAggregator.orgs.remove is called, the AuthFields are no longer accessible.
298
258
  return this.options.authInfo.getFields() || {};
299
259
  }
300
260
  /**
@@ -321,6 +281,7 @@ class Connection extends jsforce_1.Connection {
321
281
  * @param url Partial url.
322
282
  */
323
283
  normalizeUrl(url) {
284
+ // eslint-disable-next-line no-underscore-dangle
324
285
  return this._normalizeUrl(url);
325
286
  }
326
287
  /**
@@ -331,15 +292,16 @@ class Connection extends jsforce_1.Connection {
331
292
  * @param soql The SOQL string.
332
293
  * @param queryOptions The query options. NOTE: the autoFetch option will always be true.
333
294
  */
334
- async autoFetchQuery(soql, queryOptions = {}) {
295
+ async autoFetchQuery(soql, queryOptions = { tooling: false }) {
335
296
  const config = await configAggregator_1.ConfigAggregator.create();
336
297
  // take the limit from the calling function, then the config, then default 10,000
337
- const maxFetch = config.getInfo('maxQueryLimit').value || queryOptions.maxFetch || 10000;
338
- const options = Object.assign(queryOptions, {
298
+ const maxFetch = (config.getInfo(orgConfigProperties_1.OrgConfigProperties.ORG_MAX_QUERY_LIMIT).value || queryOptions.maxFetch) ?? 10000;
299
+ const { tooling, ...queryOptionsWithoutTooling } = queryOptions;
300
+ const options = Object.assign(queryOptionsWithoutTooling, {
339
301
  autoFetch: true,
340
302
  maxFetch,
341
303
  });
342
- const query = await this.query(soql, options);
304
+ const query = tooling ? await this.tooling.query(soql, options) : await this.query(soql, options);
343
305
  if (query.records.length && query.totalSize > query.records.length) {
344
306
  void lifecycleEvents_1.Lifecycle.getInstance().emitWarning(`The query result is missing ${query.totalSize - query.records.length} records due to a ${maxFetch} record limit. Increase the number of records returned by setting the config value "maxQueryLimit" or the environment variable "SFDX_MAX_QUERY_LIMIT" to ${query.totalSize} or greater than ${maxFetch}.`);
345
307
  }
@@ -357,11 +319,12 @@ class Connection extends jsforce_1.Connection {
357
319
  }) {
358
320
  const result = options.tooling ? await this.tooling.query(soql) : await this.query(soql);
359
321
  if (result.totalSize === 0) {
360
- throw new sfdxError_1.SfdxError(`No record found for ${soql}`, exports.SingleRecordQueryErrors.NoRecords);
322
+ throw new sfError_1.SfError(`No record found for ${soql}`, exports.SingleRecordQueryErrors.NoRecords);
361
323
  }
362
324
  if (result.totalSize > 1) {
363
- throw new sfdxError_1.SfdxError(options.returnChoicesOnMultiple
364
- ? `Multiple records found. ${result.records.map((item) => item[options.choiceField]).join(',')}`
325
+ throw new sfError_1.SfError(options.returnChoicesOnMultiple
326
+ ? // eslint-disable-next-line @typescript-eslint/no-unsafe-return
327
+ `Multiple records found. ${result.records.map((item) => item[options.choiceField]).join(',')}`
365
328
  : 'The query returned more than 1 record', exports.SingleRecordQueryErrors.MultipleRecords);
366
329
  }
367
330
  return result.records[0];
@@ -378,10 +341,16 @@ class Connection extends jsforce_1.Connection {
378
341
  };
379
342
  await this.request(requestInfo);
380
343
  }
381
- async loadInstanceApiVersion() {
344
+ getCachedApiVersion() {
345
+ // Exit early if the API version cache is disabled.
346
+ if (kit_1.env.getBoolean('SFDX_IGNORE_API_VERSION_CACHE', false)) {
347
+ this.logger.debug('Using latest API version since SFDX_IGNORE_API_VERSION_CACHE = true');
348
+ return;
349
+ }
350
+ // Get API version cache data
382
351
  const authFileFields = this.options.authInfo.getFields();
383
352
  const lastCheckedDateString = authFileFields.instanceApiVersionLastRetrieved;
384
- let version = (0, ts_types_1.getString)(authFileFields, 'instanceApiVersion');
353
+ const version = authFileFields.instanceApiVersion;
385
354
  let lastChecked;
386
355
  try {
387
356
  if (lastCheckedDateString && (0, ts_types_1.isString)(lastCheckedDateString)) {
@@ -391,35 +360,20 @@ class Connection extends jsforce_1.Connection {
391
360
  catch (e) {
392
361
  /* Do nothing, it will just request the version again */
393
362
  }
394
- // Grab the latest api version from the server and cache it in the auth file
395
- const useLatest = async () => {
396
- // verifies DNS
397
- await this.useLatestApiVersion();
398
- version = this.getApiVersion();
399
- await this.options.authInfo.save({
400
- instanceApiVersion: version,
401
- // This will get messed up if the user changes their local time on their machine.
402
- // Not a big deal since it will just get updated sooner/later.
403
- instanceApiVersionLastRetrieved: new Date().toLocaleString(),
404
- });
405
- };
406
- const ignoreCache = kit_1.env.getBoolean('SFDX_IGNORE_API_VERSION_CACHE', false);
407
- if (lastChecked && !ignoreCache) {
363
+ // Check if the cache has expired
364
+ if (lastChecked) {
408
365
  const now = new Date();
409
366
  const has24HoursPastSinceLastCheck = now.getTime() - lastChecked > kit_1.Duration.hours(24).milliseconds;
410
- this.logger.debug(`Last checked on ${lastCheckedDateString} (now is ${now.toLocaleString()}) - ${has24HoursPastSinceLastCheck ? '' : 'not '}getting latest`);
411
- if (has24HoursPastSinceLastCheck) {
412
- await useLatest();
367
+ this.logger.debug(`API version cache last checked on ${lastCheckedDateString} (now is ${now.toLocaleString()})`);
368
+ if (!has24HoursPastSinceLastCheck && version) {
369
+ // return cached API version
370
+ this.logger.debug(`Using cached API version: ${version}`);
371
+ return version;
372
+ }
373
+ else {
374
+ this.logger.debug('API version cache expired. Re-fetching latest.');
413
375
  }
414
376
  }
415
- else {
416
- this.logger.debug(`Using the latest because lastChecked=${lastChecked} and SFDX_IGNORE_API_VERSION_CACHE=${ignoreCache}`);
417
- // No version found in the file (we never checked before)
418
- // so get the latest.
419
- await useLatest();
420
- }
421
- this.logger.debug(`Loaded latest apiVersion ${version}`);
422
- return version;
423
377
  }
424
378
  }
425
379
  exports.Connection = Connection;
package/lib/org/index.js CHANGED
@@ -7,7 +7,11 @@
7
7
  */
8
8
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
9
  if (k2 === undefined) k2 = k;
10
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
11
15
  }) : (function(o, m, k, k2) {
12
16
  if (k2 === undefined) k2 = k;
13
17
  o[k2] = m[k];