@salesforce/core 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +93 -44
  3. package/lib/config/authInfoConfig.d.ts +19 -0
  4. package/lib/config/authInfoConfig.js +35 -0
  5. package/lib/config/config.d.ts +87 -22
  6. package/lib/config/config.js +117 -65
  7. package/lib/config/configAggregator.d.ts +41 -35
  8. package/lib/config/configAggregator.js +102 -73
  9. package/lib/config/configFile.d.ts +2 -2
  10. package/lib/config/configFile.js +38 -29
  11. package/lib/config/configStore.d.ts +9 -9
  12. package/lib/config/configStore.js +17 -15
  13. package/lib/config/envVars.d.ts +15 -9
  14. package/lib/config/envVars.js +71 -47
  15. package/lib/config/orgUsersConfig.js +2 -0
  16. package/lib/config/sandboxOrgConfig.js +2 -0
  17. package/lib/config/sandboxProcessCache.d.ts +16 -0
  18. package/lib/config/sandboxProcessCache.js +38 -0
  19. package/lib/config/tokensConfig.d.ts +10 -0
  20. package/lib/config/tokensConfig.js +29 -0
  21. package/lib/config/ttlConfig.d.ts +34 -0
  22. package/lib/config/ttlConfig.js +50 -0
  23. package/lib/crypto/crypto.js +15 -22
  24. package/lib/crypto/keyChain.js +2 -3
  25. package/lib/crypto/keyChainImpl.d.ts +5 -3
  26. package/lib/crypto/keyChainImpl.js +58 -61
  27. package/lib/crypto/secureBuffer.d.ts +1 -1
  28. package/lib/deviceOauthService.d.ts +3 -3
  29. package/lib/deviceOauthService.js +27 -25
  30. package/lib/exported.d.ts +15 -12
  31. package/lib/exported.js +28 -16
  32. package/lib/global.d.ts +11 -3
  33. package/lib/global.js +39 -12
  34. package/lib/lifecycleEvents.d.ts +1 -1
  35. package/lib/lifecycleEvents.js +3 -0
  36. package/lib/logger.d.ts +19 -9
  37. package/lib/logger.js +112 -86
  38. package/lib/messages.d.ts +53 -36
  39. package/lib/messages.js +81 -91
  40. package/lib/org/authInfo.d.ts +56 -20
  41. package/lib/org/authInfo.js +232 -131
  42. package/lib/org/authRemover.d.ts +8 -7
  43. package/lib/org/authRemover.js +32 -28
  44. package/lib/org/connection.d.ts +13 -37
  45. package/lib/org/connection.js +78 -124
  46. package/lib/org/index.js +5 -1
  47. package/lib/org/org.d.ts +151 -48
  48. package/lib/org/org.js +468 -225
  49. package/lib/org/orgConfigProperties.d.ts +64 -3
  50. package/lib/org/orgConfigProperties.js +96 -4
  51. package/lib/org/permissionSetAssignment.js +4 -13
  52. package/lib/org/scratchOrgCache.d.ts +20 -0
  53. package/lib/org/scratchOrgCache.js +33 -0
  54. package/lib/org/scratchOrgCreate.d.ts +28 -17
  55. package/lib/org/scratchOrgCreate.js +125 -53
  56. package/lib/org/scratchOrgErrorCodes.d.ts +9 -3
  57. package/lib/org/scratchOrgErrorCodes.js +34 -17
  58. package/lib/org/scratchOrgFeatureDeprecation.js +1 -6
  59. package/lib/org/scratchOrgInfoApi.d.ts +21 -47
  60. package/lib/org/scratchOrgInfoApi.js +129 -63
  61. package/lib/org/scratchOrgInfoGenerator.d.ts +6 -5
  62. package/lib/org/scratchOrgInfoGenerator.js +76 -62
  63. package/lib/org/scratchOrgLifecycleEvents.d.ts +10 -0
  64. package/lib/org/scratchOrgLifecycleEvents.js +41 -0
  65. package/lib/org/scratchOrgSettingsGenerator.d.ts +44 -21
  66. package/lib/org/scratchOrgSettingsGenerator.js +165 -98
  67. package/lib/org/scratchOrgTypes.d.ts +43 -0
  68. package/lib/org/scratchOrgTypes.js +9 -0
  69. package/lib/org/user.d.ts +1 -1
  70. package/lib/org/user.js +25 -34
  71. package/lib/schema/printer.d.ts +6 -0
  72. package/lib/schema/printer.js +34 -31
  73. package/lib/schema/validator.d.ts +12 -10
  74. package/lib/schema/validator.js +56 -76
  75. package/lib/{sfdxError.d.ts → sfError.d.ts} +12 -20
  76. package/lib/{sfdxError.js → sfError.js} +40 -30
  77. package/lib/{sfdxProject.d.ts → sfProject.d.ts} +75 -35
  78. package/lib/sfProject.js +651 -0
  79. package/lib/stateAggregator/accessors/aliasAccessor.d.ts +129 -0
  80. package/lib/stateAggregator/accessors/aliasAccessor.js +263 -0
  81. package/lib/stateAggregator/accessors/orgAccessor.d.ts +101 -0
  82. package/lib/stateAggregator/accessors/orgAccessor.js +240 -0
  83. package/lib/stateAggregator/accessors/sandboxAccessor.d.ts +8 -0
  84. package/lib/stateAggregator/accessors/sandboxAccessor.js +28 -0
  85. package/lib/stateAggregator/accessors/tokenAccessor.d.ts +63 -0
  86. package/lib/stateAggregator/accessors/tokenAccessor.js +80 -0
  87. package/lib/stateAggregator/index.d.ts +4 -0
  88. package/lib/stateAggregator/index.js +27 -0
  89. package/lib/stateAggregator/stateAggregator.d.ts +25 -0
  90. package/lib/stateAggregator/stateAggregator.js +46 -0
  91. package/lib/status/myDomainResolver.d.ts +1 -1
  92. package/lib/status/myDomainResolver.js +4 -4
  93. package/lib/status/pollingClient.js +4 -4
  94. package/lib/status/streamingClient.d.ts +2 -2
  95. package/lib/status/streamingClient.js +58 -63
  96. package/lib/status/types.d.ts +2 -2
  97. package/lib/testSetup.d.ts +204 -75
  98. package/lib/testSetup.js +468 -164
  99. package/lib/util/cache.d.ts +2 -2
  100. package/lib/util/cache.js +6 -6
  101. package/lib/util/checkLightningDomain.js +3 -4
  102. package/lib/util/directoryWriter.d.ts +12 -0
  103. package/lib/util/directoryWriter.js +54 -0
  104. package/lib/util/getJwtAudienceUrl.js +1 -1
  105. package/lib/util/internal.d.ts +28 -2
  106. package/lib/util/internal.js +65 -8
  107. package/lib/util/jsonXmlTools.js +2 -4
  108. package/lib/util/mapKeys.d.ts +9 -9
  109. package/lib/util/mapKeys.js +13 -9
  110. package/lib/util/sfdc.d.ts +51 -51
  111. package/lib/util/sfdc.js +74 -79
  112. package/lib/util/sfdcUrl.d.ts +5 -19
  113. package/lib/util/sfdcUrl.js +40 -49
  114. package/lib/util/structuredWriter.d.ts +9 -0
  115. package/lib/util/structuredWriter.js +3 -0
  116. package/lib/util/zipWriter.d.ts +8 -6
  117. package/lib/util/zipWriter.js +13 -13
  118. package/lib/webOAuthServer.d.ts +20 -6
  119. package/lib/webOAuthServer.js +102 -56
  120. package/messageTransformer/messageTransformer.ts +93 -0
  121. package/messages/auth.md +9 -1
  122. package/messages/config.md +42 -6
  123. package/messages/connection.md +8 -0
  124. package/messages/core.md +10 -0
  125. package/messages/envVars.md +37 -3
  126. package/messages/org.md +21 -1
  127. package/messages/scratchOrgCreate.md +2 -6
  128. package/messages/scratchOrgErrorCodes.md +17 -1
  129. package/messages/scratchOrgInfoApi.md +9 -0
  130. package/messages/scratchOrgInfoGenerator.md +9 -1
  131. package/package.json +123 -46
  132. package/CHANGELOG.md +0 -1244
  133. package/lib/config/keychainConfig.d.ts +0 -19
  134. package/lib/config/keychainConfig.js +0 -43
  135. package/lib/globalInfo/accessors/aliasAccessor.d.ts +0 -83
  136. package/lib/globalInfo/accessors/aliasAccessor.js +0 -130
  137. package/lib/globalInfo/accessors/orgAccessor.d.ts +0 -13
  138. package/lib/globalInfo/accessors/orgAccessor.js +0 -45
  139. package/lib/globalInfo/accessors/tokenAccessor.d.ts +0 -13
  140. package/lib/globalInfo/accessors/tokenAccessor.js +0 -35
  141. package/lib/globalInfo/globalInfoConfig.d.ts +0 -36
  142. package/lib/globalInfo/globalInfoConfig.js +0 -105
  143. package/lib/globalInfo/index.d.ts +0 -6
  144. package/lib/globalInfo/index.js +0 -29
  145. package/lib/globalInfo/sfdxDataHandler.d.ts +0 -43
  146. package/lib/globalInfo/sfdxDataHandler.js +0 -217
  147. package/lib/globalInfo/types.d.ts +0 -39
  148. package/lib/globalInfo/types.js +0 -10
  149. package/lib/sfdxProject.js +0 -557
  150. package/lib/util/fs.d.ts +0 -201
  151. package/lib/util/fs.js +0 -378
