vaderjs 1.3.3-alpha-114 → 1.3.3-alpha-115

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.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/runtime/router.js +1 -1
  3. package/vader.js +122 -119
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-alpha-114",
5
+ "version": "1.3.3-alpha-115",
6
6
  "bin": {
7
7
  "vader": "./vader.js"
8
8
  },
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,console.log(this.basePath)}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){this.middlewares.push(e)}listen(e,t){if(e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length){let e=`/${window.location.pathname.split("/")[1]}`;this.handleRoute(e)}else this.listeners.pop();t&&t(),window.onpopstate=async e=>{let t=`/${window.location.pathname.split("/")[1]}`;routes.find((e=>e.url.includes(t)))||(t="/404");let s=(new DOMParser).parseFromString(await fetch(t,{cache:"reload"}).then((e=>e.text())),"text/html").documentElement;document.querySelector("#root").innerHTML=s.querySelector("#root").innerHTML,document.title=s.querySelector("title").innerHTML,document.querySelector('script[id="router"]').remove();let n=document.createElement("script");n.id="router",n.innerHTML=s.querySelector('script[id="router"]').innerHTML,n.setAttribute("type","module"),document.body.appendChild(n)}}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,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=window.routes.find((e=>{if(e.url.includes("/404"))window.history.replaceState({},"","/404");else if(!this.error&&e.url.includes("/404"))return!0})),t=n?200:404);const r=this.extractQueryParams(s),o=n&&n.path?this.extractParams(n.path,s):{};Object.keys(o).forEach((e=>{o[e]=o[e].split("?")?o[e].split("?")[0]:o[e]}));const i={headers:{},params:o,query:r,path:e,fileUrl:window.location.href.split(window.location.origin)[1],url:window.location.href,method:n?n.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=i.path,window.$FULL_URL=window.location.href.replace("#","");const a={status:t,log:e=>{void 0===e?console.log(`${i.path} ${i.method} ${a.status} ${i.timestamp}`):console.table({"Request Path":i.path,"Request Method":n.method,"Response Status":a.status,"Request Timestamp":i.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.location.hash=`#${e}`},render:async(e,t,s,n)=>{function isClass(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let n=new Component;if(isClass(e.default)){let t=new e.default;n.state=t.state,n=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');n.key=e.default.toString().split('key="')[1]?e.default.toString().split('key="')[1].split('"')[0]:null;let i={key:n.key,render:()=>e.default.apply(n,[t,s]),request:t,response:s,params:o,queryParams:r,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),useReducer:n.useReducer.bind(n),onMount:n.onMount.bind(n),onUnmount:n.onUnmount.bind(n),hydrate:n.hydrate.bind(n)};n.render=i.render,n=i,console.log(t)}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");n.reset(),n.components={},n.request=t,n.response=s,n.router.use&&!n.isChild?await new Promise((async r=>{if(isClass(e.default))if(isClass(e.default))switch(await n.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(n,[t,s]),await n.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()}})):n.router.use&&n.isChild&&console.warn("Router.use() is not supported in child components");const i=await n.render();document.querySelector("#root").innerHTML!==i&&(console.log("rendering"),document.querySelector("#root").innerHTML=i),n.bindMount(),n.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(i,a)})),n&&n.handler(i,a)}}window.VaderRouter=VaderRouter;export default VaderRouter;
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){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.pathname):this.listeners.pop(),t&&t(),window.onpopstate=async e=>{let t=window.location.pathname,r=`/${t.split("/")[1]}`;this.checkroute(t)||(t="/404");let s=(new DOMParser).parseFromString(await fetch(r,{cache:"reload"}).then((e=>e.text())),"text/html").documentElement;document.querySelector("#root").innerHTML=s.querySelector("#root").innerHTML,document.title=s.querySelector("title").innerHTML,document.querySelector('script[id="router"]').remove();let n=document.createElement("script");n.id="router",n.innerHTML=s.querySelector('script[id="router"]').innerHTML,n.setAttribute("type","module"),document.body.appendChild(n)}}extractParams(e,t){const r=e.split("/").filter((e=>""!==e)),s=t.split("/").filter((e=>""!==e)),n={};return r.forEach(((e,t)=>{if(e.startsWith(":")){const r=e.slice(1);n[r]=s[t]}else if(e.startsWith("*")){s.slice(t).forEach(((e,t)=>{n[t]=e}))}})),n}extractQueryParams(e){const t=e.split("?")[1];if(!t)return{};const r={};return t.split("&").forEach((e=>{const[t,s]=e.split("=");r[t]=s})),r}checkroute(e){return 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 r=t.path.split("/").filter((e=>""!==e)),s=e.split("/").filter((e=>""!==e));if(r.length!==s.length&&!t.path.endsWith("*"))return!1;for(let e=0;e<r.length;e++){const t=r[e],n=s[e];if(!t.startsWith(":")&&!t.startsWith("*")&&t!==n)return!1}return!0}const r=this.extractParams(t.path,e);return Object.keys(r).length>0}))}handleRoute(e){let t=200,r=e,s=this.checkroute(e);s||(s=window.routes.find((e=>e.url.includes("/404")&&!this.error?(this.error=!0,!0):!(this.error||!e.url.includes("/404"))||void 0)),t=s?200:404);const n=this.extractQueryParams(r),o=s&&s.path?this.extractParams(s.path,r):{};Object.keys(o).forEach((e=>{o[e]=o[e].split("?")?o[e].split("?")[0]:o[e]}));const i={headers:{},params:o,query:n,path:e,fileUrl:window.location.href.split(window.location.origin)[1],url:window.location.href,method:s?s.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=i.path,window.$FULL_URL=window.location.href.replace("#","");const a={status:t,log:e=>{void 0===e?console.log(`${i.path} ${i.method} ${a.status} ${i.timestamp}`):console.table({"Request Path":i.path,"Request Method":s.method,"Response Status":a.status,"Request Timestamp":i.timestamp})},refresh:()=>{this.handleRoute(window.location.pathname)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.history.pushState({},"",e),window.dispatchEvent(new Event("popstate"))},render:async(e,t,r,s)=>{function isClass(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let s=new Component;if(isClass(e.default)){let t=new e.default;s.state=t.state,s=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');s.key=e.default.toString().split('key="')[1]?e.default.toString().split('key="')[1].split('"')[0]:null;let i={key:s.key,render:()=>e.default.apply(s,[t,r]),request:t,response:r,params:o,queryParams:n,reset:s.reset.bind(s),onMount:s.onMount.bind(s),useState:null,router:{use:s.router.use.bind(s)},bindMount:s.bindMount.bind(s),memoize:s.memoize.bind(s),createComponent:s.createComponent.bind(s),isChild:!1,useState:s.useState.bind(s),parseStyle:s.parseStyle.bind(s),bind:s.bind.bind(s),useRef:s.useRef.bind(s),useReducer:s.useReducer.bind(s),onMount:s.onMount.bind(s),onUnmount:s.onUnmount.bind(s),hydrate:s.hydrate.bind(s)};s.render=i.render,s=i}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");s.reset(),s.components={},s.request=t,s.response=r,s.router.use&&!s.isChild?await new Promise((async n=>{if(isClass(e.default))if(isClass(e.default))switch(await s.router.use(t,r),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing",t.pause):(clearInterval(e),n())}),1e3);break;case!1:n()}else n();else switch(await e.default.apply(s,[t,r]),await s.router.use(t,r),t.pause){case!0:let e=setInterval((()=>{t.pause?console.log("still pausing request",t.url):(clearInterval(e),n())}),1e3);break;case!1:n()}})):s.router.use&&s.isChild&&console.warn("Router.use() is not supported in child components");const i=await s.render();document.querySelector("#root").innerHTML!==i&&(document.querySelector("#root").innerHTML=i),s.bindMount(),s.onMount()}catch(e){console.error(e)}},setQuery:e=>{let t="";Object.keys(e).forEach(((r,s)=>{t+=`${0===s?"?":"&"}${r}=${e[r]}`}));let r=window.location.hash.split("?")[0];t=t.replace("/","-").replaceAll("/","-"),window.location.hash=`${r}${t}`},send:e=>{document.querySelector("#root").innerHTML=e},json:e=>{const t=document.querySelector("#root");t.innerHTML="";const r=document.createElement("pre");r.textContent=JSON.stringify(e,null,2),t.appendChild(r)}};middlewares.forEach((e=>{e(i,a)})),s&&s.handler(i,a)}}window.VaderRouter=VaderRouter;export default VaderRouter;
package/vader.js CHANGED
@@ -13,15 +13,15 @@ let errorCodes = {
13
13
  /**
14
14
  * define directories
15
15
  */
16
-
17
16
 
18
- if(!fs.existsSync(process.cwd() + '/dist')){
17
+
18
+ if (!fs.existsSync(process.cwd() + '/dist')) {
19
19
  fs.mkdirSync(process.cwd() + '/dist')
20
20
  }
21
21
 
22
22
 
23
23
 
24
- if (typeof process.env.isCloudflare !== "undefined" || !fs.existsSync(process.cwd() + '/dist/index.html')) {
24
+ if (typeof process.env.isCloudflare !== "undefined" || !fs.existsSync(process.cwd() + '/dist/index.html')) {
25
25
  let htmlFile = fs.readFileSync(process.cwd() + "/node_modules/vaderjs/runtime/index.html", 'utf8')
26
26
  fs.writeFileSync(process.cwd() + "/dist/index.html", htmlFile)
27
27
  }
@@ -100,7 +100,7 @@ function Compiler(func, file) {
100
100
  let functionAttributes = [];
101
101
  let functionMatch;
102
102
  while ((functionMatch = functionAttributeRegex.exec(code)) !== null) {
103
- let [, attributeName, attributeValue] = functionMatch;
103
+ let [, attributeName, attributeValue] = functionMatch;
104
104
  let attribute = {};
105
105
 
106
106
  if (attributeValue && attributeValue.includes("=>") || attributeValue && attributeValue.includes("function")) {
@@ -138,18 +138,18 @@ function Compiler(func, file) {
138
138
  }
139
139
  });
140
140
  // add ; after newlines
141
-
141
+
142
142
 
143
143
  let newvalue = attributeValue.includes('=>') ? attributeValue.split("=>").slice(1).join("=>").trim() : attributeValue.split("function").slice(1).join("function").trim()
144
144
 
145
-
145
+
146
146
 
147
147
  newvalue = newvalue.trim();
148
148
 
149
149
  //remove starting {
150
150
  newvalue = newvalue.replace("{", "")
151
-
152
-
151
+
152
+
153
153
 
154
154
  let params = attributeValue
155
155
  .split("=>")[0]
@@ -164,23 +164,23 @@ function Compiler(func, file) {
164
164
  // split first {}
165
165
  newvalue = newvalue.trim();
166
166
 
167
-
168
167
 
169
- newvalue = newvalue.replace(/}\s*$/, '');
170
168
 
171
-
172
-
169
+ newvalue = newvalue.replace(/}\s*$/, '');
170
+
171
+
172
+
173
173
  newvalue = newvalue.trim();
174
174
 
175
175
  // remmove trailing }
176
176
 
177
- newvalue = newvalue.trim();
178
- newvalue = newvalue.replace(/}\s*$/, '');
179
-
177
+ newvalue = newvalue.trim();
178
+ newvalue = newvalue.replace(/}\s*$/, '');
179
+
180
+
181
+
182
+ functionparams.length > 0 ? params = params + ',' + functionparams.map((e) => e.name).join(',') : null
180
183
 
181
-
182
- functionparams.length > 0 ? params = params + ',' + functionparams.map((e) => e.name).join(',') : null
183
-
184
184
  newvalue = newvalue.replaceAll(',,', ',')
185
185
  let paramnames = params ? params.split(',').map((e) => e.trim()) : null
186
186
  paramnames = paramnames ? paramnames.filter((e) => e.length > 0) : null
@@ -195,7 +195,7 @@ function Compiler(func, file) {
195
195
  }
196
196
  return e
197
197
  }) : ''}" ${params ? params.split(',').map((e) => e.trim()).filter(Boolean).map((e) => `,${e}`).join('') : ''})}"`
198
-
198
+
199
199
  string = string.replace(old, bind);
200
200
  }
201
201
  }
@@ -662,7 +662,7 @@ function Compiler(func, file) {
662
662
 
663
663
  }
664
664
 
665
-
665
+
666
666
  if (newImport) {
667
667
  string = string.replace(beforeimport, newImport)
668
668
  }
@@ -720,24 +720,25 @@ async function Build() {
720
720
  globalThis.isBuilding = true
721
721
  console.log(`Generating html files for ${routes.length} routes`)
722
722
  routes.forEach(async (route) => {
723
- if(route.url.includes(':')){
723
+ if (route.url.includes(':')) {
724
724
  console.log('Route ' + route.url + ' is a dynamic route and will not be generated')
725
- return
725
+ return
726
726
  }
727
727
  console.log('Generating html file for route ' + route.url)
728
728
  let equalparamroute = routes.map((e) => {
729
-
729
+ console.log(e.url, route.url)
730
730
  if (e.url.includes(':')) {
731
- let url = e.url.split('/:')[0]
732
- if(url&&route.url === url){
733
- return e
734
- }else{
735
- return null
736
-
737
- }
731
+ let url = e.url.split('/:')[0]
732
+ console.log(url, route.url)
733
+ if (url && route.url === url) {
734
+ return e
735
+ } else {
736
+ return null
737
+
738
+ }
738
739
  }
739
740
  return null
740
- }).filter(Boolean)
741
+ }).filter(Boolean)
741
742
  let document = `
742
743
  <!DOCTYPE html>
743
744
  <html lang="en">
@@ -809,77 +810,79 @@ async function Build() {
809
810
  let module = await import('/${route.fileName.replace('.jsx', '.js')}')
810
811
  res.render(module, req, res, module.$metadata)
811
812
  })
812
- ${equalparamroute.length > 0 ? equalparamroute.map((e) => {
813
-
813
+ ${equalparamroute.length > 0 ? equalparamroute.map((e) => {
814
+
815
+
814
816
 
815
817
  return `router.get('${e.url}', async (req, res) => {
816
818
  let module = await import('/${e.fileName.replace('.jsx', '.js')}')
817
819
  res.render(module, req, res, module.$metadata)
818
820
  })\n`
819
- }): ''}
821
+ }) : ''}
820
822
  router.listen(3000)
821
823
 
822
824
  </script>
823
825
  </html>
824
826
  `;
825
-
826
- // generate random but common ports
827
- let port = Math.floor(Math.random() * (65535 - 49152 + 1) + 49152)
828
-
829
- const server = http.createServer((req, res) => {
827
+
828
+ // generate random but common ports
829
+ let port = Math.floor(Math.random() * (65535 - 49152 + 1) + 49152)
830
+
831
+ const server = http.createServer((req, res) => {
830
832
  if (req.url === '/') {
831
833
  // Respond with the generated HTML
832
834
  res.writeHead(200, { 'Content-Type': 'text/html' });
833
835
  res.end(document);
834
836
  } else {
835
837
  // Serve static files (adjust the file paths based on your project structure)
836
- const filePath = process.cwd() + '/dist/' + req.url
837
-
838
+ const filePath = process.cwd() + '/dist/' + req.url
839
+
838
840
  fs.readFile(filePath, (err, data) => {
839
841
  if (err) {
840
- res.writeHead(404, { 'Content-Type': filePath.includes('js') ? 'text/javascript' : 'text/html' });
842
+ res.writeHead(404, { 'Content-Type': filePath.includes('js') ? 'text/javascript' : 'text/html' });
841
843
  res.end('File not found');
842
844
  } else {
843
845
  res.writeHead(200, { 'Content-Type': filePath.includes('js') ? 'text/javascript' : 'text/html' });
844
- res.end(data);
846
+ res.end(data);
845
847
  }
846
848
  });
847
849
  }
848
850
  });
849
-
851
+
850
852
  server.listen(port)
851
-
853
+
852
854
  globalThis.listen = true;
853
855
 
854
- puppeteer.launch({ headless: "new", args: ['--no-sandbox', '--disable-setuid-sandbox'],
855
- warning: false,
856
- }).then(async (browser) => {
857
-
856
+ puppeteer.launch({
857
+ headless: "new", args: ['--no-sandbox', '--disable-setuid-sandbox'],
858
+ warning: false,
859
+ }).then(async (browser) => {
860
+
858
861
  // remove /: from route
859
- route.url = route.url.replaceAll(/\/:[a-zA-Z0-9_-]+/gs, '')
860
- const page = await browser.newPage();
862
+ route.url = route.url.replaceAll(/\/:[a-zA-Z0-9_-]+/gs, '')
863
+ const page = await browser.newPage();
861
864
  await page.goto(`http://localhost:${port}` + '#' + route.url, { waitUntil: 'networkidle2' });
862
- await page.waitForSelector('#root');
865
+ await page.waitForSelector('#root');
863
866
  await page.evaluate(() => {
864
867
  document.getElementById('meta').remove()
865
868
  })
866
869
  const html = await page.content();
867
- await page.close();
870
+ await page.close();
868
871
  let isBasePath = route.url === '/' ? true : false
869
872
  await writer(process.cwd() + '/dist/' + (isBasePath ? 'index.html' : `${route.url}/` + 'index.html'), html)
870
873
  await browser.close();
871
- // close http
872
- server.close()
874
+ // close http
875
+ server.close()
873
876
  })
874
-
877
+
875
878
  })
876
-
877
- let timeout = setTimeout(() => {
879
+
880
+ let timeout = setTimeout(() => {
878
881
  globalThis.isBuilding = false
879
882
  clearTimeout(timeout)
880
883
  }, 1000)
881
884
  }
882
-
885
+
883
886
  globalThis.routes = []
884
887
 
885
888
  for await (let file of glb) {
@@ -909,7 +912,7 @@ async function Build() {
909
912
 
910
913
  let data = await fs.readFileSync(origin, "utf8");
911
914
  data = Compiler(data, origin);
912
-
915
+
913
916
 
914
917
 
915
918
  await writer(process.cwd() + "/dist/" + fileName.replace('.jsx', '.js'), data).then(async () => {
@@ -939,11 +942,11 @@ async function Build() {
939
942
  obj.compiledPath = process.cwd() + "/dist/pages/" + fileName.replace('.jsx', '.js')
940
943
 
941
944
 
942
-
943
- globalThis.routes.push({fileName:fileName, url:obj.url, html:'/' + (isBasePath ? 'index.html' : `${obj.url}/` + 'index.html')})
944
-
945
945
 
946
-
946
+ globalThis.routes.push({ fileName: fileName, url: obj.url, html: '/' + (isBasePath ? 'index.html' : `${obj.url}/` + 'index.html') })
947
+
948
+
949
+
947
950
  }
948
951
 
949
952
  ssg(globalThis.routes)
@@ -1043,32 +1046,32 @@ async function Build() {
1043
1046
 
1044
1047
  globalThis.isBuilding = false
1045
1048
  console.log(`Build completed in ${Date.now() - start}ms with ${Math.round(bundleSize / 1000)}kb`)
1046
-
1049
+
1047
1050
  bundleSize = 0;
1048
1051
  return true
1049
- }
1050
- const s = ()=>{
1051
-
1052
+ }
1053
+ const s = () => {
1054
+
1052
1055
  const server = http.createServer((req, res) => {
1053
-
1054
- if(!req.url.endsWith('.js') && !req.url.endsWith('.css') && !req.url.endsWith('.mjs') && !req.url.endsWith('.cjs') && !req.url.endsWith('.html') && !req.url.endsWith('.json')){
1055
- req.url = req.url !== '/' ? req.url.split('/')[1] : req.url
1056
+
1057
+ if (!req.url.endsWith('.js') && !req.url.endsWith('.css') && !req.url.endsWith('.mjs') && !req.url.endsWith('.cjs') && !req.url.endsWith('.html') && !req.url.endsWith('.json')) {
1058
+ req.url = req.url !== '/' ? req.url.split('/')[1] : req.url
1056
1059
  req.url = process.cwd() + '/dist/' + req.url + '/index.html'
1057
- }else{
1060
+ } else {
1058
1061
  req.url = process.cwd() + '/dist/' + req.url
1059
- }
1060
-
1061
- const filePath = req.url
1062
+ }
1063
+
1064
+ const filePath = req.url
1062
1065
 
1063
1066
  fs.readFile(filePath, (err, data) => {
1064
- if (err) {
1065
- res.writeHead(404, { 'Content-Type': 'text/html' });
1066
- res.end(fs.existsSync(process.cwd() + '/dist/404') ? fs.readFileSync(process.cwd() + '/dist/404/index.html') : '404');
1067
- } else {
1068
- const contentType = getContentType(filePath);
1069
- switch(true){
1070
- case contentType === 'text/html' && globalThis.devMode:
1071
- data = data.toString() + `<script type="module">
1067
+ if (err) {
1068
+ res.writeHead(404, { 'Content-Type': 'text/html' });
1069
+ res.end(fs.existsSync(process.cwd() + '/dist/404') ? fs.readFileSync(process.cwd() + '/dist/404/index.html') : '404');
1070
+ } else {
1071
+ const contentType = getContentType(filePath);
1072
+ switch (true) {
1073
+ case contentType === 'text/html' && globalThis.devMode:
1074
+ data = data.toString() + `<script type="module">
1072
1075
  let ws = new WebSocket('ws://localhost:3000')
1073
1076
  ws.onmessage = (e) => {
1074
1077
  if(e.data === 'reload'){
@@ -1078,51 +1081,51 @@ const s = ()=>{
1078
1081
  }
1079
1082
  </script>
1080
1083
  `
1081
- }
1082
- res.writeHead(200, { 'Content-Type': contentType });
1083
- res.end(data);
1084
1084
  }
1085
+ res.writeHead(200, { 'Content-Type': contentType });
1086
+ res.end(data);
1087
+ }
1085
1088
  });
1086
- });
1089
+ });
1090
+
1087
1091
 
1088
-
1089
- const ws = new WebSocketServer({ server });
1090
- ws.on('connection', (socket) => {
1092
+ const ws = new WebSocketServer({ server });
1093
+ ws.on('connection', (socket) => {
1091
1094
  console.log('Client connected');
1092
1095
  socket.on('close', () => console.log('Client disconnected'));
1093
- });
1096
+ });
1094
1097
 
1095
1098
 
1096
- function getContentType(filePath) {
1099
+ function getContentType(filePath) {
1097
1100
  if (filePath.includes('js')) {
1098
- return 'text/javascript';
1101
+ return 'text/javascript';
1099
1102
  } else if (filePath.includes('.css')) {
1100
- return 'text/css';
1103
+ return 'text/css';
1101
1104
  } else {
1102
- return 'text/html';
1105
+ return 'text/html';
1103
1106
  }
1104
- }
1107
+ }
1105
1108
 
1106
- const PORT = process.env.PORT || 3000;
1107
- server.listen(PORT, () => {
1109
+ const PORT = process.env.PORT || 3000;
1110
+ server.listen(PORT, () => {
1108
1111
  console.log(`Server is running on port ${PORT}`);
1109
- });
1110
- let i =
1111
- setInterval(() => {
1112
- if (globalThis.isBuilding && globalThis.devMode) {
1113
- // reload page
1114
- console.log('Reloading page...')
1115
- ws.clients.forEach((client) => {
1116
- client.send('reload')
1117
- console.log('Reloaded page')
1118
- })
1119
- } else{
1120
- clearInterval(i)
1121
- }
1122
- },120)
1123
-
1112
+ });
1113
+ let i =
1114
+ setInterval(() => {
1115
+ if (globalThis.isBuilding && globalThis.devMode) {
1116
+ // reload page
1117
+ console.log('Reloading page...')
1118
+ ws.clients.forEach((client) => {
1119
+ client.send('reload')
1120
+ console.log('Reloaded page')
1121
+ })
1122
+ } else {
1123
+ clearInterval(i)
1124
+ }
1125
+ }, 120)
1126
+
1124
1127
  }
1125
-
1128
+
1126
1129
 
1127
1130
  switch (true) {
1128
1131
  case process.argv.includes('--watch'):
@@ -1149,10 +1152,10 @@ Vader.js v1.3.3
1149
1152
  }
1150
1153
  }).on('error', (err) => console.log(err))
1151
1154
  })
1152
-
1155
+
1153
1156
  s()
1154
-
1155
- globalThis.listen = true;
1157
+
1158
+ globalThis.listen = true;
1156
1159
 
1157
1160
  break;
1158
1161
  case process.argv.includes('--build'):
@@ -1160,9 +1163,9 @@ Vader.js v1.3.3
1160
1163
  console.log(`
1161
1164
  Vader.js v1.3.3
1162
1165
  Building to ./dist
1163
- `)
1166
+ `)
1164
1167
  Build()
1165
-
1168
+
1166
1169
  break;
1167
1170
  case process.argv.includes('--serve'):
1168
1171
  let port = process.argv[process.argv.indexOf('--serve') + 1] || 3000