-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
1970 lines (1864 loc) · 84.3 KB
/
api.js
File metadata and controls
1970 lines (1864 loc) · 84.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// noinspection JSUnusedGlobalSymbols,ExceptionCaughtLocallyJS,JSPotentiallyInvalidConstructorUsage
const random = () => crypto.getRandomValues(new BigUint64Array([0n]))[0].toString(36);
const crypto = require("crypto");
const fs = require("fs");
const https = require("https");
const http = require("http");
const path = require("path");
const mime = require("mime");
const os = require("os");
const {exec} = require("child_process");
const {stdin} = process;
const {EventEmitter} = require("events");
const WS = require("ws");
const open = require("open");
const babel = require("@babel/core");
const babelParser = require("@babel/parser");
const babelGenerator = require("@babel/generator");
const traverse = require("@babel/traverse").default;
const printer = require("fancy-printer");
const esbuild = require("esbuild");
const minify = {
js: (...r) => require("uglify-js").minify(...r).code,
css: (...r) => require("csso").minify(...r).css,
html: (...r) => require("html-minifier-terser").minify(...r)
};
const xss = require("xss");
const url = require("url");
const exit = (...msg) => {
printer.dev.error(...msg);
process.exit(1);
};
process.on("exit", () => {
if (global.Hizzy) {
const addons = Hizzy.getAddons && Hizzy.getAddons();
for (const i in addons) addons[i].module.disable("termination");
}
});
process.on("SIGINT", () => {
process.exit(0);
});
process.on("uncaughtException", error => {
printer.dev.error(error);
process.exit(1);
});
const isTerminal = require.main.filename === path.join(__dirname, "hizzy.js") || require.main.filename === path.join(__dirname, "hizzy.min.js");
let hizzy = {};
const hizzyPath = path.join(__dirname, "hizzy.js");
const hizzyMinPath = path.join(__dirname, "hizzy.min.js");
if (isTerminal) hizzy = require(fs.existsSync(hizzyPath) ? hizzyPath : hizzyMinPath);
const {args: argv, config} = hizzy;
const staticJSON = JSON.stringify(config?.static);
// todo: a playground in the web page, update: idk if i will do this, this requires a sandbox server, i might use something like repl.it or glitch.com
// no-odo: variable transaction? bad idea, just use functions to move them around
// todo: test it on mac
// todo: add a package that installs example projects: npx @hizzyjs/example example-name-here
const runtimeId = random();
const pack = s => {
/*if(typeof s === "bigint") return `\x00\x00${s.toString()}`;
if(typeof s === "function") return `\x00\x01${s.toString()}`;*/
return JSON.stringify(s); // todo: sophisticated packing; date, bigint, function or objects/arrays including these
};
const EVERYONE = f => {
if (!f["__FUNCTION__"]) throw new Error("EVERYONE function only allows client-sided functions!");
const cl = [];
const toCl = TO_CLIENTS(f)(cl);
return async (...a) => {
cl.length = 0;
cl.push(...Hizzy.clientUUIDs());
return await toCl(...a);
}
};
const TO_CLIENTS = f => {
if (!f["__FUNCTION__"]) throw new Error("TO_CLIENTS function only allows client-sided functions!");
return clients => {
return async (...a) => {
const res = {};
for (const uuid of clients)
res[uuid] = (await makeClientFunction(f["__FUNCTION__FILE__"], f["__FUNCTION__"], typeof uuid === "string" ? uuid : uuid.uuid, f["__FROM__"]))(...a);
return res;
};
}
};
Object.defineProperty(Function.prototype, "everyone", {
get: function () {
return EVERYONE(this);
}
});
Object.defineProperty(Function.prototype, "toClients", {
get: function () {
return TO_CLIENTS(this);
}
});
const makeClientFunction = (file, name, uuid = null, fromFunction = null) => {
file = path.join(file);
const fJ = JSON.stringify(file);
const f = async (...a) => {
if (uuid === null) throw new Error("This client-sided function wasn't assigned to any clients! Although you can still use the function with the '.everyone' property of this function!");
const hash = Hizzy.getHash(uuid);
return await Hizzy.sendEvalTo(uuid, fromFunction ?
`args=${JSON.stringify(a)};__hizzy_run${hash}__2["${fromFunction}"]("${name}(...args)")` :
`args=${JSON.stringify(a)};__hizzy_run${hash}__[${fJ}].normal.${name}(...args)` // old fashion way
);
};
f.__FUNCTION__ = name;
f.__FUNCTION__FILE__ = file;
f.__FUNCTION__FILE_J__ = fJ;
f.__FROM__ = fromFunction;
// f.everyone = EVERYONE(f);
return f;
};
const makeBeginCode = (uuid, clientFunctions, fJ, fromFunction = null) => clientFunctions.map(i => `const ${i} = Hizzy.makeClientFunction(${fJ}, ${JSON.stringify(i)}, ${JSON.stringify(uuid)}, "${fromFunction}");`).join("");
const {CLIENT2SERVER, SERVER2CLIENT} = {
CLIENT2SERVER: {
HANDSHAKE_RESPONSE: "0", // agreed on shaking the hand
CLIENT_FUNCTION_RESPONSE: "1", // the response got from running a client-sided function
SERVER_FUNCTION_REQUEST: "2", // requested to run a function with the @server decorator
KEEPALIVE: "3", // keep alive packet
"0": "HANDSHAKE_RESPONSE",
"1": "SERVER_FUNCTION_REQUEST",
"2": "CLIENT_FUNCTION_RESPONSE",
"3": "KEEPALIVE"
},
SERVER2CLIENT: {
FILE_REFRESH: "0", // requests to refresh the page, so it can load the new contents
HANDSHAKE_REQUESTED: "1", // requests handshake
CLIENT_FUNCTION_REQUEST: "2", // requested to run a client-sided function
SERVER_FUNCTION_RESPONSE: "3", // the response got from running a function with the @server decorator
SURE_HANDSHAKE: "4", // server agreed on shaking the hand as well, what a friendship!
PAGE_PAYLOAD: "5",
"0": "FILE_REFRESH",
"1": "HANDSHAKE_REQUESTED",
"2": "CLIENT_FUNCTION_REQUEST",
"3": "SERVER_FUNCTION_RESPONSE",
"4": "SURE_HANDSHAKE",
"5": "PAGE_PAYLOAD"
}
};
const fx = (a, b) => {
a = a.toString();
const spl = a.split(".");
let d = spl[1] || "";
if (d.length > b) d = d.substring(0, b);
return spl[0] + (d ? "." + d : "");
};
const timeForm = ms => {
if (ms >= 24 * 60 * 60 * 1000) return fx(ms / 24 / 60 / 60 / 1000, 3) + "d";
if (ms >= 60 * 60 * 1000) return fx(ms / 60 / 60 / 1000, 3) + "h";
if (ms >= 60 * 1000) return fx(ms / 60 / 1000, 3) + "m";
if (ms >= 1000) return fx(ms / 1000, 3) + "s";
return ms + "ms";
};
const ck = "__" + __PRODUCT__ + "__";
const jsOpt = {
mangle: {toplevel: true},
module: true
};
const HIZZY_EXPERIMENTAL = process.argv.includes("--injections");
let experimentalId = Date.now().toString(36);
let jsxInjection, htmlInjection, preactCode, preactHooksCode;
const generateInjections = async () => {
try {
const t = Date.now();
jsxInjection = minify.js(fs.readFileSync(path.join(__dirname, "injections/jsx.js"), "utf8"), jsOpt);
fs.writeFileSync(path.join(__dirname, "injections/jsx.min.js"), jsxInjection);
htmlInjection = minify.js(fs.readFileSync(path.join(__dirname, "injections/html.js"), "utf8")
.replace("$CKL", ck.length + 1 + "")
.replaceAll("$CK", ck), jsOpt);
fs.writeFileSync(path.join(__dirname, "injections/html.min.js"), htmlInjection);
preactCode = (await (await fetch("https://esm.sh/stable/preact/es2022/preact.mjs")).text())
.replace("sourceMappingURL", "");
fs.writeFileSync(path.join(__dirname, "injections/preact.min.js"), preactCode); // todo: update 2022 to 2023(or 2024) when needed
preactHooksCode = (await (await fetch("https://esm.sh/stable/preact/es2022/hooks.js")).text())
.replace("sourceMappingURL", "")
.replace(/"\/stable\/preact@(\d.?)+\/es2022\/preact\.mjs"/, `"./__${__PRODUCT__}__preact__"`) +
`\nimport *as React from "./__${__PRODUCT__}__preact__"; export{React}`;
fs.writeFileSync(path.join(__dirname, "injections/hooks.min.js"), preactHooksCode);
fs.writeFileSync(path.join(__dirname, "injections/.last"), experimentalId);
const sT = Date.now() - t;
printer.dev.pass("Injections have been minified. (%c" + timeForm(sT) + "&t)", "color: orange");
} catch (e) {
printer.dev.fail("Couldn't compile the injections!");
printer.dev.error(e);
}
};
if (HIZZY_EXPERIMENTAL) generateInjections().then(r => r);
else {
jsxInjection = fs.readFileSync(path.join(__dirname, "injections/jsx.min.js"), "utf8");
htmlInjection = fs.readFileSync(path.join(__dirname, "injections/html.min.js"), "utf8");
preactCode = fs.readFileSync(path.join(__dirname, "injections/preact.min.js"), "utf8");
preactHooksCode = fs.readFileSync(path.join(__dirname, "injections/hooks.min.js"), "utf8");
experimentalId = fs.readFileSync(path.join(__dirname, "injections/.last"), "utf8");
}
const interfaces = os.networkInterfaces();
const addresses = [];
for (const interfaceName in interfaces) {
const iFace = interfaces[interfaceName];
for (const alias of iFace) if (alias.family === "IPv4" && !alias.internal) addresses.push(alias.address);
}
const ideaCmd = {win32: "idea64.exe", darwin: "idea"}[os.platform()] || "idea.sh";
const phpStormCmd = {win32: "phpstorm64.exe", darwin: "phpstorm"}[os.platform()] || "phpstorm.sh";
const webStormCmd = {win32: "webstorm.exe", darwin: "webstorm"}[os.platform()] || "webstorm.sh";
const codeAtCache = {};
const runCodeAt = async (code, at) => {
const k = at + "\x00" + code;
if (codeAtCache[k]) return codeAtCache[k];
at += random() + ".mjs";
fs.writeFileSync(at, code);
let res;
try {
res = {success: true, result: await import(url.pathToFileURL(at))};
} catch (e) {
res = {success: false, result: e};
}
fs.rmSync(at);
return codeAtCache[k] = res;
};
const runCodeAtSpecial = async (code, args, at) => await runCodeAt(`export default async (${args.join(",")}) => {${code}}`, at);
class Client {
static clients = {};
__socket;
class = Client;
attributes = {};
routes = {};
constructor(socket) {
if (Client.clients[socket._uuid]) return Client.clients[socket._uuid];
this.__socket = socket;
Client.clients[socket._uuid] = this;
};
get uuid() {
return this.__socket._uuid;
};
get ip() {
return this.__socket._req.ip;
};
get request() {
return this.__socket._req;
};
get actualRequest() {
return this.__socket._actualReq;
};
async eval(code) {
return await API.API.sendEvalTo(this.uuid, code);
};
remove(reason = "forced") {
this.__socket._close(reason);
};
run(file, name, ...args) {
return makeClientFunction(file, name, this.uuid)(...args);
};
}
class Addon {
static addons = {};
#name;
#options;
#module;
#init = false;
static async create(name, options) {
const p = new Addon(name, options);
await p.init();
return p;
};
constructor(a, options) {
const name = a instanceof AddonModule ? a.name : a;
if (Addon.addons[name]) return Addon.addons[name];
if (a instanceof AddonModule) {
this.#init = true;
this.#module = a;
printer.dev.pass("Loaded addon: %c" + this.#module.name + "@" + this.#module.version, "color: blue");
}
this.#name = name;
this.#options = options;
};
async init() {
const t = Date.now();
let {name} = this;
Addon.addons[name] = this;
if (this.#init) return;
this.#init = true;
try {
let pkgPath = path.join(Hizzy.directory, "node_modules", name, "package.json");
/*
if (HIZZY_EXPERIMENTAL && name.startsWith("@hizzyjs/")) {
name = path.join(__dirname, "addons", name.substring(6));
pkgPath = path.join(name, "package.json");
name = url.pathToFileURL(name).href;
}*/
if (!fs.existsSync(pkgPath) || !fs.statSync(pkgPath).isFile()) {
printer.dev.fail("No package.json found for the addon %c" + name + "&t. Try installing it by using%c npm install " + name + "&t", "color: orange", "color: orange");
throw "";
}
const cont = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
this.#module = new (await import(url.pathToFileURL(path.join(Hizzy.directory, "node_modules", name, cont.main)))).default(cont, this.#options);
} catch (e) {
printer.dev.fail("Failed to require addon: %c" + this.name + "&t, disabling it...", "color: orange");
printer.dev.error(e);
delete Addon.addons[name];
return;
}
if (typeof this.#module.onLoad === "function") this.#module.onLoad();
const dt = Date.now() - t;
printer.dev.pass("Loaded addon: %c" + this.#module.name + "@" + this.#module.version + " &t(%c" + timeForm(dt) + "&t)", "color: blue", "color: orange");
};
get options() {
return this.#options;
};
get name() {
return this.#name;
};
get module() {
return this.#module;
};
}
class AddonModule {
#pkg;
#options;
constructor(pkg, options) {
this.#pkg = pkg;
this.#options = options;
};
get name() {
return this.#pkg.name;
};
get description() {
return this.#pkg.description;
};
get version() {
return this.#pkg.version;
};
get options() {
return this.#options;
};
onLoad() {
};
onEnable() {
};
onDisable(reason) {
};
onClientSideLoad = "";
onClientSideRendered = "";
onClientSideError = "";
disable(reason) {
printer.dev[reason ? "fail" : "debug"]("Disabling addon %c" + this.name + "&t" + (reason ? " for " + reason : "") + "...", "color: orange");
this.onDisable();
};
log(...s) {
printer.dev.log("[" + this.constructor.name + "] ", ...s);
};
}
class API extends EventEmitter {
/*** @type {API | null} */
static API = null;
Addon = Addon;
Client = Client;
AddonModule = AddonModule;
#listening = false;
#realtime = false;
#isBuilding = false;
#isScanningBuild = false;
#dir;
#buildCache = null;
#buildPromise = new Promise(r => r());
#builtAt = null;
#buildRuntimeId = null;
#scanPromise = new Promise(r => r());
#webUUIDs = {};
#clients = {};
#jsxCache = {};
#jsxFunctions = {};
#port = -1;
#https = config.https;
#serverAddress;
#evalId = 0;
#evalResponses = {};
#isInputOn = false;
#hashes = {};
#initFunctions = [];
#importMap = {};
#watchingFiles = {};
#isInit = false;
#uuidTimeout = {};
#builtJSXCache = {};
#builtJSXPage = {};
#clientPages = {};
#firstBuild = true;
#firstScan = true;
#addonCache = null;
#globalStates = new Map;
#startPacket = {};
#mainDoneCb = {};
server;
socketServer;
autoRefresh = false;
dev = false;
customShortcuts = {};
preRequests = [];
preRawSend = [];
buildHandlers = {};
scanHandlers = {};
functionDecorators = {};
preFileHandlers = {};
filePacketHandlers = {};
constructor(dir) {
if (API.API) return API.API;
super();
API.API = this;
this.#dir = dir;
const app = this.app = require("express")();
app.disable("x-powered-by");
this.server = (this.#https ? https : http).createServer(app);
};
async init() {
if (this.#isInit) return;
this.#isInit = true;
this.app.use(async (req, res, next) => {
// if (!req.headers.referer) return res.send("Made with Hizzy!");
res.setHeader("X-Powered-By", "Hizzy");
const uuid = this.getCookie(req.headers.cookie, ck);
const socket = this.#clients[uuid];
printer.dev.debug("request: " + req.url + ", method: " + req.method + ", ip: " + (req.ip.startsWith("::ffff:") ? req.ip.substring(7) : req.ip));
if (!this.dev && (this.#isBuilding || this.#isScanningBuild)) return res.send("Building, please be patient.<script>setTimeout(()=>location.reload(),1000)</script>");
let l = req.url.split("?")[0].split("#")[0];
if (l[0] !== "/") return;
l = l.substring(1);
req.__socket = socket;
req._uuid = uuid;
if (socket) socket._req = req;
if (socket && l === runtimeId + `/__${__PRODUCT__}__addons__`) {
const cache = config.cache["addons"] * 1;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
await this.sendRawFile(".json", this.#addonCache, req, res);
return;
}
if (socket && l.includes("/") && l.split("/")[0] === `__${__PRODUCT__}__npm__`) {
const cache = config.cache["npm"] * 1;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
const name = l.split("/")[2];
if (!name) return;
if (!this.#importMap[name]) return this.sendRawFile(".js", `throw "Module not found: ${JSON.stringify(name)}"`, req, res);
await this.sendRawFile(".js", this.#importMap[name].code, req, res);
return;
}
if (socket && l === experimentalId + "/__" + __PRODUCT__ + "__preact__") {
const cache = config.cache["preact"] || 0;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
await this.sendRawFile(".js", preactCode, req, res);
return;
}
if (socket && l === experimentalId + "/__" + __PRODUCT__ + "__preact__hooks__") {
// noinspection PointlessArithmeticExpressionJS
const cache = config.cache["preact-hooks"] || 0;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
await this.sendRawFile(".js", preactHooksCode, req, res);
return;
}
if (this.#webUUIDs[uuid] && !socket && l === experimentalId + "/__" + __PRODUCT__ + "__injection__html__") {
const cache = config.cache["html-injection"] || 0;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
await this.sendRawFile(".js", `(async()=>{${htmlInjection}})()`, req, res);
return;
}
if (this.#webUUIDs[uuid] && !socket && l === experimentalId + "/__" + __PRODUCT__ + "__injection__jsx__") {
const cache = config.cache["jsx-injection"] || 0;
if (cache && cache > 0) res.setHeader("Cache-Control", "max-age=" + cache);
await this.sendRawFile(".js", `(async()=>{${jsxInjection}})()`, req, res);
return;
}
const r = i => {
if (i === this.preRequests.length) return next();
this.preRequests[i](req, res, () => r(i + 1));
};
await r(0);
});
if (this.dev && !fs.existsSync(path.join(this.#dir, config.srcFolder))) {
printer.dev.warn("No %c/" + config.srcFolder + "&t found. Forcing to disable the developer mode.", "color: orange");
this.dev = false;
}
this.buildHandlers.jsx = this.buildHandlers.tsx = [async (file, get, set, zip, ext, pt) => {
const norm = await this.readClientJSX([...pt, file].join("/"), get.toString());
set(norm.code);
delete norm.code;
zip.file("jsx/" + pt.map(i => i + "/").join("") + file.substring(0, file.length - 4) + ".json", JSON.stringify(norm));
}];
const pureHandler = async (file, get, set, zip, ext) => {
set(get.length ? await minify[ext](get.toString()) : "");
};
this.buildHandlers.html = [pureHandler];
this.buildHandlers.js = [pureHandler];
this.buildHandlers.css = [pureHandler];
const sourceJSXHandler = async (file, data, files) => {
data = data.toString();
const jsxJson = "jsx/" + file.substring(0, file.length - 4) + ".json";
let jsonData;
try {
if (!files[jsxJson]) throw new Error("File not found: " + jsxJson);
jsonData = JSON.parse(await files[jsxJson].async("string"));
await this.#pseudoBuildJSX(file, data, jsonData, this.#initFunctions);
} catch (e) {
printer.dev.warn("Couldn't scan JSX: '" + file + "', meta file is missing or corrupted. Try rebuilding.");
printer.dev.error(e);
}
};
this.scanHandlers.source = {
jsx: [sourceJSXHandler],
tsx: [sourceJSXHandler],
__default__: [(file, data) => this.#buildCache[file] = data]
};
const srvRpl = ({name, pth, json, getIdentifiers, tempName}) => {
const identifiers = config.serverClientVariables ? getIdentifiers(pth) : null;
json.functionIdentifiers[tempName] = identifiers;
json.after.push(() => {
pth.insertAfter(babelParser.parse(`function ${name}(...args){return FN${runtimeId}("${tempName}",args` +
(identifiers && identifiers.length ? `,${JSON.stringify(identifiers)}.map(i=>eval(\`try{\${i}}catch(e){undefined}\`))` : "")
+ `);}SRH${runtimeId}("${tempName}",r=>eval(r));`));
pth.remove();
});
}
this.functionDecorators["@server"] = ({name, pth, json, code, getIdentifiers}) => {
const tempName = random();
srvRpl({name, pth, json, code, getIdentifiers, tempName});
json.serverFunctions[tempName] = {name, r: false, code};
// json.serverFunctionDepths[tempName] = getDepth(pth);
};
this.functionDecorators["@server/respond"] = ({name, pth, json, code, getIdentifiers}) => {
const tempName = random();
srvRpl({name, pth, json, code, getIdentifiers, tempName});
json.serverFunctions[tempName] = {name, r: true, code};
// json.serverFunctionDepths[tempName] = getDepth(pth);
};
this.functionDecorators["@server/start"] = ({name, pth, json, code}) => {
pth.remove();
json.serverInit.push({name, code});
};
this.functionDecorators["@server/join"] = ({name, pth, json, code}) => {
pth.remove();
json.joinEvent.push({name, code});
};
this.functionDecorators["@server/leave"] = ({name, pth, json, code}) => {
pth.remove();
json.leaveEvent.push({name, code});
};
this.functionDecorators["@client"] = ({name, pth, json}) => {
pth.insertAfter(babelParser.parse(`CFN${runtimeId}.normal.${name}=${name};`).program.body[0]);
json.clientFunctionList.push(name);
};
this.functionDecorators["@client/render"] = ({name, pth}) => {
pth.insertAfter(babelParser.parse(`CFN${runtimeId}.load.${name}=${name};`).program.body[0]);
};
this.functionDecorators["@client/navigate"] = ({name, pth}) => {
pth.insertAfter(babelParser.parse(`CFN${runtimeId}.navigate.${name}=${name};`).program.body[0]);
};
this.preFileHandlers.css = (file, content, f, c) => {
f(".js");
c(`let st=document.createElement("style");st.innerHTML=${JSON.stringify(content.toString())};document.head.appendChild(st);export default st`);
};
this.preFileHandlers.html = (file, content, f, c) => {
f(".js");
c(`export default new DOMParser().parseFromString(${JSON.stringify(content.toString())},"text/html")`);
};
};
findOptimalFile(file) {
return fs.existsSync(file) && fs.statSync(file).isFile() ? file : null;
};
cacheDevFile(file) {
return fs.readFileSync(file);
};
async cacheBuildFile(file) {
if (!this.#buildCache) {
await this.#scanPromise;
await this.scanBuild();
}
return this.#buildCache[file];
};
async notFound(req, res) {
if (!res.headersSent) res.send(`<pre>Not found: ${xss.filterXSS(req.url)}</pre>`);
};
prepLoad(req, res) {
req._uuid = res._uuid = crypto.randomUUID();
this.#webUUIDs[req._uuid] = req._Route;
res.cookie(ck, res._uuid);
if (config.connectionTimeout > 0 && this.#realtime) this.#uuidTimeout[req._uuid] = setTimeout(() => {
delete this.#webUUIDs[req._uuid];
}, config.connectionTimeout);
};
random() {
return random();
};
enableRealtime() {
if (this.#realtime) return;
this.#realtime = true;
const server_ = this.socketServer = new WS.WebSocketServer({server: this.server});
server_.on("connection", (socket, req) => {
const uuid = this.getCookie(req.headers.cookie, ck);
socket._uuid = uuid;
let beginCode = {}; // note: begin code is server-sided
socket._handshook = false;
socket._closed = false;
socket._req = req;
socket._actualReq = req;
const o = this.#clientPages[uuid] || [];
socket._clientPages = o[0];
socket._mainFile = o[1];
socket._URL_ = this.#webUUIDs[uuid];
const isJSX = !!o[0];
delete this.#clientPages[uuid];
const client = new Client(socket);
socket._send = s => {
if (argv["debug-socket"]) printer.dev.debug("> " + s);
if (!socket._closed) socket.send(s);
};
clearTimeout(this.#uuidTimeout[uuid]);
const close = socket._close = (reason, t = true) => {
clearTimeout(timeout);
clearTimeout(keepalive);
if (socket._closed) return;
if (socket._handshook && isJSX) if (socket._mainFile) {
const jsx = socket._clientPages[socket._mainFile].json;
const leaveEvents = jsx.leaveEvent;
(async () => { // it could break some functionality of _close() function, so I moved async to here
const f = await runCodeAtSpecial(
`${jsx.serverImportCode};${beginCode[socket._mainFile]()};${leaveEvents.map(i => `try{(${i.code})()}catch(e){printer.dev.error(e)}`).join("")}`,
["currentUUID", "currentClient"],
path.join(this.#dir, config.srcFolder, socket._mainFile)
);
if (!f.success) return printer.dev.error(f.result);
try {
await f.result.default(uuid, client);
} catch (e) {
printer.dev.error(e);
}
})();
}
if (t) {
socket.close();
printer.dev.debug("socket remove: " + (socket._uuid || "-1") + ", " + reason);
}
socket._closed = true;
delete this.#clients[uuid];
if (Client.clients[uuid]) delete Client.clients[uuid];
};
let keepalive;
let keepaliveStart;
const ka = () => {
if (config.keepaliveTimeout < 0 || !(socket._URL_.endsWith(".jsx") || socket._URL_.endsWith(".tsx"))) return;
if (!keepaliveStart || keepaliveStart + config.minClientKeepalive < Date.now()) {
clearTimeout(keepalive);
keepaliveStart = Date.now();
keepalive = setTimeout(() => close("couldn't stay alive"), config.keepaliveTimeout);
}
};
const timeout = config.connectionTimeout > 0 ? setTimeout(_ => close("timeout"), config.connectionTimeout) : null;
if (!uuid || this.#clients[uuid] || !(uuid in this.#webUUIDs)) return close("invalid key");
this.#clients[uuid] = socket;
delete this.#webUUIDs[uuid];
printer.dev.debug("socket add: " + uuid);
socket._send(SERVER2CLIENT.HANDSHAKE_REQUESTED);
const prepareCodes = () => socket._clientPages && Object.keys(socket._clientPages).forEach(f => {
if (!f || !(f.endsWith(".jsx") || f.endsWith(".tsx"))) return;
const jsx = socket._clientPages[f].json;
const clientFunctions = jsx.clientFunctionList;
const fJ = JSON.stringify(f);
beginCode[f] = funcId => makeBeginCode(uuid, clientFunctions, fJ, funcId);
});
prepareCodes();
const onPageLoad = async () => {
if (!socket._mainFile) return;
const jsx = socket._clientPages[socket._mainFile].json;
const joinEvents = jsx.joinEvent;
const f = await runCodeAtSpecial(
`${jsx.serverImportCode};${beginCode[socket._mainFile]()};${joinEvents.map(i => `try{(${i.code})()}catch(e){printer.dev.error(e)}`).join("")}`,
["currentUUID", "currentClient"],
path.join(this.#dir, config.srcFolder, socket._mainFile)
);
if (!f.success) {
close("internal server error");
return printer.dev.error(f.result);
}
try {
await f.result.default(uuid, client);
} catch (e) {
close("internal server error");
return printer.dev.error(e);
}
};
const sendPagePayload = pk => {
if (socket._closed) return;
socket.send(SERVER2CLIENT.PAGE_PAYLOAD + "" + pk);
};
socket._externalLoad = (url, cPages, pk, isCached) => {
if (!cPages) return;
socket._clientPages = cPages[0];
socket._mainFile = cPages[1];
socket._URL_ = url;
prepareCodes();
onPageLoad().then(r => r);
if (!isCached) sendPagePayload(pk);
};
ka();
socket.on("message", async data => {
if (socket._closed) return close("bypass attempt");
clearTimeout(timeout);
try {
data = data.toString();
if (socket._closed) return;
if (argv["debug-socket"]) printer.dev.debug("< " + data);
if (data[0] === CLIENT2SERVER.HANDSHAKE_RESPONSE) { // handshake finished
if (socket._handshook) return close("one handshake is enough");
socket._handshook = true;
socket._send(SERVER2CLIENT.SURE_HANDSHAKE);
const pk = this.#startPacket[socket._uuid];
delete this.#startPacket[socket._uuid];
onPageLoad();
if (pk) sendPagePayload(pk);
return;
}
if (!socket._handshook) return close("haven't handshook"); // todo: try to use jsx packets in html process and see if it can be exploited
if (!(socket._URL_.endsWith(".jsx") || socket._URL_.endsWith(".tsx"))) return;
if (data[0] === CLIENT2SERVER.SERVER_FUNCTION_REQUEST) { // @server function run request
if (!isJSX) return close("unauthorized");
const spl = data.substring(1).split(":")
const evalId = spl[0];
const page = spl[1];
const fnName = spl[2];
if (typeof beginCode[page] !== "function" || typeof socket._clientPages[page] !== "object") return close("invalid jsx");
const jsx = socket._clientPages[page].json;
const fn = jsx.serverFunctions[fnName];
if (!fn) return close("invalid function");
const hash = this.#hashes[uuid];
if (!hash) return;
let args;
try {
args = JSON.parse(spl.slice(3).join(":"));
} catch (e) {
return close("invalid json");
}
if (
typeof args !== "object" || !Array.isArray(args) ||
typeof args[0] !== "object" || !Array.isArray(args[0]) ||
typeof args[1] !== "object" || !Array.isArray(args[1]) ||
args.length !== 2
) return close("invalid function args");
let res;
let err;
let identifierPk = {};
const fnIds = jsx.functionIdentifiers[fnName];
if (config.serverClientVariables && fnIds && fnIds.length) {
if (fnIds.length !== args[1].length) return close("an attempt of an exploit");
fnIds
.map((i, j) => [i, args[1][j]])
.filter(i => !global[i[0]])
.forEach(i => {
if (!i[1]) return;
identifierPk[i[0]] = i[1];
});
}
const k = Object.keys(identifierPk);
const definer = `${k.map(i => `if((typeof ${i})[0]=="u"){var ${i}=I${runtimeId}.${i}}`).join("")}`;
try {
const f = await runCodeAtSpecial(
`${jsx.serverImportCode};${beginCode[page](fnName)};${definer}return await (${fn.code})(...ARGS${runtimeId})`,
["currentUUID", "currentClient", "I" + runtimeId, "...ARGS" + runtimeId],
path.join(this.#dir, config.srcFolder, socket._mainFile)
);
if (f.success) res = await f.result.default(uuid, client, identifierPk, ...args[0]);
else err = f.result;
} catch (e) {
err = e;
}
if (err) {
printer.dev.error(err);
return close("internal server error");
}
if (fn.r) {
let r;
try {
r = JSON.stringify(res);
} catch (e) {
r = "undefined";
printer.dev.fail("Couldn't stringify the response from the '@server/respond -> " + fn.name + "' function at '/" + socket._URL_ + "'.");
printer.dev.error(e);
}
socket._send(SERVER2CLIENT.SERVER_FUNCTION_RESPONSE + evalId + ":" + r);
}// else socket._send(SERVER2CLIENT.SERVER_FUNCTION_RESPONSE + evalId);
} else if (data[0] === CLIENT2SERVER.CLIENT_FUNCTION_RESPONSE) { // client-sided function response
if (!isJSX) return close("unauthorized");
const hasError = data[1] === "1";
const spl = data.substring(2).split(":");
const id = spl[0];
if (!id || !this.#evalResponses[id]) return close("invalid eval");
const raw = spl.slice(1).join(":");
let res;
const got = {
"true": true,
"false": false,
"null": null,
"undefined": undefined
};
try {
if (raw in got) res = got[raw];
else res = hasError ? new Error(raw) : JSON.parse(raw);
} catch (e) {
return close("invalid json");
}
this.#evalResponses[id](res);
delete this.#evalResponses[id];
} else if (data[0] === CLIENT2SERVER.KEEPALIVE) ka();
} catch (e) {
printer.dev.error(e);
close("internal server error");
}
});
socket.on("close", () => close("disconnect", false));
});
return server_;
};
async #builtJSX(file, code, req, res, files, pk) {
file = path.join(file).replaceAll("\\", "/");
if (files[file] || res.headersSent) return;
if (this.#builtJSXCache[file]) {
files[file] = this.#builtJSXCache[file];
pk[file] = files[file].pk;
return;
}
let json;
if (this.dev) {
const inits = [];
json = await this.#pseudoBuildJSX(file, code, null, inits);
code = json.code;
delete json.code;
if (inits.length) {
printer.dev.fail("A function with the decorator @server/start was found. Please use the main file instead.\n Note: @server/start decorator can only be used in production mode!");
res.json({error: "Internal server error"});
return;
}
} else json = this.#jsxFunctions[file];
if (!json) {
printer.dev.fail("Couldn't find the JSX file in build: " + file);
res.json({error: "Internal server error"});
return;
}
const sr = json.serverFunctions;
const k = Object.keys(sr);
const nmPath = path.join(this.#dir, "node_modules");
let pkgL = json.importList;
if (config.allowAllPackages && fs.existsSync(nmPath)) {
pkgL = fs.readdirSync(nmPath);
for (const pkgN of pkgL) this.#getPackageImport(pkgN);
}
files[file] = {
code,
json,
pk: {
code,
functions: k.filter(i => !sr[i].r),
respondFunctions: k.filter(i => sr[i].r),
importList: pkgL.map(i => [i, (this.#importMap[i] || {}).version || ""])
}
};
pk[file] = files[file].pk;
if (!this.dev) this.#builtJSXCache[file] = files[file];
let ls = req._Allow;
const deny = req._Deny;
if (deny === "*") ls = [];
else if (ls === "*") {
if (this.dev) {
ls = [];
const d = h => {
const p = path.join(this.#dir, config.srcFolder, h).replaceAll("\\", "/");
const fl = fs.readdirSync(p);
for (const i of fl) {
const fl = path.join(p, i).replaceAll("\\", "/");
if (!fs.existsSync(fl)) return;
if (fs.statSync(fl).isFile()) {
const p = (h ? h + "/" : "") + i;
if (!deny.includes(p)) ls.push(p);
} else d((h ? h + "/" : "") + i)
}
};
d("");
} else ls = Object.keys(this.#buildCache).filter(i => !deny.includes(i));
} else if (ls === "auto") ls = json.fileImportList.map(i => path.join(path.dirname(file), i));
const ch = async s => {
if (this.dev) {
const pt = path.join(this.#dir, config.srcFolder, s);
if (!fs.existsSync(pt) || !fs.statSync(pt).isFile()) return;
return this.cacheDevFile(pt);
} else return await this.cacheBuildFile(s);
};
for (let f of ls) {
let c;
const pR = path.join(f).replaceAll("\\", "/");
let p = pR;
if (!path.extname(pR)) for (const a of ["tsx", "jsx", "ts", "js"]) {
c = await ch(p);
if (c === undefined) p = pR + "." + a;
else {
f = p;
break;
}
} else {
f = p;
c = await ch(p);
}
if (deny.includes(f) || files[f] || c === undefined) continue;
if (!c) c = "";
this.watchFile(f);
if (f.endsWith(".jsx") || f.endsWith(".tsx")) await this.#builtJSX(f, c, req, res, files, pk);
else {
if (c instanceof Buffer) {
const ext = path.extname(f).substring(1);
if (["js", "html", "css"].includes(ext)) c = c.toString();
else {
const fH = this.filePacketHandlers[ext];
if (fH) c = await fH(f, c);
else c = [...c];
}
}
files[f] = c;
pk[f] = c;
}
}
};
async renderJSX(file, code, req, res, fromScript = false) {
if (res.headersSent) return;
this.prepLoad(req, res);
const r = random();
if (!this.#realtime) return res.json({error: "Expected 'realtime' option in the Hizzy configuration file to be true."});
if (fromScript && req.__socket) {
if (
typeof req.headers["hizzy-payload-id"] !== "string" ||
req.headers["hizzy-payload-id"].includes("\x00") // no xss allowed 👀
) return;
const cPages = await this.#getPagePacket(file, code, req, res);
if (res.headersSent) return;
req.__socket._externalLoad(
file, this.#clientPages[req._uuid],
req._RouteJSON + "\x00" + req.headers["hizzy-payload-id"] + "\x00" + cPages,
req.headers["hizzy-cache"] === "yes"
);
}
if (req.__socket) return res.send("<script>location.reload()</script>"); // in case somehow client sees this.
this.#hashes[req._uuid] = r;
const cPages = await this.#getPagePacket(file, code, req, res);
this.#startPacket[req._uuid] = req._RouteJSON + "\x00\x00" + cPages;
const confJ = `['${r}','${this.#buildRuntimeId || runtimeId}',` +
`${config.keepaliveTimeout > 0 ? config.clientKeepalive : -1},${this.dev ? 1 : 0},` +