silverbullet/common/space_lua/stdlib/js.ts

71 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2024-10-10 02:35:07 +08:00
import {
2024-10-11 21:34:27 +08:00
jsToLuaValue,
LuaBuiltinFunction,
LuaTable,
luaValueToJS,
2024-10-10 02:35:07 +08:00
} from "$common/space_lua/runtime.ts";
export const jsApi = new LuaTable({
/**
* Creates a new instance of a JavaScript class.
* @param constructorFn - The constructor function.
* @param args - The arguments to pass to the constructor.
* @returns The new instance.
*/
2024-10-11 21:34:27 +08:00
new: new LuaBuiltinFunction(
(_sf, constructorFn: any, ...args) => {
2024-10-11 21:34:27 +08:00
return new constructorFn(
...args.map(luaValueToJS),
);
},
),
/**
* Imports a JavaScript module.
* @param url - The URL of the module to import.
* @returns The imported module.
*/
import: new LuaBuiltinFunction(async (_sf, url) => {
let m = await import(url);
// Unwrap default if it exists
if (Object.keys(m).length === 1 && m.default) {
m = m.default;
}
return m;
2024-10-11 21:34:27 +08:00
}),
2025-01-16 19:35:15 +08:00
each_iterable: new LuaBuiltinFunction((_sf, val) => {
2025-01-16 22:35:56 +08:00
const iterator = val[Symbol.asyncIterator]();
2025-01-16 19:35:15 +08:00
return async () => {
const result = await iterator.next();
if (result.done) {
return;
}
return result.value;
};
}),
/**
* Converts a JavaScript value to a Lua value.
* @param val - The JavaScript value to convert.
* @returns The Lua value.
*/
2024-10-20 21:06:23 +08:00
tolua: new LuaBuiltinFunction((_sf, val) => jsToLuaValue(val)),
/**
* Converts a Lua value to a JavaScript value.
* @param val - The Lua value to convert.
* @returns The JavaScript value.
*/
2024-10-20 21:06:23 +08:00
tojs: new LuaBuiltinFunction((_sf, val) => luaValueToJS(val)),
/**
* Logs a message to the console.
* @param args - The arguments to log.
*/
2024-10-20 21:06:23 +08:00
log: new LuaBuiltinFunction((_sf, ...args) => {
2024-10-11 21:34:27 +08:00
console.log(...args);
}),
/**
* Converts a Lua value to a JSON string.
* @param val - The Lua value to convert.
* @returns The JSON string.
*/
2025-01-09 00:09:09 +08:00
stringify: new LuaBuiltinFunction((_sf, val) => JSON.stringify(val)),
2024-10-10 02:35:07 +08:00
});