blob: b97fba16c2cc3e483a662a6fd30264f09a4cfd2e [file] [log] [blame]
Adrià Vilanova Martínez46773172024-01-10 21:44:22 +01001import rescape from '@stdlib/utils-escape-regexp-string';
2
3import {correctArrayKeys} from './protojs';
4
5export function parseView(viewVar) {
6 const escapedViewVar = rescape(viewVar);
7 const viewRegex = new RegExp(`var ${escapedViewVar} ?= ?'([^']+)';`);
8
9 const scripts = document.querySelectorAll('script');
10 let viewData = null;
11 for (let i = 0; i < scripts.length; ++i) {
12 const matches = scripts[i].textContent.match(viewRegex);
13 if (matches?.[1]) {
14 let rawJsonStringContents =
15 matches[1]
16 .replace(
17 /\\x([0-9a-f]{2})/ig,
18 (_, pair) => {
19 return String.fromCharCode(parseInt(pair, 16));
20 })
21 .replace(/\\'/g, `'`)
22 .replace(/"/g, `\\"`);
23 let rawJsonString = `"${rawJsonStringContents}"`;
24 let rawJson = JSON.parse(rawJsonString);
25 viewData = JSON.parse(rawJson);
26 break;
27 }
28 }
29 if (!viewData) throw new Error(`Could not find ${viewVar} view data.`);
30 return correctArrayKeys(viewData);
31}