> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dragdropdo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> The official `dragdropdo-sdk` package provides a high‑level, type‑safe interface to the D3 Business API.

## Installation

```bash theme={null}
npm install dragdropdo-sdk
```

## Quick start

```ts theme={null}
import { Dragdropdo } from "dragdropdo-sdk";

// Initialize the client
const client = new Dragdropdo({
  apiKey: "your-api-key-here",
  baseURL: "https://api.dragdropdo.com", // Optional, defaults to https://api.dragdropdo.com
  timeout: 30000, // Optional, defaults to 30000ms
});

// Upload a file
const uploadResult = await client.uploadFile({
  file: "/path/to/document.pdf",
  fileName: "document.pdf",
  mimeType: "application/pdf",
});

console.log("File key:", uploadResult.fileKey);
```

## Initialization

```ts theme={null}
new Dragdropdo(config: D3ClientConfig)
```

**Config:**

* `apiKey` (**required**) – your D3 API key.
* `baseURL` (optional) – API base URL, default: `https://api.dragdropdo.com`.
* `timeout` (optional) – request timeout in ms, default: `30000`.
* `headers` (optional) – additional headers to send with every request.

## File upload

```ts theme={null}
uploadFile(options: UploadFileOptions): Promise<UploadResponse>
```

**Options:**

* `file` (**required**) – file path string.
* `fileName` (**required**) – original file name.
* `mimeType` (optional) – MIME type (auto‑detected if omitted).
* `parts` (optional) – number of upload parts (auto‑calculated).
* `onProgress` (optional) – progress callback.

Example:

```ts theme={null}
const result = await client.uploadFile({
  file: "/path/to/file.pdf",
  fileName: "document.pdf",
  mimeType: "application/pdf",
  onProgress: (progress) => {
    console.log(`Upload: ${progress.percentage}%`);
  },
});
```

## Supported operations

```ts theme={null}
checkSupportedOperation(
  options: SupportedOperationOptions
): Promise<SupportedOperationResponse>
```

**Options:**

* `ext` (**required**) – file extension (e.g. `pdf`, `jpg`).
* `action` (optional) – specific action (`convert`, `compress`, ...).
* `parameters` (optional) – parameters to validate (e.g. `{ convert_to: "png" }`).

Examples:

```ts theme={null}
// Get available actions for PDF
const actions = await client.checkSupportedOperation({ ext: "pdf" });
console.log(actions.availableActions);

// Check if convert to PNG is supported
const supported = await client.checkSupportedOperation({
  ext: "pdf",
  action: "convert",
  parameters: { convert_to: "png" },
});
console.log("Supported:", supported.supported);
```

## Create operations

```ts theme={null}
createOperation(options: OperationOptions): Promise<OperationResponse>
```

**Options:**

* `action` (**required**) – `"convert" | "compress" | "merge" | "zip" | "lock" | "unlock" | "reset_password"`.
* `fileKeys` (**required**) – array of file keys from upload.
* `parameters` (optional) – action‑specific parameters.
* `notes` (optional) – user metadata.

Examples:

```ts theme={null}
// Convert PDF to PNG
await client.createOperation({
  action: "convert",
  fileKeys: [uploadResult.fileKey],
  parameters: { convert_to: "png" },
  notes: { userId: "user-123" },
});

// Compress
await client.createOperation({
  action: "compress",
  fileKeys: [uploadResult.fileKey],
  parameters: { compression_value: "recommended" },
});
```

### Convenience helpers

The client exposes shorthand helpers:

```ts theme={null}
await client.convert(fileKeys, convertTo, notes?);
await client.compress(fileKeys, compressionValue?, notes?);
await client.merge(fileKeys, notes?);
await client.zip(fileKeys, notes?);
await client.lockPdf(fileKeys, password, notes?);
await client.unlockPdf(fileKeys, password, notes?);
await client.resetPdfPassword(fileKeys, oldPassword, newPassword, notes?);
```

## Status & polling

```ts theme={null}
getStatus(options: StatusOptions): Promise<StatusResponse>
pollStatus(options: PollStatusOptions): Promise<StatusResponse>
```

**`StatusOptions`** (used by `getStatus`):

* `mainTaskId` (**required**) – main task ID from `createOperation` / convenience helpers.
* `fileKey` (optional) – when set, requests status for that specific input file.

**`PollStatusOptions`** (extends `StatusOptions`; used by `pollStatus`):

* Same fields as `StatusOptions`, plus:
* `interval` (optional) – milliseconds between polls, default `2000`.
* `timeout` (optional) – maximum total polling time in milliseconds, default `300000` (5 minutes).
* `onUpdate` (optional) – `(status: StatusResponse) => void`, invoked after each successful status fetch.

Examples:

```ts theme={null}
// Single status fetch
const status = await client.getStatus({ mainTaskId: "task-123" });

// Poll until completion
const finalStatus = await client.pollStatus({
  mainTaskId: "task-123",
  interval: 2000,
  timeout: 300000,
  onUpdate: (status) => {
    console.log("Status:", status.operationStatus);
  },
});
```

## Complete workflow example

```ts theme={null}
import { Dragdropdo, D3APIError, D3ValidationError } from "dragdropdo-sdk";

async function processFile() {
  const client = new Dragdropdo({
    apiKey: process.env.D3_API_KEY!,
    baseURL: "https://api.dragdropdo.com",
  });

  try {
    // 1. Upload
    const uploadResult = await client.uploadFile({
      file: "./document.pdf",
      fileName: "document.pdf",
    });

    // 2. Check support
    const supported = await client.checkSupportedOperation({
      ext: "pdf",
      action: "convert",
      parameters: { convert_to: "png" },
    });
    if (!supported.supported)
      throw new Error("Convert to PNG is not supported");

    // 3. Create operation
    const operation = await client.convert([uploadResult.fileKey], "png", {
      userId: "user-123",
      source: "api",
    });

    // 4. Poll
    const status = await client.pollStatus({
      mainTaskId: operation.mainTaskId,
      interval: 2000,
    });

    if (status.operationStatus === "completed") {
      status.filesData.forEach((file) => {
        console.log(`Download: ${file.downloadLink}`);
      });
    }
  } catch (error) {
    if (error instanceof D3APIError) {
      console.error(`API Error (${error.statusCode}):`, error.message);
    } else if (error instanceof D3ValidationError) {
      console.error("Validation Error:", error.message);
    } else {
      console.error("Error:", error);
    }
  }
}
```
