# SDK Overview
Under Active Development
SDK APIs are subject to change (2026)
The tdx SDK provides a TypeScript/JavaScript API for interacting with Treasure Data, usable in both Node.js and browser environments.
## Installation
```bash
npm install @treasuredata/tdx
```
## Quick Start
### Node.js
```typescript
import { TDX } from '@treasuredata/tdx/sdk';
// Create TDX instance (loads API key from environment if not provided)
const tdx = TDX.create({
site: 'us01',
apiKey: 'your_key_id/your_key_secret' // Optional: omit to load from env
});
// List databases
const databases = await tdx.query.listDatabases();
// Run a query
const result = await tdx.query.execute('SELECT * FROM mydb.users LIMIT 10');
```
### Browser
```html
```
## Configuration
### SDKConfig Options
| Option | Type | Description | Default |
| --- | --- | --- | --- |
| `site` | string | TD site (us01, jp01, eu01, ap02) | us01 |
| `apiKey` | string | API key (key_id/key_secret) | from env |
| `logLevel` | LogLevel | Log level (TRACE, DEBUG, INFO, WARN, ERROR) | INFO |
| `proxy` | string | HTTP proxy URL for corporate networks | from config/env |
### Creating TDX Instance
```typescript
import { TDX, LogLevel } from '@treasuredata/tdx/sdk';
// Load API key from environment variables
const tdx = TDX.create();
// Override specific options
const tdx = TDX.create({
site: 'jp01',
logLevel: LogLevel.DEBUG
});
// Pass API key directly
const tdx = TDX.create({
apiKey: 'your_key_id/your_key_secret'
});
// Use an HTTP proxy (corporate networks)
const tdx = TDX.create({
site: 'us01',
proxy: 'http://proxy.corp.com:8080'
});
```
## API Modules
The SDK exposes several API modules via the `TDX` class:
| Module | Property | Description |
| --- | --- | --- |
| QuerySDK | `tdx.query` | Execute queries, list databases/tables, describe schemas |
| JobSDK | `tdx.jobs` | Submit and manage jobs |
| SegmentSDK | `tdx.segment` | CDP segment operations |
| WorkflowSDK | `tdx.workflow` | Workflow management |
| LLMSDK | `tdx.llm` | LLM projects and agents |
| RawAPI | `tdx.api` | Raw HTTP requests to TD APIs |
The `QuerySDK` module provides all query and schema operations via `tdx.query.*`.
API Reference
See the full [API Reference](https://tdx.treasuredata.com/api/) for detailed documentation of all classes, interfaces, and types.
## Examples
### List Databases
```typescript
const databases = await tdx.query.listDatabases();
for (const db of databases) {
console.log(db.database_name);
}
// Filter by pattern
const prodDbs = await tdx.query.listDatabases('prod_*');
```
### List Tables
```typescript
// List all tables in a database
const tables = await tdx.query.listTables('mydb');
// Filter by pattern
const userTables = await tdx.query.listTables('mydb', 'user_*');
```
### Run a Query
```typescript
const result = await tdx.query.execute('SELECT * FROM mydb.users LIMIT 10');
for (const row of result.data) {
console.log(row);
}
// Access column metadata
console.log('Columns:', result.columns.map(c => c.name));
```
### Get Table Schema
```typescript
const columns = await tdx.query.describeTable('mydb', 'users');
for (const col of columns) {
console.log(col.column_name, col.data_type, col.is_nullable);
}
```
### Show Table Contents
```typescript
const result = await tdx.query.showTable('mydb', 'users', 10);
for (const row of result.data) {
console.log(row);
}
```
### Submit a Job
```typescript
const job = await tdx.jobs.submit('mydb', 'SELECT * FROM users', 'trino');
console.log('Job ID:', job.job_id);
// Get job results
const results = await tdx.jobs.result(job.job_id);
```
## Error Handling
```typescript
import { SDKError, ErrorCode } from '@treasuredata/tdx/sdk';
try {
await tdx.query.execute('INVALID SQL');
} catch (error) {
if (error instanceof SDKError) {
console.error('Error code:', error.code);
console.error('Message:', error.message);
// Check for specific error types
if (error.code === ErrorCode.TRINO_SYNTAX_ERROR) {
console.error('SQL syntax error');
}
}
}
```
## TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
```typescript
import type {
SDKConfig,
DatabaseInfo,
TableInfo,
ColumnInfo,
CompleteQueryResult
} from '@treasuredata/tdx/sdk';
// Typed query results
const result: CompleteQueryResult<{ id: number; name: string }> =
await tdx.query.execute<{ id: number; name: string }>('SELECT id, name FROM users');
// result.data is typed as { id: number; name: string }[]
```
## Architecture
The tdx project is designed with a layered architecture that separates the CLI interface from the core SDK.
### High-Level Architecture
```mermaid
flowchart TB
subgraph Clients["Client Environments"]
CLI["Node.js / CLI
tdx commands"]
Browser["Web Browser
Client-side Apps"]
end
subgraph SDK["TDX SDK (TypeScript)"]
SDKAPI["TypeScript/JavaScript API"]
end
subgraph APIs["Treasure Data APIs"]
REST["TD REST API
(DB, Table, Job)"]
Trino["Trino API
(Queries)"]
CDP["CDP API
(Segments)"]
LLM["LLM API
(AI/Chat)"]
end
CLI --> SDKAPI
Browser --> SDKAPI
SDKAPI --> REST
SDKAPI --> Trino
SDKAPI --> CDP
SDKAPI --> LLM
```
### Key Architectural Patterns
#### SDK Configuration Pattern
Configuration is separated from object instantiation:
- **Configuration is a pure data structure** - No loading logic in config objects
- **Load configuration outside constructors** - Use dedicated loading functions
- **Pass configuration objects to constructors** - Not individual parameters
```typescript
// Config loading function: loadConfigOnce(options) → Config
// SDK/Client constructors: constructor(config: Config)
// CLI creates config once, passes to all components
```
#### Dependency Injection
Dependencies are passed instead of created:
- **Commands receive SDK instance via context** - Don't instantiate inside commands
- **Clients receive config object** - Don't load config inside clients
- **Create instances at application entry point** - CLI creates once, passes down
#### Command Pattern
Commands are thin wrappers over SDK:
- Receive dependencies via context (SDK instance, options, args)
- Call SDK methods for business logic
- Handle output formatting and display
- Return exit codes (0 = success, 1 = error)
#### SDK Layer
The SDK layer contains all business logic:
- Testable without CLI concerns
- Reusable programmatically
- Independent of framework (Commander.js, etc.)
- Works in multiple environments (Node.js, browser)
#### Client Layer
API clients handle HTTP communication:
- Accept configuration object in constructor
- Implement API protocols (REST, streaming, etc.)
- Handle retries, rate limiting, error handling
- Return structured data
### Configuration Loading
Configuration is loaded with priority order:
1. Explicitly passed values (highest priority)
2. Environment variables (site-specific, then generic)
3. Config files (site-specific, then generic)
4. Defaults (lowest priority)
### Multi-Site Support
| Site | API Endpoint |
| --- | --- |
| us01 (default) | api.treasuredata.com |
| jp01 | api.treasuredata.co.jp |
| eu01 | api.eu01.treasuredata.com |
| ap02 | api.ap02.treasuredata.com |
Site aliases are supported (us → us01, jp → jp01).