diff --git a/packages/cli/src/commands/wordpress-source.ts b/packages/cli/src/commands/wordpress-source.ts index 86c9eff5..e7467e51 100644 --- a/packages/cli/src/commands/wordpress-source.ts +++ b/packages/cli/src/commands/wordpress-source.ts @@ -1,4 +1,4 @@ -import { materializePlaygroundWordPressSource, type PlaygroundWordPressSource, type PlaygroundWordPressSourceOptions } from "@automattic/wp-codebox-playground" +import { materializePlaygroundWordPressSource, WORDPRESS_SOURCE_SCHEMA, type PlaygroundWordPressSource, type PlaygroundWordPressSourceOptions } from "@automattic/wp-codebox-playground" interface WordPressSourceCommandOptions { wp?: string @@ -12,7 +12,11 @@ type WordPressSourceMaterializer = (versionQuery: string | undefined, options: P * * Prints the host path of WordPress core source extracted from the validated * Playground archive cache. stdout carries only the result (root path, or one - * JSON object with --json); diagnostics and failures go to stderr. + * JSON object with --json); diagnostics go to stderr. Failures always print a + * one-line reason on stderr; with --json, stdout additionally carries one + * `{ schema, error: { code, message, ... } }` object so callers can branch on + * a stable code instead of parsing prose. Exit codes: 0 success, 1 the source + * could not be materialized, 2 invalid arguments. */ export async function runWordPressSourceCommand(args: string[], materialize: WordPressSourceMaterializer = materializePlaygroundWordPressSource): Promise { let options: WordPressSourceCommandOptions @@ -20,6 +24,9 @@ export async function runWordPressSourceCommand(args: string[], materialize: Wor options = parseWordPressSourceOptions(args) } catch (error) { process.stderr.write(`wp-codebox wordpress-source: ${errorMessage(error)}\n`) + if (args.includes("--json")) { + writeJsonError({ code: "wordpress-source-invalid-arguments", message: errorMessage(error) }) + } return 2 } @@ -27,7 +34,11 @@ export async function runWordPressSourceCommand(args: string[], materialize: Wor try { source = await materialize(options.wp, { log: (message) => process.stderr.write(`[wp-codebox] ${message}\n`) }) } catch (error) { - process.stderr.write(`wp-codebox wordpress-source: failed to materialize WordPress ${options.wp ?? "latest"} source: ${errorMessage(error)}\n`) + const message = `failed to materialize WordPress ${options.wp ?? "latest"} source: ${errorMessage(error)}` + process.stderr.write(`wp-codebox wordpress-source: ${message}\n`) + if (options.json) { + writeJsonError({ ...wordPressSourceErrorDetails(error), message, requestedVersion: options.wp ?? "latest" }) + } return 1 } @@ -59,6 +70,36 @@ function parseWordPressSourceOptions(args: string[]): WordPressSourceCommandOpti return options } +export type WordPressSourceErrorCode = + | "wordpress-source-invalid-arguments" + | "wordpress-source-invalid-version" + | "wordpress-source-release-unresolved" + | "wordpress-source-download-failed" + | "wordpress-source-cache-locked" + | "wordpress-source-materialization-failed" + +interface WordPressSourceError { + code: WordPressSourceErrorCode + message: string + requestedVersion?: string + sourceUrl?: string +} + +function writeJsonError(error: WordPressSourceError): void { + process.stdout.write(`${JSON.stringify({ schema: WORDPRESS_SOURCE_SCHEMA, error })}\n`) +} + +/** Maps a materializer failure to a stable error code (and the asset URL when known). */ +function wordPressSourceErrorDetails(error: unknown): { code: WordPressSourceErrorCode; sourceUrl?: string } { + const asset = error && typeof error === "object" && "asset" in error && typeof error.asset === "string" ? error.asset : undefined + const sourceUrl = error && typeof error === "object" && "sourceUrl" in error && typeof error.sourceUrl === "string" ? error.sourceUrl : undefined + if (asset === "wordpress-archive-cache") return { code: "wordpress-source-download-failed", sourceUrl } + if (asset === "wordpress-release-metadata") return { code: "wordpress-source-release-unresolved", sourceUrl } + if (asset === "wordpress-archive-cache-lock") return { code: "wordpress-source-cache-locked" } + if (/requires a WordPress release version/.test(errorMessage(error))) return { code: "wordpress-source-invalid-version" } + return { code: "wordpress-source-materialization-failed" } +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error) } diff --git a/packages/runtime-playground/src/playground-cli-runner.ts b/packages/runtime-playground/src/playground-cli-runner.ts index e3380d43..495299ef 100644 --- a/packages/runtime-playground/src/playground-cli-runner.ts +++ b/packages/runtime-playground/src/playground-cli-runner.ts @@ -841,11 +841,11 @@ export async function resolvePlaygroundWordPressStartupAsset(versionQuery: strin } } - await downloadWordPressArchiveToCache(release.releaseUrl, cachedArchivePath) - const downloadedValidation = await validateWordPressArchivePaths(release.version, release.releaseUrl, [cachedArchivePath], { deleteInvalid: false }) + const downloadedFrom = await downloadWordPressArchiveToCache(wordPressArchiveDownloadUrls(release.version, release.releaseUrl), cachedArchivePath) + const downloadedValidation = await validateWordPressArchivePaths(release.version, downloadedFrom, [cachedArchivePath], { deleteInvalid: false }) const invalidDownloadedArchive = downloadedValidation.invalidArchives[0] if (invalidDownloadedArchive) { - throw new PlaygroundStartupAssetError("wordpress-archive-cache", release.releaseUrl, versionQuery ?? "latest", new Error(`Downloaded WordPress archive is invalid: ${invalidDownloadedArchive.reason}`)) + throw new PlaygroundStartupAssetError("wordpress-archive-cache", downloadedFrom, versionQuery ?? "latest", new Error(`Downloaded WordPress archive is invalid: ${invalidDownloadedArchive.reason}`)) } const archiveReference = isCustomPlaygroundWordPressArchive(cachedArchivePath) ? await acquirePlaygroundArchiveReference(cachedArchivePath) : undefined @@ -863,7 +863,38 @@ export async function resolvePlaygroundWordPressStartupAsset(versionQuery: strin }, (lockPath) => new PlaygroundStartupAssetError("wordpress-archive-cache-lock", lockPath, release.version, new Error("Timed out waiting for WordPress archive cache lock"))) } -async function downloadWordPressArchiveToCache(sourceUrl: string, archivePath: string): Promise { +/** + * Ordered download candidates for a WordPress release archive: the URL the + * release API (or inference) returned first, then the equivalent official + * mirrors. The release API currently answers with a `downloads.w.org` URL, + * which is unreachable from some networks that can still reach + * `downloads.wordpress.org` and `wordpress.org`; without mirrors a single + * unreachable host made every cache miss fatal. + */ +export function wordPressArchiveDownloadUrls(version: string, releaseUrl: string): string[] { + const urls = [releaseUrl] + if (/^\d+\.\d+(?:\.\d+)?(?:-(?:alpha|beta|RC)\d*)?$/i.test(version)) { + urls.push(`https://downloads.wordpress.org/release/wordpress-${version}.zip`, `https://wordpress.org/wordpress-${version}.zip`) + } + return [...new Set(urls)] +} + +/** Downloads the first candidate that yields a valid archive and returns its URL. */ +async function downloadWordPressArchiveToCache(sourceUrls: string[], archivePath: string): Promise { + const failures: string[] = [] + for (const sourceUrl of sourceUrls) { + try { + await downloadWordPressArchiveFrom(sourceUrl, archivePath) + return sourceUrl + } catch (error) { + failures.push(`${sourceUrl}: ${fetchErrorMessage(error)}`) + } + } + const summary = failures.length === 1 ? failures[0].slice(sourceUrls[0].length + 2) : `all ${failures.length} download sources failed (${failures.join("; ")})` + throw new PlaygroundStartupAssetError("wordpress-archive-cache", sourceUrls[0], basename(archivePath, ".zip"), new Error(summary)) +} + +async function downloadWordPressArchiveFrom(sourceUrl: string, archivePath: string): Promise { const tempPath = `${archivePath}.${process.pid}.${Date.now()}.partial` try { const response = await fetch(sourceUrl) @@ -879,8 +910,21 @@ async function downloadWordPressArchiveToCache(sourceUrl: string, archivePath: s await rename(tempPath, archivePath) } catch (error) { await rm(tempPath, { force: true }) - throw new PlaygroundStartupAssetError("wordpress-archive-cache", sourceUrl, basename(archivePath, ".zip"), error) + throw error + } +} + +/** undici reports network failures as a bare "fetch failed"; surface the underlying cause (e.g. EHOSTUNREACH). */ +function fetchErrorMessage(error: unknown): string { + const message = error instanceof Error ? error.message : String(error) + const cause = error instanceof Error ? error.cause : undefined + if (!cause || typeof cause !== "object") { + return message } + const code = "code" in cause && typeof cause.code === "string" ? cause.code : undefined + const causeMessage = "message" in cause && typeof cause.message === "string" ? cause.message : undefined + const detail = code && causeMessage && !causeMessage.includes(code) ? `${code}: ${causeMessage}` : causeMessage ?? code + return detail ? `${message} (${detail})` : message } export async function resolveWordPressReleaseForStartup(versionQuery: string | undefined, cacheDirectory = playgroundWordPressArchiveCacheDirectory(), resolver: WordPressReleaseResolver = resolveWordPressRelease): Promise { diff --git a/tests/wordpress-source.test.ts b/tests/wordpress-source.test.ts index 83a7e909..8e002c5f 100644 --- a/tests/wordpress-source.test.ts +++ b/tests/wordpress-source.test.ts @@ -7,6 +7,7 @@ import { collectBytes, encodeZip } from "@php-wasm/stream-compression" import { runWordPressSourceCommand } from "../packages/cli/src/commands/wordpress-source.js" import { materializePlaygroundWordPressSource, verifiedWordPressRootError, WORDPRESS_SOURCE_SCHEMA } from "../packages/runtime-playground/src/playground-wordpress-source.js" +import { wordPressArchiveDownloadUrls } from "../packages/runtime-playground/src/playground-cli-runner.js" const TAG_PROCESSOR = "wp-includes/html-api/class-wp-html-tag-processor.php" @@ -138,6 +139,63 @@ try { assert.equal(existsSync(join(cacheDirectory, "9.9.10.zip")), false) assert.equal(existsSync(join(cacheDirectory, "source", "9.9.10")), false) + // Mirror fallback: an unreachable release host falls through to the official + // mirrors instead of failing the cache miss. (The release API answers + // "latest" with a downloads.w.org URL, which some networks cannot reach.) + assert.deepEqual(wordPressArchiveDownloadUrls("9.9.12", "https://downloads.w.org/release/wordpress-9.9.12.zip"), [ + "https://downloads.w.org/release/wordpress-9.9.12.zip", + "https://downloads.wordpress.org/release/wordpress-9.9.12.zip", + "https://wordpress.org/wordpress-9.9.12.zip", + ]) + assert.deepEqual(wordPressArchiveDownloadUrls("9.9.12-RC1", "https://wordpress.org/wordpress-9.9.12-RC1.zip"), [ + "https://wordpress.org/wordpress-9.9.12-RC1.zip", + "https://downloads.wordpress.org/release/wordpress-9.9.12-RC1.zip", + ]) + assert.deepEqual(wordPressArchiveDownloadUrls("custom-1234abcd", "https://example.test/custom.zip"), ["https://example.test/custom.zip"]) + + const mirrorArchive = await wordpressZip("9.9.12") + const mirrorRequests: string[] = [] + const unreachable = () => new TypeError("fetch failed", { cause: Object.assign(new Error("connect EHOSTUNREACH 192.0.2.1:443"), { code: "EHOSTUNREACH" }) }) + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input) + mirrorRequests.push(url) + if (url.startsWith("https://wordpress.org/")) { + throw unreachable() + } + return new Response(mirrorArchive, { status: 200 }) + }) as typeof fetch + const mirrored = await materializePlaygroundWordPressSource("9.9.12", { cacheDirectory }) + assert.deepEqual(mirrorRequests, [ + "https://wordpress.org/wordpress-9.9.12.zip", + "https://downloads.wordpress.org/release/wordpress-9.9.12.zip", + ]) + assert.equal(mirrored.version, "9.9.12") + assert.equal(mirrored.sourceUrl, "https://downloads.wordpress.org/release/wordpress-9.9.12.zip") + assert.equal(mirrored.archive, join(cacheDirectory, "9.9.12.zip")) + assert.equal(await verifiedWordPressRootError(mirrored.root, "9.9.12"), undefined) + + // Every source unreachable: one error naming each URL and the network cause. + globalThis.fetch = (async () => { throw unreachable() }) as typeof fetch + await assert.rejects(() => materializePlaygroundWordPressSource("9.9.13", { cacheDirectory }), (error: Error) => { + assert.match(error.message, /all 2 download sources failed/) + assert.match(error.message, /https:\/\/wordpress\.org\/wordpress-9\.9\.13\.zip: fetch failed \(connect EHOSTUNREACH/) + assert.match(error.message, /https:\/\/downloads\.wordpress\.org\/release\/wordpress-9\.9\.13\.zip: fetch failed/) + return true + }) + assert.equal(existsSync(join(cacheDirectory, "9.9.13.zip")), false) + + // CLI --json failure: a structured error object on stdout with a stable code. + const offlineJson = await captureStdout(() => runWordPressSourceCommand(["--wp", "9.9.13", "--json"], (versionQuery, options) => materializePlaygroundWordPressSource(versionQuery, { ...options, cacheDirectory }))) + assert.equal(offlineJson.code, 1) + const offlineError = JSON.parse(offlineJson.stdout) + assert.equal(offlineError.schema, WORDPRESS_SOURCE_SCHEMA) + assert.equal(offlineError.root, undefined) + assert.equal(offlineError.error.code, "wordpress-source-download-failed") + assert.equal(offlineError.error.requestedVersion, "9.9.13") + assert.equal(offlineError.error.sourceUrl, "https://wordpress.org/wordpress-9.9.13.zip") + assert.match(offlineError.error.message, /EHOSTUNREACH/) + assert.match(offlineJson.stderr, /failed to materialize WordPress 9\.9\.13 source/) + // Invalid archive bytes are rejected by the existing validator. globalThis.fetch = (async () => new Response("not a zip", { status: 200 })) as typeof fetch await assert.rejects(() => materializePlaygroundWordPressSource("9.9.11", { cacheDirectory }), /invalid/) @@ -162,9 +220,18 @@ try { const failed = await captureStdout(() => runWordPressSourceCommand(["--wp", "9.9.2", "--json"], materialize)) assert.equal(failed.code, 1) - assert.equal(failed.stdout, "") + assert.equal(failed.stdout.trim().split("\n").length, 1, "a --json failure prints exactly one JSON line") + assert.equal(JSON.parse(failed.stdout).error.code, "wordpress-source-materialization-failed") assert.match(failed.stderr, /failed to materialize WordPress 9\.9\.2 source/) + const failedPlain = await captureStdout(() => runWordPressSourceCommand(["--wp", "9.9.2"], materialize)) + assert.equal(failedPlain.code, 1) + assert.equal(failedPlain.stdout, "", "without --json, failures stay on stderr") + + const trunkJson = await captureStdout(() => runWordPressSourceCommand(["--wp", "trunk", "--json"], materialize)) + assert.equal(trunkJson.code, 1) + assert.equal(JSON.parse(trunkJson.stdout).error.code, "wordpress-source-invalid-version") + const usage = await captureStdout(() => runWordPressSourceCommand(["--bogus"], materialize)) assert.equal(usage.code, 2) assert.equal(usage.stdout, "") @@ -172,6 +239,7 @@ try { const missingValue = await captureStdout(() => runWordPressSourceCommand(["--wp", "--json"], materialize)) assert.equal(missingValue.code, 2) + assert.equal(JSON.parse(missingValue.stdout).error.code, "wordpress-source-invalid-arguments") assert.match(missingValue.stderr, /--wp requires a version query/) console.log("wordpress-source passed")