Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: eval store not a constructor #36

Merged
merged 3 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@
"web-component-base": "^2.0.6"
},
"devDependencies": {
"nitropack": "^2.9.2"
"nitropack": "2.8"
}
}
79 changes: 50 additions & 29 deletions packages/core/event-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function useMcFlyRoute({ config, storage }) {
}

function getPurePath(path) {
return path.split('?')[0]
return path.split("?")[0];
}

/**
Expand All @@ -61,7 +61,8 @@ function getPurePath(path) {
*/
async function getHtml(path, storage) {
const purePath = getPurePath(path);
const rawPath = purePath[purePath.length - 1] === "/" ? purePath.slice(0, -1) : purePath;
const rawPath =
purePath[purePath.length - 1] === "/" ? purePath.slice(0, -1) : purePath;
const filename = rawPath === "" ? "/index.html" : `${rawPath}.html`;
const fallback = getPath(rawPath + "/index.html");
const filePath = getPath(filename);
Expand Down Expand Up @@ -140,22 +141,25 @@ async function buildRegistry(usedCustomElements, type, storage) {
const evalStore = eval(
`class WebComponent {}; class HTMLElement {}; (${content.toString()})`
);
const className = new evalStore().constructor.name;

if (!classesImported.includes(className)) {
if (
!isBaseClassImported &&
content.toString().includes("extends WebComponent")
) {
const baseClassImport = `import { WebComponent, html, attachEffect } from "https://unpkg.com/web-component-base@2.0.6/index.js";`;
registryScript += baseClassImport;
isBaseClassImported = true;
}

registryScript += content;
if (isConstructor(evalStore)) {
const className = new evalStore().constructor.name;

if (!classesImported.includes(className)) {
if (
!isBaseClassImported &&
content.toString().includes("extends WebComponent")
) {
const baseClassImport = `import { WebComponent, html, attachEffect } from "https://unpkg.com/web-component-base@2.0.6/index.js";`;
registryScript += baseClassImport;
isBaseClassImported = true;
}

registryScript += content;

registryScript += `customElements.define("${name}", ${className});`;
classesImported.push(className);
registryScript += `customElements.define("${name}", ${className});`;
classesImported.push(className);
}
}
}

Expand All @@ -164,6 +168,21 @@ async function buildRegistry(usedCustomElements, type, storage) {
return registryScript;
}

/**
* Check if function is a constructor
* @param {function} f
* @returns boolean
*/
function isConstructor(f) {
try {
new f();
} catch (err) {
// verify err is the expected error and then
return false;
}
return true;
}

/**
* Evaluates server:setup script and replaces all variables used in the HTML
* @param {string} html
Expand Down Expand Up @@ -207,14 +226,14 @@ function doSetUp(html) {
let [key, value] = match;
value = value.replace(/\s/g, "");
// nested objects
const keys = value.split('.');
let finalValue = '';
const keys = value.split(".");
let finalValue = "";
let setupCopy = setupMap;

keys.forEach(i => {
finalValue = setupCopy[i]
keys.forEach((i) => {
finalValue = setupCopy[i];
setupCopy = finalValue;
})
});

html = html.replace(key, finalValue);
}
Expand Down Expand Up @@ -350,24 +369,26 @@ async function useFragments(html, storage) {
*/
function replaceSlots(fragmentNode, node) {
let slotted = [];
const containsAll = (arr, target) => target.every(v => arr.includes(v));
const containsAll = (arr, target) => target.every((v) => arr.includes(v));
walkSync(fragmentNode, (n) => {
if (n.type === ELEMENT_NODE && n.name === "slot") {
// find node child with same name attribute
const currentSlotName = n.attributes?.['name'] ?? null;
const currentSlotName = n.attributes?.["name"] ?? null;
let nodeChildren = [];

if (currentSlotName === null) {
nodeChildren = node.children.filter(child => !child.attributes?.['slot']);
if (currentSlotName === null) {
nodeChildren = node.children.filter(
(child) => !child.attributes?.["slot"]
);
} else {
nodeChildren = node.children.filter(child => {
const childSlotName = child.attributes?.['slot'];
nodeChildren = node.children.filter((child) => {
const childSlotName = child.attributes?.["slot"];
return childSlotName === currentSlotName;
})
});
}

if (nodeChildren.length > 0 && !containsAll(slotted, nodeChildren)) {
slotted = [...slotted, ...nodeChildren]
slotted = [...slotted, ...nodeChildren];
const index = n.parent.children.indexOf(n);
n.parent.children.splice(index, 1, ...nodeChildren);
}
Expand Down
3 changes: 3 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@
"esprima": "^4.0.1",
"h3": "^1.8.2",
"ultrahtml": "^1.5.2"
},
"devDependencies": {
"unstorage": "^1.10.1"
}
}
Loading