npm package: @nuclicore/documents
Description: Nuclicore Documents SDK - PDF generation from DOCX templates and document merging
Latest version: 1.0.0

# @nuclicore/documents

JavaScript SDK for Nuclicore's document API — generate PDFs from templates and merge files into a single PDF.

## Installation

```bash
npm install @nuclicore/documents
```

## Configuration

### Option 1: Environment variables

```bash
NUCLICORE_APP_ID=your-app-id
NUCLICORE_INTEGRATION_KEY=your-api-key
# Optional — defaults to https://integrations.build.nuclicore.com
NUCLICORE_GATEWAY_URL=https://integrations.build.nuclicore.com
```

```ts
import { NuclicoreDocuments } from '@nuclicore/documents';

const docs = new NuclicoreDocuments();
```

### Option 2: Constructor config

```ts
import { NuclicoreDocuments } from '@nuclicore/documents';

const docs = new NuclicoreDocuments({
  appId: 'your-app-id',
  apiKey: 'your-api-key',
  gatewayUrl: 'https://integrations.build.nuclicore.com', // optional
  environment: 'production', // 'preview' | 'production' — defaults based on NODE_ENV
});
```

Constructor values take precedence over environment variables.

## Usage

### Generate PDF from a DOCX template

Create a PDF by rendering variables into a DOCX template. The template uses single-brace expressions (e.g., `{firstName}`).

```ts
import { readFileSync, writeFileSync } from 'fs';
import { NuclicoreDocuments } from '@nuclicore/documents';

const docs = new NuclicoreDocuments();

const template = readFileSync('./invoice-template.docx');

const pdf = await docs.generatePdf({
  template,
  templateFilename: 'invoice-template.docx', // optional
  variables: {
    firstName: 'John',
    lastName: 'Doe',
    invoiceNumber: 'INV-2024-001',
    amount: '$1,250.00',
  },
});

writeFileSync('./invoice.pdf', pdf);
```

#### Template syntax

Templates use single-brace Angular-style expressions with optional filters:

- `{firstName}` — simple variable
- `{name | upper}` — uppercase filter
- `{name | lower}` — lowercase filter

### Merge files into a single PDF

Combine multiple PDFs, images, and documents into one PDF. Files are converted automatically — images are fitted to A4 pages, and Word documents are converted via LibreOffice.

```ts
import { readFileSync, writeFileSync } from 'fs';
import { NuclicoreDocuments } from '@nuclicore/documents';

const docs = new NuclicoreDocuments();

const pdf = await docs.mergeDocuments({
  files: [
    {
      content: readFileSync('./cover.pdf'),
      filename: 'cover.pdf',
      contentType: 'application/pdf',
    },
    {
      content: readFileSync('./photo.png'),
      filename: 'photo.png',
      contentType: 'image/png',
    },
    {
      content: readFileSync('./scan.heic'),
      filename: 'scan.heic',
      contentType: 'image/heic',
    },
    {
      content: readFileSync('./appendix.docx'),
      filename: 'appendix.docx',
      contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    },
  ],
});

writeFileSync('./merged.pdf', pdf);
```

#### Supported file types

| Category  | Types                                              |
| --------- | -------------------------------------------------- |
| PDF       | `.pdf`                                             |
| Images    | `.jpg`, `.png`, `.heic`, `.heif`, `.tiff`, `.bmp`  |
| Documents | `.docx`, `.doc`, `.txt`, `.rtf`                    |

#### Limits

- Max **50 files** per merge request
- Max **80 MB** per file

## Switching environments

The SDK defaults to `preview` in development and `production` when `NODE_ENV=production`. You can switch at runtime:

```ts
docs.setEnvironment('production');
console.log(docs.getEnvironment()); // 'production'
```

## Error handling

The SDK throws standard `Error` instances with messages from the API:

```ts
try {
  const pdf = await docs.generatePdf({ template });
} catch (err) {
  console.error(err.message); // e.g., 'PDF conversion failed: ...'
}
```

Common errors:

| Error | Cause |
| ----- | ----- |
| `appId is required` | Missing `NUCLICORE_APP_ID` env var or `appId` config |
| `template is required` | No template buffer provided |
| `template must be a Buffer` | Template is not a Node.js Buffer |
| `At least one file is required` | Empty files array in merge |
| `Cannot merge more than 50 files at once` | Too many files |
| `Insufficient credits` | Account needs more credits |

## API reference

### `new NuclicoreDocuments(config?)`

| Parameter | Type | Default | Description |
| --------- | ---- | ------- | ----------- |
| `config.appId` | `string` | `NUCLICORE_APP_ID` env | Application ID |
| `config.apiKey` | `string` | `NUCLICORE_INTEGRATION_KEY` env | API key |
| `config.gatewayUrl` | `string` | `NUCLICORE_GATEWAY_URL` env or `https://integrations.build.nuclicore.com` | Gateway URL |
| `config.environment` | `'preview' \| 'production'` | Based on `NODE_ENV` | Target environment |

### `docs.generatePdf(params): Promise<Buffer>`

| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `params.template` | `Buffer` | Yes | DOCX template file |
| `params.templateFilename` | `string` | No | Filename (default: `template.docx`) |
| `params.variables` | `Record<string, unknown>` | No | Template variables |

Returns the generated PDF as a `Buffer`.

### `docs.mergeDocuments(params): Promise<Buffer>`

| Parameter | Type | Required | Description |
| --------- | ---- | -------- | ----------- |
| `params.files` | `Array<{ content, filename, contentType? }>` | Yes | Files to merge (1–50) |
| `params.files[].content` | `Buffer` | Yes | File content |
| `params.files[].filename` | `string` | Yes | Filename with extension |
| `params.files[].contentType` | `string` | No | MIME type (auto-detected if omitted) |

Returns the merged PDF as a `Buffer`.

### `docs.getAppId(): string`

Returns the configured application ID.

### `docs.getEnvironment(): string`

Returns the current environment (`'preview'` or `'production'`).

### `docs.setEnvironment(env: 'preview' | 'production'): void`

Switches the target environment at runtime.

## License

MIT