# @binect/js Library Improvement Requirements

**Version:** 1.1
**Date:** 2026-01-16
**Author:** BinectChrome Development Team
**Status:** Updated after v0.1.0 review

---

## Executive Summary

This document outlines suggested improvements to the `@binect/js` library based on real-world integration experience building the BinectChrome browser extension.

**Update (v1.1):** After reviewing `@binect/js` v0.1.0, most requirements have been addressed. This document now reflects the current status and remaining gaps.

---

## Requirements Status Summary

| Requirement | Status | Notes |
|-------------|--------|-------|
| REQ-1: Status Constants | ✅ **ADDRESSED** | `DocumentStatus` enum exported |
| REQ-2: listAll() Method | ❌ **OPEN** | Still requires 2 API calls |
| REQ-3: Error Accessibility | ✅ **ADDRESSED** | Helper functions added |
| REQ-4: Document ListResponse | ✅ **ADDRESSED** | JSDoc comments improved |
| REQ-5: Pagination Docs | ⚠️ **PARTIAL** | Interface exists, no fetchAll helper |
| REQ-6: Error Type Definitions | ✅ **ADDRESSED** | `ValidationMessage` interface |

---

## Addressed Requirements

### REQ-1: Export Document Status Constants ✅

**Status:** Fully addressed in v0.1.0

The library now exports a `DocumentStatus` enum:

```typescript
export enum DocumentStatus {
  IN_PREPARATION = 1,
  SHIPPABLE = 2,
  PRODUCTION_QUEUE = 3,
  PRINTING = 4,
  SENT = 5,
  CANCELED = 6,
  ERRONEOUS = 7
}
```

**Usage:**
```typescript
import { DocumentStatus } from '@binect/js';

if (doc.status.code === DocumentStatus.ERRONEOUS) {
  // Handle erroneous document
}
```

---

### REQ-3: Improve Error Information Accessibility ✅

**Status:** Fully addressed in v0.1.0

The library now exports comprehensive helper functions:

```typescript
// Status predicates
isShippable(doc)        // status === 2
isErroneous(doc)        // status === 7
isInPreparation(doc)    // status === 1
isInProductionQueue(doc) // status === 3
isPrinting(doc)         // status === 4
isSent(doc)             // status === 5
isCanceled(doc)         // status === 6
isTerminal(doc)         // status in [5, 6, 7]
isCancelable(doc)       // status in [3, 4]

// Error extraction
getErrors(doc)          // ValidationMessage[] of type 'ERROR'
getWarnings(doc)        // ValidationMessage[] of type 'WARNING'
getInfoMessages(doc)    // ValidationMessage[] of type 'INFO'
hasErrors(doc)          // boolean
hasWarnings(doc)        // boolean

// Status description
getStatusDescription(status) // Human-readable string
```

**Usage:**
```typescript
import { isErroneous, getErrors } from '@binect/js';

if (isErroneous(doc)) {
  const errors = getErrors(doc);
  console.error('Errors:', errors.map(e => e.message).join('; '));
}
```

---

### REQ-4: Document ListResponse Structure ✅

**Status:** Addressed in v0.1.0

The `ListResponse<T>` interface now has clear JSDoc documentation:

```typescript
/**
 * List response wrapper
 */
export interface ListResponse<T> {
  items: T[];
  total: number;
  limit: number;
  offset: number;
}
```

---

### REQ-6: Improve Type Definitions for Error Objects ✅

**Status:** Addressed in v0.1.0

The `ValidationMessage` interface is now properly typed:

```typescript
export interface ValidationMessage {
  type: 'INFO' | 'WARNING' | 'ERROR';
  code: string;
  message: string;
  page?: number;
}
```

---

## Open Requirements

### REQ-2: Add Method to List All Documents ❌

**Status:** NOT ADDRESSED
**Priority:** Medium

#### Problem Statement

There is still no single method to retrieve all documents regardless of status:

```typescript
// Current: Multiple calls still required
const shippable = await client.documents.list();       // Only status 2
const erroneous = await client.documents.listErrors(); // Only status 7
// Still missing: status 1, 3, 4, 5, 6
```

#### API Limitation

This may be a limitation of the Binect REST API itself, not the JS library. The API only provides:
- `GET /documents` - Returns shippable documents (status 2)
- `GET /documents/errors` - Returns erroneous documents (status 7)

There is no endpoint to list documents in other states (in_preparation, in_production, sent, canceled).

#### Proposed Solutions

**Option A: Library-level aggregation** (if API supports individual document lookup)
```typescript
// Library could provide a helper that fetches known IDs
async listByIds(documentIds: string[]): Promise<Document[]>;
```

**Option B: Document the limitation**
- Clearly document which documents each endpoint returns
- Explain that documents in production (3, 4) cannot be listed, only queried by ID
- Provide example of tracking document IDs locally

**Option C: API Enhancement Request**
- Request Binect API team to add `GET /documents/all` or status filter parameter:
  ```
  GET /documents?status=1,2,3,4,5,6,7
  ```

#### Impact on BinectChrome

Currently, BinectChrome can only discover:
- Documents ready to ship (status 2)
- Documents with errors (status 7)

Documents in production (3, 4), sent (5), or canceled (6) can only be tracked if we uploaded them and stored their IDs locally.

---

### REQ-5: Document and Improve Pagination ⚠️

**Status:** PARTIALLY ADDRESSED
**Priority:** Low

#### What's Addressed

- `PaginationOptions` interface is exported
- Methods accept pagination parameters

```typescript
export interface PaginationOptions {
  limit?: number;
  offset?: number;
}
```

#### What's Missing

1. **Documentation of default values** - What is the default limit?
2. **fetchAll helper** - No built-in way to fetch all pages automatically

#### Proposed Addition

```typescript
// Optional helper for fetching all pages
async function fetchAllDocuments(client: BinectClient): Promise<Document[]> {
  const allDocs: Document[] = [];
  let offset = 0;
  const limit = 100;

  while (true) {
    const response = await client.documents.list({ limit, offset });
    allDocs.push(...response.items);
    if (response.items.length < limit) break;
    offset += limit;
  }

  return allDocs;
}
```

This could be added to the helpers module as `fetchAll()` or similar.

---

## New Features in v0.1.0

The following features were added that weren't in our original requirements:

### Polling Utilities

```typescript
import { pollUntil, waitForShippable } from '@binect/js';

// Wait for document to become shippable or erroneous
const doc = await waitForShippable(
  () => client.documents.get(docId),
  { intervalMs: 2000, maxAttempts: 30 }
);

// Generic polling
const result = await pollUntil(
  () => fetchSomething(),
  (result) => result.status === 'complete',
  { intervalMs: 1000 }
);
```

### Encoding Helpers

```typescript
import { fileToBase64, bufferToBase64 } from '@binect/js';

// Browser: File/Blob to base64
const base64 = await fileToBase64(file);

// Node.js: Buffer to base64
const base64 = bufferToBase64(buffer);
```

---

## Recommendations for BinectChrome

Based on the updated library, we should:

1. **Refactor to use `DocumentStatus` enum** instead of magic numbers
2. **Use helper functions** like `isErroneous()`, `getErrors()` instead of manual checks
3. **Use `getStatusDescription()`** for human-readable status text
4. **Consider using `waitForShippable()`** for upload flow instead of manual polling

---

## Revision History

| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2026-01-16 | BinectChrome Team | Initial draft |
| 1.1 | 2026-01-16 | BinectChrome Team | Updated after v0.1.0 review - marked addressed requirements |
