Skip to content

Commit 7886c57

Browse files
committed
fix(utils): ignore non-json lines in fromJsonLines utility
1 parent 703c27e commit 7886c57

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

packages/utils/src/lib/transform.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,19 @@ export function toUnixNewlines(text: string): string {
114114
return platform() === 'win32' ? text.replace(/\r\n/g, '\n') : text;
115115
}
116116

117-
export function fromJsonLines<T = unknown>(jsonLines: string) {
117+
export function fromJsonLines<T extends unknown[]>(jsonLines: string) {
118118
const unifiedNewLines = toUnixNewlines(jsonLines).trim();
119-
return JSON.parse(`[${unifiedNewLines.split('\n').join(',')}]`) as T;
119+
const invalid = Symbol('invalid json');
120+
return unifiedNewLines
121+
.split('\n')
122+
.map(line => {
123+
try {
124+
return JSON.parse(line);
125+
} catch {
126+
return invalid;
127+
}
128+
})
129+
.filter(line => line !== invalid) as T;
120130
}
121131

122132
export function toJsonLines<T>(json: T[]) {

packages/utils/src/lib/transform.unit.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,17 @@ describe('JSON lines format', () => {
258258

259259
expect(fromJsonLines(jsonLines)).toEqual([head, body]);
260260
});
261+
262+
it('should ignore non-JSON lines', () => {
263+
const jsonLines = [
264+
'(node:346640) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.',
265+
'(Use `node --trace-deprecation ...` to show where the warning was created)',
266+
JSON.stringify(head),
267+
JSON.stringify(body),
268+
].join('\n');
269+
270+
expect(fromJsonLines(jsonLines)).toEqual([head, body]);
271+
});
261272
});
262273

263274
describe('toJsonLines', () => {

0 commit comments

Comments
 (0)