@@ -1,8 +1,69 @@
1
+ import { ConfigValue } from '../config/configStore';
1
2
  export declare enum OrgConfigProperties {
3
+ /**
4
+ * Username associate with the default org.
5
+ */
2
6
  TARGET_ORG = "target-org",
3
- TARGET_DEV_HUB = "target-dev-hub"
7
+ /**
8
+ * Username associated with the default dev hub org.
9
+ */
10
+ TARGET_DEV_HUB = "target-dev-hub",
11
+ /**
12
+ * The api version
13
+ */
14
+ ORG_API_VERSION = "org-api-version",
15
+ /**
16
+ * Custom templates repo or local location.
17
+ */
18
+ ORG_CUSTOM_METADATA_TEMPLATES = "org-custom-metadata-templates",
19
+ /**
20
+ * Allows users to override the 10,000 result query limit.
21
+ */
22
+ ORG_MAX_QUERY_LIMIT = "org-max-query-limit",
23
+ /**
24
+ * The instance url of the org.
25
+ */
26
+ ORG_INSTANCE_URL = "org-instance-url",
27
+ /**
28
+ * The sid for the debugger configuration.
29
+ */
30
+ ORG_ISV_DEBUGGER_SID = "org-isv-debugger-sid",
31
+ /**
32
+ * The url for the debugger configuration.
33
+ */
34
+ ORG_ISV_DEBUGGER_URL = "org-isv-debugger-url"
4
35
  }
5
- export declare const ORG_CONFIG_ALLOWED_PROPERTIES: {
36
+ export declare const ORG_CONFIG_ALLOWED_PROPERTIES: ({
6
37
  key: OrgConfigProperties;
7
38
  description: string;
8
- }[];
39
+ input?: undefined;
40
+ hidden?: undefined;
41
+ encrypted?: undefined;
42
+ } | {
43
+ key: OrgConfigProperties;
44
+ description: string;
45
+ input: {
46
+ validator: (value: ConfigValue) => boolean;
47
+ failedMessage: string;
48
+ };
49
+ hidden?: undefined;
50
+ encrypted?: undefined;
51
+ } | {
52
+ key: OrgConfigProperties;
53
+ description: string;
54
+ hidden: boolean;
55
+ input: {
56
+ validator: (value: ConfigValue) => boolean;
57
+ failedMessage: string;
58
+ };
59
+ encrypted?: undefined;
60
+ } | {
61
+ key: OrgConfigProperties;
62
+ description: string;
63
+ encrypted: boolean;
64
+ input: {
65
+ validator: (value: ConfigValue) => boolean;
66
+ failedMessage: string;
67
+ };
68
+ hidden?: undefined;
69
+ })[];
@@ -8,22 +8,114 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ORG_CONFIG_ALLOWED_PROPERTIES = exports.OrgConfigProperties = void 0;
10
10
  const path_1 = require("path");
