vaderjs 1.4.0-90gbho234 → 1.4.1-d560b9aa7f

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/binaries/main.js CHANGED
@@ -1,676 +1,1318 @@
1
1
  import { Glob } from "bun";
2
- import fs from "fs";
2
+
3
+ import fs from "fs";
4
+
3
5
  import * as Bun from "bun";
4
- import WebSocket from 'ws'
5
- let config = await import(process.cwd() + '/vader.config.js').then((m) => m ? m.default : {}).catch((e) => {
6
- console.error(e)
7
- return {}
8
- })
6
+
7
+ let config = await import(process.cwd() + "/vader.config.js")
8
+ .then((m) => (m ? m.default : {}))
9
+ .catch((e) => {
10
+ return {};
11
+ });
12
+
13
+ async function checkIFUptodate() {
14
+ let lts = await fetch("https://registry.npmjs.org/vaderjs").then((res) =>
15
+ res.json()
16
+ );
17
+ let latest = lts["dist-tags"].latest;
18
+ let current = JSON.parse(
19
+ fs.readFileSync(process.cwd() + "/node_modules/vaderjs/package.json")
20
+ ).version;
21
+ return {
22
+ latest,
23
+ current,
24
+ };
25
+ }
26
+
27
+ import IPCServer from "vaderjs/binaries/IPC/index.js";
28
+ import { exec } from "child_process";
29
+
30
+ const IPC = IPCServer;
31
+
32
+ globalThis.isVader = true;
33
+
34
+ /**
35
+
36
+ * @description - Call functions when the integration is triggered
37
+
38
+ * @param {function} fn
39
+
40
+ * @param {args} args
41
+
42
+ */
43
+
44
+ globalThis.call = async (fn, args) => {
45
+ return (await fn(args)) || void 0;
46
+ };
47
+
9
48
  /**@description - Used to store hmr websocket clients */
10
- globalThis.clients = []
49
+
50
+ globalThis.clients = [];
51
+
11
52
  /**@description - Used to keep track of routes */
12
- globalThis.routes = []
53
+
54
+ globalThis.routes = [];
55
+
13
56
  /**
57
+
14
58
  * @description - Used to keep track of the mode
59
+
15
60
  */
16
- globalThis.mode = 'dev'
61
+
62
+ globalThis.mode = "";
63
+
17
64
  /**@usedby @transForm */
18
- globalThis.isBuilding = false
19
- globalThis.hasGenerated = []
65
+
66
+ globalThis.isBuilding = false;
67
+
68
+ globalThis.hasGenerated = [];
69
+
70
+ let currentState = "";
71
+
20
72
  /**
73
+
21
74
  * @description - Used to keep track of the bundle size
75
+
22
76
  */
23
- let bundleSize = 0
24
77
 
25
-
26
- if(globalThis.mode === 'dev'){
27
- Bun.spawn({
28
- cwd: process.cwd() + '/node_modules/vaderjs/binaries/',
29
- env: {
30
- PWD: process.cwd(),
31
- onExit: (code) => {
32
- globalThis.isBuilding = false
33
- globalThis.oneAndDone = true
34
- }
35
- },
36
- cmd: ['node', 'generator.js'],
37
- })
38
- globalThis.generatorWs = new WebSocket(`ws://localhost:${3436}`)
39
- globalThis.generatorWs.on('message', (message) => {
40
- let data = JSON.parse(message.toString())
41
- switch(true){
42
- case data.type === 'done':
43
- let file = data.file
44
- globalThis.hasGenerated.push(file)
45
- console.log('Generated', file)
46
- break;
47
- case data.type === 'error':
48
- console.error(data.message)
49
- break;
50
- }
51
- })
52
- globalThis.generatorWs.on('connection', (ws) => {
53
- console.log('Connected to generator...')
54
- })
55
-
56
- if(!globalThis.generatorWs.readyState === 1){
57
- console.log('Generator is not ready...')
58
- }
59
- }
60
-
78
+ let bundleSize = 0;
79
+
61
80
  /**
81
+
62
82
  * @description - variables used to generate arrays of paths recursively
83
+
63
84
  */
64
- const glob = new Glob("/pages/**/**/*.{,tsx,js,jsx}", {absolute: true});
65
- const vaderGlob = new Glob("/node_modules/vaderjs/runtime/**/**/*.{,tsx,js}", {absolute: true});
66
- const srcGlob = new Glob("/src/**/**/*.{jsx,ts,tsx,js}", {absolute: true});
67
- const publicGlob = new Glob("/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}", {absolute: true});
68
- const distPages = new Glob("/dist/pages/**/**/*.{tsx,js,jsx}", {absolute: true})
69
- const distSrc = new Glob("/dist/src/**/**/*.{tsx,js,jsx}", {absolute: true})
70
- const distPublic = new Glob("/dist/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}", {absolute: true});
85
+
86
+ const glob = new Glob("/pages/**/**/*.{,tsx,js,jsx,md}", {
87
+ absolute: true,
88
+ });
89
+
90
+ const vaderGlob = new Glob("/node_modules/vaderjs/runtime/**/**/*.{,tsx,js}", {
91
+ absolute: true,
92
+ });
93
+
94
+ const srcGlob = new Glob("/src/**/**/*.{jsx,ts,tsx,js}", {
95
+ absolute: true,
96
+ });
97
+
98
+ const publicGlob = new Glob(
99
+ "/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}",
100
+ {
101
+ absolute: true,
102
+ }
103
+ );
104
+
105
+ const distPages = new Glob("/dist/pages/**/**/*.{tsx,js,jsx}", {
106
+ absolute: true,
107
+ });
108
+
109
+ const distSrc = new Glob("/dist/src/**/**/*.{tsx,js,jsx}", {
110
+ absolute: true,
111
+ });
112
+
113
+ const distPublic = new Glob(
114
+ "/dist/public/**/**/*.{css,js,html,jpg,png,gif,svg,ico,video,webm,mp4,jpeg}",
115
+ {
116
+ absolute: true,
117
+ }
118
+ );
71
119
 
72
120
  const router = new Bun.FileSystemRouter({
73
- style: "nextjs",
74
- dir: process.cwd() + '/pages',
75
- origin: process.env.ORIGIN || "http://localhost:3000",
76
- assetPrefix: "_next/static/"
77
- });
121
+ style: "nextjs",
122
+
123
+ dir: process.cwd() + "/pages",
124
+
125
+ origin: process.env.ORIGIN || "http://localhost:3000",
126
+
127
+ assetPrefix: "_next/static/",
128
+ });
129
+
78
130
  /**
131
+
79
132
  * @function handleReplaceMents
133
+
80
134
  * @description - replaces data to be compatible with Vader.js
135
+
81
136
  * @param {*} data
137
+
82
138
  * @returns
139
+
83
140
  */
