示例工程 33-clipboard-dnd-fs

33-clipboard-dnd-fs/app/shared/ipc.ts

typescript · 2.0 KB

export const CH = {
  get: "clipboard:get",
  readClipboard: "clipboard:read",
  writeText: "clipboard:write-text",
  writeHtml: "clipboard:write-html",
  readPath: "fs:read-path",
  pickFile: "fs:pick",
  refreshRecent: "fs:refresh-recent",
  clearRecent: "fs:clear-recent",
} as const;

export type ClipboardInfo = {
  formats: string[];
  text: string;
  html: string;
  error: string;
};

export type RecentEntry = {
  path: string;
  name: string;
  ext: string;
  size: number;
  exists: boolean;
  at: number;
  error: string;
};

export type FilePreview = {
  ok: boolean;
  path: string;
  name: string;
  ext: string;
  size: number;
  content: string;
  error: string;
};

export type Samples = {
  notes: string;
  config: string;
  big: string;
  wrong: string;
  missing: string;
};

export type Snapshot = {
  platform: string;
  clipboard: ClipboardInfo;
  lastFile: FilePreview | null;
  recent: RecentEntry[];
  samples: Samples;
};

export function assertTextReq(
  value: unknown,
): asserts value is { text: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_TEXT_REQ");
  }
  const text = (value as { text?: unknown }).text;
  if (typeof text !== "string" || text.length > 100_000) {
    throw new Error("BAD_TEXT_REQ");
  }
}

export function assertHtmlReq(
  value: unknown,
): asserts value is { html: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_HTML_REQ");
  }
  const html = (value as { html?: unknown }).html;
  if (typeof html !== "string" || html.length > 100_000) {
    throw new Error("BAD_HTML_REQ");
  }
}

export function assertPathReq(
  value: unknown,
): asserts value is { path: string } {
  if (typeof value !== "object" || value === null) {
    throw new Error("BAD_PATH_REQ");
  }
  const path = (value as { path?: unknown }).path;
  if (
    typeof path !== "string" ||
    path.length === 0 ||
    path.length > 4096 ||
    path.includes("\0")
  ) {
    throw new Error("BAD_PATH_REQ");
  }
}