/
package.ts
316 lines (291 loc) · 9.5 KB
/
package.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import type { Schema } from '@jsforce/jsforce-node';
import { Connection, Messages, SfError, SfProject } from '@salesforce/core';
import {
ConvertPackageOptions,
PackageCreateOptions,
PackageOptions,
PackageSaveResult,
PackageType,
PackageUpdateOptions,
PackageVersionCreateRequestResult,
PackageVersionListOptions,
PackageVersionListResult,
PackageVersionMetadataDownloadOptions,
PackageVersionMetadataDownloadResult,
PackagingSObjects,
} from '../interfaces';
import { applyErrorAction, BY_LABEL, massageErrorMessage, validateId } from '../utils/packageUtils';
import { createPackage } from './packageCreate';
import { convertPackage } from './packageConvert';
import { retrievePackageVersionMetadata } from './packageVersionRetrieve';
import { listPackageVersions } from './packageVersionList';
import { deletePackage } from './packageDelete';
import { PackageAncestry } from './packageAncestry';
const packagePrefixes = {
PackageId: '0Ho',
SubscriberPackageVersionId: '04t',
PackageInstallRequestId: '0Hf',
PackageUninstallRequestId: '06y',
};
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/packaging', 'package');
export const Package2Fields = [
'Id',
'IsDeleted',
'CreatedDate',
'CreatedById',
'LastModifiedDate',
'LastModifiedById',
'SystemModstamp',
'SubscriberPackageId',
'Name',
'Description',
'NamespacePrefix',
'ContainerOptions',
'IsDeprecated',
'IsOrgDependent',
'ConvertedFromPackageId',
'PackageErrorUsername',
'AppAnalyticsEnabled',
];
/**
* Provides the ability to list, create, update, delete, convert, and get version
* ancestry for a 2nd generation package.
*
* **Examples**
*
* Create a new instance and get the ID (0Ho):
*
* `const id = new Package({connection, project, packageOrAliasId}).getId();`
*
* Create a new package in the org:
*
* `const myPkg = await Package.create(connection, project, options);`
*
* List all packages in the org:
*
* `const pkgList = await Package.list(connection);`
*/
export class Package {
private readonly packageId: string;
private packageData?: PackagingSObjects.Package2;
public constructor(private options: PackageOptions) {
let packageId = this.options.packageAliasOrId;
if (!packageId.startsWith(packagePrefixes.PackageId)) {
packageId =
this.options.project.getPackageIdFromAlias(this.options.packageAliasOrId) ?? this.options.packageAliasOrId;
if (packageId === this.options.packageAliasOrId) {
throw messages.createError('packageAliasNotFound', [this.options.packageAliasOrId]);
}
}
if (packageId.startsWith(packagePrefixes.PackageId)) {
this.packageId = packageId;
} else {
throw messages.createError('invalidPackageId', [this.options.packageAliasOrId, packagePrefixes.PackageId]);
}
}
/**
* Create a new package.
*
* @param connection - instance of Connection
* @param project - instance of SfProject
* @param options - options for creating a package - see PackageCreateOptions
* @returns Package
*/
public static async create(
connection: Connection,
project: SfProject,
options: PackageCreateOptions
): Promise<{ Id: string }> {
return createPackage(connection, project, options);
}
/**
* Returns all the packages that are available in the org, up to 10,000. If more records are
* needed use the `SF_ORG_MAX_QUERY_LIMIT` env var.
*
* @param connection
*/
public static async list(connection: Connection): Promise<PackagingSObjects.Package2[]> {
const query = `select ${this.getPackage2Fields(
connection
).toString()} from Package2 ORDER BY NamespacePrefix, Name`;
return (await connection.autoFetchQuery<PackagingSObjects.Package2 & Schema>(query, { tooling: true }))?.records;
}
/**
* Returns the package versions in the org.
* See {@link PackageVersionListOptions} for list options
*
* @param connection - connection to the org
* @param project - instance of SfProject
* @param options - see {@link PackageVersionListOptions}
*/
public static async listVersions(
connection: Connection,
project: SfProject,
options?: PackageVersionListOptions
): Promise<PackageVersionListResult[]> {
// resolve/verify packages
const packages = options?.packages?.map((pkg) => {
const id = project.getPackageIdFromAlias(pkg) ?? pkg;
// validate ID
if (id.startsWith('0Ho')) {
validateId(BY_LABEL.PACKAGE_ID, id);
return id;
} else {
throw messages.createError('invalidPackageId', [id, '0Ho']);
}
});
const opts = options ?? {};
opts.packages = packages ?? [];
return (await listPackageVersions(connection, opts)).records;
}
/**
* create a PackageAncestry instance
*
* @param packageId to get version information for
* @param project SfProject instance
* @param connection Hub Org Connection
*/
public static async getAncestry(
packageId: string,
project: SfProject,
connection: Connection
): Promise<PackageAncestry> {
return PackageAncestry.create({
packageId,
project,
connection,
});
}
/**
* Convert a 1st generation package to a 2nd generation package.
* See {@link ConvertPackageOptions} for conversion options.
*
* @param pkgId the 1GP package ID (033) of the package to convert
* @param connection
* @param options {@link ConvertPackageOptions}
* @param project
*/
public static async convert(
pkgId: string,
connection: Connection,
options: ConvertPackageOptions,
project?: SfProject
): Promise<PackageVersionCreateRequestResult> {
return convertPackage(pkgId, connection, options, project);
}
/**
* Download the metadata files for a previously published package version, convert them to source format, and put them into a new project folder within the sfdx project.
*
* @param project
* @param options {@link PackageVersionMetadataDownloadOptions}
* @param connection
* @returns
*/
public static async downloadPackageVersionMetadata(
project: SfProject,
options: PackageVersionMetadataDownloadOptions,
connection: Connection
): Promise<PackageVersionMetadataDownloadResult> {
return retrievePackageVersionMetadata(project, options, connection);
}
private static getPackage2Fields(connection: Connection): string[] {
const apiVersion = connection.getApiVersion();
return Package2Fields.filter((field) => (apiVersion >= '59.0' ? true : field !== 'AppAnalyticsEnabled'));
}
/**
* Returns the package ID of the package.
*
* @returns {string} package ID (0Ho)
*/
public getId(): string {
return this.packageId;
}
/**
* Returns the package type of the package.
*
* @returns {Promise<PackageType>}
*/
public async getType(): Promise<PackageType | undefined> {
return (await this.getPackageData())?.ContainerOptions;
}
/**
* Returns the list of package versions for the package.
* See {@link PackageVersionListOptions} for list options
*
* @param options
* @returns {Promise<PackageVersionListResult[]>}
*/
public async getPackageVersions(options?: PackageVersionListOptions): Promise<PackageVersionListResult[]> {
const packageOptions = {
packages: [this.packageId],
};
return Package.listVersions(this.options.connection, this.options.project, {
...packageOptions,
...options,
});
}
/**
* Deletes the package.
*
*/
public async delete(): Promise<PackageSaveResult> {
return deletePackage(this.getId(), this.options.project, this.options.connection, false);
}
/**
* Un-Deletes the package.
*
*/
public async undelete(): Promise<PackageSaveResult> {
return deletePackage(this.getId(), this.options.project, this.options.connection, true);
}
/**
* Updates the package using the values defined in the options.
* See {@link PackageUpdateOptions} for update options.
*
* @param options
*/
public async update(options: PackageUpdateOptions): Promise<PackageSaveResult> {
try {
// filter out any undefined values and their keys
const opts = Object.fromEntries(
Object.entries(options).filter(([, value]) => value !== undefined)
) as PackageUpdateOptions;
if (opts.AppAnalyticsEnabled !== undefined && this.options.connection.getApiVersion() < '59.0') {
throw messages.createError('appAnalyticsEnabledApiPriorTo59Error');
}
const result = await this.options.connection.tooling.update('Package2', opts);
if (!result.success) {
throw new SfError(result.errors.join(', '));
}
return result;
} catch (err) {
if (err instanceof Error) {
throw applyErrorAction(massageErrorMessage(err));
}
throw err;
}
}
/**
* Returns the package data for the package.
*
* @param force force a refresh of the package data
*/
public async getPackageData(force = false): Promise<PackagingSObjects.Package2 | undefined> {
if (!this.packageData ?? force) {
this.packageData = (await this.options.connection.tooling
.sobject('Package2')
.retrieve(this.packageId)) as PackagingSObjects.Package2;
if (!this.packageData) {
throw messages.createError('packageNotFound', [this.packageId]);
}
}
return this.packageData;
}
}