API Reference

Comprehensive reference for the ToolBox API and Dataverse API available to all tools running in Power Platform ToolBox.

ToolBox API

The ToolBox API provides access to platform features and utilities.

Connections

Get information about the active Dataverse connection(s).

toolboxAPI.connections.getActiveConnection()

Returns the currently active connection or null if none is selected.

const connection = await toolboxAPI.connections.getActiveConnection()

if (connection) {
  console.log('Connected to:', connection.name)
  console.log('Environment:', connection.environment)
  console.log('API URL:', connection.apiUrl)
} else {
  console.log('No active connection')
}

Returns: Promise<DataverseConnection | null>

interface DataverseConnection {
  id: string // Unique identifier of the connection
  name: string // Friendly name of the connection
  url: string // Base URL of the Dataverse instance
  environment: string // Dev | Test | UAT | Prod - Defines the type as established by the user
  clientId: string // Application (client) ID used for authentication
  tenantId: string // Tenant ID of the Azure AD tenant
  createdAt: string // ISO date string of when the connection was created
  lastUsedAt: string // ISO date string of when the connection was last used
}

Secondary Connections

As a tool developer, you may require access to a second Dataverse connections. This can be useful for copying data or configuration between environments.

To enable this feature, you must update the package.json file to indicate your tool requires multiconnections.