11
+ const ts_types_1 = require("@salesforce/ts-types");
11
12
  const messages_1 = require("../messages");
12
- messages_1.Messages.importMessagesDirectory((0, path_1.join)(__dirname));
13
- const messages = messages_1.Messages.load('@salesforce/core', 'config', ['targetOrg', 'targetDevHub']);
13
+ const sfdcUrl_1 = require("../util/sfdcUrl");
14
+ const sfdc_1 = require("../util/sfdc");
15
+ const messages = new messages_1.Messages('@salesforce/core', 'config', new Map([["unknownConfigKey", "Unknown config name: %s."], ["deprecatedConfigKey", "Deprecated config name: %s. Please use %s instead."], ["invalidWrite", "The writeSync method is not allowed on SfdxConfig. Use the async write method instead."], ["invalidConfigValue", "Invalid config value: %s."], ["invalidInstanceUrl", "Specify a valid Salesforce instance URL."], ["invalidApiVersion", "Specify a valid Salesforce API version, for example, 42.0."], ["invalidCustomOrgMetadataTemplates", "Specify a valid repository URL or directory for the custom org metadata templates."], ["invalidIsvDebuggerSid", "Specify a valid Debugger SID."], ["invalidIsvDebuggerUrl", "Specify a valid Debugger URL."], ["invalidNumberConfigValue", "Specify a valid positive integer, for example, 150000."], ["invalidBooleanConfigValue", "The config value can only be set to true or false."], ["invalidProjectWorkspace", "This directory does not contain a valid Salesforce DX project."], ["schemaValidationError", "The config file \"%s\" is not schema valid.\nDue to: %s"], ["schemaValidationError.actions", ["Fix the invalid entries at %s."]], ["missingDefaultPath", "In sfdx-project.json, be sure to specify which package directory (path) is the default. Example: `[{ \"path\": \"packageDirectory1\", \"default\": true }, { \"path\": \"packageDirectory2\" }]`"], ["missingPackageDirectory", "The path \"%s\", specified in sfdx-project.json, does not exist. Be sure this directory is included in your project root."], ["invalidPackageDirectory", "The path \"%s\", specified in sfdx-project.json, must be indicated as a relative path to the project root."], ["multipleDefaultPaths", "In sfdx-project.json, indicate only one package directory (path) as the default."], ["singleNonDefaultPackage", "The sfdx-project.json file must include one, and only one, default package directory (path). Because your sfdx-project.json file contains only one package directory, it must be the default. Remove the `\"default\": false` key and try again."], ["target-org", "Username or alias of the org that all commands run against by default. (sf only)"], ["target-dev-hub", "Username or alias of your default Dev Hub org. (sf only)"], ["defaultUsername", "Username or alias of the org that all commands run against by default. (sfdx only)"], ["defaultDevHubUsername", "Username or alias of your default Dev Hub org. (sfdx only)"], ["isvDebuggerSid", "ISV debugger SID (sfdx only)"], ["isvDebuggerUrl", "ISV debugger URL (sfdx only)"], ["org-isv-debugger-sid", "ISV debugger SID."], ["org-isv-debugger-url", "ISV debugger URL."], ["apiVersion", "API version of your project. Default: API version of your Dev Hub org. (sfdx only)"], ["org-api-version", "API version of your project. Default: API version of your Dev Hub org."], ["disableTelemetry", "Disables the collection of usage and user environment information, etc. Default: false. (sfdx only)"], ["disable-telemetry", "Disables the collection of usage and user environment information, etc. Default: false."], ["maxQueryLimit", "Maximum number of Salesforce records returned by a CLI command. Default: 10,000. (sfdx only)"], ["org-max-query-limit", "Maximum number of Salesforce records returned by a CLI command. Default: 10,000."], ["restDeploy", "Whether deployments use the Metadata REST API (true) or SOAP API (false, default value). (sfdx only)"], ["instanceUrl", "URL of the Salesforce instance hosting your org. Default: https://login.salesforce.com. (sfdx only)"], ["org-instance-url", "URL of the Salesforce instance hosting your org. Default: https://login.salesforce.com."], ["customOrgMetadataTemplates", "A valid repository URL or directory for the custom org metadata templates."], ["org-custom-metadata-templates", "A valid repository URL or directory for the custom org metadata templates."], ["invalidId", "The given id %s is not a valid 15 or 18 character Salesforce ID."]]));
14
16
  var OrgConfigProperties;
15
17
  (function (OrgConfigProperties) {
18
+ /**
19
+ * Username associate with the default org.
20
+ */
16
21
  OrgConfigProperties["TARGET_ORG"] = "target-org";
22
+ /**
23
+ * Username associated with the default dev hub org.
24
+ */
17
25
  OrgConfigProperties["TARGET_DEV_HUB"] = "target-dev-hub";
26
+ /**
27
+ * The api version
28
+ */
29
+ OrgConfigProperties["ORG_API_VERSION"] = "org-api-version";
30
+ /**
31
+ * Custom templates repo or local location.
32
+ */
33
+ OrgConfigProperties["ORG_CUSTOM_METADATA_TEMPLATES"] = "org-custom-metadata-templates";
34
+ /**
35
+ * Allows users to override the 10,000 result query limit.
36
+ */
37
+ OrgConfigProperties["ORG_MAX_QUERY_LIMIT"] = "org-max-query-limit";
38
+ /**
39
+ * The instance url of the org.
40
+ */
41
+ OrgConfigProperties["ORG_INSTANCE_URL"] = "org-instance-url";
42
+ /**
43
+ * The sid for the debugger configuration.
44
+ */
45
+ OrgConfigProperties["ORG_ISV_DEBUGGER_SID"] = "org-isv-debugger-sid";
46
+ /**
47
+ * The url for the debugger configuration.
48
+ */
49
+ OrgConfigProperties["ORG_ISV_DEBUGGER_URL"] = "org-isv-debugger-url";
18
50
  })(OrgConfigProperties = exports.OrgConfigProperties || (exports.OrgConfigProperties = {}));
