Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/cli-docs/src/content/docs/library-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ const sdk = createSentrySDK({ token: "...", text: true, cwd: "/my/project" });
|--------|------|---------|-------------|
| `token` | `string` | Auto-detected | Auth token for this invocation |
| `url` | `string` | `sentry.io` | Sentry instance URL for self-hosted |
| `org` | `string` | Auto-detected | Default organization slug |
| `project` | `string` | Auto-detected | Default project slug |
| `org` | `string` | Auto-detected | Organization slug; also a limit while `limitToTarget` is on |
| `project` | `string` | Auto-detected | Project slug; also a limit while `limitToTarget` is on |
| `limitToTarget` | `boolean` | `true` | Refuse an issue outside `org` and `project`, even one an ID alone names (`12345`, `@latest`). Set `false` to use `org` and `project` only as defaults |
| `text` | `boolean` | `false` | Return human-readable text instead of parsed JSON (`run()` only) |
| `cwd` | `string` | `process.cwd()` | Working directory for DSN auto-detection |
| `headers` | `Record<string, string>` | — | Extra HTTP headers for self-hosted instances behind a reverse proxy (same as [`SENTRY_CUSTOM_HEADERS`](../configuration/#sentry_custom_headers)); ignored for sentry.io |
Expand Down
8 changes: 8 additions & 0 deletions packages/cli/script/check-env-coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ const INTERNAL_ENV_VARS = new Map<string, string>([
"SENTRY_CLI_NO_PERSISTENCE",
"set by createSentrySDK() unless persist: true, for one invocation",
],
[
"SENTRY_CLI_SCOPE_ORG",
"set by createSentrySDK({ limitToTarget: true }), for one invocation",
],
[
"SENTRY_CLI_SCOPE_PROJECT",
"set by createSentrySDK({ limitToTarget: true }), for one invocation",
],
["SENTRY_RN_BUNDLE_COMMAND", "internal react-native wrapper plumbing"],
["SENTRY_RN_NO_DEBUG_ID", "internal react-native wrapper plumbing"],
["SENTRY_RN_REAL_HERMES_CLI_PATH", "internal react-native wrapper plumbing"],
Expand Down
13 changes: 11 additions & 2 deletions packages/cli/src/commands/event/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import {
} from "../../lib/sentry-url-parser.js";
import { buildEventSearchUrl } from "../../lib/sentry-web-urls.js";
import { getSpanTreeLines } from "../../lib/span-tree.js";
import { getTargetScope } from "../../lib/target-scope.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import type { InferOutput } from "valibot";
import type { SentryEvent } from "../../types/index.js";
Expand Down Expand Up @@ -1139,8 +1140,16 @@ async function resolveIssueIdShortcut(
parsed.type === ProjectSpecificationType.Explicit
? parsed.project
: undefined;
const projectPromise = explicitProject
? Promise.resolve(explicitProject)
// A target-scoped invocation checks the issue (`getIssueInOrg`) before it
// reads the issue's events: the ID names no project, and an explicit one
// need not be the issue's.
const scopedProject = getTargetScope()
? (await getIssueInOrg(org, issueId, { collapse: ISSUE_DETAIL_COLLAPSE }))
.project?.slug
: undefined;
const knownProject = explicitProject ?? scopedProject;
const projectPromise = knownProject
? Promise.resolve(knownProject)
: tryResolveIssueProject(org, issueId);
const [event, project] = await Promise.all([
getLatestEvent(org, issueId),
Expand Down
13 changes: 12 additions & 1 deletion packages/cli/src/commands/feedback/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import {
parseIssueArgument,
} from "../../lib/issue-arguments.js";
import { resolveEffectiveOrg } from "../../lib/region.js";
import { resolveOrg } from "../../lib/resolve-target.js";
import {
resolveOrg,
resolveProjectIdsInOrg,
} from "../../lib/resolve-target.js";
import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import type { SentryFeedback } from "../../types/index.js";
import { buildCommandHint, resolveIssue } from "../issue/utils.js";
Expand Down Expand Up @@ -53,9 +57,15 @@ async function resolveFeedbackSelector(
);
}

// A project-scoped invocation picks the latest Feedback of its project.
const scopeProject = getTargetScope()?.project;
const [projectId] = scopeProject
? await resolveProjectIdsInOrg(org, [scopeProject])
: [];
const { feedback } = await listFeedback(org, "", {
limit: 1,
status: "unresolved",
projectId,
});
const latest = feedback[0];
if (!latest) {
Expand All @@ -67,6 +77,7 @@ async function resolveFeedbackSelector(
);
}

assertIssueInScope(org, latest);
setOrgProjectContext(
[org],
latest.project?.slug ? [latest.project.slug] : [],
Expand Down
24 changes: 17 additions & 7 deletions packages/cli/src/commands/issue/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
} from "../../lib/resolve-target.js";
import { applySentryUrlContext } from "../../lib/sentry-url-parser.js";
import { buildIssueUrl } from "../../lib/sentry-web-urls.js";
import { assertIssueInScope, getTargetScope } from "../../lib/target-scope.js";
import { setOrgProjectContext } from "../../lib/telemetry.js";
import { isAllDigits, shellQuote } from "../../lib/utils.js";
import type { SentryIssue } from "../../types/index.js";
Expand Down Expand Up @@ -599,14 +600,15 @@ async function resolveSelector(
* @param org - Organization slug
* @param project - Project slug to look in, selected by its numeric ID
* (a `project:<slug>` filter misses projects that are not actively
* selected, #1317); omit for the whole organization
* @throws {ResolutionError} When no unresolved issue matches, or the
* project does not exist
* selected, #1317); omit for the whole organization, or for the project
* of the invocation's target scope when it has one
* @throws {ResolutionError} When no unresolved issue matches, the project
* does not exist, or the issue is outside the target scope
*/
export async function findSelectorIssue(
selector: IssueSelector,
org: string,
project?: string,
project = getTargetScope()?.project,
): Promise<SentryIssue> {
const projects = project
? await resolveProjectIdsInOrg(org, [project])
Expand All @@ -633,6 +635,7 @@ export async function findSelectorIssue(
],
);
}
assertIssueInScope(org, issue);
return issue;
}

Expand Down Expand Up @@ -662,29 +665,36 @@ async function resolveIssueSearch(
throw new ContextError("Organization", commandHint);
}
const { org } = resolved;
const scopeProject = getTargetScope()?.project;
const { data: issues, nextCursor } = await listIssuesPaginated(org, "", {
query,
perPage: SEARCH_CANDIDATES,
collapse: ISSUE_DETAIL_COLLAPSE,
projects: scopeProject
? await resolveProjectIdsInOrg(org, [scopeProject])
: undefined,
});
const [issue] = issues;
if (issue && issues.length === 1) {
assertIssueInScope(org, issue);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return { org, issue };
}

const listCommand = sentry`issue list ${org}/ --query ${shellQuote(query)}`;
// In a project scope, the search ran in that project alone.
const searched = scopeProject ? `${org}/${scopeProject}` : org;
const listCommand = sentry`issue list ${org}/${scopeProject ?? ""} --query ${shellQuote(query)}`;
if (!issue) {
throw new ResolutionError(
`Search ${shellQuote(query)}`,
`matched no issues in '${org}'`,
`matched no issues in '${searched}'`,
listCommand,
["Pass an issue ID or short ID instead, e.g. CLI-G or 123456789"],
);
}
const count = nextCursor ? `${issues.length}+` : String(issues.length);
throw new ResolutionError(
`Search ${shellQuote(query)}`,
`matched ${count} issues in '${org}'`,
`matched ${count} issues in '${searched}'`,
listCommand,
issues.map(
(candidate) =>
Expand Down
12 changes: 11 additions & 1 deletion packages/cli/src/lib/api/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from "../custom-ca.js";
import { applyCustomHeaders } from "../custom-headers.js";
import { ApiError, ValidationError } from "../errors.js";
import { assertIssueInScope, assertOrgInScope } from "../target-scope.js";

import {
getOrgSdkConfig,
Expand Down Expand Up @@ -325,19 +326,24 @@ export async function listIssuesAllPages(
* @param orgSlug - Organization slug (used for region routing)
* @param issueId - Numeric issue ID
* @param options - Optional collapse fields to skip expensive backend queries
* @throws {ResolutionError} When the issue is outside the invocation's
* target scope (`limitToTarget`)
*/
export async function getIssueInOrg(
orgSlug: string,
issueId: string,
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
assertOrgInScope(orgSlug, issueId);
const collapse = toIssueDetailsCollapse(options?.collapse);
const result = await getOrganizationIssue({
...getOrgSdkConfig(),
path: { organization_id_or_slug: orgSlug, issue_id: issueId },
...(collapse && { query: { collapse } }),
});
return unwrapResult<SentryIssue>(result, "Failed to get issue");
const issue = unwrapResult<SentryIssue>(result, "Failed to get issue");
assertIssueInScope(orgSlug, issue);
return issue;
}

/**
Expand Down Expand Up @@ -398,13 +404,16 @@ export async function findIssueInOrgs(
* @param orgSlug - Organization slug
* @param shortId - Short ID (e.g., "CLI-G5", "SPOTLIGHT-ELECTRON-4D")
* @param options - Optional collapse fields to skip expensive backend queries
* @throws {ResolutionError} When the issue is outside the invocation's
* target scope (`limitToTarget`)
*/
export async function getIssueByShortId(
orgSlug: string,
shortId: string,
options?: { collapse?: IssueCollapseField[] },
): Promise<SentryIssue> {
const normalizedShortId = shortId.toUpperCase();
assertOrgInScope(orgSlug, normalizedShortId);
const config = getOrgSdkConfig();

let data: { group?: SentryIssue };
Expand Down Expand Up @@ -444,6 +453,7 @@ export async function getIssueByShortId(
"Issue not found",
);
}
assertIssueInScope(orgSlug, data.group);
return data.group;
}

Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,12 @@ export const NO_PERSISTENCE_ENV_VAR = "SENTRY_CLI_NO_PERSISTENCE";
export function isPersistenceDisabled(): boolean {
return getEnv()[NO_PERSISTENCE_ENV_VAR] === "1";
}

/**
* Internal env vars `createSentrySDK()` sets to the organization and project
* an invocation is limited to, unless `limitToTarget` is `false`. See
* `target-scope.ts`.
*/
export const SCOPE_ORG_ENV_VAR = "SENTRY_CLI_SCOPE_ORG";
/** See {@link SCOPE_ORG_ENV_VAR}. */
export const SCOPE_PROJECT_ENV_VAR = "SENTRY_CLI_SCOPE_PROJECT";
41 changes: 25 additions & 16 deletions packages/cli/src/lib/sdk-invoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ import { homedir } from "node:os";
import type { Span } from "@sentry/core";
import type { Writer } from "../types/index.js";
import { type AsyncChannel, createAsyncChannel } from "./async-channel.js";
import { NO_PERSISTENCE_ENV_VAR, withInvocation } from "./env.js";
import {
NO_PERSISTENCE_ENV_VAR,
SCOPE_ORG_ENV_VAR,
SCOPE_PROJECT_ENV_VAR,
withInvocation,
} from "./env.js";
import { stringifyUnknown } from "./errors.js";
import { SentryError, type SentryOptions } from "./sdk-types.js";
import generatedStreamingCommands from "../generated/streaming-commands.json" with { type: "json" };
Expand All @@ -32,7 +37,8 @@ const STREAMING_COMMANDS: StreamingCommands = generatedStreamingCommands;

/**
* Build an isolated env from options, starting from `options.env` or the
* consumer's process.env. Sets auth token, host URL, default org/project,
* consumer's process.env. Sets auth token, host URL, org/project (as
* defaults and, unless `limitToTarget` is `false`, as the target scope),
* output format, and the no-persistence flag.
*/
function buildIsolatedEnv(
Expand All @@ -56,6 +62,12 @@ function buildIsolatedEnv(
if (options?.project) {
env["SENTRY_PROJECT"] = options.project;
}
if (options?.limitToTarget !== false && options?.org) {
env[SCOPE_ORG_ENV_VAR] = options.org;
if (options.project) {
env[SCOPE_PROJECT_ENV_VAR] = options.project;
}
}
if (jsonByDefault && !options?.text) {
env["SENTRY_OUTPUT_FORMAT"] = "json";
}
Expand Down Expand Up @@ -303,7 +315,8 @@ type CaptureContext = {
stdin: NodeJS.ReadStream & { fd: 0 };
env: NodeJS.ProcessEnv;
cwd: () => string;
exitCode: number;
/** Unset until something fails, as on Node's own `process`. */
exitCode: number | undefined;
};
stdout: Writer;
stderr: Writer;
Expand Down Expand Up @@ -365,7 +378,9 @@ async function buildCaptureContext(
stdin: process.stdin,
env,
cwd: () => cwd,
exitCode: 0,
// Unset, as on Node's `process`: Stricli's `run()` records a failure
// with `exitCode ??= code`, which a 0 here would swallow.
exitCode: undefined,
};

if (opts?.abortSignal) {
Expand Down Expand Up @@ -443,11 +458,9 @@ async function executeWithCapture<T>(
await flushTelemetry();

// Check exit code (Stricli sets it without throwing for some errors)
if (captureCtx.context.process.exitCode !== 0) {
throw buildSdkError(
captureCtx.stderrChunks,
captureCtx.context.process.exitCode,
);
const exitCode = captureCtx.context.process.exitCode ?? 0;
if (exitCode !== 0) {
throw buildSdkError(captureCtx.stderrChunks, exitCode);
}

return parseOutput(
Expand Down Expand Up @@ -512,13 +525,9 @@ function executeWithStream<T>(
});

// Check exit code — Stricli sets it without throwing for some errors
if (captureCtx.context.process.exitCode !== 0) {
channel.error(
buildSdkError(
captureCtx.stderrChunks,
captureCtx.context.process.exitCode,
),
);
const exitCode = captureCtx.context.process.exitCode ?? 0;
if (exitCode !== 0) {
channel.error(buildSdkError(captureCtx.stderrChunks, exitCode));
} else {
// Drain any raw stdout the command wrote directly (via stdout.write)
// instead of yielding via captureObject — e.g. a binary Uint8Array
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/lib/sdk-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ export type SentryOptions = {
*/
project?: string;

/**
* Treat `org` and `project` as a limit, not only as defaults (default
* `true`). A command then refuses an issue outside them, including one
* named by an ID that says nothing about its project (a numeric ID, a
* share link, `@latest`). Has no effect without `org`. Set `false` to use
* `org` and `project` only as defaults.
*/
limitToTarget?: boolean;

/**
* Return human-readable text instead of parsed JSON.
* When `true`, the `run()` function returns a `string` instead of a parsed object.
Expand Down
Loading
Loading