Add Hopper transport: protocol, bridge launcher, client
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { HopperProtocolError, HopperRemoteError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
export const jsonValueSchema = z.json();
|
||||
export type JsonValue = z.infer<typeof jsonValueSchema>;
|
||||
|
||||
const responseSchema = z.union([
|
||||
z.object({
|
||||
id: z.number().int().nonnegative(),
|
||||
result: jsonValueSchema,
|
||||
}),
|
||||
z.object({
|
||||
id: z.number().int().nonnegative(),
|
||||
error: z.object({ code: z.number().int(), message: z.string() }),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type HopperResponse = z.infer<typeof responseSchema>;
|
||||
|
||||
/** Parse one complete Hopper NDJSON response line. */
|
||||
export const parseResponseLine = (
|
||||
line: string,
|
||||
): Result<HopperResponse, HopperProtocolError> => {
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(line);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new HopperProtocolError("Hopper returned malformed JSON", { cause }),
|
||||
);
|
||||
}
|
||||
|
||||
const parsed = responseSchema.safeParse(decoded);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
: err(
|
||||
new HopperProtocolError(
|
||||
"Hopper returned a response outside the bridge contract",
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
/** Project a parsed response into its result or expected remote failure. */
|
||||
export const responseResult = (
|
||||
response: HopperResponse,
|
||||
): Result<JsonValue, HopperRemoteError> =>
|
||||
"error" in response
|
||||
? err(new HopperRemoteError(response.error.code, response.error.message))
|
||||
: ok(response.result);
|
||||
Reference in New Issue
Block a user