vaderjs 1.7.9 → 1.8.1

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/bundler/index.js CHANGED
@@ -93,7 +93,7 @@ const handleReplacements = (code) => {
93
93
 
94
94
  let key = line.split(',')[0].split('[')[1].replace(' ', '');
95
95
 
96
- let updatedLine = line.replace(/\buseState\d*\(/, `this.useState('${key + Math.random()}',`);
96
+ let updatedLine = line.replace(/\buseState\d*\(/, `this.useState('${key}',`);
97
97
 
98
98
  line = updatedLine;
99
99
  }
@@ -103,7 +103,7 @@ const handleReplacements = (code) => {
103
103
 
104
104
  let key = line.split(',')[0].split('[')[1].replace(' ', '');
105
105
 
106
- let updatedLine = line.replace(/\buseAsyncState\d*\(/, `this.useAsyncState('${key + Math.random()}',`);
106
+ let updatedLine = line.replace(/\buseAsyncState\d*\(/, `this.useAsyncState('${key}',`);
107
107
 
108
108
  line = updatedLine;
109
109
  }
@@ -191,7 +191,7 @@ const generatePage = async (
191
191
  import c from '${process.env.filePath}'
192
192
  import {render, e} from '/src/vader/index.js'
193
193
  window.e = e
194
- render(c, document.body)
194
+ render(c, document.body.firstChild)
195
195
  </script>
196
196
  `
197
197
  );
package/index.ts CHANGED
@@ -79,15 +79,15 @@ export const A = (props: {
79
79
  /**
80
80
  * @description Set the elements classlist
81
81
  */
82
- class: string;
82
+ className?: string;
83
83
  /**
84
84
  * @description Once clicked send user to a different link
85
85
  */
86
- href: string;
87
- style: string;
88
- openInNewTab: boolean
89
- onClick: () => void;
90
- onChange: () => void;
86
+ href?: string;
87
+ style?: string;
88
+ openInNewTab?: boolean
89
+ onClick?: () => void;
90
+ onChange?: () => void;
91
91
  }, children: any) => {
92
92
  function handleClick(e) {
93
93
  e.preventDefault();
@@ -95,9 +95,7 @@ export const A = (props: {
95
95
  window.open(props.href, "_blank");
96
96
  return void 0;
97
97
  }
98
- window.history.pushState({}, "", props.href);
99
- window.dispatchEvent(new PopStateEvent("popstate"));
100
- window.location.reload();
98
+ window.location.href = props.href;
101
99
  return void 0;
102
100
  }
103
101
  return e("a", { ...props, onClick: handleClick }, props.children);
@@ -112,6 +110,14 @@ export const Fragment = (props: any, children: any) => {
112
110
  }
113
111
  }
114
112
 
113
+ if(typeof window !== "undefined") {
114
+ window.history.back = () => {
115
+ window.history.go(-1);
116
+ }
117
+ window.history.forward = () => {
118
+ window.history.go(1);
119
+ }
120
+ }
115
121
  globalThis.Fragment = Fragment;
116
122
 
117
123
  /**
@@ -153,6 +159,12 @@ export const e = (element, props, ...children) => {
153
159
  if (el.type !== "head") {
154
160
  el.props = { idKey: crypto.randomUUID(), ...el.props };
155
161
  }
162
+
163
+ // if element == false return empty string
164
+ if (el.type === false) {
165
+ return "";
166
+ }
167
+
156
168
  return el;
157
169
  }
158
170
  };
@@ -166,9 +178,14 @@ export const e = (element, props, ...children) => {
166
178
  */
167
179
 
168
180
 
169
- export function Switch({ children }) {
181
+ interface SwitchProps {
182
+ children: any[] | any;
183
+ }
184
+
185
+ // make children optional
186
+ export function Switch({ children = [] }: SwitchProps) {
170
187
  for (let child of children) {
171
- if (child.props.when) {
188
+ if (child && child.props && child.props.when) {
172
189
  return child;
173
190
  }
174
191
  }
@@ -625,7 +642,7 @@ export class Component {
625
642
  } else if (typeof child === "object") {
626
643
  // Nested object children
627
644
  el.appendChild(this.parseToElement(child));
628
- } else if (child !== null && child !== undefined) {
645
+ } else if (child !== null && child !== undefined && child !== false) {
629
646
  // Text nodes
630
647
  el.appendChild(document.createTextNode(child));
631
648
  }
package/main.js CHANGED
@@ -75,15 +75,16 @@ if (!fs.existsSync(process.cwd() + '/jsconfig.json')) {
75
75
  await Bun.write(process.cwd() + '/jsconfig.json', JSON.stringify(json, null, 4))
76
76
  }
77
77
 
78
- var bindes = []
78
+ globalThis.bindes = []
79
79
  var fnmap = []
80
80
  const vader = {
81
+ isDev: mode === 'development',
81
82
  onFileChange: (file, cb) => {
82
83
  fs.watch(file, cb)
83
84
  },
84
85
  runCommand: (cmd) => {
85
86
  return new Promise((resolve, reject) => {
86
- Bun.spawn(cmd, {
87
+ let c = Bun.spawn(cmd, {
87
88
  stdout: 'inherit',
88
89
  cwd: process.cwd(),
89
90
  onExit({ exitCode: code }) {
@@ -95,6 +96,11 @@ const vader = {
95
96
  }
96
97
  })
97
98
 
99
+ setTimeout(() => {
100
+ c.kill()
101
+ reject()
102
+ }, 5000)
103
+
98
104
 
99
105
  })
100
106
  },
@@ -105,6 +111,7 @@ const vader = {
105
111
  },
106
112
  injectHTML: (html) => {
107
113
  bindes.push(html)
114
+ globalThis.bindes = bindes
108
115
  },
109
116
  }
110
117
  const handleReplacements = (code) => {
@@ -201,9 +208,9 @@ async function generateApp() {
201
208
 
202
209
  let r = routes.routes[route]
203
210
  let code = await Bun.file(r).text()
211
+ code = handleReplacements(code)
204
212
  let size = code.length / 1024
205
213
  r = r.replace(process.cwd().replace(/\\/g, '/') + '/app', '')
206
- var beforeR = r
207
214
  r = r.replace('.jsx', '.js').replace('.tsx', '.js')
208
215
  fs.mkdirSync(path.join(process.cwd() + '/dist', path.dirname(r)), { recursive: true })
209
216
  fs.writeFileSync(process.cwd() + '/dist/' + path.dirname(r) + '/' + path.basename(r), `
@@ -227,7 +234,6 @@ async function generateApp() {
227
234
  fs.writeFileSync(process.cwd() + '/dist/src/vader/index.js', await new Bun.Transpiler({
228
235
  loader: 'ts',
229
236
  }).transformSync(await Bun.file(require.resolve('vaderjs')).text()))
230
-
231
237
  Bun.spawn({
232
238
  cmd: ['bun', 'run', './dev/bundler.js'],
233
239
  cwd: process.cwd(),
@@ -240,12 +246,10 @@ async function generateApp() {
240
246
  DEV: mode === 'development',
241
247
  size,
242
248
  bindes: bindes.join('\n'),
243
- isTs: beforeR.endsWith(".tsx"),
244
249
  filePath: r,
245
-
246
- isJsx: beforeR.endsWith('.tsx') || beforeR.endsWith(".jsx"),
247
250
  isAppFile: true,
248
- INPUT: `../app/${beforeR}`,
251
+ isJsx: true,
252
+ INPUT: `../app/${r.replace('.js', '.jsx').replace('.tsx', '.js')}`,
249
253
  },
250
254
  onExit({ exitCode: code }) {
251
255
  if (code === 0) {
@@ -297,6 +301,7 @@ async function generateApp() {
297
301
  await plugin.onBuildFinish(vader)
298
302
  }
299
303
  }
304
+
300
305
  })
301
306
 
302
307
 
@@ -305,6 +310,7 @@ async function generateApp() {
305
310
  function handleFiles() {
306
311
  return new Promise(async (resolve, reject) => {
307
312
  try {
313
+ console.log(Glob)
308
314
  let glob = new Glob('public/**/*')
309
315
  for await (var i of glob.scan()) {
310
316
  let file = i
@@ -319,11 +325,11 @@ function handleFiles() {
319
325
  var file = i
320
326
  fs.mkdirSync(path.join(process.cwd() + '/dist', path.dirname(file)), { recursive: true })
321
327
  // turn jsx to js
322
- if (file.endsWith('.jsx') || file.endsWith('.tsx')) {
328
+ if (file.includes('.jsx') || file.includes('.tsx')) {
323
329
  let code = await Bun.file(file).text()
324
330
 
325
331
  code = handleReplacements(code)
326
- var url = file
332
+
327
333
  file = file.replace('.jsx', '.js').replace('.tsx', '.js')
328
334
  fs.writeFileSync(path.join(process.cwd() + '/dist', file.replace('.jsx', '.js').replace('.tsx', '.js')), code)
329
335
  await Bun.spawn({
@@ -339,9 +345,8 @@ function handleFiles() {
339
345
  DEV: mode === 'development',
340
346
  size: code.length / 1024,
341
347
  filePath: file.replace('.jsx', '.js'),
342
- isJsx: url.endsWith('.tsx') || url.endsWith(".jsx"),
343
- isAppFile: false,
344
- INPUT: path.join(process.cwd(), url),
348
+ isTs: file.includes('.tsx'),
349
+ INPUT: path.join(process.cwd(), file.replace('.js', '.jsx').replace('.tsx', '.js')),
345
350
  },
346
351
  onExit({ exitCode: code }) {
347
352
  if (code === 0) {
@@ -351,7 +356,7 @@ function handleFiles() {
351
356
  }
352
357
  }
353
358
  })
354
- } else if (file.endsWith('.ts')) {
359
+ } else if (file.includes('.ts')) {
355
360
  let code = await Bun.file(file).text()
356
361
  code = handleReplacements(code)
357
362
  file = file.replace('.ts', '.js')
@@ -392,8 +397,8 @@ function handleFiles() {
392
397
  globalThis.clients = []
393
398
 
394
399
  if (mode === 'development') {
395
- await handleFiles()
396
400
  await generateApp()
401
+ await handleFiles()
397
402
  const watcher = fs.watch(path.join(process.cwd() + '/'), { recursive: true })
398
403
  let isBuilding = false; // Flag to track build status
399
404
 
@@ -403,10 +408,10 @@ if (mode === 'development') {
403
408
  // Function to handle file changes with debounce
404
409
  const handleFileChangeDebounced = async (change, file) => {
405
410
  if (file.endsWith('.tsx') || file.endsWith('.jsx') || file.endsWith('.css') || file.endsWith('.ts')
406
- && !file.includes('node_module')
411
+ && !file.includes('node_module')
407
412
  ) {
408
413
  // delete files cache
409
- if (file.endsWith('vader.config.ts')) {
414
+ if (file.endsWith('vader.config.ts')){
410
415
  delete require.cache[require.resolve(process.cwd() + '/vader.config.ts')]
411
416
 
412
417
  config = require(process.cwd() + '/vader.config.ts').default
@@ -447,90 +452,106 @@ if (mode === 'development') {
447
452
  else if (mode == 'production') {
448
453
  await handleFiles()
449
454
  await generateApp()
455
+
456
+ console.log(`Build complete in ${Date.now() - start}ms at ${new Date().toLocaleTimeString()}`);
450
457
  }
451
458
  else {
452
459
  if (isBuilding) console.log(`Build complete in ${Date.now() - start}ms at ${new Date().toLocaleTimeString()}`);
453
-
454
- }
455
-
456
-
457
- if (mode == 'development' || mode == 'serve') {
458
- let server = Bun.serve({
459
- port: port || 8080,
460
- websocket: {
461
- open(ws) {
462
- globalThis.clients.push(ws)
463
- ws.send('Connected')
464
- },
465
- message(ws, message) {
466
- globalThis.clients.forEach(c => {
467
- c.send(message)
468
- })
460
+ if (mode == 'development' || mode == 'serve') {
461
+ let server = Bun.serve({
462
+ port: port || 8080,
463
+ websocket: {
464
+ open(ws) {
465
+ globalThis.clients.push(ws)
466
+ ws.send('Connected')
467
+ },
468
+ message(ws, message) {
469
+ globalThis.clients.forEach(c => {
470
+ c.send(message)
471
+ })
472
+ },
473
+
469
474
  },
470
-
471
- },
472
- async fetch(req, res) {
473
- if (res.upgrade(req)) {
474
- return new Response('Upgraded', { status: 101 })
475
- }
476
-
477
- let url = new URL(req.url)
478
- if (url.pathname.includes('.')) {
479
- let p = url.pathname.replaceAll("%5B", "[").replaceAll("%5D", "]")
480
- let file = await Bun.file(path.join(process.cwd() + '/dist' + p))
481
- if (!await file.exists()) return new Response('Not found', { status: 404 })
482
- let imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/tiff', 'image/bmp', 'image/ico', 'image/cur', 'image/jxr', 'image/jpg']
483
-
484
- return new Response(imageTypes.includes(file.type) ? await file.arrayBuffer() : await file.text(), {
485
- headers: {
486
- 'Content-Type': file.type,
487
- 'Cache-Control': imageTypes.includes(file.type) ? 'max-age=31536000' : 'no-cache',
488
- 'Access-Control-Allow-Origin': '*'
489
- }
490
- })
491
- }
492
- let router = new Bun.FileSystemRouter({
493
- dir: process.cwd() + '/app',
494
- style: 'nextjs'
495
- })
496
- router.reload()
497
- let route = router.match(url.pathname)
498
- if (!route) {
499
- return new Response('Not found', { status: 404 })
500
- }
501
- let p = route.pathname;
502
- let base = path.dirname(route.filePath)
503
- base = base.replace(/\\/g, '/')
504
- base = base.replace(path.join(process.cwd() + '/app').replace(/\\/g, '/'), '');
505
- base = base.replace(/\\/g, '/').replace(/\/app(\/|$)/, '/dist$1');
506
- base = process.cwd() + '/dist/' + base;
507
- let data = await Bun.file(path.join(base, 'index.html')).text()
508
- if (mode == "development") {
509
- return new Response(data + `
510
- <script>
511
- let ws = new WebSocket('ws://localhost:${server.port}')
512
- ws.onmessage = (e) => {
513
- if(e.data === 'reload'){
514
- console.log('Reloading to display changes from server')
515
- window.location.reload()
475
+ async fetch(req, res) {
476
+ if (res.upgrade(req)) {
477
+ return new Response('Upgraded', { status: 101 })
516
478
  }
517
- }
518
- </script>
519
- `, {
520
- headers: {
521
- 'Content-Type': 'text/html'
522
- }
479
+
480
+ let url = new URL(req.url)
481
+ if (url.pathname.includes('.')) {
482
+ let p = url.pathname.replaceAll("%5B", "[").replaceAll("%5D", "]")
483
+ let file = await Bun.file(path.join(process.cwd() + '/dist' + p))
484
+ if (!await file.exists()) return new Response('Not found', { status: 404 })
485
+ let imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp', 'image/tiff', 'image/bmp', 'image/ico', 'image/cur', 'image/jxr', 'image/jpg']
486
+
487
+ return new Response(imageTypes.includes(file.type) ? await file.arrayBuffer() : await file.text(), {
488
+ headers: {
489
+ 'Content-Type': file.type,
490
+ 'Cache-Control': imageTypes.includes(file.type) ? 'max-age=31536000' : 'no-cache',
491
+ 'Access-Control-Allow-Origin': '*'
492
+ }
493
+ })
494
+ }
495
+ let router = new Bun.FileSystemRouter({
496
+ dir: process.cwd() + '/app',
497
+ style: 'nextjs'
523
498
  })
524
- } else {
525
- return new Response(data, {
526
- headers: {
527
- 'Content-Type': 'text/html'
499
+ router.reload()
500
+ let route = router.match(url.pathname)
501
+ if (!route) {
502
+ return new Response('Not found', { status: 404 })
503
+ }
504
+ let p = route.pathname;
505
+ let base = path.dirname(route.filePath)
506
+ base = base.replace(/\\/g, '/')
507
+ base = base.replace(path.join(process.cwd() + '/app').replace(/\\/g, '/'), '')
508
+ base = base.replace(/\\/g, '/').replace('/app', '/dist')
509
+ base = process.cwd() + "/dist/" + base
510
+ if(!fs.existsSync(path.join(base, 'index.html'))){
511
+ return new Response(`
512
+ <html>
513
+ <head>
514
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
515
+ <meta http-equiv="refresh" content="5">
516
+ </head>
517
+ <body>
518
+ <h1>404 Not Found</h1>
519
+ <p>Route not found</p>
520
+ </body>
521
+ `, { status: 404 }, {
522
+ headers: {
523
+ 'Content-Type': 'text/html'
524
+ }
525
+ })
526
+ }
527
+ let data = await Bun.file(path.join(base, 'index.html')).text()
528
+ if (mode == "development") {
529
+ return new Response(data + `
530
+ <script>
531
+ let ws = new WebSocket('ws://localhost:${server.port}')
532
+ ws.onmessage = (e) => {
533
+ if(e.data === 'reload'){
534
+ console.log('Reloading to display changes from server')
535
+ window.location.reload()
528
536
  }
529
- })
537
+ }
538
+ </script>
539
+ `, {
540
+ headers: {
541
+ 'Content-Type': 'text/html'
542
+ }
543
+ })
544
+ } else {
545
+ return new Response(data, {
546
+ headers: {
547
+ 'Content-Type': 'text/html'
548
+ }
549
+ })
550
+ }
551
+
530
552
  }
531
-
532
- }
533
- })
534
-
535
- console.log(ansiColors.green('Server started at http://localhost:' + port || 8080))
536
- }
553
+ })
554
+
555
+ console.log(ansiColors.green('Server started at http://localhost:' + port || 8080))
556
+ }
557
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vaderjs",
3
- "version": "1.7.9",
3
+ "version": "1.8.1",
4
4
  "description": "A simple and powerful JavaScript library for building modern web applications.",
5
5
  "bin": {
6
6
  "vaderjs": "./main.js"
@@ -47,15 +47,18 @@ export default {
47
47
  }else{
48
48
  initTailwind()
49
49
 
50
- vader.onFileChange('tailwind.config.js', async () => {
50
+ if(vader.isDev){
51
+ vader.onFileChange('tailwind.config.js', async () => {
51
52
  console.log('Rebuilding TailwindCSS...')
52
53
  await vader.runCommand(['bun', 'run', 'postcss', './public/styles.css', '-o', 'dist/public/tailwind.css'])
53
54
  console.log('TailwindCSS rebuilt successfully!')
54
55
  })
56
+ }
55
57
  await vader.runCommand(['bun', 'run', 'postcss', './public/styles.css', '-o', 'dist/public/tailwind.css'])
56
58
  vader.injectHTML(`<style>${fs.readFileSync(path.resolve(process.cwd(), 'dist/public/tailwind.css'))}</style>`)
57
59
  }
58
60
 
61
+ return
59
62
  },
60
63
  onBuildFinish: async (vader) => {
61
64
  console.log('TailwindCSS plugin finished building')
@@ -1,72 +0,0 @@
1
- //@ts-nocheck
2
- import fs from 'fs'
3
- import path from 'path'
4
- function checkIfTailwindInstalled() {
5
- try {
6
- //@ts-ignore
7
- require.resolve('tailwindcss')
8
- return true
9
- } catch (e) {
10
- return false
11
- }
12
- }
13
-
14
- function initTailwind() {
15
- const tailwindConfig = path.resolve(process.cwd(), 'tailwind.config.js')
16
- const postcssConfig = path.resolve(process.cwd(), 'postcss.config.js')
17
- if(!fs.existsSync(path.join(process.cwd(), '/public/styles.css'))){
18
-
19
- fs.writeFileSync(path.join(process.cwd(), '/public/styles.css'), `
20
- @tailwind base;
21
- @tailwind components;
22
- @tailwind utilities;
23
- `)
24
- }
25
- if (!fs.existsSync(tailwindConfig)) {
26
- fs.writeFileSync(postcssConfig, `module.exports = {
27
- plugins: {
28
- tailwindcss: {},
29
- autoprefixer: {},
30
- }
31
- }`)
32
-
33
- fs.writeFileSync(tailwindConfig, `/** @type {import('tailwindcss').Config} */
34
- module.exports = {
35
- content: ['./src/**/*.{html,js,jsx,ts,tsx}', './app/**/*.{html,js,jsx,ts,tsx}'],
36
- theme: {
37
- extend: {},
38
- },
39
- plugins: [],
40
- }`)
41
-
42
- }
43
-
44
- }
45
-
46
-
47
- export default {
48
- name: 'tailwindcss',
49
- description: 'TailwindCSS plugin for Vader.js',
50
- version: '0.0.1',
51
- onBuildStart: async (vader) => {
52
- if (!checkIfTailwindInstalled()) {
53
- console.error('TailwindCSS is not installed. Please install it using `bun install tailwindcss postcss-cli autoprefixer`')
54
- process.exit(1)
55
- }else{
56
- initTailwind()
57
-
58
- vader.onFileChange('tailwind.config.js', async () => {
59
- console.log('Rebuilding TailwindCSS...')
60
- await vader.runCommand(['bun', 'run', 'postcss', './public/styles.css', '-o', 'dist/public/tailwind.css'])
61
- console.log('TailwindCSS rebuilt successfully!')
62
- })
63
- await vader.runCommand(['bun', 'run', 'postcss', './public/styles.css', '-o', 'dist/public/tailwind.css'])
64
- vader.injectHTML(`<style>${fs.readFileSync(path.resolve(process.cwd(), 'dist/public/tailwind.css'))}</style>`)
65
- }
66
-
67
- },
68
- onBuildFinish: async (vader) => {
69
- console.log('TailwindCSS plugin finished building')
70
- },
71
-
72
- }