Options
All
  • Public
  • Public/Protected
  • All
Menu

Salesforce DX Core Library (Beta)

This library provides client-side management of Salesforce DX projects, org authentication, connections to Salesforce APIs, and various other utilities. These libraries are used by and follow patterns of the Salesforce CLI.

Requires Node.js v8.4 or greater and TypeScript target es2017.


As a beta feature, Salesforce DX Core Library is a preview and isn’t part of the “Services” under your master subscription agreement with Salesforce. Use this feature at your sole discretion, and make your purchase decisions only on the basis of generally available products and features. Salesforce doesn’t guarantee general availability of this feature within any particular time frame or at all, and we can discontinue it at any time. This feature is for evaluation purposes only, not for production use. It’s offered as is and isn’t supported, and Salesforce has no liability for any harm or damage arising out of or in connection with it. All restrictions, Salesforce reservation of rights, obligations concerning the Services, and terms for related Non-Salesforce Applications and Content apply equally to your use of this feature. You can provide feedback and suggestions for Salesforce DX Core Library in the issues section of this repo.


AuthInfo

Create, read, update, and delete authentication information for an org.

Connection

Create an instance of an API connection to a Salesforce org.

Org

Create a representation of an org based on an already authenticated alias, username, or default. The representation has a connection and other useful methods for interacting with an org and its users.

StreamingClient

Create an instance of a streaming API connection to a Salesforce org for a particular streaming channel.

ConfigFile

Represents a config file at either a local or global path. The config file extends the ConfigStore which provides map-like functions to interact with config values. The following classes are config files.

ConfigAggregator

Aggregates local, global, and environment config values using Config and environment variables.

SfdxProject

Represents a Salesforce DX project, defined by the file sfdx-project.json.

Logger

All logging in sfdx-core is accomplished through this logging class. Anyone can also use the logger to log their own log lines to the sfdx.log file or to any other log file or stream by utilizing the log level flags and envars set by the CLI or framework.

SfdxError

An error class that is always thrown from sfdx-core, providing useful formatting and contextual data.

Messages

Manage user messages that are accessible by all plugins and consumers of sfdx-core.

Index

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Object literals

Type aliases

ConfigContents

ConfigContents: Dictionary<ConfigValue>

The type of content a config stores.

ConfigEntry

ConfigEntry: [string, ConfigValue]

The type of entries in a config store defined by the key and value type of ConfigContents.

ConfigValue

ConfigValue: AnyJson

The allowed types stored in a config store.

ConnectionOptions

ConnectionOptions: AuthFields & object

FieldValue

FieldValue: string | number | boolean

FsIfc

FsIfc: Pick<"fs", "statSync">

KeyChain

LoggerLevelValue

LoggerLevelValue: LoggerLevel | number

RefreshFn

RefreshFn: function

Type declaration

    • (conn: Connection, callback: function): Promise<void>
    • Parameters

      • conn: Connection
      • callback: function
          • (err: Nullable<Error>, accessToken?: undefined | string, res?: undefined | object): Promise<void>
          • Parameters

            • err: Nullable<Error>
            • Optional accessToken: undefined | string
            • Optional res: undefined | object

            Returns Promise<void>

      Returns Promise<void>

Serializer

Serializer: function

Type declaration

    • (input: any): any
    • Parameters

      • input: any

      Returns any

StreamProcessor

StreamProcessor: function

Function type for processing messages

Type declaration

Tokens

Tokens: Array<string | boolean | number | null | undefined>

UserFields

UserFields: object

Required fields type needed to represent a Salesforce User object.

see

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm

Type declaration

Variables

Const DEFAULT_USER_DIR_MODE

DEFAULT_USER_DIR_MODE: "700" = "700"

The default file system mode to use when creating directories.

Const DEFAULT_USER_FILE_MODE

DEFAULT_USER_FILE_MODE: "600" = "600"

The default file system mode to use when creating files.

Private Const SFDX_PROJECT_JSON

SFDX_PROJECT_JSON: "sfdx-project.json" = "sfdx-project.json"
property

{string} SFDX_PROJECT_JSON The name of the project config file.

Const access

access: __promisify__ = promisify(fs.access)

Promisified version of fs.access.

function

access

returns

