Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep code span parsing linear in body length

Yudhi Armyndhariscd614dc5ba7b
diff --git a/dashboard/src/utils/messageFormatter.test.ts b/dashboard/src/utils/messageFormatter.test.ts
index ff7639c34..dca94f7e5 100644
--- a/dashboard/src/utils/messageFormatter.test.ts
+++ b/dashboard/src/utils/messageFormatter.test.ts
@@ -118,6 +118,26 @@ test('hostile input: openers with no closer do not rescan the rest of the messag
assert.deepEqual(parseMessageBody('_a *b* _a'), [text('_a '), { type: 'bold', children: [text('b')] }, text(' _a')]);
});
+test('hostile input: code spans with no triple backtick after them do not rescan the message each time', () => {
+ // Each span used to look for a ``` to the end of the body before the next one, which is absent:
+ // several seconds of main thread for one 64k message.
+ for (const evil of ['`a` '.repeat(16_000), '`` '.repeat(21_000)]) {
+ const started = performance.now();
+ const nodes = parseMessageBody(evil);
+ const elapsed = performance.now() - started;
+ assert.ok(elapsed < 1000, `parsing ${evil.length} chars took ${Math.round(elapsed)} ms`);
+ assert.ok(nodes.length > 0);
+ }
+ // A triple backtick further on is still found once the spans in front of it are consumed.
+ assert.deepEqual(parseMessageBody('`a` b ```c``` `d`'), [
+ { type: 'code', value: 'a' },
+ text(' b '),
+ { type: 'codeblock', value: 'c' },
+ text(' '),
+ { type: 'code', value: 'd' },
+ ]);
+});
+
test('a MENTION_OPEN/MENTION_CLOSE span becomes its own mention node, not text', () => {
assert.deepEqual(parseMessageBody(`hi ${wrap('@Ravi')} there`), [
text('hi '),
diff --git a/dashboard/src/utils/messageFormatter.ts b/dashboard/src/utils/messageFormatter.ts
index 0fca37a1f..677e166e7 100644
--- a/dashboard/src/utils/messageFormatter.ts
+++ b/dashboard/src/utils/messageFormatter.ts
@@ -66,9 +66,12 @@ export function parseMessageBody(input: string): MessageNode[] {
cursor = end;
};
+ // The next triple backtick is searched for again only once the cursor has passed it: looking from
+ // the cursor on every turn scans the whole remainder each time when none follows.
+ let tripleStart = input.indexOf('```');
while (cursor < input.length) {
// Look for next ``` first (longer marker wins).
- const tripleStart = input.indexOf('```', cursor);
+ if (tripleStart !== -1 && tripleStart < cursor) tripleStart = input.indexOf('```', cursor);
const singleStart = findSingleBacktick(input, cursor);
let nextCode: 'triple' | 'single' | null = null;