47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { redactAnalysis, type RedactionResult } from "./redact";
|
|
import type { Analysis } from "./types";
|
|
|
|
const results = new WeakMap<Analysis, Promise<RedactionResult>>();
|
|
|
|
function runInline(analysis: Analysis): Promise<RedactionResult> {
|
|
try {
|
|
return Promise.resolve(redactAnalysis(analysis));
|
|
} catch (reason) {
|
|
return Promise.reject(reason);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Redact in a Web Worker so large analyses never block the UI thread.
|
|
* Results are cached per loaded analysis; the original object is never mutated.
|
|
*/
|
|
export function redactInBackground(analysis: Analysis): Promise<RedactionResult> {
|
|
const cached = results.get(analysis);
|
|
if (cached) return cached;
|
|
const pending =
|
|
typeof Worker === "undefined"
|
|
? runInline(analysis)
|
|
: new Promise<RedactionResult>((resolve, reject) => {
|
|
let worker: Worker;
|
|
try {
|
|
worker = new Worker(new URL("./workers/redact.worker.ts", import.meta.url), { type: "module" });
|
|
} catch {
|
|
runInline(analysis).then(resolve, reject);
|
|
return;
|
|
}
|
|
worker.onmessage = (message: MessageEvent<RedactionResult>) => {
|
|
worker.terminate();
|
|
resolve(message.data);
|
|
};
|
|
worker.onerror = (event) => {
|
|
event.preventDefault();
|
|
worker.terminate();
|
|
runInline(analysis).then(resolve, reject);
|
|
};
|
|
worker.postMessage(analysis);
|
|
});
|
|
results.set(analysis, pending);
|
|
pending.catch(() => results.delete(analysis));
|
|
return pending;
|
|
}
|