From 7ecf5c098b44c1200b96de7024e0d39c8fc44fb2 Mon Sep 17 00:00:00 2001 From: grypez <143971198+grypez@users.noreply.github.com> Date: Sat, 28 Sep 2024 06:03:32 -0500 Subject: [PATCH] feat(kernel): Add Error as a possible params type of CommandReply. --- packages/extension/src/kernel-worker.ts | 13 +++++++++++- packages/kernel/src/command.ts | 27 +++++++++++++++++-------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/packages/extension/src/kernel-worker.ts b/packages/extension/src/kernel-worker.ts index 87ec5dd2f..29791d42e 100644 --- a/packages/extension/src/kernel-worker.ts +++ b/packages/extension/src/kernel-worker.ts @@ -172,6 +172,17 @@ async function main(): Promise { postMessage({ method, params }); }; + /** + * Cast an unknown problem to an Error object. + * + * @param problem - Whatever was caught. + * @returns The problem if it is an Error, or a new Error with the problem as the cause. + */ + const asError = (problem: unknown): Error => + problem instanceof Error + ? problem + : new Error('Unknown', { cause: problem }); + // Handle messages from the console service worker globalThis.onmessage = async (event: MessageEvent) => { if (!isCommand(event.data)) { @@ -213,7 +224,7 @@ async function main(): Promise { const result = kvGet(params); reply(CommandMethod.KVGet, result); } catch (problem) { - reply(CommandMethod.KVGet, problem as string); // cast is a lie, it really is an Error + reply(CommandMethod.KVGet, asError(problem)); } break; } diff --git a/packages/kernel/src/command.ts b/packages/kernel/src/command.ts index 8d3e6cc72..de287c6e1 100644 --- a/packages/kernel/src/command.ts +++ b/packages/kernel/src/command.ts @@ -31,6 +31,15 @@ type CommandLike = { params: Data; }; +type CommandReplyLike< + Method extends CommandMethod, + Data extends CommandParams, + ErrorType extends Error = never, +> = { + method: Method; + params: Data | ErrorType; +}; + const isCommandLike = ( value: unknown, ): value is { @@ -67,22 +76,24 @@ export type CommandFunction> = { }; export type CommandReply = - | CommandLike - | CommandLike - | CommandLike - | CommandLike - | CommandLike - | CommandLike; + | CommandReplyLike + | CommandReplyLike + | CommandReplyLike + | CommandReplyLike + | CommandReplyLike + | CommandReplyLike; export const isCommandReply = (value: unknown): value is CommandReply => - isCommandLike(value) && typeof value.params === 'string'; + isCommandLike(value) && + (typeof value.params === 'string' || value.params instanceof Error); type UnionMinus = Union extends Minus ? never : Union; export type CommandReplyFunction = { (method: CommandMethod.Ping, params: 'pong'): Return; + (method: CommandMethod.KVGet, params: string | Error): Return; ( - method: UnionMinus, + method: UnionMinus, params: string, ): Return; };