index.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. import { WEBUI_BASE_URL } from '$lib/constants';
  4. //////////////////////////
  5. // Helper functions
  6. //////////////////////////
  7. export const sanitizeResponseContent = (content: string) => {
  8. // First, temporarily replace valid <video> tags with a placeholder
  9. const videoTagRegex = /<video\s+src="([^"]+)"\s+controls><\/video>/gi;
  10. const placeholders: string[] = [];
  11. content = content.replace(videoTagRegex, (_, src) => {
  12. const placeholder = `{{VIDEO_${placeholders.length}}}`;
  13. placeholders.push(`<video src="${src}" controls></video>`);
  14. return placeholder;
  15. });
  16. // Now apply the sanitization to the rest of the content
  17. content = content
  18. .replace(/<\|[a-z]*$/, '')
  19. .replace(/<\|[a-z]+\|$/, '')
  20. .replace(/<$/, '')
  21. .replaceAll(/<\|[a-z]+\|>/g, ' ')
  22. .replaceAll('<', '&lt;')
  23. .replaceAll('>', '&gt;')
  24. .trim();
  25. // Replace placeholders with original <video> tags
  26. placeholders.forEach((placeholder, index) => {
  27. content = content.replace(`{{VIDEO_${index}}}`, placeholder);
  28. });
  29. return content.trim();
  30. };
  31. export const replaceTokens = (content, char, user) => {
  32. const charToken = /{{char}}/gi;
  33. const userToken = /{{user}}/gi;
  34. const videoIdToken = /{{VIDEO_FILE_ID_([a-f0-9-]+)}}/gi; // Regex to capture the video ID
  35. const htmlIdToken = /{{HTML_FILE_ID_([a-f0-9-]+)}}/gi; // Regex to capture the HTML ID
  36. // Replace {{char}} if char is provided
  37. if (char !== undefined && char !== null) {
  38. content = content.replace(charToken, char);
  39. }
  40. // Replace {{user}} if user is provided
  41. if (user !== undefined && user !== null) {
  42. content = content.replace(userToken, user);
  43. }
  44. // Replace video ID tags with corresponding <video> elements
  45. content = content.replace(videoIdToken, (match, fileId) => {
  46. const videoUrl = `${WEBUI_BASE_URL}/api/v1/files/${fileId}/content`;
  47. return `<video src="${videoUrl}" controls></video>`;
  48. });
  49. // Replace HTML ID tags with corresponding HTML content
  50. content = content.replace(htmlIdToken, (match, fileId) => {
  51. const htmlUrl = `${WEBUI_BASE_URL}/api/v1/files/${fileId}/content`;
  52. return `<iframe src="${htmlUrl}" width="100%" frameborder="0" onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';"></iframe>`;
  53. });
  54. return content;
  55. };
  56. export const revertSanitizedResponseContent = (content: string) => {
  57. return content.replaceAll('&lt;', '<').replaceAll('&gt;', '>');
  58. };
  59. export const capitalizeFirstLetter = (string) => {
  60. return string.charAt(0).toUpperCase() + string.slice(1);
  61. };
  62. export const splitStream = (splitOn) => {
  63. let buffer = '';
  64. return new TransformStream({
  65. transform(chunk, controller) {
  66. buffer += chunk;
  67. const parts = buffer.split(splitOn);
  68. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  69. buffer = parts[parts.length - 1];
  70. },
  71. flush(controller) {
  72. if (buffer) controller.enqueue(buffer);
  73. }
  74. });
  75. };
  76. export const convertMessagesToHistory = (messages) => {
  77. const history = {
  78. messages: {},
  79. currentId: null
  80. };
  81. let parentMessageId = null;
  82. let messageId = null;
  83. for (const message of messages) {
  84. messageId = uuidv4();
  85. if (parentMessageId !== null) {
  86. history.messages[parentMessageId].childrenIds = [
  87. ...history.messages[parentMessageId].childrenIds,
  88. messageId
  89. ];
  90. }
  91. history.messages[messageId] = {
  92. ...message,
  93. id: messageId,
  94. parentId: parentMessageId,
  95. childrenIds: []
  96. };
  97. parentMessageId = messageId;
  98. }
  99. history.currentId = messageId;
  100. return history;
  101. };
  102. export const getGravatarURL = (email) => {
  103. // Trim leading and trailing whitespace from
  104. // an email address and force all characters
  105. // to lower case
  106. const address = String(email).trim().toLowerCase();
  107. // Create a SHA256 hash of the final string
  108. const hash = sha256(address);
  109. // Grab the actual image URL
  110. return `https://www.gravatar.com/avatar/${hash}`;
  111. };
  112. export const canvasPixelTest = () => {
  113. // Test a 1x1 pixel to potentially identify browser/plugin fingerprint blocking or spoofing
  114. // Inspiration: https://github.com/kkapsner/CanvasBlocker/blob/master/test/detectionTest.js
  115. const canvas = document.createElement('canvas');
  116. const ctx = canvas.getContext('2d');
  117. canvas.height = 1;
  118. canvas.width = 1;
  119. const imageData = new ImageData(canvas.width, canvas.height);
  120. const pixelValues = imageData.data;
  121. // Generate RGB test data
  122. for (let i = 0; i < imageData.data.length; i += 1) {
  123. if (i % 4 !== 3) {
  124. pixelValues[i] = Math.floor(256 * Math.random());
  125. } else {
  126. pixelValues[i] = 255;
  127. }
  128. }
  129. ctx.putImageData(imageData, 0, 0);
  130. const p = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  131. // Read RGB data and fail if unmatched
  132. for (let i = 0; i < p.length; i += 1) {
  133. if (p[i] !== pixelValues[i]) {
  134. console.log(
  135. 'canvasPixelTest: Wrong canvas pixel RGB value detected:',
  136. p[i],
  137. 'at:',
  138. i,
  139. 'expected:',
  140. pixelValues[i]
  141. );
  142. console.log('canvasPixelTest: Canvas blocking or spoofing is likely');
  143. return false;
  144. }
  145. }
  146. return true;
  147. };
  148. export const generateInitialsImage = (name) => {
  149. const canvas = document.createElement('canvas');
  150. const ctx = canvas.getContext('2d');
  151. canvas.width = 100;
  152. canvas.height = 100;
  153. if (!canvasPixelTest()) {
  154. console.log(
  155. 'generateInitialsImage: failed pixel test, fingerprint evasion is likely. Using default image.'
  156. );
  157. return '/user.png';
  158. }
  159. ctx.fillStyle = '#F39C12';
  160. ctx.fillRect(0, 0, canvas.width, canvas.height);
  161. ctx.fillStyle = '#FFFFFF';
  162. ctx.font = '40px Helvetica';
  163. ctx.textAlign = 'center';
  164. ctx.textBaseline = 'middle';
  165. const sanitizedName = name.trim();
  166. const initials =
  167. sanitizedName.length > 0
  168. ? sanitizedName[0] +
  169. (sanitizedName.split(' ').length > 1
  170. ? sanitizedName[sanitizedName.lastIndexOf(' ') + 1]
  171. : '')
  172. : '';
  173. ctx.fillText(initials.toUpperCase(), canvas.width / 2, canvas.height / 2);
  174. return canvas.toDataURL();
  175. };
  176. export const copyToClipboard = async (text) => {
  177. let result = false;
  178. if (!navigator.clipboard) {
  179. const textArea = document.createElement('textarea');
  180. textArea.value = text;
  181. // Avoid scrolling to bottom
  182. textArea.style.top = '0';
  183. textArea.style.left = '0';
  184. textArea.style.position = 'fixed';
  185. document.body.appendChild(textArea);
  186. textArea.focus();
  187. textArea.select();
  188. try {
  189. const successful = document.execCommand('copy');
  190. const msg = successful ? 'successful' : 'unsuccessful';
  191. console.log('Fallback: Copying text command was ' + msg);
  192. result = true;
  193. } catch (err) {
  194. console.error('Fallback: Oops, unable to copy', err);
  195. }
  196. document.body.removeChild(textArea);
  197. return result;
  198. }
  199. result = await navigator.clipboard
  200. .writeText(text)
  201. .then(() => {
  202. console.log('Async: Copying to clipboard was successful!');
  203. return true;
  204. })
  205. .catch((error) => {
  206. console.error('Async: Could not copy text: ', error);
  207. return false;
  208. });
  209. return result;
  210. };
  211. export const compareVersion = (latest, current) => {
  212. return current === '0.0.0'
  213. ? false
  214. : current.localeCompare(latest, undefined, {
  215. numeric: true,
  216. sensitivity: 'case',
  217. caseFirst: 'upper'
  218. }) < 0;
  219. };
  220. export const findWordIndices = (text) => {
  221. const regex = /\[([^\]]+)\]/g;
  222. const matches = [];
  223. let match;
  224. while ((match = regex.exec(text)) !== null) {
  225. matches.push({
  226. word: match[1],
  227. startIndex: match.index,
  228. endIndex: regex.lastIndex - 1
  229. });
  230. }
  231. return matches;
  232. };
  233. export const removeFirstHashWord = (inputString) => {
  234. // Split the string into an array of words
  235. const words = inputString.split(' ');
  236. // Find the index of the first word that starts with #
  237. const index = words.findIndex((word) => word.startsWith('#'));
  238. // Remove the first word with #
  239. if (index !== -1) {
  240. words.splice(index, 1);
  241. }
  242. // Join the remaining words back into a string
  243. const resultString = words.join(' ');
  244. return resultString;
  245. };
  246. export const transformFileName = (fileName) => {
  247. // Convert to lowercase
  248. const lowerCaseFileName = fileName.toLowerCase();
  249. // Remove special characters using regular expression
  250. const sanitizedFileName = lowerCaseFileName.replace(/[^\w\s]/g, '');
  251. // Replace spaces with dashes
  252. const finalFileName = sanitizedFileName.replace(/\s+/g, '-');
  253. return finalFileName;
  254. };
  255. export const calculateSHA256 = async (file) => {
  256. // Create a FileReader to read the file asynchronously
  257. const reader = new FileReader();
  258. // Define a promise to handle the file reading
  259. const readFile = new Promise((resolve, reject) => {
  260. reader.onload = () => resolve(reader.result);
  261. reader.onerror = reject;
  262. });
  263. // Read the file as an ArrayBuffer
  264. reader.readAsArrayBuffer(file);
  265. try {
  266. // Wait for the FileReader to finish reading the file
  267. const buffer = await readFile;
  268. // Convert the ArrayBuffer to a Uint8Array
  269. const uint8Array = new Uint8Array(buffer);
  270. // Calculate the SHA-256 hash using Web Crypto API
  271. const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
  272. // Convert the hash to a hexadecimal string
  273. const hashArray = Array.from(new Uint8Array(hashBuffer));
  274. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('');
  275. return `${hashHex}`;
  276. } catch (error) {
  277. console.error('Error calculating SHA-256 hash:', error);
  278. throw error;
  279. }
  280. };
  281. export const getImportOrigin = (_chats) => {
  282. // Check what external service chat imports are from
  283. if ('mapping' in _chats[0]) {
  284. return 'openai';
  285. }
  286. return 'webui';
  287. };
  288. export const getUserPosition = async (raw = false) => {
  289. // Get the user's location using the Geolocation API
  290. const position = await new Promise((resolve, reject) => {
  291. navigator.geolocation.getCurrentPosition(resolve, reject);
  292. }).catch((error) => {
  293. console.error('Error getting user location:', error);
  294. throw error;
  295. });
  296. if (!position) {
  297. return 'Location not available';
  298. }
  299. // Extract the latitude and longitude from the position
  300. const { latitude, longitude } = position.coords;
  301. if (raw) {
  302. return { latitude, longitude };
  303. } else {
  304. return `${latitude.toFixed(3)}, ${longitude.toFixed(3)} (lat, long)`;
  305. }
  306. };
  307. const convertOpenAIMessages = (convo) => {
  308. // Parse OpenAI chat messages and create chat dictionary for creating new chats
  309. const mapping = convo['mapping'];
  310. const messages = [];
  311. let currentId = '';
  312. let lastId = null;
  313. for (let message_id in mapping) {
  314. const message = mapping[message_id];
  315. currentId = message_id;
  316. try {
  317. if (
  318. messages.length == 0 &&
  319. (message['message'] == null ||
  320. (message['message']['content']['parts']?.[0] == '' &&
  321. message['message']['content']['text'] == null))
  322. ) {
  323. // Skip chat messages with no content
  324. continue;
  325. } else {
  326. const new_chat = {
  327. id: message_id,
  328. parentId: lastId,
  329. childrenIds: message['children'] || [],
  330. role: message['message']?.['author']?.['role'] !== 'user' ? 'assistant' : 'user',
  331. content:
  332. message['message']?.['content']?.['parts']?.[0] ||
  333. message['message']?.['content']?.['text'] ||
  334. '',
  335. model: 'gpt-3.5-turbo',
  336. done: true,
  337. context: null
  338. };
  339. messages.push(new_chat);
  340. lastId = currentId;
  341. }
  342. } catch (error) {
  343. console.log('Error with', message, '\nError:', error);
  344. }
  345. }
  346. let history = {};
  347. messages.forEach((obj) => (history[obj.id] = obj));
  348. const chat = {
  349. history: {
  350. currentId: currentId,
  351. messages: history // Need to convert this to not a list and instead a json object
  352. },
  353. models: ['gpt-3.5-turbo'],
  354. messages: messages,
  355. options: {},
  356. timestamp: convo['create_time'],
  357. title: convo['title'] ?? 'New Chat'
  358. };
  359. return chat;
  360. };
  361. const validateChat = (chat) => {
  362. // Because ChatGPT sometimes has features we can't use like DALL-E or migh have corrupted messages, need to validate
  363. const messages = chat.messages;
  364. // Check if messages array is empty
  365. if (messages.length === 0) {
  366. return false;
  367. }
  368. // Last message's children should be an empty array
  369. const lastMessage = messages[messages.length - 1];
  370. if (lastMessage.childrenIds.length !== 0) {
  371. return false;
  372. }
  373. // First message's parent should be null
  374. const firstMessage = messages[0];
  375. if (firstMessage.parentId !== null) {
  376. return false;
  377. }
  378. // Every message's content should be a string
  379. for (let message of messages) {
  380. if (typeof message.content !== 'string') {
  381. return false;
  382. }
  383. }
  384. return true;
  385. };
  386. export const convertOpenAIChats = (_chats) => {
  387. // Create a list of dictionaries with each conversation from import
  388. const chats = [];
  389. let failed = 0;
  390. for (let convo of _chats) {
  391. const chat = convertOpenAIMessages(convo);
  392. if (validateChat(chat)) {
  393. chats.push({
  394. id: convo['id'],
  395. user_id: '',
  396. title: convo['title'],
  397. chat: chat,
  398. timestamp: convo['timestamp']
  399. });
  400. } else {
  401. failed++;
  402. }
  403. }
  404. console.log(failed, 'Conversations could not be imported');
  405. return chats;
  406. };
  407. export const isValidHttpUrl = (string) => {
  408. let url;
  409. try {
  410. url = new URL(string);
  411. } catch (_) {
  412. return false;
  413. }
  414. return url.protocol === 'http:' || url.protocol === 'https:';
  415. };
  416. export const removeEmojis = (str) => {
  417. // Regular expression to match emojis
  418. const emojiRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  419. // Replace emojis with an empty string
  420. return str.replace(emojiRegex, '');
  421. };
  422. export const removeFormattings = (str) => {
  423. return str.replace(/(\*)(.*?)\1/g, '').replace(/(```)(.*?)\1/gs, '');
  424. };
  425. export const extractSentences = (text) => {
  426. // This regular expression matches code blocks marked by triple backticks
  427. const codeBlockRegex = /```[\s\S]*?```/g;
  428. let codeBlocks = [];
  429. let index = 0;
  430. // Temporarily replace code blocks with placeholders and store the blocks separately
  431. text = text.replace(codeBlockRegex, (match) => {
  432. let placeholder = `\u0000${index}\u0000`; // Use a unique placeholder
  433. codeBlocks[index++] = match;
  434. return placeholder;
  435. });
  436. // Split the modified text into sentences based on common punctuation marks, avoiding these blocks
  437. let sentences = text.split(/(?<=[.!?])\s+/);
  438. // Restore code blocks and process sentences
  439. sentences = sentences.map((sentence) => {
  440. // Check if the sentence includes a placeholder for a code block
  441. return sentence.replace(/\u0000(\d+)\u0000/g, (_, idx) => codeBlocks[idx]);
  442. });
  443. return sentences
  444. .map((sentence) => removeFormattings(removeEmojis(sentence.trim())))
  445. .filter((sentence) => sentence);
  446. };
  447. export const extractSentencesForAudio = (text) => {
  448. return extractSentences(text).reduce((mergedTexts, currentText) => {
  449. const lastIndex = mergedTexts.length - 1;
  450. if (lastIndex >= 0) {
  451. const previousText = mergedTexts[lastIndex];
  452. const wordCount = previousText.split(/\s+/).length;
  453. if (wordCount < 2) {
  454. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  455. } else {
  456. mergedTexts.push(currentText);
  457. }
  458. } else {
  459. mergedTexts.push(currentText);
  460. }
  461. return mergedTexts;
  462. }, []);
  463. };
  464. export const blobToFile = (blob, fileName) => {
  465. // Create a new File object from the Blob
  466. const file = new File([blob], fileName, { type: blob.type });
  467. return file;
  468. };
  469. /**
  470. * @param {string} template - The template string containing placeholders.
  471. * @returns {string} The template string with the placeholders replaced by the prompt.
  472. */
  473. export const promptTemplate = (
  474. template: string,
  475. user_name?: string,
  476. user_location?: string
  477. ): string => {
  478. // Get the current date
  479. const currentDate = new Date();
  480. // Format the date to YYYY-MM-DD
  481. const formattedDate =
  482. currentDate.getFullYear() +
  483. '-' +
  484. String(currentDate.getMonth() + 1).padStart(2, '0') +
  485. '-' +
  486. String(currentDate.getDate()).padStart(2, '0');
  487. // Format the time to HH:MM:SS AM/PM
  488. const currentTime = currentDate.toLocaleTimeString('en-US', {
  489. hour: 'numeric',
  490. minute: 'numeric',
  491. second: 'numeric',
  492. hour12: true
  493. });
  494. // Replace {{CURRENT_DATETIME}} in the template with the formatted datetime
  495. template = template.replace('{{CURRENT_DATETIME}}', `${formattedDate} ${currentTime}`);
  496. // Replace {{CURRENT_DATE}} in the template with the formatted date
  497. template = template.replace('{{CURRENT_DATE}}', formattedDate);
  498. // Replace {{CURRENT_TIME}} in the template with the formatted time
  499. template = template.replace('{{CURRENT_TIME}}', currentTime);
  500. if (user_name) {
  501. // Replace {{USER_NAME}} in the template with the user's name
  502. template = template.replace('{{USER_NAME}}', user_name);
  503. }
  504. if (user_location) {
  505. // Replace {{USER_LOCATION}} in the template with the current location
  506. template = template.replace('{{USER_LOCATION}}', user_location);
  507. }
  508. return template;
  509. };
  510. /**
  511. * This function is used to replace placeholders in a template string with the provided prompt.
  512. * The placeholders can be in the following formats:
  513. * - `{{prompt}}`: This will be replaced with the entire prompt.
  514. * - `{{prompt:start:<length>}}`: This will be replaced with the first <length> characters of the prompt.
  515. * - `{{prompt:end:<length>}}`: This will be replaced with the last <length> characters of the prompt.
  516. * - `{{prompt:middletruncate:<length>}}`: This will be replaced with the prompt truncated to <length> characters, with '...' in the middle.
  517. *
  518. * @param {string} template - The template string containing placeholders.
  519. * @param {string} prompt - The string to replace the placeholders with.
  520. * @returns {string} The template string with the placeholders replaced by the prompt.
  521. */
  522. export const titleGenerationTemplate = (template: string, prompt: string): string => {
  523. template = template.replace(
  524. /{{prompt}}|{{prompt:start:(\d+)}}|{{prompt:end:(\d+)}}|{{prompt:middletruncate:(\d+)}}/g,
  525. (match, startLength, endLength, middleLength) => {
  526. if (match === '{{prompt}}') {
  527. return prompt;
  528. } else if (match.startsWith('{{prompt:start:')) {
  529. return prompt.substring(0, startLength);
  530. } else if (match.startsWith('{{prompt:end:')) {
  531. return prompt.slice(-endLength);
  532. } else if (match.startsWith('{{prompt:middletruncate:')) {
  533. if (prompt.length <= middleLength) {
  534. return prompt;
  535. }
  536. const start = prompt.slice(0, Math.ceil(middleLength / 2));
  537. const end = prompt.slice(-Math.floor(middleLength / 2));
  538. return `${start}...${end}`;
  539. }
  540. return '';
  541. }
  542. );
  543. template = promptTemplate(template);
  544. return template;
  545. };
  546. export const approximateToHumanReadable = (nanoseconds: number) => {
  547. const seconds = Math.floor((nanoseconds / 1e9) % 60);
  548. const minutes = Math.floor((nanoseconds / 6e10) % 60);
  549. const hours = Math.floor((nanoseconds / 3.6e12) % 24);
  550. const results: string[] = [];
  551. if (seconds >= 0) {
  552. results.push(`${seconds}s`);
  553. }
  554. if (minutes > 0) {
  555. results.push(`${minutes}m`);
  556. }
  557. if (hours > 0) {
  558. results.push(`${hours}h`);
  559. }
  560. return results.reverse().join(' ');
  561. };
  562. export const getTimeRange = (timestamp) => {
  563. const now = new Date();
  564. const date = new Date(timestamp * 1000); // Convert Unix timestamp to milliseconds
  565. // Calculate the difference in milliseconds
  566. const diffTime = now.getTime() - date.getTime();
  567. const diffDays = diffTime / (1000 * 3600 * 24);
  568. const nowDate = now.getDate();
  569. const nowMonth = now.getMonth();
  570. const nowYear = now.getFullYear();
  571. const dateDate = date.getDate();
  572. const dateMonth = date.getMonth();
  573. const dateYear = date.getFullYear();
  574. if (nowYear === dateYear && nowMonth === dateMonth && nowDate === dateDate) {
  575. return 'Today';
  576. } else if (nowYear === dateYear && nowMonth === dateMonth && nowDate - dateDate === 1) {
  577. return 'Yesterday';
  578. } else if (diffDays <= 7) {
  579. return 'Previous 7 days';
  580. } else if (diffDays <= 30) {
  581. return 'Previous 30 days';
  582. } else if (nowYear === dateYear) {
  583. return date.toLocaleString('default', { month: 'long' });
  584. } else {
  585. return date.getFullYear().toString();
  586. }
  587. };
  588. /**
  589. * Extract frontmatter as a dictionary from the specified content string.
  590. * @param content {string} - The content string with potential frontmatter.
  591. * @returns {Object} - The extracted frontmatter as a dictionary.
  592. */
  593. export const extractFrontmatter = (content) => {
  594. const frontmatter = {};
  595. let frontmatterStarted = false;
  596. let frontmatterEnded = false;
  597. const frontmatterPattern = /^\s*([a-z_]+):\s*(.*)\s*$/i;
  598. // Split content into lines
  599. const lines = content.split('\n');
  600. // Check if the content starts with triple quotes
  601. if (lines[0].trim() !== '"""') {
  602. return {};
  603. }
  604. frontmatterStarted = true;
  605. for (let i = 1; i < lines.length; i++) {
  606. const line = lines[i];
  607. if (line.includes('"""')) {
  608. if (frontmatterStarted) {
  609. frontmatterEnded = true;
  610. break;
  611. }
  612. }
  613. if (frontmatterStarted && !frontmatterEnded) {
  614. const match = frontmatterPattern.exec(line);
  615. if (match) {
  616. const [, key, value] = match;
  617. frontmatter[key.trim()] = value.trim();
  618. }
  619. }
  620. }
  621. return frontmatter;
  622. };
  623. // Function to determine the best matching language
  624. export const bestMatchingLanguage = (supportedLanguages, preferredLanguages, defaultLocale) => {
  625. const languages = supportedLanguages.map((lang) => lang.code);
  626. const match = preferredLanguages
  627. .map((prefLang) => languages.find((lang) => lang.startsWith(prefLang)))
  628. .find(Boolean);
  629. console.log(languages, preferredLanguages, match, defaultLocale);
  630. return match || defaultLocale;
  631. };