-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathfile-sink-jsonl.ts
More file actions
60 lines (53 loc) · 1.56 KB
/
file-sink-jsonl.ts
File metadata and controls
60 lines (53 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import * as fs from 'node:fs';
import {
type FileOutput,
FileSink,
type FileSinkOptions,
stringDecode,
stringEncode,
stringRecover,
} from './file-sink-text.js';
import type { RecoverOptions, RecoverResult } from './sink-source.types.js';
export const jsonlEncode = <
T extends Record<string, unknown> = Record<string, unknown>,
>(
input: T,
): FileOutput => JSON.stringify(input);
export const jsonlDecode = <
T extends Record<string, unknown> = Record<string, unknown>,
>(
output: FileOutput,
): T => JSON.parse(stringDecode(output)) as T;
export function recoverJsonlFile<
T extends Record<string, unknown> = Record<string, unknown>,
>(filePath: string, opts: RecoverOptions = {}): RecoverResult<T> {
return stringRecover(filePath, jsonlDecode<T>, opts);
}
export class JsonlFileSink<
T extends Record<string, unknown> = Record<string, unknown>,
> extends FileSink<T> {
constructor(options: FileSinkOptions) {
const { filePath, ...fileOptions } = options;
super({
...fileOptions,
filePath,
recover: () => recoverJsonlFile<T>(filePath),
finalize: () => {
// No additional finalization needed for JSONL files
},
});
}
override encode(input: T): FileOutput {
return stringEncode(jsonlEncode(input));
}
override decode(output: FileOutput): T {
return jsonlDecode(stringDecode(output));
}
override repack(outputPath?: string): void {
const { records } = this.recover();
fs.writeFileSync(
outputPath ?? this.getFilePath(),
records.map(this.encode).join(''),
);
}
}