toonfile 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) 2026 ideas2code.dev
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,302 @@
1
+ # toonfile
2
+
3
+ Easily read/write TOON (Token-Oriented Object Notation) files in Node.js.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/toonfile.svg)](https://www.npmjs.com/package/toonfile)
6
+ [![npm downloads](https://img.shields.io/npm/dm/toonfile.svg)](https://www.npmjs.com/package/toonfile)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue.svg)](https://www.typescriptlang.org/)
9
+ [![Node.js](https://img.shields.io/badge/Node.js->=14-green.svg)](https://nodejs.org/)
10
+
11
+ ## Why?
12
+
13
+ TOON is a compact, human-readable format designed for LLM prompts that reduces token usage by 30-60% compared to JSON while maintaining readability. This library makes it as easy to work with `.toon` files as it is to work with `.json` files.
14
+
15
+ **Like [jsonfile](https://github.com/jprichardson/node-jsonfile), but for TOON format.**
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install toonfile
21
+ ```
22
+
23
+ ## Quick Start
24
+
25
+ ```javascript
26
+ const toonfile = require('toonfile')
27
+
28
+ // Read TOON file
29
+ const config = await toonfile.readFile('./config.toon')
30
+
31
+ // Write TOON file
32
+ const data = { name: 'Alice', scores: [95, 87, 92] }
33
+ await toonfile.writeFile('./output.toon', data)
34
+ ```
35
+
36
+ ## API
37
+
38
+ ### readFile(filename, [options], callback)
39
+
40
+ Read and parse a TOON file.
41
+
42
+ **Options:**
43
+ - `encoding` (string, default: `'utf8'`): File encoding
44
+ - `throws` (boolean, default: `true`): Throw error on parse failure. If `false`, returns `null` for invalid files.
45
+ - `reviver` (function): Transform function for parsed values
46
+ - `fs` (object): Custom fs module for testing
47
+
48
+ **Examples:**
49
+
50
+ ```javascript
51
+ // With callback
52
+ toonfile.readFile('config.toon', (err, data) => {
53
+ if (err) console.error(err)
54
+ console.log(data)
55
+ })
56
+
57
+ // With promise
58
+ const data = await toonfile.readFile('config.toon')
59
+
60
+ // With async/await
61
+ async function loadConfig () {
62
+ const config = await toonfile.readFile('config.toon')
63
+ return config
64
+ }
65
+
66
+ // Silent error handling
67
+ const data = await toonfile.readFile('config.toon', { throws: false })
68
+ if (!data) console.log('File not found or invalid')
69
+ ```
70
+
71
+ ### readFileSync(filename, [options])
72
+
73
+ Synchronous version of `readFile`.
74
+
75
+ ```javascript
76
+ const toonfile = require('toonfile')
77
+ const config = toonfile.readFileSync('./config.toon')
78
+ console.log(config)
79
+ ```
80
+
81
+ ### writeFile(filename, obj, [options], callback)
82
+
83
+ Stringify object and write to TOON file.
84
+
85
+ **Options:**
86
+ - `encoding` (string, default: `'utf8'`): File encoding
87
+ - `indentSize` (number, default: `2`): Spaces per indent level
88
+ - `delimiter` (string, default: `','`): Delimiter for arrays: `','`, `'\t'`, or `'|'`
89
+ - `EOL` (string, default: `'\n'`): End-of-line character
90
+ - `finalEOL` (boolean, default: `true`): Include EOL at end of file
91
+ - `fs` (object): Custom fs module for testing
92
+
93
+ **Examples:**
94
+
95
+ ```javascript
96
+ const data = {
97
+ company: 'TechCorp',
98
+ employees: [
99
+ { id: 1, name: 'Alice', role: 'Engineer' },
100
+ { id: 2, name: 'Bob', role: 'Designer' }
101
+ ]
102
+ }
103
+
104
+ // Basic write
105
+ await toonfile.writeFile('data.toon', data)
106
+
107
+ // With options
108
+ await toonfile.writeFile('data.toon', data, {
109
+ indentSize: 4,
110
+ delimiter: '|',
111
+ EOL: '\r\n'
112
+ })
113
+
114
+ // Callback style
115
+ toonfile.writeFile('data.toon', data, (err) => {
116
+ if (err) console.error(err)
117
+ console.log('Write complete!')
118
+ })
119
+ ```
120
+
121
+ **Formatting with spaces:**
122
+
123
+ ```javascript
124
+ await toonfile.writeFile('data.toon', obj, { indentSize: 4 })
125
+ ```
126
+
127
+ **Overriding EOL:**
128
+
129
+ ```javascript
130
+ await toonfile.writeFile('data.toon', obj, { EOL: '\r\n' })
131
+ ```
132
+
133
+ **Disabling the EOL at the end of file:**
134
+
135
+ ```javascript
136
+ await toonfile.writeFile('data.toon', obj, { finalEOL: false })
137
+ ```
138
+
139
+ **Appending to an existing file:**
140
+
141
+ You can use the `fs.writeFile` option `{ flag: 'a' }` to achieve this.
142
+
143
+ ```javascript
144
+ await toonfile.writeFile('data.toon', obj, { flag: 'a' })
145
+ ```
146
+
147
+ ### writeFileSync(filename, obj, [options])
148
+
149
+ Synchronous version of `writeFile`.
150
+
151
+ ```javascript
152
+ const toonfile = require('toonfile')
153
+ toonfile.writeFileSync('./data.toon', { name: 'Bob', age: 25 })
154
+ ```
155
+
156
+ ### parse(toonString, [options])
157
+
158
+ Parse a TOON string to JavaScript object.
159
+
160
+ ```javascript
161
+ const toon = 'name: Alice\nage: 30'
162
+ const obj = toonfile.parse(toon)
163
+ // → { name: 'Alice', age: 30 }
164
+ ```
165
+
166
+ ### stringify(obj, [options])
167
+
168
+ Convert JavaScript object to TOON string.
169
+
170
+ ```javascript
171
+ const obj = { name: 'Bob', scores: [95, 87, 92] }
172
+ const toon = toonfile.stringify(obj)
173
+ // → 'name: Bob\nscores[3]: 95,87,92'
174
+ ```
175
+
176
+ ## TOON Format Examples
177
+
178
+ ### Simple Object
179
+
180
+ **JavaScript:**
181
+ ```javascript
182
+ { name: 'Alice', age: 30, city: 'Boston' }
183
+ ```
184
+
185
+ **TOON:**
186
+ ```
187
+ name: Alice
188
+ age: 30
189
+ city: Boston
190
+ ```
191
+
192
+ ### Nested Objects
193
+
194
+ **JavaScript:**
195
+ ```javascript
196
+ {
197
+ person: {
198
+ name: 'Alice',
199
+ address: { city: 'Boston', zip: '02101' }
200
+ }
201
+ }
202
+ ```
203
+
204
+ **TOON:**
205
+ ```
206
+ person:
207
+ name: Alice
208
+ address:
209
+ city: Boston
210
+ zip: 02101
211
+ ```
212
+
213
+ ### Arrays (Inline)
214
+
215
+ **JavaScript:**
216
+ ```javascript
217
+ { scores: [95, 87, 92] }
218
+ ```
219
+
220
+ **TOON:**
221
+ ```
222
+ scores[3]: 95,87,92
223
+ ```
224
+
225
+ ### Complex Example
226
+
227
+ **JavaScript:**
228
+ ```javascript
229
+ {
230
+ company: 'TechCorp',
231
+ founded: 2020,
232
+ active: true,
233
+ employees: ['Alice', 'Bob', 'Carol'],
234
+ metadata: {
235
+ location: 'Boston',
236
+ remote: true
237
+ }
238
+ }
239
+ ```
240
+
241
+ **TOON:**
242
+ ```
243
+ company: TechCorp
244
+ founded: 2020
245
+ active: true
246
+ employees[3]: Alice,Bob,Carol
247
+ metadata:
248
+ location: Boston
249
+ remote: true
250
+ ```
251
+
252
+ ## Comparison with JSON
253
+
254
+ **JSON (124 characters):**
255
+ ```json
256
+ {
257
+ "name": "Alice",
258
+ "age": 30,
259
+ "scores": [95, 87, 92],
260
+ "address": {
261
+ "city": "Boston"
262
+ }
263
+ }
264
+ ```
265
+
266
+ **TOON (73 characters - 41% reduction):**
267
+ ```
268
+ name: Alice
269
+ age: 30
270
+ scores[3]: 95,87,92
271
+ address:
272
+ city: Boston
273
+ ```
274
+
275
+ ## About TOON Format
276
+
277
+ TOON (Token-Oriented Object Notation) is a compact, human-readable encoding designed specifically for LLM prompts. It provides:
278
+
279
+ - **30-60% token reduction** compared to JSON
280
+ - **Human-readable** syntax similar to YAML
281
+ - **Schema-aware** structure with explicit array lengths
282
+ - **Lossless** serialization of the JSON data model
283
+
284
+ Learn more at [toon-format.org](https://github.com/toon-format/spec)
285
+
286
+ ## Related Projects
287
+
288
+ - [jsonfile](https://github.com/jprichardson/node-jsonfile) - The inspiration for this library
289
+ - [TOON Specification](https://github.com/toon-format/spec) - Official TOON format spec
290
+ - [TOON TypeScript SDK](https://github.com/toon-format/toon) - Official TypeScript implementation
291
+
292
+ ## GitHub Repository
293
+
294
+ [https://github.com/ideas2codedev/node-toonfile](https://github.com/ideas2codedev/node-toonfile)
295
+
296
+ ## License
297
+
298
+ MIT
299
+
300
+ ## Contributing
301
+
302
+ Contributions are welcome! Please feel free to submit a Pull Request at [https://github.com/ideas2codedev/node-toonfile](https://github.com/ideas2codedev/node-toonfile).
@@ -0,0 +1,106 @@
1
+ import { parse, stringify } from './utils';
2
+ import type { ReadOptions, WriteOptions, Callback } from './types';
3
+ /**
4
+ * Read and parse a TOON file asynchronously
5
+ *
6
+ * @param file - Path to the TOON file
7
+ * @param options - Read options or encoding string
8
+ * @param callback - Optional callback function
9
+ * @returns Promise that resolves to parsed object (if no callback provided)
10
+ *
11
+ * @example
12
+ * // With promise
13
+ * const data = await readFile('config.toon')
14
+ *
15
+ * @example
16
+ * // With callback
17
+ * readFile('config.toon', (err, data) => {
18
+ * if (err) console.error(err)
19
+ * console.log(data)
20
+ * })
21
+ *
22
+ * @example
23
+ * // With options
24
+ * const data = await readFile('config.toon', { throws: false })
25
+ */
26
+ export declare const readFile: {
27
+ (file: string, options?: ReadOptions | string): Promise<any>;
28
+ (file: string, callback: Callback<any>): void;
29
+ (file: string, options: ReadOptions | string, callback: Callback<any>): void;
30
+ };
31
+ /**
32
+ * Read and parse a TOON file synchronously
33
+ *
34
+ * @param file - Path to the TOON file
35
+ * @param options - Read options or encoding string
36
+ * @returns Parsed object
37
+ *
38
+ * @example
39
+ * const data = readFileSync('config.toon')
40
+ *
41
+ * @example
42
+ * const data = readFileSync('config.toon', { throws: false })
43
+ */
44
+ export declare function readFileSync(file: string, options?: ReadOptions | string): any;
45
+ /**
46
+ * Stringify object and write to TOON file asynchronously
47
+ *
48
+ * @param file - Path to the TOON file
49
+ * @param obj - Object to stringify and write
50
+ * @param options - Write options
51
+ * @param callback - Optional callback function
52
+ * @returns Promise that resolves when file is written (if no callback provided)
53
+ *
54
+ * @example
55
+ * // With promise
56
+ * await writeFile('data.toon', { name: 'Alice', age: 30 })
57
+ *
58
+ * @example
59
+ * // With callback
60
+ * writeFile('data.toon', obj, (err) => {
61
+ * if (err) console.error(err)
62
+ * })
63
+ *
64
+ * @example
65
+ * // With options
66
+ * await writeFile('data.toon', obj, { indentSize: 4, delimiter: '|' })
67
+ */
68
+ export declare const writeFile: {
69
+ (file: string, obj: any, options?: WriteOptions): Promise<void>;
70
+ (file: string, obj: any, callback: Callback<void>): void;
71
+ (file: string, obj: any, options: WriteOptions, callback: Callback<void>): void;
72
+ };
73
+ /**
74
+ * Stringify object and write to TOON file synchronously
75
+ *
76
+ * @param file - Path to the TOON file
77
+ * @param obj - Object to stringify and write
78
+ * @param options - Write options
79
+ *
80
+ * @example
81
+ * writeFileSync('data.toon', { name: 'Bob', age: 25 })
82
+ *
83
+ * @example
84
+ * writeFileSync('data.toon', obj, { indentSize: 4 })
85
+ */
86
+ export declare function writeFileSync(file: string, obj: any, options?: WriteOptions): void;
87
+ export { parse, stringify } from './utils';
88
+ export type { ReadOptions, WriteOptions, ParseOptions, StringifyOptions, Callback, ToonValue, ToonObject, ToonArray } from './types';
89
+ declare const _default: {
90
+ readFile: {
91
+ (file: string, options?: ReadOptions | string): Promise<any>;
92
+ (file: string, callback: Callback<any>): void;
93
+ (file: string, options: ReadOptions | string, callback: Callback<any>): void;
94
+ };
95
+ readFileSync: typeof readFileSync;
96
+ writeFile: {
97
+ (file: string, obj: any, options?: WriteOptions): Promise<void>;
98
+ (file: string, obj: any, callback: Callback<void>): void;
99
+ (file: string, obj: any, options: WriteOptions, callback: Callback<void>): void;
100
+ };
101
+ writeFileSync: typeof writeFileSync;
102
+ parse: typeof parse;
103
+ stringify: typeof stringify;
104
+ };
105
+ export default _default;
106
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAY,MAAM,SAAS,CAAA;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAyDlE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,QAAQ,EAAE;IACrB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;IAC5D,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;IAC7C,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;CAChC,CAAA;AAE9C;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,WAAW,GAAG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,IAAI;;;;;;AA0CjF,wBAOC"}
package/dist/index.js ADDED
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.stringify = exports.parse = exports.writeFile = exports.readFile = void 0;
37
+ exports.readFileSync = readFileSync;
38
+ exports.writeFileSync = writeFileSync;
39
+ const fs = __importStar(require("fs"));
40
+ const universalify = __importStar(require("universalify"));
41
+ const utils_1 = require("./utils");
42
+ let _fs;
43
+ try {
44
+ _fs = require('graceful-fs');
45
+ }
46
+ catch (_) {
47
+ _fs = fs;
48
+ }
49
+ // ============ READ FILE ============
50
+ async function _readFile(file, options = {}) {
51
+ if (typeof options === 'string') {
52
+ options = { encoding: options };
53
+ }
54
+ const fsModule = options.fs || _fs;
55
+ const shouldThrow = 'throws' in options ? options.throws : true;
56
+ let data;
57
+ try {
58
+ const result = await new Promise((resolve, reject) => {
59
+ fsModule.readFile(file, options.encoding || 'utf8', (err, data) => {
60
+ if (err)
61
+ reject(err);
62
+ else
63
+ resolve(data);
64
+ });
65
+ });
66
+ data = typeof result === 'string' ? result : result.toString('utf8');
67
+ }
68
+ catch (err) {
69
+ if (shouldThrow) {
70
+ const error = err;
71
+ error.message = `${file}: ${error.message}`;
72
+ throw error;
73
+ }
74
+ else {
75
+ return null;
76
+ }
77
+ }
78
+ data = (0, utils_1.stripBom)(data);
79
+ let obj;
80
+ try {
81
+ obj = (0, utils_1.parse)(data, options);
82
+ }
83
+ catch (err) {
84
+ if (shouldThrow) {
85
+ const error = err;
86
+ error.message = `${file}: ${error.message}`;
87
+ throw error;
88
+ }
89
+ else {
90
+ return null;
91
+ }
92
+ }
93
+ return obj;
94
+ }
95
+ /**
96
+ * Read and parse a TOON file asynchronously
97
+ *
98
+ * @param file - Path to the TOON file
99
+ * @param options - Read options or encoding string
100
+ * @param callback - Optional callback function
101
+ * @returns Promise that resolves to parsed object (if no callback provided)
102
+ *
103
+ * @example
104
+ * // With promise
105
+ * const data = await readFile('config.toon')
106
+ *
107
+ * @example
108
+ * // With callback
109
+ * readFile('config.toon', (err, data) => {
110
+ * if (err) console.error(err)
111
+ * console.log(data)
112
+ * })
113
+ *
114
+ * @example
115
+ * // With options
116
+ * const data = await readFile('config.toon', { throws: false })
117
+ */
118
+ exports.readFile = universalify.fromPromise(_readFile);
119
+ /**
120
+ * Read and parse a TOON file synchronously
121
+ *
122
+ * @param file - Path to the TOON file
123
+ * @param options - Read options or encoding string
124
+ * @returns Parsed object
125
+ *
126
+ * @example
127
+ * const data = readFileSync('config.toon')
128
+ *
129
+ * @example
130
+ * const data = readFileSync('config.toon', { throws: false })
131
+ */
132
+ function readFileSync(file, options = {}) {
133
+ if (typeof options === 'string') {
134
+ options = { encoding: options };
135
+ }
136
+ const fsModule = options.fs || _fs;
137
+ const shouldThrow = 'throws' in options ? options.throws : true;
138
+ try {
139
+ const buffer = fsModule.readFileSync(file, options);
140
+ let content = typeof buffer === 'string' ? buffer : buffer.toString('utf8');
141
+ content = (0, utils_1.stripBom)(content);
142
+ return (0, utils_1.parse)(content, options);
143
+ }
144
+ catch (err) {
145
+ if (shouldThrow) {
146
+ const error = err;
147
+ error.message = `${file}: ${error.message}`;
148
+ throw error;
149
+ }
150
+ else {
151
+ return null;
152
+ }
153
+ }
154
+ }
155
+ // ============ WRITE FILE ============
156
+ async function _writeFile(file, obj, options = {}) {
157
+ const fsModule = options.fs || _fs;
158
+ const str = (0, utils_1.stringify)(obj, options);
159
+ const writeOptions = { encoding: options.encoding || 'utf8' };
160
+ if (options.mode)
161
+ writeOptions.mode = options.mode;
162
+ if (options.flag)
163
+ writeOptions.flag = options.flag;
164
+ await new Promise((resolve, reject) => {
165
+ fsModule.writeFile(file, str, writeOptions, (err) => {
166
+ if (err)
167
+ reject(err);
168
+ else
169
+ resolve();
170
+ });
171
+ });
172
+ }
173
+ /**
174
+ * Stringify object and write to TOON file asynchronously
175
+ *
176
+ * @param file - Path to the TOON file
177
+ * @param obj - Object to stringify and write
178
+ * @param options - Write options
179
+ * @param callback - Optional callback function
180
+ * @returns Promise that resolves when file is written (if no callback provided)
181
+ *
182
+ * @example
183
+ * // With promise
184
+ * await writeFile('data.toon', { name: 'Alice', age: 30 })
185
+ *
186
+ * @example
187
+ * // With callback
188
+ * writeFile('data.toon', obj, (err) => {
189
+ * if (err) console.error(err)
190
+ * })
191
+ *
192
+ * @example
193
+ * // With options
194
+ * await writeFile('data.toon', obj, { indentSize: 4, delimiter: '|' })
195
+ */
196
+ exports.writeFile = universalify.fromPromise(_writeFile);
197
+ /**
198
+ * Stringify object and write to TOON file synchronously
199
+ *
200
+ * @param file - Path to the TOON file
201
+ * @param obj - Object to stringify and write
202
+ * @param options - Write options
203
+ *
204
+ * @example
205
+ * writeFileSync('data.toon', { name: 'Bob', age: 25 })
206
+ *
207
+ * @example
208
+ * writeFileSync('data.toon', obj, { indentSize: 4 })
209
+ */
210
+ function writeFileSync(file, obj, options = {}) {
211
+ const fsModule = options.fs || _fs;
212
+ const str = (0, utils_1.stringify)(obj, options);
213
+ fsModule.writeFileSync(file, str, options);
214
+ }
215
+ // ============ EXPORTS ============
216
+ // Re-export utility functions
217
+ var utils_2 = require("./utils");
218
+ Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return utils_2.parse; } });
219
+ Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return utils_2.stringify; } });
220
+ // NOTE: do not change this export format; required for ESM compat
221
+ // Default export for CommonJS compatibility
222
+ exports.default = {
223
+ readFile: exports.readFile,
224
+ readFileSync,
225
+ writeFile: exports.writeFile,
226
+ writeFileSync,
227
+ parse: utils_1.parse,
228
+ stringify: utils_1.stringify
229
+ };
230
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,oCAuBC;AA+DD,sCAKC;AAjMD,uCAAwB;AACxB,2DAA4C;AAC5C,mCAAoD;AAGpD,IAAI,GAAc,CAAA;AAClB,IAAI,CAAC;IACH,GAAG,GAAG,OAAO,CAAC,aAAa,CAAc,CAAA;AAC3C,CAAC;AAAC,OAAO,CAAC,EAAE,CAAC;IACX,GAAG,GAAG,EAAE,CAAA;AACV,CAAC;AAED,sCAAsC;AAEtC,KAAK,UAAU,SAAS,CAAE,IAAY,EAAE,UAAgC,EAAE;IACxE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,GAAG,EAAE,QAAQ,EAAE,OAAyB,EAAE,CAAA;IACnD,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,EAAE,I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