@salesforce/core 3.7.0 → 3.7.4

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 (51) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/LICENSE.txt +1 -1
  3. package/lib/config/config.js +15 -15
  4. package/lib/config/configAggregator.js +4 -4
  5. package/lib/config/configFile.js +9 -9
  6. package/lib/config/configStore.js +12 -13
  7. package/lib/config/envVars.js +5 -5
  8. package/lib/config/keychainConfig.js +1 -1
  9. package/lib/crypto/crypto.js +6 -6
  10. package/lib/crypto/keyChainImpl.js +6 -5
  11. package/lib/crypto/secureBuffer.js +1 -1
  12. package/lib/deviceOauthService.js +5 -4
  13. package/lib/exported.d.ts +1 -1
  14. package/lib/exported.js +4 -2
  15. package/lib/globalInfo/globalInfoConfig.js +1 -1
  16. package/lib/globalInfo/sfdxDataHandler.js +11 -11
  17. package/lib/lifecycleEvents.d.ts +38 -1
  18. package/lib/lifecycleEvents.js +73 -2
  19. package/lib/logger.js +13 -12
  20. package/lib/messages.js +10 -9
  21. package/lib/org/authInfo.d.ts +2 -6
  22. package/lib/org/authInfo.js +44 -41
  23. package/lib/org/connection.js +14 -11
  24. package/lib/org/org.d.ts +121 -9
  25. package/lib/org/org.js +373 -36
  26. package/lib/org/orgConfigProperties.js +1 -1
  27. package/lib/org/permissionSetAssignment.js +3 -3
  28. package/lib/org/user.js +20 -20
  29. package/lib/schema/printer.js +18 -18
  30. package/lib/schema/validator.js +8 -8
  31. package/lib/sfdxError.d.ts +1 -1
  32. package/lib/sfdxError.js +3 -2
  33. package/lib/sfdxProject.js +15 -13
  34. package/lib/status/myDomainResolver.js +3 -3
  35. package/lib/status/pollingClient.js +2 -2
  36. package/lib/status/streamingClient.d.ts +2 -3
  37. package/lib/status/streamingClient.js +16 -22
  38. package/lib/status/types.d.ts +89 -0
  39. package/lib/status/types.js +18 -0
  40. package/lib/testSetup.d.ts +6 -4
  41. package/lib/testSetup.js +25 -25
  42. package/lib/util/cache.js +3 -3
  43. package/lib/util/fs.js +12 -12
  44. package/lib/util/sfdc.js +3 -3
  45. package/lib/util/sfdcUrl.d.ts +2 -1
  46. package/lib/util/sfdcUrl.js +16 -8
  47. package/lib/webOAuthServer.js +7 -7
  48. package/messages/core.json +3 -3
  49. package/messages/core.md +1 -1
  50. package/messages/org.md +36 -0
  51. package/package.json +38 -45
@@ -149,7 +149,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
149
149
  const orgs = Object.values(globalInfo.orgs.getAll());
150
150
  const final = [];
151
151
  for (const org of orgs) {
152
- const username = ts_types_1.ensureString(org.username);
152
+ const username = (0, ts_types_1.ensureString)(org.username);
153
153
  const aliases = (_a = globalInfo.aliases.getAll(username)) !== null && _a !== void 0 ? _a : undefined;
154
154
  // Get a list of configuration values that are set to either the username or one
155
155
  // of the aliases
@@ -170,7 +170,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
170
170
  accessToken: authInfo.getConnectionOptions().accessToken,
171
171
  oauthMethod: authInfo.isJwt() ? 'jwt' : authInfo.isOauth() ? 'web' : 'token',
172
172
  isExpired: Boolean(devHubUsername) && expirationDate
173
- ? new Date(ts_types_1.ensureString(expirationDate)).getTime() < new Date().getTime()
173
+ ? new Date((0, ts_types_1.ensureString)(expirationDate)).getTime() < new Date().getTime()
174
174
  : 'unknown',
175
175
  });
176
176
  }
