npm package: @naman22khater/data-converter
Description: A universal data format converter with central engine architecture - supports JSON, XML, YAML conversions
Author: naman22khater
Latest version: 1.0.1

# @naman22khater/data-converter

A universal data format converter with a central engine architecture. Convert seamlessly between JSON, XML, and YAML formats.

[![npm version](https://img.shields.io/npm/v/@naman22khater/data-converter.svg)](https://www.npmjs.com/package/@naman22khater/data-converter)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔄 **Universal Conversion** - Convert between JSON, XML, and YAML
- 🏗️ **Central Engine Architecture** - Uses Intermediate Representation (IR) for efficient format conversion
- 📦 **Zero Dependencies** - Lightweight with no external dependencies
- 🎯 **TypeScript Support** - Full TypeScript definitions included
- 🌐 **Multiple Builds** - ESM, CommonJS, and UMD bundles available
- ⚡ **Extensible** - Easy to add new formats (only requires parser + serializer)

## Installation

```bash
npm install @naman22khater/data-converter
```

## Quick Start

```typescript
import { convert } from '@naman22khater/data-converter';

// JSON to XML
const xmlResult = convert('{"name": "John", "age": 30}', {
  from: 'json',
  to: 'xml'
});
console.log(xmlResult.output);
// <?xml version="1.0" encoding="UTF-8"?>
// <root>
//   <name>John</name>
//   <age>30</age>
// </root>

// XML to YAML
const yamlResult = convert('<user><name>John</name></user>', {
  from: 'xml',
  to: 'yaml'
});
console.log(yamlResult.output);
// user:
//   name: John

// JSON to YAML
const yamlResult2 = convert('{"users": [{"name": "Alice"}, {"name": "Bob"}]}', {
  from: 'json',
  to: 'yaml'
});
console.log(yamlResult2.output);
```

## API Reference

### `convert(input, options)`

Main conversion function.

```typescript
const result = convert(input: string, {
  from: 'json' | 'xml' | 'yaml',
  to: 'json' | 'xml' | 'yaml',
  parseOptions?: object,    // Format-specific parse options
  serializeOptions?: object // Format-specific serialize options
});

// Returns: { output: string, ir?: IRDocument }
```

### `parse(input, format, options?)`

Parse input into Intermediate Representation.

```typescript
import { parse } from '@naman22khater/data-converter';

const ir = parse('{"name": "John"}', 'json');
```

### `serialize(ir, format, options?)`

Serialize IR to a specific format.

```typescript
import { serialize } from '@naman22khater/data-converter';

const output = serialize(ir, 'xml', { indent: 4 });
```

### `engine`

Access the conversion engine directly for advanced use cases.

```typescript
import { engine } from '@naman22khater/data-converter';

// Check supported formats
console.log(engine.getSupportedSourceFormats()); // ['json', 'xml', 'yaml']

// Check if conversion is possible
console.log(engine.canConvert('json', 'xml')); // true

// Register custom format handlers
engine.registerParser(myCustomParser);
engine.registerSerializer(myCustomSerializer);
```

## Serialization Options

### XML Options

```typescript
convert(json, {
  from: 'json',
  to: 'xml',
  serializeOptions: {
    declaration: true,      // Include XML declaration (default: true)
    indent: 2,              // Indentation spaces (default: 2)
    rootElement: 'root',    // Root element name for objects/arrays
    arrayItemName: 'item',  // Element name for array items
    attributePrefix: '@',   // Prefix for attributes in JSON
    textNodeName: '#text'   // Key for text content in JSON
  }
});
```

### JSON Options

```typescript
convert(xml, {
  from: 'xml',
  to: 'json',
  serializeOptions: {
    indent: 2,              // Indentation spaces (default: 2)
    attributePrefix: '@',   // Prefix for XML attributes
    textNodeName: '#text'   // Key for text content
  }
});
```

### YAML Options

```typescript
convert(json, {
  from: 'json',
  to: 'yaml',
  serializeOptions: {
    indent: 2,              // Indentation spaces (default: 2)
    quoteStrings: false     // Force quote all strings
  }
});
```

## Parse Options

### XML Parse Options

```typescript
convert(xml, {
  from: 'xml',
  to: 'json',
  parseOptions: {
    ignoreAttributes: false,  // Skip XML attributes
    ignoreComments: true,     // Skip XML comments
    trimText: true            // Trim whitespace from text
  }
});
```

## Architecture

This library uses a **Central Engine with Intermediate Representation (IR)** architecture:

```
Source Format → Parser → IR → Serializer → Target Format
```

### Benefits

- **O(2n) complexity** instead of O(n²) - Adding a new format only requires 1 parser + 1 serializer
- **Consistent behavior** - All conversions go through the same IR
- **Extensible** - Easy to add new formats without modifying existing code

### IR Node Types

The Intermediate Representation supports these node types:

- `document` - Root document node
- `element` - XML-like element with name, attributes, children
- `object` - Key-value pairs
- `array` - Ordered list of items
- `text` - Text content
- `primitive` - String, number, boolean, null
- `attribute` - Element attribute
- `comment` - Comment node
- `cdata` - CDATA section

## Adding Custom Formats

You can extend the converter with custom formats:

```typescript
import { engine, FormatParser, FormatSerializer, IRDocument } from '@naman22khater/data-converter';

// Create a parser
const myParser: FormatParser = {
  format: 'myformat',
  parse(input: string, options?: object): IRDocument {
    // Parse input and return IR
    return { type: 'document', children: [...] };
  }
};

// Create a serializer
const mySerializer: FormatSerializer = {
  format: 'myformat',
  serialize(ir: IRDocument, options?: object): string {
    // Convert IR to string
    return '...';
  }
};

// Register with engine
engine.registerParser(myParser);
engine.registerSerializer(mySerializer);

// Now you can convert to/from your format
convert(input, { from: 'json', to: 'myformat' });
```

## Legacy API

For backward compatibility, direct conversion functions are available:

```typescript
import { jsonToXml, xmlToJson } from '@naman22khater/data-converter';

const xml = jsonToXml('{"name": "John"}');
const json = xmlToJson('<name>John</name>');
```

## Browser Usage

The UMD build can be used directly in browsers:

```html
<script src="https://unpkg.com/@naman22khater/data-converter/dist/index.umd.js"></script>
<script>
  const { convert } = DataConverter;
  const result = convert('{"hello": "world"}', { from: 'json', to: 'xml' });
  console.log(result.output);
</script>
```

## Examples

### Convert API Response to YAML Config

```typescript
const apiResponse = `{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp"
  },
  "cache": {
    "enabled": true,
    "ttl": 3600
  }
}`;

const yamlConfig = convert(apiResponse, { from: 'json', to: 'yaml' });
console.log(yamlConfig.output);
// database:
//   host: localhost
//   port: 5432
//   name: myapp
// cache:
//   enabled: true
//   ttl: 3600
```

### Parse XML with Attributes

```typescript
const xml = `
<user id="123" active="true">
  <name>John Doe</name>
  <email>john@example.com</email>
</user>
`;

const result = convert(xml, { from: 'xml', to: 'json' });
console.log(result.output);
// {
//   "user": {
//     "@id": "123",
//     "@active": "true",
//     "name": "John Doe",
//     "email": "john@example.com"
//   }
// }
```

## Author

**Naman Khater**

- [LinkedIn](https://www.linkedin.com/in/naman-22-khater/)
- [npm](https://www.npmjs.com/~naman22khater)
- [GitHub](https://github.com/MadMaxINDIAN)

## License

MIT © [Naman Khater](https://www.linkedin.com/in/naman-22-khater/)