vaderjs 1.4.1-ui7iuy47 → 1.4.2-jpbvml56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.editorconfig +11 -0
  2. package/.vscode/c_cpp_properties.json +21 -0
  3. package/.vscode/settings.json +12 -0
  4. package/README.md +44 -197
  5. package/binaries/Kalix/index.js +677 -0
  6. package/binaries/compiler/main.js +502 -0
  7. package/binaries/vader.js +74 -0
  8. package/binaries/watcher/hmr.js +41 -0
  9. package/client/index.d.ts +226 -0
  10. package/client/runtime/index.js +1 -0
  11. package/client/runtime/router.js +1 -0
  12. package/config/index.ts +87 -0
  13. package/index.ts +344 -0
  14. package/package.json +13 -25
  15. package/plugins/cloudflare/functions/index.js +102 -0
  16. package/plugins/cloudflare/toCopy/@server/Kalix/index.js +673 -0
  17. package/plugins/cloudflare/toCopy/@server/cloudflare_ssr/index.js +85 -0
  18. package/plugins/cloudflare/toCopy/node_modules/vaderjs/server/index.js +99 -0
  19. package/plugins/cloudflare/toCopy/src/client.js +1 -0
  20. package/plugins/cloudflare/toCopy/src/router.js +1 -0
  21. package/plugins/ssg/index.js +197 -0
  22. package/plugins/tailwind/index.ts +102 -0
  23. package/plugins/vercel/functions/index.ts +8 -0
  24. package/router/index.ts +208 -0
  25. package/server/index.js +143 -0
  26. package/vader_dev.js +177 -0
  27. package/@integrations/ssg.js +0 -189
  28. package/LICENSE +0 -21
  29. package/binaries/IPC/index.js +0 -277
  30. package/binaries/main.js +0 -1464
  31. package/binaries/readme.md +0 -4
  32. package/binaries/watcher.js +0 -74
  33. package/binaries/win32/check.ps1 +0 -7
  34. package/client/index.js +0 -426
  35. package/config/index.js +0 -36
  36. package/logo.png +0 -0
  37. package/runtime/router.js +0 -1
  38. package/runtime/vader.js +0 -1
  39. package/vader.js +0 -230