Const constants

constants: constants = fs.constants

A convenience reference to https://nodejs.org/api/fs.html#fs_fs_constants to reduce the need to import multiple fs modules.

Const mkdirp

mkdirp: function = promisify(mkdirpLib)

Promisified version of mkdirp.

function

mkdirp

returns

Type declaration

    • (folderPath: string, mode?: string | any): Promise<void>
    • Parameters

      • folderPath: string
      • Optional mode: string | any

      Returns Promise<void>

Const open

open: __promisify__ = promisify(fs.open)

Promisified version of fs.open.

function

open

returns

Const readFile

readFile: __promisify__ = promisify(fs.readFile)

Promisified version of fs.readFile.

function

readFile

returns

Const readdir

readdir: __promisify__ = promisify(fs.readdir)

Promisified version of fs.readdir.

function

readdir

returns

Const rmdir

rmdir: __promisify__ = promisify(fs.rmdir)

Promisified version of fs.rmdir.

function

rmdir

returns

Const stat

stat: __promisify__ = promisify(fs.stat)

Promisified version of fs.stat.

function

stat

returns

Const testSetup

testSetup: (Anonymous function) = once((sinon?: any) => {if (!sinon) {try {sinon = require('sinon');} catch (e) {throw new Error('The package sinon was not found. Add it to your package.json and pass it in to testSetup(sinon.sandbox)');}}// Import all the messages files in the sfdx-core messages dir.// Messages.importMessagesDirectory(pathJoin(__dirname, '..', '..'));Messages.importMessagesDirectory(pathJoin(__dirname));// Create a global sinon sandbox and a test logger instance for use within tests.const defaultSandbox = sinon.createSandbox();const testContext: TestContext = {SANDBOX: defaultSandbox,SANDBOXES: {DEFAULT: defaultSandbox,CONFIG: sinon.createSandbox(),CRYPTO: sinon.createSandbox(),CONNECTION: sinon.createSandbox()},TEST_LOGGER: new Logger({name: 'SFDX_Core_Test_Logger'}).useMemoryLogging(),id: _uniqid(),uniqid: _uniqid,configStubs: {},localPathRetriever: getTestLocalPath,globalPathRetriever: getTestGlobalPath,rootPathRetriever: retrieveRootPath,fakeConnectionRequest: defaultFakeConnectionRequest,getConfigStubContents(name: string, group?: string): ConfigContents {const stub: Optional<ConfigStub> = this.configStubs[name];if (stub && stub.contents) {if (group && stub.contents[group]) {return ensureJsonMap(stub.contents[group]);} else {return stub.contents;}}return {};},setConfigStubContents(name: string, value: ConfigContents) {if (ensureString(name) && isJsonMap(value)) {this.configStubs[name] = value;}}};beforeEach(() => {// Most core files create a child logger so stub this to return our test logger.testContext.SANDBOX.stub(Logger, 'child').returns(Promise.resolve(testContext.TEST_LOGGER));testContext.SANDBOXES.CONFIG.stub(ConfigFile,'resolveRootFolder').callsFake((isGlobal: boolean) =>testContext.rootPathRetriever(isGlobal, testContext.id));// Mock out all config file IO for all tests. They can restore individually if they need original functionality.testContext.SANDBOXES.CONFIG.stub(ConfigFile.prototype, 'read').callsFake(async function(this: ConfigFile<ConfigFile.Options>) {const stub = testContext.configStubs[this.constructor.name] || {};if (stub.readFn) {return await stub.readFn.call(this);}let contents = stub.contents || {};if (stub.retrieveContents) {contents = await stub.retrieveContents.call(this);}this.setContentsFromObject(contents);return Promise.resolve(this.getContents());});testContext.SANDBOXES.CONFIG.stub(ConfigFile.prototype, 'write').callsFake(async function(this: ConfigFile<ConfigFile.Options>,newContents: ConfigContents) {if (!testContext.configStubs[this.constructor.name]) {testContext.configStubs[this.constructor.name] = {};}const stub = testContext.configStubs[this.constructor.name];if (!stub) return;if (stub.writeFn) {return await stub.writeFn.call(this, newContents);}let contents = newContents || this.getContents();if (stub.updateContents) {contents = await stub.updateContents.call(this);}this.setContents(contents);stub.contents = this.toObject();});testContext.SANDBOXES.CRYPTO.stub(Crypto.prototype,'getKeyChain').callsFake(() =>Promise.resolve({setPassword: () => Promise.resolve(),getPassword: (data: object, cb: AnyFunction) =>cb(undefined, '12345678901234567890123456789012')}));testContext.SANDBOXES.CONNECTION.stub(Connection.prototype,'request').callsFake(function(this: Connection,request: string,options?: Dictionary) {if (request === `${this.instanceUrl}/services/data`) {return Promise.resolve([{ version: '42.0' }]);}return testContext.fakeConnectionRequest.call(this, request, options);});});afterEach(() => {testContext.SANDBOX.restore();Object.values(testContext.SANDBOXES).forEach(theSandbox =>theSandbox.restore());testContext.configStubs = {};});return testContext;})

Use to mock out different pieces of sfdx-core to make testing easier. This will mock out logging to a file, config file reading and writing, local and global path resolution, and http request using connection (soon).

function

testSetup

returns
example

// In a mocha tests import testSetup from '@salesforce/core/lib/testSetup';

const $$ = testSetup();

describe(() => { it('test', () => { // Stub out your own method $$.SANDBOX.stub(MyClass.prototype, 'myMethod').returnsFake(() => {});

// Set the contents that is used when aliases are read. Same for all config files. $$.configStubs.Aliases = { contents: { 'myTestAlias': 'user@company.com' } };

// Will use the contents set above. const username = Aliases.fetch('myTestAlias'); expect(username).to.equal('user@company.com'); }); });

Const unexpectedResult

unexpectedResult: SfdxError = new SfdxError('This code was expected to failed','UnexpectedResult')

A pre-canned error for try/catch testing.

see

shouldThrow

type

{SfdxError}

Const unlink

unlink: __promisify__ = promisify(fs.unlink)

Promisified version of fs.unlink.

function

unlink

returns

Const writeFile

writeFile: __promisify__ = promisify(fs.writeFile)

Promisified version of fs.writeFile.

function

writeFile

returns

Functions

findUpperCaseKeys

  • findUpperCaseKeys(data?: JsonMap): Optional<string>
  • Returns the first key within the object that has an upper case first letter.

    Parameters

    • Optional data: JsonMap

      The object in which to check key casing.

    Returns Optional<string>

isSalesforceDomain

  • isSalesforceDomain(urlString: string): boolean
  • Returns true if a provided URL contains a Salesforce owned domain.

    Parameters

    • urlString: string

      The URL to inspect.

    Returns boolean

readJson

  • readJson(jsonPath: string, throwOnEmpty?: undefined | false | true): Promise<AnyJson>
  • Read a file and convert it to JSON.

    Parameters

    • jsonPath: string

      The path of the file.

    • Optional throwOnEmpty: undefined | false | true

    Returns Promise<AnyJson>

    The contents of the file as a JSON object.

readJsonMap

  • readJsonMap(jsonPath: string, throwOnEmpty?: undefined | false | true): Promise<JsonMap>
  • Read a file and convert it to JSON, throwing an error if the parsed contents are not a JsonMap.

    Parameters

    • jsonPath: string

      The path of the file.

    • Optional throwOnEmpty: undefined | false | true

    Returns Promise<JsonMap>

    The contents of the file as a JSON object.

remove

  • remove(dirPath: string): Promise<void>
  • Deletes a folder recursively, removing all descending files and folders.

    throws

    {SfdxError} {name: 'PathIsNullOrUndefined'} The path is not defined.

    throws

    {SfdxError} {name: 'DirMissingOrNoAccess'} The folder or any sub-folder is missing or has no access.

    Parameters

    • dirPath: string

      The path to remove.

    Returns Promise<void>

Private resolveProjectPath

  • resolveProjectPath(dir?: string): Promise<string>
  • Performs an upward directory search for an sfdx project file.

    throws

    {SfdxError} {name: 'InvalidProjectWorkspace'} If the current folder is not located in a workspace.

    see

    util.SFDX_PROJECT_JSON

    see

    util.traverseForFile

    see

    process.cwd()

    Parameters

    • Default value dir: string = process.cwd()

    Returns Promise<string>

    The absolute path to the project.

Private Const retrieveKeychain

  • retrieveKeychain(platform: string): Promise<KeyChain>
  • Gets the os level keychain impl.

    Parameters

    • platform: string

      The os platform.

    Returns Promise<KeyChain>

    The keychain impl.

shouldThrow

  • shouldThrow(f: Promise<unknown>): Promise<never>
  • Use for this testing pattern:

    try { await call() assert.fail('this should never happen'); } catch (e) { ... }

    Just do this

    try { await shouldThrow(call()); // If this succeeds unexpectedResultError is thrown. } catch(e) { ... }

    Parameters

    • f: Promise<unknown>

      The async function that is expected to throw.

    Returns Promise<never>

traverseForFile

  • traverseForFile(dir: string, file: string): Promise<Optional<string>>
  • Searches a file path in an ascending manner (until reaching the filesystem root) for the first occurrence a specific file name. Resolves with the directory path containing the located file, or null if the file was not found.

    Parameters

    • dir: string

      The directory path in which to start the upward search.

    • file: string

      The file name to look for.

    Returns Promise<Optional<string>>

trimTo15

  • trimTo15(id?: undefined | string): Optional<string>
  • Converts an 18 character Salesforce ID to 15 characters.

    Parameters

    • Optional id: undefined | string

      The id to convert.

    Returns Optional<string>

validateApiVersion

  • validateApiVersion(value: string): boolean
  • Tests whether an API version matches the format i.0.

    Parameters

    • value: string

      The API version as a string.

    Returns boolean

validateEmail

  • validateEmail(value: string): boolean
  • Tests whether an email matches the format `me@my.org`

    Parameters

    • value: string

      The email as a string.

    Returns boolean

validatePathDoesNotContainInvalidChars

  • validatePathDoesNotContainInvalidChars(value: string): boolean
  • Tests whether a path is in the correct format; the value doesn't include the characters "[", "]", "?", "<", ">", "?", "|"

    Parameters

    • value: string

      The path as a string.

    Returns boolean

validateSalesforceId

  • validateSalesforceId(value: string): boolean
  • Tests whether a Salesforce ID is in the correct format, a 15- or 18-character length string with only letters and numbers

    Parameters

    • value: string

      The ID as a string.

    Returns boolean

writeJson

  • writeJson(jsonPath: string, data: AnyJson): Promise<void>
  • Convert a JSON-compatible object to a string and write it to a file.

    Parameters

    • jsonPath: string

      The path of the file to write.

    • data: AnyJson

      The JSON object to write.

    Returns Promise<void>

Object literals

Const ORG_DEFAULT

ORG_DEFAULT: object

DEVHUB

DEVHUB: string = Config.DEFAULT_DEV_HUB_USERNAME

USERNAME

USERNAME: string = Config.DEFAULT_USERNAME

list

  • list(): string[]
  • Returns string[]

Const REQUIRED_FIELDS

REQUIRED_FIELDS: object

A Map of Required Salesforce User fields.

alias

alias: string = "alias"

email

email: string = "email"

emailEncodingKey

emailEncodingKey: string = "emailEncodingKey"

id

id: string = "id"

languageLocaleKey

languageLocaleKey: string = "languageLocaleKey"

lastName

lastName: string = "lastName"

localeSidKey

localeSidKey: string = "localeSidKey"

profileId

profileId: string = "profileId"

timeZoneSidKey

timeZoneSidKey: string = "timeZoneSidKey"

username

username: string = "username"

Const SFDX_HTTP_HEADERS

SFDX_HTTP_HEADERS: object

content-type

content-type: string = "application/json"

user-agent

user-agent: string = clientId

Private Const keyChainImpl

keyChainImpl: object

darwin

darwin: KeychainAccess = new KeychainAccess(_darwinImpl, nodeFs)

generic_unix

generic_unix: GenericUnixKeychainAccess = new GenericUnixKeychainAccess()

generic_windows

generic_windows: GenericWindowsKeychainAccess = new GenericWindowsKeychainAccess()

linux

linux: KeychainAccess = new KeychainAccess(_linuxImpl, nodeFs)

validateProgram

validateProgram: _validateProgram = _validateProgram