vaderjs 1.3.3-alpha-2 → 1.3.3-alpha-4

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
@@ -64,6 +64,7 @@ public - used for anything
64
64
 
65
65
  4. And your done - Run `bun run vader --build` and the compiled output is visible inside of the `/dist/` folder!
66
66
 
67
+
67
68
  ## Key Features & Examples
68
69
 
69
70
  ### File based routing
package/package.json CHANGED
@@ -2,20 +2,12 @@
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-2",
5
+ "version": "1.3.3-alpha-4",
6
6
  "bin": {
7
- "vader": "./vader"
8
- },
9
- "scripts": {
10
- "build": "bunx vader --build",
11
- "watch": "bun run vader --watch",
12
- "help": "bunx vader"
7
+ "vader": "./vader.js"
13
8
  },
14
9
  "type": "module",
15
10
  "devDependencies": {
16
- "@types/bun": "latest"
17
- },
18
- "peerDependencies": {
19
- "typescript": "^5.0.0"
11
+ "glob": "^10.3.10"
20
12
  }
21
- }
13
+ }
@@ -10,7 +10,7 @@
10
10
  <body>
11
11
  <div id="root"></div>
12
12
  <script type="module">
13
- import VaderRouter from './public/vader/router.js'
13
+ import VaderRouter from './router.js'
14
14
 
15
15
  const router = new VaderRouter('/', 3000)
16
16
  window.router = router
