toon-formatter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ankit Pal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,406 @@
1
+ # 🚀 TOON Converter
2
+
3
+ A lightweight, zero-dependency* library to convert between **TOON** (Token-Oriented Object Notation) and popular data formats (JSON, YAML, XML, CSV).
4
+
5
+ **Reduce your LLM token costs by up to 40%** using the TOON format!
6
+
7
+ \* *Only external dependencies: `js-yaml` and `papaparse` for YAML and CSV parsing*
8
+
9
+ ---
10
+
11
+ ## 📦 Installation
12
+
13
+ ```bash
14
+ npm install toon-converter
15
+ ```
16
+
17
+ ---
18
+
19
+ ## 🎯 What is TOON?
20
+
21
+ **TOON (Token-Oriented Object Notation)** is a compact, human-readable data serialization format designed specifically for use with Large Language Models (LLMs). It represents the same data model as JSON but with significantly fewer tokens.
22
+
23
+ ### Why TOON?
24
+
25
+ - **💰 Lower API Costs**: Fewer tokens = lower costs
26
+ - **⚡ Faster Processing**: Reduced latency with smaller payloads
27
+ - **📊 More Context**: Fit more data in the same context window
28
+ - **🎯 Explicit Structure**: Array lengths and field declarations reduce hallucinations
29
+
30
+ ### TOON vs JSON Example
31
+
32
+ **JSON** (87 tokens):
33
+ ```json
34
+ {
35
+ "users": [
36
+ {"id": 1, "name": "Alice", "active": true},
37
+ {"id": 2, "name": "Bob", "active": false},
38
+ {"id": 3, "name": "Charlie", "active": true}
39
+ ]
40
+ }
41
+ ```
42
+
43
+ **TOON** (52 tokens - 40% reduction):
44
+ ```
45
+ users[3]{id,name,active}:
46
+ 1,"Alice",true
47
+ 2,"Bob",false
48
+ 3,"Charlie",true
49
+ ```
50
+
51
+ ---
52
+
53
+ ## 🚀 Quick Start
54
+
55
+ ### Basic Usage
56
+
57
+ ```javascript
58
+ import { jsonToToon, toonToJson } from 'toon-converter';
59
+
60
+ // JSON to TOON
61
+ const jsonData = { name: "Alice", age: 30, active: true };
62
+ const toonString = jsonToToon(jsonData);
63
+ console.log(toonString);
64
+ // Output:
65
+ // name: "Alice"
66
+ // age: 30
67
+ // active: true
68
+
69
+ // TOON to JSON
70
+ const toonInput = `name: "Alice"\nage: 30\nactive: true`;
71
+ const jsonOutput = toonToJson(toonInput);
72
+ console.log(jsonOutput);
73
+ // Output: { name: "Alice", age: 30, active: true }
74
+ ```
75
+
76
+ ### Using the ToonConverter Class
77
+
78
+ ```javascript
79
+ import ToonConverter from 'toon-converter';
80
+
81
+ // Convert from various formats
82
+ const toonFromJson = ToonConverter.fromJson({ key: "value" });
83
+ const toonFromYaml = ToonConverter.fromYaml("key: value");
84
+ const toonFromXml = ToonConverter.fromXml("<root><key>value</key></root>");
85
+ const toonFromCsv = await ToonConverter.fromCsv("name,age\nAlice,30");
86
+
87
+ // Convert to various formats
88
+ const jsonData = ToonConverter.toJson(toonString);
89
+ const yamlData = ToonConverter.toYaml(toonString);
90
+ const xmlData = ToonConverter.toXml(toonString);
91
+ const csvData = ToonConverter.toCsv(toonString);
92
+
93
+ // Validate TOON
94
+ const result = ToonConverter.validate(toonString);
95
+ if (result.isValid) {
96
+ console.log("Valid TOON!");
97
+ } else {
98
+ console.error("Invalid TOON:", result.error);
99
+ }
100
+ ```
101
+
102
+ ---
103
+
104
+ ## 📚 API Reference
105
+
106
+ ### JSON Converters
107
+
108
+ #### `jsonToToon(data, key?, depth?)`
109
+ Converts JSON data to TOON format.
110
+
111
+ **Parameters:**
112
+ - `data` (any): JSON data to convert
113
+ - `key` (string, optional): Key name for root object
114
+ - `depth` (number, optional): Initial indentation depth
115
+
116
+ **Returns:** `string` - TOON formatted string
117
+
118
+ **Example:**
119
+ ```javascript
120
+ import { jsonToToon } from 'toon-converter';
121
+
122
+ const data = {
123
+ users: [
124
+ { id: 1, name: "Alice" },
125
+ { id: 2, name: "Bob" }
126
+ ]
127
+ };
128
+
129
+ const toon = jsonToToon(data);
130
+ console.log(toon);
131
+ // users[2]{id,name}:
132
+ // 1,"Alice"
133
+ // 2,"Bob"
134
+ ```
135
+
136
+ #### `toonToJson(toonString)`
137
+ Converts TOON string to JSON.
138
+
139
+ **Parameters:**
140
+ - `toonString` (string): TOON formatted string
141
+
142
+ **Returns:** `any` - Parsed JSON data
143
+
144
+ ---
145
+
146
+ ### YAML Converters
147
+
148
+ #### `yamlToToon(yamlString)`
149
+ Converts YAML to TOON format.
150
+
151
+ **Parameters:**
152
+ - `yamlString` (string): YAML formatted string
153
+
154
+ **Returns:** `string` - TOON formatted string
155
+
156
+ **Throws:** `Error` if YAML is invalid
157
+
158
+ #### `toonToYaml(toonString)`
159
+ Converts TOON to YAML format.
160
+
161
+ **Parameters:**
162
+ - `toonString` (string): TOON formatted string
163
+
164
+ **Returns:** `string` - YAML formatted string
165
+
166
+ **Throws:** `Error` if TOON is invalid
167
+
168
+ ---
169
+
170
+ ### XML Converters
171
+
172
+ #### `xmlToToon(xmlString)`
173
+ Converts XML to TOON format.
174
+
175
+ **Parameters:**
176
+ - `xmlString` (string): XML formatted string
177
+
178
+ **Returns:** `string` - TOON formatted string
179
+
180
+ **Throws:** `Error` if XML is invalid
181
+
182
+ **Note:** Requires `DOMParser` (browser) or `xmldom` package (Node.js)
183
+
184
+ #### `toonToXml(toonString)`
185
+ Converts TOON to XML format.
186
+
187
+ **Parameters:**
188
+ - `toonString` (string): TOON formatted string
189
+
190
+ **Returns:** `string` - XML formatted string
191
+
192
+ **Throws:** `Error` if TOON is invalid
193
+
194
+ ---
195
+
196
+ ### CSV Converters
197
+
198
+ #### `csvToToon(csvString)`
199
+ Converts CSV to TOON format (async).
200
+
201
+ **Parameters:**
202
+ - `csvString` (string): CSV formatted string
203
+
204
+ **Returns:** `Promise<string>` - TOON formatted string
205
+
206
+ **Throws:** `Error` if CSV is invalid
207
+
208
+ #### `csvToToonSync(csvString)`
209
+ Converts CSV to TOON format (sync).
210
+
211
+ **Parameters:**
212
+ - `csvString` (string): CSV formatted string
213
+
214
+ **Returns:** `string` - TOON formatted string
215
+
216
+ **Throws:** `Error` if CSV is invalid
217
+
218
+ #### `toonToCsv(toonString)`
219
+ Converts TOON to CSV format.
220
+
221
+ **Parameters:**
222
+ - `toonString` (string): TOON formatted string
223
+
224
+ **Returns:** `string` - CSV formatted string
225
+
226
+ **Throws:** `Error` if TOON is invalid
227
+
228
+ ---
229
+
230
+ ### Validator
231
+
232
+ #### `validateToonString(toonString)`
233
+ Validates a TOON string for syntax and structural correctness.
234
+
235
+ **Parameters:**
236
+ - `toonString` (string): TOON string to validate
237
+
238
+ **Returns:** `{isValid: boolean, error: string|null}`
239
+
240
+ **Example:**
241
+ ```javascript
242
+ import { validateToonString } from 'toon-converter';
243
+
244
+ const result = validateToonString(`
245
+ users[2]{id,name}:
246
+ 1,"Alice"
247
+ 2,"Bob"
248
+ `);
249
+
250
+ if (result.isValid) {
251
+ console.log("Valid TOON!");
252
+ } else {
253
+ console.error("Error:", result.error);
254
+ }
255
+ ```
256
+
257
+ ---
258
+
259
+ ## 🎨 TOON Format Guide
260
+
261
+ ### Primitives
262
+ ```
263
+ name: "Alice"
264
+ age: 30
265
+ active: true
266
+ score: null
267
+ ```
268
+
269
+ ### Objects
270
+ ```
271
+ user:
272
+ name: "Alice"
273
+ age: 30
274
+ ```
275
+
276
+ ### Arrays (Inline)
277
+ ```
278
+ numbers[3]: 1, 2, 3
279
+ names[2]: "Alice", "Bob"
280
+ ```
281
+
282
+ ### Arrays (Block)
283
+ ```
284
+ items[2]:
285
+ - "First"
286
+ - "Second"
287
+ ```
288
+
289
+ ### Tabular Arrays (Optimized)
290
+ ```
291
+ users[3]{id,name,active}:
292
+ 1,"Alice",true
293
+ 2,"Bob",false
294
+ 3,"Charlie",true
295
+ ```
296
+
297
+ ### Nested Structures
298
+ ```
299
+ company:
300
+ name: "TechCorp"
301
+ employees[2]:
302
+ -
303
+ name: "Alice"
304
+ role: "Engineer"
305
+ -
306
+ name: "Bob"
307
+ role: "Designer"
308
+ ```
309
+
310
+ ---
311
+
312
+ ## 💡 Use Cases
313
+
314
+ ### 1. LLM API Optimization
315
+ ```javascript
316
+ import { jsonToToon } from 'toon-converter';
317
+
318
+ // Before: Sending JSON to LLM
319
+ const jsonPrompt = JSON.stringify(largeDataset);
320
+ // 1000+ tokens
321
+
322
+ // After: Sending TOON to LLM
323
+ const toonPrompt = jsonToToon(largeDataset);
324
+ // 600 tokens (40% reduction!)
325
+
326
+ const response = await openai.chat.completions.create({
327
+ messages: [{ role: "user", content: toonPrompt }]
328
+ });
329
+ ```
330
+
331
+ ### 2. Data Pipeline Integration
332
+ ```javascript
333
+ import { csvToToonSync, toonToJson } from 'toon-converter';
334
+
335
+ // Read CSV, convert to TOON, process, convert back
336
+ const csvData = fs.readFileSync('data.csv', 'utf-8');
337
+ const toonData = csvToToonSync(csvData);
338
+
339
+ // Send to LLM for processing...
340
+ const processedToon = await processWithLLM(toonData);
341
+
342
+ // Convert back to JSON for your app
343
+ const jsonResult = toonToJson(processedToon);
344
+ ```
345
+
346
+ ### 3. Configuration Files
347
+ ```javascript
348
+ import { yamlToToon, toonToYaml } from 'toon-converter';
349
+
350
+ // Convert YAML config to TOON for LLM analysis
351
+ const yamlConfig = fs.readFileSync('config.yaml', 'utf-8');
352
+ const toonConfig = yamlToToon(yamlConfig);
353
+
354
+ // LLM can analyze and suggest improvements...
355
+ ```
356
+
357
+ ---
358
+
359
+ ## 🧪 Testing
360
+
361
+ ```bash
362
+ npm test
363
+ ```
364
+
365
+ ---
366
+
367
+ ## 📄 License
368
+
369
+ MIT License - see LICENSE file for details
370
+
371
+ ---
372
+
373
+ ## 🤝 Contributing
374
+
375
+ Contributions are welcome! Please feel free to submit a Pull Request.
376
+
377
+ ---
378
+
379
+ ## 🔗 Links
380
+
381
+ - **GitHub**: https://github.com/ankitpal181/toon-converter
382
+ - **NPM**: https://www.npmjs.com/package/toon-converter
383
+ - **Online Tool**: https://toon-formatter.com
384
+
385
+ ---
386
+
387
+ ## 📊 Benchmarks
388
+
389
+ | Format | Tokens | Reduction |
390
+ |--------|--------|-----------|
391
+ | JSON | 1000 | 0% |
392
+ | TOON | 600 | 40% |
393
+
394
+ *Based on average structured data with arrays of objects*
395
+
396
+ ---
397
+
398
+ ## ⚠️ Notes
399
+
400
+ - **XML Support**: For Node.js environments, install `xmldom`: `npm install xmldom`
401
+ - **CSV Parsing**: Uses PapaParse for robust CSV handling
402
+ - **YAML Parsing**: Uses js-yaml for YAML support
403
+
404
+ ---
405
+
406
+ Made with ❤️ by Ankit Pal
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "toon-formatter",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight library to convert between TOON (Token-Oriented Object Notation) and popular data formats (JSON, YAML, XML, CSV). Reduce LLM token costs by up to 40%.",
5
+ "main": "src/index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "test": "node --test test/*.test.js",
9
+ "test:watch": "node --test --watch test/*.test.js"
10
+ },
11
+ "keywords": [
12
+ "toon",
13
+ "json",
14
+ "yaml",
15
+ "xml",
16
+ "csv",
17
+ "converter",
18
+ "llm",
19
+ "token",
20
+ "optimization",
21
+ "data-format",
22
+ "serialization",
23
+ "formatter"
24
+ ],
25
+ "author": "Ankit Pal",
26
+ "license": "MIT",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/ankitpal181/toon-formatter-lib"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/ankitpal181/toon-formatter-lib/issues"
33
+ },
34
+ "homepage": "https://github.com/ankitpal181/toon-formatter-lib#readme",
35
+ "engines": {
36
+ "node": ">=16.0.0"
37
+ },
38
+ "dependencies": {
39
+ "js-yaml": "^4.1.0",
40
+ "papaparse": "^5.4.1"
41
+ },
42
+ "devDependencies": {
43
+ "xmldom": "^0.6.0"
44
+ },
45
+ "exports": {
46
+ ".": "./src/index.js",
47
+ "./json": "./src/json.js",
48
+ "./yaml": "./src/yaml.js",
49
+ "./xml": "./src/xml.js",
50
+ "./csv": "./src/csv.js",
51
+ "./validator": "./src/validator.js",
52
+ "./utils": "./src/utils.js"
53
+ }
54
+ }
package/src/csv.js ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * CSV ↔ TOON Converter
3
+ */
4
+
5
+ import Papa from 'papaparse';
6
+ import { jsonToToon, toonToJson } from './json.js';
7
+
8
+ /**
9
+ * Converts CSV to TOON format
10
+ * @param {string} csvString - CSV formatted string
11
+ * @returns {Promise<string>} TOON formatted string
12
+ * @throws {Error} If CSV is invalid
13
+ */
14
+ export function csvToToon(csvString) {
15
+ if (!csvString || typeof csvString !== 'string') {
16
+ throw new Error('Input must be a non-empty string');
17
+ }
18
+
19
+ return new Promise((resolve, reject) => {
20
+ Papa.parse(csvString, {
21
+ header: true,
22
+ dynamicTyping: true,
23
+ complete: function (results) {
24
+ try {
25
+ const jsonObject = results.data;
26
+
27
+ if (typeof jsonObject !== "object" || jsonObject === null) {
28
+ throw new Error("CSV parsing failed — cannot convert.");
29
+ }
30
+
31
+ const toonString = jsonToToon(jsonObject);
32
+ resolve(toonString);
33
+ } catch (error) {
34
+ reject(error);
35
+ }
36
+ },
37
+ error: function (error) {
38
+ reject(new Error(`CSV parsing error: ${error.message}`));
39
+ }
40
+ });
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Converts CSV to TOON format (synchronous version)
46
+ * @param {string} csvString - CSV formatted string
47
+ * @returns {string} TOON formatted string
48
+ * @throws {Error} If CSV is invalid
49
+ */
50
+ export function csvToToonSync(csvString) {
51
+ if (!csvString || typeof csvString !== 'string') {
52
+ throw new Error('Input must be a non-empty string');
53
+ }
54
+
55
+ const results = Papa.parse(csvString, {
56
+ header: true,
57
+ dynamicTyping: true,
58
+ });
59
+
60
+ if (results.errors && results.errors.length > 0) {
61
+ throw new Error(`CSV parsing error: ${results.errors[0].message}`);
62
+ }
63
+
64
+ const jsonObject = results.data;
65
+
66
+ if (typeof jsonObject !== "object" || jsonObject === null) {
67
+ throw new Error("CSV parsing failed — cannot convert.");
68
+ }
69
+
70
+ return jsonToToon(jsonObject);
71
+ }
72
+
73
+ /**
74
+ * Converts TOON to CSV format
75
+ * @param {string} toonString - TOON formatted string
76
+ * @returns {string} CSV formatted string
77
+ * @throws {Error} If TOON is invalid
78
+ */
79
+ export function toonToCsv(toonString) {
80
+ if (!toonString || typeof toonString !== 'string') {
81
+ throw new Error('Input must be a non-empty string');
82
+ }
83
+
84
+ const jsonObject = toonToJson(toonString);
85
+
86
+ const csvString = Papa.unparse(jsonObject, {
87
+ header: true,
88
+ dynamicTyping: true,
89
+ });
90
+
91
+ return csvString;
92
+ }
package/src/index.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * TOON Converter Library
3
+ *
4
+ * A lightweight library to convert between TOON (Token-Oriented Object Notation)
5
+ * and popular data formats (JSON, YAML, XML, CSV).
6
+ *
7
+ * Reduce LLM token costs by up to 40% using TOON format.
8
+ *
9
+ * @module toon-converter
10
+ */
11
+
12
+ import { jsonToToon, toonToJson } from './json.js';
13
+ import { yamlToToon, toonToYaml } from './yaml.js';
14
+ import { xmlToToon, toonToXml } from './xml.js';
15
+ import { csvToToon, csvToToonSync, toonToCsv } from './csv.js';
16
+ import { validateToonString } from './validator.js';
17
+ import { encodeXmlReservedChars, splitByDelimiter, parseValue, formatValue } from './utils.js';
18
+
19
+ // Exports
20
+ export {
21
+ jsonToToon, toonToJson,
22
+ yamlToToon, toonToYaml,
23
+ xmlToToon, toonToXml,
24
+ csvToToon, csvToToonSync, toonToCsv,
25
+ validateToonString,
26
+ encodeXmlReservedChars, splitByDelimiter, parseValue, formatValue
27
+ };
28
+
29
+ /**
30
+ * Main converter class for easy usage
31
+ */
32
+ export class ToonConverter {
33
+ /**
34
+ * Convert JSON to TOON
35
+ * @param {*} jsonData - JSON data (object, array, or primitive)
36
+ * @returns {string} TOON formatted string
37
+ */
38
+ static fromJson(jsonData) {
39
+ return jsonToToon(jsonData);
40
+ }
41
+
42
+ /**
43
+ * Convert TOON to JSON
44
+ * @param {string} toonString - TOON formatted string
45
+ * @returns {*} Parsed JSON data
46
+ */
47
+ static toJson(toonString) {
48
+ return toonToJson(toonString);
49
+ }
50
+
51
+ /**
52
+ * Convert YAML to TOON
53
+ * @param {string} yamlString - YAML formatted string
54
+ * @returns {string} TOON formatted string
55
+ */
56
+ static fromYaml(yamlString) {
57
+ return yamlToToon(yamlString);
58
+ }
59
+
60
+ /**
61
+ * Convert TOON to YAML
62
+ * @param {string} toonString - TOON formatted string
63
+ * @returns {string} YAML formatted string
64
+ */
65
+ static toYaml(toonString) {
66
+ return toonToYaml(toonString);
67
+ }
68
+
69
+ /**
70
+ * Convert XML to TOON (Async)
71
+ * @param {string} xmlString - XML formatted string
72
+ * @returns {Promise<string>} TOON formatted string
73
+ */
74
+ static async fromXml(xmlString) {
75
+ return xmlToToon(xmlString);
76
+ }
77
+
78
+ /**
79
+ * Convert TOON to XML
80
+ * @param {string} toonString - TOON formatted string
81
+ * @returns {string} XML formatted string
82
+ */
83
+ static toXml(toonString) {
84
+ return toonToXml(toonString);
85
+ }
86
+
87
+ /**
88
+ * Convert CSV to TOON (Async)
89
+ * @param {string} csvString - CSV formatted string
90
+ * @returns {Promise<string>} TOON formatted string
91
+ */
92
+ static async fromCsv(csvString) {
93
+ return csvToToon(csvString);
94
+ }
95
+
96
+ /**
97
+ * Convert CSV to TOON (Sync)
98
+ * @param {string} csvString - CSV formatted string
99
+ * @returns {string} TOON formatted string
100
+ */
101
+ static fromCsvSync(csvString) {
102
+ return csvToToonSync(csvString);
103
+ }
104
+
105
+ /**
106
+ * Convert TOON to CSV
107
+ * @param {string} toonString - TOON formatted string
108
+ * @returns {string} CSV formatted string
109
+ */
110
+ static toCsv(toonString) {
111
+ return toonToCsv(toonString);
112
+ }
113
+
114
+ /**
115
+ * Validate a TOON string
116
+ * @param {string} toonString - TOON formatted string
117
+ * @returns {{isValid: boolean, error: string|null}} Validation result
118
+ */
119
+ static validate(toonString) {
120
+ return validateToonString(toonString);
121
+ }
122
+ }
123
+
124
+ export default ToonConverter;