UNPKG

19.5 kBTypeScriptView Raw
1import { AsyncOptionalCreatable, Duration } from '@salesforce/kit';
2import { AnyJson, JsonMap, Nullable, Optional } from '@salesforce/ts-types';
3import { ConfigAggregator } from '../config/configAggregator';
4import { OrgUsersConfig } from '../config/orgUsersConfig';
5import { Connection } from './connection';
6import { AuthFields, AuthInfo } from './authInfo';
7import { ScratchOrgCreateOptions, ScratchOrgCreateResult } from './scratchOrgCreate';
8export declare type OrganizationInformation = {
9 Name: string;
10 InstanceName: string;
11 IsSandbox: boolean;
12 TrialExpirationDate: string | null;
13 NamespacePrefix: string | null;
14};
15export declare enum OrgTypes {
16 Scratch = "scratch",
17 Sandbox = "sandbox"
18}
19export interface StatusEvent {
20 sandboxProcessObj: SandboxProcessObject;
21 interval: number;
22 remainingWait: number;
23 waitingOnAuth: boolean;
24}
25export interface ResultEvent {
26 sandboxProcessObj: SandboxProcessObject;
27 sandboxRes: SandboxUserAuthResponse;
28}
29export interface SandboxUserAuthRequest {
30 sandboxName: string;
31 clientId: string;
32 callbackUrl: string;
33}
34export declare enum SandboxEvents {
35 EVENT_STATUS = "status",
36 EVENT_ASYNC_RESULT = "asyncResult",
37 EVENT_RESULT = "result",
38 EVENT_AUTH = "auth",
39 EVENT_RESUME = "resume"
40}
41export interface SandboxUserAuthResponse {
42 authUserName: string;
43 authCode: string;
44 instanceUrl: string;
45 loginUrl: string;
46}
47export declare type SandboxProcessObject = {
48 Id: string;
49 Status: string;
50 SandboxName: string;
51 SandboxInfoId: string;
52 LicenseType: string;
53 CreatedDate: string;
54 SandboxOrganization?: string;
55 CopyProgress?: number;
56 SourceId?: string;
57 Description?: string;
58 ApexClassId?: string;
59 EndDate?: string;
60};
61export declare type SandboxRequest = {
62 SandboxName: string;
63 LicenseType?: string;
64 /** Should match a SandboxInfoId, not a SandboxProcessId */
65 SourceId?: string;
66 Description?: string;
67};
68export declare type ResumeSandboxRequest = {
69 SandboxName?: string;
70 SandboxProcessObjId?: string;
71};
72export declare type ScratchOrgRequest = Omit<ScratchOrgCreateOptions, 'hubOrg'>;
73export declare type SandboxFields = {
74 sandboxOrgId: string;
75 prodOrgUsername: string;
76 sandboxName?: string;
77 sandboxUsername?: string;
78 sandboxProcessId?: string;
79 sandboxInfoId?: string;
80};
81/**
82 * Provides a way to manage a locally authenticated Org.
83 *
84 * **See** {@link AuthInfo}
85 *
86 * **See** {@link Connection}
87 *
88 * **See** {@link Aliases}
89 *
90 * **See** {@link Config}
91 *
92 * ```
93 * // Email username
94 * const org1: Org = await Org.create({ aliasOrUsername: 'foo@example.com' });
95 * // The target-org config property
96 * const org2: Org = await Org.create();
97 * // Full Connection
98 * const org3: Org = await Org.create({
99 * connection: await Connection.create({
100 * authInfo: await AuthInfo.create({ username: 'username' })
101 * })
102 * });
103 * ```
104 *
105 * **See** https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_cli_usernames_orgs.htm
106 */
107export declare class Org extends AsyncOptionalCreatable<Org.Options> {
108 private status;
109 private configAggregator;
110 private logger;
111 private connection;
112 private options;
113 private orgId?;
114 /**
115 * @ignore
116 */
117 constructor(options?: Org.Options);
118 /**
119 * create a sandbox from a production org
120 * 'this' needs to be a production org with sandbox licenses available
121 *
122 * @param sandboxReq SandboxRequest options to create the sandbox with
123 * @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
124 */
125 createSandbox(sandboxReq: SandboxRequest, options?: {
126 wait?: Duration;
127 interval?: Duration;
128 async?: boolean;
129 }): Promise<SandboxProcessObject>;
130 /**
131 *
132 * @param sandboxReq SandboxRequest options to create the sandbox with
133 * @param sourceSandboxName the name of the sandbox that your new sandbox will be based on
134 * @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
135 * @returns {SandboxProcessObject} the newly created sandbox process object
136 */
137 cloneSandbox(sandboxReq: SandboxRequest, sourceSandboxName: string, options: {
138 wait?: Duration;
139 interval?: Duration;
140 }): Promise<SandboxProcessObject>;
141 /**
142 * resume a sandbox creation from a production org
143 * 'this' needs to be a production org with sandbox licenses available
144 *
145 * @param resumeSandboxRequest SandboxRequest options to create the sandbox with
146 * @param options Wait: The amount of time to wait (default: 30 minutes) before timing out,
147 * Interval: The time interval (default: 30 seconds) between polling
148 */
149 resumeSandbox(resumeSandboxRequest: ResumeSandboxRequest, options?: {
150 wait?: Duration;
151 interval?: Duration;
152 async?: boolean;
153 }): Promise<SandboxProcessObject>;
154 /**
155 * Creates a scratchOrg
156 * 'this' needs to be a valid dev-hub
157 *
158 * @param {options} ScratchOrgCreateOptions
159 * @returns {ScratchOrgCreateResult}
160 */
161 scratchOrgCreate(options: ScratchOrgRequest): Promise<ScratchOrgCreateResult>;
162 /**
163 * Reports sandbox org creation status. If the org is ready, authenticates to the org.
164 *
165 * @param {sandboxname} string the sandbox name
166 * @param options Wait: The amount of time to wait before timing out, Interval: The time interval between polling
167 * @returns {SandboxProcessObject} the sandbox process object
168 */
169 sandboxStatus(sandboxname: string, options: {
170 wait?: Duration;
171 interval?: Duration;
172 }): Promise<SandboxProcessObject>;
173 /**
174 * Clean all data files in the org's data path. Usually <workspace>/.sfdx/orgs/<username>.
175 *
176 * @param orgDataPath A relative path other than "orgs/".
177 * @param throwWhenRemoveFails Should the remove org operations throw an error on failure?
178 */
179 cleanLocalOrgData(orgDataPath?: string, throwWhenRemoveFails?: boolean): Promise<void>;
180 /**
181 * @ignore
182 */
183 retrieveOrgUsersConfig(): Promise<OrgUsersConfig>;
184 /**
185 * Cleans up all org related artifacts including users, sandbox config(if a sandbox and auth file.
186 *
187 * @param throwWhenRemoveFails Determines if the call should throw an error or fail silently.
188 */
189 remove(throwWhenRemoveFails?: boolean): Promise<void>;
190 /**
191 * Check if org is a sandbox org by checking its SandboxOrgConfig.
192 *
193 */
194 isSandbox(): Promise<boolean>;
195 /**
196 * Check that this org is a scratch org by asking the dev hub if it knows about it.
197 *
198 * **Throws** *{@link SfError}{ name: 'NotADevHubError' }* Not a Dev Hub.
199 *
200 * **Throws** *{@link SfError}{ name: 'NoResultsError' }* No results.
201 *
202 * @param devHubUsernameOrAlias The username or alias of the dev hub org.
203 */
204 checkScratchOrg(devHubUsernameOrAlias?: string): Promise<Partial<AuthFields>>;
205 /**
206 * Returns the Org object or null if this org is not affiliated with a Dev Hub (according to the local config).
207 */
208 getDevHubOrg(): Promise<Optional<Org>>;
209 /**
210 * Returns `true` if the org is a Dev Hub.
211 *
212 * **Note** This relies on a cached value in the auth file. If that property
213 * is not cached, this method will **always return false even if the org is a
214 * dev hub**. If you need accuracy, use the {@link Org.determineIfDevHubOrg} method.
215 */
216 isDevHubOrg(): boolean;
217 /**
218 * Will delete 'this' instance remotely and any files locally
219 *
220 * @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
221 */
222 deleteFrom(controllingOrg: string | Org): Promise<void>;
223 /**
224 * Will delete 'this' instance remotely and any files locally
225 */
226 delete(): Promise<void>;
227 /**
228 * Returns `true` if the org is a Dev Hub.
229 *
230 * Use a cached value. If the cached value is not set, then check access to the
231 * ScratchOrgInfo object to determine if the org is a dev hub.
232 *
233 * @param forceServerCheck Ignore the cached value and go straight to the server
234 * which will be required if the org flips on the dev hub after the value is already
235 * cached locally.
236 */
237 determineIfDevHubOrg(forceServerCheck?: boolean): Promise<boolean>;
238 /**
239 * Returns `true` if the org is a scratch org.
240 *
241 * **Note** This relies on a cached value in the auth file. If that property
242 * is not cached, this method will **always return false even if the org is a
243 * scratch org**. If you need accuracy, use the {@link Org.determineIfScratch} method.
244 */
245 isScratch(): boolean;
246 /**
247 * Returns `true` if the org uses source tracking.
248 * Side effect: updates files where the property doesn't currently exist
249 */
250 tracksSource(): Promise<boolean>;
251 /**
252 * Set the tracking property on the org's auth file
253 *
254 * @param value true or false (whether the org should use source tracking or not)
255 */
256 setTracksSource(value: boolean): Promise<void>;
257 /**
258 * Returns `true` if the org is a scratch org.
259 *
260 * Use a cached value. If the cached value is not set, then check
261 * `Organization.IsSandbox == true && Organization.TrialExpirationDate != null`
262 * using {@link Org.retrieveOrganizationInformation}.
263 */
264 determineIfScratch(): Promise<boolean>;
265 /**
266 * Returns `true` if the org is a sandbox.
267 *
268 * Use a cached value. If the cached value is not set, then check
269 * `Organization.IsSandbox == true && Organization.TrialExpirationDate == null`
270 * using {@link Org.retrieveOrganizationInformation}.
271 */
272 determineIfSandbox(): Promise<boolean>;
273 /**
274 * Retrieve a handful of fields from the Organization table in Salesforce. If this does not have the
275 * data you need, just use {@link Connection.singleRecordQuery} with `SELECT <needed fields> FROM Organization`.
276 *
277 * @returns org information
278 */
279 retrieveOrganizationInformation(): Promise<OrganizationInformation>;
280 /**
281 * Some organization information is locally cached, such as if the org name or if it is a scratch org.
282 * This method populates/updates the filesystem from information retrieved from the org.
283 */
284 updateLocalInformation(): Promise<void>;
285 /**
286 * Refreshes the auth for this org's instance by calling HTTP GET on the baseUrl of the connection object.
287 */
288 refreshAuth(): Promise<void>;
289 /**
290 * Reads and returns the content of all user auth files for this org as an array.
291 */
292 readUserAuthFiles(): Promise<AuthInfo[]>;
293 /**
294 * Adds a username to the user config for this org. For convenience `this` object is returned.
295 *
296 * ```
297 * const org: Org = await Org.create({
298 * connection: await Connection.create({
299 * authInfo: await AuthInfo.create('foo@example.com')
300 * })
301 * });
302 * const userAuth: AuthInfo = await AuthInfo.create({
303 * username: 'bar@example.com'
304 * });
305 * await org.addUsername(userAuth);
306 * ```
307 *
308 * @param {AuthInfo | string} auth The AuthInfo for the username to add.
309 */
310 addUsername(auth: AuthInfo | string): Promise<Org>;
311 /**
312 * Removes a username from the user config for this object. For convenience `this` object is returned.
313 *
314 * **Throws** *{@link SfError}{ name: 'MissingAuthInfoError' }* Auth info is missing.
315 *
316 * @param {AuthInfo | string} auth The AuthInfo containing the username to remove.
317 */
318 removeUsername(auth: AuthInfo | string): Promise<Org>;
319 /**
320 * set the sandbox config related to this given org
321 *
322 * @param orgId {string} orgId of the sandbox
323 * @param config {SandboxFields} config of the sandbox
324 */
325 setSandboxConfig(orgId: string, config: SandboxFields): Promise<Org>;
326 /**
327 * get the sandbox config for the given orgId
328 *
329 * @param orgId {string} orgId of the sandbox
330 */
331 getSandboxConfig(orgId: string): Promise<Nullable<SandboxFields>>;
332 /**
333 * Retrieves the highest api version that is supported by the target server instance. If the apiVersion configured for
334 * Sfdx is greater than the one returned in this call an api version mismatch occurs. In the case of the CLI that
335 * results in a warning.
336 */
337 retrieveMaxApiVersion(): Promise<string>;
338 /**
339 * Returns the admin username used to create the org.
340 */
341 getUsername(): Optional<string>;
342 /**
343 * Returns the orgId for this org.
344 */
345 getOrgId(): string;
346 /**
347 * Returns for the config aggregator.
348 */
349 getConfigAggregator(): ConfigAggregator;
350 /**
351 * Returns an org field. Returns undefined if the field is not set or invalid.
352 */
353 getField<T = AnyJson>(key: Org.Fields): T;
354 /**
355 * Returns a map of requested fields.
356 */
357 getFields(keys: Org.Fields[]): JsonMap;
358 /**
359 * Returns the JSForce connection for the org.
360 */
361 getConnection(): Connection;
362 supportsSourceTracking(): Promise<boolean>;
363 /**
364 * query SandboxProcess via sandbox name
365 *
366 * @param name SandboxName to query for
367 * @private
368 */
369 querySandboxProcessBySandboxName(name: string): Promise<SandboxProcessObject>;
370 /**
371 * query SandboxProcess via SandboxInfoId
372 *
373 * @param id SandboxInfoId to query for
374 * @private
375 */
376 querySandboxProcessBySandboxInfoId(id: string): Promise<SandboxProcessObject>;
377 /**
378 * query SandboxProcess via Id
379 *
380 * @param id SandboxProcessId to query for
381 * @private
382 */
383 querySandboxProcessById(id: string): Promise<SandboxProcessObject>;
384 /**
385 * Initialize async components.
386 */
387 protected init(): Promise<void>;
388 /**
389 * **Throws** *{@link SfError}{ name: 'NotSupportedError' }* Throws an unsupported error.
390 */
391 protected getDefaultOptions(): Org.Options;
392 private getLocalDataDir;
393 /**
394 * Gets the sandboxProcessObject and then polls for it to complete.
395 *
396 * @param sandboxProcessName sanbox process name
397 * @param options { wait?: Duration; interval?: Duration }
398 * @returns {SandboxProcessObject} The SandboxProcessObject for the sandbox
399 */
400 private authWithRetriesByName;
401 /**
402 * Polls the sandbox org for the sandboxProcessObject.
403 *
404 * @param sandboxProcessObj: The in-progress sandbox signup request
405 * @param options { wait?: Duration; interval?: Duration }
406 * @returns {SandboxProcessObject}
407 */
408 private authWithRetries;
409 /**
410 * Query the sandbox for the SandboxProcessObject by sandbox name
411 *
412 * @param sandboxName The name of the sandbox to query
413 * @returns {SandboxProcessObject} The SandboxProcessObject for the sandbox
414 */
415 private queryLatestSandboxProcessBySandboxName;
416 private queryProduction;
417 private destroySandbox;
418 private destroyScratchOrg;
419 /**
420 * this method will delete the sandbox org from the production org and clean up any local files
421 *
422 * @param prodOrg - Production org associated with this sandbox
423 * @private
424 */
425 private deleteSandbox;
426 /**
427 * If this Org is a scratch org, calling this method will delete the scratch org from the DevHub and clean up any local files
428 *
429 * @param devHub - optional DevHub Org of the to-be-deleted scratch org
430 * @private
431 */
432 private deleteScratchOrg;
433 /**
434 * Delete an auth info file from the local file system and any related cache information for
435 * this Org. You don't want to call this method directly. Instead consider calling Org.remove()
436 */
437 private removeAuth;
438 /**
439 * Deletes the users config file
440 */
441 private removeUsersConfig;
442 private manageDelete;
443 /**
444 * Remove the org users auth file.
445 *
446 * @param throwWhenRemoveFails true if manageDelete should throw or not if the deleted fails.
447 */
448 private removeUsers;
449 private removeSandboxConfig;
450 private writeSandboxAuthFile;
451 private pollStatusAndAuth;
452 /**
453 * query SandboxProcess using supplied where clause
454 *
455 * @param where clause to query for
456 * @private
457 */
458 private querySandboxProcess;
459 /**
460 * determines if the sandbox has successfully been created
461 *
462 * @param sandboxProcessObj sandbox signup progress
463 * @private
464 */
465 private sandboxSignupComplete;
466 private validateWaitOptions;
467}
468export declare namespace Org {
469 /**
470 * Constructor Options for and Org.
471 */
472 interface Options {
473 aliasOrUsername?: string;
474 connection?: Connection;
475 aggregator?: ConfigAggregator;
476 isDevHub?: boolean;
477 }
478 /**
479 * Scratch Org status.
480 */
481 enum Status {
482 /**
483 * The scratch org is active.
484 */
485 ACTIVE = "ACTIVE",
486 /**
487 * The scratch org has expired.
488 */
489 EXPIRED = "EXPIRED",
490 /**
491 * The org is a scratch Org but no dev hub is indicated.
492 */
493 UNKNOWN = "UNKNOWN",
494 /**
495 * The dev hub configuration is reporting an active Scratch org but the AuthInfo cannot be found.
496 */
497 MISSING = "MISSING"
498 }
499 /**
500 * Org Fields.
501 */
502 enum Fields {
503 /**
504 * The org alias.
505 */
506 ALIAS = "alias",
507 CREATED = "created",
508 NAME = "name",
509 NAMESPACE_PREFIX = "namespacePrefix",
510 INSTANCE_NAME = "instanceName",
511 TRIAL_EXPIRATION_DATE = "trailExpirationDate",
512 /**
513 * The Salesforce instance the org was created on. e.g. `cs42`.
514 */
515 CREATED_ORG_INSTANCE = "createdOrgInstance",
516 /**
517 * The username of the dev hub org that created this org. Only populated for scratch orgs.
518 */
519 DEV_HUB_USERNAME = "devHubUsername",
520 /**
521 * The full url of the instance the org lives on.
522 */
523 INSTANCE_URL = "instanceUrl",
524 /**
525 * Is the current org a dev hub org. e.g. They have access to the `ScratchOrgInfo` object.
526 */
527 IS_DEV_HUB = "isDevHub",
528 /**
529 * Is the current org a scratch org. e.g. Organization has IsSandbox == true and TrialExpirationDate != null.
530 */
531 IS_SCRATCH = "isScratch",
532 /**
533 * Is the current org a dev hub org. e.g. Organization has IsSandbox == true and TrialExpirationDate == null.
534 */
535 IS_SANDBOX = "isSandbox",
536 /**
537 * The login url of the org. e.g. `https://login.salesforce.com` or `https://test.salesforce.com`.
538 */
539 LOGIN_URL = "loginUrl",
540 /**
541 * The org ID.
542 */
543 ORG_ID = "orgId",
544 /**
545 * The `OrgStatus` of the org.
546 */
547 STATUS = "status",
548 /**
549 * The snapshot used to create the scratch org.
550 */
551 SNAPSHOT = "snapshot",
552 /**
553 * true: the org supports and wants source tracking
554 * false: the org opted out of tracking or can't support it
555 */
556 TRACKS_SOURCE = "tracksSource"
557 }
558}