File size: 1,431 Bytes
9705b6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const citationRegex = /\[\^\d+?\^\]/g;
const regex = / \[.*?]\(.*?\)/g;

const getCitations = (res) => {
  const adaptiveCards = res.details.adaptiveCards;
  const textBlocks = adaptiveCards && adaptiveCards[0].body;
  if (!textBlocks) {
    return '';
  }
  let links = textBlocks[textBlocks.length - 1]?.text.match(regex);
  if (links?.length === 0 || !links) {
    return '';
  }
  links = links.map((link) => link.trim());
  return links.join('\n - ');
};

const citeText = (res, noLinks = false) => {
  let result = res.text || res;
  const citations = Array.from(new Set(result.match(citationRegex)));
  if (citations?.length === 0) {
    return result;
  }

  if (noLinks) {
    citations.forEach((citation) => {
      const digit = citation.match(/\d+?/g)[0];
      // result = result.replaceAll(citation, `<sup>[${digit}](#)  </sup>`);
      result = result.replaceAll(citation, `[^${digit}^](#)`);
    });

    return result;
  }

  let sources = res.details.sourceAttributions;
  if (sources?.length === 0) {
    return result;
  }
  sources = sources.map((source) => source.seeMoreUrl);

  citations.forEach((citation) => {
    const digit = citation.match(/\d+?/g)[0];
    result = result.replaceAll(citation, `[^${digit}^](${sources[digit - 1]})`);
    // result = result.replaceAll(citation, `<sup>[${digit}](${sources[digit - 1]})  </sup>`);
  });

  return result;
};

module.exports = { getCitations, citeText };