Files
plainleaf/web/syscalls/system.ts
T
+1 766fb96ff2 Adding support for hosting with URL prefix (#1357)
* Adding support for hosting with URL prefix to make reverse-proxy setup on sub-path possible

* Adjusting recent changes to auth.html (changing to relative URLs)  after rebasing from upstream

* Adjusting service_worker and application manifest to support URL-prefix

* Add notes on Space Lua Pattern Matching (#1366)

* Remove common/space_lua/stdlib/math.md (#1371)

* Escape pipe symbol in string.gsub (#1370)

* feat: configure vim in CONFIG (#1369)

* Fix week calculation (#1368)

* Add more tests for week calculation

* Fix week calculation

* Add more tests

* Implement Lua built-in function os.difftime (#1367)

* Implement Lua built-in function os.difftime

* Test os.difftime

---------

Co-authored-by: Zef Hemel <zef@zef.me>

* Fix index page naming during server initialization (#1365)

* Allow non-zero shell exit codes (#1377)

* Generate version from git describe at build time (#1374)

* Generate version from git describe at build time

* Add 2.0-beta prefix

* Use Deno.Command instead of Deno.run

* Add missing case to math.random and check arguments (#1372)

* Fix paragraphs for the tag page (#1376)

* Render a predefined string for empty markdown table instead of pipe characters (#1387)

* Fix string.find (#1390)

* Fetch tags and history for proper version string generation (#1388)

* Fix support for disabling shortcuts (#1393)

* Add GitHub Actions Cache to reduce build times (#1394)

* Order strings in queries using collation algorithm (#1391)

Configurable with queryCollation, default value maintains old behaviour.
Added tests, schema, example settings, and documentation to query page.

Close: #614
Close: #1316

* Utility function to handle empty query results and templates (#1386)

* Add global Lua function 'some'

Moved documentation for 'each' function to non-standard section.

* Revert "Add optional argument to template.each for empty collection output (#1359)"

This reverts commit b73dadec67.

* Reimplement #1359 using 'some' function

* Update Lua to event.listEvents to match plugos syscall (#1397)

The documentation, example, and other function names use
`event.listEvents`, but `event.list` is being registered with the
client.

* Update widget header to not overflow container (#1410)

Also add a 10px margin below the header to maintain consistent spacing
around the widget contents.

* fix: case insensitive admonitions by default (#1409)

* fix: closing bracket is missing (#1408)

* Add optional priority attribute to PageCreatingContent (#1392)

* Add optional priority attribute to PageCreatingContent

* Minor simplification

* Fix comments

* Revert changes

* Add pageEventHandlers

* Use UTC year, month, and date for strings lacking time components (#1403)

* feat: allow CONFIG.md in any directory (#1398)

* fix: bundle external dependencies (#1379)

* Deno bump

* Copy-edit splash screen text (#1413)

* Fixes #1401 by implementing Lua's select

* Fixes offline capability of PWA (I hope).

Now storing config in localStorage.

* fix lint

* Reduce blast radius of Lua errors

* Fixes #1411: adds 'priority' setting for space style

* Refactor: Merging common/ into web/

* Fixes #1400

* Improves #1312 by rendering Lua expressions (but not widgets)

* Fix minor typos, add configuration to the docs

---------

Co-authored-by: wbhouston <wmbhouston@gmail.com>
Co-authored-by: Lennart Ochel <lennart.ochel@outlook.com>
Co-authored-by: Matthias Benaets <89214559+MatthiasBenaets@users.noreply.github.com>
Co-authored-by: Zef Hemel <zef@zef.me>
Co-authored-by: Marek S. Łukasiewicz <marek@lukasiewicz.tech>
Co-authored-by: Ivan Alejandro <ivanalejandro0@gmail.com>
Co-authored-by: Albert-Jan de Vries <aj+github@albert-jandevries.nl>
Co-authored-by: Cole Stowell <121599022+costowell@users.noreply.github.com>
Co-authored-by: Jim Tittsler <jimt@onjapan.net>
2025-06-04 15:15:14 +02:00

191 lines
6.3 KiB
TypeScript

import type { SyscallMeta } from "../../plug-api/types.ts";
import type { SysCallMapping } from "../../lib/plugos/system.ts";
import type { Client } from "../client.ts";
import type { CommandDef } from "$lib/command.ts";
import { version } from "../../version.ts";
import { deleteDB } from "idb";
export function systemSyscalls(
client: Client,
readOnlyMode: boolean,
): SysCallMapping {
const api: SysCallMapping = {
"system.invokeFunction": (
_ctx,
fullName: string, // plug.function
...args: any[]
) => {
const [plugName, functionName] = fullName.split(".");
if (!plugName || !functionName) {
throw Error(`Invalid function name ${fullName}`);
}
const plug = client.clientSystem.system.loadedPlugs.get(plugName);
if (!plug) {
throw Error(`Plug ${plugName} not found`);
}
const functionDef = plug.manifest!.functions[functionName];
if (!functionDef) {
throw Error(`Function ${functionName} not found`);
}
return plug.invoke(functionName, args);
},
"system.invokeFunctionOnServer": (
ctx,
fullName: string, // plug.function
...args: any[]
) => {
console.warn(
"Calling deprecated system.invokeFunctionOnServer, use system.invokeFunction instead",
);
return api["system.invokeFunction"](ctx, fullName, ...args);
},
"system.serverSyscall": (_ctx, name: string, ...args: any[]) => {
console.warn(
"Calling deprecated system.serverSyscall, use syscall instead",
);
return client.clientSystem.localSyscall(name, args);
},
"system.invokeCommand": (_ctx, name: string, args?: string[]) => {
if (!client) {
throw new Error("Not supported");
}
return client.runCommandByName(name, args);
},
"system.listCommands": (): { [key: string]: CommandDef } => {
const commandHook = client.clientSystem.commandHook;
const allCommands: { [key: string]: CommandDef } = {};
for (const [cmd, def] of commandHook.editorCommands) {
allCommands[cmd] = {
name: def.command.name,
contexts: def.command.contexts,
priority: def.command.priority,
key: def.command.key,
mac: def.command.mac,
hide: def.command.hide,
requireMode: def.command.requireMode,
};
}
return allCommands;
},
"system.listSyscalls": (): SyscallMeta[] => {
const syscalls: SyscallMeta[] = [];
for (
const [name, info] of client.clientSystem.system.registeredSyscalls
) {
syscalls.push({
name,
requiredPermissions: info.requiredPermissions,
argCount: Math.max(0, info.callback.length - 1),
});
}
return syscalls;
},
"system.reloadPlugs": () => {
if (!client) {
throw new Error("Not supported");
}
return client.loadPlugs();
},
"system.reloadConfig": (): Record<string, any> => {
console.warn("system.reloadConfig is deprecated, it's now a no-op");
return client.config.values;
},
"system.loadSpaceScripts": async () => {
await client.clientSystem.loadSpaceScripts();
},
"system.loadSpaceStyles": async () => {
if (!client) {
throw new Error("Not supported on server");
}
await client.loadCustomStyles();
},
"system.wipeClient": async (_ctx, logout = false) => {
// Two tracks:
// 1. Service worker unregister
// 2. IndexedDB cleaning
if (navigator.serviceWorker) {
const registration = await navigator.serviceWorker.ready;
if (registration?.active) {
// Disconnect the datastore in the service worker first
registration.active.postMessage({ type: "shutdown" });
// Then flush the cache
registration.active.postMessage({ type: "flushCache" });
await new Promise<void>((resolve) => {
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data.type === "cacheFlushed") {
console.log("Cache flushed");
navigator.serviceWorker.getRegistrations().then(
async (registrations) => {
for (const registration of registrations) {
await registration.unregister();
}
resolve();
},
);
}
});
});
} else {
console.info("No service worker active, so not unregistering");
}
} else {
console.info("Service workers not supported, so not unregistering");
}
console.log("Stop all the systems");
client.space.unwatch();
client.syncService.close();
client.ds.kv.close();
if (indexedDB.databases) {
// get a list of all existing IndexedDB databases
const databases = await indexedDB.databases();
// loop through the list and delete each database
for (const database of databases) {
console.log("Deleting database", database.name);
await deleteDB(database.name!);
}
} else {
// Firefox doesn't support indexedDB.databases :(
console.info(
"Cannot delete local database, so go to empty them instead",
);
const allKeys = [];
for await (
const { key } of client.ds.kv.query({})
) {
allKeys.push(key);
}
await client.ds.batchDelete(allKeys);
}
if (logout) {
location.href = ".logout";
} else {
alert("Client wiped, feel free to navigate elsewhere");
}
},
// DEPRECATED
"system.getEnv": () => {
console.warn(
"system.getEnv is deprecated, you can assume the env to always be the client",
);
return null;
},
"system.getSpaceConfig": (_ctx, key, defaultValue?) => {
console.warn(
"system.getSpaceConfig is deprecated, use system.getConfig instead",
);
return client.config.get(key, defaultValue);
},
"system.getMode": () => {
return readOnlyMode ? "ro" : "rw";
},
"system.getVersion": () => {
return version;
},
"system.getConfig": (_ctx, key: string, defaultValue: any = undefined) => {
return client.config.get(key, defaultValue);
},
};
return api;
}