-
Notifications
You must be signed in to change notification settings - Fork 14
/
packageVersionCreate.ts
1217 lines (1095 loc) · 49.2 KB
/
packageVersionCreate.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 path from 'node:path';
import os from 'node:os';
import fs from 'node:fs';
import {
Connection,
Lifecycle,
Logger,
Messages,
NamedPackageDir,
ScratchOrgInfo,
SfdcUrl,
SfProject,
ScratchOrgSettingsGenerator,
} from '@salesforce/core';
import {
ComponentSet,
ComponentSetBuilder,
ComponentSetOptions,
ConvertResult,
MetadataConverter,
} from '@salesforce/source-deploy-retrieve';
import { isNamedPackagingDirectory, isPackagingDirectory } from '@salesforce/core/project';
import { ensureArray, env } from '@salesforce/kit';
import { XMLParser, XMLBuilder } from 'fast-xml-parser';
import { isString } from '@salesforce/ts-types';
import { PackagePackageDir, PackageDirDependency } from '@salesforce/schemas';
import * as pkgUtils from '../utils/packageUtils';
import {
BY_LABEL,
copyDescriptorProperties,
copyDir,
getPackageVersionId,
getPackageVersionNumber,
uniqid,
validateId,
VERSION_NUMBER_SEP,
zipDir,
} from '../utils/packageUtils';
import {
MDFolderForArtifactOptions,
PackageDescriptorJson,
PackageType,
PackageVersionCreateOptions,
PackageVersionCreateRequest,
PackageVersionCreateRequestResult,
PackageVersionEvents,
PackageXml,
PackagingSObjects,
} from '../interfaces';
import { PackageProfileApi } from './packageProfileApi';
import { byId } from './packageVersionCreateRequest';
import { Package } from './package';
import { BuildNumberToken, VersionNumber } from './versionNumber';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/packaging', 'package_version_create');
const DESCRIPTOR_FILE = 'package2-descriptor.json';
export class PackageVersionCreate {
private apiVersionFromPackageXml: string | undefined;
private readonly project: SfProject;
private readonly connection: Connection;
private packageObject!: NamedPackageDir & PackageDescriptorJson;
private packageId!: string;
private pkg?: Package;
private readonly logger: Logger;
private metadataResolver: MetadataResolver;
public constructor(private options: PackageVersionCreateOptions) {
this.connection = this.options.connection;
this.project = this.options.project;
this.logger = Logger.childFromRoot('packageVersionCreate');
this.metadataResolver = new MetadataResolver();
}
public createPackageVersion(): Promise<PackageVersionCreateRequestResult> {
try {
return this.packageVersionCreate();
} catch (err) {
if (err instanceof Error) {
throw pkgUtils.applyErrorAction(pkgUtils.massageErrorMessage(err));
}
throw err;
}
}
/**
* A dependency in the project config file may be specified using either a subscriber package version id (04t)
* or a package Id (0Ho) + a version number. Additionally, a build number may be the actual build number, or a
* keyword: LATEST or RELEASED (meaning the latest or released build number for a given major.minor.patch).
*
* This method resolves a package Id + version number to a subscriber package version id (04t)
* and adds it as a SubscriberPackageVersionId parameter in the dependency object.
*/
public async retrieveSubscriberPackageVersionId(dependency: PackageDescriptorJson): Promise<string> {
if (!dependency.versionNumber) {
throw messages.createError('errorDependencyPair', [JSON.stringify(dependency)]);
}
if (!dependency.packageId) {
throw messages.createError('errorDependencyPair', [JSON.stringify(dependency)]);
}
const versionNumber = VersionNumber.from(dependency.versionNumber);
const buildNumber = versionNumber.build;
// use the dependency.branch if present otherwise use the branch of the version being created
const branch = dependency.branch ?? this.options.branch;
const branchString = !branch ? 'null' : `'${branch}'`;
// resolve a build number keyword to an actual number, if needed
const resolvedBuildNumber = await this.resolveBuildNumber(versionNumber, dependency.packageId, branch);
// now that we have a full build number, query for the associated 04t.
// because the build number may not be unique across versions, add in conditionals for
// the branch or the RELEASED token (if used)
const branchOrReleasedCondition =
buildNumber === BuildNumberToken.RELEASED_BUILD_NUMBER_TOKEN
? 'AND IsReleased = true'
: `AND Branch = ${branchString}`;
const query = `SELECT SubscriberPackageVersionId FROM Package2Version WHERE Package2Id = '${dependency.packageId}' AND MajorVersion = ${versionNumber.major} AND MinorVersion = ${versionNumber.minor} AND PatchVersion = ${versionNumber.patch} AND BuildNumber = ${resolvedBuildNumber} ${branchOrReleasedCondition}`;
const pkgVerQueryResult = await this.connection.tooling.query<PackagingSObjects.Package2Version>(query);
const subRecords = pkgVerQueryResult.records;
if (!subRecords || subRecords.length !== 1) {
throw messages.createError('versionNumberNotFoundInDevHub', [
dependency.packageId,
branchString,
versionNumber.toString(),
resolvedBuildNumber,
]);
}
// warn user of the resolved build number when LATEST and RELEASED keywords are used
if (versionNumber.isBuildKeyword()) {
versionNumber.build = resolvedBuildNumber;
if (buildNumber === BuildNumberToken.LATEST_BUILD_NUMBER_TOKEN) {
this.logger.info(
messages.getMessage('buildNumberResolvedForLatest', [
dependency.package,
versionNumber.toString(),
branchString,
dependency.subscriberPackageVersionId,
])
);
} else if (buildNumber === BuildNumberToken.RELEASED_BUILD_NUMBER_TOKEN) {
this.logger.info(
messages.getMessage('buildNumberResolvedForReleased', [
dependency.package,
versionNumber.toString(),
dependency.subscriberPackageVersionId,
])
);
}
}
return pkgVerQueryResult.records[0].SubscriberPackageVersionId;
}
/** side effect: removes properties from the passed in dependency! */
private async resolveSubscriberPackageVersionId(dependency: PackageDescriptorJson): Promise<PackageDescriptorJson> {
await this.validateDependencyValues(dependency);
if (dependency.subscriberPackageVersionId) {
delete dependency.package;
// if a 04t id is specified just use it.
return dependency;
}
dependency.subscriberPackageVersionId = await this.retrieveSubscriberPackageVersionId(dependency);
delete dependency.packageId;
delete dependency.package;
delete dependency.versionNumber;
delete dependency.branch;
return dependency;
}
private async validateDependencyValues(dependency: PackageDescriptorJson): Promise<void> {
// If valid 04t package, just return it to be used straight away.
if (dependency.subscriberPackageVersionId) {
pkgUtils.validateId(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, dependency.subscriberPackageVersionId);
return;
}
if (dependency.packageId && dependency.package) {
throw messages.createError('errorPackageAndPackageIdCollision', []);
}
const idOrPackage = dependency.packageId ?? dependency.package;
if (!idOrPackage) {
throw messages.createError('errorPackageOrPackageIdMissing', []);
}
const packageIdFromAlias = this.project.getPackageIdFromAlias(idOrPackage) ?? idOrPackage;
// If valid 04t package, just return it to be used straight away.
if (pkgUtils.validateIdNoThrow(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, packageIdFromAlias)) {
dependency.subscriberPackageVersionId = packageIdFromAlias;
return;
}
if (!packageIdFromAlias || !dependency.versionNumber) {
throw messages.createError('errorDependencyPair', [JSON.stringify(dependency)]);
}
// Just override dependency.packageId value to the resolved alias.
dependency.packageId = packageIdFromAlias;
pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, dependency.packageId);
validateVersionNumber(
dependency.versionNumber,
BuildNumberToken.LATEST_BUILD_NUMBER_TOKEN,
BuildNumberToken.RELEASED_BUILD_NUMBER_TOKEN
);
await this.validatePatchVersion(dependency.versionNumber, dependency.packageId);
// Validate that the Package2 id exists on the server
const query = `SELECT Id FROM Package2 WHERE Id = '${dependency.packageId}'`;
const result = await this.connection.tooling.query<{ Id: string }>(query);
if (!result.records || result.records.length !== 1) {
throw messages.createError('errorNoIdInHub', [dependency.packageId]);
}
}
private async resolveBuildNumber(
versionNumber: VersionNumber,
packageId: string,
branch: string | undefined
): Promise<string> {
if (!versionNumber.isBuildKeyword()) {
// The build number is already specified so just return it using the tooling query result obj structure
return `${versionNumber.build}`;
}
// query for the LATEST or RELEASED build number (excluding deleted versions)
let branchCondition = '';
let releasedCondition = '';
if (versionNumber.build === BuildNumberToken.LATEST_BUILD_NUMBER_TOKEN) {
// respect the branch when querying for LATEST
const branchString = !branch || branch === '' ? 'null' : `'${branch}'`;
branchCondition = `AND Branch = ${branchString}`;
} else if (versionNumber.build === BuildNumberToken.RELEASED_BUILD_NUMBER_TOKEN) {
releasedCondition = 'AND IsReleased = true';
}
const query = `SELECT MAX(BuildNumber) FROM Package2Version WHERE Package2Id = '${packageId}' AND IsDeprecated != true AND MajorVersion = ${versionNumber.major} AND MinorVersion = ${versionNumber.minor} AND PatchVersion = ${versionNumber.patch} ${branchCondition} ${releasedCondition}`;
const results = await this.connection.tooling.query(query);
if (results.records?.length === 0 || results.records[0].expr0 == null) {
if (versionNumber.build === BuildNumberToken.RELEASED_BUILD_NUMBER_TOKEN) {
throw messages.createError('noReleaseVersionFound', [packageId, versionNumber.toString()]);
} else {
throw messages.createError('noReleaseVersionFoundForBranch', [packageId, branch, versionNumber.toString()]);
}
}
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `${results.records[0].expr0}`;
}
private async createRequestObject(
preserveFiles: boolean,
packageVersTmpRoot: string,
packageVersBlobZipFile: string
): Promise<PackageVersionCreateRequest> {
const zipFileBase64 = fs.readFileSync(packageVersBlobZipFile).toString('base64');
const requestObject: PackageVersionCreateRequest = {
Package2Id: this.packageId,
VersionInfo: zipFileBase64,
Tag: this.options.tag,
Branch: this.options.branch,
InstallKey: this.options.installationkey,
Instance: this.options.buildinstance,
SourceOrg: this.options.sourceorg,
CalculateCodeCoverage: this.options.codecoverage ?? false,
SkipValidation: this.options.skipvalidation ?? false,
AsyncValidation: this.options.asyncvalidation ?? false,
// note: the createRequest's Language corresponds to the AllPackageVersion's language
Language: this.options.language,
};
// Ensure we only include the Language property for a connection api version
// of v57.0 or higher.
if (this.connection.getApiVersion() < '57.0') {
if (requestObject.Language) {
this.logger.warn(
`The language option is only valid for API version 57.0 and higher. Ignoring ${requestObject.Language}`
);
}
delete requestObject.Language;
}
// Ensure we only include the async validation property for a connection api version
// of v60.0 or higher.
if (this.connection.getApiVersion() <= '60.0') {
if (requestObject.AsyncValidation) {
this.logger.warn(
`The async validation option is only valid for API version 60.0 and higher. Ignoring ${requestObject.AsyncValidation}`
);
}
delete requestObject.AsyncValidation;
}
if (preserveFiles) {
const message = messages.getMessage('tempFileLocation', [packageVersTmpRoot]);
await Lifecycle.getInstance().emit(PackageVersionEvents.create['preserve-files'], {
location: packageVersTmpRoot,
message,
});
this.logger.info(message);
return requestObject;
} else {
return fs.promises.rm(packageVersTmpRoot, { recursive: true, force: true }).then(() => requestObject);
}
}
/**
* Convert the list of command line options to a JSON object that can be used to create an Package2VersionCreateRequest entity.
*
* @returns {{Package2Id: (*|p|boolean), Package2VersionMetadata: *, Tag: *, Branch: number}}
* @private
*/
private async createPackageVersionCreateRequestFromOptions(): Promise<PackageVersionCreateRequest> {
const preserveFiles = !!(this.options.preserve ?? env.getBoolean('SF_PACKAGE2_VERSION_CREATE_PRESERVE'));
const uniqueHash = uniqid({ template: `${this.packageId}-%s` });
const packageVersTmpRoot = path.join(os.tmpdir(), `${uniqueHash}`);
const packageVersMetadataFolder = path.join(packageVersTmpRoot, 'md-files');
const unpackagedMetadataFolder = path.join(packageVersTmpRoot, 'unpackaged-md-files');
const seedMetadataFolder = path.join(packageVersTmpRoot, 'seed-md-files');
const packageVersProfileFolder = path.join(packageVersMetadataFolder, 'profiles');
const packageVersBlobDirectory = path.join(packageVersTmpRoot, 'package-version-info');
const metadataZipFile = path.join(packageVersBlobDirectory, 'package.zip');
const unpackagedMetadataZipFile = path.join(packageVersBlobDirectory, 'unpackaged-metadata-package.zip');
const seedMetadataZipFile = path.join(packageVersBlobDirectory, 'seed-metadata-package.zip');
const settingsZipFile = path.join(packageVersBlobDirectory, 'settings.zip');
const packageVersBlobZipFile = path.join(packageVersTmpRoot, 'package-version-info.zip');
const sourceBaseDir = path.join(this.project.getPath(), this.packageObject?.path ?? '');
const mdOptions: MDFolderForArtifactOptions = {
deploydir: packageVersMetadataFolder,
sourceDir: sourceBaseDir,
sourceApiVersion: this.project?.getSfProjectJson()?.get('sourceApiVersion'),
};
await fs.promises.mkdir(packageVersBlobDirectory, { recursive: true });
const settingsGenerator = new ScratchOrgSettingsGenerator({ asDirectory: true });
let packageDescriptorJson = structuredClone(this.packageObject) as PackageDescriptorJson;
const apvLanguage = packageDescriptorJson.language;
// Copy all the metadata from the workspace to a tmp folder
const componentSet = await this.metadataResolver.generateMDFolderForArtifact(mdOptions);
this.verifyHasSource(componentSet);
if (packageDescriptorJson.package) {
delete packageDescriptorJson.package;
packageDescriptorJson.id = this.packageId;
}
if (packageDescriptorJson.language) {
// the structuredClone() call above added the packageDir's language to the descriptor;
// remove that from the descriptor here; it will be set correctly from the definitionFile values below
delete packageDescriptorJson.language;
}
const definitionFile = this.options.definitionfile
? this.options.definitionfile
: packageDescriptorJson.definitionFile;
if (definitionFile) {
// package2-descriptor.json sent to the server should contain only the features, snapshot & orgPreferences
// defined in the definition file.
delete packageDescriptorJson.features;
delete packageDescriptorJson.orgPreferences;
delete packageDescriptorJson.definitionFile;
delete packageDescriptorJson.snapshot;
const definitionFilePayload = await fs.promises.readFile(definitionFile, 'utf8');
const definitionFileJson = JSON.parse(definitionFilePayload) as ScratchOrgInfo;
// Load any settings from the definition
await settingsGenerator.extract(definitionFileJson);
if (settingsGenerator.hasSettings() && definitionFileJson.orgPreferences) {
// this is not allowed, exit with an error
throw messages.createError('signupDuplicateSettingsSpecified');
}
packageDescriptorJson = copyDescriptorProperties(packageDescriptorJson, definitionFileJson);
}
this.resolveBuildUserPermissions(packageDescriptorJson);
// All dependencies for the packaging dir should be resolved to an 04t id to be passed to the server.
// (see resolveSubscriberPackageVersionId() for details)
const dependencies = packageDescriptorJson.dependencies;
// branch and APV language can be set via options or packageDirectory; option takes precedence
this.options.branch = this.options.branch ?? packageDescriptorJson.branch;
this.options.language = this.options.language ?? apvLanguage;
const resultValues = await Promise.all(
!dependencies ? [] : dependencies.map((dependency) => this.resolveSubscriberPackageVersionId(dependency))
);
const versionNumber = this.options.versionnumber ?? packageDescriptorJson.versionNumber;
if (!versionNumber) {
throw messages.createError('versionNumberRequired');
}
const ancestorId = await this.getAncestorId(
packageDescriptorJson,
this.options.project,
versionNumber,
!!this.options.skipancestorcheck
);
// If dependencies exist, the resultValues array will contain the dependencies populated with a resolved
// subscriber pkg version id.
if (resultValues.length > 0) {
packageDescriptorJson.dependencies = resultValues as PackageDirDependency[];
}
packageDescriptorJson = cleanPackageDescriptorJson(packageDescriptorJson);
packageDescriptorJson = setPackageDescriptorJsonValues(packageDescriptorJson, this.options, this.logger);
await fs.promises.mkdir(packageVersTmpRoot, { recursive: true });
await fs.promises.mkdir(packageVersBlobDirectory, { recursive: true });
if (Reflect.has(packageDescriptorJson, 'ancestorVersion')) {
delete packageDescriptorJson.ancestorVersion;
}
packageDescriptorJson.ancestorId = ancestorId;
await fs.promises.writeFile(
path.join(packageVersBlobDirectory, DESCRIPTOR_FILE),
JSON.stringify(packageDescriptorJson),
'utf-8'
);
await this.cleanGeneratedPackage({
packageVersMetadataFolder,
packageVersProfileFolder,
unpackagedMetadataFolder,
seedMetadataFolder,
metadataZipFile,
settingsZipFile,
packageVersBlobDirectory,
packageVersBlobZipFile,
unpackagedMetadataZipFile,
seedMetadataZipFile,
settingsGenerator,
});
return this.createRequestObject(preserveFiles, packageVersTmpRoot, packageVersBlobZipFile);
}
private verifyHasSource(result: ConvertResult): void {
if (!result.converted || result.converted?.length === 0) {
throw messages.createError('noSourceInRootDirectory', [this.packageObject.path ?? '<unknown>']);
}
}
private async cleanGeneratedPackage({
packageVersMetadataFolder,
packageVersProfileFolder,
unpackagedMetadataFolder,
seedMetadataFolder,
metadataZipFile,
settingsZipFile,
packageVersBlobDirectory,
packageVersBlobZipFile,
unpackagedMetadataZipFile,
seedMetadataZipFile,
settingsGenerator,
}: {
packageVersMetadataFolder: string;
packageVersProfileFolder: string;
unpackagedMetadataFolder: string;
seedMetadataFolder: string;
metadataZipFile: string;
settingsZipFile: string;
packageVersBlobDirectory: string;
packageVersBlobZipFile: string;
unpackagedMetadataZipFile: string;
seedMetadataZipFile: string;
settingsGenerator: ScratchOrgSettingsGenerator;
}): Promise<void> {
// As part of the source convert process, the package.xml has been written into the tmp metadata directory.
// The package.xml may need to be manipulated due to processing profiles in the workspace or additional
// metadata exclusions. If necessary, read the existing package.xml and then re-write it.
const currentPackageXml = await fs.promises.readFile(path.join(packageVersMetadataFolder, 'package.xml'), 'utf8');
// convert to json
const packageXmlAsJson = packageXmlStringToPackageXmlJson(currentPackageXml);
if (!packageXmlAsJson) {
throw messages.createError('packageXmlDoesNotContainPackage');
}
if (!packageXmlAsJson?.types) {
throw messages.createError('packageXmlDoesNotContainPackageTypes');
}
fs.mkdirSync(packageVersMetadataFolder, { recursive: true });
fs.mkdirSync(packageVersProfileFolder, { recursive: true });
this.apiVersionFromPackageXml = packageXmlAsJson.version;
const sourceApiVersion = this.project?.getSfProjectJson()?.get('sourceApiVersion') as string;
const hasSeedMetadata = await this.metadataResolver.resolveMetadata(
this.packageObject.seedMetadata?.path,
seedMetadataFolder,
'seedMDDirectoryDoesNotExist',
sourceApiVersion
);
let hasUnpackagedMetadata = false;
const unpackagedMetadataPath = this.packageObject.unpackagedMetadata?.path;
if (this.options.codecoverage) {
hasUnpackagedMetadata = await this.metadataResolver.resolveMetadata(
unpackagedMetadataPath,
unpackagedMetadataFolder,
'unpackagedMDDirectoryDoesNotExist',
sourceApiVersion
);
}
let profileExcludeDirs: string[] = [];
if (this.packageObject.scopeProfiles) {
this.logger.debug(
`packageDirectory: ${this.packageObject.name} has 'scopeProfiles' set, so only including profiles from within this directory`
);
// exclude all package dirs except the one being packaged
profileExcludeDirs = this.project
.getPackageDirectories()
.map((packageDir) => {
if (packageDir.path !== this.packageObject.path) {
return packageDir.path;
}
})
.filter((packageDirPath) => packageDirPath) as string[];
} else {
// don't package the profiles from any un-packagedMetadata dir in the project
profileExcludeDirs = this.project
.getPackageDirectories()
.filter(isNamedPackagingDirectory)
.map((packageDir) => packageDir.unpackagedMetadata?.path)
.filter(isString);
let debugMsg = 'Searching for profiles to include from all packageDirectories';
if (profileExcludeDirs?.length) {
debugMsg += ` excluding these unpackagedMetadata dirs: ${profileExcludeDirs.toString()}`;
}
this.logger.debug(debugMsg);
}
const typesArr =
this.options?.profileApi?.filterAndGenerateProfilesForManifest(packageXmlAsJson.types, profileExcludeDirs) ??
packageXmlAsJson.types;
// Next generate profiles and retrieve any profiles that were excluded because they had no matching nodes.
const excludedProfiles = this.options?.profileApi?.generateProfiles(
packageVersProfileFolder,
typesArr,
profileExcludeDirs
);
packageXmlAsJson.types = typesArr.map((type) => {
if (type.name !== 'Profile') return type;
return { ...type, members: type.members.filter((m) => !excludedProfiles?.includes(m)) };
});
const xml = packageXmlJsonToXmlString(packageXmlAsJson);
await fs.promises.writeFile(path.join(packageVersMetadataFolder, 'package.xml'), xml, 'utf-8');
// Zip the packageVersMetadataFolder folder and put the zip in {packageVersBlobDirectory}/package.zip
await zipDir(packageVersMetadataFolder, metadataZipFile);
if (hasSeedMetadata) {
// Zip the seedMetadataFolder folder and put the zip in {packageVersBlobDirectory}/{seedMetadataZipFile}
await zipDir(seedMetadataFolder, seedMetadataZipFile);
}
if (hasUnpackagedMetadata) {
// Zip the unpackagedMetadataFolder folder and put the zip in {packageVersBlobDirectory}/{unpackagedMetadataZipFile}
await zipDir(unpackagedMetadataFolder, unpackagedMetadataZipFile);
}
// Zip up the expanded settings (if present)
if (settingsGenerator.hasSettings()) {
await settingsGenerator.createDeploy();
await settingsGenerator.createDeployPackageContents(this.apiVersionFromPackageXml);
await zipDir(
`${settingsGenerator.getDestinationPath() ?? ''}${path.sep}${settingsGenerator.getShapeDirName()}`,
settingsZipFile
);
}
// Zip the Version Info and package.zip files into another zip
await zipDir(packageVersBlobDirectory, packageVersBlobZipFile);
}
/** side effect: modifies the passed in parameter! */
private resolveBuildUserPermissions(packageDescriptorJson: PackageDescriptorJson): void {
// Process permissionSet and permissionSetLicenses that should be enabled when running Apex tests
// This only applies if code coverage is enabled
if (this.options.codecoverage) {
// Assuming no permission sets are named 0, 0n, null, undefined, false, NaN, and the empty string
if (packageDescriptorJson.apexTestAccess?.permissionSets) {
let permSets = packageDescriptorJson.apexTestAccess.permissionSets;
if (!Array.isArray(permSets)) {
permSets = permSets.split(',');
}
packageDescriptorJson.permissionSetNames = permSets.map((s) => s.trim());
}
if (packageDescriptorJson.apexTestAccess?.permissionSetLicenses) {
let permissionSetLicenses = packageDescriptorJson.apexTestAccess.permissionSetLicenses;
if (!Array.isArray(permissionSetLicenses)) {
permissionSetLicenses = permissionSetLicenses.split(',');
}
packageDescriptorJson.permissionSetLicenseDeveloperNames = permissionSetLicenses.map((s) => s.trim());
}
}
// Process permissionSet and permissionsetLicenses that should be enabled for the package metadata deploy
if (packageDescriptorJson.packageMetadataAccess?.permissionSets) {
let permSets = packageDescriptorJson.packageMetadataAccess.permissionSets;
if (!Array.isArray(permSets)) {
permSets = permSets.split(',');
}
packageDescriptorJson.packageMetadataPermissionSetNames = permSets.map((s) => s.trim());
}
if (packageDescriptorJson.packageMetadataAccess?.permissionSetLicenses) {
let permissionSetLicenses = packageDescriptorJson.packageMetadataAccess.permissionSetLicenses;
if (!Array.isArray(permissionSetLicenses)) {
permissionSetLicenses = permissionSetLicenses.split(',');
}
packageDescriptorJson.packageMetadataPermissionSetLicenseNames = permissionSetLicenses.map((s) => s.trim());
}
delete packageDescriptorJson.apexTestAccess;
delete packageDescriptorJson.packageMetadataAccess;
}
// eslint-disable-next-line complexity
private async packageVersionCreate(): Promise<PackageVersionCreateRequestResult> {
// For the first rollout of validating sfdx-project.json data against schema, make it optional and defaulted
// to false. Validation only occurs if the optional validateschema option has been specified.
if (this.options.validateschema) {
await this.project.getSfProjectJson().schemaValidate();
}
// Check for empty packageDirectories
if (this.project.getPackageDirectories()?.length === 0) {
throw messages.createError('errorEmptyPackageDirs');
}
// either options.packageId or options.path is required
if (!this.options.packageId && !this.options.path) {
throw messages.createError('errorMissingPackageIdOrPath');
}
// establish the package Id (0ho) and load the package directory
let packageName: string | undefined;
let packageObject: NamedPackageDir | undefined;
if (this.options.packageId) {
const pkg = this.options.packageId;
// for backward compatibility allow for a packageDirectory package property to be an id (0Ho) instead of an alias.
packageName = (await this.getPackageDirFromId(pkg))?.package;
if (!packageName) {
packageName = pkg.startsWith('0Ho') ? this.project.getAliasesFromPackageId(pkg).find((alias) => alias) : pkg;
if (!packageName) throw messages.createError('errorMissingPackage', [this.options.packageId]);
}
packageObject = this.project.findPackage(
(namedPackageDir) =>
isPackagingDirectory(namedPackageDir) &&
(namedPackageDir.package === packageName || namedPackageDir.name === packageName)
);
} else {
// We'll either have a package ID or alias, or a directory path
if (!this.options.path) {
throw messages.createError('errorMissingPackagePath', [JSON.stringify(this.options)]);
}
packageObject = this.project.getPackageFromPath(this.options.path);
if (!packageObject || !isPackagingDirectory(packageObject))
throw messages.createError('errorCouldNotFindPackageUsingPath', [this.options.path]);
packageName = packageObject?.package;
}
if (!packageObject) {
throw messages.createError('errorCouldNotFindPackageDir', [
this.options.packageId ? 'packageId or alias' : 'path',
this.options.packageId ?? this.options.path,
]);
} else {
this.packageObject = packageObject;
}
this.packageId = this.project.getPackageIdFromAlias(packageName) ?? packageName;
this.options.profileApi = await PackageProfileApi.create({
project: this.project,
includeUserLicenses: !!this.packageObject.includeProfileUserLicenses,
});
// At this point, the packageIdFromAlias should have been resolved to an Id. Now, we
// need to validate that the Id is correct.
pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, this.packageId);
try {
await this.validateOptionsForPackageType();
} catch (error) {
if (error instanceof Error) {
if (error.name === 'NOT_FOUND') {
// this means the 0Ho package was not found in the org. throw a better error.
throw messages.createError('errorNoIdInHub', [this.packageId]);
}
}
throw error;
}
const request = await this.createPackageVersionCreateRequestFromOptions();
const options = {
multipartFileFields: {
VersionInfo: {
contentType: 'application/zip',
filename: 'package-version-info.zip',
},
},
};
const createResult = await this.connection.tooling.create('Package2VersionCreateRequest', request, options);
if (!createResult.success) {
const errStr = createResult.errors?.join(', ') ?? createResult.errors;
const id: string = createResult.id ?? '';
throw messages.createError('failedToCreatePVCRequest', [id === '' ? '' : ` [${id}]`, errStr.toString()]);
}
return (await byId(createResult.id, this.connection))[0];
}
private async getPackageDirFromId(pkg: string): Promise<PackagePackageDir | undefined> {
if (pkg.startsWith('0Ho')) {
const dir = (await this.project.getSfProjectJson().getPackageDirectories())
.filter(isPackagingDirectory)
.filter((p) => p.package === pkg);
if (dir.length === 1) {
return dir[0];
}
}
}
private async getPackageType(): Promise<PackageType | undefined> {
// this.packageId should be an 0Ho package Id at this point
if (!this.pkg) {
this.pkg = new Package({
packageAliasOrId: this.packageId,
project: this.project,
connection: this.connection,
});
}
return this.pkg.getType();
}
private async validateOptionsForPackageType(): Promise<void> {
if ((await this.getPackageType()) === 'Unlocked') {
// Don't allow scripts in unlocked packages
if (Boolean(this.options.postinstallscript) || this.options.uninstallscript) {
throw messages.createError('errorScriptsNotApplicableToUnlockedPackage');
}
// Don't allow ancestor in unlocked packages
if (Boolean(this.packageObject.ancestorId) || this.packageObject.ancestorVersion) {
throw messages.createError('errorAncestorNotApplicableToUnlockedPackage');
}
}
}
private async validatePatchVersion(versionNumberString: string, packageId: string): Promise<void> {
const query = `SELECT ContainerOptions FROM Package2 WHERE id ='${packageId}'`;
const queryResult = await this.connection.tooling.query(query);
if (queryResult.records === null || queryResult.records.length === 0) {
throw messages.createError('errorInvalidPackageId', [packageId]);
}
// Enforce a patch version of zero (0) for Locked packages only
if (queryResult.records[0].ContainerOptions === 'Locked') {
const versionNumber = VersionNumber.from(versionNumberString);
if (versionNumber.patch !== '0') {
throw messages.createError('errorInvalidPatchNumber', [versionNumberString]);
}
}
}
// eslint-disable-next-line complexity
private async getAncestorId(
packageDescriptorJson: PackageDescriptorJson,
project: SfProject,
versionNumberString: string,
skipAncestorCheck: boolean
): Promise<string> {
// If an id property is present, use it. Otherwise, look up the package id from the package property.
const packageId =
packageDescriptorJson.id ??
project.getPackageIdFromAlias(packageDescriptorJson.package ?? '') ??
packageDescriptorJson.package;
// No need to proceed if Unlocked
if ((await this.getPackageType()) === 'Unlocked') {
return '';
}
let ancestorId = '';
// ancestorID can be alias, 05i, or 04t;
// validate and convert to 05i, as needed
const versionNumber = VersionNumber.from(versionNumberString);
let origSpecifiedAncestor = packageDescriptorJson.ancestorId ?? '';
let highestReleasedVersion: PackagingSObjects.Package2Version | null = null;
const explicitUseHighestRelease =
packageDescriptorJson.ancestorId === BuildNumberToken.HIGHEST_VERSION_NUMBER_TOKEN ||
packageDescriptorJson.ancestorVersion === BuildNumberToken.HIGHEST_VERSION_NUMBER_TOKEN;
const explicitUseNoAncestor =
packageDescriptorJson.ancestorId === BuildNumberToken.NONE_VERSION_NUMBER_TOKEN ||
packageDescriptorJson.ancestorVersion === BuildNumberToken.NONE_VERSION_NUMBER_TOKEN;
if (
(explicitUseHighestRelease || explicitUseNoAncestor) &&
packageDescriptorJson.ancestorId &&
packageDescriptorJson.ancestorVersion
) {
if (packageDescriptorJson.ancestorId !== packageDescriptorJson.ancestorVersion) {
// both ancestorId and ancestorVersion specified, HIGHEST and/or NONE are used, the values disagree
throw messages.createError('errorAncestorIdVersionHighestOrNoneMismatch', [
packageDescriptorJson.ancestorId,
packageDescriptorJson.ancestorVersion,
]);
}
}
if (explicitUseNoAncestor && skipAncestorCheck) {
return '';
} else {
const result = await this.getAncestorIdHighestRelease(
packageId,
versionNumberString,
explicitUseHighestRelease,
skipAncestorCheck
);
if (result.finalAncestorId) {
return result.finalAncestorId;
}
highestReleasedVersion = result.highestReleasedVersion;
}
// at this point if explicitUseHighestRelease=true, we have returned the ancestorId or thrown an error
// highestReleasedVersion should be null only if skipAncestorCheck or if there is no existing released package version
if (!explicitUseNoAncestor && packageDescriptorJson.ancestorId) {
ancestorId = project.getPackageIdFromAlias(packageDescriptorJson.ancestorId) ?? packageDescriptorJson.ancestorId;
validateId([BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, BY_LABEL.PACKAGE_VERSION_ID], ancestorId);
ancestorId = (await getPackageVersionId(ancestorId, this.connection)) ?? '';
}
if (!explicitUseNoAncestor && packageDescriptorJson.ancestorVersion) {
const regNumbers = new RegExp('^[0-9]+$');
const versionNumberSplit = packageDescriptorJson.ancestorVersion.split(VERSION_NUMBER_SEP);
if (
versionNumberSplit.length < 3 ||
versionNumberSplit.length > 4 ||
!versionNumberSplit[0].match(regNumbers) ||
!versionNumberSplit[1].match(regNumbers) ||
!versionNumberSplit[2].match(regNumbers)
) {
throw new Error(
messages.getMessage('errorInvalidAncestorVersionFormat', [packageDescriptorJson.ancestorVersion])
);
}
const query =
'SELECT Id, IsReleased FROM Package2Version ' +
`WHERE Package2Id = '${packageId ?? ''}' AND MajorVersion = ${versionNumberSplit[0]} AND MinorVersion = ${
versionNumberSplit[1]
} AND PatchVersion = ${versionNumberSplit[2]}`;
let queriedAncestorId: string;
const ancestorVersionResult = await this.connection.tooling.query<PackagingSObjects.Package2Version>(query);
if (!ancestorVersionResult.totalSize) {
throw messages.createError('errorNoMatchingAncestor', [packageDescriptorJson.ancestorVersion, packageId]);
} else {
const releasedAncestor = ancestorVersionResult.records.find((rec) => rec.IsReleased === true);
if (!releasedAncestor) {
throw messages.createError('errorAncestorNotReleased', [packageDescriptorJson.ancestorVersion]);
} else {
queriedAncestorId = releasedAncestor.Id;
}
}
// check for discrepancy between queried ancestorId and descriptor's ancestorId
if (packageDescriptorJson?.ancestorId && ancestorId !== queriedAncestorId) {
throw messages.createError('errorAncestorIdVersionMismatch', [
packageDescriptorJson.ancestorVersion,
packageDescriptorJson.ancestorId,
]);
}
ancestorId = queriedAncestorId;
origSpecifiedAncestor = packageDescriptorJson.ancestorVersion;
}
return validateAncestorId(
ancestorId,
highestReleasedVersion,
explicitUseNoAncestor,
versionNumber.patch !== '0',
skipAncestorCheck,
origSpecifiedAncestor
);
}
private async getAncestorIdHighestRelease(
packageId: string | undefined,
versionNumberString: string,
explicitUseHighestRelease: boolean,
skipAncestorCheck: boolean
): Promise<{ finalAncestorId: string | null; highestReleasedVersion: PackagingSObjects.Package2Version | null }> {
type Package2VersionResult = Partial<
Pick<
PackagingSObjects.Package2Version,
'Id' | 'SubscriberPackageVersionId' | 'MajorVersion' | 'MinorVersion' | 'PatchVersion'
>
>;
if (!packageId) {
throw messages.createError('packageIdCannotBeUndefined');
}
const versionNumber = versionNumberString.split(VERSION_NUMBER_SEP);
const isPatch = versionNumber[2] !== '0';
const result: { finalAncestorId: string | null; highestReleasedVersion: PackagingSObjects.Package2Version | null } =
{
finalAncestorId: null,
highestReleasedVersion: null,
};
if (isPatch && explicitUseHighestRelease) {
// based on server-side validation, whatever ancestor is specified for a patch is
// tightly controlled; therefore we only need concern ourselves if explicitUseHighestRelease == true;
// equally applies when skipAncestorCheck == true
// gather appropriate matching major.minor.0
const query =
`SELECT Id FROM Package2Version WHERE Package2Id = '${packageId}' ` +
'AND IsReleased = True AND IsDeprecated = False AND PatchVersion = 0 ' +
`AND MajorVersion = ${versionNumber[0]} AND MinorVersion = ${versionNumber[1]} ` +
'ORDER BY MajorVersion Desc, MinorVersion Desc, PatchVersion Desc, BuildNumber Desc LIMIT 1';
const majorMinorVersionResult = await this.connection.tooling.query<Package2VersionResult>(query);
const majorMinorVersionRecords = majorMinorVersionResult.records;
if (majorMinorVersionRecords && majorMinorVersionRecords?.length === 1 && majorMinorVersionRecords[0]) {
result.finalAncestorId = majorMinorVersionRecords[0].Id ?? null;
} else {
const majorMinorNotFound = `${versionNumber[0]}.${versionNumber[1]}.0`;
throw messages.createError('errorNoMatchingMajorMinorForPatch', [majorMinorNotFound]);
}
} else if (!isPatch && (explicitUseHighestRelease || !skipAncestorCheck)) {
// ancestor must be set to latest released major.minor version
const query =
'SELECT Id, SubscriberPackageVersionId, MajorVersion, MinorVersion, PatchVersion FROM Package2Version ' +
`WHERE Package2Id = '${packageId}' AND IsReleased = True AND IsDeprecated = False AND PatchVersion = 0 ` +
'ORDER BY MajorVersion Desc, MinorVersion Desc, PatchVersion Desc, BuildNumber Desc LIMIT 1';
const highestVersionResult = await this.connection.tooling.query<Package2VersionResult>(query);
const highestVersionRecords = highestVersionResult.records;
if (highestVersionRecords?.[0]) {
result.highestReleasedVersion = highestVersionRecords[0] as PackagingSObjects.Package2Version;
if (explicitUseHighestRelease) {
result.finalAncestorId = result.highestReleasedVersion.Id;
}
} else if (explicitUseHighestRelease) {
// there is no eligible ancestor version
throw messages.createError('errorNoMatchingAncestor', [versionNumberString, packageId]);
}
}
return result;
}
}
export class MetadataResolver {
public async resolveMetadata(
metadataRelativePath: string | undefined,
metadataOutputPath: string,
errorMessageLabel: string,
sourceApiVersion?: string
): Promise<boolean> {
if (metadataRelativePath) {
const metadataFullPath = path.join(process.cwd(), metadataRelativePath);
if (!fs.existsSync(metadataFullPath)) {
throw messages.createError(errorMessageLabel, [metadataRelativePath]);
}
fs.mkdirSync(metadataOutputPath, { recursive: true });
await this.generateMDFolderForArtifact({
deploydir: metadataOutputPath,
sourceDir: metadataFullPath,
sourceApiVersion,
});
return true;
}
return false;
}