Skip to content

Commit

Permalink
fix: building with core3 command5
Browse files Browse the repository at this point in the history
  • Loading branch information
WillieRuemmele committed Mar 8, 2022
1 parent 92c202d commit f69c752
Show file tree
Hide file tree
Showing 14 changed files with 1,955 additions and 1,651 deletions.
15 changes: 9 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
{
"name": "@salesforce/plugin-auth",
"description": "plugin for sfdx auth commands",
"version": "1.8.1",
"version": "2.0.0",
"author": "Salesforce",
"bugs": "https://github.com/forcedotcom/cli/issues",
"main": "lib/index.js",
"dependencies": {
"@oclif/config": "^1.18.1",
"@oclif/core": "^1.5.2",
"@salesforce/command": "^4.2.0",
"@salesforce/core": "^2.31.0",
"@salesforce/core": "^3.7.9",
"@salesforce/kit": "^1.5.17",
"chalk": "^4.1.2",
"fs-extra": "^10.0.1",
"open": "^8.2.1",
"tslib": "^2"
},
"devDependencies": {
"@oclif/dev-cli": "^1",
"@oclif/plugin-command-snapshot": "^2.2.2",
"@salesforce/cli-plugins-testkit": "^1.4.10",
"@salesforce/dev-config": "^2.1.2",
"@salesforce/dev-scripts": "^1.0.0",
"@salesforce/dev-config": "^3.0.1",
"@salesforce/dev-scripts": "^2.0.1",
"@salesforce/plugin-command-reference": "^1.3.16",
"@salesforce/plugin-config": "^1.2.5",
"@salesforce/prettier-config": "^0.0.2",
"@salesforce/ts-sinon": "^1.3.15",
"@types/fs-extra": "^9.0.13",
"@types/graceful-fs": "^4.1.5",
"@types/jsforce": "^1.9.29",
"@types/mkdirp": "^1.0.1",
Expand All @@ -41,7 +44,7 @@
"eslint-plugin-prettier": "^3.4.0",
"husky": "^7.0.4",
"lint-staged": "^11.0.0",
"mocha": "^8.4.0",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"prettier": "^2.3.1",
"pretty-quick": "^3.1.0",
Expand Down
11 changes: 4 additions & 7 deletions src/commands/auth/accesstoken/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthFields, AuthInfo, AuthInfoConfig, Messages, sfdc, SfdxError } from '@salesforce/core';
import { AuthFields, AuthInfo, GlobalInfo, Messages, sfdc, SfError } from '@salesforce/core';
import { ensureString, getString } from '@salesforce/ts-types';
import { env } from '@salesforce/kit';
import { Prompts } from '../../../prompts';
Expand Down Expand Up @@ -83,11 +83,8 @@ export default class Store extends SfdxCommand {

private async overwriteAuthInfo(username: string): Promise<boolean> {
if (!this.flags.noprompt) {
const authInfoConfig = await AuthInfoConfig.create({
...AuthInfoConfig.getOptions(username),
throwOnNotFound: false,
});
if (await authInfoConfig.exists()) {
const info = await GlobalInfo.create();
if (info.orgs.has(username)) {
return Prompts.askOverwriteAuthFile(this.ux, username);
}
}
Expand All @@ -102,7 +99,7 @@ export default class Store extends SfdxCommand {
accessToken = await Prompts.askForAccessToken(this.ux);
}
if (!sfdc.matchesAccessToken(accessToken)) {
throw new SfdxError(messages.getMessage('invalidAccessTokenFormat', [ACCESS_TOKEN_FORMAT]));
throw new SfError(messages.getMessage('invalidAccessTokenFormat', [ACCESS_TOKEN_FORMAT]));
}
return accessToken;
}
Expand Down
6 changes: 3 additions & 3 deletions src/commands/auth/device/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
*/

import * as os from 'os';

import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthFields, DeviceOauthService, Messages, OAuth2Options } from '@salesforce/core';
import { OAuth2Config } from 'jsforce';
import { AuthFields, DeviceOauthService, Messages } from '@salesforce/core';
import { get, Optional } from '@salesforce/ts-types';
import { Prompts } from '../../../prompts';
import { Common } from '../../../common';
Expand Down Expand Up @@ -52,7 +52,7 @@ export default class Login extends SfdxCommand {
public async run(): Promise<AuthFields> {
if (await Prompts.shouldExitCommand(this.ux, this.flags.noprompt)) return {};

const oauthConfig: OAuth2Options = {
const oauthConfig: OAuth2Config = {
loginUrl: await Common.resolveLoginUrl(get(this.flags.instanceurl, 'href', null) as Optional<string>),
clientId: this.flags.clientid as string,
};
Expand Down
6 changes: 3 additions & 3 deletions src/commands/auth/jwt/grant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthFields, AuthInfo, AuthRemover, Messages, SfdxError } from '@salesforce/core';
import { AuthFields, AuthInfo, AuthRemover, Messages, SfError } from '@salesforce/core';
import { get, getString, Optional } from '@salesforce/ts-types';
import { Prompts } from '../../../prompts';
import { Common } from '../../../common';
Expand Down Expand Up @@ -73,7 +73,7 @@ export default class Grant extends SfdxCommand {
await Common.identifyPossibleScratchOrgs(result, authInfo);
} catch (err) {
const msg = getString(err, 'message');
throw SfdxError.create('@salesforce/plugin-auth', 'jwt.grant', 'JwtGrantError', [msg]);
throw messages.createError('JwtGrantError', [msg]);
}

const successMsg = commonMessages.getMessage('authorizeCommandSuccess', [result.username, result.orgId]);
Expand All @@ -98,7 +98,7 @@ export default class Grant extends SfdxCommand {
oauth2Options,
});
} catch (error) {
const err = error as SfdxError;
const err = error as SfError;
if (err.name === 'AuthInfoOverwriteError') {
this.logger.debug('Auth file already exists. Removing and starting fresh.');
const remover = await AuthRemover.create();
Expand Down
23 changes: 11 additions & 12 deletions src/commands/auth/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { FlagsConfig, SfdxCommand, TableOptions } from '@salesforce/command';
import { AuthInfo, Authorization, Messages } from '@salesforce/core';
import { FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthInfo, OrgAuthorization, Messages } from '@salesforce/core';
import { CliUx } from '@oclif/core';

Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-auth', 'list');
Expand All @@ -16,21 +17,19 @@ export default class List extends SfdxCommand {
public static aliases = ['force:auth:list'];

public static readonly flagsConfig: FlagsConfig = {};
public async run(): Promise<Authorization[]> {
public async run(): Promise<OrgAuthorization[]> {
try {
const auths = await AuthInfo.listAllAuthorizations();
const hasErrors = auths.filter((auth) => !!auth.error).length > 0;
const columns: TableOptions = {
columns: [
{ key: 'alias', label: 'ALIAS' },
{ key: 'username', label: 'USERNAME' },
{ key: 'orgId', label: 'ORG ID' },
{ key: 'instanceUrl', label: 'INSTANCE URL' },
{ key: 'oauthMethod', label: 'AUTH METHOD' },
],
let columns: CliUx.Table.table.Columns<Record<string, unknown>> = {
alias: { header: 'ALIAS' },
username: { header: 'USERNAME' },
orgId: { header: 'ORG ID' },
instanceUrl: { header: 'INSTANCE URL' },
oauthMethod: { header: 'AUTH METHOD' },
};
if (hasErrors) {
columns.columns.push({ key: 'error', label: 'ERROR' });
columns = { ...columns, ...{ error: { header: 'ERROR' } } };
}
this.ux.styledHeader('authenticated orgs');
this.ux.table(auths, columns);
Expand Down
14 changes: 7 additions & 7 deletions src/commands/auth/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import * as os from 'os';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthConfigs, AuthRemover, Global, Messages, Mode, SfdxError } from '@salesforce/core';
import { AuthRemover, Global, Messages, Mode, SfError } from '@salesforce/core';
import { Prompts } from '../../prompts';

Messages.importMessagesDirectory(__dirname);
Expand Down Expand Up @@ -36,18 +36,18 @@ export default class Logout extends SfdxCommand {

public async run(): Promise<string[]> {
if (this.flags.targetusername && this.flags.all) {
const err = new SfdxError(messages.getMessage('specifiedBothUserAndAllError'), 'SpecifiedBothUserAndAllError');
const err = new SfError(messages.getMessage('specifiedBothUserAndAllError'), 'SpecifiedBothUserAndAllError');
return Promise.reject(err);
}

const remover = await AuthRemover.create();

const authConfigs = this.shouldFindAllAuths()
? await remover.findAllAuthConfigs()
: await remover.findAuthConfigs(this.flags.targetusername);
? Object.keys(remover.findAllAuths())
: (await remover.findAuth(this.flags.targetusername)).username;

if (await this.shouldRunCommand(authConfigs)) {
const usernames = [...authConfigs.keys()];
const usernames = [...authConfigs];
for (const username of usernames) {
await remover.removeAuth(username);
}
Expand All @@ -61,8 +61,8 @@ export default class Logout extends SfdxCommand {
return !!this.flags.all || (!this.flags.targetusername && Global.getEnvironmentMode() === Mode.DEMO);
}

private async shouldRunCommand(authConfigs: AuthConfigs): Promise<boolean> {
const orgsToDelete = [[...authConfigs.keys()].join(os.EOL)];
private async shouldRunCommand(usernames: string[] | string): Promise<boolean> {
const orgsToDelete = [[...usernames].join(os.EOL)];
const message = messages.getMessage('logoutCommandYesNo', orgsToDelete);
return Prompts.shouldRunCommand(this.ux, this.flags.noprompt, message);
}
Expand Down
8 changes: 5 additions & 3 deletions src/commands/auth/sfdxurl/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
*/

import * as os from 'os';
import { readFile } from 'fs/promises';
import { readJson } from 'fs-extra';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthFields, AuthInfo, fs, Messages } from '@salesforce/core';
import { AuthFields, AuthInfo, Messages } from '@salesforce/core';
import { AnyJson } from '@salesforce/ts-types';
import { Prompts } from '../../../prompts';
import { Common } from '../../../common';
Expand Down Expand Up @@ -60,7 +62,7 @@ export default class Store extends SfdxCommand {

const sfdxAuthUrl = authFile.endsWith('.json')
? await this.getUrlFromJson(authFile)
: await fs.readFile(authFile, 'utf8');
: await readFile(authFile, 'utf8');

if (!sfdxAuthUrl) {
throw new Error(
Expand All @@ -84,7 +86,7 @@ export default class Store extends SfdxCommand {
}

private async getUrlFromJson(authFile: string): Promise<string> {
const authFileJson = (await fs.readJson(authFile)) as AuthJson;
const authFileJson = (await readJson(authFile)) as AuthJson;
return authFileJson.result?.sfdxAuthUrl || authFileJson.sfdxAuthUrl;
}
}
11 changes: 6 additions & 5 deletions src/commands/auth/web/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import * as os from 'os';
import * as open from 'open';

import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthFields, AuthInfo, Logger, Messages, OAuth2Options, SfdxError, WebOAuthServer } from '@salesforce/core';
import { OAuth2Config } from 'jsforce';
import { AuthFields, AuthInfo, Logger, Messages, SfError, WebOAuthServer } from '@salesforce/core';
import { Env } from '@salesforce/kit';
import { get, Optional } from '@salesforce/ts-types';
import { Prompts } from '../../../prompts';
Expand Down Expand Up @@ -59,12 +60,12 @@ export default class Login extends SfdxCommand {

public async run(): Promise<AuthFields> {
if (this.isSFDXContainerMode()) {
throw new SfdxError(messages.getMessage('deviceWarning'), 'DEVICE_WARNING');
throw new SfError(messages.getMessage('deviceWarning'), 'DEVICE_WARNING');
}

if (await Prompts.shouldExitCommand(this.ux, this.flags.noprompt)) return {};

const oauthConfig: OAuth2Options = {
const oauthConfig: OAuth2Config = {
loginUrl: await Common.resolveLoginUrl(get(this.flags.instanceurl, 'href', null) as Optional<string>),
clientId: this.flags.clientid as string,
};
Expand All @@ -86,13 +87,13 @@ export default class Login extends SfdxCommand {
const error = err as Error;
Logger.childFromRoot('auth').debug(error);
if (error.name === 'AuthCodeExchangeError') {
throw new SfdxError(messages.getMessage('invalidClientId', [error.message]));
throw new SfError(messages.getMessage('invalidClientId', [error.message]));
}
throw error;
}
}

private async executeLoginFlow(oauthConfig: OAuth2Options): Promise<AuthInfo> {
private async executeLoginFlow(oauthConfig: OAuth2Config): Promise<AuthInfo> {
const oauthServer = await WebOAuthServer.create({ oauthConfig });
await oauthServer.start();
await open(oauthServer.getAuthorizationUrl(), { wait: false });
Expand Down
14 changes: 7 additions & 7 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { basename } from 'path';
import { QueryResult } from 'jsforce';
import { AuthInfo, AuthFields, Logger, SfdcUrl, SfdxProject, Messages, Org, SfdxError, sfdc } from '@salesforce/core';
import { AuthInfo, AuthFields, Logger, SfdcUrl, SfdxProject, Messages, Org, SfError, sfdc } from '@salesforce/core';
import { getString, isObject, Optional } from '@salesforce/ts-types';

Messages.importMessagesDirectory(__dirname);
Expand All @@ -24,8 +24,8 @@ export class Common {

if (flags.setdefaultdevhubusername || flags.setdefaultusername) {
await authInfo.setAsDefault({
defaultUsername: flags.setdefaultusername,
defaultDevhubUsername: flags.setdefaultdevhubusername,
org: flags.setdefaultusername,
devHub: flags.setdefaultdevhubusername,
});
}
}
Expand All @@ -34,7 +34,7 @@ export class Common {
if (instanceUrl) {
if (instanceUrl.includes('lightning.force.com')) {
logger.warn(messages.getMessage('invalidInstanceUrl'));
throw new SfdxError(messages.getMessage('invalidInstanceUrl'), 'URL_WARNING');
throw new SfError(messages.getMessage('invalidInstanceUrl'), 'URL_WARNING');
}
return instanceUrl;
}
Expand All @@ -50,7 +50,7 @@ export class Common {
}
if (loginUrl.includes('lightning.force.com')) {
logger.warn(messages.getMessage('invalidInstanceUrl'));
throw new SfdxError(messages.getMessage('invalidInstanceUrl'), 'URL_WARNING');
throw new SfError(messages.getMessage('invalidInstanceUrl'), 'URL_WARNING');
}
logger.debug(`loginUrl: ${loginUrl}`);
return loginUrl;
Expand Down Expand Up @@ -104,8 +104,8 @@ export class Common {
public static async getDevHubAuthInfos(): Promise<AuthInfo[]> {
return (
await Promise.all(
(await AuthInfo.listAllAuthFiles())
.map((fileName) => basename(fileName, '.json'))
(await AuthInfo.listAllAuthorizations())
.map((org) => basename(org.username, '.json'))
.map((username) => AuthInfo.create({ username }))
)
).filter((possibleHub) => possibleHub?.getFields()?.isDevHub);
Expand Down
4 changes: 2 additions & 2 deletions test/commands/auth/accesstoken/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import { $$, expect } from '@salesforce/command/lib/test';
import { IConfig } from '@oclif/config';
import { AuthFields, AuthInfo, ConfigFile, SfdxError } from '@salesforce/core';
import { AuthFields, AuthInfo, ConfigFile, SfError } from '@salesforce/core';
import { Crypto } from '@salesforce/core/lib/crypto';
import { StubbedType, stubInterface, stubMethod } from '@salesforce/ts-sinon';
import { UX } from '@salesforce/command';
Expand Down Expand Up @@ -100,7 +100,7 @@ describe('auth:accesstoken:store', () => {
await store.run();
assert(false, 'should throw error');
} catch (e) {
const err = e as SfdxError;
const err = e as SfError;
expect(err.message).to.include("The access token isn't in the correct format");
}
});
Expand Down
4 changes: 2 additions & 2 deletions test/commands/auth/jwt/grant.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { $$, expect, test } from '@salesforce/command/lib/test';
import { AuthFields, AuthInfo, SfdxError } from '@salesforce/core';
import { AuthFields, AuthInfo, SfError } from '@salesforce/core';
import { MockTestOrgData } from '@salesforce/core/lib/testSetup';
import { StubbedType, stubInterface, stubMethod } from '@salesforce/ts-sinon';
import { UX } from '@salesforce/command';
Expand Down Expand Up @@ -37,7 +37,7 @@ describe('auth:jwt:grant', async () => {
} else if (options.existingAuth) {
stubMethod($$.SANDBOX, AuthInfo, 'create')
.onFirstCall()
.throws(new SfdxError('auth exists', 'AuthInfoOverwriteError'))
.throws(new SfError('auth exists', 'AuthInfoOverwriteError'))
.onSecondCall()
.callsFake(async () => authInfoStub);
} else {
Expand Down
Loading

0 comments on commit f69c752

Please sign in to comment.