Adrià Vilanova MartÃnez | 4677317 | 2024-01-10 21:44:22 +0100 | [diff] [blame] | 1 | import rescape from '@stdlib/utils-escape-regexp-string'; |
| 2 | |
| 3 | import {correctArrayKeys} from './protojs'; |
| 4 | |
| 5 | export 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 | } |