@@ -196,13 +196,14 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
196
196
  static async hasAuthentications() {
197
197
  try {
198
198
  const auths = (await globalInfo_1.GlobalInfo.getInstance()).orgs.getAll();
199
- return !kit_1.isEmpty(auths);
199
+ return !(0, kit_1.isEmpty)(auths);
200
200
  }
201
201
  catch (err) {
202
- if (err.name === 'OrgDataNotAvailableError' || err.code === 'ENOENT') {
202
+ const error = err;
203
+ if (error.name === 'OrgDataNotAvailableError' || error.code === 'ENOENT') {
203
204
  return false;
204
205
  }
205
- throw err;
206
+ throw error;
206
207
  }
207
208
  }
208
209
  /**
@@ -217,7 +218,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
217
218
  // The state parameter allows the redirectUri callback listener to ignore request
218
219
  // that don't contain the state value.
219
220
  const params = {
220
- state: crypto_1.randomBytes(Math.ceil(6)).toString('hex'),
221
+ state: (0, crypto_1.randomBytes)(Math.ceil(6)).toString('hex'),
221
222
  prompt: 'login',
222
223
  // Default connected app is 'refresh_token api web'
223
224
  scope: options.scope || kit_1.env.getString('SFDX_AUTH_SCOPES', 'refresh_token api web'),
@@ -236,7 +237,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
236
237
  static parseSfdxAuthUrl(sfdxAuthUrl) {
237
238
  const match = sfdxAuthUrl.match(/^force:\/\/([a-zA-Z0-9._-]+):([a-zA-Z0-9._-]*):([a-zA-Z0-9._-]+={0,2})@([a-zA-Z0-9._-]+)/);
238
239
  if (!match) {
239
- throw new sfdxError_1.SfdxError('Invalid sfdx auth url. Must be in the format `force://<clientId>:<clientSecret>:<refreshToken>@<loginUrl>`. The instanceUrl must not have the protocol set.', 'INVALID_SFDX_AUTH_URL');
240
+ throw new sfdxError_1.SfdxError('Invalid SFDX auth URL. Must be in the format "force://<clientId>:<clientSecret>:<refreshToken>@<instanceUrl>". Note that the SFDX auth URL uses the "force" protocol, and not "http" or "https". Also note that the "instanceUrl" inside the SFDX auth URL doesn\'t include the protocol ("https://").', 'INVALID_SFDX_AUTH_URL');
240
241
  }
241
242
  const [, clientId, clientSecret, refreshToken, loginUrl] = match;
242
243
  return {
@@ -286,7 +287,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
286
287
  */
287
288
  async save(authData) {
288
289
  this.update(authData);
289
- const username = ts_types_1.ensure(this.getUsername());
290
+ const username = (0, ts_types_1.ensure)(this.getUsername());
290
291
  if (sfdc_1.sfdc.matchesAccessToken(username)) {
291
292
  this.logger.debug('Username is an accesstoken. Skip saving authinfo to disk.');
292
293
  return this;
@@ -303,7 +304,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
303
304
  */
304
305
  update(authData) {
305
306
  // todo move into configstore
306
- if (authData && ts_types_1.isPlainObject(authData)) {
307
+ if (authData && (0, ts_types_1.isPlainObject)(authData)) {
307
308
  this.username = authData.username || this.username;
308
309
  const existingFields = this.globalInfo.orgs.get(this.getUsername());
309
310
  const mergedFields = Object.assign({}, existingFields || {}, authData);
@@ -373,8 +374,8 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
373
374
  */
374
375
  getOrgFrontDoorUrl() {
375
376
  const authFields = this.getFields(true);
376
- const base = ts_types_1.ensureString(authFields.instanceUrl).replace(/\/+$/, '');
377
- const accessToken = ts_types_1.ensureString(authFields.accessToken);
377
+ const base = (0, ts_types_1.ensureString)(authFields.instanceUrl).replace(/\/+$/, '');
378
+ const accessToken = (0, ts_types_1.ensureString)(authFields.accessToken);
378
379
  return `${base}/secur/frontdoor.jsp?sid=${accessToken}`;
379
380
  }
380
381
  /**
@@ -390,12 +391,12 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
390
391
  */
391
392
  getSfdxAuthUrl() {
392
393
  const decryptedFields = this.getFields(true);
393
- const instanceUrl = ts_types_1.ensure(decryptedFields.instanceUrl, 'undefined instanceUrl').replace(/^https?:\/\//, '');
394
+ const instanceUrl = (0, ts_types_1.ensure)(decryptedFields.instanceUrl, 'undefined instanceUrl').replace(/^https?:\/\//, '');
394
395
  let sfdxAuthUrl = 'force://';
395
396
  if (decryptedFields.clientId) {
396
397
  sfdxAuthUrl += `${decryptedFields.clientId}:${decryptedFields.clientSecret || ''}:`;
397
398
  }
398
- sfdxAuthUrl += `${ts_types_1.ensure(decryptedFields.refreshToken, 'undefined refreshToken')}@${instanceUrl}`;
399
+ sfdxAuthUrl += `${(0, ts_types_1.ensure)(decryptedFields.refreshToken, 'undefined refreshToken')}@${instanceUrl}`;
399
400
  return sfdxAuthUrl;
400
401
  }
401
402
  /**
@@ -414,7 +415,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
414
415
  catch {
415
416
  config = await config_1.Config.create({ isGlobal: true });
416
417
  }
417
- const username = ts_types_1.ensureString(this.getUsername());
418
+ const username = (0, ts_types_1.ensureString)(this.getUsername());
418
419
  const alias = this.globalInfo.aliases.get(username);
419
420
  const value = alias !== null && alias !== void 0 ? alias : username;
420
421
  if (options.org) {
@@ -453,12 +454,12 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
453
454
  throw messages.createError('authInfoOverwriteError');
454
455
  }
455
456
  }
456
- const oauthUsername = username || ts_types_1.getString(authOptions, 'username');
457
+ const oauthUsername = username || (0, ts_types_1.getString)(authOptions, 'username');
457
458
  if (oauthUsername) {
458
459
  this.username = oauthUsername;
459
460
  } // Else it will be set in initAuthOptions below.
460
461
  // If the username is an access token, use that for auth and don't persist
461
- if (ts_types_1.isString(oauthUsername) && sfdc_1.sfdc.matchesAccessToken(oauthUsername)) {
462
+ if ((0, ts_types_1.isString)(oauthUsername) && sfdc_1.sfdc.matchesAccessToken(oauthUsername)) {
462
463
  // Need to initAuthOptions the logger and authInfoCrypto since we don't call init()
463
464
  this.logger = await logger_1.Logger.child('AuthInfo');
464
465
  const aggregator = await configAggregator_1.ConfigAggregator.create();
@@ -480,7 +481,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
480
481
  }
481
482
  }
482
483
  getInstanceUrl(options, aggregator) {
483
- const instanceUrl = ts_types_1.getString(options, 'instanceUrl') || aggregator.getPropertyValue('instanceUrl');
484
+ const instanceUrl = (0, ts_types_1.getString)(options, 'instanceUrl') || aggregator.getPropertyValue('instanceUrl');
484
485
  return instanceUrl || sfdcUrl_1.SfdcUrl.PRODUCTION;
485
486
  }
486
487
  /**
@@ -497,10 +498,10 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
497
498
  // If options were passed, use those before checking cache and reading an auth file.
498
499
  let authConfig;
499
500
  if (options) {
500
- options = kit_1.cloneJson(options);
501
+ options = (0, kit_1.cloneJson)(options);
501
502
  if (this.isTokenOptions(options)) {
502
503
  authConfig = options;
503
- const userInfo = await this.retrieveUserInfo(ts_types_1.ensureString(options.instanceUrl), ts_types_1.ensureString(options.accessToken));
504
+ const userInfo = await this.retrieveUserInfo((0, ts_types_1.ensureString)(options.instanceUrl), (0, ts_types_1.ensureString)(options.accessToken));
504
505
  this.update({ username: userInfo === null || userInfo === void 0 ? void 0 : userInfo.username, orgId: userInfo === null || userInfo === void 0 ? void 0 : userInfo.organizationId });
505
506
  }
506
507
  else {
@@ -514,14 +515,14 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
514
515
  // Grab whatever flow is defined
515
516
  Object.assign(options, {
516
517
  clientSecret: parentFields.clientSecret,
517
- privateKey: parentFields.privateKey ? path_1.resolve(parentFields.privateKey) : parentFields.privateKey,
518
+ privateKey: parentFields.privateKey ? (0, path_1.resolve)(parentFields.privateKey) : parentFields.privateKey,
518
519
  });
519
520
  }
520
521
  }
521
522
  // jwt flow
522
523
  // Support both sfdx and jsforce private key values
523
524
  if (!options.privateKey && options.privateKeyFile) {
524
- options.privateKey = path_1.resolve(options.privateKeyFile);
525
+ options.privateKey = (0, path_1.resolve)(options.privateKeyFile);
525
526
  }
526
527
  if (options.privateKey) {
527
528
  authConfig = await this.buildJwtConfig(options);
@@ -565,6 +566,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
565
566
  // A callback function for a connection to refresh an access token. This is used
566
567
  // both for a JWT connection and an OAuth connection.
567
568
  async refreshFn(conn, callback) {
569
+ var _a;
568
570
  this.logger.info('Access token has expired. Updating...');
569
571
  try {
570
572
  const fields = this.getFields(true);
@@ -573,19 +575,20 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
573
575
  return await callback(null, fields.accessToken);
574
576
  }
575
577
  catch (err) {
576
- if (err.message && err.message.includes('Data Not Available')) {
578
+ const error = err;
579
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes('Data Not Available')) {
577
580
  // Set cause to keep original stacktrace
578
- return await callback(messages.createError('orgDataNotAvailableError', [this.getUsername()], [], err));
581
+ return await callback(messages.createError('orgDataNotAvailableError', [this.getUsername()], [], error));
579
582
  }
580
- return await callback(err);
583
+ return await callback(error);
581
584
  }
582
585
  }
583
586
  // Build OAuth config for a JWT auth flow
584
587
  async buildJwtConfig(options) {
585
- const privateKeyContents = await fs_1.fs.readFile(ts_types_1.ensure(options.privateKey), 'utf8');
588
+ const privateKeyContents = await fs_1.fs.readFile((0, ts_types_1.ensure)(options.privateKey), 'utf8');
586
589
  const { loginUrl = sfdcUrl_1.SfdcUrl.PRODUCTION } = options;
587
590
  const url = new sfdcUrl_1.SfdcUrl(loginUrl);
588
- const createdOrgInstance = ts_types_1.getString(options, 'createdOrgInstance', '').trim().toLowerCase();
591
+ const createdOrgInstance = (0, ts_types_1.getString)(options, 'createdOrgInstance', '').trim().toLowerCase();
589
592
  const audienceUrl = await url.getJwtAudienceUrl(createdOrgInstance);
590
593
  const jwtToken = jwt.sign({
591
594
  iss: options.clientId,
@@ -598,19 +601,19 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
598
601
  const oauth2 = new JwtOAuth2({ loginUrl: options.loginUrl });
599
602
  let authFieldsBuilder;
600
603
  try {
601
- authFieldsBuilder = ts_types_1.ensureJsonMap(await oauth2.jwtAuthorize(jwtToken));
604
+ authFieldsBuilder = (0, ts_types_1.ensureJsonMap)(await oauth2.jwtAuthorize(jwtToken));
602
605
  }
603
606
  catch (err) {
604
607
  throw messages.createError('jwtAuthError', [err.message]);
605
608
  }
606
609
  const authFields = {
607
- accessToken: ts_types_1.asString(authFieldsBuilder.access_token),
608
- orgId: parseIdUrl(ts_types_1.ensureString(authFieldsBuilder.id)).orgId,
610
+ accessToken: (0, ts_types_1.asString)(authFieldsBuilder.access_token),
611
+ orgId: parseIdUrl((0, ts_types_1.ensureString)(authFieldsBuilder.id)).orgId,
609
612
  loginUrl: options.loginUrl,
610
613
  privateKey: options.privateKey,
611
614
  clientId: options.clientId,
612
615
  };
613
- const instanceUrl = ts_types_1.ensureString(authFieldsBuilder.instance_url);
616
+ const instanceUrl = (0, ts_types_1.ensureString)(authFieldsBuilder.instance_url);
614
617
  const sfdcUrl = new sfdcUrl_1.SfdcUrl(instanceUrl);
615
618
  try {
616
619
  // Check if the url is resolvable. This can fail when my-domains have not been replicated.
@@ -637,7 +640,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
637
640
  const oauth2 = new jsforce_1.OAuth2(options);
638
641
  let authFieldsBuilder;
639
642
  try {
640
- authFieldsBuilder = await oauth2.refreshToken(ts_types_1.ensure(options.refreshToken));
643
+ authFieldsBuilder = await oauth2.refreshToken((0, ts_types_1.ensure)(options.refreshToken));
641
644
  }
642
645
  catch (err) {
643
646
  throw messages.createError('refreshTokenAuthError', [err.message]);
@@ -648,7 +651,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
648
651
  if (!username) {
649
652
  // @ts-ignore
650
653
  const userInfo = await this.retrieveUserInfo(authFieldsBuilder.instance_url, authFieldsBuilder.access_token);
651
- username = ts_types_1.ensureString(userInfo === null || userInfo === void 0 ? void 0 : userInfo.username);
654
+ username = (0, ts_types_1.ensureString)(userInfo === null || userInfo === void 0 ? void 0 : userInfo.username);
652
655
  }
653
656
  return {
654
657
  orgId,
@@ -680,7 +683,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
680
683
  let authFields;
681
684
  try {
682
685
  this.logger.info(`Exchanging auth code for access token using loginUrl: ${options.loginUrl}`);
683
- authFields = await oauth2.requestToken(ts_types_1.ensure(options.authCode));
686
+ authFields = await oauth2.requestToken((0, ts_types_1.ensure)(options.authCode));
684
687
  }
685
688
  catch (err) {
686
689
  throw messages.createError('authCodeExchangeError', [err.message]);
@@ -713,7 +716,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
713
716
  // but we don't want to create circular dependencies or lots of snowflakes
714
717
  // within this file to support it.
715
718
  const apiVersion = 'v51.0'; // hardcoding to v51.0 just for this call is okay.
716
- const instance = ts_types_1.ensure(instanceUrl);
719
+ const instance = (0, ts_types_1.ensure)(instanceUrl);
717
720
  const baseUrl = new sfdcUrl_1.SfdcUrl(instance);
718
721
  const userInfoUrl = `${baseUrl}services/oauth2/userinfo`;
719
722
  const headers = Object.assign({ Authorization: `Bearer ${accessToken}` }, connection_1.SFDX_HTTP_HEADERS);
@@ -724,7 +727,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
724
727
  this.throwUserGetException(response);
725
728
  }
726
729
  else {
727
- const userInfoJson = kit_1.parseJsonMap(response.body);
730
+ const userInfoJson = (0, kit_1.parseJsonMap)(response.body);
728
731
  const url = `${baseUrl}/services/data/${apiVersion}/sobjects/User/${userInfoJson.user_id}`;
729
732
  this.logger.info(`Sending request for User SObject after successful auth code exchange to URL: ${url}`);
730
733
  response = await new transport_1.default().httpRequest({ url, method: 'GET', headers });
@@ -733,7 +736,7 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
733
736
  }
734
737
  else {
735
738
  // eslint-disable-next-line camelcase
736
- userInfoJson.preferred_username = kit_1.parseJsonMap(response.body).Username;
739
+ userInfoJson.preferred_username = (0, kit_1.parseJsonMap)(response.body).Username;
737
740
  }
738
741
  return { username: userInfoJson.preferred_username, organizationId: userInfoJson.organization_id };
739
742
  }
@@ -751,16 +754,16 @@ class AuthInfo extends kit_1.AsyncOptionalCreatable {
751
754
  throwUserGetException(response) {
752
755
  var _a;
753
756
  let errorMsg = '';
754
- const bodyAsString = ts_types_1.getString(response, 'body', JSON.stringify({ message: 'UNKNOWN', errorCode: 'UNKNOWN' }));
757
+ const bodyAsString = (0, ts_types_1.getString)(response, 'body', JSON.stringify({ message: 'UNKNOWN', errorCode: 'UNKNOWN' }));
755
758
  try {
756
- const body = kit_1.parseJson(bodyAsString);
757
- if (ts_types_1.isArray(body)) {
759
+ const body = (0, kit_1.parseJson)(bodyAsString);
760
+ if ((0, ts_types_1.isArray)(body)) {
758
761
  errorMsg = body
759
- .map((line) => { var _a; return (_a = ts_types_1.getString(line, 'message')) !== null && _a !== void 0 ? _a : ts_types_1.getString(line, 'errorCode', 'UNKNOWN'); })
762
+ .map((line) => { var _a; return (_a = (0, ts_types_1.getString)(line, 'message')) !== null && _a !== void 0 ? _a : (0, ts_types_1.getString)(line, 'errorCode', 'UNKNOWN'); })
760
763
  .join(os.EOL);
761
764
  }
762
765
  else {
763
- errorMsg = (_a = ts_types_1.getString(body, 'message')) !== null && _a !== void 0 ? _a : ts_types_1.getString(body, 'errorCode', 'UNKNOWN');
766
+ errorMsg = (_a = (0, ts_types_1.getString)(body, 'message')) !== null && _a !== void 0 ? _a : (0, ts_types_1.getString)(body, 'errorCode', 'UNKNOWN');
764
767
  }
765
768
  }
766
769
  catch (err) {
@@ -20,6 +20,7 @@ const logger_1 = require("../logger");
20
20
  const sfdxError_1 = require("../sfdxError");
21
21
  const sfdc_1 = require("../util/sfdc");
22
22
  const messages_1 = require("../messages");
23
+ const lifecycleEvents_1 = require("../lifecycleEvents");
23
24
  messages_1.Messages.importMessagesDirectory(__dirname);
24
25
  const messages = messages_1.Messages.load('@salesforce/core', 'connection', [
25
26
  'incorrectAPIVersionError',
@@ -85,7 +86,7 @@ class Connection extends jsforce_1.Connection {
85
86
  if (!baseOptions.version) {
86
87
  // Set the API version obtained from the config aggregator.
87
88
  const configAggregator = options.configAggregator || (await configAggregator_1.ConfigAggregator.create());
88
- baseOptions.version = ts_types_1.asString(configAggregator.getInfo('apiVersion').value);
89
+ baseOptions.version = (0, ts_types_1.asString)(configAggregator.getInfo('apiVersion').value);
89
90
  }
90
91
  const providedOptions = options.authInfo.getConnectionOptions();
91
92
  // Get connection options from auth info and create a new jsForce connection
@@ -104,7 +105,8 @@ class Connection extends jsforce_1.Connection {
104
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'}`);
105
106
  }
106
107
  }
107
- catch (e) {
108
+ catch (err) {
109
+ const e = err;
108
110
  if (e.name === exports.DNS_ERROR_NAME) {
109
111
  throw e;
110
112
  }
@@ -171,7 +173,7 @@ class Connection extends jsforce_1.Connection {
171
173
  * @param options HTTP API request options.
172
174
  */
173
175
  request(request, options) {
174
- const httpRequest = ts_types_1.isString(request) ? { method: 'GET', url: request } : request;
176
+ const httpRequest = (0, ts_types_1.isString)(request) ? { method: 'GET', url: request } : request;
175
177
  httpRequest.headers = Object.assign({}, exports.SFDX_HTTP_HEADERS, httpRequest.headers);
176
178
  this.logger.debug(`request: ${JSON.stringify(httpRequest)}`);
177
179
  // The "as" is a workaround for the jsforce typings.
@@ -224,7 +226,7 @@ class Connection extends jsforce_1.Connection {
224
226
  await this.isResolvable();
225
227
  const versions = await this.request(`${this.instanceUrl}/services/data`);
226
228
  this.logger.debug(`response for org versions: ${versions.map((item) => item.version).join(',')}`);
227
- const max = ts_types_1.ensure(kit_1.maxBy(versions, (version) => version.version));
229
+ const max = (0, ts_types_1.ensure)((0, kit_1.maxBy)(versions, (version) => version.version));
228
230
  return max.version;
229
231
  }
230
232
  /**
@@ -235,11 +237,12 @@ class Connection extends jsforce_1.Connection {
235
237
  this.setApiVersion(await this.retrieveMaxApiVersion());
236
238
  }
237
239
  catch (err) {
238
- if (err.name === exports.DNS_ERROR_NAME) {
239
- throw err; // throws on DNS connection errors
240
+ const error = err;
241
+ if (error.name === exports.DNS_ERROR_NAME) {
242
+ throw error; // throws on DNS connection errors
240
243
  }
241
244
  // Don't fail if we can't use the latest, just use the default
242
- this.logger.warn('Failed to set the latest API version:', err);
245
+ this.logger.warn('Failed to set the latest API version:', error);
243
246
  }
244
247
  }
245
248
  /**
@@ -336,8 +339,8 @@ class Connection extends jsforce_1.Connection {
336
339
  maxFetch,
337
340
  });
338
341
  const query = await this.query(soql, options);
339
- if (query.totalSize > query.records.length) {
340
- process.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}.`);
342
+ if (query.records.length && query.totalSize > query.records.length) {
343
+ 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}.`);
341
344
  }
342
345
  return query;
343
346
  }
@@ -365,10 +368,10 @@ class Connection extends jsforce_1.Connection {
365
368
  async loadInstanceApiVersion() {
366
369
  const authFileFields = this.options.authInfo.getFields();
367
370
  const lastCheckedDateString = authFileFields.instanceApiVersionLastRetrieved;
368
- let version = ts_types_1.getString(authFileFields, 'instanceApiVersion');
371
+ let version = (0, ts_types_1.getString)(authFileFields, 'instanceApiVersion');
369
372
  let lastChecked;
370
373
  try {
371
- if (lastCheckedDateString && ts_types_1.isString(lastCheckedDateString)) {
374
+ if (lastCheckedDateString && (0, ts_types_1.isString)(lastCheckedDateString)) {
372
375
  lastChecked = Date.parse(lastCheckedDateString);
373
376
  }
374
377
  }
package/lib/org/org.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AsyncOptionalCreatable } from '@salesforce/kit';
1
+ import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
2
2
  import { AnyJson, JsonMap, Optional } from '@salesforce/ts-types';
3
3
  import { ConfigAggregator } from '../config/configAggregator';
4
4
  import { OrgUsersConfig } from '../config/orgUsersConfig';
@@ -12,6 +12,57 @@ export declare type OrganizationInformation = {
12
12
  TrialExpirationDate: string | null;
13
13
  NamespacePrefix: string | null;
14
14
  };
15
+ export declare enum OrgTypes {
16
+ Scratch = "scratch",
17
+ Sandbox = "sandbox"
18
+ }
19
+ export interface StatusEvent {
20
+ sandboxProcessObj: SandboxProcessObject;
21
+ interval: number;
22
+ retries: number;
23
+ waitingOnAuth: boolean;
24
+ }
25
+ export interface ResultEvent {
26
+ sandboxProcessObj: SandboxProcessObject;
27
+ sandboxRes: SandboxUserAuthResponse;
28
+ }
29
+ export interface SandboxUserAuthRequest {
30
+ sandboxName: string;
31
+ clientId: string;
32
+ callbackUrl: string;
33
+ }
34
+ export declare enum SandboxEvents {
35
+ EVENT_STATUS = "status",
36
+ EVENT_ASYNC_RESULT = "asyncResult",
37
+ EVENT_RESULT = "result",
38
+ EVENT_AUTH = "auth"
39
+ }
40
+ export interface SandboxUserAuthResponse {
41
+ authUserName: string;
42
+ authCode: string;
43
+ instanceUrl: string;
44
+ loginUrl: string;
45
+ }
46
+ export interface SandboxProcessObject {
47
+ Id: string;
48
+ Status: string;
49
+ SandboxName: string;
50
+ SandboxInfoId: string;
51
+ LicenseType: string;
52
+ CreatedDate: string;
53
+ SandboxOrganization?: string;
54
+ CopyProgress?: number;
55
+ SourceId?: string;
56
+ Description?: string;
57
+ ApexClassId?: string;
58
+ EndDate?: string;
59
+ }
60
+ export declare type SandboxRequest = {
61
+ SandboxName: string;
62
+ LicenseType?: string;
63
+ SourceId?: string;
64
+ Description?: string;
65
+ };
15
66
  /**
16
67
  * Provides a way to manage a locally authenticated Org.
17
68
  *
@@ -49,6 +100,17 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
49
100
  * @ignore
50
101
  */
51
102
  constructor(options?: Org.Options);
103
+ /**
104
+ * create a sandbox from a production org
105
+ * 'this' needs to be a production org with sandbox licenses available
106
+ *
107
+ * @param sandboxReq SandboxRequest options to create the sandbox with
108
+ * @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
109
+ */
110
+ createSandbox(sandboxReq: SandboxRequest, options: {
111
+ wait?: Duration;
112
+ interval?: Duration;
113
+ }): Promise<SandboxProcessObject>;
52
114
  /**
53
115
  * Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
54
116
  *
@@ -68,6 +130,11 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
68
130
  * @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
69
131
  */
70
132
  remove(throwWhenRemoveFails?: boolean): Promise<void>;
133
+ /**
134
+ * Check if org is a sandbox org by checking its SandboxOrgConfig.
135
+ *
136
+ */
137
+ isSandbox(): Promise<boolean>;
71
138
  /**
72
139
  * Check that this org is a scratch org by asking the dev hub if it knows about it.
73
140
  *
@@ -90,6 +157,16 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
90
157
  * dev hub**. If you need accuracy, use the {@link Org.determineIfDevHubOrg} method.
91
158
  */
92
159
  isDevHubOrg(): boolean;
160
+ /**
161
+ * Will delete 'this' instance remotely and any files locally
162
+ *
163
+ * @param controllingOrg username or Org that 'this.devhub' or 'this.production' refers to. AKA a DevHub for a scratch org, or a Production Org for a sandbox
164
+ */
165
+ deleteFrom(controllingOrg: string | Org): Promise<void>;
166
+ /**
167
+ * Will delete 'this' instance remotely and any files locally
168
+ */
169
+ delete(): Promise<void>;
93
170
  /**
94
171
  * Returns `true` if the org is a Dev Hub.
95
172
  *
@@ -117,14 +194,6 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
117
194
  * using {@link Org.retrieveOrganizationInformation}.
118
195
  */
119
196
  determineIfScratch(): Promise<boolean>;
120
- /**
121
- * Returns `true` if the org is a sandbox.
122
- *
123
- * **Note** This relies on a cached value in the auth file. If that property
124
- * is not cached, this method will **always return false even if the org is a
125
- * sandbox**. If you need accuracy, use the {@link Org.determineIfDevHubOrg} method.
126
- */
127
- isSandbox(): boolean;
128
197
  /**
129
198
  * Returns `true` if the org is a sandbox.
130
199
  *
@@ -229,6 +298,23 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
229
298
  * **Throws** *{@link SfdxError}{ name: 'NotSupportedError' }* Throws an unsupported error.
230
299
  */
231
300
  protected getDefaultOptions(): Org.Options;
301
+ private queryProduction;
302
+ private destorySandbox;
303
+ private destoryScratchOrg;
304
+ /**
305
+ * this method will delete the sandbox org from the production org and clean up any local files
306
+ *
307
+ * @param prodOrg - Production org associated with this sandbox
308
+ * @private
309
+ */
310
+ private deleteSandbox;
311
+ /**
312
+ * If this Org is a scratch org, calling this method will delete the scratch org from the DevHub and clean up any local files
313
+ *
314
+ * @param devHub - optional DevHub Org of the to-be-deleted scratch org
315
+ * @private
316
+ */
317
+ private deleteScratchOrg;
232
318
  /**
233
319
  * Delete an auth info file from the local file system and any related cache information for
234
320
  * this Org. You don't want to call this method directly. Instead consider calling Org.remove()
@@ -255,6 +341,32 @@ export declare class Org extends AsyncOptionalCreatable<Org.Options> {
255
341
  * @param throwWhenRemoveFails true if manageDelete should throw or not if the deleted fails.
256
342
  */
257
343
  private removeSandboxConfig;
344
+ private writeSandboxAuthFile;
345
+ /**
346
+ * Polls for the new sandbox to be created - and will write the associated auth files
347
+ *
348
+ * @private
349
+ * @param options
350
+ * sandboxProcessObj: The in-progress sandbox signup request
351
+ * retries: the number of retries to poll for every 30s
352
+ * shouldPoll: wait for polling, or just return
353
+ * pollInterval: Duration to sleep between poll events, default 30 seconds
354
+ */
355
+ private pollStatusAndAuth;
356
+ /**
357
+ * query SandboxProcess via SandboxInfoId
358
+ *
359
+ * @param id SandboxInfoId to query for
360
+ * @private
361
+ */
362
+ private querySandboxProcess;
363
+ /**
364
+ * determines if the sandbox has successfully been created
365
+ *
366
+ * @param sandboxProcessObj sandbox signup progeress
367
+ * @private
368
+ */
369
+ private sandboxSignupComplete;
258
370
  }
259
371
  export declare namespace Org {
260
372
  /**