Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
refactor(ci): use shared discord-bot-api helper for release announce
EtienneLescot36a0807e53eb
diff --git a/.github/scripts/discord-bot-api.mjs b/.github/scripts/discord-bot-api.mjsnew file mode 100644index 000000000..5de9f8a97--- /dev/null+++ b/.github/scripts/discord-bot-api.mjs@@ -0,0 +1,40 @@+import { warning } from "@actions/core";++const API_BASE = "https://discord.com/api/v10";++async function callDiscord(botToken, method, path, body) {+ const res = await fetch(`${API_BASE}${path}`, {+ method,+ headers: {+ Authorization: `Bot ${botToken}`,+ "Content-Type": "application/json",+ },+ body: body !== undefined ? JSON.stringify(body) : undefined,+ });++ if (res.status === 429) {+ const txt = await res.text();+ warning(`Discord rate-limited (429) on ${method} ${path}: ${txt}`);+ throw new Error(`Discord rate-limited (429) on ${method} ${path}`);+ }++ if (!res.ok) {+ const txt = await res.text();+ throw new Error(`Discord API ${method} ${path} failed ${res.status}: ${txt}`);+ }++ if (res.status === 204) return null;+ return res.json();+}++export async function createForumThread({ botToken, forumChannelId, payload }) {+ return callDiscord(botToken, "POST", `/channels/${forumChannelId}/threads`, payload);+}++export async function postChannelMessage({ botToken, channelId, payload }) {+ return callDiscord(botToken, "POST", `/channels/${channelId}/messages`, payload);+}++export async function patchChannel({ botToken, channelId, payload }) {+ return callDiscord(botToken, "PATCH", `/channels/${channelId}`, payload);+}diff --git a/.github/scripts/discord-bot-api.test.mjs b/.github/scripts/discord-bot-api.test.mjsnew file mode 100644index 000000000..f96bd569e--- /dev/null+++ b/.github/scripts/discord-bot-api.test.mjs@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createForumThread, patchChannel, postChannelMessage } from "./discord-bot-api.mjs";++const botToken = "test-token";++beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+});++afterEach(() => {+ vi.unstubAllGlobals();+});++function mockResponse({ status = 200, body = { id: "x" } } = {}) {+ vi.mocked(fetch).mockResolvedValue({+ ok: status >= 200 && status < 300,+ status,+ text: vi.fn().mockResolvedValue(JSON.stringify(body)),+ json: vi.fn().mockResolvedValue(body),+ });+}++const happyCases = [+ {+ name: "createForumThread",+ call: (args) => createForumThread(args),+ args: { forumChannelId: "forum-1", payload: { name: "PR #1" } },+ expectUrl: "https://discord.com/api/v10/channels/forum-1/threads",+ expectMethod: "POST",+ expectBody: { name: "PR #1" },+ },+ {+ name: "postChannelMessage",+ call: (args) => postChannelMessage(args),+ args: { channelId: "thread-1", payload: { content: "hello" } },+ expectUrl: "https://discord.com/api/v10/channels/thread-1/messages",+ expectMethod: "POST",+ expectBody: { content: "hello" },+ },+ {+ name: "patchChannel",+ call: (args) => patchChannel(args),+ args: { channelId: "thread-1", payload: { archived: true } },+ expectUrl: "https://discord.com/api/v10/channels/thread-1",+ expectMethod: "PATCH",+ expectBody: { archived: true },+ },+];++describe.each(happyCases)("$name", ({ call, args, expectUrl, expectMethod, expectBody }) => {+ it("calls Discord with the right URL, method, bot auth, and payload", async () => {+ mockResponse();++ await call({ ...args, botToken });++ const [url, init] = vi.mocked(fetch).mock.calls[0];+ expect(url).toBe(expectUrl);+ expect(init.method).toBe(expectMethod);+ expect(init.headers.Authorization).toBe(`Bot ${botToken}`);+ expect(JSON.parse(init.body)).toEqual(expectBody);+ });++ it("throws on 429 with rate-limit message", async () => {+ mockResponse({ status: 429, body: { retry_after: 1 } });+ await expect(call({ ...args, botToken })).rejects.toThrow(/rate-limited \(429\)/);+ });++ it("throws on non-ok responses with status in message", async () => {+ mockResponse({ status: 403, body: { message: "Missing Permissions" } });+ await expect(call({ ...args, botToken })).rejects.toThrow(/failed 403/);+ });+});diff --git a/.github/scripts/discord-release-announce.mjs b/.github/scripts/discord-release-announce.mjsindex 64321e67c..c4bdc5813 100644--- a/.github/scripts/discord-release-announce.mjs+++ b/.github/scripts/discord-release-announce.mjs@@ -1,5 +1,6 @@import { info, warning } from "@actions/core";import { context, getOctokit } from "@actions/github";+import { createForumThread, postChannelMessage } from "./discord-bot-api.mjs";const botToken = (process.env.DISCORD_BOT_TOKEN || "").trim();const channelId = (@@ -61,7 +62,7 @@ const isRc = kind === "rc";const embedTitle = isRc? `🧪 ${stableTag} release candidate ready for testing`: `🚀 ${stableTag} released`;-const threadName = isRc ? `${stableTag} RC — testing` : `${stableTag} released`;+const threadName = (isRc ? `${stableTag} RC — testing` : `${stableTag} released`).slice(0, 100);const color = isRc ? 15844367 : 5814783;const description = [@@ -73,6 +74,17 @@ const description = [.filter(Boolean).join("\n");+const embed = {+ title: embedTitle,+ url: releaseUrl,+ description,+ color,+ timestamp: new Date().toISOString(),+};++// Discord channel types that require a thread wrapper (no top-level messages).+const FORUM_LIKE_TYPES = new Set([15, 16]); // 15 = GUILD_FORUM, 16 = GUILD_MEDIA+async function fetchChannelType() {const res = await fetch(`https://discord.com/api/v10/channels/${channelId}`, {headers: { Authorization: `Bot ${botToken}` },@@ -85,75 +97,45 @@ async function fetchChannelType() {return res.json();}-async function postToForum() {- // Forum channel (type 15): create a thread, the first message is the announcement.- const body = {- name: threadName.slice(0, 100),- message: {- embeds: [- {- title: embedTitle,- url: releaseUrl,- description,- color,- timestamp: new Date().toISOString(),- },- ],- allowed_mentions: { parse: [] },+async function announceToForum() {+ const thread = await createForumThread({+ botToken,+ forumChannelId: channelId,+ payload: {+ name: threadName,+ auto_archive_duration: 4320,+ message: {+ embeds: [embed],+ allowed_mentions: { parse: [] },+ },},- };- const res = await fetch(`https://discord.com/api/v10/channels/${channelId}/threads`, {- method: "POST",- headers: { Authorization: `Bot ${botToken}`, "Content-Type": "application/json" },- body: JSON.stringify(body),});- if (!res.ok) {- const txt = await res.text();- warning(`Discord forum thread create failed ${res.status}: ${txt}`);- return false;- }- const data = await res.json();- info(`📣 ${kind} announcement posted to forum thread ${data.id}.`);- return true;+ info(`📣 ${kind} announcement posted to forum thread ${thread.id}.`);}-async function postToText() {- const body = {- embeds: [- {- title: embedTitle,- url: releaseUrl,- description,- color,- timestamp: new Date().toISOString(),- },- ],- allowed_mentions: { parse: [] },- };- const res = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {- method: "POST",- headers: { Authorization: `Bot ${botToken}`, "Content-Type": "application/json" },- body: JSON.stringify(body),+async function announceToText() {+ const result = await postChannelMessage({+ botToken,+ channelId,+ payload: {+ embeds: [embed],+ allowed_mentions: { parse: [] },+ },});- if (!res.ok) {- const txt = await res.text();- warning(`Discord message POST failed ${res.status}: ${txt}`);- return false;- }- info(`📣 ${kind} announcement posted to text channel.`);- return true;+ info(`📣 ${kind} announcement posted to text channel (id=${result.id}).`);}-// Discord channel types that require a thread wrapper (no top-level messages).-const FORUM_LIKE_TYPES = new Set([15, 16]); // 15 = GUILD_FORUM, 16 = GUILD_MEDIA-const channel = await fetchChannelType();if (!channel) {process.exit(0);}-if (FORUM_LIKE_TYPES.has(channel.type)) {- await postToForum();-} else {- await postToText();+try {+ if (FORUM_LIKE_TYPES.has(channel.type)) {+ await announceToForum();+ } else {+ await announceToText();+ }+} catch (err) {+ warning(`Discord announce failed: ${err?.message ?? err}`);}diff --git a/.github/scripts/discord-release-announce.test.mjs b/.github/scripts/discord-release-announce.test.mjsnew file mode 100644index 000000000..a5f23ddfb--- /dev/null+++ b/.github/scripts/discord-release-announce.test.mjs@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockCreateForumThread = vi.fn();+const mockPostChannelMessage = vi.fn();+const mockListMilestones = vi.fn();+const mockListForRepo = vi.fn();++vi.mock("@actions/core", () => ({+ info: vi.fn(),+ warning: vi.fn(),+}));+vi.mock("@actions/github", () => ({+ context: {+ repo: { owner: "acme", repo: "widget" },+ serverUrl: "https://github.com",+ },+ getOctokit: () => ({+ paginate: async (fn, opts) => {+ if (fn === mockListMilestones) return mockListMilestones(opts);+ if (fn === mockListForRepo) return mockListForRepo(opts);+ return [];+ },+ rest: {+ issues: {+ listMilestones: mockListMilestones,+ listForRepo: mockListForRepo,+ },+ },+ }),+}));+vi.mock("./discord-bot-api.mjs", () => ({+ createForumThread: mockCreateForumThread,+ postChannelMessage: mockPostChannelMessage,+}));++async function loadScript(env) {+ vi.resetModules();+ vi.spyOn(process, "exit").mockImplementation((code) => {+ throw new Error(`process.exit unexpectedly called with "${code}"`);+ });+ for (const [k, v] of Object.entries(env)) {+ process.env[k] = v;+ }+ return import("./discord-release-announce.mjs");+}++const BASE_ENV = {+ DISCORD_BOT_TOKEN: "test-token",+ GITHUB_TOKEN: "test-github",+ STABLE_TAG: "v1.5.0",+};++beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+ mockCreateForumThread.mockReset();+ mockPostChannelMessage.mockReset();+ mockListMilestones.mockReset();+ mockListForRepo.mockReset();+ mockListMilestones.mockResolvedValue([]);+ mockListForRepo.mockResolvedValue([]);+ for (const k of Object.keys(process.env)) {+ if (+ k.startsWith("DISCORD_") ||+ k === "GITHUB_TOKEN" ||+ k === "STABLE_TAG" ||+ k === "RC_TAG" ||+ k === "KIND" ||+ k === "EXTRA"+ ) {+ delete process.env[k];+ }+ }+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("discord-release-announce", () => {+ it("skips when STABLE_TAG is missing", async () => {+ await expect(+ loadScript({ DISCORD_BOT_TOKEN: "t", DISCORD_RC_TESTING_CHANNEL_ID: "c" }),+ ).rejects.toThrow(/process\.exit.*"0"/);+ expect(mockCreateForumThread).not.toHaveBeenCalled();+ expect(mockPostChannelMessage).not.toHaveBeenCalled();+ });++ it("skips when bot token or channel id is missing", async () => {+ await expect(loadScript({ STABLE_TAG: "v1.0.0" })).rejects.toThrow(/process\.exit.*"0"/);+ expect(mockCreateForumThread).not.toHaveBeenCalled();+ expect(mockPostChannelMessage).not.toHaveBeenCalled();+ });++ it("posts a forum thread when the channel is a forum (type 15)", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ type: 15, name: "rc-testing" }),+ });+ mockCreateForumThread.mockResolvedValue({ id: "thread-1" });++ await loadScript({+ ...BASE_ENV,+ DISCORD_RC_TESTING_CHANNEL_ID: "1521416826146263051",+ KIND: "rc",+ RC_TAG: "v1.4.5-rc.3",+ });++ expect(mockCreateForumThread).toHaveBeenCalledTimes(1);+ const args = mockCreateForumThread.mock.calls[0][0];+ expect(args.botToken).toBe("test-token");+ expect(args.forumChannelId).toBe("1521416826146263051");+ expect(args.payload.name).toBe("v1.5.0 RC — testing".slice(0, 100));+ expect(args.payload.message.embeds[0].title).toContain("release candidate");+ expect(args.payload.message.embeds[0].description).toContain(+ "https://github.com/acme/widget/releases/tag/v1.5.0",+ );+ expect(args.payload.message.embeds[0].description).toContain("Promoted from `v1.4.5-rc.3`");+ expect(mockPostChannelMessage).not.toHaveBeenCalled();+ });++ it("posts a media thread when the channel is media (type 16)", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ type: 16 }),+ });+ mockCreateForumThread.mockResolvedValue({ id: "thread-2" });++ await loadScript({ ...BASE_ENV, DISCORD_RELEASE_CHANNEL_ID: "1493594372409917512" });++ expect(mockCreateForumThread).toHaveBeenCalledTimes(1);+ expect(mockPostChannelMessage).not.toHaveBeenCalled();+ });++ it("posts a regular message when the channel is text (type 0)", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ type: 0 }),+ });+ mockPostChannelMessage.mockResolvedValue({ id: "msg-1" });++ await loadScript({ ...BASE_ENV, DISCORD_RELEASE_CHANNEL_ID: "123" });++ expect(mockPostChannelMessage).toHaveBeenCalledTimes(1);+ const args = mockPostChannelMessage.mock.calls[0][0];+ expect(args.channelId).toBe("123");+ expect(args.payload.embeds[0].title).toContain("released");+ expect(mockCreateForumThread).not.toHaveBeenCalled();+ });++ it("includes closed issues from the versioned milestone", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ type: 0 }),+ });+ mockPostChannelMessage.mockResolvedValue({ id: "msg-2" });+ mockListMilestones.mockResolvedValue([{ number: 7, title: "v1.5.0" }]);+ mockListForRepo.mockResolvedValue([+ { number: 42, title: "fix bug", html_url: "https://x/42", pull_request: null },+ { number: 43, title: "add feature", html_url: "https://x/43", pull_request: { url: "x" } },+ ]);++ await loadScript({ ...BASE_ENV, DISCORD_RELEASE_CHANNEL_ID: "123" });++ const args = mockPostChannelMessage.mock.calls[0][0];+ const desc = args.payload.embeds[0].description;+ expect(desc).toContain("Closed issues in this release");+ expect(desc).toContain("#42");+ expect(desc).toContain("fix bug");+ expect(desc).not.toContain("add feature");+ });++ it("handles 4xx gracefully without throwing", async () => {+ vi.mocked(fetch).mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ type: 0 }),+ });+ mockPostChannelMessage.mockRejectedValue(new Error("failed 403: Missing Permissions"));++ await loadScript({ ...BASE_ENV, DISCORD_RELEASE_CHANNEL_ID: "123" });+ expect(mockPostChannelMessage).toHaveBeenCalledTimes(1);+ });+});