vaderjs 1.3.3-alpha-62 → 1.3.3-alpha-64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/runtime/router.js +1 -1
- package/runtime/vader.js +1 -1
- package/vader.js +30 -15
package/package.json
CHANGED
package/runtime/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(e,t){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=e}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){console.log(e),this.middlewares.push(e)}listen(e,t){e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),t&&t(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(e,t){const s=e.split("/"),n=t.split("/"),
|
|
1
|
+
import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(e,t){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=e}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){console.log(e),this.middlewares.push(e)}listen(e,t){e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),t&&t(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(e,t){const s=e.split("/"),n=t.split("/"),r={};return s.forEach(((e,t)=>{if(e.startsWith(":")){const s=e.slice(1);r[s]=n[t]}else if(e.startsWith("*")){n.slice(t).forEach(((e,t)=>{r[t]=e}))}})),r}extractQueryParams(e){const t=e.split("?")[1];if(!t)return{};const s={};return t.split("&").forEach((e=>{const[t,n]=e.split("=");s[t]=n})),s}handleRoute(e){let t=200,s=e=e.slice(1),n=this.routes.find((t=>{if(t.path===e)return!0;if(""===e&&"/"===t.path)return!0;if(e.includes("?")&&(e=e.split("?")[0]),t.path.includes("*")||t.path.includes(":")){const s=t.path.split("/"),n=e.split("/");if(s.length!==n.length&&!t.path.endsWith("*"))return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if(!t.startsWith(":")&&!t.startsWith("*")&&t!==r)return!1}return!0}const n=this.extractParams(t.path,s);return Object.keys(n).length>0}));n||(n=this.routes.find((e=>{if(e.path.includes("/404"))return this.error=!0,!0;!this.error&&e.path.includes("/404")&&(window.location.hash=this.basePath)})),t=n?200:404);const r=this.extractQueryParams(s),o=n&&n.path?this.extractParams(n.path,s):{},a={headers:{},params:o,query:r,path:e,url:window.location.href+e,method:n?n.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=a.path,window.$FULL_URL=window.location.href.replace("#","");const i={status:t,log:e=>{void 0===e?console.log(`${a.path} ${a.method} ${i.status} ${a.timestamp}`):console.table({"Request Path":a.path,"Request Method":n.method,"Response Status":i.status,"Request Timestamp":a.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.location.hash=`#${e}`},render:async(e,t,s)=>{function n(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let a=new Component;if(n(e.default)){let t=new e.default;a.state=t.state,a=t}else{if(e.default.toString().includes("this.key"))throw new Error('Using this.key is not supported in functional components use the attribute key="a value" instead');a.key=e.default.toString().split('key="')[1]?e.default.toString().split('key="')[1].split('"')[0]:null;let n={key:a.key,render:()=>e.default.apply(a,[t,s]),request:t,response:s,params:o,queryParams:r,reset:a.reset.bind(a),onMount:a.onMount.bind(a),useState:null,router:{use:a.router.use.bind(a)},bindMount:a.bindMount.bind(a),memoize:a.memoize.bind(a),createComponent:a.createComponent.bind(a),isChild:!1,useState:a.useState.bind(a),parseStyle:a.parseStyle.bind(a),bind:a.bind.bind(a),useRef:a.useRef.bind(a),useReducer:a.useReducer.bind(a),hydrate:a.hydrate.bind(a)};a.render=n.render,a=n}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");a.reset(),a.components={},a.request=t,a.response=s,a.router.use&&!a.isChild?await new Promise((async r=>{if(n(e.default))if(n(e.default))switch(await a.router.use(t,s),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing",t.pause):(clearInterval(e),r())}),1e3);break;case!1:r()}else r();else switch(await e.default.apply(a,[t,s]),await a.router.use(t,s),t.pause){case!0:let e=setInterval((()=>{t.pause?console.log("still pausing request",t.url):(clearInterval(e),r())}),1e3);break;case!1:r()}})):a.router.use&&a.isChild&&console.warn("Router.use() is not supported in child components");const i=await a.render();document.querySelector("#root").innerHTML=i,a.bindMount(),a.onMount()}catch(e){console.error(e)}},setQuery:e=>{let t="";Object.keys(e).forEach(((s,n)=>{t+=`${0===n?"?":"&"}${s}=${e[s]}`}));let s=window.location.hash.split("?")[0];t=t.replace("/","-").replaceAll("/","-"),window.location.hash=`${s}${t}`},send:e=>{document.querySelector("#root").innerHTML=e},json:e=>{const t=document.querySelector("#root");t.innerHTML="";const s=document.createElement("pre");s.textContent=JSON.stringify(e,null,2),t.appendChild(s)}};middlewares.forEach((e=>{e(a,i)})),n&&n.handler(a,i)}}window.VaderRouter=VaderRouter;export default VaderRouter;
|
package/runtime/vader.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let o=new Component(t);if(s(e
|
|
1
|
+
window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let o=new Component(t);if(s(e))r.props=t,r.children=n,r.props.children=n.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=t.key||null,o=r;else{e.toString();o.key=e.toString().split('key="')[1]?e.toString().split('key="')[1].split('"')[0]:null;let n={key:o.key,render:()=>e.apply(o,[t]),request:this.request,isChild:!0,response:this.response,params:this.request.params,queryParams:this.request.query,reset:o.reset.bind(o),onMount:o.onMount.bind(o),useState:null,router:{use:o.router.use.bind(o)},bindMount:o.bindMount.bind(o),memoize:o.memoize.bind(o),createComponent:o.createComponent.bind(o),isChild:!1,useState:o.useState.bind(o),parseStyle:o.parseStyle.bind(o),bind:o.bind.bind(o),useRef:o.useRef.bind(o),request:this.request,response:this.response,useReducer:o.useReducer.bind(o),hydrate:o.hydrate.bind(o),parentNoe:this};o.render=n.render,o=n}return this.components[t.key]||(this.components[t.key]=o),!this.children.includes(o)&&this.children.push(o),this.components[t.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){if(!e.key)throw new Error("Component must have a static key");if(!0==!this.memoizes.includes(e.key))this.memoizes.push(e.key),this.components[e.key]=e;let t=this.components[e.key];t.bindMount(),t.parentNode=this,t.props=e.props,t.request=this.request,t.response=this.response;let n=t.render();return n&&n.split(">,").length>1&&(n=n.replaceAll(">,",">")),`<div key="${e.key}">${n}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((n=>{let s=e[n];n=n.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${n}:${s};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s],o=t[s];r&&o&&!r.isEqualNode(o)&&n.push({type:"replace",old:r,new:o.cloneNode(!0)})}return n}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.parentNode.replaceChild(e.new,e.old);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){console.log(e);let t=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[ref="${e}"]`),n=document.querySelector(`[ref="${e}"]`);console.log(t,n)}else{let e=this.key?document.querySelector(`[key="${this.key}"]`):null,t=(new DOMParser).parseFromString(this.render(),"text/html").body;if(t=document.createElement("div").appendChild(t),!e&&(e=document.querySelector(`[key="${t.attributes?.key?.value||null}"]`)),!e)return void console.error('Hydration failed, component not found got ensure you have set key="a value" on the component or this.key inside of function or render method body');t.querySelectorAll("*").forEach((e=>{e.hasAttribute("key")&&e.innerHTML!==document.querySelector(`[key="${e.attributes.key.value}"]`).innerHTML&&document.querySelector(`[key="${e.attributes.key.value}"]`).replaceWith(e)}))}}patch(e,t){const n=this.domDifference(e,t);this.updateChangedElements(n)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,n,s,...r){n=n+this.key||2022;let o={},i=(s=s.replace(/,,/g,",")).replaceAll(",,",",");for(var u in r){let e=r[u];o[i.split(",")[u]]=e}s=s.replace(",,",",");let a=null;try{a=new Function(`event, ${s}`,` \n return (async (event, ${s}) => { \n ${e.toString()}\n })(event, ${Object.keys(o).join(",")}) \n `)}catch(e){let{message:t}=e;console.error(`Error in function ${n} ${t}`)}return a=a.bind(this),this.functions.find((e=>e.ref===n))||document.addEventListener(`$dispatch_#id=${n}`,(e=>{let{name:t,event:s}=e.detail;if(t===n){let e=this.functions.find((e=>e.ref===n)).params;Object.keys(e).forEach((t=>{e[t]instanceof CustomEvent&&delete e[t],void 0===e[t]?delete e[t]:e[t]})),a(s,...Object.values(e))}})),window.callFunction=(e,t)=>{document.dispatchEvent(new CustomEvent(`$dispatch_#id=${e}`,{detail:{name:e,params:null,event:t}}))},!this.functions.find((e=>e.ref===n))&&this.functions.push({ref:n,params:o}),t?e:`((event)=>{event.target.ev = event; callFunction('${n}', event.target.ev)})(event)`}useState(e,t){this.state[e]||(this.state[e]=t);let n=()=>this.state[e],s=n();return[s,(t,r)=>{this.state[e]=t,this.hydrate(r),s=n()}]}useRef(e=null,t){this.state[e]||(this.state[e]=t);return{bind:e+this.key,current:(()=>document.querySelector(`[ref="${e+this.key}"]`)||t)()}}useReducer(e=null,t,n=null){this.state[e]||(this.state[e]=t);const s=()=>this.state[e];let r=s();return[s(),(t,o)=>{const i=n(r,t)??t;this.state[e]=i,this.hydrate(o),r=s()}]}render(){}checkIFMounted(){new MutationObserver((e=>{e.forEach((e=>{e.target.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.onMount(),this.mounted=!0),Array.from(e.removedNodes).find((e=>e.attributes&&e.attributes.key&&e.attributes.key.value===this.key))&&(this.onUnmount(),this.reset())}))})).observe(document.body,{childList:!0,subtree:!0})}onMount(){}onUnmount(){}}export const useState=(e,t)=>{states[e]||(states[e]=t);return[states[e],(t,n)=>{states[e]=t,this.hydrate(n)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount};
|
package/vader.js
CHANGED
|
@@ -178,8 +178,7 @@ function Compiler(func, file) {
|
|
|
178
178
|
newvalue = newvalue.trim();
|
|
179
179
|
if (newvalue.endsWith("}")) {
|
|
180
180
|
newvalue = newvalue.replace("}", "");
|
|
181
|
-
}
|
|
182
|
-
console.log(newvalue)
|
|
181
|
+
}
|
|
183
182
|
functionparams.length > 0 ? params = params + ',' + functionparams.map((e) => e.name).join(',') : null
|
|
184
183
|
newvalue = newvalue.split('\n').map(line => line.trim() ? line.trim() + ';' : line).join('\n');
|
|
185
184
|
newvalue = newvalue.replaceAll(',,', ',')
|
|
@@ -518,13 +517,13 @@ function Compiler(func, file) {
|
|
|
518
517
|
return match;
|
|
519
518
|
});
|
|
520
519
|
|
|
520
|
+
string = string.replaceAll(/\$\{\/\*.*\*\/\}/gs, "");
|
|
521
521
|
string = string.replaceAll("<>", "`").replaceAll("</>", "`");
|
|
522
522
|
string = parseComponents(string);
|
|
523
523
|
|
|
524
524
|
string = string
|
|
525
525
|
.replaceAll("className", "class")
|
|
526
|
-
.replaceAll("classname", "class");
|
|
527
|
-
string = string.replaceAll(/\$\{\/\*.*\*\/\}/gs, "");
|
|
526
|
+
.replaceAll("classname", "class");
|
|
528
527
|
|
|
529
528
|
string = string.replaceAll('../src', './src')
|
|
530
529
|
string += `\n\n //wascompiled`;
|
|
@@ -591,8 +590,10 @@ function Compiler(func, file) {
|
|
|
591
590
|
path = path.replace(/'/g, '').trim().replace(/"/g, '').trim()
|
|
592
591
|
// remove double / from path
|
|
593
592
|
path = path.split('//').join('/')
|
|
594
|
-
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')
|
|
595
|
-
|
|
593
|
+
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')
|
|
594
|
+
&& !path.startsWith('/public')
|
|
595
|
+
) {
|
|
596
|
+
path = '/src/' + path
|
|
596
597
|
}
|
|
597
598
|
|
|
598
599
|
path = path.replaceAll('.jsx', '.js');
|
|
@@ -635,20 +636,23 @@ function Compiler(func, file) {
|
|
|
635
636
|
}
|
|
636
637
|
path = path.replace(/'/g, '').trim().replace(/"/g, '').trim()
|
|
637
638
|
// remove double / from path
|
|
638
|
-
path = path.split('//').join('/')
|
|
639
|
-
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src')) {
|
|
639
|
+
path = path.split('//').join('/')
|
|
640
|
+
if (!path.startsWith('./') && !path.includes('/vader.js') && !path.startsWith('src') && !path.startsWith('public')) {
|
|
640
641
|
path.includes('src') ? path.split('src')[1] : null
|
|
641
642
|
path = '/src/' + path
|
|
642
|
-
} else if (path.startsWith('src')) {
|
|
643
|
+
} else if (path.startsWith('src') || path.startsWith('public')) {
|
|
643
644
|
path = '/' + path
|
|
644
645
|
}
|
|
646
|
+
console.log(path)
|
|
645
647
|
path = path.replaceAll('.jsx', '.js');
|
|
646
648
|
|
|
647
649
|
|
|
648
650
|
string = string.replace(beforePath, "'" + path + "'")
|
|
649
651
|
}
|
|
650
652
|
let html = fs.existsSync(process.cwd() + '/dist/index.html') ? fs.readFileSync(process.cwd() + '/dist/index.html', 'utf8') : ''
|
|
651
|
-
if (!html.includes(`<link rel="preload" href="${path.replace(/'/g, '').trim()}" as="${path.replace(/'/g, '').trim().includes('.css') ? 'style' : 'script'}">`)
|
|
653
|
+
if (!html.includes(`<link rel="preload" href="${path.replace(/'/g, '').trim()}" as="${path.replace(/'/g, '').trim().includes('.css') ? 'style' : 'script'}">`)
|
|
654
|
+
&& !path.includes('.module.css')
|
|
655
|
+
) {
|
|
652
656
|
if (!html.includes(`</head>`)) {
|
|
653
657
|
throw new Error('Could not find </head> in index.html')
|
|
654
658
|
}
|
|
@@ -677,6 +681,7 @@ let exec = await import('child_process').then((child) => {
|
|
|
677
681
|
return child.exec
|
|
678
682
|
})
|
|
679
683
|
globalThis.isBuilding = false
|
|
684
|
+
globalThis.isWriting = null
|
|
680
685
|
async function Build() {
|
|
681
686
|
globalThis.isBuilding = true
|
|
682
687
|
console.log('Compiling......')
|
|
@@ -684,14 +689,20 @@ async function Build() {
|
|
|
684
689
|
let text = await fs.readFileSync(file, "utf8");
|
|
685
690
|
return text;
|
|
686
691
|
};
|
|
692
|
+
|
|
687
693
|
let writer = async (file, data) => {
|
|
694
|
+
globalThis.isWriting = file
|
|
688
695
|
switch (true) {
|
|
689
696
|
case !fs.existsSync(file):
|
|
690
697
|
fs.mkdirSync(file.split('/').slice(0, -1).join('/'), { recursive: true })
|
|
691
698
|
break;
|
|
692
699
|
}
|
|
693
|
-
|
|
700
|
+
if(globalThis.isWriting !== file){
|
|
701
|
+
return
|
|
702
|
+
}
|
|
703
|
+
await fs.writeFileSync(file, data);
|
|
694
704
|
|
|
705
|
+
globalThis.isWriting = null
|
|
695
706
|
return { _written: true };
|
|
696
707
|
};
|
|
697
708
|
|
|
@@ -746,14 +757,18 @@ async function Build() {
|
|
|
746
757
|
await writer(process.cwd() + "/dist/pages/" + fileName.replace('.jsx', '.js'), data).then(async () => {
|
|
747
758
|
|
|
748
759
|
let { minify } = await import('terser')
|
|
760
|
+
|
|
749
761
|
try {
|
|
750
762
|
let minified = await minify(data, {
|
|
751
|
-
|
|
763
|
+
toplevel: true,
|
|
764
|
+
ecma:2016,
|
|
765
|
+
enclose:false,
|
|
752
766
|
module: true,
|
|
753
767
|
compress: true,
|
|
754
|
-
mangle: true,
|
|
755
768
|
keep_fnames: true,
|
|
769
|
+
|
|
756
770
|
})
|
|
771
|
+
|
|
757
772
|
await writer(process.cwd() + "/dist/pages/" + fileName.replace('.jsx', '.js'), minified.code)
|
|
758
773
|
} catch (error) {
|
|
759
774
|
console.log(error)
|
|
@@ -895,13 +910,13 @@ Vader.js v1.3.3
|
|
|
895
910
|
|
|
896
911
|
|
|
897
912
|
Array.from(Array(3).keys()).forEach((i) => {
|
|
898
|
-
let p = `${process.cwd()}${i == 0 ? '/pages/' : i == 1 ? '/src/' : '/public/'}`
|
|
899
|
-
|
|
913
|
+
let p = `${process.cwd()}${i == 0 ? '/pages/' : i == 1 ? '/src/' : '/public/'}`
|
|
900
914
|
watch(p
|
|
901
915
|
, { recursive: true }, (event, filename) => {
|
|
902
916
|
if (event == 'change'
|
|
903
917
|
&& !globalThis.isBuilding
|
|
904
918
|
) {
|
|
919
|
+
|
|
905
920
|
Build()
|
|
906
921
|
}
|
|
907
922
|
}).on('error', (err) => console.log(err))
|