@@ -0,0 +1,208 @@
1
+
2
+ //@ts-nocheck
3
+ import fs from 'fs'
4
+ const router = new Bun.FileSystemRouter({
5
+ dir: process.cwd() + '/pages',
6
+ style:'nextjs'
7
+ })
8
+ let wsClients = []
9
+ function handleContentTypes(url: string){
10
+ let types: any = {
11
+ 'html': 'text/html',
12
+ 'css': 'text/css',
13
+ 'js': 'text/javascript',
14
+ 'json': 'application/json',
15
+ 'png': 'image/png',
16
+ 'jpg': 'image/jpg',
17
+ 'jpeg': 'image/jpeg',
18
+ 'svg': 'image/svg+xml',
19
+ 'gif': 'image/gif',
20
+ 'ico': 'image/x-icon',
21
+ 'tiff': 'image/tiff',
22
+ 'woff': 'font/woff',
23
+ 'woff2': 'font/woff2',
24
+ }
25
+
26
+ let typeArray = Array.from(Object.keys(types))
27
+
28
+ let ext = url.split('.').pop()
29
+ if(typeArray.includes(ext)){
30
+ return types[ext]
31
+ }
32
+
33
+ }
34
+
35
+
36
+ function spawn_ssr_server(config: any ){
37
+ if(!fs.existsSync(process.cwd() + '/routes')){
38
+ throw new Error('SSR requires a routes directory to be present in your project')
39
+ }
40
+ let routesRouter = new Bun.FileSystemRouter({
41
+ dir: process.cwd() + '/routes',
42
+ style: 'nextjs'
43
+ })
44
+ async function serve (req,res){
45
+ routesRouter.reload()
46
+ if(res.upgrade(req)){
47
+ return
48
+ }
49
+ let url = new URL(req.url)
50
+ if(url.pathname.includes('.')){
51
+ url.pathname = url.pathname.replace('/\/', '/').replace('/build/', '')
52
+ if(url.pathname.includes('/build')){
53
+ url.pathname = url.pathname.replace('/build', '')
54
+ }
55
+ let file = process.cwd() + '/build' + url.pathname
56
+ let fileType = handleContentTypes(file)
57
+ if(fs.existsSync(file)){
58
+ let content = await Bun.file(file).text()
59
+ let data = Buffer.from(content, 'utf-8');
60
+ const compressed = Bun.gzipSync(data);
61
+ return new Response(compressed, {status: 200, headers: {'Content-Type': fileType, 'x-powered-by': 'Vader',
62
+ 'Content-Encoding':'gzip',
63
+ ...config?.routes.find(route => route.pathname === "*" || route.pathname === url.pathname)?.headers}})
64
+ }
65
+ }
66
+ let routeMatch = routesRouter.match(url.pathname)
67
+ if(routeMatch){
68
+ let route = require(routeMatch.filePath).default
69
+
70
+ if(route?.name !== req?.method){
71
+ return new Response('Method Not Allowed', {status: 405})
72
+ }else{
73
+ try {
74
+ let Request = {
75
+ req,
76
+ res
77
+ }
78
+ let response = await route(Request)
79
+
80
+ if(response instanceof Response){
81
+ // set x-powered-by header
82
+ response.headers.set('x-powered-by', 'Vader')
83
+ response.headers.set('Content-Type', 'text/html')
84
+ return response
85
+ }
86
+ throw new Error(`Route ${routeMatch.filePath.split('/routes')[1]} did not return a response in file ${routeMatch.filePath}`)
87
+ } catch (error) {
88
+ console.log(error)
89
+ return new Response('Internal Server Error', {status: 500})
90
+ }
91
+ }
92
+
93
+
94
+ }
95
+ }
96
+ let server = Bun.serve({
97
+ port: config?.env?.PORT || 3000,
98
+ hostname: config?.host?.hostname || 'localhost',
99
+ reusePort: true,
100
+ lowMemoryMode: true,
101
+ development: false,
102
+ ...(config?.Router?.tls && {tls: {cert: config.Router.tls.cert, key: config.Router.tls.key}}),
103
+ websocket: {
104
+ message(event){
105
+
106
+ },
107
+
108
+ open(ws){
109
+ wsClients.push(ws)
110
+ },
111
+ },
112
+ async fetch(req,res){
113
+ return await serve(req,res)
114
+ },
115
+
116
+ error(error) {
117
+ console.log(error)
118
+ }
119
+ })
120
+
121
+ return {serve, server}
122
+ }
123
+
124
+ function spawnServer(config: any){
125
+ Bun.serve({
126
+ port: config.env.PORT || 3000,
127
+ hostname: config.host.hostname || 'localhost',
128
+ reusePort: true,
129
+ websocket: {
130
+ message(event){
131
+
132
+ },
133
+ open(ws){
134
+ wsClients.push(ws)
135
+ },
136
+ },
137
+ async fetch(req,res){
138
+ router.reload()
139
+ if(res.upgrade(req)){
140
+ return
141
+ }
142
+ let url = new URL(req.url)
143
+ if(url.pathname.includes('.')){
144
+ url.pathname = url.pathname.replace('/\/', '/')
145
+ url.pathname = url.pathname.replace('/build/', '')
146
+
147
+ let file = process.cwd() + '/build' + url.pathname
148
+ let fileType = handleContentTypes(file)
149
+ if(fs.existsSync(file)){
150
+ let content = await Bun.file(file).text()
151
+ let data = Buffer.from(content, 'utf-8');
152
+ const compressed = Bun.gzipSync(data);
153
+
154
+ return new Response(compressed, {status: 200, headers: {'Content-Type': fileType, 'x-powered-by': 'Vader', 'x-powered-by': 'Vader',
155
+ 'Content-Encoding':'gzip',
156
+ 'Accept-Encoding': 'gzip, deflate, br','Connection': 'keep-alive', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '0', ...config?.Router?.headers}})
157
+ }
158
+ }
159
+ let route = router.match(url.pathname)
160
+ if(route){
161
+ let isParamRoute = route.filePath.includes('[') && route.filePath.includes(']')
162
+ let path = route.filePath.split('/pages')[1].replace('.jsx', '.js').replace('.tsx', '.js').replace('.ts', '.js')
163
+ path = isParamRoute ? 'index.html' : path
164
+ let html = fs.readFileSync(process.cwd() + `/build/${path.replace('.js', '.html')}`).toString()
165
+ html = html + `
166
+ <script>
167
+ let ws = new WebSocket('ws://${config.host.hostname || 'localhost'}:${config.env.PORT || 3000}')
168
+ ws.onmessage = function(event){
169
+ console.log(event.data)
170
+ }
171
+ ws.onclose = function(event){
172
+ window.location.reload()
173
+ }
174
+ </script>
175
+ `
176
+ const data = Buffer.from(html, 'utf-8');
177
+ const compressed = Bun.gzipSync(data);
178
+ return new Response(compressed, {status: 200, headers: {'Content-Type': 'text/html', 'x-powered-by': 'Vader',
179
+ 'Content-Encoding':'gzip',
180
+ 'Accept-Encoding': 'gzip, deflate, br','Connection': 'keep-alive', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Expires': '0',
181
+ ...config?.Router?.headers}})
182
+ }
183
+ return new Response('Not Found', {status: 404})
184
+ }
185
+ })
186
+
187
+
188
+ }
189
+ /**
190
+ * @name Vader Router
191
+ * @description This plugin is responsible for routing and serving the application
192
+ */
193
+ export default {
194
+ name: 'Vader Router',
195
+ version: '1.0.0',
196
+ once: true,
197
+ init: ( ) => {
198
+ if(!globalThis.isListening){
199
+ let config = require(process.cwd() + '/vader.config.js').default
200
+ if(process.env.mode === 'production'){
201
+ console.log(`\x1b[32msuccess \x1b[0m- listening on port ${config.env.PORT || 3000}`)
202
+ spawnServer(config)
203
+ }
204
+ config?.env?.SSR ? spawn_ssr_server(config ) : spawnServer(config)
205
+ globalThis.isListening = true
206
+ }
207
+ }
208
+ }
@@ -0,0 +1,143 @@
1
+ import { Document, Element} from "vaderjs/binaries/Kalix"
2
+ class Component {
3
+ constructor(props){
4
+ this.props = props
5
+ this._key = Math.random().toString(36).substring(7)
6
+ this.state = {}
7
+ this.htmlNode = null
8
+ this.firstChild = null
9
+ this.Element = Element
10
+ }
11
+
12
+
13
+ setState(newState){
14
+ this.state = newState
15
+ }
16
+
17
+
18
+ useState(name, initialValue){
19
+ if(!this.state[name]){
20
+ this.state[name] = initialValue
21
+ }
22
+
23
+ let getState = () => this.state[name]
24
+ let setState = (newValue) => {
25
+
26
+
27
+ }
28
+ return [getState, setState]
29
+
30
+ }
31
+ useReducer(name, reducer, initialState){
32
+ let [state, setState] = this.useState(name, initialState)
33
+ let dispatch = (action) => {
34
+ let newState = reducer(state(), action)
35
+ setState(newState)
36
+ }
37
+
38
+ return [state, dispatch]
39
+ }
40
+
41
+ useEffect(effect, deps){
42
+
43
+ }
44
+
45
+ render(){
46
+ return null
47
+ }
48
+
49
+ }
50
+ export async function renderToString(element, args = []) {
51
+ globalThis.isServer = true
52
+ globalThis.preRender = true
53
+ let data = typeof element === 'function' ? await element(args) : element
54
+ if(data?.tagName === 'html'){
55
+ let body = data.querySelector('body') || new Document().createElement('body')
56
+ let innerHTML = body.innerHTML
57
+ innerHTML = `${innerHTML}`
58
+ body.tagName = 'div'
59
+ body.setAttribute('id', 'root')
60
+ body.innerHTML = innerHTML
61
+ data.removeChild(data.querySelector('body'))
62
+ data.appendChild(body)
63
+ }else if(data){
64
+ data.firstChild.setAttribute('id', 'root')
65
+ }
66
+ let doc = new Document()
67
+ let el = doc.createElement(data)
68
+
69
+ return el.toString()
70
+
71
+ }
72
+
73
+ /**
74
+ * @description This function is used to generate the server side rendered page
75
+ * @param {Element} element
76
+ * @param {Object} options
77
+ * @param {string} options.entry - The entry file for the component (refers to /build/pages/~)
78
+ * @param {Function} options.props - The server side props function
79
+ * @param {Array} args - The arguments to pass to the props function - ie Request or any other data
80
+ * @param {*} args
81
+ * @returns
82
+ */
83
+
84
+ export async function generatePage(element, options = {entry:"", props: any}, args = []) {
85
+ let config = await import(process.cwd() + '/vader.config.js').then((config) => { return config.default })
86
+ //@ts-ignore
87
+ globalThis.isServer = true
88
+ // @ts-ignore
89
+ let serverSideProps = await options.props({req: args[0], res: args[1]}, args.slice(2))
90
+ let name = element.name
91
+
92
+ let comp = new Component(serverSideProps?.props)
93
+ element = element.bind(comp)
94
+ comp.render = (props)=> {
95
+ return element(props)
96
+ }
97
+ let data = new Document().createElement(comp.render({props: serverSideProps.props, ...args}))
98
+ let document = new Document()
99
+ document.documentElement.setContent(data.querySelector('html') ? data.querySelector('html').innerHTML : '')
100
+ document.documentElement.setAttribute('lang', data.querySelector('html') ? data.querySelector('html').getAttribute('lang') : 'en')
101
+ document.head.setContent(data.querySelector('head') ? data.querySelector('head').innerHTML : '')
102
+ data.removeChild(data.querySelector('head'))
103
+ let div = new Document().createElement('div')
104
+ div.setAttribute('id', 'app')
105
+ div.setContent(data.innerHTML)
106
+ document.body.appendChild(div)
107
+ let script = new Document().createElement('script')
108
+ script.setAttribute('type', 'module')
109
+
110
+ script.setContent(script.innerHTML + '\n' + `
111
+
112
+ import ${name} from "${options?.entry}"
113
+ import {render} from '/src/client.js'
114
+ import Kuai from '/src/router.js'
115
+ let kuai = new Kuai({container: document.getElementById('app')})
116
+ kuai.get('/', (c) => {
117
+ c.html(render(${name}, document.getElementById('app'), {...c, props: ${JSON.stringify(serverSideProps.props)}}))
118
+ })
119
+ kuai.use('/', () => console.log('Middleware'))
120
+ kuai.listen()
121
+ ${
122
+ config?.mode === 'development' ? `
123
+ let ws = new WebSocket('ws://localhost:${env.PORT || 3000}')
124
+ ws.onopen = () => {
125
+ ws.send('Hello')
126
+ }
127
+ ws.onmessage = (e) => {
128
+ if(e.data === 'reload'){
129
+ window.location.reload()
130
+ }
131
+ }
132
+ ws.onclose = () => {
133
+ console.log('Connection closed')
134
+ window.location.reload()
135
+ }
136
+ ` :''
137
+ }
138
+ `)
139
+ document.body.appendChild(script)
140
+ return `<!DOCTYPE html><html lang="${document.documentElement.getAttribute('lang')}">${document.head.toString()}${document.body.innerHTML}</html>`
141
+ }
142
+
143
+ export default renderToString
package/vader_dev.js ADDED
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env node
2
+ import { exec } from "child_process";
3
+ import fs from "fs";
4
+ globalThis.currentCommand = null;
5
+ globalThis.isRunning = false;
6
+ let vaderisInstalled = process.cwd() + "/node_modules/vaderjs/binaries/vader.js";
7
+ if (!fs.existsSync(process.cwd() + "/_dev")) {
8
+ fs.mkdirSync(process.cwd() + "/_dev");
9
+ !fs.existsSync(process.cwd() + "/_dev/readme.md") && fs.writeFileSync(process.cwd() + "/_dev/readme.md", `This folder is used by vader.js to store important files, deletables include: Bun, Chrome - These should only be uninstalled if you need to reinstall them.`);
10
+ }
11
+
12
+ if (!fs.existsSync(process.cwd() + "/_dev/vader.js")) {
13
+ console.log("Copying vader to dev folder....");
14
+ fs.copyFileSync(vaderisInstalled, process.cwd() + "/_dev/vader.js");
15
+ }
16
+
17
+ function checkIFBundleIsInstalled() {
18
+ if (fs.existsSync(process.cwd() + "/_dev/bun")) {
19
+ return new Promise((resolve, reject) => {
20
+ resolve(true);
21
+ });
22
+ }
23
+ return new Promise((resolve, reject) => {
24
+ exec("bun -v", (err, stdout, stderr) => {
25
+ if (err) {
26
+ reject(err);
27
+ }
28
+ if (stdout) {
29
+ resolve(`Bun.js is installed: ${stdout}`);
30
+ }
31
+ if (stderr) {
32
+ reject(`Bun.js is not installed: ${stderr}`);
33
+ }
34
+ });
35
+ });
36
+ }
37
+
38
+ function run() {
39
+ if(!fs.existsSync(process.cwd() + "/pages")) {
40
+ fs.mkdirSync(process.cwd() + "/pages");
41
+ }
42
+ if(!fs.existsSync(process.cwd() + "/public")) {
43
+ fs.mkdirSync(process.cwd() + "/public");
44
+ }
45
+ if(!fs.existsSync(process.cwd() + "/src")) {
46
+ fs.mkdirSync(process.cwd() + "/src");
47
+ }
48
+ if (!fs.existsSync(process.cwd() + "/package.json")) {
49
+ fs.writeFileSync(process.cwd() + "/package.json", JSON.stringify({ name: "my_app", version: "1.0.0" }, null, 2));
50
+ return;
51
+ }
52
+ let packageJson = JSON.parse(fs.readFileSync(process.cwd() + "/package.json").toString());
53
+ if (!packageJson.scripts) {
54
+ packageJson.scripts = {};
55
+ }
56
+ packageJson.scripts["dev"] = "bun run ./_dev/vader.js dev";
57
+ packageJson.scripts["build"] = "bun run ./_dev/vader.js build";
58
+ packageJson.scripts["start"] = "bun run ./_dev/vader.js start";
59
+ if (!packageJson.dependencies) {
60
+ packageJson.dependencies = {};
61
+ }
62
+ fs.writeFileSync(process.cwd() + "/package.json", JSON.stringify(packageJson, null, 2));
63
+
64
+ if (currentCommand) {
65
+ let child = exec(currentCommand);
66
+ child.stdout.pipe(process.stdout);
67
+ child.stderr.pipe(process.stderr);
68
+ child.on("exit", (code) => {
69
+ process.exit(code);
70
+ });
71
+ child.on("message", (message) => {
72
+ console.log(message.toString());
73
+ });
74
+ child.on("error", (err) => {
75
+ console.error(err);
76
+ });
77
+
78
+ return;
79
+ }
80
+
81
+ console.log(`
82
+ Vader.js is a reactive framework for building interactive applications for the web built ontop of bun.js!
83
+
84
+ Usage: npx vaderjs <command>
85
+
86
+ Commands:
87
+
88
+ vaderjs run dev -p <number> Start the development server
89
+
90
+ vaderjs run build Build the project to ./dist
91
+
92
+ vaderjs run start -p <number> Production Mode (default 3000 or process.env.PORT)
93
+
94
+ Learn more about vader: https://vader-js.pages.dev/
95
+
96
+ `);
97
+ }
98
+
99
+ let Commands = {
100
+ dev: `bun run dev`,
101
+ build: `bun run build`,
102
+ start: `bun run start`,
103
+ };
104
+ let port = process.argv.includes("-p") || process.argv.includes("--port") ? process.argv[process.argv.indexOf("-p") + 1] || process.argv[process.argv.indexOf("--port") + 1] || process.env.PORT || 3000 : process.env.PORT || 3000;
105
+ switch (true) {
106
+ case process.argv.includes("dev") && !process.argv.includes("build") && !process.argv.includes("start"):
107
+ currentCommand = Commands.dev + (port ? ` -p ${port}` : "");
108
+ break;
109
+ case process.argv.includes("build") && !process.argv.includes("dev") && !process.argv.includes("start"):
110
+ currentCommand = Commands.build + (port ? ` -p ${port}` : "");
111
+ break;
112
+ case process.argv.includes("start") && !process.argv.includes("dev") && !process.argv.includes("build"):
113
+ currentCommand = Commands.start + (port ? ` -p ${port}` : "");
114
+ break;
115
+ default:
116
+ currentCommand = null;
117
+ break;
118
+ }
119
+ checkIFBundleIsInstalled()
120
+ .then((stdout) => {
121
+ if (stdout && !isRunning) {
122
+ if (!fs.existsSync(process.cwd() + "/_dev/bun")) {
123
+ fs.writeFileSync(process.cwd() + "/_dev/bun", `Installed: ${stdout}`);
124
+ }
125
+ run();
126
+ globalThis.isRunning = true;
127
+ }
128
+ })
129
+ .catch(async (err) => {
130
+ console.log("Bun.js is not installed. Installing....");
131
+ let installScipt = {
132
+ windows: 'powershell -c "irm bun.sh/install.ps1|iex',
133
+ others: "curl -fsSL https://bun.sh/install.sh | bash",
134
+ };
135
+ let scriptotRun = process.platform === "win32" ? installScipt.windows : installScipt.others;
136
+ exec(scriptotRun, async (err, stdout, stderr) => {
137
+ if (err) {
138
+ console.log("Error installing bun.js, may want to install manually");
139
+ process.exit(1);
140
+ }
141
+ if (stdout) {
142
+ if (!process.platform === "win32") {
143
+ await new Promise((resolve, reject) => {
144
+ console.log(`Adding bun.js to path...`);
145
+ exec("source ~/.bashrc", (err, stdout, stderr) => {
146
+ if (err) {
147
+ console.log("Error installing bun.js");
148
+ return;
149
+ }
150
+ if (stdout) {
151
+ run();
152
+ }
153
+ if (stderr) {
154
+ console.log("Error installing bun.js");
155
+ process.exit(1);
156
+ }
157
+ });
158
+ });
159
+ exec("chmod +x bun.sh/install.sh", (err, stdout, stderr) => {
160
+ if (err) {
161
+ console.log("Error installing bun.js");
162
+ return;
163
+ }
164
+ if (stdout) {
165
+ console.log("Bun.js installed successfully");
166
+ run();
167
+ }
168
+ if (stderr) {
169
+ console.log("Error installing bun.js");
170
+ process.exit(1);
171
+ }
172
+ });
173
+ }
174
+ run();
175
+ }
176
+ });
177
+ });