19
51
  exports.ORG_CONFIG_ALLOWED_PROPERTIES = [
52
+ {
53
+ key: OrgConfigProperties.ORG_CUSTOM_METADATA_TEMPLATES,
54
+ description: messages.getMessage(OrgConfigProperties.ORG_CUSTOM_METADATA_TEMPLATES),
55
+ },
20
56
  {
21
57
  key: OrgConfigProperties.TARGET_ORG,
22
- description: messages.getMessage('targetOrg'),
58
+ description: messages.getMessage(OrgConfigProperties.TARGET_ORG),
23
59
  },
24
60
  {
25
61
  key: OrgConfigProperties.TARGET_DEV_HUB,
26
- description: messages.getMessage('targetDevHub'),
62
+ description: messages.getMessage(OrgConfigProperties.TARGET_DEV_HUB),
63
+ },
64
+ {
65
+ key: OrgConfigProperties.ORG_INSTANCE_URL,
66
+ description: messages.getMessage(OrgConfigProperties.ORG_INSTANCE_URL),
67
+ input: {
68
+ // If a value is provided validate it otherwise no value is unset.
69
+ validator: (value) => {
70
+ if (value == null)
71
+ return true;
72
+ // validate if the value is a string and is a valid url and is either a salesforce domain
73
+ // or an internal url.
74
+ return ((0, ts_types_1.isString)(value) &&
75
+ sfdcUrl_1.SfdcUrl.isValidUrl(value) &&
76
+ (new sfdcUrl_1.SfdcUrl(value).isSalesforceDomain() || new sfdcUrl_1.SfdcUrl(value).isInternalUrl()));
77
+ },
78
+ failedMessage: messages.getMessage('invalidInstanceUrl'),
79
+ },
80
+ },
81
+ {
82
+ key: OrgConfigProperties.ORG_API_VERSION,
83
+ description: messages.getMessage(OrgConfigProperties.ORG_API_VERSION),
84
+ hidden: true,
85
+ input: {
86
+ // If a value is provided validate it otherwise no value is unset.
87
+ validator: (value) => value == null || ((0, ts_types_1.isString)(value) && (0, sfdc_1.validateApiVersion)(value)),
88
+ failedMessage: messages.getMessage('invalidApiVersion'),
89
+ },
90
+ },
91
+ {
92
+ key: OrgConfigProperties.ORG_ISV_DEBUGGER_SID,
93
+ description: messages.getMessage(OrgConfigProperties.ORG_ISV_DEBUGGER_SID),
94
+ encrypted: true,
95
+ input: {
96
+ // If a value is provided validate it otherwise no value is unset.
97
+ validator: (value) => value == null || (0, ts_types_1.isString)(value),
98
+ failedMessage: messages.getMessage('invalidIsvDebuggerSid'),
99
+ },
100
+ },
101
+ {
102
+ key: OrgConfigProperties.ORG_ISV_DEBUGGER_URL,
103
+ description: messages.getMessage(OrgConfigProperties.ORG_ISV_DEBUGGER_URL),
104
+ input: {
105
+ // If a value is provided validate it otherwise no value is unset.
106
+ validator: (value) => value == null || (0, ts_types_1.isString)(value),
107
+ failedMessage: messages.getMessage('invalidIsvDebuggerUrl'),
108
+ },
109
+ },
110
+ {
111
+ key: OrgConfigProperties.ORG_MAX_QUERY_LIMIT,
112
+ description: messages.getMessage(OrgConfigProperties.ORG_MAX_QUERY_LIMIT),
113
+ input: {
114
+ // the bit shift will remove the negative bit, and any decimal numbers
115
+ // then the parseFloat will handle converting it to a number from a string
116
+ validator: (value) => value >>> 0 === parseFloat(value) && value > 0,
117
+ failedMessage: messages.getMessage('invalidNumberConfigValue'),
118
+ },
27
119
  },
28
120
  ];
29
121
  //# sourceMappingURL=orgConfigProperties.js.map
@@ -12,17 +12,8 @@ const kit_1 = require("@salesforce/kit");
12
12
  const ts_types_1 = require("@salesforce/ts-types");
13
13
  const logger_1 = require("../logger");
14
14
  const messages_1 = require("../messages");
15
- const sfdxError_1 = require("../sfdxError");
16
- messages_1.Messages.importMessagesDirectory(__dirname);
17
- const messages = messages_1.Messages.load('@salesforce/core', 'permissionSetAssignment', [
18
- 'errorsEncounteredCreatingAssignment',
19
- 'orgRequired',
20
- 'userIdRequired',
21
- 'permSetRequired',
22
- 'assignCommandPermissionSetNotFoundForNSError',
23
- 'assignCommandPermissionSetNotFoundError',
24
- 'notSuccessfulButNoErrorsReported',
25
- ]);
15
+ const sfError_1 = require("../sfError");
16
+ const messages = new messages_1.Messages('@salesforce/core', 'permissionSetAssignment', new Map([["orgRequired", "An Org instance is required."], ["userIdRequired", "A Salesforce id for the user is required."], ["permSetRequired", "The name of a permission set is required."], ["unexpectedType", "An unexpected response was returned from the permission set assignment."], ["assignCommandPermissionSetNotFoundError", "Permission set \"%s\" not found in target org. Do you need to push source?"], ["assignCommandPermissionSetNotFoundForNSError", "Permission set \"%s\" for namespace \"%s\" not found in target org. Do you need to push source or install the package?"], ["errorsEncounteredCreatingAssignment", "Error(s) were reported."], ["notSuccessfulButNoErrorsReported", "The permission set assignment failed but no errors were reported."]]));
26
17
  /**
27
18
  * A class for assigning a Salesforce User to one or more permission sets.
28
19
  */
@@ -61,7 +52,7 @@ class PermissionSetAssignment {
61
52
  query += ` AND NamespacePrefix='${nsPrefix}'`;
62
53
  }
