From 6d9eb88905c8334c6e7ff902a9331271b20a5f5d Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 12:37:32 +0000 Subject: [PATCH] feat(react-native): add gradle command Port `react-native gradle` from the legacy CLI. Uploads a React Native bundle + sourcemap during a Gradle build step (invoked by the sentry-android-gradle-plugin). - Injects a debug ID into the bundle and its sourcemap (reusing injectDebugId), then uploads both as artifacts under the `~/` convention via uploadSourcemaps. - Without --release: debug-ID matching. With --release: uploads once per --dist. - Rejects indexed RAM bundles (magic 0xFB0BD1E5), which can't carry a debug ID. - --wait/--wait-for are accepted for compatibility (the CLI always waits for assembly). New: src/commands/react-native/{gradle,index}.ts (react-native route). Tests cover debug-id-only upload, per-dist uploads, missing-file + RAM-bundle rejection. --- docs/src/content/docs/contributing.md | 1 + docs/src/fragments/commands/react-native.md | 28 +++ plugins/sentry-cli/skills/sentry-cli/SKILL.md | 8 + .../sentry-cli/references/react-native.md | 42 ++++ src/app.ts | 2 + src/commands/react-native/gradle.ts | 224 ++++++++++++++++++ src/commands/react-native/index.ts | 20 ++ test/commands/react-native/gradle.test.ts | 134 +++++++++++ 8 files changed, 459 insertions(+) create mode 100644 docs/src/fragments/commands/react-native.md create mode 100644 plugins/sentry-cli/skills/sentry-cli/references/react-native.md create mode 100644 src/commands/react-native/gradle.ts create mode 100644 src/commands/react-native/index.ts create mode 100644 test/commands/react-native/gradle.test.ts diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index b58f8fb946..ea79a91610 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -68,6 +68,7 @@ cli/ │ │ ├── org/ # list, view │ │ ├── proguard/ # upload, uuid │ │ ├── project/ # create, delete, list, view +│ │ ├── react-native/# gradle │ │ ├── release/ # archive, create, delete, deploy, deploys, finalize, list, propose-version, restore, set-commits, view │ │ ├── replay/ # list, view │ │ ├── repo/ # list diff --git a/docs/src/fragments/commands/react-native.md b/docs/src/fragments/commands/react-native.md new file mode 100644 index 0000000000..e616ca86e9 --- /dev/null +++ b/docs/src/fragments/commands/react-native.md @@ -0,0 +1,28 @@ +## Examples + +```bash +# Upload a bundle + sourcemap by debug ID (called by the Gradle plugin) +sentry react-native gradle \ + --bundle index.android.bundle \ + --sourcemap index.android.bundle.map + +# Also associate with a release and distribution(s) +sentry react-native gradle \ + --bundle index.android.bundle \ + --sourcemap index.android.bundle.map \ + --release com.example.app@1.0.0 \ + --dist 1000 +``` + +## Important Notes + +- `react-native gradle` is normally invoked automatically by the + [sentry-android-gradle-plugin](https://docs.sentry.io/platforms/react-native/sourcemaps/); + you rarely run it by hand. +- It injects a debug ID into both the bundle and its sourcemap, then uploads + them under the `~/` convention. Without `--release` the files are + matched by debug ID; with `--release` they are also uploaded for each + `--dist`. +- Indexed RAM bundles are not supported — use a plain or Hermes bundle. +- The CLI always waits for server-side assembly; `--wait`/`--wait-for` are + accepted for backward compatibility but do not change behavior. diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index 0ebe530300..7aa538f803 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -452,6 +452,14 @@ Work with ProGuard/R8 mapping files → Full flags and examples: `references/proguard.md` +### React-native + +Upload React Native sourcemaps from build steps + +- `sentry react-native gradle` — Upload a React Native bundle + sourcemap (Gradle build step) + +→ Full flags and examples: `references/react-native.md` + ### Replay Search and inspect Session Replays diff --git a/plugins/sentry-cli/skills/sentry-cli/references/react-native.md b/plugins/sentry-cli/skills/sentry-cli/references/react-native.md new file mode 100644 index 0000000000..ccddd335f2 --- /dev/null +++ b/plugins/sentry-cli/skills/sentry-cli/references/react-native.md @@ -0,0 +1,42 @@ +--- +name: sentry-cli-react-native +version: 0.39.0-dev.0 +description: Upload React Native sourcemaps from build steps +requires: + bins: ["sentry"] + auth: true +--- + +# React-native Commands + +Upload React Native sourcemaps from build steps + +### `sentry react-native gradle` + +Upload a React Native bundle + sourcemap (Gradle build step) + +**Flags:** +- `--sourcemap - Path to the sourcemap to upload` +- `--bundle - Path to the bundle to upload` +- `--release - Release version to publish to` +- `--dist ... - Distribution(s) to publish (repeatable; requires --release)` +- `--wait - Accepted for compatibility (the CLI always waits for assembly)` +- `--wait-for - Accepted for compatibility (the CLI always waits for assembly)` + +**Examples:** + +```bash +# Upload a bundle + sourcemap by debug ID (called by the Gradle plugin) +sentry react-native gradle \ + --bundle index.android.bundle \ + --sourcemap index.android.bundle.map + +# Also associate with a release and distribution(s) +sentry react-native gradle \ + --bundle index.android.bundle \ + --sourcemap index.android.bundle.map \ + --release com.example.app@1.0.0 \ + --dist 1000 +``` + +All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/src/app.ts b/src/app.ts index c0d3a62220..e4098a923c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -35,6 +35,7 @@ import { listCommand as orgListCommand } from "./commands/org/list.js"; import { proguardRoute } from "./commands/proguard/index.js"; import { projectRoute } from "./commands/project/index.js"; import { listCommand as projectListCommand } from "./commands/project/list.js"; +import { reactNativeRoute } from "./commands/react-native/index.js"; import { releaseRoute } from "./commands/release/index.js"; import { listCommand as releaseListCommand } from "./commands/release/list.js"; import { replayRoute } from "./commands/replay/index.js"; @@ -109,6 +110,7 @@ export const routes = buildRouteMap({ org: orgRoute, project: projectRoute, proguard: proguardRoute, + "react-native": reactNativeRoute, replay: replayRoute, release: releaseRoute, repo: repoRoute, diff --git a/src/commands/react-native/gradle.ts b/src/commands/react-native/gradle.ts new file mode 100644 index 0000000000..77da5b89e2 --- /dev/null +++ b/src/commands/react-native/gradle.ts @@ -0,0 +1,224 @@ +/** + * sentry react-native gradle + * + * Upload a React Native bundle + sourcemap during a Gradle build step (invoked + * by the sentry-android-gradle-plugin). Injects a debug ID into the bundle and + * its sourcemap, then uploads both as artifacts under the `~/` + * convention — with debug-ID-only matching, or per release/distribution. + * + * Mirrors the legacy `sentry-cli react-native gradle`. + */ + +import { readFile, stat } from "node:fs/promises"; +import { basename, resolve } from "node:path"; +import type { SentryContext } from "../../context.js"; +import type { ArtifactFile } from "../../lib/api/sourcemaps.js"; +import { uploadSourcemaps } from "../../lib/api/sourcemaps.js"; +import { buildCommand } from "../../lib/command.js"; +import { ContextError, ValidationError } from "../../lib/errors.js"; +import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { logger } from "../../lib/logger.js"; +import { resolveOrgAndProject } from "../../lib/resolve-target.js"; +import { injectDebugId } from "../../lib/sourcemap/debug-id.js"; + +const log = logger.withTag("react-native.gradle"); + +const USAGE_HINT = + "sentry react-native gradle --sourcemap --bundle "; + +/** Little-endian magic (0xFB0BD1E5) that starts an indexed RAM bundle. */ +const RAM_BUNDLE_MAGIC = [0xe5, 0xd1, 0x0b, 0xfb]; + +/** Flags accepted by `react-native gradle`. */ +type GradleFlags = { + sourcemap: string; + bundle: string; + release?: string; + dist?: string[]; + wait?: boolean; + "wait-for"?: number; +}; + +/** Structured result for the gradle upload. */ +type GradleResult = { + bundle: string; + sourcemap: string; + debugId: string; + release?: string; + dist?: string[]; + /** Number of upload operations performed (one per distribution). */ + uploads: number; +}; + +/** Human-readable summary. */ +function formatGradleResult(data: GradleResult): string { + const rows: [string, string][] = [ + ["Bundle", data.bundle], + ["Sourcemap", data.sourcemap], + ["Debug ID", data.debugId], + ]; + if (data.release) { + rows.push(["Release", data.release]); + } + if (data.dist && data.dist.length > 0) { + rows.push(["Distributions", data.dist.join(", ")]); + } + return renderMarkdown(mdKvTable(rows)); +} + +/** Ensure a path exists and is a regular file. */ +async function assertFile(path: string, label: string): Promise { + const info = await stat(path).catch(() => null); + if (!info?.isFile()) { + throw new ValidationError(`${label} not found: ${path}`, label); + } +} + +/** Reject indexed RAM bundles, which cannot carry an injected debug ID. */ +async function assertNotRamBundle(bundlePath: string): Promise { + const handle = await readFile(bundlePath); + const isRamBundle = + handle.length >= RAM_BUNDLE_MAGIC.length && + RAM_BUNDLE_MAGIC.every((byte, i) => handle[i] === byte); + if (isRamBundle) { + throw new ValidationError( + "Indexed RAM bundles are not supported. Use a plain or Hermes bundle.", + "bundle" + ); + } +} + +/** Build the artifact list for a debug-ID-injected bundle + sourcemap pair. */ +function buildArtifacts( + bundlePath: string, + sourcemapPath: string, + debugId: string +): ArtifactFile[] { + const bundleName = basename(bundlePath); + const sourcemapName = basename(sourcemapPath); + return [ + { + path: bundlePath, + debugId, + type: "minified_source", + url: `~/${bundleName}`, + sourcemapFilename: sourcemapName, + }, + { + path: sourcemapPath, + debugId, + type: "source_map", + url: `~/${sourcemapName}`, + }, + ]; +} + +export const gradleCommand = buildCommand({ + docs: { + brief: "Upload a React Native bundle + sourcemap (Gradle build step)", + fullDescription: + "Upload a React Native bundle and sourcemap during a Gradle build step " + + "(invoked by the sentry-android-gradle-plugin). A debug ID is injected " + + "into both files and they are uploaded under the `~/` " + + "convention.\n\n" + + "Without `--release`, files are matched by debug ID. With `--release`, " + + "they are also uploaded for each `--dist`.\n\n" + + "Note: the CLI always waits for server-side assembly; `--wait`/" + + "`--wait-for` are accepted for compatibility.", + }, + output: { + human: formatGradleResult, + }, + parameters: { + flags: { + sourcemap: { + kind: "parsed", + parse: String, + brief: "Path to the sourcemap to upload", + }, + bundle: { + kind: "parsed", + parse: String, + brief: "Path to the bundle to upload", + }, + release: { + kind: "parsed", + parse: String, + brief: "Release version to publish to", + optional: true, + }, + dist: { + kind: "parsed", + parse: String, + variadic: true, + brief: "Distribution(s) to publish (repeatable; requires --release)", + optional: true, + }, + wait: { + kind: "boolean", + brief: "Accepted for compatibility (the CLI always waits for assembly)", + optional: true, + }, + "wait-for": { + kind: "parsed", + parse: Number, + brief: "Accepted for compatibility (the CLI always waits for assembly)", + optional: true, + }, + }, + }, + async *func(this: SentryContext, flags: GradleFlags) { + const bundlePath = resolve(this.cwd, flags.bundle); + const sourcemapPath = resolve(this.cwd, flags.sourcemap); + await assertFile(bundlePath, "bundle"); + await assertFile(sourcemapPath, "sourcemap"); + await assertNotRamBundle(bundlePath); + + const resolved = await resolveOrgAndProject({ + cwd: this.cwd, + usageHint: USAGE_HINT, + }); + if (!resolved) { + throw new ContextError("Organization and project", USAGE_HINT); + } + const { org, project } = resolved; + + log.info("Processing React Native sourcemaps for Sentry upload."); + const { debugId } = await injectDebugId(bundlePath, sourcemapPath); + const files = buildArtifacts(bundlePath, sourcemapPath, debugId); + + const dists = flags.dist ?? []; + let uploads = 0; + if (flags.release && dists.length > 0) { + for (const dist of dists) { + log.info( + `Uploading sourcemaps for release ${flags.release} distribution ${dist}` + ); + await uploadSourcemaps({ + org, + project, + release: flags.release, + dist, + files, + }); + uploads += 1; + } + } else { + await uploadSourcemaps({ org, project, release: flags.release, files }); + uploads = 1; + } + + yield new CommandOutput({ + bundle: bundlePath, + sourcemap: sourcemapPath, + debugId, + release: flags.release, + dist: dists.length > 0 ? dists : undefined, + uploads, + }); + return { + hint: `Uploaded ${uploads} artifact set(s) with debug ID ${debugId}.`, + }; + }, +}); diff --git a/src/commands/react-native/index.ts b/src/commands/react-native/index.ts new file mode 100644 index 0000000000..075ced7074 --- /dev/null +++ b/src/commands/react-native/index.ts @@ -0,0 +1,20 @@ +/** + * sentry react-native + * + * Route map for React Native build-tool integration commands. + */ + +import { buildRouteMap } from "../../lib/route-map.js"; +import { gradleCommand } from "./gradle.js"; + +export const reactNativeRoute = buildRouteMap({ + routes: { + gradle: gradleCommand, + }, + docs: { + brief: "Upload React Native sourcemaps from build steps", + fullDescription: + "Integrations for uploading React Native bundles and sourcemaps from " + + "native build steps (Gradle/Xcode).", + }, +}); diff --git a/test/commands/react-native/gradle.test.ts b/test/commands/react-native/gradle.test.ts new file mode 100644 index 0000000000..80eb9e86bb --- /dev/null +++ b/test/commands/react-native/gradle.test.ts @@ -0,0 +1,134 @@ +/** + * Tests for `sentry react-native gradle`. + * + * Drives the command via `loader()`. Org/project resolution and the sourcemap + * upload are spied; debug-ID injection runs for real against temp fixtures. + */ + +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { gradleCommand } from "../../../src/commands/react-native/gradle.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as sourcemaps from "../../../src/lib/api/sourcemaps.js"; +import { ValidationError } from "../../../src/lib/errors.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as resolveTarget from "../../../src/lib/resolve-target.js"; + +let tmpDir: string; +let bundle: string; +let sourcemap: string; + +function createContext() { + const writes: string[] = []; + return { + context: { + stdout: { + write: (data: string | Uint8Array) => { + writes.push( + typeof data === "string" ? data : new TextDecoder().decode(data) + ); + return true; + }, + }, + stderr: { write: () => true }, + cwd: tmpDir, + env: {} as NodeJS.ProcessEnv, + process: { ...process, exitCode: undefined } as typeof process, + }, + output: () => writes.join(""), + }; +} + +describe("react-native gradle", () => { + let uploadSpy: ReturnType; + + beforeEach(async () => { + tmpDir = await mkdtemp(join(tmpdir(), "rn-gradle-")); + bundle = join(tmpDir, "index.android.bundle"); + sourcemap = join(tmpDir, "index.android.bundle.map"); + await writeFile(bundle, 'console.log("hello");\n'); + await writeFile( + sourcemap, + JSON.stringify({ + version: 3, + sources: ["index.js"], + names: [], + mappings: "", + sourcesContent: ["console.log('hello');"], + }) + ); + vi.spyOn(resolveTarget, "resolveOrgAndProject").mockResolvedValue({ + org: "acme", + project: "mobile", + }); + uploadSpy = vi + .spyOn(sourcemaps, "uploadSourcemaps") + .mockResolvedValue(undefined); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await rm(tmpDir, { recursive: true, force: true }); + }); + + test("injects a debug id and uploads once (debug-id only)", async () => { + const func = await gradleCommand.loader(); + await func.call(createContext().context, { bundle, sourcemap }); + + expect(uploadSpy).toHaveBeenCalledTimes(1); + const opts = uploadSpy.mock.calls[0][0] as sourcemaps.UploadOptions; + expect(opts.org).toBe("acme"); + expect(opts.project).toBe("mobile"); + expect(opts.release).toBeUndefined(); + expect(opts.files.map((f) => f.url)).toEqual([ + "~/index.android.bundle", + "~/index.android.bundle.map", + ]); + expect(opts.files[0]).toMatchObject({ + type: "minified_source", + sourcemapFilename: "index.android.bundle.map", + }); + expect(opts.files[0].debugId).toMatch(/[0-9a-f-]{36}/); + // The bundle on disk now carries the injected debug id. + expect(await readFile(bundle, "utf8")).toContain("debugId"); + }); + + test("uploads once per distribution when a release is given", async () => { + const func = await gradleCommand.loader(); + await func.call(createContext().context, { + bundle, + sourcemap, + release: "1.0.0", + dist: ["1000", "1001"], + }); + + expect(uploadSpy).toHaveBeenCalledTimes(2); + const dists = uploadSpy.mock.calls.map( + (c) => (c[0] as sourcemaps.UploadOptions).dist + ); + expect(dists).toEqual(["1000", "1001"]); + for (const call of uploadSpy.mock.calls) { + expect((call[0] as sourcemaps.UploadOptions).release).toBe("1.0.0"); + } + }); + + test("rejects a missing bundle", async () => { + const func = await gradleCommand.loader(); + await expect( + func.call(createContext().context, { + bundle: join(tmpDir, "nope.bundle"), + sourcemap, + }) + ).rejects.toThrow(ValidationError); + }); + + test("rejects an indexed RAM bundle", async () => { + await writeFile(bundle, Buffer.from([0xe5, 0xd1, 0x0b, 0xfb, 0x00, 0x00])); + const func = await gradleCommand.loader(); + await expect( + func.call(createContext().context, { bundle, sourcemap }) + ).rejects.toThrow(/RAM bundle/); + }); +});