-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplutoscript.js
560 lines (503 loc) · 13.4 KB
/
plutoscript.js
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
const LUA_TNONE = -1;
const LUA_TNIL = 0;
const LUA_TBOOLEAN = 1;
const LUA_TLIGHTUSERDATA = 2;
const LUA_TNUMBER = 3;
const LUA_TSTRING = 4;
const LUA_TTABLE = 5;
const LUA_TFUNCTION = 6;
const LUA_TUSERDATA = 7;
const LUA_TTHREAD = 8;
const LUA_OK = 0;
const LUA_YIELD = 1;
const LUAI_MAXSTACK = 1000000;
const LUA_REGISTRYINDEX = (-LUAI_MAXSTACK - 1000);
const LUA_NOREF = -2;
const LUA_REFNIL = -1;
let lib, L, callbacks = [];
libpluto().then(function(mod)
{
lib = {
mod: mod,
malloc: mod.cwrap("malloc", "int", ["int"]),
luaL_newstate: mod.cwrap("luaL_newstate", "int", []),
luaL_openlibs: mod.cwrap("luaL_openlibs", "void", ["int"]),
luaL_loadstring: mod.cwrap("luaL_loadstring", "int", ["int", "string"]),
luaL_loadbufferx: mod.cwrap("luaL_loadbufferx", "int", ["int", "array", "int", "int", "int"]),
lua_callk: mod.cwrap("lua_callk", "void", ["int", "int", "int", "int", "int"]),
lua_getglobal: mod.cwrap("lua_getglobal", "void", ["int", "string"]),
lua_type: mod.cwrap("lua_type", "int", ["int", "int"]),
lua_pushnil: mod.cwrap("lua_pushnil", "void", ["int"]),
lua_pushstring: mod.cwrap("lua_pushstring", "void", ["int", "string"]),
lua_pushlstring: mod.cwrap("lua_pushlstring", "void", ["int", "array", "int"]),
lua_pushinteger: mod.cwrap("lua_pushinteger", "void", ["int", "int"]),
lua_pushnumber: mod.cwrap("lua_pushnumber", "void", ["int", "number"]),
lua_pushboolean: mod.cwrap("lua_pushboolean", "void", ["int", "int"]),
lua_istrue: mod.cwrap("lua_istrue", "int", ["int", "int"]),
lua_isinteger: mod.cwrap("lua_isinteger", "int", ["int", "int"]),
lua_tolstring: mod.cwrap("lua_tolstring", "string", ["int", "int", "int"]),
lua_tointegerx: mod.cwrap("lua_tointegerx", "int", ["int", "int", "int"]),
lua_tonumberx: mod.cwrap("lua_tonumberx", "number", ["int", "int", "int"]),
lua_settop: mod.cwrap("lua_settop", "void", ["int", "int"]),
lua_setglobal: mod.cwrap("lua_setglobal", "void", ["int", "string"]),
lua_newthread: mod.cwrap("lua_newthread", "int", ["int"]),
lua_xmove: mod.cwrap("lua_xmove", "void", ["int", "int", "int"]),
lua_closethread: mod.cwrap("lua_closethread", "void", ["int", "int"]),
lua_status: mod.cwrap("lua_status", "int", ["int"]),
lua_resume: mod.cwrap("lua_resume", "int", ["int", "int", "int", "int"]),
lua_gettop: mod.cwrap("lua_gettop", "int", ["int"]),
lua_pushvalue: mod.cwrap("lua_pushvalue", "int", ["int", "int"]),
luaL_ref: mod.cwrap("luaL_ref", "int", ["int", "int"]),
lua_rawgeti: mod.cwrap("lua_rawgeti", "void", ["int", "int", "int"]),
luaL_unref: mod.cwrap("luaL_unref", "int", ["int", "int", "int"]),
lua_next: mod.cwrap("lua_next", "int", ["int"]),
lua_createtable: mod.cwrap("lua_createtable", "void", ["int", "int", "int"]),
lua_settable: mod.cwrap("lua_settable", "void", ["int", "int"]),
};
lib.tmpint = lib.malloc(4);
lib.lua_pop = (L, n) => lib.lua_settop(L, -(n)-1);
L = lib.luaL_newstate();
lib.luaL_openlibs(L);
lib.luaL_loadstring(L,`--[[ PlutoScript Runtime ]]
js_invoke = coroutine.yield
dofile = function(src)
local chunk, err = load(js_invoke("pluto_cmd_fetch", src))
if not chunk then
error(err)
end
return chunk()
end
window = setmetatable({}, { -- silly little thingy to make 'window.alert' work
__index = function(self, key)
return setmetatable({}, {
__call = function(_, ...)
js_invoke(key, ...)
end
})
end
})
class Element
function __construct(public path)
end
function __index(key)
if Element[key] then
return Element[key]
end
return js_invoke("pluto_cmd_Element_index", self.path, key)
end
function __newindex(key, value)
if key == "path" then
rawset(self, key, value)
end
return js_invoke("pluto_cmd_Element_newindex", self.path, key, value)
end
function addEventListener(type, callback)
js_invoke("pluto_cmd_addEventListener", self.path, type, callback)
end
function addClass(name)
js_invoke("pluto_cmd_addClass", self.path, name)
end
function removeClass(name)
js_invoke("pluto_cmd_removeClass", self.path, name)
end
function removeAttribute(name, value)
js_invoke("pluto_cmd_setAttribute", self.path, name, value)
end
function removeAttribute(name)
js_invoke("pluto_cmd_removeAttribute", self.path, name)
end
end
document = {
query = |x| -> new Element(x),
querySelector = |x| -> new Element(x),
getElementById = |x| -> new Element("#"..x),
}`);
lib.lua_callk(L, 0, 0, 0, 0);
callbacks.forEach(cb => cb());
callbacks = [];
});
function pluto_await()
{
return new Promise(resolve => {
if (lib)
{
resolve();
}
else
{
callbacks.push(resolve);
}
});
}
async function pluto_load_script_tags()
{
const requests = {};
for (const script of document.querySelectorAll("script[type=pluto]"))
{
if (script.getAttribute("src"))
{
if (!requests[script.getAttribute("src")])
{
requests[script.getAttribute("src")] = fetch(script.getAttribute("src")).then(res => res.arrayBuffer());
}
}
}
await pluto_await();
for (const script of document.querySelectorAll("script[type=pluto]"))
{
if (script.getAttribute("src"))
{
const abRes = await requests[script.getAttribute("src")];
pluto_load(new Uint8Array(abRes));
}
else
{
pluto_load(script.textContent);
}
}
}
if (document.readyState == "complete" || document.readyState == "interactive")
{
pluto_load_script_tags();
}
else
{
window.addEventListener("DOMContentLoaded", pluto_load_script_tags);
}
function pluto_require(src)
{
return new Promise(resolve => {
fetch(src).then(res => res.arrayBuffer()).then(cont => pluto_await().then(() => pluto_load(new Uint8Array(cont)).then(resolve)));
});
}
function pluto_load(cont)
{
if ((cont instanceof Uint8Array
? lib.luaL_loadbufferx(L, cont, cont.length, 0, 0)
: lib.luaL_loadstring(L, cont))
== LUA_OK)
{
return pluto_invoke_impl();
}
else
{
let err = lib.lua_tolstring(L, -1, 0);
lib.lua_pop(L, 1);
return Promise.reject(err);
}
}
function pluto_push(coro, arg)
{
switch (typeof(arg))
{
case "string":
lib.lua_pushstring(coro, arg);
return true;
case "number":
if (arg % 1 === 0)
{
lib.lua_pushinteger(coro, arg);
}
else
{
lib.lua_pushnumber(coro, arg);
}
return true;
case "boolean":
lib.lua_pushboolean(coro, arg ? 1 : 0);
return true;
case "object":
if (arg instanceof Uint8Array)
{
lib.lua_pushlstring(coro, arg, arg.length);
}
else
{
lib.lua_createtable(coro, 0, 0);
for (key in arg)
{
let intkey = parseInt(key);
if (pluto_push(coro, intkey == key ? intkey + 1 : key))
{
if (pluto_push(coro, arg[key]))
{
lib.lua_settable(coro, -3);
}
else
{
lib.lua_pop(coro, 1);
}
}
}
}
return true;
}
return false;
}
function pluto_extract(coro, nvals)
{
let vals = [];
for (let i = 0; i != nvals; ++i)
{
switch (lib.lua_type(coro, -(nvals-i)))
{
case LUA_TBOOLEAN:
vals.push(lib.lua_istrue(coro, -(nvals-i)));
break;
case LUA_TSTRING:
vals.push(lib.lua_tolstring(coro, -(nvals-i), 0));
break;
case LUA_TNUMBER:
if (lib.lua_isinteger(coro, -(nvals-i)))
{
vals.push(lib.lua_tointegerx(coro, -(nvals-i), 0));
}
else
{
vals.push(lib.lua_tonumberx(coro, -(nvals-i), 0));
}
break;
case LUA_TFUNCTION:
lib.lua_pushvalue(coro, -(nvals-i));
let ref = lib.luaL_ref(coro, LUA_REGISTRYINDEX);
vals.push(function()
{
lib.lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
pluto_invoke_impl();
});
break;
case LUA_TTABLE:
let obj = {};
lib.lua_pushvalue(coro, -(nvals-i));
lib.lua_pushnil(coro);
while (lib.lua_next(coro, -2))
{
let [key, value] = pluto_extract(coro, 2);
if (typeof(key) == "number")
{
key--;
}
obj[key] = value;
lib.lua_pop(coro, 1);
}
lib.lua_pop(coro, 1);
vals.push(obj);
break;
default:
throw new Error("Unsupported return type: " + lib.lua_type(coro, -(nvals-i)));
}
}
return vals;
}
// Calls the function at -1
function pluto_invoke_impl(...args)
{
return new Promise((resolve, reject) => {
let interval, coro, coro_ref, nargs = 0, awaiting_promise = false;
coro = lib.lua_newthread(L);
coro_ref = lib.luaL_ref(L, LUA_REGISTRYINDEX);
lib.lua_xmove(L, coro, 1);
args.forEach(arg => {
if (!pluto_push(coro, arg))
{
return reject(new Error("Unsupported argument type: " + typeof(arg)));
}
++nargs;
});
interval = setInterval(function()
{
if (awaiting_promise)
{
return;
}
let err, nres, res;
for (let initial = true; initial || lib.lua_status(coro) == LUA_YIELD; initial = false)
{
let status = lib.lua_resume(coro, L, nargs, lib.tmpint);
nargs = 0;
if (status == LUA_YIELD)
{
nres = lib.mod.HEAP32[lib.tmpint / 4];
if (nres == 0)
{
return;
}
let data = pluto_extract(coro, nres);
lib.lua_pop(coro, nres);
let ret = window[data.shift()](...data);
if (ret)
{
if (ret instanceof Promise)
{
awaiting_promise = true;
ret.then(ret => {
if (pluto_push(coro, ret))
{
nargs = 1;
}
}).finally(() => {
awaiting_promise = false;
});
return;
}
if (pluto_push(coro, ret))
{
nargs = 1;
}
}
}
else if (status != LUA_OK)
{
err = new Error(lib.lua_tolstring(coro, -1, 0));
break;
}
}
clearInterval(interval);
if (!err)
{
nres = lib.lua_gettop(coro);
res = pluto_extract(coro, nres);
}
lib.lua_closethread(coro, L);
lib.luaL_unref(L, LUA_REGISTRYINDEX, coro_ref);
if (!err)
{
resolve(nres == 1 ? res[0] : res);
}
else
{
reject(err);
}
}, 1);
});
}
function pluto_invoke(name, ...args)
{
lib.lua_getglobal(L, name);
if (lib.lua_type(L, -1) != LUA_TFUNCTION)
{
throw new Error(name + " is not defined as a function in any Pluto script");
}
return pluto_invoke_impl(...args);
}
const utf32_to_utf8 = function(utf8/*: array */, utf32/*: number */)/*: void */
{
// 1
if (utf32 < 0b10000000)
{
utf8.push(utf32);
return;
}
// 2
const UTF8_CONTINUATION_FLAG = 0b10000000;
utf8.push((utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
if (utf32 <= 0b11111)
{
utf8.splice(utf8.length - 1, 0, utf32 | 0b11000000); // 110xxxxx
return;
}
// 3
utf8.splice(utf8.length - 1, 0, (utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
if (utf32 <= 0b1111)
{
utf8.splice(utf8.length - 2, 0, utf32 | 0b11100000); // 1110xxxx
return;
}
// 4
utf8.splice(utf8.length - 2, 0, (utf32 & 0b111111) | UTF8_CONTINUATION_FLAG);
utf32 >>= 6;
utf8.splice(utf8.length - 3, 0, utf32 | 0b11110000); // 11110xxx
}
const utf16_to_utf8 = function(str)
{
let arr = [];
for(let i = 0; i < str.length; ++i)
{
let c = str.charCodeAt(i);
if ((c >> 10) == 0x36) // Surrogate pair?
{
let hi = c & 0x3ff;
let lo = str.charCodeAt(++i) & 0x3ff;
c = (((hi * 0x400) + lo) + 0x10000);
}
utf32_to_utf8(arr, c);
}
return arr;
}
function pluto_give_file(name, data)
{
if (typeof data == "string")
{
data = new Uint8Array(utf16_to_utf8(data));
}
let stream = lib.mod.FS.open(name, "w+");
lib.mod.FS.write(stream, data, 0, data.length, 0);
lib.mod.FS.close(stream);
}
// Commands for Pluto Runtime
function pluto_cmd_fetch(src)
{
return new Promise(resolve => {
fetch(src).then(res => res.arrayBuffer()).then(cont => resolve(new Uint8Array(cont)));
});
}
function pluto_cmd_Element_index(path, key)
{
return document.querySelector(path)[key];
}
function pluto_cmd_Element_newindex(path, key, value)
{
document.querySelector(path)[key] = value;
}
function pluto_cmd_addEventListener(path, evt, f)
{
document.querySelector(path).addEventListener(evt, f);
}
function pluto_cmd_addClass(path, name)
{
document.querySelector(path).classList.add(name);
}
function pluto_cmd_removeClass(path, name)
{
document.querySelector(path).classList.remove(name);
}
function pluto_cmd_setAttribute(path, name, value)
{
document.querySelector(path).setAttribute(name, value);
}
function pluto_cmd_removeAttribute(path, name)
{
document.querySelector(path).removeAttribute(name);
}
// DOM Helpers (stolen from https://dev.to/aniket_chauhan/generate-a-css-selector-path-of-a-dom-element-4aim)
function generateSelector(context) {
let index, pathSelector, localName;
if (context == "null") throw "not an dom reference";
// call getIndex function
index = getIndex(context);
while (context.tagName) {
// selector path
pathSelector = context.localName + (pathSelector ? ">" + pathSelector : "");
context = context.parentNode;
}
// selector path for nth of type
pathSelector = pathSelector + `:nth-of-type(${index})`;
return pathSelector;
}
// get index for nth of type element
function getIndex(node) {
let i = 1;
let tagName = node.tagName;
while (node.previousSibling) {
node = node.previousSibling;
if (
node.nodeType === 1 &&
tagName.toLowerCase() == node.tagName.toLowerCase()
) {
i++;
}
}
return i;
}