Skip to content

Commit

Permalink
fix(whitespace): maintain trailing whitespace after json payload in r…
Browse files Browse the repository at this point in the history
…esult
  • Loading branch information
grantila committed Apr 26, 2022
1 parent e4fc53b commit cb9fcfc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
6 changes: 5 additions & 1 deletion lib/document/document.ts
Expand Up @@ -21,6 +21,7 @@ export class JsonDocument
private json: string,
public root: JsonNodeType,
private rootIndentation: Indentable,
private trailingIndentation: string,
options?: Partial< JsonDocumentOptions >
)
{
Expand Down Expand Up @@ -135,7 +136,9 @@ export class JsonDocument
throw new Error( `Unexpected node type` );
};

return rootIndent + stringify( this.root, rootIndent );
return rootIndent
+ stringify( this.root, rootIndent )
+ this.trailingIndentation;
}

toJSON( ): string
Expand Down Expand Up @@ -177,6 +180,7 @@ export function parseJson( json: string, options?: JsonDocumentOptions )
json,
parsed.root,
parsed.initialIndentation,
parsed.trailingWhitespace,
{
whitespace: 'auto',
...options,
Expand Down
13 changes: 10 additions & 3 deletions lib/document/parse-to-nodes.ts
Expand Up @@ -20,22 +20,29 @@ import { JsonValueBase } from './types-internal.js'
export interface ParseResult
{
initialIndentation: Indentable;
trailingWhitespace: string;
root: JsonNodeType;
}

export function parse( json: string ): ParseResult
{
const tokens = lexer( json );
const tokens = lexer( json ) as LexerTokens;

const { whitespace: initialWhitespace, consumedTokens: pos } =
extractWhitespace( tokens, 0 );

const initialIndentation = initialWhitespace.indentable;
const root = makeJsonAny( tokens, pos ).value;
const { value: root, consumedTokens } = makeJsonAny( tokens, pos );

const trailingPos = pos + consumedTokens;
const trailingWhitespace =
tokens[ trailingPos ]?.type === 'whitespace'
? tokens[ trailingPos ]!.raw
: '';

makeRelativeIndentations( root );

return { initialIndentation, root };
return { initialIndentation, trailingWhitespace, root };
}

function makeRelativeIndentations( node: JsonNodeType )
Expand Down
10 changes: 10 additions & 0 deletions lib/rfc6902.test.ts
Expand Up @@ -4,6 +4,16 @@ import type { Operation } from './types-rfc6902.js'

describe( 'rfc6902', ( ) =>
{
it( 'maintains trailing whitespace', ( ) =>
{
const before = `{\n "foo": "bar"\n}\n\n\t \n`;
const after = `{\n "foo": "bar"\n}\n\n\t \n`;

const res = jsonPatch( before, [ ] );

expect( res ).toBe( after );
} );

describe( 'add', ( ) =>
{
it( 'object add ordered (after)', ( ) =>
Expand Down

0 comments on commit cb9fcfc

Please sign in to comment.