示例工程 63-sessions-search-and-ship

63-sessions-search-and-ship/demo-02-export-feed/ship.ts

typescript · 1.9 KB

type Feed = {
  version: string;
  files: Array<{ url: string; sha256: string; size: number }>;
};

const CURRENT = "1.0.0";

function compare(a: string, b: string): number {
  const left = a.split(".").map(Number);
  const right = b.split(".").map(Number);
  for (let index = 0; index < 3; index += 1) {
    const diff = (left[index] ?? 0) - (right[index] ?? 0);
    if (diff !== 0) return diff;
  }
  return 0;
}

function validate(feed: Feed): { decision: string; reasons: string[] } {
  const reasons: string[] = [];
  if (!/^\d+\.\d+\.\d+$/.test(feed.version)) reasons.push("BAD_VERSION");
  if (feed.files.length === 0) reasons.push("NO_FILES");
  for (const file of feed.files) {
    if (!file.url.startsWith("https://")) reasons.push("BAD_URL");
    if (!/^[a-f0-9]{64}$/i.test(file.sha256)) reasons.push("BAD_SHA256");
    if (file.size <= 0) reasons.push("BAD_SIZE");
  }
  return {
    reasons: [...new Set(reasons)],
    decision:
      reasons.length > 0
        ? "error"
        : compare(feed.version, CURRENT) > 0
          ? "update"
          : "none",
  };
}

const good: Feed = {
  version: "1.2.0",
  files: [
    {
      url: "https://updates.example.com/app-1.2.0.zip",
      sha256: "9f2c".repeat(16),
      size: 113_500_000,
    },
  ],
};

const bad: Feed = {
  version: "1.2",
  files: [
    {
      url: "http://updates.example.com/app.zip",
      sha256: "abc",
      size: 0,
    },
  ],
};

const goodResult = validate(good);
const badResult = validate(bad);
const same = validate({ ...good, version: CURRENT });

const ok =
  goodResult.decision === "update" &&
  goodResult.reasons.length === 0 &&
  badResult.decision === "error" &&
  badResult.reasons.includes("BAD_VERSION") &&
  badResult.reasons.includes("BAD_URL") &&
  badResult.reasons.includes("BAD_SHA256") &&
  badResult.reasons.includes("BAD_SIZE") &&
  same.decision === "none";

console.log(
  JSON.stringify({ evt: "smoke", ok, good: goodResult, bad: badResult, same }),
);

export {};