@salesforce/packaging 0.1.11 → 0.1.13

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 (38) hide show
  1. package/lib/constants.d.ts +3 -0
  2. package/lib/constants.js +4 -1
  3. package/lib/interfaces/packagingInterfacesAndType.d.ts +20 -13
  4. package/lib/interfaces/packagingSObjects.d.ts +1 -1
  5. package/lib/package/index.d.ts +1 -5
  6. package/lib/package/index.js +1 -10
  7. package/lib/package/package.d.ts +79 -32
  8. package/lib/package/package.js +159 -71
  9. package/lib/package/packageAncestry.d.ts +3 -1
  10. package/lib/package/packageAncestry.js +43 -25
  11. package/lib/package/packageConvert.js +2 -3
  12. package/lib/package/packageCreate.d.ts +2 -12
  13. package/lib/package/packageCreate.js +30 -53
  14. package/lib/package/packageDelete.js +4 -1
  15. package/lib/package/packageInstall.d.ts +7 -14
  16. package/lib/package/packageInstall.js +65 -148
  17. package/lib/package/packageInstalledList.js +8 -2
  18. package/lib/package/packageUninstall.d.ts +5 -1
  19. package/lib/package/packageUninstall.js +51 -41
  20. package/lib/package/packageVersion.d.ts +53 -6
  21. package/lib/package/packageVersion.js +139 -29
  22. package/lib/package/packageVersionCreate.d.ts +2 -2
  23. package/lib/package/packageVersionCreate.js +27 -25
  24. package/lib/package/packageVersionCreateRequest.js +15 -6
  25. package/lib/package/packageVersionCreateRequestReport.js +9 -3
  26. package/lib/package/packageVersionList.js +3 -1
  27. package/lib/package/packageVersionReport.js +1 -27
  28. package/lib/package/subscriberPackageVersion.d.ts +156 -0
  29. package/lib/package/subscriberPackageVersion.js +346 -0
  30. package/lib/utils/packageUtils.d.ts +10 -11
  31. package/lib/utils/packageUtils.js +35 -24
  32. package/messages/package.md +18 -2
  33. package/messages/package_version.md +12 -0
  34. package/messages/pkg_utils.md +5 -33
  35. package/messages/subscriber_package_version.md +19 -0
  36. package/package.json +3 -3
  37. package/lib/package/packageList.d.ts +0 -4
  38. package/lib/package/packageList.js +0 -19
@@ -1,16 +1,16 @@
1
1
  "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
2
7
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
8
  if (kind === "m") throw new TypeError("Private method is not writable");
4
9
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
12
  };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _PackageAncestryNode_version, _PackageAncestryNode_MajorVersion, _PackageAncestryNode_MinorVersion, _PackageAncestryNode_PatchVersion, _PackageAncestryNode_BuildNumber, _PackageAncestryNode_AncestorId, _PackageAncestryNode_SubscriberPackageVersionId, _PackageAncestryNode_depthCounter;
13
+ var _PackageAncestry_requestedPackageId, _PackageAncestryNode_version, _PackageAncestryNode_MajorVersion, _PackageAncestryNode_MinorVersion, _PackageAncestryNode_PatchVersion, _PackageAncestryNode_BuildNumber, _PackageAncestryNode_AncestorId, _PackageAncestryNode_SubscriberPackageVersionId, _PackageAncestryNode_depthCounter;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.PackageAncestryNode = exports.AncestryDotProducer = exports.AncestryJsonProducer = exports.AncestryTreeProducer = exports.PackageAncestry = void 0;
16
16
  /*
@@ -27,11 +27,11 @@ const tree_1 = require("@oclif/core/lib/cli-ux/styled/tree");
27
27
  const graphology_traversal_1 = require("graphology-traversal");
28
28
  const pkgUtils = require("../utils/packageUtils");
29
29
  const utils_1 = require("../utils");
30
+ const packageVersion_1 = require("./packageVersion");
31
+ const package_1 = require("./package");
30
32
  core_1.Messages.importMessagesDirectory(__dirname);
31
33
  const messages = core_1.Messages.loadMessages('@salesforce/packaging', 'package_ancestry');
32
34
  const SELECT_PACKAGE_VERSION = 'SELECT AncestorId, SubscriberPackageVersionId, MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version';
33
- const SELECT_PACKAGE_CONTAINER_OPTIONS = 'SELECT ContainerOptions FROM Package2 ';
34
- const SELECT_PACKAGE_VERSION_CONTAINER_OPTIONS = 'SELECT Package2ContainerOptions FROM SubscriberPackageVersion';
35
35
  // Add this to query calls to only show released package versions in the output
36
36
  const releasedOnlyFilter = ' AND IsReleased = true';
37
37
  const sortAncestryNodeData = (a, b) => {
@@ -41,15 +41,17 @@ const sortAncestryNodeData = (a, b) => {
41
41
  };
42
42
  /**
43
43
  * A class that represents the package ancestry graph.
44
+ * Given a package Id (0Ho) or a package version Id (04t), it will build a graph of the package's ancestors.
44
45
  */
