fix: bech32 duplication bug in parseTextNote

This commit is contained in:
Shusui MOYATANI
2023-05-05 17:13:19 +09:00
parent acb862a5a5
commit 18e9ddd16a
2 changed files with 24 additions and 8 deletions

View File

@@ -173,6 +173,16 @@ describe('parseTextNote', () => {
assert.deepStrictEqual(parsed, expected); assert.deepStrictEqual(parsed, expected);
}); });
it('should parse text note which includes invalid npub string', () => {
const parsed = parseTextNote('this is pubkey\nnpub1srf6g8\nhello');
const expected: ParsedTextNoteNode[] = [
{ type: 'PlainText', content: 'this is pubkey\nnpub1srf6g8\nhello' },
];
assert.deepStrictEqual(parsed, expected);
});
}); });
describe('resolveTagReference', () => { describe('resolveTagReference', () => {

View File

@@ -78,10 +78,19 @@ const parseTextNote = (textNoteContent: string) => {
const result: ParsedTextNote = []; const result: ParsedTextNote = [];
const pushPlainText = (index: number | undefined) => { const pushPlainText = (index: number | undefined) => {
if (index != null && pos !== index) { if (index != null && index > pos) {
const content = textNoteContent.slice(pos, index); const content = textNoteContent.slice(pos, index);
const plainText: PlainText = { type: 'PlainText', content };
result.push(plainText); // combine plaintext node when failed to decode (e.g. bech32)
const lastNode = result[result.length - 1];
if (lastNode?.type === 'PlainText') {
lastNode.content += content;
} else {
const plainText: PlainText = { type: 'PlainText', content };
result.push(plainText);
}
pos = index;
} }
}; };
@@ -118,7 +127,6 @@ const parseTextNote = (textNoteContent: string) => {
} catch (e) { } catch (e) {
console.warn(`failed to parse Bech32 entity (NIP-19): ${match[0]}`); console.warn(`failed to parse Bech32 entity (NIP-19): ${match[0]}`);
pushPlainText(index + match[0].length); pushPlainText(index + match[0].length);
return;
} }
} else if (match.groups?.hashtag) { } else if (match.groups?.hashtag) {
pushPlainText(index); pushPlainText(index);
@@ -133,10 +141,8 @@ const parseTextNote = (textNoteContent: string) => {
pos = index + match[0].length; pos = index + match[0].length;
}); });
if (pos !== textNoteContent.length) { if (pos < textNoteContent.length) {
const content = textNoteContent.slice(pos); pushPlainText(textNoteContent.length);
const plainText: PlainText = { type: 'PlainText', content };
result.push(plainText);
} }
return result; return result;