index.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. import { WEBUI_BASE_URL } from '$lib/constants';
  4. import dayjs from 'dayjs';
  5. import relativeTime from 'dayjs/plugin/relativeTime';
  6. import isToday from 'dayjs/plugin/isToday';
  7. import isYesterday from 'dayjs/plugin/isYesterday';
  8. import localizedFormat from 'dayjs/plugin/localizedFormat';
  9. dayjs.extend(relativeTime);
  10. dayjs.extend(isToday);
  11. dayjs.extend(isYesterday);
  12. dayjs.extend(localizedFormat);
  13. import { TTS_RESPONSE_SPLIT } from '$lib/types';
  14. import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.mjs?url';
  15. import { marked } from 'marked';
  16. import markedExtension from '$lib/utils/marked/extension';
  17. import markedKatexExtension from '$lib/utils/marked/katex-extension';
  18. import hljs from 'highlight.js';
  19. //////////////////////////
  20. // Helper functions
  21. //////////////////////////
  22. export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
  23. function escapeRegExp(string: string): string {
  24. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  25. }
  26. export const replaceTokens = (content, sourceIds, char, user) => {
  27. const tokens = [
  28. { regex: /{{char}}/gi, replacement: char },
  29. { regex: /{{user}}/gi, replacement: user },
  30. {
  31. regex: /{{VIDEO_FILE_ID_([a-f0-9-]+)}}/gi,
  32. replacement: (_, fileId) =>
  33. `<video src="${WEBUI_BASE_URL}/api/v1/files/${fileId}/content" controls></video>`
  34. },
  35. {
  36. regex: /{{HTML_FILE_ID_([a-f0-9-]+)}}/gi,
  37. replacement: (_, fileId) => `<file type="html" id="${fileId}" />`
  38. }
  39. ];
  40. // Replace tokens outside code blocks only
  41. const processOutsideCodeBlocks = (text, replacementFn) => {
  42. return text
  43. .split(/(```[\s\S]*?```|`[\s\S]*?`)/)
  44. .map((segment) => {
  45. return segment.startsWith('```') || segment.startsWith('`')
  46. ? segment
  47. : replacementFn(segment);
  48. })
  49. .join('');
  50. };
  51. // Apply replacements
  52. content = processOutsideCodeBlocks(content, (segment) => {
  53. tokens.forEach(({ regex, replacement }) => {
  54. if (replacement !== undefined && replacement !== null) {
  55. segment = segment.replace(regex, replacement);
  56. }
  57. });
  58. if (Array.isArray(sourceIds)) {
  59. sourceIds.forEach((sourceId, idx) => {
  60. const regex = new RegExp(`\\[${idx + 1}\\]`, 'g');
  61. segment = segment.replace(regex, `<source_id data="${idx + 1}" title="${sourceId}" />`);
  62. });
  63. }
  64. return segment;
  65. });
  66. return content;
  67. };
  68. export const sanitizeResponseContent = (content: string) => {
  69. return content
  70. .replace(/<\|[a-z]*$/, '')
  71. .replace(/<\|[a-z]+\|$/, '')
  72. .replace(/<$/, '')
  73. .replaceAll('<', '&lt;')
  74. .replaceAll('>', '&gt;')
  75. .replaceAll(/<\|[a-z]+\|>/g, ' ')
  76. .trim();
  77. };
  78. export const processResponseContent = (content: string) => {
  79. content = processChineseContent(content);
  80. return content.trim();
  81. };
  82. function isChineseChar(char: string): boolean {
  83. return /\p{Script=Han}/u.test(char);
  84. }
  85. // Tackle "Model output issue not following the standard Markdown/LaTeX format" in Chinese.
  86. function processChineseContent(content: string): string {
  87. // This function is used to process the response content before the response content is rendered.
  88. const lines = content.split('\n');
  89. const processedLines = lines.map((line) => {
  90. if (/[\u4e00-\u9fa5]/.test(line)) {
  91. // Problems caused by Chinese parentheses
  92. /* Discription:
  93. * When `*` has Chinese delimiters on the inside, markdown parser ignore bold or italic style.
  94. * - e.g. `**中文名(English)**中文内容` will be parsed directly,
  95. * instead of `<strong>中文名(English)</strong>中文内容`.
  96. * Solution:
  97. * Adding a `space` before and after the bold/italic part can solve the problem.
  98. * - e.g. `**中文名(English)**中文内容` -> ` **中文名(English)** 中文内容`
  99. * Note:
  100. * Similar problem was found with English parentheses and other full delimiters,
  101. * but they are not handled here because they are less likely to appear in LLM output.
  102. * Change the behavior in future if needed.
  103. */
  104. if (line.includes('*')) {
  105. // Handle **bold** and *italic*
  106. // 1. With Chinese parentheses
  107. if (/(|)/.test(line)) {
  108. line = processChineseDelimiters(line, '**', '(', ')');
  109. line = processChineseDelimiters(line, '*', '(', ')');
  110. }
  111. // 2. With Chinese quotations
  112. if (/“|”/.test(line)) {
  113. line = processChineseDelimiters(line, '**', '“', '”');
  114. line = processChineseDelimiters(line, '*', '“', '”');
  115. }
  116. }
  117. }
  118. return line;
  119. });
  120. content = processedLines.join('\n');
  121. return content;
  122. }
  123. // Helper function for `processChineseContent`
  124. function processChineseDelimiters(
  125. line: string,
  126. symbol: string,
  127. leftSymbol: string,
  128. rightSymbol: string
  129. ): string {
  130. // NOTE: If needed, with a little modification, this function can be applied to more cases.
  131. const escapedSymbol = escapeRegExp(symbol);
  132. const regex = new RegExp(
  133. `(.?)(?<!${escapedSymbol})(${escapedSymbol})([^${escapedSymbol}]+)(${escapedSymbol})(?!${escapedSymbol})(.)`,
  134. 'g'
  135. );
  136. return line.replace(regex, (match, l, left, content, right, r) => {
  137. const result =
  138. (content.startsWith(leftSymbol) && l && l.length > 0 && isChineseChar(l[l.length - 1])) ||
  139. (content.endsWith(rightSymbol) && r && r.length > 0 && isChineseChar(r[0]));
  140. if (result) {
  141. return `${l} ${left}${content}${right} ${r}`;
  142. } else {
  143. return match;
  144. }
  145. });
  146. }
  147. export function unescapeHtml(html: string) {
  148. const doc = new DOMParser().parseFromString(html, 'text/html');
  149. return doc.documentElement.textContent;
  150. }
  151. export const capitalizeFirstLetter = (string) => {
  152. return string.charAt(0).toUpperCase() + string.slice(1);
  153. };
  154. export const splitStream = (splitOn) => {
  155. let buffer = '';
  156. return new TransformStream({
  157. transform(chunk, controller) {
  158. buffer += chunk;
  159. const parts = buffer.split(splitOn);
  160. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  161. buffer = parts[parts.length - 1];
  162. },
  163. flush(controller) {
  164. if (buffer) controller.enqueue(buffer);
  165. }
  166. });
  167. };
  168. export const convertMessagesToHistory = (messages) => {
  169. const history = {
  170. messages: {},
  171. currentId: null
  172. };
  173. let parentMessageId = null;
  174. let messageId = null;
  175. for (const message of messages) {
  176. messageId = uuidv4();
  177. if (parentMessageId !== null) {
  178. history.messages[parentMessageId].childrenIds = [
  179. ...history.messages[parentMessageId].childrenIds,
  180. messageId
  181. ];
  182. }
  183. history.messages[messageId] = {
  184. ...message,
  185. id: messageId,
  186. parentId: parentMessageId,
  187. childrenIds: []
  188. };
  189. parentMessageId = messageId;
  190. }
  191. history.currentId = messageId;
  192. return history;
  193. };
  194. export const getGravatarURL = (email) => {
  195. // Trim leading and trailing whitespace from
  196. // an email address and force all characters
  197. // to lower case
  198. const address = String(email).trim().toLowerCase();
  199. // Create a SHA256 hash of the final string
  200. const hash = sha256(address);
  201. // Grab the actual image URL
  202. return `https://www.gravatar.com/avatar/${hash}`;
  203. };
  204. export const canvasPixelTest = () => {
  205. // Test a 1x1 pixel to potentially identify browser/plugin fingerprint blocking or spoofing
  206. // Inspiration: https://github.com/kkapsner/CanvasBlocker/blob/master/test/detectionTest.js
  207. const canvas = document.createElement('canvas');
  208. const ctx = canvas.getContext('2d');
  209. canvas.height = 1;
  210. canvas.width = 1;
  211. const imageData = new ImageData(canvas.width, canvas.height);
  212. const pixelValues = imageData.data;
  213. // Generate RGB test data
  214. for (let i = 0; i < imageData.data.length; i += 1) {
  215. if (i % 4 !== 3) {
  216. pixelValues[i] = Math.floor(256 * Math.random());
  217. } else {
  218. pixelValues[i] = 255;
  219. }
  220. }
  221. ctx.putImageData(imageData, 0, 0);
  222. const p = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  223. // Read RGB data and fail if unmatched
  224. for (let i = 0; i < p.length; i += 1) {
  225. if (p[i] !== pixelValues[i]) {
  226. console.log(
  227. 'canvasPixelTest: Wrong canvas pixel RGB value detected:',
  228. p[i],
  229. 'at:',
  230. i,
  231. 'expected:',
  232. pixelValues[i]
  233. );
  234. console.log('canvasPixelTest: Canvas blocking or spoofing is likely');
  235. return false;
  236. }
  237. }
  238. return true;
  239. };
  240. export const compressImage = async (imageUrl, maxWidth, maxHeight) => {
  241. return new Promise((resolve, reject) => {
  242. const img = new Image();
  243. img.onload = () => {
  244. const canvas = document.createElement('canvas');
  245. let width = img.width;
  246. let height = img.height;
  247. // Maintain aspect ratio while resizing
  248. if (maxWidth && maxHeight) {
  249. // Resize with both dimensions defined (preserves aspect ratio)
  250. if (width <= maxWidth && height <= maxHeight) {
  251. resolve(imageUrl);
  252. return;
  253. }
  254. if (width / height > maxWidth / maxHeight) {
  255. height = Math.round((maxWidth * height) / width);
  256. width = maxWidth;
  257. } else {
  258. width = Math.round((maxHeight * width) / height);
  259. height = maxHeight;
  260. }
  261. } else if (maxWidth) {
  262. // Only maxWidth defined
  263. if (width <= maxWidth) {
  264. resolve(imageUrl);
  265. return;
  266. }
  267. height = Math.round((maxWidth * height) / width);
  268. width = maxWidth;
  269. } else if (maxHeight) {
  270. // Only maxHeight defined
  271. if (height <= maxHeight) {
  272. resolve(imageUrl);
  273. return;
  274. }
  275. width = Math.round((maxHeight * width) / height);
  276. height = maxHeight;
  277. }
  278. canvas.width = width;
  279. canvas.height = height;
  280. const context = canvas.getContext('2d');
  281. context.drawImage(img, 0, 0, width, height);
  282. // Get compressed image URL
  283. const compressedUrl = canvas.toDataURL();
  284. resolve(compressedUrl);
  285. };
  286. img.onerror = (error) => reject(error);
  287. img.src = imageUrl;
  288. });
  289. };
  290. export const generateInitialsImage = (name) => {
  291. const canvas = document.createElement('canvas');
  292. const ctx = canvas.getContext('2d');
  293. canvas.width = 100;
  294. canvas.height = 100;
  295. if (!canvasPixelTest()) {
  296. console.log(
  297. 'generateInitialsImage: failed pixel test, fingerprint evasion is likely. Using default image.'
  298. );
  299. return `${WEBUI_BASE_URL}/user.png`;
  300. }
  301. ctx.fillStyle = '#F39C12';
  302. ctx.fillRect(0, 0, canvas.width, canvas.height);
  303. ctx.fillStyle = '#FFFFFF';
  304. ctx.font = '40px Helvetica';
  305. ctx.textAlign = 'center';
  306. ctx.textBaseline = 'middle';
  307. const sanitizedName = name.trim();
  308. const initials =
  309. sanitizedName.length > 0
  310. ? sanitizedName[0] +
  311. (sanitizedName.split(' ').length > 1
  312. ? sanitizedName[sanitizedName.lastIndexOf(' ') + 1]
  313. : '')
  314. : '';
  315. ctx.fillText(initials.toUpperCase(), canvas.width / 2, canvas.height / 2);
  316. return canvas.toDataURL();
  317. };
  318. export const formatDate = (inputDate) => {
  319. const date = dayjs(inputDate);
  320. const now = dayjs();
  321. if (date.isToday()) {
  322. return `Today at ${date.format('LT')}`;
  323. } else if (date.isYesterday()) {
  324. return `Yesterday at ${date.format('LT')}`;
  325. } else {
  326. return `${date.format('L')} at ${date.format('LT')}`;
  327. }
  328. };
  329. export const copyToClipboard = async (text, html = null, formatted = false) => {
  330. if (formatted) {
  331. let styledHtml = '';
  332. if (!html) {
  333. const options = {
  334. throwOnError: false,
  335. highlight: function (code, lang) {
  336. const language = hljs.getLanguage(lang) ? lang : 'plaintext';
  337. return hljs.highlight(code, { language }).value;
  338. }
  339. };
  340. marked.use(markedKatexExtension(options));
  341. marked.use(markedExtension(options));
  342. // DEVELOPER NOTE: Go to `$lib/components/chat/Messages/Markdown.svelte` to add extra markdown extensions for rendering.
  343. const htmlContent = marked.parse(text);
  344. // Add basic styling to make the content look better when pasted
  345. styledHtml = `
  346. <div>
  347. <style>
  348. pre {
  349. background-color: #f6f8fa;
  350. border-radius: 6px;
  351. padding: 16px;
  352. overflow: auto;
  353. }
  354. code {
  355. font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  356. font-size: 14px;
  357. }
  358. .hljs-keyword { color: #d73a49; }
  359. .hljs-string { color: #032f62; }
  360. .hljs-comment { color: #6a737d; }
  361. .hljs-function { color: #6f42c1; }
  362. .hljs-number { color: #005cc5; }
  363. .hljs-operator { color: #d73a49; }
  364. .hljs-class { color: #6f42c1; }
  365. .hljs-title { color: #6f42c1; }
  366. .hljs-params { color: #24292e; }
  367. .hljs-built_in { color: #005cc5; }
  368. blockquote {
  369. border-left: 4px solid #dfe2e5;
  370. padding-left: 16px;
  371. color: #6a737d;
  372. margin-left: 0;
  373. margin-right: 0;
  374. }
  375. table {
  376. border-collapse: collapse;
  377. width: 100%;
  378. margin-bottom: 16px;
  379. }
  380. table, th, td {
  381. border: 1px solid #dfe2e5;
  382. }
  383. th, td {
  384. padding: 8px 12px;
  385. }
  386. th {
  387. background-color: #f6f8fa;
  388. }
  389. </style>
  390. ${htmlContent}
  391. </div>
  392. `;
  393. } else {
  394. // If HTML is provided, use it directly
  395. styledHtml = html;
  396. }
  397. // Create a blob with HTML content
  398. const blob = new Blob([styledHtml], { type: 'text/html' });
  399. try {
  400. // Create a ClipboardItem with HTML content
  401. const data = new ClipboardItem({
  402. 'text/html': blob,
  403. 'text/plain': new Blob([text], { type: 'text/plain' })
  404. });
  405. // Write to clipboard
  406. await navigator.clipboard.write([data]);
  407. return true;
  408. } catch (err) {
  409. console.error('Error copying formatted content:', err);
  410. // Fallback to plain text
  411. return await copyToClipboard(text);
  412. }
  413. } else {
  414. let result = false;
  415. if (!navigator.clipboard) {
  416. const textArea = document.createElement('textarea');
  417. textArea.value = text;
  418. // Avoid scrolling to bottom
  419. textArea.style.top = '0';
  420. textArea.style.left = '0';
  421. textArea.style.position = 'fixed';
  422. document.body.appendChild(textArea);
  423. textArea.focus();
  424. textArea.select();
  425. try {
  426. const successful = document.execCommand('copy');
  427. const msg = successful ? 'successful' : 'unsuccessful';
  428. console.log('Fallback: Copying text command was ' + msg);
  429. result = true;
  430. } catch (err) {
  431. console.error('Fallback: Oops, unable to copy', err);
  432. }
  433. document.body.removeChild(textArea);
  434. return result;
  435. }
  436. result = await navigator.clipboard
  437. .writeText(text)
  438. .then(() => {
  439. console.log('Async: Copying to clipboard was successful!');
  440. return true;
  441. })
  442. .catch((error) => {
  443. console.error('Async: Could not copy text: ', error);
  444. return false;
  445. });
  446. return result;
  447. }
  448. };
  449. export const compareVersion = (latest, current) => {
  450. return current === '0.0.0'
  451. ? false
  452. : current.localeCompare(latest, undefined, {
  453. numeric: true,
  454. sensitivity: 'case',
  455. caseFirst: 'upper'
  456. }) < 0;
  457. };
  458. export const extractCurlyBraceWords = (text) => {
  459. const regex = /\{\{([^}]+)\}\}/g;
  460. const matches = [];
  461. let match;
  462. while ((match = regex.exec(text)) !== null) {
  463. matches.push({
  464. word: match[1].trim(),
  465. startIndex: match.index,
  466. endIndex: regex.lastIndex - 1
  467. });
  468. }
  469. return matches;
  470. };
  471. export const removeLastWordFromString = (inputString, wordString) => {
  472. console.log('inputString', inputString);
  473. // Split the string by newline characters to handle lines separately
  474. const lines = inputString.split('\n');
  475. // Take the last line to operate only on it
  476. const lastLine = lines.pop();
  477. // Split the last line into an array of words
  478. const words = lastLine.split(' ');
  479. // Conditional to check for the last word removal
  480. if (words.at(-1) === wordString || (wordString === '' && words.at(-1) === '\\#')) {
  481. words.pop(); // Remove last word if condition is satisfied
  482. }
  483. // Join the remaining words back into a string and handle space correctly
  484. let updatedLastLine = words.join(' ');
  485. // Add a trailing space to the updated last line if there are still words
  486. if (updatedLastLine !== '') {
  487. updatedLastLine += ' ';
  488. }
  489. // Combine the lines together again, placing the updated last line back in
  490. const resultString = [...lines, updatedLastLine].join('\n');
  491. // Return the final string
  492. console.log('resultString', resultString);
  493. return resultString;
  494. };
  495. export const removeFirstHashWord = (inputString) => {
  496. // Split the string into an array of words
  497. const words = inputString.split(' ');
  498. // Find the index of the first word that starts with #
  499. const index = words.findIndex((word) => word.startsWith('#'));
  500. // Remove the first word with #
  501. if (index !== -1) {
  502. words.splice(index, 1);
  503. }
  504. // Join the remaining words back into a string
  505. const resultString = words.join(' ');
  506. return resultString;
  507. };
  508. export const transformFileName = (fileName) => {
  509. // Convert to lowercase
  510. const lowerCaseFileName = fileName.toLowerCase();
  511. // Remove special characters using regular expression
  512. const sanitizedFileName = lowerCaseFileName.replace(/[^\w\s]/g, '');
  513. // Replace spaces with dashes
  514. const finalFileName = sanitizedFileName.replace(/\s+/g, '-');
  515. return finalFileName;
  516. };
  517. export const calculateSHA256 = async (file) => {
  518. // Create a FileReader to read the file asynchronously
  519. const reader = new FileReader();
  520. // Define a promise to handle the file reading
  521. const readFile = new Promise((resolve, reject) => {
  522. reader.onload = () => resolve(reader.result);
  523. reader.onerror = reject;
  524. });
  525. // Read the file as an ArrayBuffer
  526. reader.readAsArrayBuffer(file);
  527. try {
  528. // Wait for the FileReader to finish reading the file
  529. const buffer = await readFile;
  530. // Convert the ArrayBuffer to a Uint8Array
  531. const uint8Array = new Uint8Array(buffer);
  532. // Calculate the SHA-256 hash using Web Crypto API
  533. const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
  534. // Convert the hash to a hexadecimal string
  535. const hashArray = Array.from(new Uint8Array(hashBuffer));
  536. const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('');
  537. return `${hashHex}`;
  538. } catch (error) {
  539. console.error('Error calculating SHA-256 hash:', error);
  540. throw error;
  541. }
  542. };
  543. export const getImportOrigin = (_chats) => {
  544. // Check what external service chat imports are from
  545. if ('mapping' in _chats[0]) {
  546. return 'openai';
  547. }
  548. return 'webui';
  549. };
  550. export const getUserPosition = async (raw = false) => {
  551. // Get the user's location using the Geolocation API
  552. const position = await new Promise((resolve, reject) => {
  553. navigator.geolocation.getCurrentPosition(resolve, reject);
  554. }).catch((error) => {
  555. console.error('Error getting user location:', error);
  556. throw error;
  557. });
  558. if (!position) {
  559. return 'Location not available';
  560. }
  561. // Extract the latitude and longitude from the position
  562. const { latitude, longitude } = position.coords;
  563. if (raw) {
  564. return { latitude, longitude };
  565. } else {
  566. return `${latitude.toFixed(3)}, ${longitude.toFixed(3)} (lat, long)`;
  567. }
  568. };
  569. const convertOpenAIMessages = (convo) => {
  570. // Parse OpenAI chat messages and create chat dictionary for creating new chats
  571. const mapping = convo['mapping'];
  572. const messages = [];
  573. let currentId = '';
  574. let lastId = null;
  575. for (const message_id in mapping) {
  576. const message = mapping[message_id];
  577. currentId = message_id;
  578. try {
  579. if (
  580. messages.length == 0 &&
  581. (message['message'] == null ||
  582. (message['message']['content']['parts']?.[0] == '' &&
  583. message['message']['content']['text'] == null))
  584. ) {
  585. // Skip chat messages with no content
  586. continue;
  587. } else {
  588. const new_chat = {
  589. id: message_id,
  590. parentId: lastId,
  591. childrenIds: message['children'] || [],
  592. role: message['message']?.['author']?.['role'] !== 'user' ? 'assistant' : 'user',
  593. content:
  594. message['message']?.['content']?.['parts']?.[0] ||
  595. message['message']?.['content']?.['text'] ||
  596. '',
  597. model: 'gpt-3.5-turbo',
  598. done: true,
  599. context: null
  600. };
  601. messages.push(new_chat);
  602. lastId = currentId;
  603. }
  604. } catch (error) {
  605. console.log('Error with', message, '\nError:', error);
  606. }
  607. }
  608. const history: Record<PropertyKey, (typeof messages)[number]> = {};
  609. messages.forEach((obj) => (history[obj.id] = obj));
  610. const chat = {
  611. history: {
  612. currentId: currentId,
  613. messages: history // Need to convert this to not a list and instead a json object
  614. },
  615. models: ['gpt-3.5-turbo'],
  616. messages: messages,
  617. options: {},
  618. timestamp: convo['create_time'],
  619. title: convo['title'] ?? 'New Chat'
  620. };
  621. return chat;
  622. };
  623. const validateChat = (chat) => {
  624. // Because ChatGPT sometimes has features we can't use like DALL-E or might have corrupted messages, need to validate
  625. const messages = chat.messages;
  626. // Check if messages array is empty
  627. if (messages.length === 0) {
  628. return false;
  629. }
  630. // Last message's children should be an empty array
  631. const lastMessage = messages[messages.length - 1];
  632. if (lastMessage.childrenIds.length !== 0) {
  633. return false;
  634. }
  635. // First message's parent should be null
  636. const firstMessage = messages[0];
  637. if (firstMessage.parentId !== null) {
  638. return false;
  639. }
  640. // Every message's content should be a string
  641. for (const message of messages) {
  642. if (typeof message.content !== 'string') {
  643. return false;
  644. }
  645. }
  646. return true;
  647. };
  648. export const convertOpenAIChats = (_chats) => {
  649. // Create a list of dictionaries with each conversation from import
  650. const chats = [];
  651. let failed = 0;
  652. for (const convo of _chats) {
  653. const chat = convertOpenAIMessages(convo);
  654. if (validateChat(chat)) {
  655. chats.push({
  656. id: convo['id'],
  657. user_id: '',
  658. title: convo['title'],
  659. chat: chat,
  660. timestamp: convo['create_time']
  661. });
  662. } else {
  663. failed++;
  664. }
  665. }
  666. console.log(failed, 'Conversations could not be imported');
  667. return chats;
  668. };
  669. export const isValidHttpUrl = (string: string) => {
  670. let url;
  671. try {
  672. url = new URL(string);
  673. } catch (_) {
  674. return false;
  675. }
  676. return url.protocol === 'http:' || url.protocol === 'https:';
  677. };
  678. export const removeEmojis = (str: string) => {
  679. // Regular expression to match emojis
  680. const emojiRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g;
  681. // Replace emojis with an empty string
  682. return str.replace(emojiRegex, '');
  683. };
  684. export const removeFormattings = (str: string) => {
  685. return (
  686. str
  687. // Block elements (remove completely)
  688. .replace(/(```[\s\S]*?```)/g, '') // Code blocks
  689. .replace(/^\|.*\|$/gm, '') // Tables
  690. // Inline elements (preserve content)
  691. .replace(/(?:\*\*|__)(.*?)(?:\*\*|__)/g, '$1') // Bold
  692. .replace(/(?:[*_])(.*?)(?:[*_])/g, '$1') // Italic
  693. .replace(/~~(.*?)~~/g, '$1') // Strikethrough
  694. .replace(/`([^`]+)`/g, '$1') // Inline code
  695. // Links and images
  696. .replace(/!?\[([^\]]*)\](?:\([^)]+\)|\[[^\]]*\])/g, '$1') // Links & images
  697. .replace(/^\[[^\]]+\]:\s*.*$/gm, '') // Reference definitions
  698. // Block formatting
  699. .replace(/^#{1,6}\s+/gm, '') // Headers
  700. .replace(/^\s*[-*+]\s+/gm, '') // Lists
  701. .replace(/^\s*(?:\d+\.)\s+/gm, '') // Numbered lists
  702. .replace(/^\s*>[> ]*/gm, '') // Blockquotes
  703. .replace(/^\s*:\s+/gm, '') // Definition lists
  704. // Cleanup
  705. .replace(/\[\^[^\]]*\]/g, '') // Footnotes
  706. .replace(/\n{2,}/g, '\n')
  707. ); // Multiple newlines
  708. };
  709. export const cleanText = (content: string) => {
  710. return removeFormattings(removeEmojis(content.trim()));
  711. };
  712. export const removeDetails = (content, types) => {
  713. for (const type of types) {
  714. content = content.replace(
  715. new RegExp(`<details\\s+type="${type}"[^>]*>.*?<\\/details>`, 'gis'),
  716. ''
  717. );
  718. }
  719. return content;
  720. };
  721. export const removeAllDetails = (content) => {
  722. content = content.replace(/<details[^>]*>.*?<\/details>/gis, '');
  723. return content;
  724. };
  725. export const processDetails = (content) => {
  726. content = removeDetails(content, ['reasoning', 'code_interpreter']);
  727. // This regex matches <details> tags with type="tool_calls" and captures their attributes to convert them to a string
  728. const detailsRegex = /<details\s+type="tool_calls"([^>]*)>([\s\S]*?)<\/details>/gis;
  729. const matches = content.match(detailsRegex);
  730. if (matches) {
  731. for (const match of matches) {
  732. const attributesRegex = /(\w+)="([^"]*)"/g;
  733. const attributes = {};
  734. let attributeMatch;
  735. while ((attributeMatch = attributesRegex.exec(match)) !== null) {
  736. attributes[attributeMatch[1]] = attributeMatch[2];
  737. }
  738. content = content.replace(match, `"${attributes.result}"`);
  739. }
  740. }
  741. return content;
  742. };
  743. // This regular expression matches code blocks marked by triple backticks
  744. const codeBlockRegex = /```[\s\S]*?```/g;
  745. export const extractSentences = (text: string) => {
  746. const codeBlocks: string[] = [];
  747. let index = 0;
  748. // Temporarily replace code blocks with placeholders and store the blocks separately
  749. text = text.replace(codeBlockRegex, (match) => {
  750. const placeholder = `\u0000${index}\u0000`; // Use a unique placeholder
  751. codeBlocks[index++] = match;
  752. return placeholder;
  753. });
  754. // Split the modified text into sentences based on common punctuation marks, avoiding these blocks
  755. let sentences = text.split(/(?<=[.!?])\s+/);
  756. // Restore code blocks and process sentences
  757. sentences = sentences.map((sentence) => {
  758. // Check if the sentence includes a placeholder for a code block
  759. return sentence.replace(/\u0000(\d+)\u0000/g, (_, idx) => codeBlocks[idx]);
  760. });
  761. return sentences.map(cleanText).filter(Boolean);
  762. };
  763. export const extractParagraphsForAudio = (text: string) => {
  764. const codeBlocks: string[] = [];
  765. let index = 0;
  766. // Temporarily replace code blocks with placeholders and store the blocks separately
  767. text = text.replace(codeBlockRegex, (match) => {
  768. const placeholder = `\u0000${index}\u0000`; // Use a unique placeholder
  769. codeBlocks[index++] = match;
  770. return placeholder;
  771. });
  772. // Split the modified text into paragraphs based on newlines, avoiding these blocks
  773. let paragraphs = text.split(/\n+/);
  774. // Restore code blocks and process paragraphs
  775. paragraphs = paragraphs.map((paragraph) => {
  776. // Check if the paragraph includes a placeholder for a code block
  777. return paragraph.replace(/\u0000(\d+)\u0000/g, (_, idx) => codeBlocks[idx]);
  778. });
  779. return paragraphs.map(cleanText).filter(Boolean);
  780. };
  781. export const extractSentencesForAudio = (text: string) => {
  782. return extractSentences(text).reduce((mergedTexts, currentText) => {
  783. const lastIndex = mergedTexts.length - 1;
  784. if (lastIndex >= 0) {
  785. const previousText = mergedTexts[lastIndex];
  786. const wordCount = previousText.split(/\s+/).length;
  787. const charCount = previousText.length;
  788. if (wordCount < 4 || charCount < 50) {
  789. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  790. } else {
  791. mergedTexts.push(currentText);
  792. }
  793. } else {
  794. mergedTexts.push(currentText);
  795. }
  796. return mergedTexts;
  797. }, [] as string[]);
  798. };
  799. export const getMessageContentParts = (content: string, splitOn: string = 'punctuation') => {
  800. const messageContentParts: string[] = [];
  801. switch (splitOn) {
  802. default:
  803. case TTS_RESPONSE_SPLIT.PUNCTUATION:
  804. messageContentParts.push(...extractSentencesForAudio(content));
  805. break;
  806. case TTS_RESPONSE_SPLIT.PARAGRAPHS:
  807. messageContentParts.push(...extractParagraphsForAudio(content));
  808. break;
  809. case TTS_RESPONSE_SPLIT.NONE:
  810. messageContentParts.push(cleanText(content));
  811. break;
  812. }
  813. return messageContentParts;
  814. };
  815. export const blobToFile = (blob, fileName) => {
  816. // Create a new File object from the Blob
  817. const file = new File([blob], fileName, { type: blob.type });
  818. return file;
  819. };
  820. export const getPromptVariables = (user_name, user_location) => {
  821. return {
  822. '{{USER_NAME}}': user_name,
  823. '{{USER_LOCATION}}': user_location || 'Unknown',
  824. '{{CURRENT_DATETIME}}': getCurrentDateTime(),
  825. '{{CURRENT_DATE}}': getFormattedDate(),
  826. '{{CURRENT_TIME}}': getFormattedTime(),
  827. '{{CURRENT_WEEKDAY}}': getWeekday(),
  828. '{{CURRENT_TIMEZONE}}': getUserTimezone(),
  829. '{{USER_LANGUAGE}}': localStorage.getItem('locale') || 'en-US'
  830. };
  831. };
  832. /**
  833. * This function is used to replace placeholders in a template string with the provided prompt.
  834. * The placeholders can be in the following formats:
  835. * - `{{prompt}}`: This will be replaced with the entire prompt.
  836. * - `{{prompt:start:<length>}}`: This will be replaced with the first <length> characters of the prompt.
  837. * - `{{prompt:end:<length>}}`: This will be replaced with the last <length> characters of the prompt.
  838. * - `{{prompt:middletruncate:<length>}}`: This will be replaced with the prompt truncated to <length> characters, with '...' in the middle.
  839. *
  840. * @param {string} template - The template string containing placeholders.
  841. * @param {string} prompt - The string to replace the placeholders with.
  842. * @returns {string} The template string with the placeholders replaced by the prompt.
  843. */
  844. export const titleGenerationTemplate = (template: string, prompt: string): string => {
  845. template = template.replace(
  846. /{{prompt}}|{{prompt:start:(\d+)}}|{{prompt:end:(\d+)}}|{{prompt:middletruncate:(\d+)}}/g,
  847. (match, startLength, endLength, middleLength) => {
  848. if (match === '{{prompt}}') {
  849. return prompt;
  850. } else if (match.startsWith('{{prompt:start:')) {
  851. return prompt.substring(0, startLength);
  852. } else if (match.startsWith('{{prompt:end:')) {
  853. return prompt.slice(-endLength);
  854. } else if (match.startsWith('{{prompt:middletruncate:')) {
  855. if (prompt.length <= middleLength) {
  856. return prompt;
  857. }
  858. const start = prompt.slice(0, Math.ceil(middleLength / 2));
  859. const end = prompt.slice(-Math.floor(middleLength / 2));
  860. return `${start}...${end}`;
  861. }
  862. return '';
  863. }
  864. );
  865. return template;
  866. };
  867. export const approximateToHumanReadable = (nanoseconds: number) => {
  868. const seconds = Math.floor((nanoseconds / 1e9) % 60);
  869. const minutes = Math.floor((nanoseconds / 6e10) % 60);
  870. const hours = Math.floor((nanoseconds / 3.6e12) % 24);
  871. const results: string[] = [];
  872. if (seconds >= 0) {
  873. results.push(`${seconds}s`);
  874. }
  875. if (minutes > 0) {
  876. results.push(`${minutes}m`);
  877. }
  878. if (hours > 0) {
  879. results.push(`${hours}h`);
  880. }
  881. return results.reverse().join(' ');
  882. };
  883. export const getTimeRange = (timestamp) => {
  884. const now = new Date();
  885. const date = new Date(timestamp * 1000); // Convert Unix timestamp to milliseconds
  886. // Calculate the difference in milliseconds
  887. const diffTime = now.getTime() - date.getTime();
  888. const diffDays = diffTime / (1000 * 3600 * 24);
  889. const nowDate = now.getDate();
  890. const nowMonth = now.getMonth();
  891. const nowYear = now.getFullYear();
  892. const dateDate = date.getDate();
  893. const dateMonth = date.getMonth();
  894. const dateYear = date.getFullYear();
  895. if (nowYear === dateYear && nowMonth === dateMonth && nowDate === dateDate) {
  896. return 'Today';
  897. } else if (nowYear === dateYear && nowMonth === dateMonth && nowDate - dateDate === 1) {
  898. return 'Yesterday';
  899. } else if (diffDays <= 7) {
  900. return 'Previous 7 days';
  901. } else if (diffDays <= 30) {
  902. return 'Previous 30 days';
  903. } else if (nowYear === dateYear) {
  904. return date.toLocaleString('default', { month: 'long' });
  905. } else {
  906. return date.getFullYear().toString();
  907. }
  908. };
  909. /**
  910. * Extract frontmatter as a dictionary from the specified content string.
  911. * @param content {string} - The content string with potential frontmatter.
  912. * @returns {Object} - The extracted frontmatter as a dictionary.
  913. */
  914. export const extractFrontmatter = (content) => {
  915. const frontmatter = {};
  916. let frontmatterStarted = false;
  917. let frontmatterEnded = false;
  918. const frontmatterPattern = /^\s*([a-z_]+):\s*(.*)\s*$/i;
  919. // Split content into lines
  920. const lines = content.split('\n');
  921. // Check if the content starts with triple quotes
  922. if (lines[0].trim() !== '"""') {
  923. return {};
  924. }
  925. frontmatterStarted = true;
  926. for (let i = 1; i < lines.length; i++) {
  927. const line = lines[i];
  928. if (line.includes('"""')) {
  929. if (frontmatterStarted) {
  930. frontmatterEnded = true;
  931. break;
  932. }
  933. }
  934. if (frontmatterStarted && !frontmatterEnded) {
  935. const match = frontmatterPattern.exec(line);
  936. if (match) {
  937. const [, key, value] = match;
  938. frontmatter[key.trim()] = value.trim();
  939. }
  940. }
  941. }
  942. return frontmatter;
  943. };
  944. // Function to determine the best matching language
  945. export const bestMatchingLanguage = (supportedLanguages, preferredLanguages, defaultLocale) => {
  946. const languages = supportedLanguages.map((lang) => lang.code);
  947. const match = preferredLanguages
  948. .map((prefLang) => languages.find((lang) => lang.startsWith(prefLang)))
  949. .find(Boolean);
  950. return match || defaultLocale;
  951. };
  952. // Get the date in the format YYYY-MM-DD
  953. export const getFormattedDate = () => {
  954. const date = new Date();
  955. const year = date.getFullYear();
  956. const month = String(date.getMonth() + 1).padStart(2, '0');
  957. const day = String(date.getDate()).padStart(2, '0');
  958. return `${year}-${month}-${day}`;
  959. };
  960. // Get the time in the format HH:MM:SS
  961. export const getFormattedTime = () => {
  962. const date = new Date();
  963. return date.toTimeString().split(' ')[0];
  964. };
  965. // Get the current date and time in the format YYYY-MM-DD HH:MM:SS
  966. export const getCurrentDateTime = () => {
  967. return `${getFormattedDate()} ${getFormattedTime()}`;
  968. };
  969. // Get the user's timezone
  970. export const getUserTimezone = () => {
  971. return Intl.DateTimeFormat().resolvedOptions().timeZone;
  972. };
  973. // Get the weekday
  974. export const getWeekday = () => {
  975. const date = new Date();
  976. const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  977. return weekdays[date.getDay()];
  978. };
  979. export const createMessagesList = (history, messageId) => {
  980. if (messageId === null) {
  981. return [];
  982. }
  983. const message = history.messages[messageId];
  984. if (message === undefined) {
  985. return [];
  986. }
  987. if (message?.parentId) {
  988. return [...createMessagesList(history, message.parentId), message];
  989. } else {
  990. return [message];
  991. }
  992. };
  993. export const formatFileSize = (size) => {
  994. if (size == null) return 'Unknown size';
  995. if (typeof size !== 'number' || size < 0) return 'Invalid size';
  996. if (size === 0) return '0 B';
  997. const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  998. let unitIndex = 0;
  999. while (size >= 1024 && unitIndex < units.length - 1) {
  1000. size /= 1024;
  1001. unitIndex++;
  1002. }
  1003. return `${size.toFixed(1)} ${units[unitIndex]}`;
  1004. };
  1005. export const getLineCount = (text) => {
  1006. console.log(typeof text);
  1007. return text ? text.split('\n').length : 0;
  1008. };
  1009. // Helper function to recursively resolve OpenAPI schema into JSON schema format
  1010. function resolveSchema(schemaRef, components, resolvedSchemas = new Set()) {
  1011. if (!schemaRef) return {};
  1012. if (schemaRef['$ref']) {
  1013. const refPath = schemaRef['$ref'];
  1014. const schemaName = refPath.split('/').pop();
  1015. if (resolvedSchemas.has(schemaName)) {
  1016. // Avoid infinite recursion on circular references
  1017. return {};
  1018. }
  1019. resolvedSchemas.add(schemaName);
  1020. const referencedSchema = components.schemas[schemaName];
  1021. return resolveSchema(referencedSchema, components, resolvedSchemas);
  1022. }
  1023. if (schemaRef.type) {
  1024. const schemaObj = { type: schemaRef.type };
  1025. if (schemaRef.description) {
  1026. schemaObj.description = schemaRef.description;
  1027. }
  1028. switch (schemaRef.type) {
  1029. case 'object':
  1030. schemaObj.properties = {};
  1031. schemaObj.required = schemaRef.required || [];
  1032. for (const [propName, propSchema] of Object.entries(schemaRef.properties || {})) {
  1033. schemaObj.properties[propName] = resolveSchema(propSchema, components);
  1034. }
  1035. break;
  1036. case 'array':
  1037. schemaObj.items = resolveSchema(schemaRef.items, components);
  1038. break;
  1039. default:
  1040. // for primitive types (string, integer, etc.), just use as is
  1041. break;
  1042. }
  1043. return schemaObj;
  1044. }
  1045. // fallback for schemas without explicit type
  1046. return {};
  1047. }
  1048. // Main conversion function
  1049. export const convertOpenApiToToolPayload = (openApiSpec) => {
  1050. const toolPayload = [];
  1051. for (const [path, methods] of Object.entries(openApiSpec.paths)) {
  1052. for (const [method, operation] of Object.entries(methods)) {
  1053. if (operation?.operationId) {
  1054. const tool = {
  1055. name: operation.operationId,
  1056. description: operation.description || operation.summary || 'No description available.',
  1057. parameters: {
  1058. type: 'object',
  1059. properties: {},
  1060. required: []
  1061. }
  1062. };
  1063. // Extract path and query parameters
  1064. if (operation.parameters) {
  1065. operation.parameters.forEach((param) => {
  1066. let description = param.schema.description || param.description || '';
  1067. if (param.schema.enum && Array.isArray(param.schema.enum)) {
  1068. description += `. Possible values: ${param.schema.enum.join(', ')}`;
  1069. }
  1070. tool.parameters.properties[param.name] = {
  1071. type: param.schema.type,
  1072. description: description
  1073. };
  1074. if (param.required) {
  1075. tool.parameters.required.push(param.name);
  1076. }
  1077. });
  1078. }
  1079. // Extract and recursively resolve requestBody if available
  1080. if (operation.requestBody) {
  1081. const content = operation.requestBody.content;
  1082. if (content && content['application/json']) {
  1083. const requestSchema = content['application/json'].schema;
  1084. const resolvedRequestSchema = resolveSchema(requestSchema, openApiSpec.components);
  1085. if (resolvedRequestSchema.properties) {
  1086. tool.parameters.properties = {
  1087. ...tool.parameters.properties,
  1088. ...resolvedRequestSchema.properties
  1089. };
  1090. if (resolvedRequestSchema.required) {
  1091. tool.parameters.required = [
  1092. ...new Set([...tool.parameters.required, ...resolvedRequestSchema.required])
  1093. ];
  1094. }
  1095. } else if (resolvedRequestSchema.type === 'array') {
  1096. tool.parameters = resolvedRequestSchema; // special case when root schema is an array
  1097. }
  1098. }
  1099. }
  1100. toolPayload.push(tool);
  1101. }
  1102. }
  1103. }
  1104. return toolPayload;
  1105. };
  1106. export const slugify = (str: string): string => {
  1107. return (
  1108. str
  1109. // 1. Normalize: separate accented letters into base + combining marks
  1110. .normalize('NFD')
  1111. // 2. Remove all combining marks (the accents)
  1112. .replace(/[\u0300-\u036f]/g, '')
  1113. // 3. Replace any sequence of whitespace with a single hyphen
  1114. .replace(/\s+/g, '-')
  1115. // 4. Remove all characters except alphanumeric characters, hyphens, and underscores
  1116. .replace(/[^a-zA-Z0-9-_]/g, '')
  1117. // 5. Convert to lowercase
  1118. .toLowerCase()
  1119. );
  1120. };
  1121. export const extractInputVariables = (text: string): Record<string, any> => {
  1122. const regex = /{{\s*([^|}\s]+)\s*\|\s*([^}]+)\s*}}/g;
  1123. const regularRegex = /{{\s*([^|}\s]+)\s*}}/g;
  1124. const variables: Record<string, any> = {};
  1125. let match;
  1126. // Use exec() loop instead of matchAll() for better compatibility
  1127. while ((match = regex.exec(text)) !== null) {
  1128. const varName = match[1].trim();
  1129. const definition = match[2].trim();
  1130. variables[varName] = parseVariableDefinition(definition);
  1131. }
  1132. // Then, extract regular variables (without pipe) - only if not already processed
  1133. while ((match = regularRegex.exec(text)) !== null) {
  1134. const varName = match[1].trim();
  1135. // Only add if not already processed as custom variable
  1136. if (!variables.hasOwnProperty(varName)) {
  1137. variables[varName] = { type: 'text' }; // Default type for regular variables
  1138. }
  1139. }
  1140. return variables;
  1141. };
  1142. export const splitProperties = (str: string, delimiter: string): string[] => {
  1143. const result: string[] = [];
  1144. let current = '';
  1145. let depth = 0;
  1146. let inString = false;
  1147. let escapeNext = false;
  1148. for (let i = 0; i < str.length; i++) {
  1149. const char = str[i];
  1150. if (escapeNext) {
  1151. current += char;
  1152. escapeNext = false;
  1153. continue;
  1154. }
  1155. if (char === '\\') {
  1156. current += char;
  1157. escapeNext = true;
  1158. continue;
  1159. }
  1160. if (char === '"' && !escapeNext) {
  1161. inString = !inString;
  1162. current += char;
  1163. continue;
  1164. }
  1165. if (!inString) {
  1166. if (char === '{' || char === '[') {
  1167. depth++;
  1168. } else if (char === '}' || char === ']') {
  1169. depth--;
  1170. }
  1171. if (char === delimiter && depth === 0) {
  1172. result.push(current.trim());
  1173. current = '';
  1174. continue;
  1175. }
  1176. }
  1177. current += char;
  1178. }
  1179. if (current.trim()) {
  1180. result.push(current.trim());
  1181. }
  1182. return result;
  1183. };
  1184. export const parseVariableDefinition = (definition: string): Record<string, any> => {
  1185. // Use splitProperties for the main colon delimiter to handle quoted strings
  1186. const parts = splitProperties(definition, ':');
  1187. const [firstPart, ...propertyParts] = parts;
  1188. // Parse type (explicit or implied)
  1189. const type = firstPart.startsWith('type=') ? firstPart.slice(5) : firstPart;
  1190. // Parse properties using reduce
  1191. const properties = propertyParts.reduce((props, part) => {
  1192. // Use splitProperties for the equals sign as well, in case there are nested quotes
  1193. const equalsParts = splitProperties(part, '=');
  1194. const [propertyName, ...valueParts] = equalsParts;
  1195. const propertyValue = valueParts.join('='); // Handle values with = signs
  1196. return propertyName && propertyValue
  1197. ? {
  1198. ...props,
  1199. [propertyName.trim()]: parseJsonValue(propertyValue.trim())
  1200. }
  1201. : props;
  1202. }, {});
  1203. return { type, ...properties };
  1204. };
  1205. export const parseJsonValue = (value: string): any => {
  1206. // Remove surrounding quotes if present (for string values)
  1207. if (value.startsWith('"') && value.endsWith('"')) {
  1208. return value.slice(1, -1);
  1209. }
  1210. // Check if it starts with square or curly brackets (JSON)
  1211. if (/^[\[{]/.test(value)) {
  1212. try {
  1213. return JSON.parse(value);
  1214. } catch {
  1215. return value; // Return as string if JSON parsing fails
  1216. }
  1217. }
  1218. return value;
  1219. };
  1220. async function ensurePDFjsLoaded() {
  1221. if (!window.pdfjsLib) {
  1222. const pdfjs = await import('pdfjs-dist');
  1223. pdfjs.GlobalWorkerOptions.workerSrc = pdfWorkerUrl;
  1224. if (!window.pdfjsLib) {
  1225. throw new Error('pdfjsLib is required for PDF extraction');
  1226. }
  1227. }
  1228. return window.pdfjsLib;
  1229. }
  1230. export const extractContentFromFile = async (file: File) => {
  1231. // Known text file extensions for extra fallback
  1232. const textExtensions = [
  1233. '.txt',
  1234. '.md',
  1235. '.csv',
  1236. '.json',
  1237. '.js',
  1238. '.ts',
  1239. '.css',
  1240. '.html',
  1241. '.xml',
  1242. '.yaml',
  1243. '.yml',
  1244. '.rtf'
  1245. ];
  1246. function getExtension(filename: string) {
  1247. const dot = filename.lastIndexOf('.');
  1248. return dot === -1 ? '' : filename.substr(dot).toLowerCase();
  1249. }
  1250. // Uses pdfjs to extract text from PDF
  1251. async function extractPdfText(file: File) {
  1252. const pdfjsLib = await ensurePDFjsLoaded();
  1253. const arrayBuffer = await file.arrayBuffer();
  1254. const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
  1255. let allText = '';
  1256. for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
  1257. const page = await pdf.getPage(pageNum);
  1258. const content = await page.getTextContent();
  1259. const strings = content.items.map((item: any) => item.str);
  1260. allText += strings.join(' ') + '\n';
  1261. }
  1262. return allText;
  1263. }
  1264. // Reads file as text using FileReader
  1265. function readAsText(file: File) {
  1266. return new Promise((resolve, reject) => {
  1267. const reader = new FileReader();
  1268. reader.onload = () => resolve(reader.result);
  1269. reader.onerror = reject;
  1270. reader.readAsText(file);
  1271. });
  1272. }
  1273. const type = file.type || '';
  1274. const ext = getExtension(file.name);
  1275. // PDF check
  1276. if (type === 'application/pdf' || ext === '.pdf') {
  1277. return await extractPdfText(file);
  1278. }
  1279. // Text check (plain or common text-based)
  1280. if (type.startsWith('text/') || textExtensions.includes(ext)) {
  1281. return await readAsText(file);
  1282. }
  1283. // Fallback: try to read as text, if decodable
  1284. try {
  1285. return await readAsText(file);
  1286. } catch (err) {
  1287. throw new Error('Unsupported or non-text file type: ' + (file.name || type));
  1288. }
  1289. };
  1290. export const querystringValue = (key: string): string | null => {
  1291. const querystring = window.location.search;
  1292. const urlParams = new URLSearchParams(querystring);
  1293. return urlParams.get(key);
  1294. };
  1295. export const getAge = (birthDate) => {
  1296. const today = new Date();
  1297. const bDate = new Date(birthDate);
  1298. let age = today.getFullYear() - bDate.getFullYear();
  1299. const m = today.getMonth() - bDate.getMonth();
  1300. if (m < 0 || (m === 0 && today.getDate() < bDate.getDate())) {
  1301. age--;
  1302. }
  1303. return age.toString();
  1304. };
  1305. export const convertHeicToJpeg = async (file: File) => {
  1306. const { default: heic2any } = await import('heic2any');
  1307. try {
  1308. return await heic2any({ blob: file, toType: 'image/jpeg' });
  1309. } catch (err: any) {
  1310. if (err?.message?.includes('already browser readable')) {
  1311. return file;
  1312. }
  1313. throw err;
  1314. }
  1315. };