-
Notifications
You must be signed in to change notification settings - Fork 69
/
org.ts
1717 lines (1556 loc) · 60.7 KB
/
org.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) 2020, 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
*/
/* eslint-disable class-methods-use-this */
import { join as pathJoin } from 'node:path';
import * as fs from 'node:fs';
import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
import {
AnyFunction,
AnyJson,
ensure,
ensureJsonArray,
ensureString,
isBoolean,
isString,
JsonArray,
JsonMap,
Nullable,
} from '@salesforce/ts-types';
import { HttpRequest, SaveResult } from 'jsforce';
import { Config } from '../config/config';
import { ConfigAggregator } from '../config/configAggregator';
import { ConfigContents } from '../config/configStackTypes';
import { OrgUsersConfig } from '../config/orgUsersConfig';
import { Global } from '../global';
import { Lifecycle } from '../lifecycleEvents';
import { Logger } from '../logger/logger';
import { SfError } from '../sfError';
import { trimTo15 } from '../util/sfdc';
import { WebOAuthServer } from '../webOAuthServer';
import { Messages } from '../messages';
import { StateAggregator } from '../stateAggregator/stateAggregator';
import { PollingClient } from '../status/pollingClient';
import { StatusResult } from '../status/types';
import { Connection, SingleRecordQueryErrors } from './connection';
import { AuthFields, AuthInfo } from './authInfo';
import { scratchOrgCreate, ScratchOrgCreateOptions, ScratchOrgCreateResult } from './scratchOrgCreate';
import { OrgConfigProperties } from './orgConfigProperties';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/core', 'org');
export type OrganizationInformation = {
Name: string;
InstanceName: string;
IsSandbox: boolean;
TrialExpirationDate: string | null;
NamespacePrefix: string | null;
};
export enum OrgTypes {
Scratch = 'scratch',
Sandbox = 'sandbox',
}
export interface StatusEvent {
sandboxProcessObj: SandboxProcessObject;
interval: number;
remainingWait: number;
waitingOnAuth: boolean;
}
export interface ResultEvent {
sandboxProcessObj: SandboxProcessObject;
sandboxRes: SandboxUserAuthResponse;
}
export interface SandboxUserAuthRequest {
sandboxName: string;
clientId: string;
callbackUrl: string;
}
export enum SandboxEvents {
EVENT_STATUS = 'status',
EVENT_ASYNC_RESULT = 'asyncResult',
EVENT_RESULT = 'result',
EVENT_AUTH = 'auth',
EVENT_RESUME = 'resume',
EVENT_MULTIPLE_SBX_PROCESSES = 'multipleMatchingSbxProcesses',
}
export interface SandboxUserAuthResponse {
authUserName: string;
authCode: string;
instanceUrl: string;
loginUrl: string;
}
const resumableSandboxStatus = ['Activating', 'Pending', 'Pending Activation', 'Processing', 'Sampling', 'Completed'];
export function sandboxIsResumable(value: string): boolean {
return resumableSandboxStatus.includes(value);
}
export type SandboxProcessObject = {
Id: string;
Status: string;
SandboxName: string;
SandboxInfoId: string;
LicenseType: string;
CreatedDate: string;
SandboxOrganization?: string;
CopyProgress?: number;
SourceId?: string;
Description?: string;
ApexClassId?: string;
EndDate?: string;
};
const sandboxProcessFields = [
'Id',
'Status',
'SandboxName',
'SandboxInfoId',
'LicenseType',
'CreatedDate',
'CopyProgress',
'SandboxOrganization',
'SourceId',
'Description',
'EndDate',
];
export type SandboxRequest = {
SandboxName: string;
LicenseType?: string;
/** Should match a SandboxInfoId, not a SandboxProcessId */
SourceId?: string;
Description?: string;
};
export type ResumeSandboxRequest = {
SandboxName?: string;
SandboxProcessObjId?: string;
};
// https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_sandboxinfo.htm
export type SandboxInfo = {
Id: string; // 0GQB0000000TVobOAG
IsDeleted: boolean;
CreatedDate: string; // 2023-06-16T18:35:47.000+0000
CreatedById: string; // 005B0000004TiUpIAK
LastModifiedDate: string; // 2023-09-27T20:50:26.000+0000
LastModifiedById: string; // 005B0000004TiUpIAK
SandboxName: string; // must be 10 or less alphanumeric chars
LicenseType: 'DEVELOPER' | 'DEVELOPER PRO' | 'PARTIAL' | 'FULL';
TemplateId?: string; // reference to PartitionLevelScheme
HistoryDays: -1 | 0 | 10 | 20 | 30 | 60 | 90 | 120 | 150 | 180; // full sandboxes only
CopyChatter: boolean;
AutoActivate: boolean; // only editable for an update/refresh
ApexClassId?: string; // apex class ID. Only editable on create.
Description?: string;
SourceId?: string; // SandboxInfoId as the source org used for a clone
// 'ActivationUserGroupId', // Support might be added back in API v61.0 (Summer '24)
CopyArchivedActivities?: boolean; // only for full sandboxes; depends if a license was purchased
};
export type ScratchOrgRequest = Omit<ScratchOrgCreateOptions, 'hubOrg'>;
export type SandboxFields = {
sandboxOrgId: string;
prodOrgUsername: string;
sandboxName?: string;
sandboxUsername?: string;
sandboxProcessId?: string;
sandboxInfoId?: string;
timestamp?: string;
};
/**
* Provides a way to manage a locally authenticated Org.
*
* **See** {@link AuthInfo}
*
* **See** {@link Connection}
*
* **See** {@link Aliases}
*
* **See** {@link Config}
*
* ```
* // Email username
* const org1: Org = await Org.create({ aliasOrUsername: '[email protected]' });
* // The target-org config property
* const org2: Org = await Org.create();
* // Full Connection
* const org3: Org = await Org.create({
* connection: await Connection.create({
* authInfo: await AuthInfo.create({ username: 'username' })
* })
* });
* ```
*
* **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
*/
export class Org extends AsyncOptionalCreatable<Org.Options> {
private status: Org.Status = Org.Status.UNKNOWN;
private configAggregator!: ConfigAggregator;
// Initialized in create
private logger!: ReturnType<Logger['getRawLogger']>;
private connection!: Connection;
private options: Org.Options;
private orgId?: string;
/**
* @ignore
*/
public constructor(options?: Org.Options) {
super(options);
this.options = options ?? {};
}
/**
* create a sandbox from a production org
* 'this' needs to be a production org with sandbox licenses available
*
* @param sandboxReq SandboxRequest options to create the sandbox with
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
*/
public async createSandbox(
sandboxReq: SandboxRequest,
options: { wait?: Duration; interval?: Duration; async?: boolean } = {
wait: Duration.minutes(6),
async: false,
interval: Duration.seconds(30),
}
): Promise<SandboxProcessObject> {
this.logger.debug(sandboxReq, 'CreateSandbox called with SandboxRequest');
const createResult = await this.connection.tooling.create('SandboxInfo', sandboxReq);
this.logger.debug(createResult, 'Return from calling tooling.create');
if (Array.isArray(createResult) || !createResult.success) {
throw messages.createError('sandboxInfoCreateFailed', [JSON.stringify(createResult)]);
}
const sandboxCreationProgress = await this.querySandboxProcessBySandboxInfoId(createResult.id);
this.logger.debug(sandboxCreationProgress, 'Return from calling singleRecordQuery with tooling');
const isAsync = !!options.async;
if (isAsync) {
// The user didn't want us to poll, so simply return the status
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_ASYNC_RESULT, sandboxCreationProgress);
return sandboxCreationProgress;
}
const [wait, pollInterval] = this.validateWaitOptions(options);
this.logger.debug(
sandboxCreationProgress,
`create - pollStatusAndAuth sandboxProcessObj, max wait time of ${wait.minutes} minutes`
);
return this.pollStatusAndAuth({
sandboxProcessObj: sandboxCreationProgress,
wait,
pollInterval,
});
}
/**
* Refresh (update) a sandbox from a production org.
* 'this' needs to be a production org with sandbox licenses available
*
* @param sandboxInfo SandboxInfo to update the sandbox with
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
*/
public async refreshSandbox(
sandboxInfo: SandboxInfo,
options: { wait?: Duration; interval?: Duration; async?: boolean } = {
wait: Duration.minutes(6),
async: false,
interval: Duration.seconds(30),
}
): Promise<SandboxProcessObject> {
this.logger.debug(sandboxInfo, 'RefreshSandbox called with SandboxInfo');
const refreshResult = await this.connection.tooling.update('SandboxInfo', sandboxInfo);
this.logger.debug(refreshResult, 'Return from calling tooling.update');
if (!refreshResult.success) {
throw messages.createError('sandboxInfoRefreshFailed', [JSON.stringify(refreshResult)]);
}
const soql = `SELECT ${sandboxProcessFields.join(',')} FROM SandboxProcess WHERE SandboxName='${
sandboxInfo.SandboxName
}' ORDER BY CreatedDate DESC`;
const sbxProcessObjects = (await this.connection.tooling.query<SandboxProcessObject>(soql)).records.filter(
(item) => !item.Status.startsWith('Del')
);
this.logger.debug(sbxProcessObjects, `SandboxProcesses for ${sandboxInfo.SandboxName}`);
// throw if none found
if (sbxProcessObjects?.length === 0) {
throw new Error(`No SandboxProcesses found for: ${sandboxInfo.SandboxName}`);
}
const sandboxRefreshProgress = sbxProcessObjects[0];
const isAsync = !!options.async;
if (isAsync) {
// The user didn't want us to poll, so simply return the status
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_ASYNC_RESULT, sandboxRefreshProgress);
return sandboxRefreshProgress;
}
const [wait, pollInterval] = this.validateWaitOptions(options);
this.logger.debug(
sandboxRefreshProgress,
`refresh - pollStatusAndAuth sandboxProcessObj, max wait time of ${wait.minutes} minutes`
);
return this.pollStatusAndAuth({
sandboxProcessObj: sandboxRefreshProgress,
wait,
pollInterval,
});
}
/**
*
* @param sandboxReq SandboxRequest options to create the sandbox with
* @param sourceSandboxName the name of the sandbox that your new sandbox will be based on
* @param options Wait: The amount of time to wait before timing out, defaults to 0, Interval: The time interval between polling defaults to 30 seconds
* @returns {SandboxProcessObject} the newly created sandbox process object
*/
public async cloneSandbox(
sandboxReq: SandboxRequest,
sourceSandboxName: string,
options: { wait?: Duration; interval?: Duration }
): Promise<SandboxProcessObject> {
const SourceId = (await this.querySandboxProcessBySandboxName(sourceSandboxName)).SandboxInfoId;
this.logger.debug(`Clone sandbox sourceId ${SourceId}`);
return this.createSandbox({ ...sandboxReq, SourceId }, options);
}
/**
* Resume a sandbox create or refresh from a production org.
* `this` needs to be a production org with sandbox licenses available.
*
* @param resumeSandboxRequest SandboxRequest options to create/refresh the sandbox with
* @param options Wait: The amount of time to wait (default: 0 minutes) before timing out,
* Interval: The time interval (default: 30 seconds) between polling
*/
public async resumeSandbox(
resumeSandboxRequest: ResumeSandboxRequest,
options: { wait?: Duration; interval?: Duration; async?: boolean } = {
wait: Duration.minutes(0),
async: false,
interval: Duration.seconds(30),
}
): Promise<SandboxProcessObject> {
this.logger.debug(resumeSandboxRequest, 'ResumeSandbox called with ResumeSandboxRequest');
let sandboxCreationProgress: SandboxProcessObject;
// seed the sandboxCreationProgress via the resumeSandboxRequest options
if (resumeSandboxRequest.SandboxProcessObjId) {
sandboxCreationProgress = await this.querySandboxProcessById(resumeSandboxRequest.SandboxProcessObjId);
} else if (resumeSandboxRequest.SandboxName) {
try {
// There can be multiple sandbox processes returned when querying by name. Use the most recent
// process and fire a warning event with all processes.
sandboxCreationProgress = await this.querySandboxProcessBySandboxName(resumeSandboxRequest.SandboxName);
} catch (err) {
if (err instanceof SfError && err.name === 'SingleRecordQuery_MultipleRecords' && err.data) {
const sbxProcesses = err.data as SandboxProcessObject[];
// 0 index will always be the most recently created process since the query sorts on created date desc.
sandboxCreationProgress = sbxProcesses[0];
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_MULTIPLE_SBX_PROCESSES, sbxProcesses);
} else {
throw err;
}
}
} else {
throw messages.createError('sandboxNotFound', [
resumeSandboxRequest.SandboxName ?? resumeSandboxRequest.SandboxProcessObjId,
]);
}
this.logger.debug(sandboxCreationProgress, 'Return from calling singleRecordQuery with tooling');
if (!sandboxIsResumable(sandboxCreationProgress.Status)) {
throw messages.createError('sandboxNotResumable', [
sandboxCreationProgress.SandboxName,
sandboxCreationProgress.Status,
]);
}
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_RESUME, sandboxCreationProgress);
const [wait, pollInterval] = this.validateWaitOptions(options);
// if wait is 0, return the sandboxCreationProgress immediately
if (wait.seconds === 0) {
if (sandboxCreationProgress.Status === 'Completed') {
// check to see if sandbox can authenticate via sandboxAuth endpoint
const sandboxInfo = await this.sandboxSignupComplete(sandboxCreationProgress);
if (sandboxInfo) {
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_AUTH, sandboxInfo);
try {
this.logger.debug(sandboxInfo, 'sandbox signup complete');
await this.writeSandboxAuthFile(sandboxCreationProgress, sandboxInfo);
return sandboxCreationProgress;
} catch (err) {
// eat the error, we don't want to throw an error if we can't write the file
}
}
}
await Lifecycle.getInstance().emit(SandboxEvents.EVENT_ASYNC_RESULT, sandboxCreationProgress);
throw messages.createError('sandboxCreateNotComplete');
}
this.logger.debug(
sandboxCreationProgress,
`resume - pollStatusAndAuth sandboxProcessObj, max wait time of ${wait.minutes} minutes`
);
return this.pollStatusAndAuth({
sandboxProcessObj: sandboxCreationProgress,
wait,
pollInterval,
});
}
/**
* Creates a scratchOrg
* 'this' needs to be a valid dev-hub
*
* @param {options} ScratchOrgCreateOptions
* @returns {ScratchOrgCreateResult}
*/
public async scratchOrgCreate(options: ScratchOrgRequest): Promise<ScratchOrgCreateResult> {
return scratchOrgCreate({ ...options, hubOrg: this });
}
/**
* Reports sandbox org creation status. If the org is ready, authenticates to the org.
*
* @param {sandboxname} string the sandbox name
* @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
* @returns {SandboxProcessObject} the sandbox process object
*/
public async sandboxStatus(
sandboxname: string,
options: { wait?: Duration; interval?: Duration }
): Promise<SandboxProcessObject> {
return this.authWithRetriesByName(sandboxname, options);
}
/**
* Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
*
* @param orgDataPath A relative path other than "orgs/".
* @param throwWhenRemoveFails Should the remove org operations throw an error on failure?
*/
public async cleanLocalOrgData(orgDataPath?: string, throwWhenRemoveFails = false): Promise<void> {
let dataPath: string;
try {
dataPath = await this.getLocalDataDir(orgDataPath);
this.logger.debug(`cleaning data for path: ${dataPath}`);
} catch (err) {
if (err instanceof Error && err.name === 'InvalidProjectWorkspaceError') {
// If we aren't in a project dir, we can't clean up data files.
// If the user unlink this org outside of the workspace they used it in,
// data files will be left over.
return;
}
throw err;
}
return this.manageDelete(async () => fs.promises.rmdir(dataPath), dataPath, throwWhenRemoveFails);
}
/**
* @ignore
*/
public async retrieveOrgUsersConfig(): Promise<OrgUsersConfig> {
return OrgUsersConfig.create(OrgUsersConfig.getOptions(this.getOrgId()));
}
/**
* Cleans up all org related artifacts including users, sandbox config (if a sandbox), source tracking files, and auth file.
*
* @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
*/
public async remove(throwWhenRemoveFails = false): Promise<void> {
// If deleting via the access token there shouldn't be any auth config files
// so just return;
if (this.getConnection().isUsingAccessToken()) {
return Promise.resolve();
}
await this.removeSandboxConfig();
await this.removeUsers(throwWhenRemoveFails);
await this.removeUsersConfig();
// An attempt to remove this org's auth file occurs in this.removeUsersConfig. That's because this org's usersname is also
// included in the OrgUser config file.
//
// So, just in case no users are added to this org we will try the remove again.
await this.removeAuth();
await this.removeSourceTrackingFiles();
}
/**
* Check if org is a sandbox org by checking its SandboxOrgConfig.
*
*/
public async isSandbox(): Promise<boolean> {
return (await StateAggregator.getInstance()).sandboxes.hasFile(this.getOrgId());
}
/**
* Check that this org is a scratch org by asking the dev hub if it knows about it.
*
* **Throws** *{@link SfError}{ name: 'NotADevHubError' }* Not a Dev Hub.
*
* **Throws** *{@link SfError}{ name: 'NoResultsError' }* No results.
*
* @param devHubUsernameOrAlias The username or alias of the dev hub org.
*/
public async checkScratchOrg(devHubUsernameOrAlias?: string): Promise<Partial<AuthFields>> {
let aliasOrUsername = devHubUsernameOrAlias;
if (!aliasOrUsername) {
aliasOrUsername = this.configAggregator.getPropertyValue<string>(OrgConfigProperties.TARGET_DEV_HUB);
}
const devHubConnection = (await Org.create({ aliasOrUsername })).getConnection();
const thisOrgAuthConfig = this.getConnection().getAuthInfoFields();
const trimmedId = trimTo15(thisOrgAuthConfig.orgId);
const DEV_HUB_SOQL = `SELECT CreatedDate,Edition,ExpirationDate FROM ActiveScratchOrg WHERE ScratchOrg='${trimmedId}'`;
try {
const results = await devHubConnection.query(DEV_HUB_SOQL);
if (results.records.length !== 1) {
throw new SfError('No results', 'NoResultsError');
}
} catch (err) {
if (err instanceof Error && err.name === 'INVALID_TYPE') {
throw messages.createError('notADevHub', [devHubConnection.getUsername()]);
}
throw err;
}
return thisOrgAuthConfig;
}
/**
* Returns the Org object or null if this org is not affiliated with a Dev Hub (according to the local config).
*/
public async getDevHubOrg(): Promise<Org | undefined> {
if (this.isDevHubOrg()) {
return this;
} else if (this.getField(Org.Fields.DEV_HUB_USERNAME)) {
const devHubUsername = ensureString(this.getField(Org.Fields.DEV_HUB_USERNAME));
return Org.create({
connection: await Connection.create({
authInfo: await AuthInfo.create({ username: devHubUsername }),
}),
});
}
}
/**
* Returns `true` if the org is a Dev Hub.
*
* **Note** This relies on a cached value in the auth file. If that property
* is not cached, this method will **always return false even if the org is a
* dev hub**. If you need accuracy, use the {@link Org.determineIfDevHubOrg} method.
*/
public isDevHubOrg(): boolean {
const isDevHub = this.getField(Org.Fields.IS_DEV_HUB);
if (isBoolean(isDevHub)) {
return isDevHub;
} else {
return false;
}
}
/**
* Will delete 'this' instance remotely and any files locally
*
* @param controllingOrg username or Org that 'this.devhub' or 'this.production' refers to. AKA a DevHub for a scratch org, or a Production Org for a sandbox
*/
public async deleteFrom(controllingOrg: string | Org): Promise<void> {
const resolvedOrg =
typeof controllingOrg === 'string'
? await Org.create({
aggregator: this.configAggregator,
aliasOrUsername: controllingOrg,
})
: controllingOrg;
if (await this.isSandbox()) {
await this.deleteSandbox(resolvedOrg);
} else {
await this.deleteScratchOrg(resolvedOrg);
}
}
/**
* Will delete 'this' instance remotely and any files locally
*/
public async delete(): Promise<void> {
const username = ensureString(this.getUsername());
// unset any aliases referencing this org
const stateAgg = await StateAggregator.getInstance();
const existingAliases = stateAgg.aliases.getAll(username);
await stateAgg.aliases.unsetValuesAndSave(existingAliases);
// unset any configs referencing this org
[...existingAliases, username].flatMap((name) => this.configAggregator.unsetByValue(name));
if (await this.isSandbox()) {
await this.deleteSandbox();
} else {
await this.deleteScratchOrg();
}
}
/**
* Returns `true` if the org is a Dev Hub.
*
* Use a cached value. If the cached value is not set, then check access to the
* ScratchOrgInfo object to determine if the org is a dev hub.
*
* @param forceServerCheck Ignore the cached value and go straight to the server
* which will be required if the org flips on the dev hub after the value is already
* cached locally.
*/
public async determineIfDevHubOrg(forceServerCheck = false): Promise<boolean> {
const cachedIsDevHub = this.getField(Org.Fields.IS_DEV_HUB);
if (!forceServerCheck && isBoolean(cachedIsDevHub)) {
return cachedIsDevHub;
}
if (this.isDevHubOrg()) {
return true;
}
this.logger.debug('isDevHub is not cached - querying server...');
const conn = this.getConnection();
let isDevHub = false;
try {
await conn.query('SELECT Id FROM ScratchOrgInfo limit 1');
isDevHub = true;
} catch (err) {
/* Not a dev hub */
}
const username = ensure(this.getUsername());
const authInfo = await AuthInfo.create({ username });
await authInfo.save({ isDevHub });
// Reset the connection with the updated auth file
this.connection = await Connection.create({ authInfo });
return isDevHub;
}
/**
* Returns `true` if the org is a scratch org.
*
* **Note** This relies on a cached value in the auth file. If that property
* is not cached, this method will **always return false even if the org is a
* scratch org**. If you need accuracy, use the {@link Org.determineIfScratch} method.
*/
public isScratch(): boolean {
const isScratch = this.getField(Org.Fields.IS_SCRATCH);
if (isBoolean(isScratch)) {
return isScratch;
} else {
return false;
}
}
/**
* Returns `true` if the org uses source tracking.
* Side effect: updates files where the property doesn't currently exist
*/
public async tracksSource(): Promise<boolean> {
// use the property if it exists
const tracksSource = this.getField(Org.Fields.TRACKS_SOURCE);
if (isBoolean(tracksSource)) {
return tracksSource;
}
// scratch orgs with no property use tracking by default
if (await this.determineIfScratch()) {
// save true for next time to avoid checking again
await this.setTracksSource(true);
return true;
}
if (await this.determineIfSandbox()) {
// does the sandbox know about the SourceMember object?
const supportsSourceMembers = await this.supportsSourceTracking();
await this.setTracksSource(supportsSourceMembers);
return supportsSourceMembers;
}
// any other non-sandbox, non-scratch orgs won't use tracking
await this.setTracksSource(false);
return false;
}
/**
* Set the tracking property on the org's auth file
*
* @param value true or false (whether the org should use source tracking or not)
*/
public async setTracksSource(value: boolean): Promise<void> {
const originalAuth = await AuthInfo.create({ username: this.getUsername() });
return originalAuth.handleAliasAndDefaultSettings({
setDefault: false,
setDefaultDevHub: false,
setTracksSource: value,
});
}
/**
* Returns `true` if the org is a scratch org.
*
* Use a cached value. If the cached value is not set, then check
* `Organization.IsSandbox == true && Organization.TrialExpirationDate != null`
* using {@link Org.retrieveOrganizationInformation}.
*/
public async determineIfScratch(): Promise<boolean> {
const cache = this.getField<boolean | undefined>(Org.Fields.IS_SCRATCH);
if (cache !== undefined) {
return cache;
}
const updated = await this.updateLocalInformation();
return updated?.isScratch === true;
}
/**
* Returns `true` if the org is a sandbox.
*
* Use a cached value. If the cached value is not set, then check
* `Organization.IsSandbox == true && Organization.TrialExpirationDate == null`
* using {@link Org.retrieveOrganizationInformation}.
*/
public async determineIfSandbox(): Promise<boolean> {
const cache = this.getField<boolean | undefined>(Org.Fields.IS_SANDBOX);
if (cache !== undefined) {
return cache;
}
const updated = await this.updateLocalInformation();
return updated?.isSandbox === true;
}
/**
* Retrieve a handful of fields from the Organization table in Salesforce. If this does not have the
* data you need, just use {@link Connection.singleRecordQuery} with `SELECT <needed fields> FROM Organization`.
*
* @returns org information
*/
public async retrieveOrganizationInformation(): Promise<OrganizationInformation> {
return this.getConnection().singleRecordQuery<OrganizationInformation>(
'SELECT Name, InstanceName, IsSandbox, TrialExpirationDate, NamespacePrefix FROM Organization'
);
}
/**
* Some organization information is locally cached, such as if the org name or if it is a scratch org.
* This method populates/updates the filesystem from information retrieved from the org.
*/
public async updateLocalInformation(): Promise<
| Pick<
AuthFields,
| Org.Fields.NAME
| Org.Fields.INSTANCE_NAME
| Org.Fields.NAMESPACE_PREFIX
| Org.Fields.IS_SANDBOX
| Org.Fields.IS_SCRATCH
| Org.Fields.TRIAL_EXPIRATION_DATE
>
| undefined
> {
const username = this.getUsername();
if (username) {
const [stateAggregator, organization] = await Promise.all([
StateAggregator.getInstance(),
this.retrieveOrganizationInformation(),
]);
const updateFields = {
[Org.Fields.NAME]: organization.Name,
[Org.Fields.INSTANCE_NAME]: organization.InstanceName,
[Org.Fields.NAMESPACE_PREFIX]: organization.NamespacePrefix,
[Org.Fields.IS_SANDBOX]: organization.IsSandbox && !organization.TrialExpirationDate,
[Org.Fields.IS_SCRATCH]: organization.IsSandbox && Boolean(organization.TrialExpirationDate),
[Org.Fields.TRIAL_EXPIRATION_DATE]: organization.TrialExpirationDate,
};
stateAggregator.orgs.update(username, updateFields);
await stateAggregator.orgs.write(username);
return updateFields;
}
}
/**
* Refreshes the auth for this org's instance by calling HTTP GET on the baseUrl of the connection object.
*/
public async refreshAuth(): Promise<void> {
this.logger.debug('Refreshing auth for org.');
const requestInfo: HttpRequest = {
url: this.getConnection().baseUrl(),
method: 'GET',
};
await this.getConnection().request(requestInfo);
}
/**
* Reads and returns the content of all user auth files for this org as an array.
*/
public async readUserAuthFiles(): Promise<AuthInfo[]> {
const config: OrgUsersConfig = await this.retrieveOrgUsersConfig();
const contents: ConfigContents = await config.read();
const thisUsername = ensure(this.getUsername());
const usernames: JsonArray = ensureJsonArray(contents.usernames ?? [thisUsername]);
return Promise.all(
usernames.map((username) =>
AuthInfo.create({
username: username === thisUsername ? this.getConnection().getUsername() : ensureString(username),
})
)
);
}
/**
* Adds a username to the user config for this org. For convenience `this` object is returned.
*
* ```
* const org: Org = await Org.create({
* connection: await Connection.create({
* authInfo: await AuthInfo.create('[email protected]')
* })
* });
* const userAuth: AuthInfo = await AuthInfo.create({
* username: '[email protected]'
* });
* await org.addUsername(userAuth);
* ```
*
* @param {AuthInfo | string} auth The AuthInfo for the username to add.
*/
public async addUsername(auth: AuthInfo | string): Promise<Org> {
if (!auth) {
throw new SfError('Missing auth info', 'MissingAuthInfo');
}
const authInfo = isString(auth) ? await AuthInfo.create({ username: auth }) : auth;
this.logger.debug(`adding username ${authInfo.getFields().username}`);
const orgConfig = await this.retrieveOrgUsersConfig();
const contents = await orgConfig.read();
// TODO: This is kind of screwy because contents values can be `AnyJson | object`...
// needs config refactoring to improve
const usernames = contents.usernames ?? [];
if (!Array.isArray(usernames)) {
throw new SfError('Usernames is not an array', 'UnexpectedDataFormat');
}
let shouldUpdate = false;
const thisUsername = ensure(this.getUsername());
if (!usernames.includes(thisUsername)) {
usernames.push(thisUsername);
shouldUpdate = true;
}
const username = authInfo.getFields().username;
if (username) {
usernames.push(username);
shouldUpdate = true;
}
if (shouldUpdate) {
orgConfig.set('usernames', usernames);
await orgConfig.write();
}
return this;
}
/**
* Removes a username from the user config for this object. For convenience `this` object is returned.
*
* **Throws** *{@link SfError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
*
* @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
*/
public async removeUsername(auth: AuthInfo | string): Promise<Org> {
if (!auth) {
throw new SfError('Missing auth info', 'MissingAuthInfoError');
}
const authInfo: AuthInfo = isString(auth) ? await AuthInfo.create({ username: auth }) : auth;
this.logger.debug(`removing username ${authInfo.getFields().username}`);
const orgConfig: OrgUsersConfig = await this.retrieveOrgUsersConfig();
const contents = await orgConfig.read();
const targetUser = authInfo.getFields().username;
const usernames = (contents.usernames ?? []).filter((username) => username !== targetUser);
orgConfig.set('usernames', usernames);
await orgConfig.write();
return this;
}
/**
* set the sandbox config related to this given org
*
* @param orgId {string} orgId of the sandbox
* @param config {SandboxFields} config of the sandbox
*/
public async setSandboxConfig(orgId: string, config: SandboxFields): Promise<Org> {
(await StateAggregator.getInstance()).sandboxes.set(orgId, config);
return this;
}
/**
* get the sandbox config for the given orgId
*
* @param orgId {string} orgId of the sandbox
*/
public async getSandboxConfig(orgId: string): Promise<Nullable<SandboxFields>> {
return (await StateAggregator.getInstance()).sandboxes.read(orgId);
}
/**
* Retrieves the highest api version that is supported by the target server instance. If the apiVersion configured for
* Sfdx is greater than the one returned in this call an api version mismatch occurs. In the case of the CLI that
* results in a warning.
*/
public async retrieveMaxApiVersion(): Promise<string> {
return this.getConnection().retrieveMaxApiVersion();
}
/**
* Returns the admin username used to create the org.
*/
public getUsername(): string | undefined {
return this.getConnection().getUsername();
}
/**
* Returns the orgId for this org.
*/
public getOrgId(): string {
return this.orgId ?? this.getField(Org.Fields.ORG_ID);
}
/**
* Returns for the config aggregator.
*/
public getConfigAggregator(): ConfigAggregator {
return this.configAggregator;
}
/**
* Returns an org field. Returns undefined if the field is not set or invalid.
*/
public getField<T = AnyJson>(key: Org.Fields): T {
/* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */
// @ts-ignore Legacy. We really shouldn't be doing this.
const ownProp = this[key];
if (ownProp && typeof ownProp !== 'function') return ownProp;
// @ts-ignore
return this.getConnection().getAuthInfoFields()[key];
/* eslint-enable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */
}
/**
* Returns a map of requested fields.
*/
public getFields(keys: Org.Fields[]): JsonMap {
return Object.fromEntries(keys.map((key) => [key, this.getField(key)]));
}
/**
* Returns the JSForce connection for the org.
* side effect: If you pass it an apiVersion, it will set it on the Org
* so that future calls to getConnection() will also use that version.
*
* @param apiVersion The API version to use for the connection.
*/
public getConnection(apiVersion?: string): Connection {
if (apiVersion) {
if (this.connection.getApiVersion() === apiVersion) {
this.logger.warn(`Default API version is already ${apiVersion}`);
} else {
this.connection.setApiVersion(apiVersion);
}
}
return this.connection;
}
public async supportsSourceTracking(): Promise<boolean> {
if (this.isScratch()) {
return true;
}