45
46
  class PackageAncestry extends kit_1.AsyncCreatable {
46
47
  constructor(options) {
47
48
  super(options);
48
49
  this.options = options;
50
+ _PackageAncestry_requestedPackageId.set(this, void 0);
49
51
  this.graph = new graphology_1.DirectedGraph();
50
52
  }
51
53
  get requestedPackageId() {
52
- return this._requestedPackageId;
54
+ return __classPrivateFieldGet(this, _PackageAncestry_requestedPackageId, "f");
53
55
  }
54
56
  async init() {
55
57
  await this.buildAncestryTree();
@@ -155,7 +157,7 @@ class PackageAncestry extends kit_1.AsyncCreatable {
155
157
  }
156
158
  async getRoots() {
157
159
  let roots = [];
158
- this._requestedPackageId = pkgUtils.getPackageIdFromAlias(this.options.packageId, this.options.project);
160
+ __classPrivateFieldSet(this, _PackageAncestry_requestedPackageId, pkgUtils.getPackageIdFromAlias(this.options.packageId, this.options.project), "f");
159
161
  switch (this.requestedPackageId.slice(0, 3)) {
160
162
  case '0Ho':
161
163
  pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, this.requestedPackageId);
@@ -168,16 +170,10 @@ class PackageAncestry extends kit_1.AsyncCreatable {
168
170
  default:
169
171
  throw messages.createError('idOrAliasNotFound', [this.requestedPackageId]);
170
172
  }
173
+ await this.validatePackageType();
171
174
  return roots;
172
175
  }
173
176
  async findRootsForPackageVersion() {
174
- // Check to see if the package version is part of an unlocked package
175
- // if so, throw an error since ancestry only applies to managed packages
176
- const versionQuery = `${SELECT_PACKAGE_VERSION_CONTAINER_OPTIONS} WHERE Id = '${this.requestedPackageId}'`;
177
- const packageVersionTypeResults = await this.options.connection.singleRecordQuery(versionQuery, { tooling: true });
178
- if (packageVersionTypeResults.Package2ContainerOptions !== 'Managed') {
179
- throw messages.createError('unlockedPackageError');
180
- }
181
177
  // Start with the node, and shoot up
182
178
  let node = await this.getPackageVersion(this.requestedPackageId);
183
179
  while (node.AncestorId !== null) {
@@ -187,6 +183,34 @@ class PackageAncestry extends kit_1.AsyncCreatable {
187
183
  }
188
184
  return [node];
189
185
  }
186
+ async validatePackageType() {
187
+ // Check to see if the package version is part of an unlocked package
188
+ // if so, throw an error since ancestry only applies to managed packages
189
+ let packageType;
190
+ switch (this.requestedPackageId.slice(0, 3)) {
191
+ case '04t':
192
+ // eslint-disable-next-line no-case-declarations
193
+ const packageVersion = new packageVersion_1.PackageVersion({
194
+ idOrAlias: this.requestedPackageId,
195
+ project: this.options.project,
196
+ connection: this.options.connection,
197
+ });
198
+ packageType = await packageVersion.getPackageType();
199
+ break;
200
+ case '0Ho':
201
+ // eslint-disable-next-line no-case-declarations
202
+ const pkg = new package_1.Package({
203
+ packageAliasOrId: this.requestedPackageId,
204
+ project: this.options.project,
205
+ connection: this.options.connection,
206
+ });
207
+ packageType = await pkg.getType();
208
+ break;
209
+ }
210
+ if (packageType !== 'Managed') {
211
+ throw messages.createError('unlockedPackageError');
212
+ }
213
+ }
190
214
  async getPackageVersion(nodeId) {
191
215
  const query = `${SELECT_PACKAGE_VERSION} WHERE SubscriberPackageVersionId = '${nodeId}'`;
192
216
  try {
@@ -205,14 +229,7 @@ class PackageAncestry extends kit_1.AsyncCreatable {
205
229
  async findRootsForPackage() {
206
230
  // Check to see if the package is an unlocked package
207
231
  // if so, throw and error since ancestry only applies to managed packages
208
- const query = `${SELECT_PACKAGE_CONTAINER_OPTIONS} WHERE Id = '${this.requestedPackageId}'`;
209
- const packageTypeResults = await this.options.connection.tooling.query(query);
210
- if (packageTypeResults?.records?.length === 0) {
211
- throw messages.createError('invalidId', [this.requestedPackageId]);
212
- }
213
- else if (packageTypeResults?.records?.length && packageTypeResults?.records[0].ContainerOptions !== 'Managed') {
214
- throw messages.createError('unlockedPackageError');
215
- }
232
+ await this.validatePackageType();
216
233
  const normalQuery = `${SELECT_PACKAGE_VERSION} WHERE AncestorId = NULL AND Package2Id = '${this.requestedPackageId}' ${releasedOnlyFilter}`;
217
234
  const subscriberPackageVersions = (await this.options.connection.tooling.query(normalQuery)).records?.map((record) => new PackageAncestryNode(record));
218
235
  // The package exists, but there are no versions for the provided package
@@ -254,6 +271,7 @@ class PackageAncestry extends kit_1.AsyncCreatable {
254
271
  }
255
272
  }
256
273
  exports.PackageAncestry = PackageAncestry;
274
+ _PackageAncestry_requestedPackageId = new WeakMap();
257
275
  class AncestryTreeProducer extends tree_1.Tree {
258
276
  constructor(options) {
259
277
  super();
@@ -183,9 +183,8 @@ async function pollForStatusWithInterval(id, retries, packageId, branch, withPro
183
183
  const record = pkgQueryResult.records[0];
184
184
  return `${record.MajorVersion}.${record.MinorVersion}.${record.PatchVersion}-${record.BuildNumber}`;
185
185
  });
186
- // TODO SfProjectJson.addPackageAlias
187
- const newConfig = await (0, utils_1.generatePackageAliasEntry)(connection, withProject, results[0].SubscriberPackageVersionId, packageVersionVersionString, branch, packageId);
188
- withProject.getSfProjectJson().set('packageAliases', newConfig);
186
+ const [alias, id] = await (0, utils_1.generatePackageAliasEntry)(connection, withProject, results[0].SubscriberPackageVersionId, packageVersionVersionString, branch, packageId);
187
+ withProject.getSfProjectJson().addPackageAlias(alias, id);
189
188
  await withProject.getSfProjectJson().write();
190
189
  }
191
190
  await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.convert.success, {
@@ -3,23 +3,13 @@ import { PackageCreateOptions, PackagingSObjects } from '../interfaces';
3
3
  declare type Package2Request = Pick<PackagingSObjects.Package2, 'Name' | 'Description' | 'NamespacePrefix' | 'ContainerOptions' | 'IsOrgDependent' | 'PackageErrorUsername'>;
4
4
  export declare function createPackageRequestFromContext(project: SfProject, options: PackageCreateOptions): Package2Request;
5
5
  /**
6
- * Generate packageDirectory json entry for this package that can be written to sfdx-project.json
6
+ * Create packageDirectory json entry for this package that can be written to sfdx-project.json
7
7
  *
8
8
  * @param project
9
9
  * @param packageId the 0Ho id of the package to create the entry for
10
10
  * @private
11
11
  */
12
- export declare function generatePackageDirEntry(project: SfProject, options: PackageCreateOptions): PackageDir[] | NamedPackageDir[];
13
- /**
14
- * Generate package alias json entry for this package that can be written to sfdx-project.json
15
- *
16
- * @param context
17
- * @param packageId the 0Ho id of the package to create the alias entry for
18
- * @private
19
- */
20
- export declare function generatePackageAliasEntry(project: SfProject, options: PackageCreateOptions, packageId: string): {
21
- [key: string]: string;
22
- };
12
+ export declare function createPackageDirEntry(project: SfProject, options: PackageCreateOptions): PackageDir | NamedPackageDir;
23
13
  export declare function createPackage(connection: Connection, project: SfProject, options: PackageCreateOptions): Promise<{
24
14
  Id: string;
25
15
  }>;
@@ -6,10 +6,11 @@
6
6
  * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.createPackage = exports.generatePackageAliasEntry = exports.generatePackageDirEntry = exports.createPackageRequestFromContext = void 0;
9
+ exports.createPackage = exports.createPackageDirEntry = exports.createPackageRequestFromContext = void 0;
10
10
  const core_1 = require("@salesforce/core");
11
11
  const ts_types_1 = require("@salesforce/ts-types");
12
12
  const pkgUtils = require("../utils/packageUtils");
13
+ const packageUtils_1 = require("../utils/packageUtils");
13
14
  core_1.Messages.importMessagesDirectory(__dirname);
14
15
  const messages = core_1.Messages.loadMessages('@salesforce/packaging', 'package_create');
15
16
  function createPackageRequestFromContext(project, options) {
@@ -25,61 +26,39 @@ function createPackageRequestFromContext(project, options) {
25
26
  }
26
27
  exports.createPackageRequestFromContext = createPackageRequestFromContext;
27
28
  /**
28
- * Generate packageDirectory json entry for this package that can be written to sfdx-project.json
29
+ * Create packageDirectory json entry for this package that can be written to sfdx-project.json
29
30
  *
30
31
  * @param project
31
32
  * @param packageId the 0Ho id of the package to create the entry for
32
33
  * @private
33
34
  */
34
- function generatePackageDirEntry(project, options) {
35
- // TODO: use SfProjectJson#addPackageDirectory for this maintenance
36
- let packageDirs = project.getPackageDirectories();
35
+ function createPackageDirEntry(project, options) {
36
+ let packageDirs = project.getSfProjectJson().getContents().packageDirectories;
37
+ let isNew = false;
37
38
  if (!packageDirs) {
38
39
  packageDirs = [];
39
40
  }
40
- // add an entry if it doesn't exist
41
- // or update an existing entry if it matches path but has no package or id attribute (W-5092620)
42
- let packageDir = project.getPackage(options.name) ||
43
- project
44
- .getPackageDirectories()
45
- // TODO: I don't understand where id is coming from, because it is not in sfdx-project.json schema
46
- .find((pd) => pd.path === options.path && !pd.id && !pd.package);
47
- if (packageDir) {
48
- // update existing entry
49
- packageDir.package = options.name;
50
- packageDir.versionName ?? (packageDir.versionName = pkgUtils.DEFAULT_PACKAGE_DIR.versionName);
51
- packageDir.versionNumber ?? (packageDir.versionNumber = pkgUtils.DEFAULT_PACKAGE_DIR.versionNumber);
52
- // set as default if this is the only entry or no other entry is the default
53
- if (!Reflect.getOwnPropertyDescriptor(packageDir, 'default')) {
54
- packageDir.default = !pkgUtils.getConfigPackageDirectory(packageDirs, 'default', true);
55
- }
56
- }
57
- else {
58
- // add new entry
41
+ // see if package exists (exists means it has an id or package)
42
+ let packageDir = packageDirs.find((pd) => pd.path === options.path && !pd.id && !pd.package);
43
+ if (!packageDir) {
44
+ // no match - create a new one
45
+ isNew = true;
59
46
  packageDir = pkgUtils.DEFAULT_PACKAGE_DIR;
60
- packageDir.package = options.name;
61
- // set as default if this is the only entry or no other entry is the default
62
- packageDir.default = !pkgUtils.getConfigPackageDirectory(packageDirs, 'default', true);
63
- packageDir.path = options.path;
64
- packageDirs.push(packageDir);
47
+ packageDir.path = packageDir.path || options.path;
65
48
  }
66
- return packageDirs;
67
- }
68
- exports.generatePackageDirEntry = generatePackageDirEntry;
69
- /**
70
- * Generate package alias json entry for this package that can be written to sfdx-project.json
71
- *
72
- * @param context
73
- * @param packageId the 0Ho id of the package to create the alias entry for
74
- * @private
75
- */
76
- function generatePackageAliasEntry(project, options, packageId) {
77
- const packageAliases = project.getSfProjectJson().getContents().packageAliases || {};
78
- const packageName = options.name;
79
- packageAliases[packageName] = packageId;
80
- return packageAliases;
49
+ if (packageDirs.length === 0) {
50
+ packageDir.default = true;
51
+ }
52
+ else if (isNew) {
53
+ packageDir.default = !packageDirs.find((pd) => pd.default);
54
+ }
55
+ packageDir.package = packageDir.package || options.name;
56
+ packageDir.versionName = packageDir.versionName || pkgUtils.DEFAULT_PACKAGE_DIR.versionName;
57
+ packageDir.versionNumber = packageDir.versionNumber || pkgUtils.DEFAULT_PACKAGE_DIR.versionNumber;
58
+ packageDir.versionDescription = packageDir.versionDescription || options.description;
59
+ return packageDir;
81
60
  }
82
- exports.generatePackageAliasEntry = generatePackageAliasEntry;
61
+ exports.createPackageDirEntry = createPackageDirEntry;
83
62
  async function createPackage(connection, project, options) {
84
63
  // strip trailing slash from path param
85
64
  options.path = options.path.replace(/\/$/, '');
@@ -89,8 +68,8 @@ async function createPackage(connection, project, options) {
89
68
  .sobject('Package2')
90
69
  .create(request)
91
70
  .catch((err) => {
92
- const error = (0, ts_types_1.isString)(err) ? err : err.message;
93
- throw core_1.SfError.wrap(error);
71
+ const error = (0, ts_types_1.isString)(err) ? new Error(err) : err;
72
+ throw core_1.SfError.wrap((0, packageUtils_1.applyErrorAction)((0, packageUtils_1.massageErrorMessage)(error)));
94
73
  });
95
74
  if (!createResult.success) {
96
75
  throw pkgUtils.combineSaveErrors('Package2', 'create', createResult.errors);
@@ -102,12 +81,10 @@ async function createPackage(connection, project, options) {
102
81
  }
103
82
  const record = queryResult.records[0];
104
83
  if (!process.env.SFDX_PROJECT_AUTOUPDATE_DISABLE_FOR_PACKAGE_CREATE) {
105
- const packageDirectory = generatePackageDirEntry(project, options);
106
- const packageAliases = generatePackageAliasEntry(project, options, record.Id);
107
- const projectJson = project.getSfProjectJson();
108
- projectJson.set('packageDirectories', packageDirectory);
109
- projectJson.set('packageAliases', packageAliases);
110
- await projectJson.write();
84
+ const packageDirectory = createPackageDirEntry(project, options);
85
+ project.getSfProjectJson().addPackageDirectory(packageDirectory);
86
+ project.getSfProjectJson().addPackageAlias(options.name, record.Id);
87
+ await project.getSfProjectJson().write();
111
88
  }
112
89
  return { Id: record.Id };
113
90
  }
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.deletePackage = void 0;
10
10
  const pkgUtils = require("../utils/packageUtils");
11
11
  const utils_1 = require("../utils");
12
+ const packageUtils_1 = require("../utils/packageUtils");
12
13
  async function deletePackage(idOrAlias, project, connection, undelete) {
13
14
  const packageId = pkgUtils.getPackageIdFromAlias(idOrAlias, project);
14
15
  pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, packageId);
@@ -16,7 +17,9 @@ async function deletePackage(idOrAlias, project, connection, undelete) {
16
17
  request.Id = packageId;
17
18
  const isUndelete = undelete;
18
19
  request.IsDeprecated = !isUndelete;
19
- const updateResult = await connection.tooling.update('Package2', request);
20
+ const updateResult = await connection.tooling.update('Package2', request).catch((err) => {
21
+ throw (0, packageUtils_1.applyErrorAction)((0, packageUtils_1.massageErrorMessage)(err));
22
+ });
20
23
  if (!updateResult.success) {
21
24
  throw (0, utils_1.combineSaveErrors)('Package2', 'update', updateResult.errors);
22
25
  }
@@ -1,19 +1,12 @@
1
1
  import { Connection } from '@salesforce/core';
2
- import { Optional } from '@salesforce/ts-types';
2
+ import { QueryResult } from 'jsforce';
3
3
  import { Duration } from '@salesforce/kit';
4
- import { PackagingSObjects, PackageInstallOptions, PackageInstallCreateRequest } from '../interfaces';
4
+ import { PackagingSObjects, PackageInstallCreateRequest, PackageType, PackageInstallOptions } from '../interfaces';
5
5
  import PackageInstallRequest = PackagingSObjects.PackageInstallRequest;
6
- export declare function installPackage(connection: Connection, pkgInstallCreateRequest: PackageInstallCreateRequest, options?: PackageInstallOptions): Promise<PackageInstallRequest>;
7
- /**
8
- * Returns an array of RSS and CSP external sites for the package.
9
- *
10
- * @param connection The `Connection` object to the org.
11
- * @param subscriberPackageVersionId The ID of the subscriber package version (begins with "04t")
12
- * @param installationKey The installation key (if any) for the subscriber package version.
13
- * @returns an array of RSS and CSP site URLs, or undefined if the package doesn't have any.
14
- */
15
- export declare function getExternalSites(connection: Connection, subscriberPackageVersionId: string, installationKey?: string): Promise<Optional<string[]>>;
16
- export declare function getStatus(connection: Connection, installRequestId: string): Promise<PackageInstallRequest>;
6
+ export declare function createPackageInstallRequest(connection: Connection, pkgInstallCreateRequest: PackageInstallCreateRequest, packageType: PackageType): Promise<PackagingSObjects.PackageInstallRequest>;
7
+ export declare function getStatus(connection: Connection, packageInstallRequestId: string): Promise<PackageInstallRequest>;
17
8
  export declare function isErrorFromSPVQueryRestriction(err: Error): boolean;
18
9
  export declare function isErrorPackageNotAvailable(err: Error): boolean;
19
- export declare function waitForPublish(connection: Connection, subscriberPackageVersionId: string, timeout: number | Duration, installationKey?: string): Promise<void>;
10
+ export declare function getInstallationStatus(subscriberPackageVersionId: string, installationKey: string, connection: Connection): Promise<QueryResult<PackagingSObjects.SubscriberPackageVersion>>;
11
+ export declare function waitForPublish(connection: Connection, subscriberPackageVersionId: string, frequency: number | Duration, timeout: number | Duration, installationKey?: string): Promise<void>;
12
+ export declare function pollStatus(connection: Connection, installRequestId: string, options: PackageInstallOptions): Promise<PackageInstallRequest>;
@@ -6,13 +6,12 @@
6
6
  * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.waitForPublish = exports.isErrorPackageNotAvailable = exports.isErrorFromSPVQueryRestriction = exports.getStatus = exports.getExternalSites = exports.installPackage = void 0;
9
+ exports.pollStatus = exports.waitForPublish = exports.getInstallationStatus = exports.isErrorPackageNotAvailable = exports.isErrorFromSPVQueryRestriction = exports.getStatus = exports.createPackageInstallRequest = void 0;
10
10
  const core_1 = require("@salesforce/core");
11
11
  const ts_types_1 = require("@salesforce/ts-types");
12
- const kit_1 = require("@salesforce/kit");
13
12
  const utils_1 = require("../utils");
14
- const constants_1 = require("../constants");
15
13
  const interfaces_1 = require("../interfaces");
14
+ const constants_1 = require("../constants");
16
15
  core_1.Messages.importMessagesDirectory(__dirname);
17
16
  const installMsgs = core_1.Messages.loadMessages('@salesforce/packaging', 'package_install');
18
17
  let logger;
@@ -22,27 +21,7 @@ const getLogger = () => {
22
21
  }
23
22
  return logger;
24
23
  };
25
- /**
26
- * Given 04t the package type type (Managed, Unlocked, Locked(deprecated?))
27
- *
28
- * @param packageVersionId the 04t
29
- * @param connection For tooling query
30
- * @param installKey For tooling query, if an installation key is applicable to the package version it must be passed in the queries
31
- * @throws Error with message when package2 cannot be found
32
- */
33
- async function getPackageTypeBy04t(packageVersionId, connection, installKey) {
34
- let query = `SELECT Package2ContainerOptions FROM SubscriberPackageVersion WHERE id ='${packageVersionId}'`;
35
- if (installKey) {
36
- const escapedInstallationKey = installKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
37
- query += ` AND InstallationKey ='${escapedInstallationKey}'`;
38
- }
39
- const queryResult = await connection.tooling.query(query);
40
- if (!queryResult || queryResult.records === null || queryResult.records.length === 0) {
41
- throw installMsgs.createError('errorInvalidPackageId', [packageVersionId]);
42
- }
43
- return queryResult.records[0].Package2ContainerOptions;
44
- }
45
- async function installPackage(connection, pkgInstallCreateRequest, options) {
24
+ async function createPackageInstallRequest(connection, pkgInstallCreateRequest, packageType) {
46
25
  const defaults = {
47
26
  ApexCompileType: 'all',
48
27
  EnableRss: false,
@@ -55,9 +34,8 @@ async function installPackage(connection, pkgInstallCreateRequest, options) {
55
34
  if (request.Password) {
56
35
  request.Password = (0, utils_1.escapeInstallationKey)(request.Password);
57
36
  }
58
- const pkgType = await getPackageTypeBy04t(request.SubscriberPackageVersionKey, connection, request.Password);
59
37
  // Only unlocked packages can change the UpgradeType and ApexCompile options from the defaults.
60
- if (pkgType !== 'Unlocked') {
38
+ if (packageType !== 'Unlocked') {
61
39
  if (request.UpgradeType !== defaults.UpgradeType) {
62
40
  const msg = installMsgs.getMessage('upgradeTypeOnlyForUnlockedWarning');
63
41
  await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.install.warning, msg);
@@ -79,106 +57,13 @@ async function installPackage(connection, pkgInstallCreateRequest, options) {
79
57
  result.errors.toString(),
80
58
  ]);
81
59
  }
82
- if (options?.pollingTimeout == null) {
83
- return getStatus(connection, packageInstallRequestId);
84
- }
85
- else {
86
- return pollStatus(connection, packageInstallRequestId, options);
87
- }
60
+ return getStatus(connection, packageInstallRequestId);
88
61
  }
89
- exports.installPackage = installPackage;
90
- /**
91
- * Returns an array of RSS and CSP external sites for the package.
92
- *
93
- * @param connection The `Connection` object to the org.
94
- * @param subscriberPackageVersionId The ID of the subscriber package version (begins with "04t")
95
- * @param installationKey The installation key (if any) for the subscriber package version.
96
- * @returns an array of RSS and CSP site URLs, or undefined if the package doesn't have any.
97
- */
98
- async function getExternalSites(connection, subscriberPackageVersionId, installationKey) {
99
- const queryNoKey = `SELECT RemoteSiteSettings, CspTrustedSites FROM SubscriberPackageVersion WHERE Id ='${subscriberPackageVersionId}'`;
100
- let queryResult;
101
- try {
102
- const escapedInstallationKey = installationKey ? (0, utils_1.escapeInstallationKey)(installationKey) : null;
103
- const queryWithKey = `${queryNoKey} AND InstallationKey ='${escapedInstallationKey}'`;
104
- getLogger().debug(`Checking package: [${subscriberPackageVersionId}] for external sites`);
105
- queryResult = await connection.tooling.query(queryWithKey);
106
- }
107
- catch (e) {
108
- // First check for Implementation Restriction error that is enforced in 214, before it was possible to query
109
- // against InstallationKey, otherwise surface the error.
110
- if (e instanceof Error && isErrorFromSPVQueryRestriction(e)) {
111
- queryResult = await connection.tooling.query(queryNoKey);
112
- }
113
- else {
114
- throw e;
115
- }
116
- }
117
- if (queryResult?.records?.length > 0) {
118
- const record = queryResult.records[0];
119
- const rssUrls = record.RemoteSiteSettings.settings.map((rss) => rss.url);
120
- const cspUrls = record.CspTrustedSites.settings.map((csp) => csp.endpointUrl);
121
- const sites = [...rssUrls, ...cspUrls];
122
- if (sites.length) {
123
- return sites;
124
- }
125
- }
126
- }
127
- exports.getExternalSites = getExternalSites;
128
- async function getStatus(connection, installRequestId) {
129
- return (await connection.tooling.retrieve('PackageInstallRequest', installRequestId));
62
+ exports.createPackageInstallRequest = createPackageInstallRequest;
63
+ async function getStatus(connection, packageInstallRequestId) {
64
+ return (await connection.tooling.retrieve('PackageInstallRequest', packageInstallRequestId));
130
65
  }
131
66
  exports.getStatus = getStatus;
132
- // internal
133
- async function pollStatus(connection, installRequestId, options) {
134
- let packageInstallRequest;
135
- const { pollingFrequency, pollingTimeout } = options;
136
- let frequency;
137
- if (pollingFrequency != null) {
138
- frequency = (0, ts_types_1.isNumber)(pollingFrequency) ? kit_1.Duration.milliseconds(pollingFrequency) : pollingFrequency;
139
- }
140
- else {
141
- frequency = kit_1.Duration.milliseconds(constants_1.consts.PACKAGE_INSTALL_POLL_FREQUENCY);
142
- }
143
- let timeout;
144
- if (pollingTimeout != null) {
145
- timeout = (0, ts_types_1.isNumber)(pollingTimeout) ? kit_1.Duration.minutes(pollingTimeout) : pollingTimeout;
146
- }
147
- else {
148
- timeout = kit_1.Duration.minutes(constants_1.consts.PACKAGE_INSTALL_POLL_TIMEOUT);
149
- }
150
- const pollingOptions = {
151
- frequency,
152
- timeout,
153
- poll: async () => {
154
- packageInstallRequest = await getStatus(connection, installRequestId);
155
- getLogger().debug(installMsgs.getMessage('packageInstallPolling', [packageInstallRequest?.Status]));
156
- await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.install.status, packageInstallRequest);
157
- if (['SUCCESS', 'ERROR'].includes(packageInstallRequest?.Status)) {
158
- return { completed: true, payload: packageInstallRequest };
159
- }
160
- return { completed: false };
161
- },
162
- };
163
- const pollingClient = await core_1.PollingClient.create(pollingOptions);
164
- try {
165
- getLogger().debug(`Polling for PackageInstallRequest status. Package ID = ${installRequestId}`);
166
- getLogger().debug(`Polling frequency (ms): ${pollingOptions.frequency.milliseconds}`);
167
- getLogger().debug(`Polling timeout (min): ${pollingOptions.timeout.minutes}`);
168
- await pollingClient.subscribe();
169
- return packageInstallRequest;
170
- }
171
- catch (e) {
172
- const errMsg = e instanceof Error ? e.message : (0, ts_types_1.isString)(e) ? e : 'polling timed out';
173
- const error = new core_1.SfError(errMsg, 'PackageInstallTimeout');
174
- error.setData(packageInstallRequest);
175
- if (error.stack && e.stack) {
176
- // add the original stack to this new error
177
- error.stack += `\nDUE TO:\n${e.stack}`;
178
- }
179
- throw error;
180
- }
181
- }
182
67
  // determines if error is from malformed SubscriberPackageVersion query
183
68
  // this is in place to allow cli to run against app version 214, where SPV queries
184
69
  // do not require installation key
@@ -191,45 +76,39 @@ function isErrorPackageNotAvailable(err) {
191
76
  return err.name === 'UNKNOWN_EXCEPTION' || err.name === 'PACKAGE_UNAVAILABLE';
192
77
  }
193
78
  exports.isErrorPackageNotAvailable = isErrorPackageNotAvailable;
194
- async function waitForPublish(connection, subscriberPackageVersionId, timeout, installationKey) {
79
+ async function getInstallationStatus(subscriberPackageVersionId, installationKey, connection) {
80
+ const QUERY_NO_KEY = `SELECT Id, SubscriberPackageId, InstallValidationStatus FROM SubscriberPackageVersion WHERE Id ='${subscriberPackageVersionId}'`;
81
+ const escapedInstallationKey = installationKey ? (0, utils_1.escapeInstallationKey)(installationKey) : null;
82
+ const queryWithKey = `${QUERY_NO_KEY} AND InstallationKey ='${escapedInstallationKey}'`;
83
+ return connection.tooling.query(queryWithKey);
84
+ }
85
+ exports.getInstallationStatus = getInstallationStatus;
86
+ async function waitForPublish(connection, subscriberPackageVersionId, frequency, timeout, installationKey) {
87
+ const pollingTimeout = (0, utils_1.numberToDuration)(timeout || 0);
88
+ if (pollingTimeout.milliseconds <= 0) {
89
+ return;
90
+ }
195
91
  let queryResult;
92
+ let installValidationStatus;
196
93
  const pollingOptions = {
197
- frequency: kit_1.Duration.milliseconds(constants_1.consts.PACKAGE_INSTALL_POLL_FREQUENCY),
198
- timeout: (0, ts_types_1.isNumber)(timeout) ? kit_1.Duration.minutes(timeout) : timeout,
94
+ frequency: (0, utils_1.numberToDuration)(frequency || 0),
95
+ timeout: pollingTimeout,
199
96
  poll: async () => {
200
- const QUERY_NO_KEY = `SELECT Id, SubscriberPackageId, InstallValidationStatus FROM SubscriberPackageVersion WHERE Id ='${subscriberPackageVersionId}'`;
201
- try {
202
- const escapedInstallationKey = installationKey ? (0, utils_1.escapeInstallationKey)(installationKey) : null;
203
- const queryWithKey = `${QUERY_NO_KEY} AND InstallationKey ='${escapedInstallationKey}'`;
204
- queryResult = await connection.tooling.query(queryWithKey);
205
- }
206
- catch (e) {
207
- // Check first for Implementation Restriction error that is enforced in 214, before it was possible to query
208
- // against InstallationKey, otherwise surface the error.
209
- if (e instanceof Error && isErrorFromSPVQueryRestriction(e)) {
210
- queryResult = await connection.tooling.query(QUERY_NO_KEY);
211
- }
212
- else {
213
- if (e instanceof Error && !isErrorPackageNotAvailable(e)) {
214
- throw e;
215
- }
216
- }
217
- }
97
+ queryResult = await getInstallationStatus(subscriberPackageVersionId, installationKey, connection);
218
98
  // Continue retrying if there is no record
219
99
  // or for an InstallValidationStatus of PACKAGE_UNAVAILABLE (replication to the subscriber's instance has not completed)
220
100
  // or for an InstallValidationStatus of UNINSTALL_IN_PROGRESS
221
- let installValidationStatus;
222
101
  if (queryResult?.records?.length) {
223
102
  installValidationStatus = queryResult.records[0].InstallValidationStatus;
224
103
  await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.install['subscriber-status'], installValidationStatus);
225
104
  if (!['PACKAGE_UNAVAILABLE', 'UNINSTALL_IN_PROGRESS'].includes(installValidationStatus)) {
226
- return { completed: true, payload: queryResult };
105
+ return { completed: true, payload: installValidationStatus };
227
106
  }
228
107
  }
229
108
  const tokens = installValidationStatus ? [` Status = ${installValidationStatus}`] : [];
230
109
  getLogger().debug(installMsgs.getMessage('publishWaitProgress', tokens));
231
110
  await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.install['subscriber-status'], installValidationStatus);
232
- return { completed: false, payload: queryResult };
111
+ return { completed: false, payload: installValidationStatus };
233
112
  },
234
113
  };
235
114
  const pollingClient = await core_1.PollingClient.create(pollingOptions);
@@ -242,7 +121,7 @@ async function waitForPublish(connection, subscriberPackageVersionId, timeout, i
242
121
  catch (e) {
243
122
  // if polling timed out
244
123
  const error = installMsgs.createError('subscriberPackageVersionNotPublished');
245
- error.setData(queryResult);
124
+ error.setData(queryResult?.records[0]);
246
125
  if (error.stack && e.stack) {
247
126
  // append the original stack to this new error
248
127
  error.stack += `\nDUE TO:\n${e.stack}`;
@@ -251,4 +130,42 @@ async function waitForPublish(connection, subscriberPackageVersionId, timeout, i
251
130
  }
252
131
  }
253
132
  exports.waitForPublish = waitForPublish;
133
+ async function pollStatus(connection, installRequestId, options) {
134
+ let packageInstallRequest;
135
+ const { pollingFrequency, pollingTimeout } = options;
136
+ const frequency = (0, utils_1.numberToDuration)(pollingFrequency || constants_1.consts.PACKAGE_INSTALL_POLL_FREQUENCY);
137
+ const timeout = (0, utils_1.numberToDuration)(pollingTimeout || constants_1.consts.PACKAGE_INSTALL_POLL_TIMEOUT);
138
+ const pollingOptions = {
139
+ frequency,
140
+ timeout,
141
+ poll: async () => {
142
+ packageInstallRequest = await getStatus(connection, installRequestId);
143
+ getLogger().debug(installMsgs.getMessage('packageInstallPolling', [packageInstallRequest?.Status]));
144
+ await core_1.Lifecycle.getInstance().emit(interfaces_1.PackageEvents.install.status, packageInstallRequest);
145
+ if (['SUCCESS', 'ERROR'].includes(packageInstallRequest?.Status)) {
146
+ return { completed: true, payload: packageInstallRequest };
147
+ }
148
+ return { completed: false };
149
+ },
150
+ };
151
+ const pollingClient = await core_1.PollingClient.create(pollingOptions);
152
+ try {
153
+ getLogger().debug(`Polling for PackageInstallRequest status. Package ID = ${installRequestId}`);
154
+ getLogger().debug(`Polling frequency (ms): ${pollingOptions.frequency.milliseconds}`);
155
+ getLogger().debug(`Polling timeout (min): ${pollingOptions.timeout.minutes}`);
156
+ await pollingClient.subscribe();
157
+ return packageInstallRequest;
158
+ }
159
+ catch (e) {
160
+ const errMsg = e instanceof Error ? e.message : (0, ts_types_1.isString)(e) ? e : 'polling timed out';
161
+ const error = new core_1.SfError(errMsg, 'PackageInstallTimeout');
162
+ error.setData(packageInstallRequest);
163
+ if (error.stack && e.stack) {
164
+ // add the original stack to this new error
165
+ error.stack += `\nDUE TO:\n${e.stack}`;
166
+ }
167
+ throw error;
168
+ }
169
+ }
170
+ exports.pollStatus = pollStatus;
254
171
  //# sourceMappingURL=packageInstall.js.map