vaderjs 1.7.6 → 1.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/bundler/index.js +114 -95
  2. package/index.ts +40 -11
  3. package/package.json +1 -1
package/bundler/index.js CHANGED
@@ -15,8 +15,8 @@ let path2 = require("path");
15
15
  globalThis.Fragment = Fragment;
16
16
  globalThis.window = {
17
17
  location: {
18
- hash: "",
19
- host: "",
18
+ hash: "",
19
+ host: "",
20
20
  },
21
21
  };
22
22
  globalThis.Component = Component;
@@ -35,138 +35,157 @@ globalThis.document = {
35
35
  };
36
36
  try {
37
37
  await Bun.build({
38
- entrypoints: [process.env.ENTRYPOINT],
39
- minify: false,
40
- root: process.cwd() + "/dist/",
41
- outdir: process.cwd() + "/dist/",
42
- format: "esm",
43
- ...(process.env.DEV ? { sourcemap: "inline" } : {}),
44
- packages: "bundle",
38
+ entrypoints: [process.env.ENTRYPOINT],
39
+ minify: false,
40
+ root: process.cwd() + "/dist/",
41
+ outdir: process.cwd() + "/dist/",
42
+ format: "esm",
43
+ ...(process.env.DEV ? { sourcemap: "inline" } : {}),
44
+ packages: "bundle",
45
+ external: ["vaderjs"]
45
46
  });
46
47
  } catch (error) {
47
- console.error(error)
48
+ console.error(error)
48
49
  }
49
50
 
50
51
 
