clipboard.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. export interface ClipboardSnapshot {
  2. readonly text: string;
  3. readonly html?: string;
  4. }
  5. /**
  6. * Browser-facing clipboard boundary. Implementations must not assume access
  7. * to the host operating system clipboard; a provider can be scoped to one
  8. * evaluation case and restored when that case finishes.
  9. */
  10. export interface ClipboardProvider {
  11. read(): Promise<ClipboardSnapshot>;
  12. write(snapshot: ClipboardSnapshot): Promise<void>;
  13. snapshot(): Promise<ClipboardSnapshot>;
  14. restore(snapshot: ClipboardSnapshot): Promise<void>;
  15. }
  16. /**
  17. * In-memory clipboard used by native-headless evaluation. It deliberately
  18. * never calls a platform clipboard API, so parallel cases cannot leak text to
  19. * the developer machine or to one another.
  20. */
  21. export class IsolatedClipboardProvider implements ClipboardProvider {
  22. private current: ClipboardSnapshot;
  23. constructor(initial: Partial<ClipboardSnapshot> = {}) {
  24. this.current = normalizeSnapshot(initial);
  25. }
  26. async read(): Promise<ClipboardSnapshot> {
  27. return { ...this.current };
  28. }
  29. async write(snapshot: ClipboardSnapshot): Promise<void> {
  30. this.current = normalizeSnapshot(snapshot);
  31. }
  32. async snapshot(): Promise<ClipboardSnapshot> {
  33. return { ...this.current };
  34. }
  35. async restore(snapshot: ClipboardSnapshot): Promise<void> {
  36. this.current = normalizeSnapshot(snapshot);
  37. }
  38. }
  39. function normalizeSnapshot(snapshot: Partial<ClipboardSnapshot>): ClipboardSnapshot {
  40. const text = typeof snapshot.text === 'string' ? snapshot.text : '';
  41. const html = typeof snapshot.html === 'string' ? snapshot.html : undefined;
  42. return html === undefined ? { text } : { text, html };
  43. }