84
- function handleReplaceMents(data){
85
- data.split('\n').forEach((line, index)=>{
86
- switch(true){
87
-
88
- case line.includes('useReducer') && !line.includes('import'):
89
- line = line.replaceAll(/\s+/g, " ");
90
-
91
- let varTypereducer = line.split("=")[0].trim().split("[")[0].trim();
92
- let keyreducer = line.split("=")[0].trim().split("[")[1].trim().split(",")[0].trim();
93
- let setKeyreducer = line.split("=")[0].trim().split(",")[1].trim().replace("]", "");
94
- let reducer = line.split("=")[1].split("useReducer(")[1];
95
-
96
- let newStatereducer = `${varTypereducer} [${keyreducer}, ${setKeyreducer}] = this.useReducer('${keyreducer}', ${line.includes('=>') ? reducer + '=>{' : reducer}`;
97
-
98
- data = data.replace(line, newStatereducer);
99
- break
100
-
101
- case line.includes('useState') && !line.includes('import'):
102
- let varType = line.split("[")[0]
103
- if (!line.split("=")[0].split(",")[1]) {
104
- throw new Error('You forgot to value selector (useState) ' + ' at ' + `${file}:${string.split(line)[0].split('\n').length}`)
105
- }
106
- let key = line.split("=")[0].split(",")[0].trim().split('[')[1];
141
+ const cssToObj = (css) => {
142
+ let styles = {};
143
+ let currentSelector = "";
107
144
 
108
- if (!line.split("=")[0].split(",")[1]) {
109
- throw new Error('You forgot to add a setter (useState) ' + ' at ' + `${file}:${string.split(line)[0].split('\n').length}`)
110
- }
111
- let setKey = line.split("=")[0].split(",")[1].trim().replace("]", "");
112
- key = key.replace("[", "").replace(",", "");
113
- let valuestate = line.split("=")[1].split("useState(")[1];
114
-
115
- let regex = /useState\((.*)\)/gs;
116
- valuestate = valuestate.match(regex) ? valuestate.match(regex)[0].split("useState(")[1].split(")")[0].trim() : valuestate
117
- let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}`;
118
- data = data.replace(line, newState);
119
- break;
120
-
121
- case line.includes("useRef") && !line.includes("import"):
122
- line = line.trim();
123
- let typeref = line.split(" ")[0]
145
+ css.split("\n").forEach((line) => {
146
+ line = line.trim();
124
147
 
125
- let keyref = line.split(typeref)[1].split("=")[0].trim().replace("[", "").replace(",", "");
148
+
149
+ if (line.endsWith("{")) {
150
+ // Start of a block, extract the selector
151
+ currentSelector = line.slice(0, -1).trim();
152
+ currentSelector = currentSelector.replace(/-./g, (x) => x[1].toUpperCase());
153
+ currentSelector = currentSelector.replace('.', '');
154
+ styles[currentSelector] = {};
155
+ } else if (line.endsWith("}")) {
156
+ // End of a block
157
+ currentSelector = "";
158
+ } else if (line.includes(":") && currentSelector) {
159
+ // Inside a block and contains key-value pair
160
+ let [key, value] = line.split(":").map((part) => part.trim());
161
+ styles[currentSelector][key] = value;
162
+ }
163
+ });
126
164
 
165
+ return styles;
166
+ };
127
167
 
128
- let valueref = line.split("=")[1].split("useRef(")[1];
168
+ function handleReplaceMents(data) {
169
+ data.split("\n").forEach(async (line, index) => {
170
+ switch (true) {
171
+ case line.includes("import") && line.includes("module.css"):
172
+ let path = line.split("from")[1].trim().split(";")[0].trim();
173
+ let name = line.split("import")[1].split("from")[0].trim();
174
+ path = path.replace(";", "");
175
+ path = path.replace(/'/g, "").trim().replace(/"/g, "").trim();
176
+ path = path.replaceAll(".jsx", ".js");
177
+ path = path.replaceAll("../", "");
178
+ let css = fs.readFileSync(process.cwd() + "/" + path, "utf8");
179
+ let styles = cssToObj(css);
180
+ let style = JSON.stringify(styles);
181
+ let newLine = `let ${name} = ${style}`;
182
+ data = data.replace(line, newLine);
129
183
 
130
- let newStateref = `${typeref} ${keyref} = this.useRef('${keyref}', ${valueref}`;
131
- data = data.replace(line, newStateref);
132
- case line.includes('.jsx') && line.includes('import') || line.includes('.tsx') && line.includes('import'):
133
- let old = line
134
- line = line.replace('.jsx', '.js')
135
- line = line.replace('.tsx', '.js')
136
- data = data.replace(old, line)
137
-
138
- break;
184
+ break;
185
+
186
+ case line.includes("useReducer") && !line.includes("import"):
187
+ line = line.replaceAll(/\s+/g, " ");
188
+
189
+ let varTypereducer = line.split("=")[0].trim().split("[")[0].trim();
190
+
191
+ let keyreducer = line
192
+ .split("=")[0]
193
+ .trim()
194
+ .split("[")[1]
195
+ .trim()
196
+ .split(",")[0]
197
+ .trim();
198
+
199
+ let setKeyreducer = line
200
+ .split("=")[0]
201
+ .trim()
202
+ .split(",")[1]
203
+ .trim()
204
+ .replace("]", "");
205
+
206
+ let reducer = line.split("=")[1].split("useReducer(")[1];
207
+
208
+ let newStatereducer = `${varTypereducer} [${keyreducer}, ${setKeyreducer}] = this.useReducer('${keyreducer}', ${
209
+ line.includes("=>") ? reducer + "=>{" : reducer
210
+ }`;
211
+
212
+ data = datam(line, newStatereducer);
213
+
214
+ break;
215
+
216
+ case line.includes("useState") && !line.includes("import"):
217
+ let varType = line.split("[")[0];
218
+
219
+ if (!line.split("=")[0].split(",")[1]) {
220
+ throw new Error(
221
+ "You forgot to value selector (useState) " +
222
+ " at " +
223
+ `${file}:${string.split(line)[0].split("\n").length}`
224
+ );
139
225
  }
140
- })
141
-
142
- data = data.replaceAll('jsxDEV', 'Vader.createElement')
143
- data = data.replaceAll('jsx', 'Vader.createElement')
144
- data = data.replaceAll('vaderjs/client', '/vader.js')
145
- data = data.replaceAll('.tsx', '.js')
146
- let reactImportMatch = data.match(/import React/g);
147
- if(reactImportMatch){
148
- let fullmatch = data.match(/import React from "react"/g);
149
- if(fullmatch){
150
- data = data.replaceAll('import React from "react"', '');
151
- }
226
+
227
+ let key = line.split("=")[0].split(",")[0].trim().split("[")[1];
228
+
229
+ if (!line.split("=")[0].split(",")[1]) {
230
+ throw new Error(
231
+ "You forgot to add a setter (useState) " +
232
+ " at " +
233
+ `${file}:${string.split(line)[0].split("\n").length}`
234
+ );
235
+ }
236
+
237
+ let setKey = line.split("=")[0].split(",")[1].trim().replace("]", "");
238
+
239
+ key = key.replace("[", "").replace(",", "");
240
+
241
+ let valuestate = line.split("=")[1].split("useState(")[1];
242
+
243
+ let regex = /useState\((.*)\)/gs;
244
+
245
+ valuestate = valuestate.match(regex)
246
+ ? valuestate
247
+ .match(regex)[0]
248
+ .split("useState(")[1]
249
+ .split(")")[0]
250
+ .trim()
251
+ : valuestate;
252
+
253
+ let newState = `${varType} [${key}, ${setKey}] = this.useState('${key}', ${valuestate}`;
254
+
255
+ data = data.replace(line, newState);
256
+
257
+ break;
258
+
259
+ case line.includes("useRef") && !line.includes("import"):
260
+ line = line.trim();
261
+
262
+ let typeref = line.split(" ")[0];
263
+
264
+ let keyref = line
265
+ .split(typeref)[1]
266
+ .split("=")[0]
267
+ .trim()
268
+ .replace("[", "")
269
+ .replace(",", "");
270
+
271
+ let valueref = line.split("=")[1].split("useRef(")[1];
272
+
273
+ let newStateref = `${typeref} ${keyref} = this.useRef('${keyref}', ${valueref}`;
274
+
275
+ data = data.replace(line, newStateref);
276
+
277
+ case (line.includes(".jsx") && line.includes("import")) ||
278
+ (line.includes(".tsx") && line.includes("import")):
279
+ let old = line;
280
+
281
+ line = line.replace(".jsx", ".js");
282
+
283
+ line = line.replace(".tsx", ".js");
284
+
285
+ data = data.replace(old, line);
286
+
287
+ break;
152
288
  }
153
- data = data.replaceAll('.ts', '.js')
289
+ });
290
+
291
+ data = data.replaceAll("jsxDEV", "Vader.createElement");
292
+
293
+ data = data.replaceAll("jsx", "Vader.createElement");
294
+
295
+ data = data.replaceAll("vaderjs/client", "/vader.js");
296
+
297
+ data = data.replaceAll(".tsx", ".js");
298
+
299
+ let reactImportMatch = data.match(/import React/g);
154
300
 
155
- // check if Vader is imported
156
- let vaderImport = data.match(/import Vader/g);
157
- if(!vaderImport){
158
- data = `import Vader from "/vader.js";\n` + data;
301
+ if (reactImportMatch) {
302
+ let fullmatch = data.match(/import React from "react"/g);
303
+
304
+ if (fullmatch) {
305
+ data = data.replaceAll('import React from "react"', "");
159
306
  }
160
- return data;
307
+ }
308
+
309
+ data = data.replaceAll(".ts", ".js");
310
+
311
+ // check if Vader is imported
312
+
313
+ let vaderImport = data.match(/import Vader/g);
314
+
315
+ if (!vaderImport) {
316
+ data = `import Vader from "/vader.js";\n` + data;
317
+ }
318
+
319
+ return data;
161
320
  }
162
-
163
321
 
164
322
  /**
323
+
165
324
  * @function ContentType
325
+
166
326
  * @description - returns the content type based on the file extension
327
+
167
328
  * @param {*} url
329
+
168
330
  * @returns
331
+
169
332
  */
170
- const ContentType = (url)=>{
171
- switch(url.split('.').pop()){
172
- case 'css':
173
- return 'text/css';
174
- case 'js':
175
- return 'text/javascript';
176
- case 'json':
177
- return 'application/json';
178
- case 'html':
179
- return 'text/html';
180
- case 'jpg':
181
- return 'image/jpg';
182
- case 'png':
183
- return 'image/png';
184
- case 'gif':
185
- return 'image/gif';
186
- case 'svg':
187
- return 'image/svg+xml';
188
- case 'ico':
189
- return 'image/x-icon';
190
- default:
191
- return 'text/html';
192
-
193
- }
194
- }
195
-
333
+
334
+ const ContentType = (url) => {
335
+ switch (url.split(".").pop()) {
336
+ case "css":
337
+ return "text/css";
338
+
339
+ case "js":
340
+ return "text/javascript";
341
+
342
+ case "json":
343
+ return "application/json";
344
+
345
+ case "html":
346
+ return "text/html";
347
+
348
+ case "jpg":
349
+ return "image/jpg";
350
+
351
+ case "png":
352
+ return "image/png";
353
+
354
+ case "gif":
355
+ return "image/gif";
356
+
357
+ case "svg":
358
+ return "image/svg+xml";
359
+
360
+ case "webp":
361
+ return "image/webp";
362
+ case "ico":
363
+ return "image/x-icon";
364
+
365
+ default:
366
+ return "text/html";
367
+ }
368
+ };
369
+
370
+ /**
371
+
372
+ * @function Server
373
+
374
+ * @description - Creates a hmr development server
375
+
376
+ * @param {Number} port
377
+
378
+ */
379
+
380
+ function Server(port) {
381
+ Bun.serve({
382
+ port: port,
383
+
384
+ async fetch(req, res) {
385
+ const url = new URL(req.url);
386
+
387
+ const success = res.upgrade(req);
388
+
389
+ if (success) {
390
+ return new Response("Connected", {
391
+ headers: {
392
+ "Content-Type": "text/html",
393
+ },
394
+ });
395
+ }
396
+
397
+ if (req.url.includes(".")) {
398
+ if (!fs.existsSync(process.cwd() + "/dist" + url.pathname)) {
399
+ return new Response("Not Found", {
400
+ status: 404,
401
+
402
+ headers: {
403
+ "Content-Type": "text/html",
404
+ },
405
+ });
406
+ }
407
+
408
+ console.log(`HTTP GET: ${url.pathname} -> ${ContentType(req.url)}`);
409
+ return new Response(
410
+ fs.readFileSync(process.cwd() + "/dist" + url.pathname),
411
+ {
412
+ headers: {
413
+ "Content-Type": ContentType(req.url),
414
+ },
415
+ }
416
+ );
417
+ }
418
+
419
+ let matchedRoute =
420
+ router.match(url.pathname)
421
+
422
+ if (matchedRoute) {
423
+ let { filePath, kind, name, params, pathname, query, scriptSrc, isAbsolute } =
424
+ matchedRoute;
425
+
426
+ scriptSrc = scriptSrc.split("pages").pop().split("index.js").shift().split('_next/static')[1]
427
+ // split the furthest file and turn it into index.js
428
+ scriptSrc = scriptSrc.split('/').filter(f => f !== '').join('/')
429
+ // ex: .JSX -> .JS
430
+ scriptSrc.includes('[[...catchall]]') ? scriptSrc = scriptSrc.replace('[[...catchall]]', 'index.js') : scriptSrc = scriptSrc.replace('.jsx', '.js')
431
+ // split if it has a param
432
+ if(scriptSrc.includes('[')){
433
+ scriptSrc = scriptSrc.split('[').shift() + 'index.js'
434
+ }
435
+ scriptSrc = scriptSrc.split('index.js').shift() + 'index.js'
196
436
 
197
- /**
198
- * @function Server
199
- * @description - Creates a hmr development server
200
- * @param {Number} port
201
- */
202
- function Server(port){
203
- Bun.serve({
204
- port: port,
205
- fetch(req, res){
206
- const url = new URL(req.url);
207
- const success = res.upgrade(req);
208
- if(success){
209
- return new Response('Connected', {
210
- headers: {
211
- "Content-Type": "text/html"
212
- }
213
- })
214
- }
215
- if(req.url.includes('.')){
216
- return new Response(fs.readFileSync(process.cwd() + '/dist/' + url.pathname, 'utf8'), {
217
- headers: {
218
- "Content-Type": ContentType(req.url)
219
- }
220
- })
221
- }
222
- let matchedRoute = router.match(url.pathname);
223
- if(matchedRoute){
224
- let {filePath, kind, name, params, pathname, query,} = matchedRoute
225
- let folder = url.pathname.split('/')[1]
226
- let jsFile = filePath.split('pages/').pop().split('.').shift() + '.js'
227
- let pageContent = fs.readFileSync(process.cwd() + '/dist/pages/' + folder + '/index.html', 'utf8')
228
- globalThis.mode === 'dev' ? pageContent += `
437
+ let folder = '/' +scriptSrc.split("index.js").shift();
438
+ folder = folder
439
+ .split("/")
440
+ .filter((f) => f !== "dist")
441
+ .join("/");
442
+ let pageContent = fs.readFileSync(
443
+ process.cwd() + "/dist/" + folder + "/index.html",
444
+ "utf8"
445
+ );
446
+
447
+ globalThis.mode === "dev"
448
+ ? (pageContent += `
449
+
229
450
  <script type="module">
451
+
230
452
  let ws = new WebSocket('ws://localhost:${port}');
453
+
231
454
  ws.onmessage = async (e) => {
455
+
232
456
  if(e.data === 'reload'){
457
+
233
458
  window.location.reload()
459
+
234
460
  console.log('Reloading...')
461
+
235
462
  }
463
+
236
464
  }
465
+
237
466
  </script>
238
- ` : void 0
239
- return new Response( pageContent, {
240
- headers: {
241
- "Content-Type": "text/html",
242
- "X-Powered-By": "Vader.js v1.3.3"
243
- }
244
- })
245
- }
246
-
247
- return new Response('Not Found', {
248
- status: 404,
249
- headers: {
250
- "Content-Type": "text/html"
251
- }
252
- })
467
+
468
+ `)
469
+ : void 0;
470
+
471
+ return new Response(pageContent, {
472
+ headers: {
473
+ "Content-Type": "text/html",
474
+
475
+ "X-Powered-By": "Vader.js v1.3.3",
476
+ },
477
+ });
478
+ }
479
+
480
+ return new Response("Not Found", {
481
+ status: 404,
482
+
483
+ headers: {
484
+ "Content-Type": "text/html",
253
485
  },
254
- websocket: {
255
- open(ws){
256
- clients.push(ws)
257
- },
258
- }
259
- })
486
+ });
487
+ },
488
+
489
+ websocket: {
490
+ open(ws) {
491
+ clients.push(ws);
492
+ },
493
+ },
494
+ });
260
495
  }
496
+
261
497
  /**
498
+
262
499
  * @function write
500
+
263
501
  * @description - Writes data to a file
502
+
264
503
  * @returns {void} 0
504
+
265
505
  * @param {string} file
506
+
266
507
  * @param {any} data
508
+
267
509
  * @returns
510
+
268
511
  */
269
- const write = (file, data) => {
270
- try {
271
- if(!fs.existsSync('./dist')){
272
- fs.mkdirSync('./dist')
273
- }
274
- Bun.write(file, data);
275
- } catch (error) {
276
- console.error(error)
512
+
513
+ const write = (file, data) => {
514
+ try {
515
+ if (!fs.existsSync("./dist")) {
516
+ fs.mkdirSync("./dist");
277
517
  }
278
-
279
- }
518
+
519
+ Bun.write(file, data);
520
+ } catch (error) {
521
+ console.error(error);
522
+ }
523
+ };
524
+
280
525
  /**
526
+
281
527
  * @function read
528
+
282
529
  * @param {path} file
530
+
283
531
  * @returns {Promise<string>}
532
+
284
533
  */
534
+
285
535
  const read = async (file) => {
286
- return await Bun.file(file).text();
536
+ return await Bun.file(file).text();
537
+ };
538
+
539
+ /**
540
+
541
+ * @object integrationStates
542
+
543
+ * @description - Used to store integration states
544
+
545
+ */
546
+
547
+ globalThis.integrationStates = [];
548
+
549
+ /**
550
+
551
+ * @description a boolean value that checks if vader is being used - useful for running toplevel code at integration start
552
+
553
+ */
554
+
555
+ globalThis.context = {
556
+ vader: true,
557
+ };
558
+
559
+ /**
560
+
561
+ * @function handleIntegrations
562
+
563
+ * @description - Handles module integrations that add more functionality to Vader.js
564
+
565
+ * @returns {void} 0
566
+
567
+ */
568
+
569
+ function handleIntegrations() {
570
+ if (config?.integrations) {
571
+ config.integrations.forEach((integration) => {
572
+ let int = integration;
573
+
574
+ globalThis.integrationStates.push(int);
575
+ });
576
+ }
577
+
578
+ return void 0;
287
579
  }
288
580
 
581
+ handleIntegrations();
582
+
289
583
  /**
584
+
290
585
  * @function generateProviderRoutes
586
+
291
587
  * @description - Generates routes for hosting provders ie: vercel, cloudflare
588
+
292
589
  * @returns {void} 0
590
+
293
591
  */
294
- async function generateProviderRoutes(){
295
- if(!config?.host?.provider){
296
- console.warn('No provider found in vader.config.js ignoring route generation...')
592
+
593
+ async function generateProviderRoutes() {
594
+ if (!config?.host?.provider) {
595
+ console.warn(
596
+ "No provider found in vader.config.js ignoring route generation..."
597
+ );
598
+
297
599
  return void 0;
298
- }
299
- let providerType = [{
300
- provider: 'vercel',
301
- file: 'vercel.json',
302
- out: process.cwd() + '/vercel.json',
303
- obj: {
304
- rewrites:[]
305
- }
306
- },{
307
- provider: 'cloudflare',
308
- file:'_redirects',
309
- out: 'dist/_redirects'
310
- }]
311
-
312
- let provider = providerType.find((p) => p.provider === config.host.provider)
313
- if(provider){
314
- let prev = null
315
-
316
- switch(provider.provider){
317
- case 'vercel':
318
- prev = await read(provider.out);
319
- if(!prev.includes('rewrites')){
320
- prev = []
321
- } else{
322
- prev = JSON.parse(prev).rewrites
323
- }
324
- routes.forEach((r) => {
325
- if(r.path === '/'
326
- || prev.find((p) => p.source === '/'+ r.path + '/index.html')
327
- ){
328
- return void 0;
329
- }
330
- prev.push({
331
- source: '/'+ r.path,
332
- destination: '/'+ r.path + '/index.html'
333
- })
334
-
335
- if(r.params.length > 0){
336
- r.params.forEach((param)=>{
337
- if(!param.paramData){
338
- return void 0;
339
- }
340
- let parampath= Object.keys(param.paramData).map((p)=>`:${p}`).join('/')
341
- prev.push({
342
- source: '/'+ r.path + '/' + parampath ,
343
- destination: '/'+ r.path + '/index.html'
344
- })
345
- })
346
- }
347
-
348
- fs.writeFileSync(provider.out, JSON.stringify({rewrites: prev}, null, 2))
349
-
350
-
351
- })
352
- provider.obj.rewrites = prev
353
- write(provider.out, JSON.stringify(provider.obj, null, 2))
354
- break;
355
- case 'cloudflare':
356
- console.warn('Cloudflare is not supported yet refer to their documentation for more information:https://developers.cloudflare.com/pages/configuration/redirects/')
357
- break;
600
+ }
601
+
602
+ let providerType = [
603
+ {
604
+ provider: "vercel",
605
+
606
+ file: "vercel.json",
607
+
608
+ out: process.cwd() + "/vercel.json",
609
+
610
+ obj: {
611
+ rewrites: [],
612
+ },
613
+ },
614
+ {
615
+ provider: "cloudflare",
616
+
617
+ file: "_redirects",
618
+
619
+ out: "dist/_redirects",
620
+ },
621
+ {
622
+ "provider":"regular_http_server",
623
+ "file":"htaaccess",
624
+ "out":"dist/.htaccess",
625
+ "obj":`
626
+ RewriteEngine On
627
+ RewriteCond %{REQUEST_FILENAME} !-f
628
+ RewriteRule ^ index.html [QSA,L]
629
+ `,
358
630
  }
631
+ ];
359
632
 
633
+ let provider = providerType.find((p) => p.provider === config.host.provider);
634
+
635
+ if (provider) {
636
+ let prev = null;
360
637
 
361
-
638
+ switch (provider.provider) {
639
+ case "vercel":
640
+ if (!fs.existsSync(provider.out)) {
641
+ fs.writeFileSync(
642
+ provider.out,
643
+ JSON.stringify({
644
+ rewrites: [],
645
+ })
646
+ );
647
+ }
362
648
 
363
- }
364
- return void 0;
365
- }
649
+ // make sure file isnt empty
650
+ if (fs.readFileSync(provider.out).toString().match(/\S/g) === null) {
651
+ console.warn("Rewrites file is empty, ignoring...");
652
+ fs.writeFileSync(
653
+ provider.out,
654
+ JSON.stringify({
655
+ rewrites: [],
656
+ })
657
+ );
658
+ }
659
+
660
+ prev = JSON.parse(fs.readFileSync(provider.out).toString()).rewrites;
661
+
662
+ for(var i in routes){
663
+ let r = routes[i];
664
+ let previous = prev.find((p) => p.source.includes(r.path));
665
+
666
+ if (previous) {
667
+ return void 0;
668
+ }
669
+
670
+ if(r.path.includes('[')){
671
+ r.path = r.path.split('[').shift() + '/:param';
672
+ }
673
+ // replace duplicate slashes
674
+ r.path = r.path.replace(/\/\//g, '/');
675
+ prev.push({
676
+ source: "/" + r.path,
677
+
678
+ destination: "/" + r.path + "/index.html",
679
+ });
680
+
681
+ if (r.params.length > 0) {
682
+ r.params.forEach((param) => {
683
+ if (!param.paramData) {
684
+ return void 0;
685
+ }
686
+
687
+ let parampath = Object.keys(param.paramData)
688
+ .map((p) => `:${p}`)
689
+ .join("/");
690
+
691
+ prev.push({
692
+ source: "/" + r.path + "/" + parampath,
693
+
694
+ destination: "/" + r.path + "/index.html",
695
+ });
696
+ });
697
+ }
698
+
699
+ fs.writeFileSync(
700
+ provider.out,
701
+ JSON.stringify(
702
+ {
703
+ rewrites: prev,
704
+ },
705
+ null,
706
+ 2
707
+ )
708
+ );
709
+ }
710
+
711
+ provider.obj.rewrites = prev;
712
+
713
+ write(provider.out, JSON.stringify(provider.obj, null, 2));
714
+
715
+ break;
716
+
717
+ case "cloudflare":
718
+ console.warn(
719
+ "Cloudflare is not supported yet refer to their documentation for more information:https://developers.cloudflare.com/pages/configuration/redirects/"
720
+ );
721
+
722
+
723
+ break;
724
+ }
725
+ }
726
+
727
+ return void 0;
728
+ }
366
729
 
367
730
  /**
731
+
368
732
  * @function transform
733
+
369
734
  * @description - Transforms the jsx files to js files based on file paths
735
+
370
736
  */
737
+
738
+ async function transForm() {
739
+ return new Promise(async (resolve, reject) => {
740
+ globalThis.isBuilding = true;
741
+
742
+ router.reload();
743
+
744
+ for await (var file of glob.scan(".")) {
745
+ file = file.replace(/\\/g, "/");
746
+
747
+ let isBasePath = file.split("pages/")?.[1]?.split("/").length === 1;
748
+
749
+ let folder =
750
+ file.split("pages/")?.[1]?.split("/").slice(0, -1).join("/") || null;
751
+
752
+ if (isBasePath) {
753
+ folder = "/";
754
+ }
755
+
756
+ if (file.endsWith(".md")) {
757
+ let data = await read(file);
758
+ if (
759
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
760
+ ) {
761
+ console.log(
762
+ `Using markdown parser ${
763
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
764
+ .name
765
+ } v${
766
+ integrationStates.find((int) => int?._df && int?._df === "i18mdf")
767
+ .version
768
+ }`
769
+ );
770
+ let parser = integrationStates.find(
771
+ (int) => int?._df && int?._df === "i18mdf"
772
+ );
773
+
774
+ parser.parse(data);
775
+ parser._class.stylesheets.forEach((sheet) => {
776
+ parser._class.output =
777
+ `<link rel="stylesheet" href="${sheet}">` + parser._class.output;
778
+ });
779
+ let output = `./dist/${
780
+ isBasePath ? "index.html" : folder + "/index.html"
781
+ }`;
782
+ write(output, parser._class.output);
783
+ }
784
+ continue;
785
+ }
786
+
787
+
788
+ let route = isBasePath ? router.match("/") : router.match("/" + folder);
371
789
 
372
- async function transForm(){
373
- globalThis.isBuilding = true
374
- router.reload()
375
- for await (var file of glob.scan('.')) {
376
- file = file.replace(/\\/g, '/');
377
- let isBasePath = file.split('pages/')?.[1]?.split('/').length === 1;
378
- let folder = file.split('pages/')?.[1]?.split('/').slice(0, -1).join('/') || null;
379
- let route = isBasePath ? router.match('/') : router.match('/' + folder)
380
- if(route){
381
- let {filePath, kind, name, params, pathname, query,} = route
382
- let data = await read(filePath);
383
- try{
384
- data = new Bun.Transpiler({loader: "tsx", target:"browser", }).transformSync(data);
385
- }catch(e){
386
- console.error(e)
387
- }
388
- let out = `./dist/pages/${isBasePath ? 'index.js' : folder + '/index.js'}`;
389
- isBasePath ? folder = '/': null;
390
- data = handleReplaceMents(data);
391
- globalThis.routes.push({path: folder, file: out, isParam: kind === 'dynamic' ? true : false, params, query, pathname})
392
- write(out, data);
393
- bundleSize += data.length
394
-
395
-
790
+ if (route) {
791
+ let { filePath, kind, name, params, pathname, query } = route;
792
+
793
+ let data = await read(filePath);
794
+
795
+ try {
796
+ data = new Bun.Transpiler({
797
+ loader: "tsx",
798
+ target: "browser",
799
+ }).transformSync(data);
800
+ } catch (e) {
801
+ console.error(e);
396
802
  }
397
-
398
- }
399
803
 
400
- for await (var file of srcGlob.scan('.')) {
401
- if(!fs.existsSync(process.cwd() +'/dist/src/')){
402
- fs.mkdirSync(process.cwd() +'/dist/src/')
804
+ let out = `./dist/${isBasePath ? "index.js" : folder + "/index.js"}`;
805
+
806
+ isBasePath ? (folder = "/") : null;
807
+
808
+ data = handleReplaceMents(data);
809
+
810
+
811
+ let isAparam = null;
812
+
813
+ if (folder === "") {
814
+ return;
815
+ }
816
+
817
+ switch (true) {
818
+ case kind === "dynamic":
819
+ isAparam = true;
820
+
821
+ break;
822
+
823
+ case kind === "catch-all":
824
+ isAparam = true;
825
+
826
+ break;
827
+
828
+ case kind === "optional-catch-all":
829
+ isAparam = true;
830
+
831
+ break;
403
832
  }
404
- file = file.replace(/\\/g, '/');
405
- switch(file.split('.').pop()){
406
- case 'ts':
407
- let transpiler = new Bun.Transpiler({loader: "ts", target:"browser", });
408
- let data = await read(file);
409
- try {
410
- data = transpiler.transformSync(data);
411
- } catch (error) {
412
- console.error(error)
413
- }
414
- file = file.replace('.ts', '.js')
415
- let path = process.cwd() +'/dist/src/' + file.split('src/').pop()
416
- write(path, data);
417
- bundleSize += data.length
418
-
419
- break;
420
-
421
- case 'tsx':
422
- let transpilerx = new Bun.Transpiler({loader: "tsx", target:"browser", });
423
- let datax = await read(file);
424
- try {
425
- datax = transpilerx.transformSync(datax);
426
- } catch (error) {
427
- console.error(error)
428
- }
429
- datax = handleReplaceMents(datax);
430
- file = file.replace('.tsx', '.js')
431
- let pathx = process.cwd() +'/dist/src/' + file.split('src/').pop()
432
- write(pathx, datax);
433
-
434
-
435
- break;
436
- case 'jsx':
437
- let transpilerjx = new Bun.Transpiler({loader: "jsx", target:"browser", });
438
- let datajx = await read(file);
439
- try {
440
- datajx = transpilerjx.transformSync(datajx);
441
- } catch (error) {
442
- console.error(error)
443
- }
444
- datajx = handleReplaceMents(datajx);
445
- file = file.replace('.jsx', '.js')
446
- let pathjx = process.cwd() +'/dist/src/' + file.split('src/').pop()
447
- write(pathjx, datajx);
448
- bundleSize += datajx.length
449
- break;
833
+
834
+ if(!routes.find(r => r.path === folder)){
835
+ routes.push({
836
+ path: folder,
837
+ file: out,
838
+ isParam: isAparam,
839
+ params: params,
840
+ kind,
841
+ isCatchAll: kind.includes("catch-all"),
842
+ query,
843
+ pathname,
844
+ });
450
845
  }
846
+
847
+ console.log(`Transforming ${file} -> ${out}`);
848
+
849
+ write(out, data);
850
+
851
+ //terser
852
+ Bun.spawn({
853
+ cwd: process.cwd(),
854
+
855
+ isVader: true,
856
+
857
+ cmd: ["npx", "terser", out, "--output", out],
858
+ });
859
+
860
+ bundleSize += data.length;
861
+ }
862
+ }
863
+
864
+ for await (var file of srcGlob.scan(".")) {
865
+ if (!fs.existsSync(process.cwd() + "/dist/src/")) {
866
+ fs.mkdirSync(process.cwd() + "/dist/src/");
867
+ }
868
+
869
+ file = file.replace(/\\/g, "/");
870
+
871
+ switch (file.split(".").pop()) {
872
+ case "ts":
873
+ let transpiler = new Bun.Transpiler({
874
+ loader: "ts",
875
+ target: "browser",
876
+ });
877
+
878
+ let data = await read(file);
879
+
880
+ try {
881
+ data = transpiler.transformSync(data);
882
+ } catch (error) {
883
+ console.error(error);
884
+ }
885
+
886
+ file = file.replace(".ts", ".js");
887
+
888
+ let path = process.cwd() + "/dist/src/" + file.split("src/").pop();
889
+
890
+ write(path, data);
891
+
892
+ bundleSize += data.length;
893
+
894
+ break;
895
+
896
+ case "tsx":
897
+ let transpilerx = new Bun.Transpiler({
898
+ loader: "tsx",
899
+ target: "browser",
900
+ });
901
+
902
+ let datax = await read(file);
903
+
904
+ try {
905
+ datax = transpilerx.transformSync(datax);
906
+ } catch (error) {
907
+ console.error(error);
908
+ }
909
+
910
+ datax = handleReplaceMents(datax);
911
+
912
+ file = file.replace(".tsx", ".js");
913
+
914
+ let pathx = process.cwd() + "/dist/src/" + file.split("src/").pop();
915
+
916
+ write(pathx, datax);
917
+
918
+ break;
919
+
920
+ case "jsx":
921
+ let transpilerjx = new Bun.Transpiler({
922
+ loader: "jsx",
923
+ target: "browser",
924
+ });
925
+
926
+ let datajx = await read(file);
927
+
928
+ let source = transpilerjx.scan(datajx);
929
+
930
+ try {
931
+ datajx = transpilerjx.transformSync(datajx);
932
+ } catch (error) {
933
+ console.error(error);
934
+ }
935
+
936
+ datajx = handleReplaceMents(datajx);
937
+
938
+ file = file.replace(".jsx", ".js");
939
+
940
+ let pathjx = process.cwd() + "/dist/src/" + file.split("src/").pop();
941
+
942
+ write(pathjx, datajx);
943
+
944
+ bundleSize += datajx.length;
945
+
946
+ break;
947
+ default:
948
+ break;
949
+ }
451
950
  }
951
+
952
+ for await (var file of publicGlob.scan(".")) {
953
+ // works
954
+
955
+ let data = null;
956
+ let isBuff = false;
957
+ file = file.replace(/\\/g, "/");
958
+ if (
959
+ file.endsWith(".png") ||
960
+ file.endsWith(".jpg") ||
961
+ file.endsWith(".jpeg") ||
962
+ file.endsWith(".gif") ||
963
+ file.endsWith(".webp") ||
964
+ file.endsWith(".ico") ||
965
+ file.endsWith(".mp4") ||
966
+ file.endsWith(".webm")
967
+ ) {
968
+ data = Buffer.from(fs.readFileSync(file)).toString("base64");
969
+ isBuff = true;
970
+ }
971
+ data = data || (await read(file));
972
+
973
+ let path = process.cwd() + "/dist/public/" + file.split("public/").pop();
974
+ if(!fs.existsSync(path.split(file.split("/").pop()).shift())){
975
+ fs.mkdirSync(path.split(file.split("/").pop()).shift(), { recursive: true });
976
+ }
452
977
 
978
+ fs.writeFileSync(path, data, isBuff ? "base64" : "utf8");
453
979
 
454
- for await (var file of publicGlob.scan('.')) {
455
- let data = await read(file);
456
- file = file.replace(/\\/g, '/');
457
- write(process.cwd() +'/dist/public/' + file.split('public/').pop(), data);
458
- bundleSize += fs.statSync(process.cwd() +'/dist/public/' + file.split('public/').pop()).size
980
+ bundleSize += data.length;
459
981
  }
460
- for await (var file of vaderGlob.scan('.')) {
461
- let data = await read(file);
462
- file = file.replace(/\\/g, '/');
463
- write(process.cwd() +'/dist/' + file.split('node_modules/vaderjs/runtime/').pop(), data);
464
- bundleSize += fs.statSync(process.cwd() +'/dist/' + file.split('node_modules/vaderjs/runtime/').pop()).size
982
+
983
+ for await (var file of vaderGlob.scan(".")) {
984
+ file = file.replace(/\\/g, "/");
985
+ if (
986
+ fs.existsSync(
987
+ process.cwd() +
988
+ "/dist/" +
989
+ file.split("node_modules/vaderjs/runtime/").pop()
990
+ )
991
+ ) {
992
+ continue;
993
+ }
994
+ let data = await read(file);
995
+
996
+ file = file.replace(/\\/g, "/");
997
+
998
+ write(
999
+ process.cwd() +
1000
+ "/dist/" +
1001
+ file.split("node_modules/vaderjs/runtime/").pop(),
1002
+ data
1003
+ );
1004
+
1005
+ bundleSize += fs.statSync(
1006
+ process.cwd() +
1007
+ "/dist/" +
1008
+ file.split("node_modules/vaderjs/runtime/").pop()
1009
+ ).size;
465
1010
  }
466
1011
 
467
1012
  // clean dist folder
468
- for await( var file of distPages.scan('.')){
469
- file = file.replace(/\\/g, '/');
470
- let path = process.cwd() +'/pages/' + file.split('dist/pages/').pop()
471
- path = path.replace('.js', config?.files?.mimeType || '.jsx')
472
-
473
- if(!fs.existsSync(path)){
474
- fs.unlinkSync(file)
475
- }
476
-
477
- }
478
1013
 
479
- for await( var file of distSrc.scan('.')){
480
- file = file.replace(/\\/g, '/');
481
- let path = process.cwd() +'/src/' + file.split('dist/src/').pop()
482
- // if the file is a js file see if theirs a matching ts file
483
- if(file.split('.').pop() === 'js'){
484
- let tsFile = path.replace('.js', '.ts')
485
- // if the ts file exists then the js file is valid else if not the js file exists then remove
486
- switch(true){
487
- case !fs.existsSync(tsFile):
488
- // check if a tsx or jsx file exists
489
- let tsxFile = path.replace('.js', '.tsx')
490
- let jsxFile = path.replace('.js', '.jsx')
491
- let tsfile = path.replace('.js', '.ts')
492
- switch(true){
493
- case fs.existsSync(tsxFile):
494
- break;
495
- case fs.existsSync(jsxFile):
496
- break;
497
- case fs.existsSync(tsfile):
498
- break
499
- default:
500
- fs.unlinkSync(file)
501
- break;
502
- }
503
- break;
504
- case fs.existsSync(tsFile):
505
-
506
- break;
507
- }
508
- }
509
- }
510
-
511
- for await( var file of distPublic.scan('.')){
512
- file = file.replace(/\\/g, '/');
513
- let path = process.cwd() +'/public/' + file.split('dist/public/').pop()
514
- if(!fs.existsSync(path)){
515
- fs.unlinkSync(file)
516
- }
517
- }
1014
+ for await (var file of distPages.scan(".")) {
1015
+ file = file.replace(/\\/g, "/");
518
1016
 
519
-
1017
+ let path = process.cwd() + "/pages/" + file.split("dist/pages/").pop();
520
1018
 
521
- /**
522
- * @function organizeRoutes
523
- * @description - Organizes routes that have param paths
524
- */
525
-
526
- const organizeRoutes = () => {
527
- // if path starts with the same path and is dynamic then they are the same route and push params to the same route
528
- let newRoutes = []
529
- routes.forEach((route) => {
530
- let exists = routes.find((r) => r.path.startsWith(route.path) && r.isParam === true)
531
- if(exists){
532
- let b4Params = route.params
533
- route.params = []
534
- route.params.push(b4Params)
535
- route.params.push( {
536
- jsFile: '/pages/' + exists.path + '/index.js',
537
- folder: '/pages/' + exists.path,
538
- paramData:exists.params
539
- }
540
- )
541
- route.query = exists.query
542
- newRoutes.push(route)
543
- }
544
- else if(!exists && !route.isParam){
545
- newRoutes.push(route)
546
-
547
- }
548
- //remove param route that matched
549
- routes = routes.filter((r) => exists ? r.path !== exists.path : true)
550
-
551
- })
552
- globalThis.routes = newRoutes
1019
+ path = path.replace(".js", config?.files?.mimeType || ".jsx");
1020
+
1021
+ if (!fs.existsSync(path)) {
1022
+ fs.unlinkSync(file);
1023
+ }
553
1024
  }
554
- organizeRoutes()
555
-
556
-
557
- if(globalThis.mode === 'dev' && !globalThis.oneAndDone || globalThis.mode === 'build'){
558
-
559
- /**
560
- * @description - create an html file for each route
1025
+
1026
+ /**
1027
+
1028
+ * @function organizeRoutes
1029
+
1030
+ * @description - Organizes routes that have param paths
1031
+
561
1032
  */
562
- routes.forEach((r)=>{
563
-
564
-
565
- globalThis.generatorWs.send(JSON.stringify({
566
- type:'generate',
567
- PWD: process.cwd(),
568
- output: process.cwd() + '/dist/pages/' + r.path + '/index.html',
569
- file: '/pages/' + r.path + '/index.js',
570
- folder:'/pages/' + r.path,
571
- params: JSON.stringify(r.params),
572
- }))
573
-
574
- })
575
- let i = setInterval(() => {
576
- if(hasGenerated.length === routes.length){
577
- globalThis.generatorWs.send(JSON.stringify({
578
- type:'done'
579
- }))
580
- globalThis.oneAndDone = true
581
- clearInterval(i)
582
- }
583
- }, 1000)
1033
+
1034
+
1035
+
1036
+ globalThis.isBuilding = false;
1037
+
1038
+ if (!fs.existsSync(process.cwd() + "/_dev/meta")) {
1039
+ fs.mkdirSync(process.cwd() + "/_dev/meta");
584
1040
  }
585
- generateProviderRoutes( )
586
- globalThis.isBuilding = false
587
- console.log(`Finished building ${Math.round(bundleSize / 1000)}kb`)
588
- bundleSize = 0
589
- return void 0;
590
1041
 
1042
+ // handle [{}]
1043
+
1044
+ generateProviderRoutes();
1045
+ write( process.cwd() + "/_dev/meta/routes.json", JSON.stringify(routes, null, 2));
1046
+
1047
+ console.log(`Finished building ${Math.round(bundleSize / 1000)}kb`);
1048
+
1049
+ bundleSize = 0;
1050
+
1051
+ resolve();
1052
+ });
591
1053
  }
592
- let port = 3000
1054
+
1055
+ let port = 3000;
1056
+ let hasRan = [];
1057
+
593
1058
  switch (true) {
594
- case process.argv.includes('dev') && !process.argv.includes('build') && !process.argv.includes('start'):
595
-
596
- port = process.env.PORT || process.argv.includes('-p') ? process.argv[process.argv.indexOf('-p') + 1] : 3000
597
- globalThis.oneAndDone = false
598
- console.log(`
599
- Vader.js v${fs.readFileSync(process.cwd() + '/node_modules/vaderjs/package.json', 'utf8').split('"version": "')[1].split('"')[0]}
1059
+ case process.argv.includes("dev") &&
1060
+ !process.argv.includes("build") &&
1061
+ !process.argv.includes("start"):
1062
+ port = process.argv.includes("-p")
1063
+ ? process.argv[process.argv.indexOf("-p") + 1]
1064
+ : config?.dev?.port || 3000;
1065
+
1066
+ globalThis.oneAndDone = false;
1067
+ let v = await checkIFUptodate();
1068
+
1069
+ console.log(`
1070
+
1071
+ ${
1072
+ v.current !== v.latest
1073
+ ? `Update available: ${v.latest} (current: ${v.current})`
1074
+ : `Vader.js v${v.current}`
1075
+ }
600
1076
  - Watching for changes in ./pages
601
1077
  - Watching for changes in ./src
602
1078
  - Watching for changes in ./public
603
- - Serving on port ${port}
604
- `)
605
- globalThis.mode = 'dev'
606
- Server(port)
607
- transForm()
1079
+ - Serving on port http://localhost:${port}
1080
+
1081
+ `);
1082
+
1083
+ globalThis.mode = "dev";
1084
+
1085
+ Server(port);
1086
+ for (var ints in integrationStates) {
1087
+ if (
1088
+ integrationStates &&
1089
+ integrationStates[ints]?.on &&
1090
+ integrationStates[ints].on.includes("dev") &&
1091
+ !hasRan.includes(integrationStates[ints].name)
1092
+ ) {
1093
+ console.log("Starting integration...");
1094
+
1095
+ let int = integrationStates[ints];
1096
+
1097
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
1098
+
1099
+ globalThis[`isRunning${name}`] = true;
1100
+ console.log(`Using integration: ${name} v${version}`);
608
1101
 
609
1102
  Bun.spawn({
610
- cwd: process.cwd() + '/node_modules/vaderjs/binaries/',
1103
+ cwd: process.cwd(),
1104
+
1105
+ isVader: true,
1106
+
1107
+ env: {
1108
+ PWD: process.cwd(),
1109
+
1110
+ isVader: true,
1111
+
1112
+ FOLDERS: "pages,src,public",
1113
+
1114
+ onExit: (code) => {
1115
+ globalThis.isBuilding = false;
1116
+
1117
+ globalThis[`isRunning${name}`] = false;
1118
+ },
1119
+ },
1120
+
1121
+ cmd: [useRuntime || "node", entryPoint],
1122
+ });
1123
+
1124
+ hasRan.push(integrationStates[ints].name);
1125
+ }
1126
+ }
1127
+
1128
+ transForm();
1129
+
1130
+ Bun.spawn({
1131
+ cwd: process.cwd() + "/node_modules/vaderjs/binaries/",
1132
+
1133
+ env: {
1134
+ PWD: process.cwd(),
1135
+
1136
+ IPC: IPC,
1137
+
1138
+ FOLDERS: "pages,src,public",
1139
+
1140
+ onExit: (code) => {
1141
+ globalThis.isBuilding = false;
1142
+
1143
+ globalThis.oneAndDone = true;
1144
+ },
1145
+ },
1146
+
1147
+ cmd: ["node", "watcher.js"],
1148
+ });
1149
+
1150
+ async function runOnChange() {
1151
+ for (var ints in integrationStates) {
1152
+ if (
1153
+ integrationStates &&
1154
+ integrationStates[ints].on &&
1155
+ integrationStates[ints]?.on.includes("dev:change")
1156
+ ) {
1157
+ let int = integrationStates[ints];
1158
+
1159
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
1160
+
1161
+ if (globalThis[`isRunning${name}`]) {
1162
+ setTimeout(() => {
1163
+ globalThis[`isRunning${name}`] = false;
1164
+ }, 1000);
1165
+ return void 0;
1166
+ }
1167
+
1168
+ globalThis[`isRunning${name}`] = true;
1169
+ console.log(`Using integration: ${name} v${version}`);
1170
+
1171
+ Bun.spawn({
1172
+ cwd: process.cwd(),
1173
+
1174
+ isVader: true,
1175
+
611
1176
  env: {
612
- PWD: process.cwd(),
613
- FOLDERS: 'pages,src,public',
614
- onExit: (code) => {
615
- globalThis.isBuilding = false
616
- globalThis.oneAndDone = true
617
- }
1177
+ PWD: process.cwd(),
1178
+
1179
+ isVader: true,
1180
+
1181
+ FOLDERS: "pages,src,public",
1182
+
1183
+ onExit: (code) => {
1184
+ globalThis.isBuilding = false;
1185
+
1186
+ globalThis[`isRunning${name}`] = false;
1187
+ },
618
1188
  },
619
- cmd: ['node', 'watcher.js'],
620
- })
621
-
622
- const ws = new WebSocket(`ws://localhost:${3434}`)
623
- ws.on('open', () => {
624
- console.log('Watching for changes...')
625
- })
626
- ws.on('message', (message) => {
627
- message = JSON.parse(message.toString())
628
- switch(true){
629
- case message.type === 'change' && !globalThis.isBuilding:
630
- console.log('Rebuilding...')
631
- globalThis.clients.forEach((client) => {
632
- client.send('reload')
633
- })
634
- transForm()
635
- break;
636
- case message.type === 'add' && !globalThis.isBuilding:
637
- console.log('Rebuilding...')
638
- globalThis.clients.forEach((client) => {
639
- client.send('reload')
640
- })
641
- transForm()
642
- break;
643
- }
644
-
645
- })
646
-
647
- break;
648
- case process.argv.includes('build') && !process.argv.includes('dev') && !process.argv.includes('start'):
649
- globalThis.devMode = false
650
- globalThis.isProduction = true
651
- globalThis.routeStates = []
652
- console.log(`
1189
+
1190
+ cmd: [useRuntime || "node", entryPoint],
1191
+ });
1192
+
1193
+ console.log(`Using integration: ${name} v${version}`);
1194
+ }
1195
+ }
1196
+ }
1197
+
1198
+ IPC.client({
1199
+ use: IPCServer.typeEnums.WATCHER,
1200
+
1201
+ port: 3434,
1202
+ }).Console.read(async (message) => {
1203
+ message = message.msg;
1204
+
1205
+ switch (true) {
1206
+ case message.data?.type === "change":
1207
+ console.log("File changed:", message.data.filename);
1208
+
1209
+ transForm();
1210
+
1211
+ clients.forEach((client) => {
1212
+ client.send("reload");
1213
+ });
1214
+
1215
+ // reload config
1216
+ config = await import(process.cwd() + "/vader.config.js").then((m) =>
1217
+ m ? m.default : {}
1218
+ );
1219
+
1220
+ runOnChange();
1221
+
1222
+ break;
1223
+
1224
+ case message.data?.type === "add":
1225
+ console.log("File added:", message.data.filename);
1226
+
1227
+ transForm();
1228
+
1229
+ break;
1230
+ }
1231
+ });
1232
+
1233
+ break;
1234
+
1235
+ case process.argv.includes("build") &&
1236
+ !process.argv.includes("dev") &&
1237
+ !process.argv.includes("start"):
1238
+ globalThis.devMode = false;
1239
+
1240
+ globalThis.mode = "prod";
1241
+
1242
+ globalThis.isProduction = true;
1243
+
1244
+ globalThis.routeStates = [];
1245
+
1246
+ console.log(`
653
1247
  Vader.js v1.3.3
654
1248
  Building to ./dist
655
- `)
656
-
657
- globalThis.mode = 'build'
658
- transForm()
659
- break;
660
- case process.argv.includes('start') && !process.argv.includes('dev') && !process.argv.includes('build'):
661
- port = process.env.PORT || process.argv.includes('-p') ? process.argv[process.argv.indexOf('-p') + 1] : 3000
662
- console.log(`
1249
+ `);
1250
+
1251
+ transForm();
1252
+
1253
+ for (var ints in integrationStates) {
1254
+ if (
1255
+ integrationStates &&
1256
+ integrationStates[ints].on &&
1257
+ integrationStates[ints]?.on.includes("build")
1258
+ ) {
1259
+ console.log("Starting integration...");
1260
+
1261
+ let int = integrationStates[ints];
1262
+
1263
+ let { name, version, useRuntime, entryPoint, onAction, doOn } = int;
1264
+
1265
+ console.log(`Using integration: ${name} v${version}`);
1266
+
1267
+ Bun.spawn({
1268
+ cwd: process.cwd(),
1269
+
1270
+ isVader: true,
1271
+
1272
+ env: {
1273
+ PWD: process.cwd(),
1274
+
1275
+ isVader: true,
1276
+
1277
+ FOLDERS: "pages,src,public",
1278
+
1279
+ onExit: (code) => {
1280
+ globalThis.isBuilding = false;
1281
+ },
1282
+ },
1283
+
1284
+ cmd: ["node", entryPoint],
1285
+ });
1286
+ }
1287
+ }
1288
+
1289
+ break;
1290
+
1291
+ case process.argv.includes("start") &&
1292
+ !process.argv.includes("dev") &&
1293
+ !process.argv.includes("build"):
1294
+ port = process.argv.includes("-p")
1295
+ ? process.argv[process.argv.indexOf("-p") + 1]
1296
+ : config?.host?.prod?.port || 3000;
1297
+
1298
+ console.log(`
1299
+
663
1300
  Vader.js v1.3.3
1301
+
664
1302
  Serving ./dist on port ${port}
665
- url: http://localhost:${port}
666
- `)
667
- globalThis.devMode = false
668
- globalThis.isProduction = true
669
-
670
- Server(port)
671
- break;
672
- default:
673
-
674
- break;
675
-
676
- }
1303
+
1304
+ url: ${config?.host?.prod?.hostname || "http://localhost"}:${port}
1305
+
1306
+ `);
1307
+
1308
+ globalThis.devMode = false;
1309
+
1310
+ globalThis.isProduction = true;
1311
+
1312
+ Server(port);
1313
+
1314
+ break;
1315
+
1316
+ default:
1317
+ break;
1318
+ }