| 1 | export const parseBuilder = (str) => { |
| 2 | let lines = str.split("\n"); |
| 3 | const ref = {}; |
| 4 | for (let line of lines) { |
| 5 | const lineData = |
| 6 | /^(?<tabs>\s*)(?<name>\w*)(?<optional>\??):(?<regex>.*)/.exec( |
| 7 | line |
| 8 | ).groups; |
| 9 | const tabs = lineData.tabs.length; |
| 10 | if (!ref[tabs]) ref[tabs] = [lineData]; |
| 11 | else ref[tabs].push(lineData); |
| 12 | if (tabs) { |
| 13 | const parentRefInd = ref[tabs - 1].length - 1; |
| 14 | let parent = ref[tabs - 1][parentRefInd]; |
| 15 | if (!parent.children) parent.children = [lineData]; |
| 16 | else parent.children.push(lineData); |
| 17 | } |
| 18 | } |
| 19 | return ref[0]; |
| 20 | }; |
| 21 | |
| 22 | export const buildToRegex = (build) => { |
| 23 | const re = buildToRegexRecursion(build, ""); |
| 24 | return re; |
| 25 | }; |
| 26 | |
| 27 | const buildToRegexRecursion = (build, re) => { |
| 28 | if (!build?.length) return re; |
| 29 | const val = build.shift(); |
| 30 | if (val.name) re += `(?P<${val.name}>${val.regex}`; |
| 31 | else re += `(?:${val.regex}`; |
| 32 | if (val.children) re += buildToRegexRecursion(val.children, ""); |
| 33 | re += `${val.optional})`; |
| 34 | |
| 35 | return buildToRegexRecursion(build, re); |
| 36 | }; |