Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { $createParagraphNode, $createTextNode, $getRoot, createEditor } from 'lexical';
import { describe, expect, it, vi } from 'vitest';
import { serializeDictionary } from '../serializecollapseddictionary';
import { convertSegmentsToString } from '../../../editor/base/utils/parsesegments';
import { convertKeyValueItemToSegments } from '../../../editor/base/utils/keyvalueitem';
import { ValueSegmentType } from '../../../editor/models/parameter';

const readItems = (text: string, valueType?: string) => {
const editor = createEditor({
onError: (e) => {
throw e;
},
});
editor.update(
() => {
const paragraph = $createParagraphNode();
paragraph.append($createTextNode(text));
$getRoot().clear().append(paragraph);
},
{ discrete: true }
);
const setItems = vi.fn();
const setIsValid = vi.fn();
serializeDictionary(editor, setItems, setIsValid, 'string', valueType);
return { setItems, setIsValid };
};

describe('serializeDictionary', () => {
it('keeps a quoted string value unescaped when the value type is any, so collapse -> expand -> collapse is stable', () => {
const literal = (value: string) => ({ id: 'v', type: ValueSegmentType.LITERAL, value });
const items = [{ id: '1', key: [literal('X-Say')], value: [literal('say "hello"')] }];

const collapsed = convertSegmentsToString(convertKeyValueItemToSegments(items, 'string', 'any'));
const { setItems, setIsValid } = readItems(collapsed, 'any');

expect(setIsValid).toHaveBeenCalledWith(true);
const expanded = setItems.mock.calls[0][0];
expect(convertSegmentsToString(expanded[0].value)).toBe('say "hello"');

const recollapsed = convertSegmentsToString(convertKeyValueItemToSegments(expanded, 'string', 'any'));
expect(recollapsed).toBe(collapsed);
});

it('still serializes non-string values with JSON.stringify when the value type is any', () => {
const { setItems } = readItems('{"a": 5, "b": {"c": 1}}', 'any');
const expanded = setItems.mock.calls[0][0];
expect(convertSegmentsToString(expanded[0].value)).toBe('5');
expect(convertSegmentsToString(expanded[1].value)).toBe('{"c":1}');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ export const serializeDictionary = (

for (const [key, value] of Object.entries(jsonEditor)) {
const newKey = keyType === constants.SWAGGER.TYPE.STRING ? (key as string) : removeQuotes(JSON.stringify(key));
const newValue = valueType === constants.SWAGGER.TYPE.STRING ? (value as string) : removeQuotes(JSON.stringify(value));
// A string value is already decoded by JSON.parse; stringifying it again would leave literal backslashes before escaped characters.
const newValue =
valueType === constants.SWAGGER.TYPE.STRING || typeof value === 'string'
? (value as string)
: removeQuotes(JSON.stringify(value));
returnItems.push({
id: guid(),
key: convertStringToSegments(newKey, nodeMap, { tokensEnabled: true }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,39 @@ describe('keyvalueitem utilities', () => {
expect(result).toMatch(/"DATE"\s*:\s*"/);
});

it('should escape double quotes in a string value so a JSON value yields valid JSON', () => {
const items = [
{
id: '1',
key: [{ id: 'k1', type: ValueSegmentType.LITERAL, value: 'X-Payload' }],
value: [{ id: 'v1', type: ValueSegmentType.LITERAL, value: '{"a":1,"b":"two"}' }],
},
];

const segments = convertKeyValueItemToSegments(items, 'string', 'string');
const result = convertSegmentsToString(segments);

expect(JSON.parse(result)).toEqual({ 'X-Payload': '{"a":1,"b":"two"}' });
});

it('should leave token segment values untouched when escaping a string value', () => {
const items = [
{
id: '1',
key: [{ id: 'k1', type: ValueSegmentType.LITERAL, value: 'X-Id' }],
value: [
{ id: 'v1', type: ValueSegmentType.LITERAL, value: 'id-"' },
{ id: 'v2', type: ValueSegmentType.TOKEN, value: 'concat("a")' },
],
},
];

const segments = convertKeyValueItemToSegments(items, 'string', 'string');

expect(segments.find((s) => s.id === 'v1')?.value).toBe('id-\\"');
expect(segments.find((s) => s.id === 'v2')?.value).toBe('concat("a")');
});

it('should handle empty items', () => {
const items: {
id: string;
Expand Down
10 changes: 9 additions & 1 deletion libs/designer-ui/src/lib/editor/base/utils/keyvalueitem.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import constants from '../../../constants';
import { isEmpty } from '../../../dictionary/expandeddictionary';
import type { ValueSegment } from '../../models/parameter';
import { ValueSegmentType } from '../../models/parameter';
import { containsTokenSegments, createLiteralValueSegment, insertQutationForStringType } from './helper';
import { convertSegmentsToString } from './parsesegments';
import { escapeBackslash } from '@microsoft/logic-apps-shared';
Expand Down Expand Up @@ -41,7 +42,7 @@ export const convertKeyValueItemToSegments = (items: KeyValueItem[], keyType?: s
convertedValueType !== constants.SWAGGER.TYPE.STRING
? segment.value
: typeof segment.value === 'string'
? escapeBackslash(segment.value)
? escapeStringValue(segment.value, segment.type)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch on the any path: expanding a collapsed say "hello" did leave the backslashes in. 03a2e8f makes serializecollapseddictionary.ts use the decoded string whenever JSON.parse returns a string, and serializecollapseddictionary.spec.ts now has the collapse → expand → collapse round trip with valueType: 'any'. That test fails without the change. The 11 dictionary tests pass here. I haven't run the full designer-ui suite or tried it in a browser. The red validate-pr check looks like it is only waiting for a maintainer to add the external-approved label.

: JSON.stringify(segment.value),
};
});
Expand All @@ -60,6 +61,13 @@ export const convertKeyValueItemToSegments = (items: KeyValueItem[], keyType?: s
return parsedItems;
};

// Literal text that ends up inside a JSON string must also have its double quotes escaped,
// otherwise a value such as {"a":1} produces invalid JSON in the collapsed editor.
const escapeStringValue = (value: string, type: string): string => {
const escaped = escapeBackslash(value);
return type === ValueSegmentType.LITERAL ? escaped.replace(/"/g, '\\"') : escaped;
};

// we want to default to string type when the value is type any
export const convertValueType = (value: ValueSegment[], type?: string): string | undefined => {
if (type && type !== constants.SWAGGER.TYPE.ANY) {
Expand Down
Loading