package/vader.js ADDED
@@ -0,0 +1,757 @@
1
+ #!/usr/bin/env node
2
+ import fs from "fs";
3
+ import { glob, globSync, globStream, globStreamSync, Glob } from 'glob'
4
+
5
+ let bundleSize = 0;
6
+ if(!fs.existsSync(process.cwd() + '/dist')){
7
+ fs.mkdirSync(process.cwd() + '/dist')
8
+ fs.mkdirSync(process.cwd() + '/dist/public')
9
+ fs.mkdirSync(process.cwd() + '/dist/src')
10
+ fs.mkdirSync(process.cwd() + '/dist/pages')
11
+ }else if(!fs.existsSync(process.cwd() + '/dist/public')){
12
+ fs.mkdirSync(process.cwd() + '/dist/public')
13
+ }else if(!fs.existsSync(process.cwd() + '/src') && !fs.existsSync(process.cwd() + '/dist/src')){
14
+ fs.mkdirSync(process.cwd() + '/dist/src')
15
+ fs.mkdirSync(process.cwd() + '/src')
16
+ }
17
+
18
+ function Compiler(func) {
19
+ let string = func;
20
+ let comments = string
21
+
22
+ .match(/\{\s*\/\*.*\*\/\s*}/gs)
23
+ ?.map((comment) => comment.trim());
24
+
25
+ let savedfuncnames = [];
26
+ let functions = string
27
+ .match(
28
+ /(?:const|let)\s*([a-zA-Z0-9_-]+)\s*=\s*function\s*\(([^)]*)\)|function\s*([a-zA-Z0-9_-]+)\s*\(([^)]*)\)/gs
29
+ )
30
+ ?.map((match) => match.trim());
31
+
32
+ let functionNames = [];
33
+
34
+ if (functions) {
35
+ functions.forEach((func) => {
36
+ if (
37
+ !func.match(
38
+ /(?:const|let)\s*([a-zA-Z0-9_-]+)\s*=\s*function\s*\(([^)]*)\)|function\s*([a-zA-Z0-9_-]+)\s*\(([^)]*)\)/gs
39
+ )
40
+ ) {
41
+ return;
42
+ }
43
+ let code = string;
44
+
45
+ let name = func.split(" ")[1].split("(")[0].trim();
46
+
47
+ let lines = string.match(/return\s*\<>.*\<\/>/gs);
48
+
49
+ if (lines) {
50
+ for (let i = 0; i < lines.length; i++) {
51
+ let line = lines[i];
52
+
53
+ if (!functionNames.includes(name)) {
54
+ functionNames.push(name);
55
+ }
56
+ }
57
+ }
58
+ });
59
+ }
60
+ // get all Obj({}) and parse to JSON.stringify
61
+
62
+ let objects = string.match(/Obj\({.*}\)/gs);
63
+ if (objects) {
64
+ objects.forEach((obj) => {
65
+ let key = obj.split("Obj")[1].split("(")[1].split(")")[0].trim();
66
+ let newobj = obj.replaceAll(`Obj(${key})`, `${key}`);
67
+ // let newobj = obj.replaceAll(`Obj(${key})`, `JSON.parse('${key}')`)
68
+ string = string.replaceAll(obj, `this.handleObject('${newobj}')`);
69
+ });
70
+ }
71
+
72
+ let childs = [];
73
+
74
+
75
+ function extractAttributes(code) {
76
+ // Match elements with opening tags
77
+ const elementRegex = /<([a-zA-Z0-9_-]+)([^>]*)>/gs;
78
+
79
+ // Match attributes in an opening tag, including those with ={}
80
+ // Match attributes in an opening tag, including those with ={...}
81
+ const attributeRegex =
82
+ /\s*([a-zA-Z0-9_-]+)(\s*=\s*("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|\{(?:[^{}]|(?:\{(?:[^{}]|(?:\{[^{}]*\})*)*\})*)*\}|(?:\([^)]*\)|\{[^}]*\}|()=>\s*(?:\{[^}]*\})?)|\[[^\]]*\]))?/gs;
83
+
84
+ // only return elements with attribute {()=>{}} or if it also has parameters ex: onclick={(event)=>{console.log(event)}} also get muti line functions
85
+ const functionAttributeRegex =
86
+ /\s*([a-zA-Z0-9_-]+)(\s*=\s*{(?:[^{}]|(?:\{(?:[^{}]|(?:\{[^{}]*\})*)*\})*)*})/gs;
87
+
88
+ let attributesList = [];
89
+
90
+ // handle functions
91
+ let functionAttributes = [];
92
+ let functionMatch;
93
+ while ((functionMatch = functionAttributeRegex.exec(code)) !== null) {
94
+ let [, attributeName, attributeValue] = functionMatch;
95
+ let attribute = {};
96
+
97
+ if (attributeValue && attributeValue.includes("=>")) {
98
+ let ref = Math.random().toString(36).substring(2);
99
+ let old = `${attributeName}${attributeValue}`;
100
+
101
+ let newvalue =
102
+ attributeValue.split("=>")[1] || attributeValue.split("=>")[1].trim();
103
+
104
+ newvalue = newvalue.trim();
105
+
106
+ //remove starting {
107
+ newvalue = newvalue.replace("{", "");
108
+
109
+ let params = attributeValue
110
+ .split("=>")[0]
111
+ .split("(")[1]
112
+ .split(")")[0]
113
+ .trim();
114
+ let functionparams = [];
115
+ // split first {}
116
+ newvalue = newvalue.trim();
117
+
118
+ if (newvalue.startsWith("{")) {
119
+ newvalue = newvalue.split("{")[1];
120
+ }
121
+
122
+ switch(true){
123
+ case newvalue.endsWith("}}"):
124
+ newvalue = newvalue.replace("}}", "");
125
+ break;
126
+ case newvalue.endsWith("}"):
127
+ newvalue = newvalue.replace("}", "");
128
+ break;
129
+ }
130
+
131
+
132
+
133
+ if (functionNames.length > 0) {
134
+ functionNames.forEach((name) => {
135
+ string.split("\n").forEach((line) => {
136
+ if (line.includes(name) && line.includes("function")) {
137
+ line = line.trim();
138
+ line = line.replace(/\s+/g, " ");
139
+
140
+ let ps = line.split("(").slice(1).join("(").split(")")[0].trim();
141
+
142
+ // remove comments
143
+ ps = ps.match(/\/\*.*\*\//gs)
144
+ ? ps.replace(ps.match(/\/\*.*\*\//gs)[0], "")
145
+ : ps;
146
+
147
+ functionparams.push({ ref: ref, name: name, params: ps });
148
+ }
149
+ });
150
+ newvalue = newvalue.trim();
151
+ let lines = newvalue.split("\n");
152
+
153
+ for (let i = 0; i < lines.length; i++) {
154
+ let line = lines[i];
155
+
156
+ if (line.includes(name) && !line.includes("useFunction")) {
157
+ let hasParams = line.includes("(") && line.includes(")");
158
+ let params = hasParams
159
+ ? line.split("(")[1].split(")")[0].trim()
160
+ : null;
161
+
162
+ if (
163
+ functionparams.length > 0 &&
164
+ functionparams.find((p) => p.name == name)
165
+ ) {
166
+ let params = functionparams.find((p) => p.name == name).params;
167
+ line.includes(params) ? (params = params) : (params = null);
168
+ }
169
+
170
+ let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
171
+ let isJSXComponent = false;
172
+ elementMatch.forEach((element) => {
173
+ element = element.trim().replace(/\s+/g, " ");
174
+ if (element.includes(attributeName)) {
175
+ let elementTag = element
176
+ .split("<")[1]
177
+ .split(">")[0]
178
+ .split(" ")[0];
179
+ isJSXComponent = elementTag.match(/^[A-Z]/) ? true : false;
180
+ }
181
+ });
182
+
183
+ let replacement = `this.useFunction(${name} ${isJSXComponent ? "" : ","
184
+ } ${params || null}${isJSXComponent ? "" : ","} true ${isJSXComponent ? "" : ","
185
+ } '${ref}')`;
186
+
187
+ newvalue = newvalue.replace(
188
+ hasParams ? `${name}(${params})` : name,
189
+ `this.callFunction(\${${replacement}}, ${isJSXComponent ? true : false
190
+ }, event,${params || null})`
191
+ );
192
+ }
193
+ }
194
+
195
+ params = params.match(/\/\*.*\*\//gs)
196
+ ? params.replace(params.match(/\/\*.*\*\//gs)[0], "")
197
+ : params;
198
+
199
+ // get full element with function from string
200
+ let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
201
+ let isJSXComponent = false;
202
+ elementMatch.forEach((element) => {
203
+ element = element.trim().replace(/\s+/g, " ");
204
+ if (element.includes(attributeName)) {
205
+ let elementTag = element
206
+ .split("<")[1]
207
+ .split(">")[0]
208
+ .split(" ")[0];
209
+ isJSXComponent = elementTag.match(/^[A-Z]/) ? true : false;
210
+ }
211
+
212
+ });
213
+
214
+
215
+
216
+ let otherdata = {};
217
+ params ? (otherdata["params"] = params) : null;
218
+ otherdata["jsx"] = isJSXComponent;
219
+ otherdata["ref"] = ref;
220
+
221
+ newvalue = newvalue.split('\n').map(line => line.trim() ? line.trim() + ';' : line).join('\n');
222
+
223
+ let newatribute = `${attributeName}="\${this.bind(\`${newvalue}\` ${isJSXComponent ? "" : ","
224
+ }${JSON.stringify(otherdata)} )}"`;
225
+
226
+
227
+ attribute[attributeName] = {
228
+ old: old,
229
+ new: newatribute,
230
+ attribute: attributeName,
231
+ };
232
+ attributesList.push({
233
+ element: attributeName,
234
+ attributes: attribute,
235
+ });
236
+ });
237
+ }
238
+ else {
239
+ let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
240
+ let isJSXComponent = false;
241
+ elementMatch.forEach((element) => {
242
+ element = element.trim().replace(/\s+/g, " ");
243
+ if (element.includes(attributeName)) {
244
+ let elementTag = element
245
+ .split("<")[1]
246
+ .split(">")[0]
247
+ .split(" ")[0];
248
+ isJSXComponent = elementTag.match(/^[A-Z]/) ? true : false;
249
+ }
250
+
251
+ });
252
+
253
+
254
+ let otherdata = {};
255
+ params ? (otherdata["params"] = params) : null;
256
+ otherdata["jsx"] = isJSXComponent;
257
+ otherdata["ref"] = ref;
258
+ // since js is all in one line split it
259
+ newvalue = newvalue.split('\n').map(line => line.trim() ? line.trim() + ';' : line).join('\n');
260
+ let newattribute = `${attributeName}="\${this.bind(\`${newvalue}\` ${isJSXComponent ? "" : ","}${JSON.stringify(otherdata)} )}"`;
261
+ newattribute = newattribute.replace(/\s+/g, " ")
262
+ string = string.replace(old, newattribute);
263
+ }
264
+ }
265
+ }
266
+
267
+ let match;
268
+ while ((match = elementRegex.exec(code)) !== null) {
269
+ let [, element, attributes] = match;
270
+
271
+ let attributesMatch;
272
+ let elementAttributes = {};
273
+
274
+ while ((attributesMatch = attributeRegex.exec(attributes)) !== null) {
275
+ let [, attributeName, attributeValue] = attributesMatch;
276
+
277
+ elementAttributes[attributeName] = attributeValue || null;
278
+ }
279
+
280
+ attributesList.push({ element, attributes: elementAttributes });
281
+ }
282
+
283
+ return attributesList;
284
+ }
285
+
286
+ function extractOuterReturn(code) {
287
+ // match return [...]
288
+ let returns = code.match(/return\s*\<>.*\<\/>/gs);
289
+
290
+ return returns || [];
291
+ }
292
+
293
+ let outerReturn = extractOuterReturn(string);
294
+ let contents = "";
295
+ let updatedContents = "";
296
+ outerReturn.forEach((returnStatement) => {
297
+ let lines = returnStatement.split("\n");
298
+
299
+ for (let i = 0; i < lines.length; i++) {
300
+ let line = lines[i];
301
+ if (line.match(/return\s*\<>/gs)) {
302
+ continue;
303
+ }
304
+ contents += line + "\n";
305
+ }
306
+
307
+ // Remove trailing ']'
308
+ contents = contents.trim().replace(/\]$/, "");
309
+ updatedContents = contents;
310
+ let attributes = extractAttributes(contents);
311
+
312
+ let newAttributes = [];
313
+ let oldAttributes = [];
314
+ attributes.forEach((attribute) => {
315
+ const { element, attributes } = attribute;
316
+ if (Object.keys(attributes).length === 0) return;
317
+
318
+ newAttributes.push(attribute);
319
+ for (let key in attributes) {
320
+
321
+ let value = attributes[key];
322
+ let oldvalue = value;
323
+ if (value && !value.new) {
324
+ if (value && value.includes("{")) {
325
+ value = value.replace("=", "");
326
+ value == "undefined" ? (value = '"') : (value = value);
327
+ key == 'style' ? value = `{this.parseStyle({${value.split('{{')[1].split('}}')[0]}})}` : null
328
+
329
+ value = `="\$${value}"`;
330
+ string = string.replace(oldvalue, value);
331
+
332
+ } else if (value && value.includes("`")) {
333
+ value = value.replace("=", "");
334
+
335
+ value = `"\$${value}"`;
336
+ string = string.replace(oldvalue, value);
337
+
338
+ }
339
+ } else if (value && value.new) {
340
+ let newvalue = value.new;
341
+ let old = value.old;
342
+ string = string.replace(old, newvalue);
343
+ }
344
+ }
345
+ });
346
+ });
347
+
348
+ let retursnString = [];
349
+ let outerReturnString = extractOuterReturn(string);
350
+
351
+ outerReturnString.forEach((returnStatement) => {
352
+ let lines = returnStatement.split("\n");
353
+ let code = "";
354
+ for (let i = 0; i < lines.length; i++) {
355
+ let line = lines[i];
356
+ if (line.match(/return\s*\<>/gs)) {
357
+ }
358
+ code += line + "\n";
359
+ }
360
+
361
+ code = code.trim().replace(/\<\/\>$/, "");
362
+ retursnString.push(code);
363
+ });
364
+
365
+ retursnString.forEach((returnStatement, index) => {
366
+ let old = outerReturnString[index];
367
+
368
+ let newReturn = `${returnStatement}</>`;
369
+ string = string.replace(old, newReturn);
370
+ });
371
+
372
+ if (comments) {
373
+ comments.forEach((comment) => {
374
+ let before = comment.trim();
375
+
376
+ comment = comment.replaceAll(/\s+/g, " ");
377
+ comment = comment.trim();
378
+ string = string.replace(before, comment);
379
+ let to_remove = comment.split("{")[1].split("}")[0].trim();
380
+ let beforeComment = comment;
381
+ comment = comment.replaceAll(`{ ${to_remove} }`, "");
382
+
383
+ string = string.replace(beforeComment, comment);
384
+ });
385
+ }
386
+ let lines = string.split("\n");
387
+ lines.forEach((line) => {
388
+ if (
389
+ line.includes("let") ||
390
+ line.includes("const") ||
391
+ line.includes("var")
392
+ ) {
393
+ if (line.includes("useState") && !line.includes("import")) {
394
+ line = line.trim();
395
+ // derive [key, value] from line
396
+ let type = line.split(" ")[0];
397
+ let key = line
398
+ .split("=")[0]
399
+ .split(" ")[1]
400
+ .trim()
401
+ .replace("[", "")
402
+ .replace(",", "");
403
+ let setKey = line.split("=")[0].split(",")[1].trim().replace("]", "");
404
+
405
+ key = key.replace("[", "").replace(",", "");
406
+ let value = line
407
+ .split("=")[1]
408
+ .split("useState")[1]
409
+ .split("(")[1]
410
+ .split(")")[0]
411
+ .trim();
412
+ let newState = `${type} [${key}, ${setKey}] = this.useState('${key}', ${value})
413
+ this.${key} = ${key}
414
+ this.${setKey} = ${setKey}
415
+ `;
416
+
417
+ // get setkey calls and replace with this.setKey
418
+ string.split("\n").forEach((line) => {
419
+ if (line.includes(setKey) && !line.includes("useState")) {
420
+ string = string.replace(line, line);
421
+ }
422
+
423
+ if (line.includes(key)) {
424
+ line = line.replace(key, `this.states['${key}']`);
425
+
426
+ string = string.replace(line, line);
427
+ }
428
+ });
429
+ string = string.replace(line, newState);
430
+ } else if (line.includes("useRef")) {
431
+ line = line.trim();
432
+ // let ref = useRef(null)
433
+ let type = line.split(" ")[0];
434
+ let key = line.split("=")[0].split(" ")[1].trim();
435
+ let value = line
436
+ .split("=")[1]
437
+ .split("useRef")[1]
438
+ .split("(")[1]
439
+ .split(")")[0]
440
+ .trim();
441
+ let newState = `${type} ${key} = this.useRef('${key}', ${value})`;
442
+
443
+ string = string.replace(line, newState);
444
+ }
445
+ }
446
+ });
447
+
448
+ // create a polyfill for Array.prototype.filter
449
+
450
+ /**
451
+ * @method Delete
452
+ * @param {*} item
453
+ * @returns {Array} array
454
+ * @description Delete an item from an array
455
+ */
456
+ Array.prototype.delete = function (item) {
457
+ let array = this;
458
+ array.forEach((i, index) => {
459
+ switch (true) {
460
+ case typeof i === "object":
461
+ if (JSON.stringify(i) === JSON.stringify(item)) {
462
+ array.splice(index, 1);
463
+ }
464
+ break;
465
+ default:
466
+ if (i === item) {
467
+ array.splice(index, 1);
468
+ }
469
+ break;
470
+ }
471
+ });
472
+
473
+ return array;
474
+ };
475
+
476
+ // capture <Component />, <Component></Component>, and <Component>content</Component>
477
+
478
+ // Example usage
479
+ function parseComponents(body, isChild) {
480
+ let componentRegex =
481
+ /<([A-Z][a-zA-Z0-9_-]+)([^>]*)\/>|<([A-Z][a-zA-Z0-9_-]+)([^>]*)>(.*?)<\/\3>/gs;
482
+
483
+ let componentMatch = body.match(componentRegex);
484
+ let topComponent = "";
485
+ componentMatch?.forEach(async (component) => {
486
+ const rewriter = new HTMLRewriter();
487
+ let [, element, attributes] = component;
488
+
489
+ !isChild ? (topComponent = component) : null;
490
+ let before = component;
491
+ component = component.trim().replace(/\s+/g, " ");
492
+
493
+ let myChildrens = [];
494
+
495
+ let name = component.split("<")[1].split(">")[0].split(" ")[0].replace("/", "");
496
+ let props = component.split(`<${name}`)[1].split(">")[0].trim();
497
+
498
+ let savedname = name;
499
+ let children = props
500
+ ? component
501
+ .split(`<${name}`)[1]
502
+ .split(`${props}`)[1]
503
+ .split(`</${name}>`)[0]
504
+ .trim()
505
+ .replace(">", "")
506
+ : component.split(`<${name}`)[1].split(`</${name}>`)[0].trim().replace(">", "");
507
+ name = name + Math.random().toString(36).substring(2);
508
+ if (children && children.match(componentRegex)) {
509
+ children = parseComponents(children, true);
510
+ childs.push({ parent: name, children: children });
511
+ } else {
512
+
513
+ children = `\`${children}\`,`;
514
+ children ? childs.push({ parent: name, children: children }) : null;
515
+ }
516
+
517
+ childs.forEach((child) => {
518
+ if (child.parent == name) {
519
+ let html = child.children.match(
520
+ /<([a-zA-Z0-9_-]+)([^>]*)>(.*?)<\/\1>/gs
521
+ );
522
+ if (html) {
523
+ html = html.map((h) => h.trim().replace(/\s+/g, " ")).join(" ");
524
+ let before = child.children;
525
+ child.children = child.children.replaceAll(html, `${html}`);
526
+ // remove duplicate quotes
527
+ }
528
+
529
+ myChildrens.push(child.children);
530
+ }
531
+ });
532
+
533
+ props = props
534
+ .replaceAll("=", ":")
535
+ .replaceAll('"', "'")
536
+ .replaceAll(" ", ",")
537
+ .replaceAll(",,", ',')
538
+ .replaceAll("className", "class")
539
+ .replaceAll("classname", "class")
540
+ .replaceAll("'${", "")
541
+ .replaceAll("}'", "")
542
+ .split("$:")
543
+ .join("")
544
+ .replaceAll("-", "");
545
+
546
+ //remove trailing /
547
+ props = props.replace("/", "");
548
+ let replace = "";
549
+ replace = isChild
550
+ ? `this.memoize(this.createComponent(${savedname.replaceAll('/', '')}, {${props}}, [${myChildrens.length > 0 ? myChildrens.join(",") : ""
551
+ }])),`
552
+ : `\${this.memoize(this.createComponent(${savedname.replaceAll('/', '')}, {${props}}, [${myChildrens.length > 0 ? myChildrens.join(",") : ""
553
+ }]))}`;
554
+
555
+ body = body.replace(before, replace);
556
+ });
557
+
558
+ return body;
559
+ }
560
+
561
+
562
+
563
+ string = string.replaceAll("<>", "`").replaceAll("</>", "`");
564
+ string = parseComponents(string);
565
+
566
+ string = string
567
+ .replaceAll("className", "class")
568
+ .replaceAll("classname", "class");
569
+
570
+ string += `\n\n //wascompiled`;
571
+
572
+ string = string.replaceAll("undefined", "");
573
+
574
+ return string;
575
+ }
576
+ let bindings = []
577
+ globalThis.isBuilding = false
578
+ async function Build() {
579
+ globalThis.isBuilding = true
580
+ console.log('Compiling......')
581
+ let reader = async (file) => {
582
+ let text = await fs.readFileSync(file, "utf8");
583
+ return text;
584
+ };
585
+ let writer = async (file, data) => {
586
+ switch (true) {
587
+ case !fs.existsSync(file):
588
+ fs.mkdirSync(file.split('/').slice(0, -1).join('/'), { recursive: true })
589
+ break;
590
+ }
591
+ await fs.writeFileSync(file, data);
592
+
593
+ return { _written: true };
594
+ };
595
+
596
+
597
+ const glb = await glob("**/**/**/**.{jsx,js}", {
598
+ ignore: ["node_modules/**/*", "dist/**/*"],
599
+ cwd: process.cwd() + '/pages/',
600
+ absolute: true,
601
+ recursive: true
602
+ });
603
+ for await (let file of glb) {
604
+
605
+ let origin = file.split(process.cwd())[1] || file
606
+ let fileName = file.split(process.cwd() + '/pages/')[1]
607
+ file = file.split(process.cwd() + '/pages/')[1]
608
+
609
+ file === 'index.jsx' ? file = '/' : null
610
+ let isBasePath = file === '/' ? true : false
611
+ // ex: /pages/index.jsx - / or /pages/[id].jsx - /:id or /pages/folder/index.jsx - /folder
612
+ let aburl = origin.split('pages')[1].split('.jsx')[0].replace('.jsx', '').replace('/index', '').replace('/_', '/:').replace('/[', '/:').replace(']', '')
613
+
614
+ aburl.includes('[') ? aburl = '/' + aburl.split('[')[0].replace('/', '') : null
615
+
616
+
617
+
618
+
619
+
620
+
621
+ let obj = {
622
+ url: isBasePath ? '/' : aburl,
623
+ pathname: origin,
624
+ }
625
+ let data = await reader(process.cwd() + origin)
626
+
627
+ data = Compiler(data)
628
+ await writer(process.cwd() + "/dist/pages/" + fileName, data);
629
+ let params = obj.params ? Object.keys(obj.params).map((r) => {
630
+ r = r.replace('[', '').replace(']', '')
631
+ return `:${r}`
632
+ }) : ''
633
+
634
+
635
+
636
+
637
+
638
+ let js = `
639
+ router.get('${obj.url}', async (req, res) => {
640
+ res.render(await require('.${obj.pathname}'), req, res)
641
+ })
642
+ //@desc ${obj.pathname}
643
+ ` + '\n'
644
+
645
+
646
+
647
+ let before = fs.existsSync(process.cwd() + "/dist/app.js") ? await reader(process.cwd() + "/dist/app.js") : ''
648
+
649
+ let newfile = before + '\n' + js
650
+ if (!before.includes(`//@desc ${obj.pathname}`)) {
651
+ await writer(process.cwd() + "/dist/app.js", newfile);
652
+ }
653
+
654
+ }
655
+
656
+
657
+ const scannedSourceFiles = await glob("**/**.{jsx,js}", {
658
+ ignore: ["node_modules/**/*", "dist/**/*"],
659
+ cwd: process.cwd() + '/src/',
660
+ absolute: true,
661
+ });
662
+ scannedSourceFiles.forEach(async (file) => {
663
+
664
+ file = file.split(process.cwd() + '/src/')[1]
665
+ let data = await reader(process.cwd() + "/src/" + file)
666
+ bundleSize += fs.statSync(process.cwd() + "/src/" + file).size;
667
+ if(file.endsWith('.jsx')){
668
+ data = Compiler(data)
669
+ }
670
+
671
+ await writer(process.cwd() + "/dist/src/" + file, data);
672
+ })
673
+
674
+ const scannedPublicFiles = await glob("**/**.{css,js,html}", {
675
+ ignore: ["node_modules/**/*", "dist/**/*"],
676
+ cwd: process.cwd() + '/public/',
677
+ absolute: true,
678
+ });
679
+ scannedPublicFiles.forEach(async (file) => {
680
+ file = file.split(process.cwd() + '/public/')[1]
681
+ let data = await reader(process.cwd() + "/public/" + file)
682
+ bundleSize += fs.statSync(process.cwd() + "/public/" + file).size;
683
+ await writer(process.cwd() + "/dist/public/" + file, data);
684
+ })
685
+ const scannedFiles = await glob("**/**.{css,js,html}", {
686
+ ignore: ["node_modules/**/*", "dist/**/*"],
687
+ cwd: process.cwd() + "/runtime/",
688
+ absolute: true,
689
+ })
690
+
691
+ if (!fs.existsSync(process.cwd() + "/dist/index.html")) {
692
+ scannedFiles.forEach(async (file) => {
693
+ file = file.split(process.cwd() + '/runtime/')[1]
694
+
695
+ if (file === "app.js") {
696
+ return
697
+ }
698
+ bundleSize += fs.statSync(process.cwd() + "/runtime/" + file).size;
699
+ let data = await reader(process.cwd() + "/runtime/" + file)
700
+ await writer(process.cwd() + "/dist/" + file, data);
701
+ });
702
+
703
+ }
704
+
705
+
706
+ console.log(`Compilation completed`)
707
+ globalThis.isBuilding = false
708
+ }
709
+ import { watch } from "fs";
710
+ import { url } from "inspector";
711
+
712
+ switch (true) {
713
+ case process.argv.includes('--watch'):
714
+
715
+ console.log(`
716
+ Vader.js v1.3.3
717
+ `)
718
+ Build()
719
+
720
+ const watcher = watch(
721
+ process.cwd() + '/pages',
722
+ { recursive: true },
723
+ (event, filename) => {
724
+ if (event == 'change'
725
+ && !globalThis.isBuilding
726
+ ) {
727
+ Build()
728
+ }
729
+ },
730
+ );
731
+ watcher.on('error', (err) => console.log(err))
732
+
733
+ break;
734
+ case process.argv.includes('--build'):
735
+
736
+ console.log(`
737
+ Vader.js v1.3.3
738
+ Building to ./dist
739
+ `)
740
+ Build()
741
+ break;
742
+ default:
743
+ console.log(`
744
+ Vader.js is a reactive framework for building interactive applications for the web built ontop of bun.js!
745
+
746
+ Usage: vader <command>
747
+
748
+ Commands:
749
+ --watch Watch the pages folder for changes and recompile
750
+
751
+ --build Build the project
752
+ Learn more about vader: https://vader-js.pages.dev/
753
+
754
+ `)
755
+ break;
756
+
757
+ }
package/vader DELETED
Binary file