示例工程 11-main-process-services

11-main-process-services/app/shared/ipc.ts

typescript · 2.8 KB

export const CH = {
  notesList: "notes:list",
  notesRead: "notes:read",
  notesWrite: "notes:write",
  notesRemove: "notes:remove",
  notesReset: "notes:reset",
  shellOpen: "shell:open",
  dialogPick: "dialog:pick",
} as const;

export type NoteMeta = {
  id: string;
  sizeBytes: number;
  updatedAt: number;
};

export type NoteRead = {
  id: string;
  content: string;
};

export type PickedFile = {
  path: string;
  name: string;
};

export type PublicError = {
  code: string;
  message: string;
  detail?: string;
  requestId: string;
};

export type Envelope<T> =
  { ok: true; value: T; requestId: string } | { ok: false; error: PublicError };

export class ServiceError extends Error {
  readonly code: string;
  readonly detail?: string;

  constructor(code: string, message: string, detail?: string) {
    super(message);
    this.name = "ServiceError";
    this.code = code;
    this.detail = detail;
  }
}

export function toPublicError(error: unknown, requestId: string): PublicError {
  if (error instanceof ServiceError) {
    return {
      code: error.code,
      message: error.message,
      ...(error.detail ? { detail: error.detail } : {}),
      requestId,
    };
  }
  return {
    code: "INTERNAL",
    message: "内部错误,请稍后重试",
    requestId,
  };
}

export function parseNoteIdReq(value: unknown): { id: string } {
  if (typeof value !== "object" || value === null) {
    throw new ServiceError("BAD_SHAPE", "请求必须是对象");
  }
  const id = (value as { id?: unknown }).id;
  if (typeof id !== "string" || !/^[a-z0-9][a-z0-9-]{0,31}$/.test(id)) {
    throw new ServiceError(
      "BAD_ID",
      "id 只能是小写字母、数字与短横线,长度 1–32",
      "id",
    );
  }
  return { id };
}

export function parseWriteReq(value: unknown): {
  id: string;
  content: string;
} {
  if (typeof value !== "object" || value === null) {
    throw new ServiceError("BAD_SHAPE", "请求必须是对象");
  }
  const record = value as Record<string, unknown>;
  const { id } = parseNoteIdReq({ id: record.id });
  if (typeof record.content !== "string") {
    throw new ServiceError("BAD_CONTENT", "content 必须是字符串", "content");
  }
  if (record.content.length > 4000) {
    throw new ServiceError(
      "CONTENT_TOO_LONG",
      "content 不能超过 4000 字符",
      "content",
    );
  }
  return { id, content: record.content };
}

export function parseShellOpenReq(value: unknown): { url: string } {
  if (typeof value !== "object" || value === null) {
    throw new ServiceError("BAD_SHAPE", "请求必须是对象");
  }
  const url = (value as { url?: unknown }).url;
  if (typeof url !== "string" || url.length === 0 || url.length > 300) {
    throw new ServiceError("BAD_URL", "url 必须是 1–300 字符的字符串", "url");
  }
  return { url };
}