63
54
  const result = await this.org.getConnection().query(query);
64
- const permissionSetId = (0, ts_types_1.getString)(result, 'records[0].Id');
55
+ const permissionSetId = result?.records[0]?.Id;
65
56
  if (!permissionSetId) {
66
57
  if (nsPrefix) {
67
58
  throw messages.createError('assignCommandPermissionSetNotFoundForNSError', [permSetName, nsPrefix]);
@@ -86,7 +77,7 @@ class PermissionSetAssignment {
86
77
  errors.forEach((_message) => {
87
78
  message = `${message}${_message}${os_1.EOL}`;
88
79
  });
89
- throw new sfdxError_1.SfdxError(message, 'errorsEncounteredCreatingAssignment');
80
+ throw new sfError_1.SfError(message, 'errorsEncounteredCreatingAssignment');
90
81
  }
91
82
  else {
92
83
  throw messages.createError('notSuccessfulButNoErrorsReported');
@@ -0,0 +1,20 @@
1
+ import { JsonMap } from '@salesforce/ts-types';
2
+ import { TTLConfig } from '../config/ttlConfig';
3
+ export type CachedOptions = {
4
+ hubUsername: string;
5
+ /** stores the scratch definition, including settings/objectSettings */
6
+ definitionjson: JsonMap;
7
+ hubBaseUrl: string;
8
+ /** may be required for auth*/
9
+ clientSecret?: string;
10
+ signupTargetLoginUrlConfig?: string;
11
+ apiVersion?: string;
12
+ alias?: string;
13
+ setDefault?: boolean;
14
+ tracksSource?: boolean;
15
+ };
16
+ export declare class ScratchOrgCache extends TTLConfig<TTLConfig.Options, CachedOptions> {
17
+ static getFileName(): string;
18
+ static getDefaultOptions(): TTLConfig.Options;
19
+ static unset(key: string): Promise<void>;
20
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ScratchOrgCache = void 0;
4
+ /*
5
+ * Copyright (c) 2020, salesforce.com, inc.
6
+ * All rights reserved.
7
+ * Licensed under the BSD 3-Clause license.
8
+ * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
9
+ */
10
+ const kit_1 = require("@salesforce/kit");
11
+ const global_1 = require("../global");
12
+ const ttlConfig_1 = require("../config/ttlConfig");
13
+ class ScratchOrgCache extends ttlConfig_1.TTLConfig {
14
+ static getFileName() {
15
+ return 'scratch-create-cache.json';
16
+ }
17
+ static getDefaultOptions() {
18
+ return {
19
+ isGlobal: true,
20
+ isState: true,
21
+ filename: ScratchOrgCache.getFileName(),
22
+ stateFolder: global_1.Global.SF_STATE_FOLDER,
23
+ ttl: kit_1.Duration.days(1),
24
+ };
25
+ }
26
+ static async unset(key) {
27
+ const cache = await ScratchOrgCache.create();
28
+ cache.unset(key);
29
+ await cache.write();
30
+ }
31
+ }
32
+ exports.ScratchOrgCache = ScratchOrgCache;
33
+ //# sourceMappingURL=scratchOrgCache.js.map
@@ -1,6 +1,6 @@
1
1
  import { Duration } from '@salesforce/kit';
2
2
  import { Org } from './org';
3
- import { ScratchOrgInfo } from './scratchOrgInfoApi';
3
+ import { ScratchOrgInfo } from './scratchOrgTypes';
4
4
  import { AuthFields, AuthInfo } from './authInfo';
5
5
  export declare const DEFAULT_STREAM_TIMEOUT_MINUTES = 6;
6
6
  export interface ScratchOrgCreateResult {
@@ -10,34 +10,45 @@ export interface ScratchOrgCreateResult {
10
10
  authFields?: AuthFields;
11
11
  warnings: string[];
12
12
  }
13
- /**
14
- * interface ScratchOrgCreateOptions
15
- *
16
- * @param hubOrg the environment hub org
17
- * @param connectedAppConsumerKey The connected app consumer key.
18
- * @param durationDays duration of the scratch org (in days) (default:1, min:1, max:30)
19
- * @param nonamespace create the scratch org with no namespace
20
- * @param noancestors do not include second-generation package ancestors in the scratch org
21
- * @param wait the streaming client socket timeout (in minutes) must be an instance of the Duration utility class (default:6, min:2)
22
- * @param retry number of scratch org auth retries after scratch org is successfully signed up (default:0, min:0, max:10)
23
- * @param apiversion target server instance API version
24
- * @param definitionjson org definition in JSON format
25
- * @param definitionfile path to an org definition file
26
- * @param orgConfig overrides definitionjson
27
- * @param clientSecret OAuth client secret of personal connected app
28
- */
29
13
  export interface ScratchOrgCreateOptions {
14
+ /** the environment hub org */
30
15
  hubOrg: Org;
16
+ /** The connected app consumer key. */
31
17
  connectedAppConsumerKey?: string;
18
+ /** duration of the scratch org (in days) (default:1, min:1, max:30) */
32
19
  durationDays?: number;
20
+ /** create the scratch org with no namespace */
33
21
  nonamespace?: boolean;
22
+ /** create the scratch org with no second-generation package ancestors */
34
23
  noancestors?: boolean;
24
+ /** the streaming client socket timeout (in minutes) must be an instance of the Duration utility class (default:6) */
35
25
  wait?: Duration;
26
+ /** number of scratch org auth retries after scratch org is successfully signed up (default:0, min:0, max:10) */
36
27
  retry?: number;
28
+ /** target server instance API version */
37
29
  apiversion?: string;
30
+ /**
31
+ * org definition in JSON format, stringified
32
+ *
33
+ * @deprecated use orgConfig
34
+ */
38
35
  definitionjson?: string;
36
+ /**
37
+ * path to an org definition file
38
+ *
39
+ * @deprecated use orgConfig
40
+ * */
39
41
  definitionfile?: string;
42
+ /** overrides definitionjson */
40
43
  orgConfig?: Record<string, unknown>;
44
+ /** OAuth client secret of personal connected app */
41
45
  clientSecret?: string;
46
+ /** alias to set for the created org */
47
+ alias?: string;
48
+ /** after complete, set the org as the default */
49
+ setDefault?: boolean;
50
+ /** if false, do not use source tracking for this scratch org */
51
+ tracksSource?: boolean;
42
52
  }
53
+ export declare const scratchOrgResume: (jobId: string) => Promise<ScratchOrgCreateResult>;
43
54
  export declare const scratchOrgCreate: (options: ScratchOrgCreateOptions) => Promise<ScratchOrgCreateResult>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scratchOrgCreate = exports.DEFAULT_STREAM_TIMEOUT_MINUTES = void 0;
3
+ exports.scratchOrgCreate = exports.scratchOrgResume = exports.DEFAULT_STREAM_TIMEOUT_MINUTES = void 0;
4
4
  /*
5
5
  * Copyright (c) 2020, salesforce.com, inc.
6
6
  * All rights reserved.
@@ -12,22 +12,18 @@ const ts_types_1 = require("@salesforce/ts-types");
12
12
  const messages_1 = require("../messages");
13
13
  const logger_1 = require("../logger");
14
14
  const configAggregator_1 = require("../config/configAggregator");
15
- const sfdxProject_1 = require("../sfdxProject");
16
- const sfdxError_1 = require("../sfdxError");
15
+ const orgConfigProperties_1 = require("../org/orgConfigProperties");
16
+ const sfProject_1 = require("../sfProject");
17
+ const stateAggregator_1 = require("../stateAggregator");
17
18
  const org_1 = require("./org");
18
19
  const scratchOrgInfoApi_1 = require("./scratchOrgInfoApi");
19
20
  const scratchOrgSettingsGenerator_1 = require("./scratchOrgSettingsGenerator");
20
21
  const scratchOrgInfoGenerator_1 = require("./scratchOrgInfoGenerator");
21
- const connection_1 = require("./connection");
22
- messages_1.Messages.importMessagesDirectory(__dirname);
23
- const messages = messages_1.Messages.load('@salesforce/core', 'scratchOrgCreate', [
24
- 'SourceStatusResetFailureError',
25
- 'DurationDaysValidationMaxError',
26
- 'DurationDaysValidationMinError',
27
- 'RetryNotIntError',
28
- 'WaitValidationMaxError',
29
- 'DurationDaysNotIntError',
30
- ]);
22
+ const authInfo_1 = require("./authInfo");
23
+ const scratchOrgLifecycleEvents_1 = require("./scratchOrgLifecycleEvents");
24
+ const scratchOrgCache_1 = require("./scratchOrgCache");
25
+ const scratchOrgErrorCodes_1 = require("./scratchOrgErrorCodes");
26
+ const messages = new messages_1.Messages('@salesforce/core', 'scratchOrgCreate', new Map([["UnsupportedSnapshotOrgCreateOptionsError", "Org snapshots don\u2019t support one or more options you specified: %s."], ["DurationDaysValidationMinError", "Expected 'durationDays' greater than or equal to %s but received %s."], ["DurationDaysValidationMaxError", "Expected 'durationDays' less than or equal to %s but received %s."], ["DurationDaysNotIntError", "Expected 'durationDays' to be an integer number."], ["RetryNotIntError", "Expected 'retry' to be an integer number."], ["CacheMissError", "The ScratchOrgInfoId %s was not found in the cache."]]));
31
27
  exports.DEFAULT_STREAM_TIMEOUT_MINUTES = 6;
32
28
  const validateDuration = (durationDays) => {
33
29
  const min = 1;
@@ -48,20 +44,72 @@ const validateRetry = (retry) => {
48
44
  throw messages.createError('RetryNotIntError');
49
45
  }
50
46
  };
51
- const validateWait = (wait) => {
52
- const min = 2;
53
- if (wait.minutes < min) {
54
- throw messages.createError('WaitValidationMaxError', [min, wait.minutes]);
47
+ const scratchOrgResume = async (jobId) => {
48
+ const [logger, cache] = await Promise.all([
49
+ logger_1.Logger.child('scratchOrgResume'),
50
+ scratchOrgCache_1.ScratchOrgCache.create(),
51
+ (0, scratchOrgLifecycleEvents_1.emit)({ stage: 'send request' }),
52
+ ]);
53
+ logger.debug(`resuming scratch org creation for jobId: ${jobId}`);
54
+ if (!cache.has(jobId)) {
55
+ throw messages.createError('CacheMissError', [jobId]);
55
56
  }
57
+ const { hubUsername, apiVersion, clientSecret, signupTargetLoginUrlConfig, definitionjson, alias, setDefault, tracksSource, } = cache.get(jobId);
58
+ const hubOrg = await org_1.Org.create({ aliasOrUsername: hubUsername });
59
+ const soi = await (0, scratchOrgInfoApi_1.queryScratchOrgInfo)(hubOrg, jobId);
60
+ await (0, scratchOrgErrorCodes_1.validateScratchOrgInfoForResume)({ jobId, scratchOrgInfo: soi, cache, hubUsername });
61
+ // At this point, the scratch org is "good".
62
+ // Some hubs have all the usernames set to `null`
63
+ const username = soi.Username ?? soi.SignupUsername;
64
+ // re-auth only if the org isn't in StateAggregator
65
+ const stateAggregator = await stateAggregator_1.StateAggregator.getInstance();
66
+ const scratchOrgAuthInfo = (await stateAggregator.orgs.exists(username))
67
+ ? await authInfo_1.AuthInfo.create({ username })
68
+ : await (0, scratchOrgInfoApi_1.authorizeScratchOrg)({
69
+ scratchOrgInfoComplete: soi,
70
+ hubOrg,
71
+ clientSecret,
72
+ signupTargetLoginUrlConfig,
73
+ retry: 0,
74
+ });
75
+ const scratchOrg = await org_1.Org.create({ aliasOrUsername: username });
76
+ const configAggregator = await configAggregator_1.ConfigAggregator.create();
77
+ await (0, scratchOrgLifecycleEvents_1.emit)({ stage: 'deploy settings', scratchOrgInfo: soi });
78
+ const settingsGenerator = new scratchOrgSettingsGenerator_1.default();
79
+ await settingsGenerator.extract({ ...soi, ...definitionjson });
80
+ const [authInfo] = await Promise.all([
81
+ (0, scratchOrgInfoApi_1.resolveUrl)(scratchOrgAuthInfo),
82
+ (0, scratchOrgInfoApi_1.deploySettings)(scratchOrg, settingsGenerator, apiVersion ??
83
+ configAggregator.getPropertyValue(orgConfigProperties_1.OrgConfigProperties.ORG_API_VERSION) ??
84
+ (await scratchOrg.retrieveMaxApiVersion())),
85
+ ]);
86
+ await scratchOrgAuthInfo.handleAliasAndDefaultSettings({
87
+ alias,
88
+ setDefault: setDefault ?? false,
89
+ setDefaultDevHub: false,
90
+ setTracksSource: tracksSource ?? true,
91
+ });
92
+ cache.unset(soi.Id ?? jobId);
93
+ const authFields = authInfo.getFields();
94
+ await Promise.all([(0, scratchOrgLifecycleEvents_1.emit)({ stage: 'done', scratchOrgInfo: soi }), cache.write(), (0, scratchOrgLifecycleEvents_1.emitPostOrgCreate)(authFields)]);
95
+ return {
96
+ username,
97
+ scratchOrgInfo: soi,
98
+ authInfo,
99
+ authFields,
100
+ warnings: [],
101
+ };
56
102
  };
103
+ exports.scratchOrgResume = scratchOrgResume;
57
104
  const scratchOrgCreate = async (options) => {
58
- var _a;
59
105
  const logger = await logger_1.Logger.child('scratchOrgCreate');
106
+ /** epoch milliseconds */
107
+ const startTimestamp = Date.now();
60
108
  logger.debug('scratchOrgCreate');
61
- const { hubOrg, connectedAppConsumerKey, durationDays = 1, nonamespace, noancestors, wait = kit_1.Duration.minutes(exports.DEFAULT_STREAM_TIMEOUT_MINUTES), retry = 0, apiversion, definitionjson, definitionfile, orgConfig, clientSecret = undefined, } = options;
109
+ await (0, scratchOrgLifecycleEvents_1.emit)({ stage: 'prepare request' });
110
+ const { hubOrg, connectedAppConsumerKey, durationDays = 1, nonamespace, noancestors, wait = kit_1.Duration.minutes(exports.DEFAULT_STREAM_TIMEOUT_MINUTES), retry = 0, apiversion, definitionjson, definitionfile, orgConfig, clientSecret = undefined, alias, setDefault = false, tracksSource = true, } = options;
62
111
  validateDuration(durationDays);
63
112
  validateRetry(retry);
64
- validateWait(wait);
65
113
  const { scratchOrgInfoPayload, ignoreAncestorIds, warnings } = await (0, scratchOrgInfoGenerator_1.getScratchOrgInfoPayload)({
66
114
  definitionjson,
67
115
  definitionfile,
@@ -79,43 +127,83 @@ const scratchOrgCreate = async (options) => {
79
127
  });
80
128
  // gets the scratch org settings (will use in both signup paths AND to deploy the settings)
81
129
  const settingsGenerator = new scratchOrgSettingsGenerator_1.default();
82
- await settingsGenerator.extract(scratchOrgInfo);
130
+ const settings = await settingsGenerator.extract(scratchOrgInfo);
83
131
  logger.debug(`the scratch org def file has settings: ${settingsGenerator.hasSettings()}`);
84
- // creates the scratch org info in the devhub
85
- const scratchOrgInfoRequestResult = await (0, scratchOrgInfoApi_1.requestScratchOrgCreation)(hubOrg, scratchOrgInfo, settingsGenerator);
86
- const scratchOrgInfoId = (0, ts_types_1.ensureString)((0, ts_types_1.getString)(scratchOrgInfoRequestResult, 'id'));
132
+ const [scratchOrgInfoRequestResult, signupTargetLoginUrlConfig] = await Promise.all([
133
+ // creates the scratch org info in the devhub
134
+ (0, scratchOrgInfoApi_1.requestScratchOrgCreation)(hubOrg, scratchOrgInfo, settingsGenerator),
135
+ getSignupTargetLoginUrl(),
136
+ ]);
137
+ const scratchOrgInfoId = (0, ts_types_1.ensureString)(scratchOrgInfoRequestResult.id);
138
+ const cache = await scratchOrgCache_1.ScratchOrgCache.create();
139
+ cache.set(scratchOrgInfoId, {
140
+ hubUsername: hubOrg.getUsername(),
141
+ hubBaseUrl: hubOrg.getField(org_1.Org.Fields.INSTANCE_URL)?.toString(),
142
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
143
+ definitionjson: { ...(definitionjson ? JSON.parse(definitionjson) : {}), ...orgConfig, ...settings },
144
+ clientSecret,
145
+ alias,
146
+ setDefault,
147
+ tracksSource,
148
+ });
149
+ await cache.write();
87
150
  logger.debug(`scratch org has recordId ${scratchOrgInfoId}`);
88
- const scratchOrgInfoResult = await (0, scratchOrgInfoApi_1.pollForScratchOrgInfo)(hubOrg, scratchOrgInfoId, wait);
89
- const signupTargetLoginUrlConfig = await getSignupTargetLoginUrl();
151
+ // this is where we stop--no polling
152
+ if (wait.minutes === 0) {
153
+ const soi = await (0, scratchOrgInfoApi_1.queryScratchOrgInfo)(hubOrg, scratchOrgInfoId);
154
+ return {
155
+ username: soi.SignupUsername,
156
+ warnings: [],
157
+ scratchOrgInfo: soi,
158
+ };
159
+ }
160
+ const soi = await (0, scratchOrgInfoApi_1.pollForScratchOrgInfo)(hubOrg, scratchOrgInfoId, wait);
90
161
  const scratchOrgAuthInfo = await (0, scratchOrgInfoApi_1.authorizeScratchOrg)({
91
- scratchOrgInfoComplete: scratchOrgInfoResult,
162
+ scratchOrgInfoComplete: soi,
92
163
  hubOrg,
93
164
  clientSecret,
94
165
  signupTargetLoginUrlConfig,
95
166
  retry: retry || 0,
96
167
  });
97
168
  // we'll need this scratch org connection later;
98
- const connection = await connection_1.Connection.create({ authInfo: scratchOrgAuthInfo });
99
- const scratchOrg = await org_1.Org.create({ connection }); // scartchOrg should come from command
169
+ const scratchOrg = await org_1.Org.create({
170
+ aliasOrUsername: soi.Username ?? soi.SignupUsername,
171
+ });
100
172
  const username = scratchOrg.getUsername();
101
173
  logger.debug(`scratch org username ${username}`);
102
- const configAggregator = new configAggregator_1.ConfigAggregator();
103
- const authInfo = await (0, scratchOrgInfoApi_1.deploySettingsAndResolveUrl)(scratchOrgAuthInfo, (_a = apiversion !== null && apiversion !== void 0 ? apiversion : configAggregator.getPropertyValue('apiVersion')) !== null && _a !== void 0 ? _a : (await scratchOrg.retrieveMaxApiVersion()), settingsGenerator, scratchOrg);
104
- logger.trace('Settings deployed to org');
105
- /** updating the revision num to zero during org:creation if source members are created during org:create.This only happens for some specific scratch org definition file.*/
106
- await updateRevisionCounterToZero(scratchOrg);
174
+ await (0, scratchOrgLifecycleEvents_1.emit)({ stage: 'deploy settings', scratchOrgInfo: soi });
175
+ const configAggregator = await configAggregator_1.ConfigAggregator.create();
176
+ const [authInfo] = await Promise.all([
177
+ (0, scratchOrgInfoApi_1.resolveUrl)(scratchOrgAuthInfo),
178
+ (0, scratchOrgInfoApi_1.deploySettings)(scratchOrg, settingsGenerator, apiversion ??
179
+ configAggregator.getPropertyValue(orgConfigProperties_1.OrgConfigProperties.ORG_API_VERSION) ??
180
+ (await scratchOrg.retrieveMaxApiVersion()),
181
+ // some of our "wait" time has already been used. Calculate how much remains that we can spend on the deployment.
182
+ kit_1.Duration.milliseconds(wait.milliseconds - (Date.now() - startTimestamp))),
183
+ ]);
184
+ await scratchOrgAuthInfo.handleAliasAndDefaultSettings({
185
+ ...{
186
+ alias,
187
+ setDefault,
188
+ setDefaultDevHub: false,
189
+ setTracksSource: tracksSource === false ? false : true,
190
+ },
191
+ });
192
+ cache.unset(scratchOrgInfoId);
193
+ const authFields = authInfo.getFields();
194
+ await Promise.all([(0, scratchOrgLifecycleEvents_1.emit)({ stage: 'done', scratchOrgInfo: soi }), cache.write(), (0, scratchOrgLifecycleEvents_1.emitPostOrgCreate)(authFields)]);
107
195
  return {
108
196
  username,
109
- scratchOrgInfo: scratchOrgInfoResult,
197
+ scratchOrgInfo: soi,
110
198
  authInfo,
111
- authFields: authInfo === null || authInfo === void 0 ? void 0 : authInfo.getFields(),
199
+ authFields: authInfo?.getFields(),
112
200
  warnings,
113
201
  };
114
202
  };
115
203
  exports.scratchOrgCreate = scratchOrgCreate;
116
204
  const getSignupTargetLoginUrl = async () => {
117
205
  try {
118
- const project = await sfdxProject_1.SfdxProject.resolve();
206
+ const project = await sfProject_1.SfProject.resolve();
119
207
  const projectJson = await project.resolveProjectConfig();
120
208
  return projectJson.signupTargetLoginUrl;
121
209
  }
@@ -123,20 +211,4 @@ const getSignupTargetLoginUrl = async () => {
123
211
  // a project isn't required for org:create
124
212
  }
125
213
  };
126
- const updateRevisionCounterToZero = async (scratchOrg) => {
127
- const conn = scratchOrg.getConnection();
128
- const queryResult = await conn.tooling.sobject('SourceMember').find({ RevisionCounter: { $gt: 0 } }, ['Id']);
129
- try {
130
- await conn.tooling
131
- .sobject('SourceMember')
132
- .update(queryResult.map((record) => ({ Id: record.Id, RevisionCounter: 0 })));
133
- }
134
- catch (err) {
135
- const message = messages.getMessage('SourceStatusResetFailureError', [
136
- scratchOrg.getOrgId(),
137
- scratchOrg.getUsername(),
138
- ]);
139
- throw new sfdxError_1.SfdxError(message, 'SourceStatusResetFailure');
140
- }
141
- };
142
214
  //# sourceMappingURL=scratchOrgCreate.js.map
@@ -1,4 +1,10 @@
1
1
  import { Optional } from '@salesforce/ts-types';
2
- import { Logger } from '../logger';
3
- import { ScratchOrgInfo } from './scratchOrgInfoApi';
4
- export declare const checkScratchOrgInfoForErrors: (orgInfo: Optional<ScratchOrgInfo>, hubUsername: Optional<string>, logger: Logger) => ScratchOrgInfo;
2
+ import { ScratchOrgInfo } from './scratchOrgTypes';
3
+ import { ScratchOrgCache } from './scratchOrgCache';
4
+ export declare const validateScratchOrgInfoForResume: ({ jobId, scratchOrgInfo, cache, hubUsername, }: {
5
+ jobId: string;
6
+ scratchOrgInfo: ScratchOrgInfo;
7
+ cache: ScratchOrgCache;
8
+ hubUsername: string;
9
+ }) => Promise<ScratchOrgInfo>;
10
+ export declare const checkScratchOrgInfoForErrors: (orgInfo: Optional<ScratchOrgInfo>, hubUsername: Optional<string>) => Promise<ScratchOrgInfo>;