### Install Dependencies Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Run this command in the root directory to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install CloudConvert Node.js SDK Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Install the SDK using npm. This is the first step before using any of the SDK's functionalities. ```bash npm install --save cloudconvert ``` -------------------------------- ### Configure Dockerfile for CloudConvert Application Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Shows a Dockerfile setup for a Node.js application using CloudConvert. It includes installing dependencies and setting environment variables at runtime. ```dockerfile # Dockerfile FROM node:20 WORKDIR /app COPY package*.json ./ RUN npm install COPY . . # Environment variables passed at runtime ENV CLOUDCONVERT_API_KEY=${CLOUDCONVERT_API_KEY} ENV CLOUDCONVERT_REGION=${CLOUDCONVERT_REGION:-eu-west} ENV NODE_ENV=production CMD ["npm", "start"] ``` -------------------------------- ### WebhooksResource Methods Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Documentation for the WebhooksResource includes methods for verifying webhooks and a guide for complete webhook implementation. ```APIDOC ## WebhooksResource ### Description Provides methods for interacting with webhook functionalities, including verification and implementation guidance. ### Methods #### verify() ##### Description Verifies incoming webhooks. ##### Method (Not specified, likely a SDK method call) ##### Parameters (Not specified) ##### Return Type (Not specified) ### Complete webhook implementation guide (Documentation for implementing webhooks is available.) ``` -------------------------------- ### Triggering Missing Required Parameters Errors Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/errors.md These examples illustrate how to trigger 'Missing Required Parameters' errors. The first example shows a missing 'output_format' when converting a file, and the second shows a missing 'url' when setting up an import job. ```typescript // Missing required 'output_format' const task = await cloudConvert.tasks.create('convert', { input: 'other-task-id' // output_format missing }); // Missing required 'url' const job = await cloudConvert.jobs.create({ tasks: { 'import': { operation: 'import/url' // url missing } } }); ``` -------------------------------- ### Generate Signed URL with 24-Hour Caching Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/SignedUrlResource.md This example demonstrates how to create a signed URL that enables 24-hour caching of conversion results. Provide a unique `cacheKey` string to activate this feature. ```typescript // URL with 24-hour caching const cachedUrl = cloudConvert.signedUrls.sign( signedUrlBase, signingSecret, { tasks: { 'import-it': { operation: 'import/url', url: 'https://example.com/large-file.iso', filename: 'large-file.iso' }, 'export-it': { operation: 'export/url', input: 'import-it' } } }, 'my-cache-key-123' // Enables 24-hour caching ); console.log('Cached URL:', cachedUrl); // Output: https://s.cloudconvert.com/abc-123-def-456?job=&cache_key=my-cache-key-123&s= ``` -------------------------------- ### Download Files from a Completed Job Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md After a job is completed, retrieve the export URLs and download the output files. This example assumes the job has finished and demonstrates piping the file stream to a local file. ```javascript job = await cloudConvert.jobs.wait(job.id); // Wait for job completion const file = this.cloudConvert.jobs.getExportUrls(job)[0]; const writeStream = fs.createWriteStream('./out/' + file.filename); https.get(file.url, function (response) { response.pipe(writeStream); }); await new Promise((resolve, reject) => { writeStream.on('finish', resolve); writeStream.on('error', reject); }); ``` -------------------------------- ### Initialize CloudConvert SDK with Specific Region Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Instantiate the CloudConvert client with your API key and specify a region to reduce latency. Examples include 'us-east' and 'eu-west'. ```typescript // Specify a region for lower latency const usEastClient = new CloudConvert('your_api_key_here', false, 'us-east'); const euWestClient = new CloudConvert('your_api_key_here', false, 'eu-west'); ``` -------------------------------- ### get() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Retrieves a single task by its ID. You can optionally include related resources in the response. ```APIDOC ## GET /tasks/{id} ### Description Retrieves a single task by ID. ### Method GET ### Endpoint /tasks/{id} ### Parameters #### Path Parameters - **id** (string) - Yes - The task ID to retrieve #### Query Parameters - **include** (string) - No - Include related resources in the response ### Response #### Success Response (200) - **operation** (string) - The type of operation performed by the task. - **status** (string) - The current status of the task (e.g., 'waiting', 'processing', 'finished', 'error'). ### Request Example ```json { "example": "// Example usage in Node.js" } ``` ### Response Example ```json { "example": "const task = await cloudConvert.tasks.get('task-abc-123');\nconsole.log(task.operation); // 'convert', 'export/url', etc.\nconsole.log(task.status); // 'waiting', 'processing', 'finished', 'error'" } ``` ``` -------------------------------- ### Advanced Webhook Verification with Multiple Routes Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/WebhooksResource.md Demonstrates a more advanced setup using middleware to verify webhook signatures before routing to specific handlers. This approach centralizes verification logic and attaches parsed webhook data to the request object for easier access in route handlers. It handles different webhook events for jobs and tasks. ```typescript import express from 'express'; import CloudConvert from 'cloudconvert'; const app = express(); const cloudConvert = new CloudConvert('your_api_key'); // Middleware to capture raw body and parse JSON const webhookMiddleware = express.raw({ type: 'application/json' }); const verifyWebhookSignature = (req, res, next) => { const payloadString = req.body.toString('utf-8'); const signature = req.headers['cloudconvert-signature']; if (!signature) { return res.status(400).json({ error: 'Missing CloudConvert-Signature header' }); } const isValid = cloudConvert.webhooks.verify( payloadString, signature, process.env.CLOUDCONVERT_SIGNING_SECRET ); if (!isValid) { console.warn('Invalid webhook signature'); return res.status(401).json({ error: 'Invalid signature' }); } // Parse the JSON and attach to request req.webhookData = JSON.parse(payloadString); next(); }; app.post('/webhooks/jobs', webhookMiddleware, verifyWebhookSignature, (req, res) => { const { event, data } = req.webhookData; if (event === 'job.finished') { console.log('Job completed:', data.job.id); // Process completed job } else if (event === 'job.failed') { console.error('Job failed:', data.job.id); // Handle job failure } res.sendStatus(200); }); app.post('/webhooks/tasks', webhookMiddleware, verifyWebhookSignature, (req, res) => { const { event, data } = req.webhookData; if (event === 'task.finished') { console.log('Task completed:', data.task.id); } res.sendStatus(200); }); app.listen(3000); ``` -------------------------------- ### get() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Retrieves a single job by its ID. Optionally include related resources like tasks in the response. ```APIDOC ## GET /jobs/{id} ### Description Retrieves a single job by ID. Optionally include related resources. ### Method GET ### Endpoint /jobs/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The job ID to retrieve #### Query Parameters - **include** (string) - Optional - Optional query parameters (e.g., `{ include: 'tasks' }`) ### Response #### Success Response (200) - **Job** ([Job](#job-interface)) - The retrieved job object. #### Response Example ```json { "id": "abc-123-def", "status": "processing" } ``` ``` -------------------------------- ### Generate Shareable Conversion Link Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/SignedUrlResource.md Create signed URLs that can be shared with end-users for conversions without exposing your API keys. This example demonstrates generating a link for optimizing a document. ```typescript // Your application generates conversion URLs without exposing API keys const generateShareableLink = (documentUrl: string) => { const url = cloudConvert.signedUrls.sign( process.env.CLOUDCONVERT_SIGNED_URL_BASE, process.env.CLOUDCONVERT_SIGNING_SECRET, { tasks: { 'import': { operation: 'import/url', url: documentUrl }, 'optimize': { operation: 'optimize', input: 'import', profile: 'web' }, 'export': { operation: 'export/url', input: 'optimize', inline: true } } }, null ); // Short URL service optional return url; }; ``` -------------------------------- ### Environment Variable Setup for Webhooks Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/WebhooksResource.md Set environment variables to securely store your CloudConvert signing secret and API key. These are essential for webhook verification and API interactions. ```bash export CLOUDCONVERT_SIGNING_SECRET="your_signing_secret_here" export CLOUDCONVERT_API_KEY="your_api_key_here" ``` -------------------------------- ### Implement Rate Limiting Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Wrap CloudConvert client calls in a rate-limiting mechanism to manage request frequency and avoid hitting API limits. This example enforces 100 requests per minute. ```typescript class RateLimitedCloudConvert { private client: CloudConvert; private requestCount = 0; private resetTime = Date.now() + 60000; constructor(apiKey: string) { this.client = new CloudConvert(apiKey); } async callWithRateLimit( fn: () => Promise ): Promise { const now = Date.now(); if (now > this.resetTime) { this.requestCount = 0; this.resetTime = now + 60000; } if (this.requestCount >= 100) { // Example: 100 requests per minute const delay = this.resetTime - now; await new Promise(resolve => setTimeout(resolve, delay)); this.requestCount = 0; this.resetTime = Date.now() + 60000; } this.requestCount++; return fn(); } async createJob(template: JobTemplate): Promise { return this.callWithRateLimit(() => this.client.jobs.create(template) ); } } ``` -------------------------------- ### Configuration Documentation Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Covers all aspects of SDK configuration, including constructor options, initialization patterns, environment variables, API endpoints, and application patterns. ```APIDOC ## Configuration ### Description Guides users through configuring and initializing the CloudConvert Node.js SDK. ### Constructor Options (Documentation for all constructor options is available.) ### Initialization Patterns (Documentation for all initialization patterns is available.) ### Environment Variables (Documentation for environment variable setup is available.) ### API Endpoints (Documentation for all API endpoints is available.) ### Application Patterns (Documentation for all application patterns is available.) ``` -------------------------------- ### Make Authenticated API Call (GET) Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/CloudConvert.md Use this method for GET requests to the CloudConvert API, including query parameters. It handles authentication automatically. ```typescript const job = await cloudConvert.call('GET', 'jobs/abc-123', { include: 'tasks' }); ``` -------------------------------- ### Basic CloudConvert Node.js SDK Usage Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Demonstrates how to create a file conversion job using the CloudConvert Node.js SDK. This includes importing a file from a URL, converting it to DOCX, and exporting the result to a URL. Ensure you replace 'your_api_key_here' with your actual API key. ```typescript import CloudConvert from 'cloudconvert'; const cloudConvert = new CloudConvert('your_api_key_here'); // Create a job const job = await cloudConvert.jobs.create({ tasks: { 'import-file': { operation: 'import/url', url: 'https://example.com/document.pdf' }, 'convert-file': { operation: 'convert', input: 'import-file', output_format: 'docx' }, 'export-file': { operation: 'export/url', input: 'convert-file' } } }); // Wait for completion const completedJob = await cloudConvert.jobs.wait(job.id); // Get output files const files = cloudConvert.jobs.getExportUrls(completedJob); console.log('Output files:', files); ``` -------------------------------- ### Instantiate CloudConvert Client Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/CloudConvert.md Learn how to create instances of the CloudConvert client for production, sandbox testing, or with a specific region. Ensure you replace 'your_api_key_here' with your actual API key. ```typescript import CloudConvert from 'cloudconvert'; // Production client const cloudConvert = new CloudConvert('your_api_key_here'); // Sandbox client for testing const sandboxClient = new CloudConvert('your_api_key_here', true); // Client with specific region const regionalClient = new CloudConvert('your_api_key_here', false, 'us-east'); ``` -------------------------------- ### Initialize Single CloudConvert Client Instance Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Demonstrates creating a singleton CloudConvert client instance for use throughout an application. Ensure initialization occurs at application startup. ```typescript // Create once at application startup class CloudConvertService { private static client: CloudConvert; static initialize(apiKey: string) { this.client = new CloudConvert(apiKey); } static getClient(): CloudConvert { if (!this.client) { throw new Error('CloudConvert not initialized'); } return this.client; } } // In your app initialization CloudConvertService.initialize(process.env.CLOUDCONVERT_API_KEY); // Use throughout your app const client = CloudConvertService.getClient(); const job = await client.jobs.get('job-id'); ``` -------------------------------- ### delete() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Deletes a job. Can only delete jobs that have not started processing or are in a terminal state. ```APIDOC ## delete() ### Description Deletes a job. Can only delete jobs that have not started processing or are in a terminal state. ### Method `delete(id: string): Promise` ### Parameters #### Path Parameters - **id** (string) - Required - The job ID to delete ### Example ```typescript await cloudConvert.jobs.delete('abc-123-def'); console.log('Job deleted'); ``` ``` -------------------------------- ### Initialize CloudConvert SDK with Sandbox Mode Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Instantiate the CloudConvert client with your API key and enable sandbox mode for testing. Sandbox mode does not consume your API quota. ```typescript // Sandbox mode doesn't consume quota const sandboxClient = new CloudConvert('your_api_key_here', true); // Run tests with sandbox account credentials const testJob = await sandboxClient.jobs.create({ tasks: { 'import': { operation: 'import/url', url: 'https://example.com/file.pdf' } } }); ``` -------------------------------- ### delete() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Deletes a task. This operation can only delete tasks that have not started or are in a terminal state. ```APIDOC ## delete() ### Description Deletes a task. Can only delete tasks that have not started or are in a terminal state. ### Method `async delete(id: string): Promise` ### Parameters #### Path Parameters - **id** (string) - Required - The task ID to delete ### Return Returns a Promise that resolves when deletion is complete. ### Example ```typescript await cloudConvert.tasks.delete('task-abc-123'); console.log('Task deleted'); ``` ``` -------------------------------- ### Initialize CloudConvert SDK Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Instantiate the CloudConvert client with your API key for production use. ```typescript import CloudConvert from 'cloudconvert'; const cloudConvert = new CloudConvert('your_api_key_here'); ``` -------------------------------- ### Access SDK region Property Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Get the configured region for the SDK, or null if the default region is used. ```typescript cloudConvert.region: string | null ``` -------------------------------- ### Enable Sandbox Mode Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Initialize the CloudConvert SDK with sandbox mode enabled for testing without consuming your API quota. Pass `true` as the second argument to the constructor. ```js // Pass `true` to the constructor const cloudConvert = new CloudConvert('api_key', true); ``` -------------------------------- ### Get a Task by ID Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Retrieves a single task using its unique identifier. Optionally include related resources in the response. ```typescript const task = await cloudConvert.tasks.get('task-abc-123'); console.log(task.operation); // 'convert', 'export/url', etc. console.log(task.status); // 'waiting', 'processing', 'finished', 'error' ``` -------------------------------- ### Run Integration Tests Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Execute integration tests against the Sandbox API. Set CLOUDCONVERT_API_KEY environment variable to use your own account. ```bash npm run test-integration ``` -------------------------------- ### create() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Creates a new job with one or more tasks. Define the sequence of operations, input files, output formats, and optional tags or webhooks. ```APIDOC ## POST /jobs ### Description Creates a new job with one or more tasks. ### Method POST ### Endpoint /jobs ### Parameters #### Request Body - **data** (JobTemplate) - Optional - Job definition including tasks, optional tag and webhook_url ### Request Example ```json { "tasks": { "import-my-file": { "operation": "import/url", "url": "https://example.com/document.pdf" }, "convert-my-file": { "operation": "convert", "input": "import-my-file", "output_format": "docx" }, "export-my-file": { "operation": "export/url", "input": "convert-my-file" } }, "tag": "my-conversion", "webhook_url": "https://example.com/webhook" } ``` ### Response #### Success Response (200) - **Job** ([Job](#job-interface)) - The newly created job object with an assigned ID. #### Response Example ```json { "id": "new-job-id", "status": "waiting" } ``` ``` -------------------------------- ### Delete a Task by ID Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Deletes a task using its ID. This operation is only permitted for tasks that have not yet started or are in a terminal state. ```typescript async delete(id: string): Promise ``` ```typescript await cloudConvert.tasks.delete('task-abc-123'); console.log('Task deleted'); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Execute the unit tests for the library using Mocha. ```bash npm run test ``` -------------------------------- ### Get a Job by ID Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Retrieves a specific job using its unique identifier. Optionally include related task details in the response. ```typescript async get(id: string, query?: object): Promise ``` ```typescript const job = await cloudConvert.jobs.get('abc-123-def'); console.log(job.status); // 'processing', 'finished', or 'error' // Fetch with included task details const jobWithTasks = await cloudConvert.jobs.get('abc-123-def', { include: 'tasks' }); ``` -------------------------------- ### CloudConvert Class Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Documentation for the main client class, including its constructor, properties, and core methods for interacting with the CloudConvert API. ```APIDOC ## CloudConvert Class ### Description Documentation for the main client class, including its constructor, properties, and core methods for interacting with the CloudConvert API. This class serves as the entry point for most SDK operations. ### Methods - **constructor(options)**: Initializes the CloudConvert client with provided options. - **call(path, options)**: Makes a generic API call to a specified path. - **callWithBase(path, options)**: Makes an API call using a base path. - **subscribe(path, callback)**: Subscribes to real-time events from a specified path. - **closeSocket()**: Closes the real-time event socket. ### Properties - **apiKey** (string): Your CloudConvert API key. - **useSandbox** (boolean): Whether to use the sandbox environment. - **region** (string): The API region to use. - **resources** (object): Access to various resource managers (e.g., Jobs, Tasks). ``` -------------------------------- ### Get Current User Account Info Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/UsersResource.md Retrieves the authenticated user's account details. Ensure you have authenticated the CloudConvert client before calling this method. ```typescript const user = await cloudConvert.users.me(); console.log(`Logged in as: ${user.username}`); console.log(`Email: ${user.email}`); console.log(`Credits: ${user.credits}`); console.log(`Account created: ${user.created_at}`); ``` -------------------------------- ### Initialize CloudConvert SDK with Environment Variables Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Configure the CloudConvert client using environment variables for API key, sandbox mode (based on NODE_ENV), and region. The region defaults to null if CLOUDCONVERT_REGION is not set. ```typescript const cloudConvert = new CloudConvert( process.env.CLOUDCONVERT_API_KEY, process.env.NODE_ENV === 'test', process.env.CLOUDCONVERT_REGION || null ); ``` -------------------------------- ### CloudConvert Constructor Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Initializes a new CloudConvert SDK client. You can specify your API key, enable sandbox mode for testing, and select a specific region for lower latency. ```APIDOC ## CloudConvert Constructor ### Description Initializes a new CloudConvert SDK client. You can specify your API key, enable sandbox mode for testing, and select a specific region for lower latency. ### Signature ```typescript constructor(apiKey: string, useSandbox?: boolean, region?: string | null) ``` ### Parameters #### Path Parameters * **apiKey** (string) - Required - CloudConvert API key for authentication. Get from https://cloudconvert.com/dashboard/api/v2 * **useSandbox** (boolean) - Optional - Enable sandbox mode for testing without consuming quota * **region** (string | null) - Optional - Specific region: 'us-east', 'us-west', 'eu-west', etc. Null uses account's default region ### Return CloudConvert instance with access to all resource endpoints. ### Initialization Examples #### Basic Production Client ```typescript import CloudConvert from 'cloudconvert'; const cloudConvert = new CloudConvert('your_api_key_here'); ``` #### Sandbox Client for Testing ```typescript // Sandbox mode doesn't consume quota const sandboxClient = new CloudConvert('your_api_key_here', true); // Run tests with sandbox account credentials const testJob = await sandboxClient.jobs.create({ tasks: { 'import': { operation: 'import/url', url: 'https://example.com/file.pdf' } } }); ``` #### Regional Client ```typescript // Specify a region for lower latency const usEastClient = new CloudConvert('your_api_key_here', false, 'us-east'); const euWestClient = new CloudConvert('your_api_key_here', false, 'eu-west'); ``` #### Environment-Based Configuration ```typescript const cloudConvert = new CloudConvert( process.env.CLOUDCONVERT_API_KEY, process.env.NODE_ENV === 'test', process.env.CLOUDCONVERT_REGION || null ); ``` ``` -------------------------------- ### CloudConvert Webhook Payload Structure Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/WebhooksResource.md Example of a webhook payload received when a job is finished. This JSON structure contains event details and associated job data. ```json { "event": "job.finished", "created_at": "2024-01-15T10:30:45Z", "data": { "job": { "id": "abc-123-def", "status": "finished", "created_at": "2024-01-15T10:15:00Z", "started_at": "2024-01-15T10:15:15Z", "ended_at": "2024-01-15T10:30:45Z", "tag": "batch-1", "tasks": [ { "id": "task-1", "name": "import", "operation": "import/url", "status": "finished" }, { "id": "task-2", "name": "convert", "operation": "convert", "status": "finished" } ] } } } ``` -------------------------------- ### CloudConvert Error Handling Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/CloudConvert.md The CloudConvert client throws errors when HTTP responses are not successful. This example demonstrates how to catch and log error messages and the underlying response object. ```APIDOC ## Error Handling The CloudConvert client throws errors when HTTP responses are not successful: ```typescript try { const job = await cloudConvert.jobs.get('invalid-id'); } catch (error) { console.error(error.message); console.error(error.cause); } ``` ``` -------------------------------- ### Create Various Task Types Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Demonstrates creating different types of tasks: import, convert, export, and thumbnail. Ensure the correct operation type and data parameters are provided for each. ```typescript async create( operation: O, data?: Extract['data'] ): Promise ``` ```typescript // Create an import task const importTask = await cloudConvert.tasks.create('import/url', { url: 'https://example.com/document.pdf', filename: 'document.pdf' }); // Create a convert task const convertTask = await cloudConvert.tasks.create('convert', { input: importTask.id, output_format: 'docx', engine: 'libreoffice' }); // Create an export task const exportTask = await cloudConvert.tasks.create('export/url', { input: convertTask.id }); // Create a thumbnail task with multiple inputs const thumbTask = await cloudConvert.tasks.create('thumbnail', { input: [importTask.id], output_format: 'png', width: 300, height: 300 }); ``` -------------------------------- ### Delete a Job Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Deletes a job using its ID. This is only possible for jobs that have not started processing or are in a terminal state. Ensure the job ID is valid and the job is in a deletable state. ```typescript await cloudConvert.jobs.delete('abc-123-def'); console.log('Job deleted'); ``` -------------------------------- ### SignedUrlResource Methods Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/DOCUMENTATION-SUMMARY.txt Documentation for the SignedUrlResource includes the sign() method and guidance on signed URL patterns. ```APIDOC ## SignedUrlResource ### Description Provides methods for generating and managing signed URLs. ### Methods #### sign() ##### Description Generates a signed URL. ##### Method (Not specified, likely a SDK method call) ##### Parameters (Not specified) ##### Return Type (Not specified) ### Complete signed URL patterns (Documentation for various signed URL patterns is available.) ``` -------------------------------- ### Build Project Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Compile the TypeScript code into JavaScript and generate type declarations in the 'built' directory. ```bash npm run build ``` -------------------------------- ### Create a CloudConvert Job Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Instantiate the CloudConvert client with your API key and create a job with import, convert, and export tasks. Ensure you have the necessary API key and understand the available task operations. ```javascript import CloudConvert from 'cloudconvert'; const cloudConvert = new CloudConvert('api_key'); let job = await cloudConvert.jobs.create({ tasks: { 'import-my-file': { operation: 'import/url', url: 'https://my-url' }, 'convert-my-file': { operation: 'convert', input: 'import-my-file', output_format: 'pdf', some_other_option': 'value' }, 'export-my-file': { operation: 'export/url', input: 'convert-my-file' } } }); ``` -------------------------------- ### call() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/CloudConvert.md Makes an authenticated API call to the CloudConvert API. This method supports GET, POST, and DELETE requests and can handle various parameter types for query strings or request bodies. ```APIDOC ## call() ### Description Makes an authenticated API call to the CloudConvert API. ### Method 'GET' | 'POST' | 'DELETE' ### Endpoint string (API endpoint path, e.g., 'jobs', 'tasks/123') ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **parameters** (UploadFile or object) - Optional - Request parameters. For GET, converted to query string. For POST, sent as JSON or multipart form data. - **options.presigned** (boolean) - Optional - If true, skips Bearer token authorization (for presigned URLs) - **options.flat** (boolean) - Optional - If true, returns the full response object instead of just the data property ### Request Example ```json // GET request with query parameters const job = await cloudConvert.call('GET', 'jobs/abc-123', { include: 'tasks' }); // POST request with JSON body const newJob = await cloudConvert.call('POST', 'jobs', { tasks: { 'import': { operation: 'import/url', url: 'https://example.com/file.pdf' } } }); ``` ### Response #### Success Response (200) - **any** - Resolves to the response data. #### Response Example ```json // Example response structure depends on the API call ``` ``` -------------------------------- ### CloudConvert Class Initialization Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Initialize the CloudConvert client with your API key to access various resources like jobs, tasks, users, webhooks, and signed URLs. ```APIDOC ## CloudConvert Class Initialization ### Description Initialize the CloudConvert client with your API key to access various resources like jobs, tasks, users, webhooks, and signed URLs. All resource methods are asynchronous and return Promises. ### Method ```typescript new CloudConvert(apiKey: string) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import CloudConvert from 'cloudconvert'; const apiKey = process.env.CLOUDCONVERT_API_KEY; const client = new CloudConvert(apiKey); // Access resources client.jobs client.tasks client.users client.webhooks client.signedUrls ``` ### Response #### Success Response An instance of the `CloudConvert` client. #### Response Example ```typescript // No direct response example for initialization, but the client object is returned. ``` ``` -------------------------------- ### Initialize CloudConvert Client Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Instantiate the CloudConvert client with your API key. Access various resources like jobs, tasks, and users through the client object. All resource methods are asynchronous and return Promises. ```typescript import CloudConvert from 'cloudconvert'; const client = new CloudConvert(apiKey); // Access resources client.jobs // JobsResource client.tasks // TasksResource client.users // UsersResource client.webhooks // WebhooksResource client.signedUrls // SignedUrlResource ``` -------------------------------- ### Get Export URLs from a Completed Job Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Retrieves all successful export URLs from a completed job. This method filters for tasks with operation 'export/url' and status 'finished'. It returns an empty array if no such tasks are found. URLs are publicly accessible. ```typescript const completedJob = await cloudConvert.jobs.wait(job.id); const files = cloudConvert.jobs.getExportUrls(completedJob); for (const file of files) { console.log(`Downloaded from: ${file.url}`); console.log(`Filename: ${file.filename}`); console.log(`Size: ${file.size} bytes`); } ``` -------------------------------- ### Lint Project Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Check the project for code style issues using ESLint and Prettier. ```bash npm run lint ``` -------------------------------- ### Verify Webhook Signature in Express.js Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/WebhooksResource.md Verifies the HMAC signature of an incoming webhook request. Ensure your Express app is configured to capture the raw request body as a string. The signing secret should be stored securely, for example, in environment variables. ```typescript import express from 'express'; import CloudConvert from 'cloudconvert'; const app = express(); const cloudConvert = new CloudConvert('your_api_key'); // Configure Express to store raw request body as string app.use(express.raw({ type: 'application/json' })); app.post('/webhook', (req, res) => { const payloadString = req.body.toString('utf-8'); const signature = req.headers['cloudconvert-signature']; const signingSecret = process.env.CLOUDCONVERT_SIGNING_SECRET; // Verify the webhook signature const isValid = cloudConvert.webhooks.verify( payloadString, signature, signingSecret ); if (!isValid) { console.warn('Webhook signature verification failed'); return res.status(401).send('Unauthorized'); } // Parse and process the webhook const webhookData = JSON.parse(payloadString); console.log('Webhook verified and processed:', webhookData); res.sendStatus(200); }); app.listen(3000); ``` -------------------------------- ### Set Signed URL Credentials Environment Variables Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Set CLOUDCONVERT_SIGNED_URL_BASE and CLOUDCONVERT_SIGNING_SECRET for generating signed URLs. ```bash # Required for signed URL generation export CLOUDCONVERT_SIGNED_URL_BASE="https://s.cloudconvert.com/..." export CLOUDCONVERT_SIGNING_SECRET="..." ``` -------------------------------- ### Triggering Invalid Parameter Values Errors Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/errors.md These examples show how to trigger 'Invalid Parameter Values' errors. The first triggers an error due to an invalid 'profile' value in an optimize task, and the second triggers an error with an out-of-range 'quality' value. ```typescript // Invalid profile value const task = await cloudConvert.tasks.create('optimize', { input: 'import-id', profile: 'invalid-profile' // Valid: 'web', 'print', 'archive', etc. }); // Invalid quality value const task = await cloudConvert.tasks.create('optimize', { input: 'import-id', quality: 150 // Valid: 0-100 }); ``` -------------------------------- ### Run Integration Tests (Custom Account) Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Configures and runs integration tests against your own CloudConvert account by setting the CLOUDCONVERT_API_KEY environment variable. ```bash export CLOUDCONVERT_API_KEY="your_key" npm run test-integration ``` -------------------------------- ### Upload Local File With Detected Size Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/errors.md This function shows how to upload a local file by first detecting its size using `fs/promises.stat` and then creating a readable stream. ```typescript import { stat } from 'fs/promises'; import { createReadStream } from 'fs'; const uploadLocalFile = async ( task: Task | JobTask, filePath: string ) => { const { size } = await stat(filePath); const stream = createReadStream(filePath); return cloudConvert.tasks.upload(task, stream, undefined, size); }; ``` -------------------------------- ### Check CloudConvert Configuration Details Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Log the current API key (truncated), sandbox status, and region settings of the CloudConvert client. ```typescript // Check current configuration console.log({ apiKey: cloudConvert.apiKey.slice(0, 10) + '...', sandbox: cloudConvert.useSandbox, region: cloudConvert.region }); ``` -------------------------------- ### CloudConvert Constructor Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/CloudConvert.md Initializes a new CloudConvert client instance. This client is used to interact with the CloudConvert API v2, manage tasks, jobs, and other resources. ```APIDOC ## CloudConvert Constructor ### Description Initializes a new CloudConvert client instance. This client is used to interact with the CloudConvert API v2, manage tasks, jobs, and other resources. ### Parameters #### Path Parameters - **apiKey** (string) - Required - Your CloudConvert API key for authentication. Obtain from https://cloudconvert.com/dashboard/api/v2 - **useSandbox** (boolean) - Optional - Enable sandbox mode to avoid consuming quota during testing. Requires MD5 hashes of test files. Defaults to false. - **region** (string or null) - Optional - Specific region to use (e.g., 'us-east'). If null, uses the region from your account settings. Defaults to null. ### Example ```typescript import CloudConvert from 'cloudconvert'; // Production client const cloudConvert = new CloudConvert('your_api_key_here'); // Sandbox client for testing const sandboxClient = new CloudConvert('your_api_key_here', true); // Client with specific region const regionalClient = new CloudConvert('your_api_key_here', false, 'us-east'); ``` ``` -------------------------------- ### ImportOpenStackData Interface for OpenStack Imports Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/types.md Configuration for importing files from OpenStack Object Storage. Includes authentication details, region, container name, and options for specific files or prefixes, plus an output filename. ```typescript interface ImportOpenStackData { auth_url: string; // OpenStack authentication URL username: string; // OpenStack username password: string; // OpenStack password region: string; // OpenStack region container: string; // Container name file?: string; // Specific file to import file_prefix?: string; // Prefix to import multiple files filename?: string; // Output filename } ``` -------------------------------- ### Configure CloudConvert Environment Variables Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Set environment variables to configure the CloudConvert SDK. This includes setting the API key, region, sandbox mode, signing secret, and signed URL base. ```bash # Required export CLOUDCONVERT_API_KEY="sk_live..." # Optional export CLOUDCONVERT_REGION="eu-west" export CLOUDCONVERT_SANDBOX="false" export CLOUDCONVERT_SIGNING_SECRET="..." export CLOUDCONVERT_SIGNED_URL_BASE="https://s.cloudconvert.com/..." ``` -------------------------------- ### Test CloudConvert Integration with Sandbox Mode Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/configuration.md Illustrates how to set up a test client that always uses sandbox mode. This is crucial for integration testing without affecting live data. ```typescript // test.ts const createTestClient = (): CloudConvert => { return new CloudConvert( process.env.CLOUDCONVERT_TEST_API_KEY || 'test-key', true // Always use sandbox for tests ); }; describe('CloudConvert Integration', () => { let client: CloudConvert; before(() => { client = createTestClient(); }); it('should create a job', async () => { const job = await client.jobs.create({ tasks: { 'import': { operation: 'import/url', url: 'https://example.com/file.pdf' } } }); expect(job.id).to.exist; expect(job.status).to.equal('processing'); }); }); ``` -------------------------------- ### Generate Signed URL for Simple Conversion Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/SignedUrlResource.md Use this snippet to create a signed URL for a basic file conversion. It requires the signed URL base, your signing secret, and a job definition. Caching is disabled by passing `null`. ```typescript import CloudConvert from 'cloudconvert'; const cloudConvert = new CloudConvert('your_api_key'); // Obtain these from your CloudConvert dashboard const signedUrlBase = 'https://s.cloudconvert.com/abc-123-def-456'; const signingSecret = 'your_signing_secret_here'; // Simple conversion URL const url = cloudConvert.signedUrls.sign( signedUrlBase, signingSecret, { tasks: { 'import-it': { operation: 'import/url', url: 'https://example.com/document.pdf', filename: 'document.pdf' }, 'convert-it': { operation: 'convert', input: 'import-it', output_format: 'docx' }, 'export-it': { operation: 'export/url', input: 'convert-it', inline: true } } }, null // No caching ); console.log('Conversion URL:', url); // Output: https://s.cloudconvert.com/abc-123-def-456?job=&s= ``` -------------------------------- ### ImportSFTPData Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/types.md Parameters for the `import/sftp` operation. Includes SFTP server connection details, credentials, and optional parameters for specifying files and the output filename. ```APIDOC ## ImportSFTPData ### Description Parameters for `import/sftp` operation. ### Parameters #### Request Body - **host** (string) - Required - SFTP server hostname - **port** (number) - Optional - SFTP port (default 22) - **username** (string) - Required - SFTP username - **password** (string) - Optional - SFTP password (use private_key alternatively) - **private_key** (string) - Optional - SSH private key for authentication - **file** (string) - Optional - Specific file to import - **path** (string) - Optional - Directory path on SFTP server - **filename** (string) - Optional - Output filename ``` -------------------------------- ### JobTemplate Interface Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/types.md Defines the structure for creating a new job, including a dictionary of named tasks, an optional tag, and an optional webhook URL for notifications. ```APIDOC ## JobTemplate Interface ### Description Definition for creating a new job with tasks. ### Interface Definition ```typescript interface JobTemplate { tasks: TaskContainer; // Dictionary of named tasks tag?: string; // Optional user-defined tag webhook_url?: string; // Optional webhook URL for completion notification } ``` ### Used By - `jobs.create()` parameter - `signedUrls.sign()` parameter ``` -------------------------------- ### JobTemplate Interface Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Defines the structure required for creating a new job, including tasks, an optional tag, and a webhook URL. ```APIDOC ## JobTemplate Interface ### Description Definition for creating a new job. ### Interface ```typescript interface JobTemplate { tasks: TaskContainer; // Required: dictionary of task definitions tag?: string; // Optional: user-defined tag for filtering webhook_url?: string; // Optional: URL to POST when job completes } ``` ``` -------------------------------- ### Create and Wait for a Job Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/README.md Create a new job with a series of tasks and wait for its completion. This is a fundamental pattern for processing files. ```typescript const job = await cloudConvert.jobs.create({ tasks: { 'step1': { operation: 'import/url', url: 'https://...' }, 'step2': { operation: 'convert', input: 'step1', output_format: 'pdf' }, 'step3': { operation: 'export/url', input: 'step2' } } }); const completed = await cloudConvert.jobs.wait(job.id); ``` -------------------------------- ### Load CloudConvert SDK via Require Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/README.md Import the CloudConvert SDK when using CommonJS modules. ```javascript const CloudConvert = require('cloudconvert'); ``` -------------------------------- ### all() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/JobsResource.md Lists jobs with optional filtering and pagination. Filter by status or tag, and control the number of results per page. ```APIDOC ## GET /jobs ### Description Lists jobs with optional filtering and pagination. ### Method GET ### Endpoint /jobs ### Parameters #### Query Parameters - **filter[status]** (JobStatus) - Optional - Filter by job status: 'processing', 'finished', or 'error' - **filter[tag]** (string) - Optional - Filter by tag (must match exactly) - **include** (string) - Optional - Include related resources (e.g., 'tasks') - **per_page** (number) - Optional - Results per page (default determined by API) - **page** (number) - Optional - Page number for pagination (1-indexed) ### Response #### Success Response (200) - **Job[]** ([Job](#job-interface)[]) - An array of job objects. #### Response Example ```json [ { "id": "abc-123-def", "status": "finished" } ] ``` ``` -------------------------------- ### ImportSFTPData Interface for SFTP Imports Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/types.md Parameters for importing files via SFTP. Requires host and username, with options for port, password or private key authentication, specific file paths, and an output filename. ```typescript interface ImportSFTPData { host: string; // SFTP server hostname port?: number; // SFTP port (default 22) username: string; // SFTP username password?: string; // SFTP password (use private_key alternatively) private_key?: string; // SSH private key for authentication file?: string; // Specific file to import path?: string; // Directory path on SFTP server filename?: string; // Output filename } ``` -------------------------------- ### Monitor All User Activity with Multiple Subscriptions Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/UsersResource.md Combines user-level subscriptions to monitor various job and task event types comprehensively. Ensure you have fetched the user ID first. ```typescript const user = await cloudConvert.users.me(); // Monitor all user activity cloudConvert.users.subscribeJobEvent(user.id, 'created', (event) => { console.log(`[Job] New job created: ${event.job.id}`); }); cloudConvert.users.subscribeTaskEvent(user.id, 'finished', (event) => { console.log(`[Task] Task completed: ${event.task.operation}`); }); cloudConvert.users.subscribeJobEvent(user.id, 'finished', (event) => { console.log(`[Job] Job completed: ${event.job.status}`); }); cloudConvert.users.subscribeTaskEvent(user.id, 'failed', (event) => { console.error(`[Task] Task failed: ${event.task.message}`); }); ``` -------------------------------- ### all() Source: https://github.com/cloudconvert/cloudconvert-node/blob/master/_autodocs/api-reference/TasksResource.md Lists all tasks with optional filtering and pagination. You can filter by job ID, status, operation type, and control the number of results per page and the page number. ```APIDOC ## GET /tasks ### Description Lists tasks with optional filtering and pagination. ### Method GET ### Endpoint /tasks ### Parameters #### Query Parameters - **filter[job_id]** (string) - No - Filter tasks by job ID - **filter[status]** (TaskStatus) - No - Filter by status: 'waiting', 'processing', 'finished', or 'error' - **filter[operation]** (Operation) - No - Filter by operation type (e.g., 'convert', 'export/url') - **per_page** (number) - No - Results per page - **page** (number) - No - Page number for pagination ### Response #### Success Response (200) - An array of [Task](#task-interface) objects. ### Request Example ```json { "example": "// Get all failed tasks\nconst failedTasks = await cloudConvert.tasks.all({\n 'filter[status]': 'error'\n});\n\n// Get finished convert tasks\nconst completedConversions = await cloudConvert.tasks.all({\n 'filter[status]': 'finished',\n 'filter[operation]': 'convert'\n});\n\n// Get tasks from a specific job\nconst jobTasks = await cloudConvert.tasks.all({\n 'filter[job_id]': 'job-abc-123'\n});" } ``` ### Response Example ```json { "example": "// Example response structure (array of Task objects)" } ``` ```