feat: parseScript to get variables

This commit is contained in:
Ayo 2023-10-10 22:42:43 +02:00
parent 6d6921aa64
commit 3b246cb711
4 changed files with 31 additions and 7 deletions

13
package-lock.json generated
View file

@ -5,6 +5,7 @@
"packages": {
"": {
"dependencies": {
"esprima": "^4.0.1",
"nitropack": "latest",
"ultrahtml": "^1.5.2"
}
@ -1757,6 +1758,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/estree-walker": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",

View file

@ -9,6 +9,7 @@
"build:preview": "npm run build && npm run preview"
},
"dependencies": {
"esprima": "^4.0.1",
"nitropack": "latest",
"ultrahtml": "^1.5.2"
}

View file

@ -1,4 +1,5 @@
import { ELEMENT_NODE, parse, walkSync } from "ultrahtml";
import { parseScript } from "esprima";
export default eventHandler(async (event) => {
const rawPath =
@ -60,9 +61,13 @@ function doSetUp(html: string) {
const setupMap = {};
serverScripts.forEach((script: string) => {
const constructor = `
new Function(\`${script}\`);
`;
const { body } = parseScript(script);
const keys = body
.filter((node) => node.type === "VariableDeclaration")
.map((node) => node.declarations[0].id.name);
const constructor = `new Function(\`${script}; return {${keys.join(
","
)}}\`);`;
const evalStore = eval(constructor);
Object.assign(setupMap, new evalStore());
});
@ -73,7 +78,7 @@ function doSetUp(html: string) {
let matches = [];
while ((match = regex.exec(html)) != null) {
console.log(match[0], match[1]);
html = html.replace(match[0], setupMap[match[1]]);
html = html.replace(match[0], setupMap[match[1].trim()]);
}
return html;

View file

@ -6,15 +6,20 @@
<title>Hello Nitro</title>
<script server:setup>
const name = "AYOs";
return { name, greeting: "hey" }; // TODO: this is illegal! figure out a way to build an object in the route intercept
let greeting = "hello";
var count = sum(1, 247);
function sum(x, y) {
return x + y;
}
</script>
</head>
<body>
<a href="/about">About</a>
<a href="/about">{{ count }}</a>
<div>
<hello-world name="{{name}}"></hello-world>
</div>
<span>some text: {{greeting}}</span>
<p>some text: {{greeting}}</p>
<clickable-text></clickable-text>
<script>
const helloWorld = document.querySelector("hello-world");