Open History to see the last commit
1import { previewFailure, type PreviewFailure } from "./previewFailure";
2import type { PreviewFailureCode } from "./previewFailureMessages";
3
4export type PreviewUnlock = { readonly type: "unlock"; readonly password: string };
5export type PreviewPassword = { readonly type: "password"; readonly incorrect: boolean };
6
7// Keep the encrypted input in the worker while the form is open. A retry only sends the password.
8export function previewUnlock<Request extends { type: string }>(
9 open: (request: Request, password?: string) => Promise<void>,
10 reply: (result: PreviewPassword | ({ type: "error" } & PreviewFailure)) => void,
11 fallback: PreviewFailureCode,
12) {
13 let locked: Request | undefined;
14 let working = false;
15 return async (request: Request | PreviewUnlock) => {
16 const input = request.type === "unlock" ? locked : (request as Request);
17 if (!input || (input.type === "open" && working)) return;
18 if (input.type === "open") working = true;
19 try {
20 await open(input, "password" in request ? request.password : undefined);
21 if (input.type === "open") locked = undefined;
22 } catch (cause) {
23 const failure = previewFailure(cause, fallback);
24 if (failure.code === "password-required" || failure.code === "password-incorrect") {
25 locked = input;
26 reply({ type: "password", incorrect: failure.code === "password-incorrect" });
27 } else {
28 if (input.type === "open") locked = undefined;
29 reply({ type: "error", ...failure });
30 }
31 } finally {
32 if (input.type === "open") working = false;
33 }
34 };
35}