51
- let builtCode = fs.readFileSync(path.join(process.cwd(), 'dist', process.env.filePath), 'utf-8')
52
+ let builtCode = fs.readFileSync(path.join(process.cwd(), 'dist', process.env.filePath), 'utf-8')
53
+
52
54
  const handleReplacements = (code) => {
53
55
  let lines = code.split('\n')
54
56
  let newLines = []
55
57
  for (let line of lines) {
56
- let hasImport = line.includes('import')
57
-
58
- if (hasImport && line.includes('.css')) {
59
- try {
60
- let isSmallColon = line.includes("'")
61
- let url = isSmallColon ? line.split("'")[1] : line.split('"')[1]
62
- // start from "/" not "/app"
63
- // remvoe all ./ and ../
64
- url = url.replaceAll('./', '/').replaceAll('../', '/')
65
-
66
- let p = path.join(process.cwd(), '/', url)
67
- line = '';
68
- url = url.replace(process.cwd() + '/app', '')
69
- url = url.replace(/\\/g, '/')
70
- if (!bindes.includes(`<link rel="stylesheet" href="${url}">`)) {
71
- bindes.push(`
58
+ let hasImport = line.includes('import')
59
+ if (hasImport && line.includes('vaderjs')) {
60
+ line = line.replace('vaderjs', '/src/vader/index.js')
61
+ }
62
+ if (hasImport && line.includes('.css')) {
63
+ try {
64
+ let isSmallColon = line.includes("'")
65
+ let url = isSmallColon ? line.split("'")[1] : line.split('"')[1]
66
+ // start from "/" not "/app"
67
+ // remvoe all ./ and ../
68
+ url = url.replaceAll('./', '/').replaceAll('../', '/')
69
+
70
+ let p = path.join(process.cwd(), '/', url)
71
+ line = '';
72
+ url = url.replace(process.cwd() + '/app', '')
73
+ url = url.replace(/\\/g, '/')
74
+ if (!bindes.includes(`<link rel="stylesheet" href="${url}">`)) {
75
+ bindes.push(`
72
76
  <style>
73
77
  ${fs.readFileSync(p, 'utf-8')}
74
78
  </style>
75
79
  `)
76
- }
77
- } catch (error) {
78
- console.error(error)
79
- }
80
- }
81
- if (line.toLowerCase().includes('genkey()')) {
82
- line = line.toLowerCase().replace('genkey()', `this.key = "${crypto.randomUUID()}"`)
83
- }
84
- if (!hasImport && line.includes('useFetch')) {
85
- line = line.replace('useFetch', 'this.useFetch')
86
- }
87
- if (!hasImport && line.includes('useState') && line.includes('[')) {
88
- let key = line.split(',')[0].split('[')[1].replace(' ', '')
89
- let b4 = line
90
- b4 = line.replace('useState(', `this.useState('${key}',`)
91
- line = b4
92
- }
93
- if (!hasImport && line.includes('useAsyncState')) {
94
- let key = line.split(',')[0].split('[')[1].replace(' ', '')
95
- let b4 = line
96
- b4 = line.replace('useAsyncState(', `this.useAsyncState('${key}',`)
97
- line = b4
98
- }
99
- if (!hasImport && line.includes('useEffect')) {
100
- let b4 = line
101
- b4 = line.replace('useEffect(', `this.useEffect(`)
102
- line = b4
103
- }
104
- if (!hasImport && line.includes('useRef')) {
105
- let b4 = line
106
- let key = line.split(' ')[1].split('=')[0]
107
- b4 = line.replace('useRef(', `this.useRef('${key}',`)
108
- line = b4
80
+ }
81
+ } catch (error) {
82
+ console.error(error)
109
83
  }
84
+ }
85
+ if (line.toLowerCase().includes('genkey()')) {
86
+ line = line.toLowerCase().replace('genkey()', `this.key = "${crypto.randomUUID()}"`)
87
+ }
88
+ if (!hasImport && line.includes('useFetch')) {
89
+ line = line.replace('useFetch', 'this.useFetch')
90
+ }
91
+ if (!hasImport && line.match(/\buseState\d*\(/) && line.includes('[') && !line.includes("this")) {
92
+
93
+
94
+ let key = line.split(',')[0].split('[')[1].replace(' ', '');
95
+
96
+ let updatedLine = line.replace(/\buseState\d*\(/, `this.useState('${key}',`);
97
+
98
+ line = updatedLine;
99
+ }
100
+
101
+ if (!hasImport && line.match(/\buseAsyncState\d*\(/) && line.includes('[') && !line.includes("this")) {
102
+
103
+
104
+ let key = line.split(',')[0].split('[')[1].replace(' ', '');
105
+
106
+ let updatedLine = line.replace(/\buseAsyncState\d*\(/, `this.useAsyncState('${key}',`);
107
+
108
+ line = updatedLine;
109
+ }
110
+
111
+ if (!hasImport && line.match(/\buseEffect\d*\(/) && !line.includes("this")) {
112
+
113
+
114
+ let updatedLine = line.replace(/\buseEffect\d*\(/, `this.useEffect(`);
115
+
116
+ line = updatedLine;
117
+ }
118
+
119
+ if (!hasImport && line.match(/\buseRef\d*\(/) && !line.includes("this")) {
120
+
121
+
122
+ let key = line.split(' ')[1].split('=')[0];
123
+
124
+ let updatedLine = line.replace(/\buseRef\d*\(/, `this.useRef('${key}',`);
125
+
126
+ line = updatedLine;
127
+ }
128
+
110
129
 
111
- newLines.push(line)
130
+ newLines.push(line)
112
131
  }
113
132
  let c = newLines.join('\n')
114
133
  return c
115
- }
134
+ }
116
135
  builtCode = handleReplacements(builtCode)
117
-
136
+
118
137
  fs.writeFileSync(path.join(process.cwd(), 'dist', process.env.filePath), builtCode)
119
138
 
120
- let isClass = function (element) {
139
+ let isClass = function (element) {
121
140
  return element && element.toString().startsWith("class");
122
141
  };
123
142
  const generatePage = async (
124
143
  data = { path: process.env.INPUT, route: process.env.OUT }
125
144
  ) => {
126
145
  const { path, route } = data;
127
- if (path.includes("root.js")) return;
146
+ if (path.includes("root.js")) return;
128
147
  let html = await import(path).then((m) => m.default);
129
-
148
+
130
149
  let { head } = await import(path).then((m) => m);
131
150
  let isFunction = false;
132
- globalThis.isServer = true;
133
- if(!html){
151
+ globalThis.isServer = true;
152
+ if (!html) {
134
153
  return
135
154
  }
136
- if (isClass(html) ) {
137
- html = new html();
138
- html.Mounted = true;
139
- html = html.render();
155
+ if (isClass(html)) {
156
+ html = new html();
157
+ html.Mounted = true;
158
+ html = html.render();
140
159
  } else {
141
- isFunction = true;
142
- let instance = new Component();
143
- html = html.bind(instance);
144
- instance.render = html;
145
- html = instance.render();
160
+ isFunction = true;
161
+ let instance = new Component();
162
+ html = html.bind(instance);
163
+ instance.render = html;
164
+ html = instance.render();
146
165
  }
147
166
 
148
167
  let h = document(html);
149
168
  if (!fs.existsSync(process.cwd() + "/dist" + path2.dirname(route))) {
150
- fs.mkdirSync(process.cwd() + "/dist" + path2.dirname(route), {
151
- recursive: true,
152
- });
169
+ fs.mkdirSync(process.cwd() + "/dist" + path2.dirname(route), {
170
+ recursive: true,
171
+ });
153
172
  }
154
173
  let headHtml = "";
155
174
  if (head) {
156
- headHtml = document(head());
175
+ headHtml = document(head());
157
176
  }
158
177
 
159
178
 
160
179
 
161
- if (h.includes("<head>")) {
162
- h = h.replace("<head>", `<head>${process.env.bindes}`)
163
- }else{
180
+ if (h.includes("<head>")) {
181
+ h = h.replace("<head>", `<head>${process.env.bindes}`)
182
+ } else {
164
183
  h += process.env.bindes
165
184
  }
166
185
 
167
186
  await Bun.write(
168
- process.cwd() + "/dist/" + route + "/index.html",
169
- `<!DOCTYPE html>
187
+ process.cwd() + "/dist/" + route + "/index.html",
188
+ `<!DOCTYPE html>
170
189
  ${h}
171
190
  <script type="module">
172
191
  import c from '${process.env.filePath}'
@@ -177,18 +196,18 @@ const generatePage = async (
177
196
  `
178
197
  );
179
198
  console.log(
180
- ansiColors.blue(
181
- `${process.env.filePath.replace(".js", ".jsx")} - ${parseInt(
182
- process.env.size
183
- ).toFixed(2)}kb`
184
- )
199
+ ansiColors.blue(
200
+ `${process.env.filePath.replace(".js", ".jsx")} - ${parseInt(
201
+ process.env.size
202
+ ).toFixed(2)}kb`
203
+ )
185
204
  );
186
205
  process.exit(0);
187
206
  };
188
- console.log(process.env.isJsx, process.env.isAppFile == "true" )
189
- try {
190
- if (process.env.isJsx == "true" && process.env.isAppFile == "true" ) {
191
- generatePage({ path: process.env.INPUT, route: process.env.OUT })
207
+
208
+ try {
209
+ if (process.env.isJsx == "true" && process.env.isAppFile == "true") {
210
+ generatePage({ path: process.env.INPUT, route: process.env.OUT })
192
211
  }
193
212
  } catch (error) {
194
213
  console.log(ansiColors.red(error))
package/index.ts CHANGED
@@ -322,33 +322,62 @@ export class Component {
322
322
  executeCallback();
323
323
  }
324
324
  }
325
- } useState(key, defaultValue, persist = false) {
325
+ }
326
+ useState(key, defaultValue, persist = false) {
326
327
  if (typeof window === "undefined")
327
- return [defaultValue, () => {
328
- }];
329
- let value = sessionStorage.getItem("state_" + key) ? JSON.parse(sessionStorage.getItem("state_" + key)).value : defaultValue;
328
+ return [defaultValue, () => {}];
329
+
330
+ // Retrieve initial value from sessionStorage or defaultValue
331
+ let value = sessionStorage.getItem("state_" + key)
332
+ ? JSON.parse(sessionStorage.getItem("state_" + key)).value
333
+ : defaultValue;
334
+
335
+ // Parse stringified values safely
330
336
  if (typeof value === "string") {
331
337
  try {
332
338
  value = JSON.parse(value);
333
- } catch (error) {
339
+ } catch {
340
+ // Value remains a string if parsing fails
334
341
  }
335
342
  }
336
- if (!window["listener" + key] && !isServer) {
337
- window["listener" + key] = true;
343
+
344
+ // Ensure event listener is added only once
345
+ if (!window[`listener_${key}`]) {
346
+ window[`listener_${key}`] = true;
338
347
  window.addEventListener("beforeunload", () => {
339
- !persist && sessionStorage.removeItem("state_" + key);
348
+ if (!persist) sessionStorage.removeItem("state_" + key);
340
349
  });
341
350
  }
351
+
342
352
  const setValue = (newValue) => {
343
353
  if (typeof newValue === "function") {
344
354
  newValue = newValue(value);
345
355
  }
346
- sessionStorage.setItem("state_" + key, JSON.stringify({ value: newValue }));
347
- this.forceUpdate(this.key);
356
+
357
+ const currentValue = sessionStorage.getItem("state_" + key)
358
+ ? JSON.parse(sessionStorage.getItem("state_" + key)).value
359
+ : defaultValue;
360
+
361
+ if (JSON.stringify(currentValue) === JSON.stringify(newValue)) {
362
+ return; // Skip if the value hasn't changed
363
+ }
364
+
365
+ sessionStorage.setItem(
366
+ "state_" + key,
367
+ JSON.stringify({ value: newValue })
368
+ );
369
+
370
+ if (this.forceUpdate) {
371
+ this.forceUpdate(this.key);
372
+ }
348
373
  };
374
+
349
375
  const getVal = () => {
350
- return sessionStorage.getItem("state_" + key) ? JSON.parse(sessionStorage.getItem("state_" + key)).value : defaultValue;
376
+ return sessionStorage.getItem("state_" + key)
377
+ ? JSON.parse(sessionStorage.getItem("state_" + key)).value
378
+ : defaultValue;
351
379
  };
380
+
352
381
  return [getVal, setValue];
353
382
  }
354
383
  useFetch(url, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vaderjs",
3
- "version": "1.7.6",
3
+ "version": "1.7.8",
4
4
  "description": "A simple and powerful JavaScript library for building modern web applications.",
5
5
  "bin": {
6
6
  "vaderjs": "./main.js"