{
  "name": "@toolname",
  "version": "0.1.10",
  "displayName": " My Awesome Tool",
  "description": "A Power Platform Tool Box tool to do awesome things",
  "main": "index.html",
  "contributors": [
    "Awesome Developer "
  ],
  // Other properties...
  // This section enables multiple connections
  "features": {
    "multiConnection": "required" or "optional"
  },

When the user opens your tool, they are presented with the option to connect to a primary and secondary environment.

toolboxAPI.connections.getSecondaryConnection()

Returns the currently active secoondary connection or null if none is configured.

const secondaryConnection =
  await toolboxAPI.connections.getSecondaryConnection()

if (secondaryConnection) {
  console.log('Connected to:', secondaryConnection.name)
  console.log('Environment:', secondaryConnection.environment)
  console.log('API URL:', secondaryConnection.apiUrl)
} else {
  console.log('No active secondary connection')
}

Returns: Promise<DataverseConnection | null>

interface DataverseConnection {
  id: string // Unique identifier of the connection
  name: string // Friendly name of the connection
  url: string // Base URL of the Dataverse instance
  environment: string // Dev | Test | UAT | Prod - Defines the type as established by the user
  clientId: string // Application (client) ID used for authentication
  tenantId: string // Tenant ID of the Azure AD tenant
  createdAt: string // ISO date string of when the connection was created
  lastUsedAt: string // ISO date string of when the connection was last used
}

When interacting with dataverse and you want to use the secondary connection, pass the connectionTarget parameter as 'secondary'. ConnectionTarget is optional and defaults to 'primary'.

// Example usage of dataverseAPI using secondary connection
const myTables = await dataverseAPI.getAllEntitiesMetadata(
  ['logicalName'],
  'secondary',
)

Utils

Utility functions for notifications, clipboard, and more.

toolboxAPI.utils.showNotification(options)

Display a notification to the user.

await toolboxAPI.utils.showNotification({
  title: 'Success',
  body: 'Operation completed successfully',
  type: 'success', // 'info' | 'success' | 'warning' | 'error'
  duration: 3000, // Auto-dismiss after 3 seconds
})

Parameters:

  • options - Notification configuration object

Types:

  • type: 'info' | 'success' | 'warning' | 'error'
  • duration: Number in milliseconds (0 = persistent)

toolboxAPI.utils.copyToClipboard(text)

Copy text to the system clipboard.

const data = JSON.stringify({ accounts: [], contacts: [] }, null, 2)
await toolboxAPI.utils.copyToClipboard(data)

await toolboxAPI.utils.showNotification({
  title: 'Copied',
  body: 'Data copied to clipboard',
  type: 'success',
})

toolboxAPI.utils.getCurrentTheme()

Get the current application theme.

const theme = await toolboxAPI.utils.getCurrentTheme()
document.body.classList.add(`theme-${theme}`)

Returns: Promise<'light' | 'dark'>

toolboxAPI.utils.showLoading(message) / hideLoading()

Show/hide a loading overlay.

await toolboxAPI.utils.showLoading('Fetching data from Dataverse...')

try {
  // Perform long-running operations
  const data = await fetchLargeDataset()
  processData(data)

  await toolboxAPI.utils.showNotification({
    title: 'Success',
    body: 'Data processed successfully',
    type: 'success',
  })
} finally {
  await toolboxAPI.utils.hideLoading()
}

toolboxAPI.utils.executeParallel(...promises)

Execute multiple async operations in parallel.

const [account, contact, opportunities] =
  await toolboxAPI.utils.executeParallel(
    dataverseAPI.retrieve('account', accountId, ['name']),
    dataverseAPI.retrieve('contact', contactId, ['fullname']),
    dataverseAPI.fetchXmlQuery(opportunityFetchXml),
  )

console.log('All data fetched:', account, contact, opportunities)

Settings

Store and retrieve tool-specific settings.

toolboxAPI.settings.get(key, defaultValue?)

Retrieve a setting value for your tool.

const theme = await toolboxAPI.settings.get('theme', 'light')
const pageSize = await toolboxAPI.settings.get('pageSize', 25)

toolboxAPI.settings.set(key, value)

Save a setting value for your tool.

await toolboxAPI.settings.set('theme', 'dark')
await toolboxAPI.settings.set('pageSize', 50)

toolboxAPI.settings.remove(key)

Remove a setting.

await toolboxAPI.settings.remove('theme')

toolboxAPI.settings.clear()

Clear all settings for your tool.

await toolboxAPI.settings.clear()

Terminal

Create and manage terminal sessions (context-aware to your tool).

toolboxAPI.terminal.create(options)

Create a new terminal.

const terminal = await toolboxAPI.terminal.create({
  name: 'Build Terminal',
  cwd: '/path/to/project',
  env: {
    NODE_ENV: 'production',
  },
})

console.log('Terminal created:', terminal.id)

toolboxAPI.terminal.execute(terminalId, command)

Execute a command in a terminal.

const result = await toolboxAPI.terminal.execute(terminal.id, 'npm install')

if (result.exitCode === 0) {
  console.log('Command completed successfully')
} else {
  console.error('Command failed:', result.error)
}

toolboxAPI.terminal.setVisibility(terminalId, visible)

Show or hide a terminal's UI panel.

await toolboxAPI.terminal.setVisibility(terminal.id, true)

toolboxAPI.terminal.list()

List all terminals created by your tool.

const terminals = await toolboxAPI.terminal.list()
console.log(`This tool has ${terminals.length} terminals`)

toolboxAPI.terminal.close(terminalId)

Close a terminal.

await toolboxAPI.terminal.close(terminal.id)

Events

Subscribe to platform events.

toolboxAPI.events.on(handler)

Subscribe to events relevant to your tool.

toolboxAPI.events.on((event, payload) => {
  console.log('Event:', event, 'Data:', payload)

  switch (event) {
    case 'connection:updated':
      refreshConnectionInfo()
      break
    case 'connection:activated':
      handleConnectionActivated(payload)
      break
    case 'settings:updated':
      if (payload && payload.theme) {
        applyTheme(payload.theme)
      }
      break
  }
})

Event Types:

  • connection:updated - Active connection changed
  • connection:activated - Connection activated
  • connection:deactivated - Connection deactivated
  • settings:updated - Settings, including Theme has been updated
  • tool:activated - Your tool tab activated
  • tool:deactivated - Your tool tab deactivated

Dataverse API

Complete HTTP client for interacting with Microsoft Dataverse.

CRUD Operations

Each method accepts an optional connectionTarget parameter to specify which connection to use ('primary' | 'secondary'). Defaults to 'primary'.

dataverseAPI.create(entityName, record, connectionTarget?)

Creates a new record in the primary or secondary dataverse.
Parameters:
entityName: string Logical name of the entity
record: Record<string, unknown> Object containing the record data to create
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<string> String representing the created record ID

// Create account using primary connection
const accountId = await dataverseAPI.create('account', {
  name: 'Contoso Ltd',
  telephone1: '555-1234',
  websiteurl: 'https://contoso.com',
})
console.log('Created account:', accountId)

// Create contact using secondary connection
const contactId = await dataverseAPI.create(
  'contact',
  {
    firstname: 'Dave',
  },
  'secondary',
)
console.log('Created contact in secondary connection:', contactId)

dataverseAPI.retrieve(entityLogicalName, id, columns?, connectionTarget?)

Retrieve a single record. Parameters:
entityLogicalName: string Logical name of the entity id: string GUID of the record to retrieve
columns?: string[] Optional array of column names to retrieve (retrieves all if not specified)
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<Record<string, any>> Object representing the retrieved record

// Retrieve an account record using the primary connection
const account = await dataverseAPI.retrieve('account', accountId, [
  'name',
  'telephone1',
  'emailaddress1',
])

console.log('Account name:', account.name)

// Retrieve all fields for a contact record using the secondary connection
// Best practice to only retrieve needed columns to optimize performance
const contact = await dataverseAPI.retrieve(
  'contact',
  contactId,
  undefined,
  'secondary',
)
console.log('Contact name:', contact.fullname)

dataverseAPI.update(entityLogicalName, id, record, connectionTarget?)

Update an existing record.
Parameters:
entityLogicalName: string Logical name of the entity
id: string GUID of the record to update
record: Record<string, unknown> Object containing the record data to update
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<void> Successful completion

/// Updating an account record using the primary connection
await dataverseAPI.update('account', accountId, {
  telephone1: '555-5678',
  websiteurl: 'https://www.contoso.com',
})

/// Updating a contact record using the secondary connection
await dataverseAPI.update(
  'contact',
  contactId,
  { firstname: 'David', lastname: 'Smith' },
  'secondary',
)

dataverseAPI.delete(entityLogicalName, id, connectionTarget?)

Deletes a record.
Parameters:
entityLogicalName: string Logical name of the entity
id: string GUID of the record to delete
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<void> Successful completion

/// Deleting an account record using the primary connection
await dataverseAPI.delete('account', 'e15a8347-f958-4c20-b964-a8d7105f645f')
/// Deleting a contact record using the secondary connection
await dataverseAPI.delete(
  'contact',
  'e15a8347-f958-4f20-b964-a8d7105f645f',
  'secondary',
)

dataverseAPI.createMultiple(entityLogicalName, records, connectionTarget?)

Creates multiple records in Dataverse
Parameters:
entityLogicalName Logical name of the entity
records Array of record data to create, each including the "@odata.type" property
connectionTarget Optional connection target for multi-connection tools ('primary' or 'secondary').
Defaults to 'primary'.
Returns: Promise<string[]> Array of strings representing the created record IDs

const results = await dataverseAPI.createMultiple('account', [
  { name: 'Contoso Ltd', '@odata.type': 'Microsoft.Dynamics.CRM.account' },
  { name: 'Fabrikam Inc', '@odata.type': 'Microsoft.Dynamics.CRM.account' },
])

dataverseAPI.updateMultiple(entityLogicalName, records, connectionTarget?)

Updates multiple records in Dataverse
Parameters:
entityLogicalName Logical name of the entity
records Array of record data to update, each including the "id" property and the "@odata.type" property
connectionTarget Optional connection target for multi-connection tools ('primary' or 'secondary').
Defaults to 'primary'.
Returns: Promise<void> Successful completion

await dataverseAPI.updateMultiple('account', [
  {
    accountid: 'guid-1',
    name: 'Updated Name 1',
    '@odata.type': 'Microsoft.Dynamics.CRM.account',
  },
  {
    accountid: 'guid-2',
    name: 'Updated Name 2',
    '@odata.type': 'Microsoft.Dynamics.CRM.account',
  },
])

Queries

dataverseAPI.fetchXmlQuery(fetchXml, connectionTarget?)

Execute a FetchXML query.
Parameters:
fetchXml: string FetchXML query string
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection
Returns: Promise<FetchXmlResult> Object with value array containing query results, odata context and paging cookie

FetchXmlResult Type:
value: Record<string, unknown>[] Array of records returned by the query
@odata.context: string OData context URL
@Microsoft.Dynamics.CRM.fetchxmlpagingcookie?: string Paging cookie for retrieving additional pages

const fetchXml = `
  <fetch top="10">
    <entity name="account">
      <attribute name="name" />
      <attribute name="accountid" />
      <filter>
        <condition attribute="statecode" operator="eq" value="0" />
      </filter>
      <order attribute="name" />
    </entity>
  </fetch>
`

const result = await dataverseAPI.fetchXmlQuery(fetchXml)

result.value.forEach((account) => {
  console.log('Account:', account.name)
})

dataverseAPI.queryData(odataQuery, connectionTarget?)

Retrieve multiple records with OData query options.

Parameters:
odataQuery: string OData query string with parameters like $select, $filter, $orderby, $top, $skip, $expand
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<{ value: Record<string, unknown>[] }> Object with value array containing query results

// Get top 10 active accounts with specific fields
const result = await dataverseAPI.queryData(
  'accounts?$select=name,emailaddress1,telephone1&$filter=statecode eq 0&$orderby=name&$top=10',
)
console.log(`Found ${result.value.length} records`)
result.value.forEach((record) => {
  console.log(`${record.name} - ${record.emailaddress1}`)
})

// Query with expand to include related records
const result = await dataverseAPI.queryData(
  'accounts?$select=name,accountid&$expand=contact_customer_accounts($select=fullname,emailaddress1)&$top=5',
)

// Simple query with just a filter
const result = await dataverseAPI.queryData(
  `contacts?$filter=contains(fullname, 'Smith')&$top=20`,
)

// Multi-connection tool using secondary connection
const result = await dataverseAPI.queryData(
  'contacts?$filter=statecode eq 0',
  'secondary',
)

Metadata

dataverseAPI.getEntityMetadata(entityLogicalName, searchByLogicalName?, selectColumns?, connectionTarget?)

Get entity metadata.
Parameters:
entityLogicalName: string Logical name or entity id of the entity
searchByLogicalName?: boolean Boolean indicating whether to search by logical name (true) or metadata ID (false)
selectColumns?: string[] Optional array of column names to retrieve (retrieves all if not specified)
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<any> Object containing entity metadata

const metadata = await dataverseAPI.getEntityMetadata('account', true, [
  'LogicalName',
  'DisplayName',
  'EntitySetName',
])
console.log('Logical Name:', metadata.LogicalName)
console.log('Display Name:', metadata.DisplayName?.LocalizedLabels[0]?.Label)

// Get entity metadata by metadata ID
const metadata = await dataverseAPI.getEntityMetadata(
  '00000000-0000-0000-0000-000000000001',
  false,
  ['LogicalName', 'DisplayName'],
)
console.log('Entity Metadata ID:', metadata.MetadataId)
console.log('Logical Name:', metadata.LogicalName)
console.log('Display Name:', metadata.DisplayName?.LocalizedLabels[0]?.Label)

// Multi-connection tool using secondary connection
const metadata = await dataverseAPI.getEntityMetadata(
  'account',
  true,
  ['LogicalName'],
  'secondary',
)
console.log('Logical Name from secondary connection:', metadata.LogicalName)

dataverseAPI.getEntityRelatedMetadata(entityLogicalName, relatedPath, selectColumns?, connectionTarget?)

Get related metadata for a specific entity (attributes, relationships, etc.)
Parameters:
entityLogicalName: string Logical name of the entity
relatedPath: string Path after EntityDefinitions(LogicalName='name') (e.g., 'Attributes', 'OneToManyRelationships', 'ManyToOneRelationships', 'ManyToManyRelationships', 'Keys')
selectColumns?: string[] Optional array of column names to retrieve (retrieves all if not specified)
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<{ value: any[] }> Object with value array containing related metadata

// Get all attributes for an entity
const attributes = await dataverseAPI.getEntityRelatedMetadata(
  'account',
  'Attributes',
)
console.log('Attributes:', attributes.value)

// Get specific attributes with select
const attributes = await dataverseAPI.getEntityRelatedMetadata(
  'account',
  'Attributes',
  ['LogicalName', 'DisplayName', 'AttributeType'],
)
console.log('Filtered attributes:', attributes.value)

// Get one-to-many relationships
const relationships = await dataverseAPI.getEntityRelatedMetadata(
  'account',
  'OneToManyRelationships',
)
console.log('One-to-many relationships:', relationships.value)

// Multi-connection tool using secondary connection
const attributes = await dataverseAPI.getEntityRelatedMetadata(
  'account',
  'Attributes',
  ['LogicalName'],
  'secondary',
)
console.log('Attributes from secondary connection:', attributes.value)

dataverseAPI.getAllEntitiesMetadata(selectColumns?, connectionTarget?)

Get metadata for all entities
Parameters:
selectColumns?: string[] Optional array of column names to retrieve (retrieves LogicalName, DisplayName, MetadataId by default)
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<{ value: any[] }> Object with value array containing all entity metadata

const allEntities = await dataverseAPI.getAllEntitiesMetadata([
  'LogicalName',
  'DisplayName',
  'EntitySetName',
])
console.log(`Total entities: ${allEntities.value.length}`)
allEntities.value.forEach((entity) => {
  console.log(
    `${entity.LogicalName} - ${entity.DisplayName?.LocalizedLabels[0]?.Label}`,
  )
})

// Multi-connection tool using secondary connection
const allEntities = await dataverseAPI.getAllEntitiesMetadata(
  ['LogicalName'],
  'secondary',
)

dataverseAPI.getEntitySetName(logicalName)

Get the entity set name for a given logical name. No connectionTarget needed. This will work in most scenarios but if you have custom entities with non-standard pluralization you may need to retrieve the metadata instead.

Parameters:
logicalName: string Logical name of the entity
Returns: Promise<string> Entity set name as a string

const tableSetName = await dataverseAPI.getEntitySetName('contact')

console.log('Entity Set Name for contact:', tableSetName) // Outputs: contacts

dataverseAPI.getSolutions(selectColumns, connectionTarget?)

Get solutions from the environment
Parameters:
selectColumns: string[] Required array of column names to retrieve (must contain at least one column)
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'.
Returns: Promise<{ value: any[] }> Object with value array containing solutions

const solutions = await dataverseAPI.getSolutions([
  'solutionid',
  'uniquename',
  'friendlyname',
  'version',
  'ismanaged',
])
console.log(`Total solutions: ${solutions.value.length}`)
solutions.value.forEach((solution) => {
  console.log(
    `${solution.friendlyname} (${solution.uniquename}) - v${solution.version}`,
  )
})

// Multi-connection tool using secondary connection
const solutions = await dataverseAPI.getSolutions(['uniquename'], 'secondary')

Actions & Functions

dataverseAPI.executeAction(actionName, parameters)

Execute a custom action.

const result = await dataverseAPI.executeAction('new_CustomAction', {
  InputParameter1: 'value1',
  InputParameter2: 123,
})

console.log('Action result:', result)

dataverseAPI.executeFunction(functionName, parameters)

Execute a custom function.

const result = await dataverseAPI.executeFunction('new_CustomFunction', {
  Parameter1: 'value',
})

console.log('Function result:', result)

dataverseAPI.publishCustomizations(tableLogicalName?, connectionTarget?)

Publish customizations for the current environment.
Parameters:
tableLogicalName?: string Optional table (entity) logical name to publish. If omitted, all pending customizations are published.
connectionTarget?: 'primary' | 'secondary' Optional connection target for multi-connection tools ('primary' or 'secondary'). Defaults to 'primary'. Returns: Promise<void> Successful completion

// Publish all customizations for the primary connection
await dataverseAPI.publishCustomizations()

// Publish only the account table customizations for the secondary connection
await dataverseAPI.publishCustomizations('account', 'secondary')

Settings API

The settings API allows tool specific settings to be stored and retrieved between sessions.

toolboxAPI.settings.getAll()

Retrieve all settings for your tool.
Returns: Promise<Record<string, any>> Object containing all settings key-value pairs

const settings = await toolboxAPI.settings.getAll()
console.log('All settings:', JSON.stringify(settings))

toolboxAPI.settings.get(key)

Retrieve a specific setting by key.
Parameters:
key: string The setting key to retrieve
Returns: Promise<any> Value of the setting or undefined if not found

const pageSize = await toolboxAPI.settings.get('pageSize')
console.log('Page Size setting:', pageSize)

toolboxAPI.settings.set(key, value)

Set a specific setting by key.
Parameters:
key: string The setting key to set
value: any The value to store for the setting
Returns: Promise<void> Successful completion

await toolboxAPI.settings.set('pageSize', 50)

toolboxAPI.settings.setAll(settings)

Set multiple settings at once.
Parameters:
settings: Record<string, any> Object containing key-value pairs to set
Returns: Promise<void> Successful completion

await toolboxAPI.settings.setAll({
  defaultColor: 'blue',
  pageSize: 50,
  showAdvancedOptions: true,
})

File System API

The File System API provides secure access to read and write files, manage directories, and interact with the local file system. All functions include path validation for security.

Reading Files

toolboxAPI.fileSystem.readText(path)

Read a UTF-8 text file (useful for configs, JSON files, manifests, etc.).

try {
  const configPath = '/path/to/config.json'
  const content = await toolboxAPI.fileSystem.readText(configPath)
  const config = JSON.parse(content)
  console.log('Config loaded:', config)
} catch (error) {
  console.error('Failed to read config:', error)
}

Parameters:

  • path: string - Absolute path to the file

Returns: Promise<string> - File content as UTF-8 string

toolboxAPI.fileSystem.readBinary(path)

Read a binary file as a Buffer (useful for ZIPs, images for hashing/upload, etc.). Properly serializes over IPC.

try {
  const imagePath = '/path/to/image.png'
  const buffer = await toolboxAPI.fileSystem.readBinary(imagePath)
  console.log('Image size:', buffer.length, 'bytes')
  
  // Use buffer for hashing, upload, or other operations
  const hash = crypto.createHash('sha256').update(buffer).digest('hex')
  console.log('Image hash:', hash)
} catch (error) {
  console.error('Failed to read image:', error)
}

Parameters:

  • path: string - Absolute path to the file

Returns: Promise<Buffer> - File content as Buffer

File System Queries

toolboxAPI.fileSystem.exists(path)

Lightweight check to verify if a file or directory exists before performing I/O operations.

const configPath = '/path/to/config.json'

if (await toolboxAPI.fileSystem.exists(configPath)) {
  const content = await toolboxAPI.fileSystem.readText(configPath)
  console.log('Config exists and loaded')
} else {
  console.log('Config file not found, using defaults')
}

Parameters:

  • path: string - Absolute path to check

Returns: Promise<boolean> - True if path exists, false otherwise

toolboxAPI.fileSystem.stat(path)

Get metadata about a file or directory. Properly handles symlinks.

const filePath = '/path/to/file.txt'
const stats = await toolboxAPI.fileSystem.stat(filePath)

console.log('Type:', stats.type) // 'file' or 'directory'
console.log('Size:', stats.size, 'bytes')
console.log('Modified:', new Date(stats.mtime))

Parameters:

  • path: string - Absolute path to the file or directory

Returns: Promise<FileStats> - File/directory metadata

interface FileStats {
  type: 'file' | 'directory' // Type of the path
  size: number // Size in bytes
  mtime: number // Last modified timestamp (milliseconds since epoch)
}

toolboxAPI.fileSystem.readDirectory(path)

List the contents of a directory. Returns only files and directories, excludes symlinks.

const dirPath = '/path/to/directory'
const contents = await toolboxAPI.fileSystem.readDirectory(dirPath)

contents.forEach((item) => {
  console.log(`${item.name} (${item.type})`)
})

// Filter for specific types
const files = contents.filter((item) => item.type === 'file')
const directories = contents.filter((item) => item.type === 'directory')

console.log(`Found ${files.length} files and ${directories.length} directories`)

Parameters:

  • path: string - Absolute path to the directory

Returns: Promise<DirectoryEntry[]> - Array of directory entries

interface DirectoryEntry {
  name: string // Name of the file or directory
  type: 'file' | 'directory' // Type of the entry
}

Writing Files and Directories

toolboxAPI.fileSystem.writeText(path, content)

Save text content to a file without a dialog prompt. Useful for automated exports and backups.

const exportData = {
  accounts: [],
  contacts: [],
  timestamp: new Date().toISOString(),
}

const exportPath = '/path/to/export.json'
await toolboxAPI.fileSystem.writeText(
  exportPath,
  JSON.stringify(exportData, null, 2),
)

console.log('Export saved to:', exportPath)

Parameters:

  • path: string - Absolute path where the file should be saved
  • content: string - Text content to write

Returns: Promise<void> - Successful completion

toolboxAPI.fileSystem.createDirectory(path)

Create a directory recursively (creates parent directories as needed).

const backupDir = '/path/to/backups/2024/january'
await toolboxAPI.fileSystem.createDirectory(backupDir)

console.log('Directory created:', backupDir)

// Now you can write files to this directory
await toolboxAPI.fileSystem.writeText(
  `${backupDir}/backup.json`,
  JSON.stringify(data),
)

Parameters:

  • path: string - Absolute path of the directory to create

Returns: Promise<void> - Successful completion

User-Interactive File Operations

toolboxAPI.fileSystem.saveFile(filename, content)

Save content to a file with a user-selected location. Opens a native save dialog.

const jsonData = { accounts: [], contacts: [] }
const filePath = await toolboxAPI.fileSystem.saveFile(
  'export.json',
  JSON.stringify(jsonData, null, 2),
)

if (filePath) {
  console.log('File saved to:', filePath)
} else {
  console.log('Save cancelled')
}

Parameters:

  • filename: string - Suggested filename for the save dialog
  • content: string - Content to save

Returns: Promise<string | null> - File path or null if cancelled

toolboxAPI.fileSystem.selectPath(options?)

Open a native dialog to select either a file or a folder and return the chosen path.

// Select a folder
const folderPath = await toolboxAPI.fileSystem.selectPath({
  type: 'folder',
  title: 'Select Export Folder',
})

if (folderPath) {
  console.log('Selected folder:', folderPath)
} else {
  console.log('Selection cancelled')
}
// Select a file
const filePath = await toolboxAPI.fileSystem.selectPath({
  type: 'file',
  title: 'Select Configuration File',
  filters: [
    { name: 'JSON Files', extensions: ['json'] },
    { name: 'All Files', extensions: ['*'] },
  ],
})

if (filePath) {
  console.log('Selected file:', filePath)
  // Read the selected file
  const content = await toolboxAPI.fileSystem.readText(filePath)
  console.log('File content:', content)
}

Parameters:

  • options - Optional configuration object
    • type: 'file' | 'folder' - Type of selection dialog
    • title: string - Dialog window title
    • filters: Array<{ name: string; extensions: string[] }> - File filters (file dialogs only)

Returns: Promise<string | null> - Selected path or null if cancelled

Error Handling

All API calls may throw errors. Always use try-catch blocks:

try {
  const account = await dataverseAPI.retrieve('account', accountId)
  // Process account
} catch (error) {
  console.error('Failed to retrieve account:', error)

  await toolboxAPI.utils.showNotification({
    title: 'Error',
    body: error.message,
    type: 'error',
    duration: 0, // Persistent
  })
}

Next Steps

Was this page helpful?