vaderjs 1.3.3-2124766be812 → 1.3.3-4943326ca409

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/README.md CHANGED
@@ -14,13 +14,13 @@
14
14
  [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Postr-Inc/Vader.js/blob/main/LICENSE) [![npm version](https://img.shields.io/npm/v/vaderjs.svg?style=flat)](https://www.npmjs.com/package/vaderjs)
15
15
 
16
16
 
17
- > Do not use any alpha versions as these where changed multiple times any version under latest is considered lts and are deemed to be stable
17
+ > Do not use any alpha versions as these where changed multiple times any version under beta is considered lts and are deemed to be stable
18
18
  ## Get Started
19
19
 
20
20
  2. Install vaderjs
21
21
 
22
22
  ```bash
23
- npm i vaderjs@latest
23
+ npm i vaderjs@beta
24
24
  ```
25
25
 
26
26
  4. Create Proper Folders
@@ -81,7 +81,7 @@ export default function(req, res){
81
81
 
82
82
  return <>
83
83
  <h1>${count}</h1>
84
- <button onClick={(event)=>{setCount(count + 1)}}>
84
+ <button onClick={(count, setCount)=>{setCount(count + 1)}}>
85
85
  </>
86
86
  }
87
87
 
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "vaderjs",
3
3
  "description": "A Reactive library aimed to helping you build reactive applications inspired by react.js",
4
4
  "module": "vader.js",
5
- "version": "1.3.3-2124766be812",
5
+ "version": "1.3.3-4943326ca409",
6
6
  "bin": {
7
7
  "vader": "./vader.js"
8
8
  },
@@ -29,8 +29,7 @@
29
29
  "dependencies": {
30
30
  "glob": "latest",
31
31
  "puppeteer":"latest",
32
- "dotenv":"latest",
33
- "prettier": "latest"
32
+ "dotenv":"latest"
34
33
 
35
34
  }
36
35
  }
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 s=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(s),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,s){function isClass(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=isClass(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let i=[];Object.keys(t).forEach((e=>{if(e.startsWith("$props")&&(i.push(t[e]),delete t[e]),e.startsWith("$_ternary")){let s=t[e];delete t[e],Object.keys(s).forEach((e=>{t[e]=s[e]})),console.log(t)}}));let n=new Component(t);if(isClass(e))r.props=t||{},r.props.children=s.join("")||[],r.props.children=s.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=r.props.key?r.props.key:Math.random(),n=r;else{e.toString();n.key=e.toString().split('key="')[1]?e.toString().split('key="')[1].split('"')[0]:null,t=t?{...t,...i.reduce(((e,t)=>({...e,...t})),{}),children:s.join("")||[]}:{children:s.join("")||[]};let r={key:n.key?n.key:Math.random(),isUnique:!!n.key,render:()=>e.apply(n,[t]),request:this.request,isChild:!0,response:this.response,params:this.request.params,queryParams:this.request.query,reset:n.reset.bind(n),onMount:n.onMount.bind(n),useState:null,router:{use:n.router.use.bind(n)},bindMount:n.bindMount.bind(n),memoize:n.memoize.bind(n),createComponent:n.createComponent.bind(n),isChild:!1,useState:n.useState.bind(n),parseStyle:n.parseStyle.bind(n),bind:n.bind.bind(n),useRef:n.useRef.bind(n),request:this.request,response:this.response,useReducer:n.useReducer.bind(n),hydrate:n.hydrate.bind(n),onUnmount:n.onUnmount.bind(n),parentNoe:this,props:{...t,children:s.join("")||[]}};n.render=r.render,n=r,n.props.children=s.join("")||[]}return this.components[n.key]||(this.components[n.key]=n),!this.children.includes(n)&&this.children.push(n),this.components[n.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){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,t.onMount=e.onMount.bind(e),t.onUnmount=e.onUnmount.bind(e);let s=t.render();return s&&s.split(">,").length>1&&(s=s.replaceAll(">,",">")),t.nokey?s:`<div key="${t.key}">${s}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((s=>{let r=e[s];s=s.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${s}:${r};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let s=[];for(let r=0;r<e.length;r++){let i=e[r],n=t[r];i&&n&&!i.isEqualNode(n)&&s.push({type:"replace",old:i,new:n.cloneNode(!0)})}return s}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.replaceWith(e.new);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){console.log("hydrating");let t=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[ref="${e}"]`);document.querySelector(`[ref="${e}"]`);document.querySelector(`[ref="${e}"]`).replaceWith(t)}else{if(this.key?document.querySelector(`[key="${this.key}"]`):null){let e=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[key="${this.key}"]`),t=document.querySelector(`[key="${this.key}"]`),s=this.domDifference(t.children,e.children);this.updateChangedElements(s)}}}patch(e,t){const s=this.domDifference(e,t);this.updateChangedElements(s)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,s,r,...i){return s+=this.key,window["callFunctions"+this.key]=(e,t)=>{console.log("called");let s=this.functions.find((t=>t.ref===e));s&&s.func(t)},this.functions.find((e=>e.ref===s))||this.functions.push({ref:s,func:e}),t?e:`((event)=>{callFunctions${this.key} ? callFunctions${this.key}('${s}', event) : null})(event)`}setState(e,t){this.state=e,this.hydrate(t)}useState(e,t){this.state.hasOwnProperty(e)||(this.state[e]=t);return[(()=>this.state[e])(),(t,s)=>{this.state[e]=t,this.hydrate(s)}]}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,s=null){this.state[e]||(this.state[e]=t);const getValue=()=>this.state[e];let r=getValue();return[getValue(),(t,i)=>{const n=s(r,t)??t;this.state[e]=n,this.hydrate(i),r=getValue()}]}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)=>{this.state[e]||(this.state[e]=t);return[states[e],(t,s)=>{states[e]=t,this.hydrate(s)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export class Link extends Component{constructor(e){super(e),this.props=e,this.link=document.createElement("a"),this.key=e.href+Math.random(),this.nokey=!0}render(){return this.link.innerHTML=this.props.children,this.link.setAttribute("id",this.props?.href),this.link.style=this.props?.style,this.link.setAttribute("class",this.props?.class||this.props?.className),this.link.setAttribute("onclick",`window.history.pushState({}, '', '${this.props?.href}'); window.dispatchEvent(new Event('popstate'));`),this.link.outerHTML}}export class Image extends Component{constructor(e){super(e),this.props={src:e.src,class:e.class,style:e.style,blur:e.blur,width:e.width,height:e.height,optimize:e.optimize||!0,loader:e.loader||!0,alt:e.alt||"image",ref:e.ref||null},this.key=e.src+Math.random(),this.img=document.createElement("img"),this.placeholder=document.createElement("div")}render(){if(window.isServer)return"";let[e,t]=this.useState("loaded",!1),s=this.useRef("hookref",null),r=this.props.width?this.props.width:window.innerWidth/2,i=this.props.height?this.props.height:window.innerHeight/2;if(!this.props.src)throw new Error("Image src is required");return this.img.setAttribute("src",this.props.src),this.img.setAttribute("class",this.props.class),this.img.setAttribute("style",this.props.style?this.props.style:""),this.img.setAttribute("width",r),this.img.setAttribute("ref",s.bind),this.img.referrerPolicy="no-referrer",this.img.setAttribute("height",i),this.img.setAttribute("loading","lazy"),this.img.setAttribute("alt",this.props.alt),this.props.blur&&this.img.setAttribute("style",`filter: blur(${this.props.blur}px);`),this.props.optimize&&this.img.setAttribute("style",`image-rendering: -webkit-optimize-contrast; object-fit: cover; object-position: center; ${this.props.style?this.props.style:""}`),!this.props.loader||e||window.isServer||(this.placeholder.setAttribute("style",`width: ${r}px; height: ${i}px; background: #eee;`),this.placeholder.setAttribute("class","vader-image-placeholder"),this.placeholder.innerHTML=this.props.loader,window.isServer)?void 0:(this.img.onload=()=>{t(!0,s.bind)},`<span ref="${s.bind}">${e?this.img.outerHTML:this.placeholder.outerHTML}</span>`)}}export class Html extends Component{constructor(e){super(e),this.props={children:e.children,lang:e.lang||"en",attributes:e.attributes||{}},this.key="html",this.html=document.createElement("div")}render(){return window.isServer?(this.html.innerHTML=this.props.children,this.html.setAttribute("lang",this.props.lang?this.props.lang:"en"),this.props.attributes&&Object.keys(this.props.attributes).forEach((e=>{this.html.setAttribute(e,this.props.attributes[e])})),this.html.innerHTML):this.props.children}onMount(){console.log("Document Has Been Mounted")}}export class Head extends Component{constructor(e){super(e),this.props=e,this.key="head",this.head=document.createElement("head")}render(){return""}onMount(){if(!this.state.hasMounted&&window.isServer){document.head.innerHTML=this.props.children+document.head.innerHTML,document.querySelectorAll("script[eager]").forEach((async e=>{if(!e.getAttribute("src"))throw new Error("Eager scripts must be external");e.remove();let t=e.getAttribute("src"),s=document.createElement("script"),r=await fetch(t).then((e=>e.text()));s.innerHTML=r,s.setAttribute("srcid",t),document.querySelector(`[srcid="${t}"]`)||document.head.prepend(s)})),this.state.hasMounted=!0}}}export class Script extends Component{constructor(e){super(e),this.props={children:e.children},this.key="script",this.script=document.createElement("script")}render(){return this.script.innerHTML=this.props.children.split("\n").join(";\n"),this.script.outerHTML}onMount(){document.head.appendChild(this.script),document.body.querySelector(`[key="${this.key}"]`).remove()}}export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount,Link:Link,Image:Image,Head:Head,Script:Script,Html:Html};
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 s=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(s),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,s){function isClass(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=isClass(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let i=new Component(t);if(isClass(e))r.props=t||{},r.props.children=s.join("")||[],r.props.children=s.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=r.props.key?r.props.key:Math.random(),i=r;else{e.toString();i.key=e.toString().split('key="')[1]?e.toString().split('key="')[1].split('"')[0]:null;let r=[];Object.keys(t).forEach((e=>{if(e.startsWith("$props")&&(r.push(t[e]),delete t[e]),e.startsWith("$_ternary")){let s=t[e];delete t[e],Object.keys(s).forEach((e=>{t[e]=s[e]}))}})),t=t?{...t,...r.reduce(((e,t)=>({...e,...t})),{}),children:s.join("")||[]}:{children:s.join("")||[]};let n={key:i.key?i.key:Math.random(),isUnique:!!i.key,render:()=>e.apply(i,[t]),request:this.request,isChild:!0,response:this.response,params:this.request.params,queryParams:this.request.query,reset:i.reset.bind(i),onMount:i.onMount.bind(i),useState:null,router:{use:i.router.use.bind(i)},bindMount:i.bindMount.bind(i),memoize:i.memoize.bind(i),createComponent:i.createComponent.bind(i),isChild:!1,useState:i.useState.bind(i),parseStyle:i.parseStyle.bind(i),bind:i.bind.bind(i),useRef:i.useRef.bind(i),request:this.request,response:this.response,useReducer:i.useReducer.bind(i),hydrate:i.hydrate.bind(i),onUnmount:i.onUnmount.bind(i),parentNoe:this,props:{...t,children:s.join("")||[]}};i.render=n.render,i=n,i.props.children=s.join("")||[]}return this.components[i.key]||(this.components[i.key]=i),!this.children.includes(i)&&this.children.push(i),this.components[i.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){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,t.onMount=e.onMount.bind(e),t.onUnmount=e.onUnmount.bind(e);let s=t.render();return s&&s.split(">,").length>1&&(s=s.replaceAll(">,",">")),t.nokey?s:`<div key="${t.key}">${s}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((s=>{let r=e[s];s=s.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${s}:${r};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let s=[];for(let r=0;r<e.length;r++){let i=e[r],n=t[r];i&&n&&!i.isEqualNode(n)&&s.push({type:"replace",old:i,new:n.cloneNode(!0)})}return s}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.replaceWith(e.new);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){console.log("hydrating");let t=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[ref="${e}"]`);document.querySelector(`[ref="${e}"]`);document.querySelector(`[ref="${e}"]`).replaceWith(t)}else{if(this.key?document.querySelector(`[key="${this.key}"]`):null){let e=(new DOMParser).parseFromString(this.render(),"text/html").body.querySelector(`[key="${this.key}"]`),t=document.querySelector(`[key="${this.key}"]`),s=this.domDifference(t.children,e.children);this.updateChangedElements(s)}}}patch(e,t){const s=this.domDifference(e,t);this.updateChangedElements(s)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,s,r,...i){return s+=this.key,window["callFunctions"+this.key]=(e,t)=>{console.log("called");let s=this.functions.find((t=>t.ref===e));s&&s.func(t)},this.functions.find((e=>e.ref===s))||this.functions.push({ref:s,func:e}),t?e:`((event)=>{callFunctions${this.key} ? callFunctions${this.key}('${s}', event) : null})(event)`}setState(e,t){this.state=e,this.hydrate(t)}useState(e,t){this.state.hasOwnProperty(e)||(this.state[e]=t);return[(()=>this.state[e])(),(t,s)=>{this.state[e]=t,this.hydrate(s)}]}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,s=null){this.state[e]||(this.state[e]=t);const getValue=()=>this.state[e];let r=getValue();return[getValue(),(t,i)=>{const n=s(r,t)??t;this.state[e]=n,this.hydrate(i),r=getValue()}]}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)=>{this.state[e]||(this.state[e]=t);return[states[e],(t,s)=>{states[e]=t,this.hydrate(s)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export class Link extends Component{constructor(e){super(e),this.props=e,this.link=document.createElement("a"),this.key=e.href+Math.random(),this.nokey=!0}render(){return this.link.innerHTML=this.props.children,this.link.setAttribute("id",this.props?.href),this.link.style=this.props?.style,this.link.setAttribute("class",this.props?.class),this.link.setAttribute("onclick",`window.history.pushState({}, '', '${this.props?.href}'); window.dispatchEvent(new Event('popstate'));`),this.link.outerHTML}}export class Image extends Component{constructor(e){super(e),this.props={src:e.src,class:e.class,style:e.style,blur:e.blur,width:e.width,height:e.height,optimize:e.optimize||!0,loader:e.loader||!0,alt:e.alt||"image",ref:e.ref||null},this.key=e.src+Math.random(),this.img=document.createElement("img"),this.placeholder=document.createElement("div")}render(){if(window.isServer)return"";let[e,t]=this.useState("loaded",!1),s=this.useRef("hookref",null),r=this.props.width?this.props.width:window.innerWidth/2,i=this.props.height?this.props.height:window.innerHeight/2;if(!this.props.src)throw new Error("Image src is required");return this.img.setAttribute("src",this.props.src),this.img.setAttribute("class",this.props.class),this.img.setAttribute("style",this.props.style?this.props.style:""),this.img.setAttribute("width",r),this.img.setAttribute("ref",s.bind),this.img.referrerPolicy="no-referrer",this.img.setAttribute("height",i),this.img.setAttribute("loading","lazy"),this.img.setAttribute("alt",this.props.alt),this.props.blur&&this.img.setAttribute("style",`filter: blur(${this.props.blur}px);`),this.props.optimize&&this.img.setAttribute("style",`image-rendering: -webkit-optimize-contrast; object-fit: cover; object-position: center; ${this.props.style?this.props.style:""}`),!this.props.loader||e||window.isServer||(this.placeholder.setAttribute("style",`width: ${r}px; height: ${i}px; background: #eee;`),this.placeholder.setAttribute("class","vader-image-placeholder"),this.placeholder.innerHTML=this.props.loader,window.isServer)?void 0:(this.img.onload=()=>{t(!0,s.bind)},`<span ref="${s.bind}">${e?this.img.outerHTML:this.placeholder.outerHTML}</span>`)}}export class Html extends Component{constructor(e){super(e),this.props={children:e.children,lang:e.lang||"en",attributes:e.attributes||{}},this.key="html",this.html=document.createElement("div")}render(){return window.isServer?(this.html.innerHTML=this.props.children,this.html.setAttribute("lang",this.props.lang?this.props.lang:"en"),this.props.attributes&&Object.keys(this.props.attributes).forEach((e=>{this.html.setAttribute(e,this.props.attributes[e])})),this.html.innerHTML):this.props.children}onMount(){console.log("Document Has Been Mounted")}}export class Head extends Component{constructor(e){super(e),this.props=e,this.key="head",this.head=document.createElement("head")}render(){return""}onMount(){if(!this.state.hasMounted&&window.isServer){document.head.innerHTML=this.props.children+document.head.innerHTML,document.querySelectorAll("script[eager]").forEach((async e=>{if(!e.getAttribute("src"))throw new Error("Eager scripts must be external");e.remove();let t=e.getAttribute("src"),s=document.createElement("script"),r=await fetch(t).then((e=>e.text()));s.innerHTML=r,s.setAttribute("srcid",t),document.querySelector(`[srcid="${t}"]`)||document.head.prepend(s)})),this.state.hasMounted=!0}}}export class Script extends Component{constructor(e){super(e),this.props={children:e.children},this.key="script",this.script=document.createElement("script")}render(){return this.script.innerHTML=this.props.children.split("\n").join(";\n"),this.script.outerHTML}onMount(){document.head.appendChild(this.script),document.body.querySelector(`[key="${this.key}"]`).remove()}}export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount,Link:Link,Image:Image,Head:Head,Script:Script,Html:Html};
package/vader.js CHANGED
@@ -4,7 +4,6 @@ import { glob, globSync, globStream, globStreamSync, Glob, } from 'glob'
4
4
  import puppeteer from 'puppeteer';
5
5
  import http from 'http'
6
6
  import { WebSocketServer } from 'ws'
7
- import prettier from 'prettier'
8
7
  import { watch } from "fs";
9
8
  import path from 'path'
10
9
  let config = await import('file://' + process.cwd() + '/vader.config.js').then((e) => e.default || e)
@@ -23,8 +22,16 @@ let writer = async (file, data) => {
23
22
  globalThis.isWriting = null
24
23
  return { _written: true };
25
24
  };
26
-
27
- let bundleSize = 0;
25
+
26
+ let start = Date.now()
27
+ let bundleSize = 0;
28
+ let errorCodes = {
29
+ "SyntaxError: Unexpected token '<'": "You forgot to enclose tags in a fragment <></>",
30
+ }
31
+ /**
32
+ * define directories
33
+ */
34
+
28
35
 
29
36
  if (!fs.existsSync(process.cwd() + '/dist')) {
30
37
  fs.mkdirSync(process.cwd() + '/dist')
@@ -33,21 +40,64 @@ if (!fs.existsSync(process.cwd() + '/dist')) {
33
40
 
34
41
 
35
42
 
36
- if (typeof process.env.isCloudflare !== "undefined" || !fs.existsSync(process.cwd() + '/dist/index.html')) {
37
- fs.writeFileSync(process.cwd() + "/dist/index.html", '')
43
+ if (typeof process.env.isCloudflare !== "undefined" || !fs.existsSync(process.cwd() + '/dist/index.html')) {
44
+ let htmlFile = fs.readFileSync(process.cwd() + "/node_modules/vaderjs/runtime/index.html", 'utf8')
45
+ fs.writeFileSync(process.cwd() + "/dist/index.html", htmlFile)
38
46
  }
39
47
 
40
48
 
41
49
 
42
50
  function Compiler(func, file) {
43
- let string = func;
51
+ let string = func;
52
+ // Remove block comments
53
+
44
54
  let returns = []
45
55
  let comments = string.match(/\{\s*\/\*.*\*\/\s*}/gs)?.map((comment) => comment.trim());
46
56
 
47
-
48
-
49
-
50
-
57
+ let savedfuncnames = [];
58
+ let functions = string.match(
59
+ /(?:const|let)\s*([a-zA-Z0-9_-]+)\s*=\s*function\s*\(([^)]*)\)|function\s*([a-zA-Z0-9_-]+)\s*\(([^)]*)\)/gs
60
+ )
61
+ ?.map((match) => match.trim());
62
+
63
+ let functionNames = [];
64
+
65
+
66
+ functions && functions.forEach((func) => {
67
+ if (
68
+ !func.match(
69
+ /(?:const|let)\s*([a-zA-Z0-9_-]+)\s*=\s*function\s*\(([^)]*)\)|function\s*([a-zA-Z0-9_-]+)\s*\(([^)]*)\)/gs
70
+ )
71
+ ) {
72
+ return;
73
+ }
74
+
75
+ let name = func.split(" ")[1].split("(")[0].trim();
76
+
77
+ let lines = string.match(/return\s*\<>.*\<\/>/gs);
78
+
79
+ if (lines) {
80
+ for (let i = 0; i < lines.length; i++) {
81
+ let line = lines[i];
82
+
83
+ if (!functionNames.includes(name)) {
84
+ functionNames.push(name);
85
+ }
86
+ }
87
+ }
88
+ });
89
+
90
+ // get all Obj({}) and parse to JSON.stringify
91
+
92
+ let objects = string.match(/Obj\({.*}\)/gs);
93
+
94
+ objects && objects.forEach((obj) => {
95
+ let key = obj.split("Obj")[1].split("(")[1].split(")")[0].trim();
96
+ let newobj = obj.replaceAll(`Obj(${key})`, `${key}`);
97
+ // let newobj = obj.replaceAll(`Obj(${key})`, `JSON.parse('${key}')`)
98
+ string = string.replaceAll(obj, `this.handleObject('${newobj}')`);
99
+ });
100
+
51
101
 
52
102
  let childs = [];
53
103
 
@@ -85,8 +135,6 @@ function Compiler(func, file) {
85
135
  e = e.replace(/:(.*)/gs, '={$1.join(" ")}')
86
136
  break;
87
137
  default:
88
- e = e.replace(/:(.*)/gs, '=$1')
89
- break;
90
138
  }
91
139
 
92
140
  return e.trim()
@@ -109,9 +157,11 @@ function Compiler(func, file) {
109
157
  const attributeRegex =
110
158
  /\s*([a-zA-Z0-9_-]+)(\s*=\s*("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|\{(?:[^{}]|(?:\{(?:[^{}]|(?:\{[^{}]*\})*)*\})*)*\}|(?:\([^)]*\)|\{[^}]*\}|()=>\s*(?:\{[^}]*\})?)|\[[^\]]*\]))?/gs;
111
159
 
112
-
160
+ // <div $={{color: 'red'}}></div>
161
+
162
+
113
163
 
114
-
164
+ // only return elements with attribute {()=>{}} or if it also has parameters ex: onclick={(event)=>{console.log(event)}} also get muti line functions or onClick=()=>{}
115
165
  const functionAttributeRegex = /\s*([a-zA-Z0-9_-]+)(\s*=\s*{((?:[^{}]|(?:\{(?:[^{}]|(?:\{[^{}]*\})*)*\})*)*)})/gs;
116
166
 
117
167
  let attributesList = [];
@@ -139,10 +189,27 @@ function Compiler(func, file) {
139
189
  if (attributeValue && attributeValue.includes("=>") || attributeValue && attributeValue.includes("function")
140
190
  && !spreadFunctions.includes(attributeValue)
141
191
  ) {
142
-
192
+ let functionparams = [];
193
+ // ref with no numbers
143
194
  let ref = Math.random().toString(36).substring(2).split('').filter((e) => !Number(e)).join('')
144
195
  let old = `${attributeName}${attributeValue}`
145
-
196
+ functionNames.forEach((name) => {
197
+ string.split("\n").forEach((line) => {
198
+ if (line.includes(name) && line.includes("function")) {
199
+ line = line.trim();
200
+ line = line.replace(/\s+/g, " ");
201
+
202
+ let ps = line.split("(").slice(1).join("(").split(")")[0].trim();
203
+
204
+ // remove comments
205
+ ps = ps.match(/\/\*.*\*\//gs)
206
+ ? ps.replace(ps.match(/\/\*.*\*\//gs)[0], "")
207
+ : ps;
208
+ functionparams.push({ ref: ref, name: name, params: ps });
209
+
210
+ }
211
+ });
212
+ });
146
213
  let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
147
214
  let isJSXComponent = false;
148
215
  elementMatch.forEach((element) => {
@@ -196,7 +263,7 @@ function Compiler(func, file) {
196
263
  newvalue = newvalue.replace(/}\s*$/, '');
197
264
 
198
265
 
199
-
266
+ functionparams.length > 0 ? params = params + ',' + functionparams.map((e) => e.name).join(',') : null
200
267
 
201
268
  newvalue = newvalue.replaceAll(',,', ',')
202
269
  let paramnames = params ? params.split(',').map((e) => e.trim()) : null
@@ -247,7 +314,8 @@ function Compiler(func, file) {
247
314
  let returns = code.match(/return\s*\<>.*\<\/>|return\s*\(.*\)/gs);
248
315
 
249
316
  return returns || [];
250
- }
317
+ }
318
+ // throw error if return is not wrapped in <></> or
251
319
  if (string.match(/return\s*\<>|return\s*\(.*\)/gs) && !string.match(/return\s*\<>.*\<\/>|return\s*\(.*\)/gs)
252
320
  || string.match(/return\s*\<[a-zA-Z0-9_-]+.*>/gs)
253
321
  ) {
@@ -280,7 +348,8 @@ function Compiler(func, file) {
280
348
  }
281
349
  let usesBraces = returnStatement.match(/return\s*\(/gs) ? true : false;
282
350
 
283
-
351
+
352
+ // Remove trailing ']' or trailing )
284
353
  contents = contents.trim().replace(/\]$/, "")
285
354
  contents = contents.replace(/\)$/, "");
286
355
  usesBraces ? !contents.includes('<>') ? contents = `<>${contents}</>` : null : null
@@ -364,7 +433,9 @@ function Compiler(func, file) {
364
433
  valuestate = valuestate.match(regex) ? valuestate.match(regex)[0].split("useState(")[1].split(")")[0].trim() : valuestate
365
434
 
366
435
 
367
- let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}`;
436
+ let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}
437
+
438
+ `;
368
439
  string = string.replace(line, newState);
369
440
  break;
370
441
  case line.includes("useRef") && !line.includes("import"):
@@ -425,8 +496,11 @@ function Compiler(func, file) {
425
496
  let myChildrens = [];
426
497
 
427
498
  let name = component.split("<")[1].split(">")[0].split(" ")[0].replace("/", "");
428
- let componentAttributes = component.split("<")[1].split(">")[0].split(" ").join(" ").replace(name, "").trim();
429
- const dynamicAttributesRegex = /(\w+)(?:="([^"]*?)"|='([^']*?)'|(?:=\{([^}]*?)\})?|(?:=\{(.*?)*\})?|(?:={([^}]*?)})?|(?:{([^}]*?)})?|(?:}))?|\$=\s*\{\s*\{\s*(.*?)\s*\}\s*\}/gs;
499
+ let componentAttributes = component.split("<")[1].split(">")[0].split(" ").join(" ").replace(name, "").trim();
500
+ // some components will have props that have html inside of them we need to only get the props ex: <Header title={<h1>hello</h1>}></Header> -> title={<h1>hello</h1>} // also spread props ex: <Header {...props}></Header> -> {...props} or {...props, title: 'hello'} or {...props, color:{color: 'red'}}
501
+ // grab ...( spread props )
502
+ const dynamicAttributesRegex = /(\w+)(?:="([^"]*)")?(?:='([^']*)')?(?:=\{([^}]*)\})?(?:=\{(.*?)\})?(?:={([^}]*)})?(?:{([^}]*)})?|(?:{(?:[^{}]+|\{(?:[^{}]+|\{[^}]*\})*\})*\})|(\.{3}\{(?:[^{}]+|\{(?:[^{}]+|\{[^}]*\})*\})*\})|\$=\{(?:[^{}]+|\{(?:[^{}]+|\{[^}]*\})*\})*\}/gs;
503
+
430
504
 
431
505
 
432
506
 
@@ -443,11 +517,12 @@ function Compiler(func, file) {
443
517
  for (let prop of props) {
444
518
 
445
519
  if (prop === componentName) {
446
-
520
+
521
+ // If the component is encountered, start collecting props
447
522
  isWithinComponent = true;
448
523
  filteredProps.push(prop);
449
524
  } else if (isWithinComponent && prop.includes('=')) {
450
-
525
+
451
526
  if (prop.startsWith('$=')) {
452
527
  let old = prop
453
528
  prop = prop.replace('$=', '$_ternary=')
@@ -460,7 +535,8 @@ function Compiler(func, file) {
460
535
  $_ternaryprops.push(prop)
461
536
 
462
537
  }
463
- else if (prop.includes('${')) {
538
+ else if (prop.includes('${')) {
539
+ // if it has an object inside of it then we should just do soemting:object else we should do something: `${object}`
464
540
 
465
541
  prop = prop.replace('="', ':').replace('}"', '}')
466
542
  if (prop.includes('${')) {
@@ -542,7 +618,6 @@ function Compiler(func, file) {
542
618
  }
543
619
 
544
620
  myChildrens.push(child.children);
545
- childs = childs.filter((e) => e.parent !== name);
546
621
  }
547
622
  });
548
623
 
@@ -605,7 +680,6 @@ function Compiler(func, file) {
605
680
  let text = fs.readFileSync(file, "utf8");
606
681
  if (!file.endsWith('.js') && file.endsWith('.jsx')) {
607
682
  text = Compiler(text, file);
608
-
609
683
  }
610
684
  let dest = file.split('node_modules')[1]
611
685
  dest = dest.split(baseFolder)[1]
@@ -823,7 +897,14 @@ async function Build() {
823
897
  return text;
824
898
  };
825
899
 
826
-
900
+
901
+
902
+
903
+
904
+
905
+ // Process files in the 'pages' directory
906
+ let appjs = '';
907
+ let hasWritten = []
827
908
  function ssg(routes = []) {
828
909
  globalThis.isBuilding = true
829
910
  console.log(`Generating html files for ${routes.length} routes`)
@@ -979,35 +1060,23 @@ async function Build() {
979
1060
  headless: "new", args: ['--no-sandbox', '--disable-setuid-sandbox'],
980
1061
  warning: false,
981
1062
  })
982
-
1063
+
983
1064
  const browserPID = browser.process().pid
984
1065
  try {
985
1066
 
986
1067
  route.url = route.url.replaceAll(/\/:[a-zA-Z0-9_-]+/gs, '')
987
1068
  let page = await browser.newPage();
988
1069
  await page.goto(`http://localhost:${port}/`, { waitUntil: 'networkidle2' });
989
- await page.on('console', msg => console.log('PAGE LOG:', msg.text()));
990
- await page.on('error', err => console.log('PAGE LOG:', err));
991
- await page.on('pageerror', err => console.log('PAGE LOG:', err));
992
- await page.on('requestfailed', err => console.log(err));
993
- await page.evaluate(() => {
994
- window.onerror = function (msg, url, lineNo, columnNo, error) {
995
- console.log(msg, url, lineNo, columnNo, error)
996
- }
997
- })
998
1070
  await page.waitForSelector('#root', { timeout: 10000 })
999
1071
  await page.evaluate(() => {
1000
1072
  document.getElementById('meta').remove()
1001
1073
  document.querySelector('#isServer').innerHTML = 'window.isServer = false'
1002
1074
  if (document.head.getAttribute('prerender') === 'false') {
1003
1075
  document.querySelector('#root').innerHTML = ''
1004
- console.log(`Disabled prerendering for ${window.location.pathname}`)
1005
1076
  }
1006
- })
1007
- let html = await page.content();
1077
+ })
1078
+ const html = await page.content();
1008
1079
 
1009
- html = await prettier.format(html, { parser: "html" })
1010
-
1011
1080
  await page.close();
1012
1081
  await writer(process.cwd() + '/dist/' + (route.url === '/' ? 'index.html' : `${route.url}/` + 'index.html'), html)
1013
1082
  await browser.close();
@@ -1065,10 +1134,10 @@ async function Build() {
1065
1134
 
1066
1135
 
1067
1136
  let data = await fs.readFileSync(origin, "utf8");
1068
- console.log(`Compiling ${fileName}...`)
1069
1137
  data = Compiler(data, origin);
1070
1138
 
1071
1139
 
1140
+
1072
1141
  await writer(process.cwd() + "/dist/" + fileName.replace('.jsx', '.js'), data).then(async () => {
1073
1142
 
1074
1143