示例工程 09-typed-ipc-contracts

09-typed-ipc-contracts/app/shared/ipc.ts

typescript · 4.1 KB

/**
 * 三端唯一来源:通道名、请求/响应类型、手写校验器。
 * 本文件不 import electron,渲染进程也能安全引用。
 */
export const CH = {
  create: "notes:create",
  list: "notes:list",
  cases: "contract:cases",
  reset: "notes:reset",
} as const;

export type Note = {
  id: number;
  title: string;
  body: string;
  tags: string[];
  createdAt: number;
};

export type CreateNoteReq = {
  title: string;
  body: string;
  tags?: string[];
};

export type ListNotesReq = { limit: number };

export type ListNotesRes = { items: Note[]; total: number };

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 type CaseResult = {
  name: string;
  ok: boolean;
  expected: string;
  actual: string;
};

export type CaseReport = {
  total: number;
  passed: number;
  failed: number;
  cases: CaseResult[];
};

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

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

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function assertOnlyKeys(
  value: Record<string, unknown>,
  allowed: string[],
): void {
  for (const key of Object.keys(value)) {
    if (!allowed.includes(key)) {
      throw new ContractError("UNKNOWN_FIELD", `不支持的字段:${key}`, key);
    }
  }
}

export function parseCreateNoteReq(value: unknown): CreateNoteReq {
  if (!isRecord(value)) {
    throw new ContractError("BAD_SHAPE", "请求必须是对象");
  }
  assertOnlyKeys(value, ["title", "body", "tags"]);
  const title = value.title;
  if (typeof title !== "string" || title.trim().length === 0) {
    throw new ContractError("TITLE_EMPTY", "title 不能为空", "title");
  }
  if (title.length > 80) {
    throw new ContractError(
      "TITLE_TOO_LONG",
      "title 不能超过 80 字符",
      "title",
    );
  }
  if (typeof value.body !== "string") {
    throw new ContractError("BODY_INVALID", "body 必须是字符串", "body");
  }
  if (value.body.length > 2000) {
    throw new ContractError("BODY_TOO_LONG", "body 不能超过 2000 字符", "body");
  }
  let tags: string[] | undefined;
  if (value.tags !== undefined) {
    if (!Array.isArray(value.tags)) {
      throw new ContractError("TAGS_INVALID", "tags 必须是数组", "tags");
    }
    if (value.tags.length > 5) {
      throw new ContractError("TOO_MANY_TAGS", "tags 最多 5 个", "tags");
    }
    tags = value.tags.map((tag) => {
      if (typeof tag !== "string" || tag.trim().length === 0) {
        throw new ContractError("TAG_EMPTY", "tag 不能为空", "tags");
      }
      if (tag.length > 16) {
        throw new ContractError("TAG_TOO_LONG", "tag 不能超过 16 字符", "tags");
      }
      return tag.trim();
    });
  }
  return { title: title.trim(), body: value.body, ...(tags ? { tags } : {}) };
}

export function parseListNotesReq(value: unknown): ListNotesReq {
  if (!isRecord(value)) {
    throw new ContractError("BAD_SHAPE", "请求必须是对象");
  }
  assertOnlyKeys(value, ["limit"]);
  const limit = value.limit;
  if (
    typeof limit !== "number" ||
    !Number.isInteger(limit) ||
    limit < 1 ||
    limit > 50
  ) {
    throw new ContractError(
      "LIMIT_INVALID",
      "limit 必须是 1–50 的整数",
      "limit",
    );
  }
  return { limit };
}

export function toPublicError(error: unknown, requestId: string): PublicError {
  if (error instanceof ContractError) {
    return {
      code: error.code,
      message: error.message,
      ...(error.detail ? { detail: error.detail } : {}),
      requestId,
    };
  }
  // 非契约错误一律脱敏:不把堆栈、路径或第三方错误文本发给页面。
  return {
    code: "INTERNAL",
    message: "内部错误,请稍后重试",
    requestId,
  };
}