feat(ota): unify desktop updates with ota service

This commit is contained in:
DIYgod
2026-04-12 15:39:13 +08:00
parent af7f2e755a
commit 33c8bb98b6
42 changed files with 5657 additions and 387 deletions
+405 -3
View File
@@ -2,22 +2,26 @@
import { spawn, spawnSync } from "node:child_process"
import { createHash } from "node:crypto"
import { existsSync } from "node:fs"
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import { fileURLToPath } from "node:url"
import yaml from "js-yaml"
import { dirname, extname, join, resolve } from "pathe"
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
const REPO_ROOT = resolve(SCRIPT_DIR, "..", "..")
const DEFAULT_MOBILE_PROJECT_DIR = join(REPO_ROOT, "apps", "mobile")
const DEFAULT_DESKTOP_PROJECT_DIR = join(REPO_ROOT, "apps", "desktop")
const OTA_PLATFORMS = ["ios", "android"]
const DESKTOP_PLATFORMS = new Set(["macos", "windows", "linux"])
const CONTENT_TYPES = new Map([
[".aac", "audio/aac"],
[".bmp", "image/bmp"],
[".bundle", "application/javascript"],
[".css", "text/css"],
[".gif", "image/gif"],
[".gz", "application/gzip"],
[".hbc", "application/javascript"],
[".html", "text/html"],
[".jpeg", "image/jpeg"],
@@ -40,6 +44,7 @@ const CONTENT_TYPES = new Map([
[".woff2", "font/woff2"],
[".xml", "application/xml"],
])
const DESKTOP_MANIFEST_FILE_NAMES = new Set(["latest.yml", "latest-mac.yml", "latest-linux.yml"])
/**
* @typedef {{
@@ -227,9 +232,95 @@ export async function buildReleaseAssets(options = {}) {
}
}
export async function buildDesktopReleaseAssets(options = {}) {
const projectDir = resolveDesktopProjectDir(options.projectDir)
const distDir = join(projectDir, "dist")
const outputPath = join(distDir, "ota-release.json")
const archivePath = join(projectDir, "dist.tar.zst")
const releaseConfig = await readJson(join(projectDir, "release.json"))
const packageJson = await readJson(join(projectDir, "package.json"))
const releaseVersion = releaseConfig.version ?? packageJson.version
const product = process.env.OTA_PRODUCT ?? "desktop"
const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}`
const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT)
const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString()
const [owner, repo] = resolveRepository(options)
const releaseKind = releaseConfig.mode === "ota" ? "ota" : "binary"
const runtimeVersion = releaseConfig.mode === "ota" ? releaseConfig.runtimeVersion : null
const desktopApp =
releaseConfig.mode === "binary-policy"
? null
: await collectDesktopAppPayload({
projectDir,
owner,
repo,
gitTag,
})
if (releaseConfig.mode !== "binary-policy" && !desktopApp) {
throw new Error(
`Desktop ${releaseConfig.mode} mode requires direct installer manifests in ${join(projectDir, "out", "make")}`,
)
}
const desktopRenderer =
releaseConfig.mode === "ota"
? await collectDesktopRendererPayload({
projectDir,
owner,
repo,
gitTag,
})
: null
await mkdir(distDir, { recursive: true })
const otaMetadata = {
schemaVersion: 2,
product,
channel: releaseConfig.channel ?? null,
releaseVersion,
releaseKind,
runtimeVersion,
publishedAt,
git: {
tag: gitTag,
commit: gitCommit,
},
policy: {
required: releaseConfig.required ?? false,
minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? releaseVersion,
message: releaseConfig.message ?? null,
distributions: Object.fromEntries(
(releaseConfig.distributions ?? []).map((distribution) => [distribution, {}]),
),
},
desktop: {
renderer: desktopRenderer,
app: desktopApp,
},
}
await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8")
if (releaseConfig.mode === "ota") {
await createTarZstArchive({ distDir, archivePath })
}
return {
projectDir,
distDir,
outputPath,
archivePath: releaseConfig.mode === "ota" ? archivePath : null,
otaMetadata,
}
}
async function main() {
try {
const result = await buildReleaseAssets()
const result =
(process.env.OTA_PRODUCT ?? "mobile") === "desktop"
? await buildDesktopReleaseAssets()
: await buildReleaseAssets()
console.info(`Wrote OTA metadata: ${result.outputPath}`)
if (result.archivePath) {
@@ -362,6 +453,24 @@ function resolveMobileProjectDir(projectDir) {
return DEFAULT_MOBILE_PROJECT_DIR
}
function resolveDesktopProjectDir(projectDir) {
if (projectDir) {
return resolve(projectDir)
}
const cwd = resolve(process.cwd())
if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "release.json"))) {
return cwd
}
if (existsSync(join(cwd, "apps", "desktop", "package.json"))) {
return join(cwd, "apps", "desktop")
}
return DEFAULT_DESKTOP_PROJECT_DIR
}
function normalizeAssetPath(assetPath) {
const normalized = assetPath
.replaceAll("\\", "/")
@@ -377,7 +486,10 @@ function normalizeAssetPath(assetPath) {
}
function resolveContentType(asset) {
const pathExtension = extname(asset.path).toLowerCase()
const normalizedPath = String(asset.path).toLowerCase()
const pathExtension = normalizedPath.endsWith(".tar.gz")
? ".gz"
: extname(normalizedPath).toLowerCase()
const metadataExtension = asset.ext ? `.${asset.ext}` : ""
const extension = pathExtension || metadataExtension
@@ -480,6 +592,296 @@ async function readJson(path) {
}
}
async function collectDesktopRendererPayload(input) {
const rendererManifestPath = join(input.projectDir, "dist", "manifest.yml")
if (!existsSync(rendererManifestPath)) {
throw new Error(`Missing desktop renderer manifest at ${rendererManifestPath}`)
}
const rendererManifest = parseYamlFile(rendererManifestPath)
if (typeof rendererManifest.version !== "string" || !rendererManifest.version) {
throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing version`)
}
if (typeof rendererManifest.commit !== "string" || !rendererManifest.commit) {
throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing commit`)
}
const filename =
typeof rendererManifest.filename === "string" && rendererManifest.filename
? rendererManifest.filename
: "render-asset.tar.gz"
const rendererArchivePath = join(input.projectDir, "dist", filename)
if (!existsSync(rendererArchivePath)) {
throw new Error(`Missing desktop renderer archive at ${rendererArchivePath}`)
}
return {
version: rendererManifest.version,
commit: rendererManifest.commit,
manifest: {
name: "manifest.yml",
downloadUrl: buildGitHubAssetUrl({
owner: input.owner,
repo: input.repo,
tag: input.gitTag,
filename: "manifest.yml",
}),
},
launchAsset: await resolveFileAsset({
sourcePath: rendererArchivePath,
metadataPath: join("renderer", filename),
}),
assets: [],
}
}
async function collectDesktopAppPayload(input) {
const makeDir = join(input.projectDir, "out", "make")
if (!existsSync(makeDir)) {
return null
}
const platformEntries = await collectDesktopPlatformEntries({
makeDir,
owner: input.owner,
repo: input.repo,
gitTag: input.gitTag,
})
if (Object.keys(platformEntries).length === 0) {
return null
}
return {
platforms: platformEntries,
}
}
async function collectDesktopPlatformEntries(input) {
/** @type {Record<string, any>} */
const result = {}
for (const manifestPath of walkFiles(input.makeDir)) {
const fileName = manifestPath.split("/").at(-1)
if (!fileName || !DESKTOP_MANIFEST_FILE_NAMES.has(fileName)) {
continue
}
const manifest = parseYamlFile(manifestPath)
const platformKey = inferDesktopPlatformKey(manifestPath, fileName)
if (!platformKey || !DESKTOP_PLATFORMS.has(platformKey)) {
continue
}
const files = normalizeDesktopManifestFiles(manifest.files, manifestPath)
if (files.length === 0) {
continue
}
const nextEntry = {
platform: inferDesktopPlatformIdentifier(platformKey, manifestPath),
releaseDate: normalizeDesktopReleaseDate(manifest.releaseDate),
manifest: {
name: fileName,
path: fileName,
downloadUrl: buildGitHubAssetUrl({
owner: input.owner,
repo: input.repo,
tag: input.gitTag,
filename: fileName,
}),
},
files: files.map((file) => ({
filename: file.url,
sha512: file.sha512,
size: file.size,
downloadUrl: buildGitHubAssetUrl({
owner: input.owner,
repo: input.repo,
tag: input.gitTag,
filename: file.url,
}),
})),
}
result[platformKey] = result[platformKey]
? mergeDesktopPlatformEntries(result[platformKey], nextEntry)
: nextEntry
}
return result
}
function inferDesktopPlatformKey(manifestPath, fileName) {
const normalized = manifestPath.replaceAll("\\", "/").toLowerCase()
if (
fileName === "latest-mac.yml" ||
normalized.includes("/darwin") ||
normalized.includes("/mac")
) {
return "macos"
}
if (fileName === "latest-linux.yml" || normalized.includes("/linux")) {
return "linux"
}
if (
fileName === "latest.yml" ||
normalized.includes("/windows") ||
normalized.includes("/squirrel.windows")
) {
return "windows"
}
return null
}
function inferDesktopPlatformIdentifier(platformKey, manifestPath) {
const normalized = manifestPath.replaceAll("\\", "/").toLowerCase()
const arch = normalized.includes("/arm64") ? "arm64" : normalized.includes("/x64") ? "x64" : null
if (!arch) {
return platformKey
}
return `${platformKey}-${arch}`
}
function normalizeDesktopManifestFiles(files, manifestPath) {
if (!Array.isArray(files)) {
throw new TypeError(`Desktop manifest at ${manifestPath} is missing files`)
}
return files.map((file, index) => {
const url = typeof file?.url === "string" ? file.url : null
const sha512 = typeof file?.sha512 === "string" ? file.sha512 : null
const size =
typeof file?.size === "number" ? file.size : Number.parseInt(String(file?.size ?? 0), 10)
if (!url || !sha512 || !Number.isFinite(size) || size < 0) {
throw new Error(`Desktop manifest at ${manifestPath} has invalid files[${index}] entry`)
}
return {
url,
sha512,
size,
}
})
}
function normalizeDesktopReleaseDate(value) {
if (typeof value === "string") {
return value
}
if (value instanceof Date) {
return value.toISOString()
}
return null
}
function mergeDesktopPlatformEntries(currentEntry, nextEntry) {
const fileByName = new Map(currentEntry.files.map((file) => [file.filename, file]))
for (const file of nextEntry.files) {
fileByName.set(file.filename, file)
}
const mergedReleaseDate = pickLatestReleaseDate(currentEntry.releaseDate, nextEntry.releaseDate)
return {
platform:
currentEntry.platform === nextEntry.platform
? currentEntry.platform
: (currentEntry.platform.split("-")[0] ?? currentEntry.platform),
releaseDate: mergedReleaseDate,
manifest: currentEntry.manifest,
files: [...fileByName.values()],
}
}
function pickLatestReleaseDate(currentValue, nextValue) {
const currentTime = currentValue ? Date.parse(currentValue) : Number.NaN
const nextTime = nextValue ? Date.parse(nextValue) : Number.NaN
if (Number.isFinite(currentTime) && Number.isFinite(nextTime)) {
return currentTime >= nextTime ? currentValue : nextValue
}
return nextValue ?? currentValue ?? null
}
function parseYamlFile(path) {
try {
const content = readFileSync(path, "utf8")
return yaml.load(String(content)) ?? {}
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
throw new Error(`Failed to parse YAML at ${path}: ${reason}`)
}
}
async function resolveFileAsset(input) {
const buffer = await readFile(input.sourcePath)
return {
path: normalizeAssetPath(input.metadataPath),
sha256: createHash("sha256").update(buffer).digest("hex"),
contentType: resolveContentType({ path: input.metadataPath }),
}
}
function buildGitHubAssetUrl({ owner, repo, tag, filename }) {
return `https://github.com/${owner}/${repo}/releases/download/${tag}/${filename}`
}
function resolveRepository(options) {
if (options.owner && options.repo) {
return [options.owner, options.repo]
}
const repository = process.env.GITHUB_REPOSITORY
if (repository && repository.includes("/")) {
return repository.split("/", 2)
}
return ["RSSNext", "Folo"]
}
function walkFiles(rootDir) {
/** @type {string[]} */
const results = []
/** @type {string[]} */
const pending = [rootDir]
while (pending.length > 0) {
const current = pending.pop()
if (!current) continue
for (const entryName of readdirSync(current)) {
const entry = join(current, entryName)
if (!existsSync(entry)) continue
if (statSync(entry).isDirectory()) {
pending.push(entry)
} else {
results.push(entry)
}
}
}
return results.sort()
}
function parseBooleanEnv(name, defaultValue) {
const value = process.env[name]
+468 -16
View File
@@ -1,4 +1,4 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "pathe"
@@ -16,7 +16,12 @@ afterEach(async () => {
delete process.env.OTA_RELEASE_VERSION
delete process.env.OTA_RUNTIME_VERSION
delete process.env.OTA_CHANNEL
delete process.env.OTA_PRODUCT
delete process.env.OTA_GIT_TAG
delete process.env.OTA_GIT_COMMIT
delete process.env.OTA_PUBLISHED_AT
delete process.env.OTA_STORE_REQUIRED
delete process.env.GITHUB_REPOSITORY
})
describe("buildOtaMetadata", () => {
@@ -49,11 +54,15 @@ describe("buildOtaMetadata", () => {
},
},
},
resolveAsset: async (assetPath: string) => ({
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}),
resolveAsset: async (asset: InputAsset) => {
const assetPath = typeof asset === "string" ? asset : asset.path
return {
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}
},
})
expect(result.releaseVersion).toBe("0.4.2")
@@ -139,11 +148,15 @@ describe("buildOtaMetadata", () => {
},
},
},
resolveAsset: async (assetPath: string) => ({
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}),
resolveAsset: async (asset: InputAsset) => {
const assetPath = typeof asset === "string" ? asset : asset.path
return {
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}
},
}),
).rejects.toThrow(/android/i)
})
@@ -177,11 +190,15 @@ describe("buildOtaMetadata", () => {
},
},
},
resolveAsset: async (assetPath: string) => ({
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}),
resolveAsset: async (asset: InputAsset) => {
const assetPath = typeof asset === "string" ? asset : asset.path
return {
path: assetPath,
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
contentType: "application/octet-stream",
}
},
}),
).rejects.toThrow(/ios.*assets/i)
})
@@ -286,3 +303,438 @@ describe("buildReleaseAssets", () => {
await expect(buildReleaseAssets({ projectDir })).rejects.toThrow(metadataPath)
})
})
describe("buildDesktopReleaseAssets", () => {
it("builds schemaVersion 2 desktop build metadata with direct app payloads only", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
manifests: [
{
relativeDir: join("out", "make", "squirrel.windows", "x64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-x64.exe
sha512: ${"a".repeat(88)}
size: 123456
releaseDate: 2026-04-11T10:00:00.000Z
`,
},
],
})
const result = await buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
})
expect(result.otaMetadata.schemaVersion).toBe(2)
expect(result.otaMetadata.product).toBe("desktop")
expect(result.otaMetadata.releaseKind).toBe("binary")
expect(result.otaMetadata.runtimeVersion).toBeNull()
expect(result.otaMetadata.channel).toBeNull()
expect(result.otaMetadata.desktop.renderer).toBeNull()
expect(result.otaMetadata.desktop.app.platforms.windows).toEqual(
expect.objectContaining({
platform: "windows-x64",
releaseDate: "2026-04-11T10:00:00.000Z",
manifest: {
name: "latest.yml",
path: "latest.yml",
downloadUrl: expect.stringContaining("/desktop/v1.5.1/latest.yml"),
},
files: [
expect.objectContaining({
filename: "Folo-1.5.1-windows-x64.exe",
sha512: "a".repeat(88),
size: 123456,
downloadUrl: expect.stringContaining("/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe"),
}),
],
}),
)
expect(result.archivePath).toBeNull()
const written = JSON.parse(await readFile(result.outputPath, "utf8"))
expect(written.schemaVersion).toBe(2)
expect(written.desktop.renderer).toBeNull()
})
it("builds schemaVersion 2 desktop ota metadata with renderer and direct app payloads", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "ota",
runtimeVersion: "1.5.0",
channel: "stable",
distributions: ["direct"],
required: false,
message: null,
},
rendererArchiveContents: "renderer archive",
rendererManifestContents: `
version: 1.5.1
hash: ${"b".repeat(64)}
mainHash: ${"c".repeat(40)}
commit: abcdef1234567890
filename: custom-renderer.tar.gz
`,
manifests: [
{
relativeDir: join("out", "make", "squirrel.windows", "x64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-x64.exe
sha512: ${"d".repeat(88)}
size: 654321
releaseDate: 2026-04-11T10:00:00.000Z
`,
},
],
})
const result = await buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
})
expect(result.otaMetadata.schemaVersion).toBe(2)
expect(result.otaMetadata.releaseKind).toBe("ota")
expect(result.otaMetadata.runtimeVersion).toBe("1.5.0")
expect(result.otaMetadata.channel).toBe("stable")
expect(result.otaMetadata.desktop.renderer).toEqual(
expect.objectContaining({
version: "1.5.1",
commit: "abcdef1234567890",
manifest: {
name: "manifest.yml",
downloadUrl:
"https://github.com/RSSNext/Folo/releases/download/desktop/v1.5.1/manifest.yml",
},
launchAsset: expect.objectContaining({
path: "renderer/custom-renderer.tar.gz",
contentType: "application/gzip",
}),
}),
)
expect(result.otaMetadata.desktop.renderer.launchAsset.sha256).toHaveLength(64)
expect(result.otaMetadata.desktop.app.platforms.windows.files[0]?.downloadUrl).toContain(
"/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe",
)
expect(result.archivePath).not.toBeNull()
})
it("builds desktop binary-policy metadata without dist.tar.zst", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "binary-policy",
runtimeVersion: null,
channel: "stable",
distributions: ["mas", "mss"],
required: true,
message: "Install the latest desktop app.",
},
})
const result = await buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
})
expect(result.otaMetadata.schemaVersion).toBe(2)
expect(result.otaMetadata.releaseKind).toBe("binary")
expect(result.otaMetadata.runtimeVersion).toBeNull()
expect(result.otaMetadata.channel).toBe("stable")
expect(result.otaMetadata.policy).toEqual({
required: true,
minSupportedBinaryVersion: "1.5.1",
message: "Install the latest desktop app.",
distributions: {
mas: {},
mss: {},
},
})
expect(result.otaMetadata.desktop).toEqual({
renderer: null,
app: null,
})
expect(result.archivePath).toBeNull()
})
it("keeps desktop binary-policy metadata installer-free even if manifests exist", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "binary-policy",
runtimeVersion: null,
channel: "stable",
distributions: ["direct"],
required: false,
message: "Use the latest direct installer.",
},
manifests: [
{
relativeDir: join("out", "make", "squirrel.windows", "x64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-x64.exe
sha512: ${"1".repeat(88)}
size: 123456
releaseDate: 2026-04-11T10:00:00.000Z
`,
},
],
})
const result = await buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
})
expect(result.otaMetadata.desktop.app).toBeNull()
expect(result.archivePath).toBeNull()
})
it("fails when a desktop manifest contains an invalid file entry", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
manifests: [
{
relativeDir: join("out", "make", "squirrel.windows", "x64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-x64.exe
size: 123456
releaseDate: 2026-04-11T10:00:00.000Z
`,
},
],
})
await expect(
buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
}),
).rejects.toThrow(/invalid files\[0\] entry/i)
})
it("fails for build mode when direct installer manifests are missing", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
})
await expect(
buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
}),
).rejects.toThrow(/requires direct installer manifests/i)
})
it("fails for ota mode when direct installer manifests are missing", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "ota",
runtimeVersion: "1.5.0",
channel: "stable",
distributions: ["direct"],
required: false,
message: null,
},
rendererArchiveContents: "renderer archive",
rendererManifestContents: `
version: 1.5.1
hash: ${"2".repeat(64)}
mainHash: ${"3".repeat(40)}
commit: abcdef1234567890
filename: custom-renderer.tar.gz
`,
})
await expect(
buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
}),
).rejects.toThrow(/requires direct installer manifests/i)
})
it("merges duplicate desktop platform manifests instead of overwriting them", async () => {
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
const projectDir = await createDesktopProjectFixture({
version: "1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
manifests: [
{
relativeDir: join("out", "make", "squirrel.windows", "x64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-x64.exe
sha512: ${"e".repeat(88)}
size: 123456
releaseDate: 2026-04-11T10:00:00.000Z
`,
},
{
relativeDir: join("out", "make", "squirrel.windows", "arm64"),
manifestName: "latest.yml",
contents: `
version: 1.5.1
files:
- url: Folo-1.5.1-windows-arm64.exe
sha512: ${"f".repeat(88)}
size: 234567
releaseDate: 2026-04-11T11:00:00.000Z
`,
},
],
})
const result = await buildDesktopReleaseAssets({
projectDir,
owner: "RSSNext",
repo: "Folo",
})
expect(result.otaMetadata.desktop.app.platforms.windows.files).toHaveLength(2)
expect(result.otaMetadata.desktop.app.platforms.windows.releaseDate).toBe(
"2026-04-11T11:00:00.000Z",
)
})
})
async function createDesktopProjectFixture(input: {
version: string
releaseConfig: {
version: string
mode: "build" | "ota" | "binary-policy"
runtimeVersion: string | null
channel: "stable" | "beta" | "alpha" | null
distributions: Array<"direct" | "mas" | "mss">
required: boolean
message: string | null
}
manifests?: Array<{
relativeDir: string
manifestName: string
contents: string
}>
rendererArchiveContents?: string
rendererManifestContents?: string
}) {
const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-desktop-test-"))
tempDirs.push(projectDir)
await writeFile(
join(projectDir, "package.json"),
JSON.stringify({ name: "@follow/desktop-test", version: input.version }),
"utf8",
)
await writeFile(
join(projectDir, "release.json"),
`${JSON.stringify(input.releaseConfig, null, 2)}\n`,
"utf8",
)
if (input.rendererArchiveContents != null || input.rendererManifestContents != null) {
await mkdir(join(projectDir, "dist"), { recursive: true })
}
if (input.rendererArchiveContents != null) {
await writeFile(
join(
projectDir,
"dist",
input.rendererManifestContents?.includes("custom-renderer.tar.gz")
? "custom-renderer.tar.gz"
: "render-asset.tar.gz",
),
input.rendererArchiveContents,
"utf8",
)
}
if (input.rendererManifestContents != null) {
await writeFile(
join(projectDir, "dist", "manifest.yml"),
input.rendererManifestContents.trimStart(),
"utf8",
)
}
for (const manifest of input.manifests ?? []) {
await mkdir(join(projectDir, manifest.relativeDir), { recursive: true })
await writeFile(
join(projectDir, manifest.relativeDir, manifest.manifestName),
manifest.contents.trimStart(),
"utf8",
)
}
return projectDir
}
@@ -0,0 +1,142 @@
#!/usr/bin/env node
import { appendFileSync } from "node:fs"
import { readFile } from "node:fs/promises"
import { pathToFileURL } from "node:url"
const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/
const VALID_MODES = new Set(["build", "ota", "binary-policy"])
const VALID_CHANNELS = new Set(["stable", "beta", "alpha"])
const VALID_DISTRIBUTIONS = new Set(["direct", "mas", "mss"])
export function resolveDesktopReleaseConfig(input) {
const normalizedReleaseVersion = input.releaseVersion.replace(/^v/, "")
const config = input.releaseConfig
if (config.version !== normalizedReleaseVersion) {
throw new Error(
`apps/desktop/release.json version ${config.version} does not match release version ${normalizedReleaseVersion}.`,
)
}
if (!VALID_MODES.has(config.mode)) {
throw new Error("apps/desktop/release.json mode must be build, ota, or binary-policy.")
}
if (
!Array.isArray(config.distributions) ||
config.distributions.some((item) => !VALID_DISTRIBUTIONS.has(item))
) {
throw new Error(
"apps/desktop/release.json distributions must only contain direct, mas, or mss.",
)
}
if (config.mode === "build") {
if (config.runtimeVersion !== null || config.channel !== null) {
throw new Error("desktop build mode must not set runtimeVersion or channel")
}
return {
triggerDirectBuild: true,
triggerStoreBuilds: true,
triggerMetadataPublish: false,
releaseKind: null,
runtimeVersion: null,
channel: null,
distributions: "",
required: "",
policyMessage: "",
releaseVersion: normalizedReleaseVersion,
}
}
if (config.mode === "ota") {
if (!config.runtimeVersion || !SEMVER_PATTERN.test(config.runtimeVersion)) {
throw new Error("apps/desktop/release.json runtimeVersion must be a plain x.y.z version.")
}
if (!config.channel || !VALID_CHANNELS.has(config.channel)) {
throw new Error("apps/desktop/release.json channel must be stable, beta, or alpha.")
}
return {
triggerDirectBuild: true,
triggerStoreBuilds: true,
triggerMetadataPublish: false,
releaseKind: "ota",
runtimeVersion: config.runtimeVersion,
channel: config.channel,
distributions: config.distributions.join(","),
required: String(config.required ?? false),
policyMessage: "",
releaseVersion: normalizedReleaseVersion,
}
}
if (!config.channel || !VALID_CHANNELS.has(config.channel)) {
throw new Error("apps/desktop/release.json channel must be stable, beta, or alpha.")
}
if (config.distributions.length === 0) {
throw new Error(
"apps/desktop/release.json binary-policy mode requires at least one distribution.",
)
}
return {
triggerDirectBuild: false,
triggerStoreBuilds: false,
triggerMetadataPublish: true,
releaseKind: "binary",
runtimeVersion: null,
channel: config.channel,
distributions: config.distributions.join(","),
required: String(config.required ?? false),
policyMessage: config.message ?? "",
releaseVersion: normalizedReleaseVersion,
}
}
async function readReleaseConfig(path) {
const raw = await readFile(path, "utf8")
return JSON.parse(raw)
}
function setGitHubOutput(key, value) {
if (!process.env.GITHUB_OUTPUT) {
return
}
const delimiter = `__GITHUB_OUTPUT_${key}_${Date.now()}_${Math.random().toString(16).slice(2)}__`
appendFileSync(process.env.GITHUB_OUTPUT, `${key}<<${delimiter}\n${value}\n${delimiter}\n`)
}
async function main() {
try {
const configPath = process.env.RELEASE_CONFIG_PATH ?? "apps/desktop/release.json"
const releaseConfig = await readReleaseConfig(configPath)
const result = resolveDesktopReleaseConfig({
releaseVersion: process.env.RELEASE_VERSION ?? "",
releaseConfig,
})
setGitHubOutput("triggerDirectBuild", String(result.triggerDirectBuild))
setGitHubOutput("triggerStoreBuilds", String(result.triggerStoreBuilds))
setGitHubOutput("triggerMetadataPublish", String(result.triggerMetadataPublish))
setGitHubOutput("releaseKind", result.releaseKind ?? "")
setGitHubOutput("runtimeVersion", result.runtimeVersion ?? "")
setGitHubOutput("channel", result.channel ?? "")
setGitHubOutput("distributions", result.distributions ?? "")
setGitHubOutput("required", result.required ?? "")
setGitHubOutput("policyMessage", result.policyMessage ?? "")
setGitHubOutput("releaseVersion", result.releaseVersion)
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
await main()
}
@@ -0,0 +1,184 @@
import { execFile } from "node:child_process"
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { promisify } from "node:util"
import { join } from "pathe"
import { describe, expect, it } from "vitest"
const execFileAsync = promisify(execFile)
describe("resolveDesktopReleaseConfig", () => {
it("triggers direct and store builds for build mode", async () => {
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
expect(
resolveDesktopReleaseConfig({
releaseVersion: "v1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
}),
).toEqual({
triggerDirectBuild: true,
triggerStoreBuilds: true,
triggerMetadataPublish: false,
releaseKind: null,
runtimeVersion: null,
channel: null,
distributions: "",
required: "",
policyMessage: "",
releaseVersion: "1.5.1",
})
})
it("triggers direct and store builds for ota mode", async () => {
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
expect(
resolveDesktopReleaseConfig({
releaseVersion: "v1.5.1",
releaseConfig: {
version: "1.5.1",
mode: "ota",
runtimeVersion: "1.5.0",
channel: "stable",
distributions: ["direct"],
required: false,
message: null,
},
}),
).toEqual({
triggerDirectBuild: true,
triggerStoreBuilds: true,
triggerMetadataPublish: false,
releaseKind: "ota",
runtimeVersion: "1.5.0",
channel: "stable",
distributions: "direct",
required: "false",
policyMessage: "",
releaseVersion: "1.5.1",
})
})
it("triggers metadata publishing only for binary-policy mode", async () => {
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
expect(
resolveDesktopReleaseConfig({
releaseVersion: "v1.5.2",
releaseConfig: {
version: "1.5.2",
mode: "binary-policy",
runtimeVersion: null,
channel: "beta",
distributions: ["mas", "mss"],
required: true,
message: "Install the store binary update.",
},
}),
).toEqual({
triggerDirectBuild: false,
triggerStoreBuilds: false,
triggerMetadataPublish: true,
releaseKind: "binary",
runtimeVersion: null,
channel: "beta",
distributions: "mas,mss",
required: "true",
policyMessage: "Install the store binary update.",
releaseVersion: "1.5.2",
})
})
it("rejects a release config that does not match the release version", async () => {
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
expect(() =>
resolveDesktopReleaseConfig({
releaseVersion: "v1.5.2",
releaseConfig: {
version: "1.5.1",
mode: "build",
runtimeVersion: null,
channel: null,
distributions: [],
required: false,
message: null,
},
}),
).toThrow(/does not match release version/i)
})
it("rejects build mode when runtimeVersion or channel is set", async () => {
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
expect(() =>
resolveDesktopReleaseConfig({
releaseVersion: "v1.5.2",
releaseConfig: {
version: "1.5.2",
mode: "build",
runtimeVersion: "1.5.1",
channel: "stable",
distributions: [],
required: false,
message: null,
},
}),
).toThrow(/must not set runtimeVersion or channel/i)
})
it("writes GitHub outputs safely for multiline policy messages", async () => {
const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-output-"))
try {
const releaseConfigPath = join(projectDir, "release.json")
const githubOutputPath = join(projectDir, "github-output.txt")
await writeFile(
releaseConfigPath,
`${JSON.stringify(
{
version: "1.5.2",
mode: "binary-policy",
runtimeVersion: null,
channel: "beta",
distributions: ["mas"],
required: true,
message: "Install the new build.\nStore rollout is required.",
},
null,
2,
)}\n`,
"utf8",
)
await execFileAsync("node", [".github/scripts/resolve-desktop-release-config.mjs"], {
cwd: process.cwd(),
env: {
...process.env,
RELEASE_VERSION: "1.5.2",
RELEASE_CONFIG_PATH: releaseConfigPath,
GITHUB_OUTPUT: githubOutputPath,
},
})
const output = await readFile(githubOutputPath, "utf8")
expect(output).toContain("policyMessage<<")
expect(output).toContain("Install the new build.\nStore rollout is required.")
expect(output).not.toContain("policyMessage=Install the new build.\n")
} finally {
await rm(projectDir, { recursive: true, force: true })
}
})
})