diff --git a/.oxlintrc.json b/.oxlintrc.json index 7bc2fbad1..18ac71c5a 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -100,6 +100,7 @@ "sentry-cli/no-examples-in-full-description": "error", "sentry-cli/no-regex-markdown-parsing": "error", "sentry-cli/json-transform-uses-fields": "error", + "sentry-cli/no-runtime-output-schema-imports": "error", "no-restricted-imports": [ "error", { diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index c9520682e..925f67aaf 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -239,29 +239,46 @@ Lint enforcement: `stderr.write()` is banned in command files (GritQL rule). Use `output.schema` drives `--fields` completion, the JSON field table in `--help`, and the skill references. Nothing validates output against it, so declare each field once and derive the TypeScript type from the schema; the compiler then keeps the two in sync ([#1824](https://github.com/getsentry/toolkit/issues/1824)). +The schemas live in `src/output-schemas/.ts` (one module per top-level command), which only the build loads ([#1914](https://github.com/getsentry/toolkit/issues/1914)). `script/generate-output-schemas.ts` (part of `generate:docs`) reads each exported `…Schema` and writes its field list and `--fields` paths to the gitignored `src/generated/output-schemas/.ts`, under the same export name. A command imports that data as its `output.schema`, so a run loads only its own route's field lists, and none of the schemas: + +- Import the schema data from `src/generated/output-schemas/`, and everything else from `src/output-schemas/` with `import type` only. Lint (`sentry-cli/no-runtime-output-schema-imports`) rejects a value import, or `import { type X }`, which `verbatimModuleSyntax` keeps as a runtime import. +- Export the type the command needs next to its schema (`export type ReleaseDeleteOutput = InferOutput`), or `import type` the schema and write `typeof`. +- A schema that also validates an API response at runtime (`SentryLogSchema`, `TransactionListItemSchema`, `ConversationListItemSchema`, `DashboardRevisionSchema`) stays where it is and is re-exported from its area's module. +- `src/output-schemas/` must not import `src/generated/output-schemas/`: the generator loads the former to write the latter. + - **API fields** keep their `@sentry/api` type and come from the generated `@sentry/api/valibot` schema (`vXxxResponse.entries`, wrapped in `pipe(field, description(…))` when it needs a description). -- **Fields the CLI adds** (target context such as `org`/`orgSlug`, flags such as `dryRun`/`deleted`, computed values such as `url`, `trace`, `period`) are written once as a valibot `object` of output fields. Spread its `entries` into the schema, and get the type with `InferOutput`, or `WithOutputFields` (`src/types/output.ts`) when the fields sit on (or override) an API object. +- **Fields the CLI adds** (target context such as `org`/`orgSlug`, flags such as `dryRun`/`deleted`, computed values such as `url`, `trace`, `period`) are written once as a valibot `object` of output fields. Spread its `entries` into the schema, and get the type with `InferOutput`, or `WithOutputFields` (`src/output-schemas/output.ts`) when the fields sit on (or override) an API object. - Type the `human` formatter's parameter (and `jsonTransform`'s, when set) with the derived type. `buildCommand`, `buildListCommand`, and `buildDeleteCommand` infer the output type from `output` and check every `CommandOutput` that `func` yields against it. Annotate a yield (`new CommandOutput(…)`) only when it builds a discriminated-union literal (`kind: "endpoints"`) that would otherwise widen to `string`. - Without `jsonTransform`, the data (each item, for array data) must also satisfy `output.schema`: a field the schema documents but the command doesn't produce, or documents with another type, is a compile error. Keep the data typed: an API response typed `Record` can't satisfy a schema built from `@sentry/api/valibot`, so type it with its `@sentry/api` response type. - With `jsonTransform`, the schema describes the transform's item: each item of a `{ data: [...] }` envelope or an array, otherwise the result itself. Every field the schema documents must exist on that item with a matching type; optionality isn't compared, since `--fields` makes items `Partial`. So the transform must return a typed result, not `unknown` or `Record`: return `ListJson` from `jsonTransformListResult`, type a hand-built envelope as `ListEnvelope` (`lib/org-list.ts`), and let a single object's type come from its spread with `filterFieldsIfSet`. The error names the mismatched fields under `~outputMismatch`. -- An `OrgListConfig` checks its entity against `schema` when you pass the schema's type: `OrgListConfig`. Don't annotate an output config as `OutputConfig` or check it with `satisfies OutputConfig`: that erases the schema's type, and the check passes without comparing anything. -- Reuse the shared fields: `DryRunOutputField`, `orgListItemSchema`/`WithOrg` (`lib/org-list.ts`) for org-scoped lists, `opaque()` for a field the docs leave opaque but the code types (a full event payload). +- An `OrgListConfig` takes the item's schema data (`orgListItemSchema(Entity)`, exported from the area's module) and checks its entity against it when you pass its type: `OrgListConfig`. Don't annotate an output config as `OutputConfig` or check it with `satisfies OutputConfig`: that erases the schema's type, and the check passes without comparing anything. +- Reuse the shared fields: `DryRunOutputField` and `opaque()` (`src/output-schemas/output.ts`; `opaque` is for a field the docs leave opaque but the code types, such as a full event payload), and `orgListItemSchema` (`src/output-schemas/org-list.ts`) with `WithOrg` (`lib/org-list.ts`) for org-scoped lists. - Data only the human formatter needs (pre-rendered lines, a resolved target) stays out of the schema; keep it outside the derived type or strip it with `jsonExclude`. ```typescript -const DeployOutputFields = object({ +// src/output-schemas/release.ts +export const ReleaseDeployOutputFields = object({ dryRun: DryRunOutputField, version: optional(pipe(string(), description("Release version (--dry-run)"))), }); -type DeployOutput = WithOutputFields; +export const ReleaseDeployOutputSchema = looseObject({ + ...SentryDeploySchema.entries, + ...ReleaseDeployOutputFields.entries, +}); + +// src/commands/release/deploy.ts +import { ReleaseDeployOutputSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseDeployOutputFields } from "../../output-schemas/release.js"; + +type DeployOutput = WithOutputFields; output: { human: (deploy: DeployOutput) => …, - schema: looseObject({ ...SentryDeploySchema.entries, ...DeployOutputFields.entries }), + schema: ReleaseDeployOutputSchema, }, ``` -Reference: `src/commands/release/deploy.ts`, `src/commands/alert/output-schemas.ts`, `ReplayViewOutputFields` in `src/types/replay.ts`. +Reference: `src/commands/release/deploy.ts`, `src/output-schemas/alert.ts`, `ReplayViewOutputFields` in `src/output-schemas/replay.ts`. ### Route Maps (Stricli) diff --git a/packages/cli/lint-rules/cli-oxlint-plugin.js b/packages/cli/lint-rules/cli-oxlint-plugin.js index 06df99150..064357e65 100644 --- a/packages/cli/lint-rules/cli-oxlint-plugin.js +++ b/packages/cli/lint-rules/cli-oxlint-plugin.js @@ -731,6 +731,36 @@ const rules = { } : {}, ), + "no-runtime-output-schema-imports": rule( + "src/output-schemas/ is build-only: use `import type` from it, and import the field data from src/generated/output-schemas/.", + (_context, file, report) => { + if (!file.includes("/src/") || file.includes("/src/output-schemas/")) + return {}; + const buildOnly = (source) => + typeof source === "string" && + /(?:^|\/)output-schemas\//.test(source) && + !/(?:^|\/)generated\/output-schemas\//.test(source); + // Only `import type` / `export type` is erased whole. Under + // `verbatimModuleSyntax`, `import { type X }` still loads the module. + return { + ImportDeclaration(node) { + if (buildOnly(node.source.value) && node.importKind !== "type") + report(node); + }, + ExportNamedDeclaration(node) { + if (buildOnly(node.source?.value) && node.exportKind !== "type") + report(node); + }, + ExportAllDeclaration(node) { + if (buildOnly(node.source.value) && node.exportKind !== "type") + report(node); + }, + ImportExpression(node) { + if (buildOnly(node.source.value)) report(node); + }, + }; + }, + ), "no-skipped-tests": rule( "Do not leave disabled tests in the suite.", (_context, file, report) => diff --git a/packages/cli/package.json b/packages/cli/package.json index ce83330b8..7ada146a2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -71,8 +71,9 @@ "generate:sdk": "pnpm tsx script/generate-sdk.ts", "generate:skill": "pnpm tsx script/generate-skill.ts", "generate:banner": "pnpm tsx script/generate-banner-image.ts", - "generate:docs": "node script/ensure-generated.mjs schema && pnpm run generate:grammar && pnpm run generate:command-api && pnpm run generate:banner && pnpm run generate:completions && pnpm run generate:top-level-routes && pnpm run generate:command-docs && pnpm run generate:docs-sections && pnpm run generate:skill", + "generate:docs": "node script/ensure-generated.mjs schema && pnpm run generate:grammar && pnpm run generate:output-schemas && pnpm run generate:command-api && pnpm run generate:banner && pnpm run generate:completions && pnpm run generate:top-level-routes && pnpm run generate:command-docs && pnpm run generate:docs-sections && pnpm run generate:skill", "generate:grammar": "node ../../scripts/generate-parsers.mjs .", + "generate:output-schemas": "pnpm tsx script/generate-output-schemas.ts", "generate:completions": "pnpm tsx script/generate-completion-targets.ts", "generate:top-level-routes": "pnpm tsx script/generate-top-level-routes.ts", "generate:docs-sections": "pnpm tsx script/generate-docs-sections.ts", diff --git a/packages/cli/script/ensure-generated.mjs b/packages/cli/script/ensure-generated.mjs index f533da5c9..238d133ba 100644 --- a/packages/cli/script/ensure-generated.mjs +++ b/packages/cli/script/ensure-generated.mjs @@ -33,6 +33,7 @@ const GRAMMAR_OUTPUTS = [ ]; /** Produced by `generate:docs`; imported at runtime by `src/`. */ const DOCS_OUTPUTS = [ + "src/generated/output-schemas", "src/generated/command-api.json", "src/generated/skill-content.ts", "src/generated/completion-targets.json", diff --git a/packages/cli/script/generate-output-schemas.ts b/packages/cli/script/generate-output-schemas.ts new file mode 100644 index 000000000..126b5fb04 --- /dev/null +++ b/packages/cli/script/generate-output-schemas.ts @@ -0,0 +1,102 @@ +#!/usr/bin/env tsx +/** + * Generate Output Schema Fields + * + * Command output schemas (`src/output-schemas/`) are valibot schemas the CLI + * only needs for their field list: `--help`, `sentry help `, `--fields` + * parsing and completion, the skill references, and the SDK's return types. + * Reading that list out of a schema needs the schema, valibot, and + * everything the schema spreads in from `@sentry/api/valibot`, so this + * script reads it at build time instead. It loads each module in + * `src/output-schemas/`, and for each exported valibot schema whose name + * ends in `Schema` writes its fields and field paths + * ({@link OutputSchemaFields}) to `src/generated/output-schemas/`, in a + * module of the same name and under the same export name. Commands import + * those, so a run loads the field data of its own route's commands and no + * schema. + * + * `src/output-schemas/` must not import from `src/generated/output-schemas/`: + * this script loads it to write that directory. + * + * The output is gitignored and regenerated by `generate:docs`, which runs as + * part of `dev`, `build`, `bundle`, `typecheck`, and `test`. + * + * Usage: tsx script/generate-output-schemas.ts + * Output: src/generated/output-schemas/*.ts + */ + +import { mkdir, readdir, rm, writeFile } from "node:fs/promises"; +import { basename, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import type { GenericSchema } from "valibot"; +import type { OutputSchemaFields } from "../src/lib/formatters/output.js"; +import { + extractSchemaFieldPaths, + extractSchemaFields, +} from "./lib/output-schema-fields.js"; + +const SOURCE_DIR = "src/output-schemas"; +const OUTPUT_DIR = "src/generated/output-schemas"; + +/** Whether `value` is a valibot schema (not an action or a plain value). */ +function isSchema(value: unknown): value is GenericSchema { + return ( + typeof value === "object" && + value !== null && + (value as { kind?: unknown }).kind === "schema" + ); +} + +/** The generated module for one `src/output-schemas/` module. */ +function renderModule( + name: string, + schemas: [string, GenericSchema][], +): string { + const source = `../../output-schemas/${name}.js`; + const lines = [ + `// Generated by script/generate-output-schemas.ts from ${SOURCE_DIR}/${name}.ts.`, + "// Do not edit; change the schemas there instead.", + "", + 'import type { OutputSchemaFields } from "../../lib/formatters/output.js";', + "import type {", + ...schemas.map(([exportName]) => ` ${exportName} as ${exportName}Source,`), + `} from ${JSON.stringify(source)};`, + ]; + for (const [exportName, schema] of schemas) { + const fields: OutputSchemaFields = { + fields: extractSchemaFields(schema), + paths: extractSchemaFieldPaths(schema), + }; + lines.push( + "", + `export const ${exportName}: OutputSchemaFields = ${JSON.stringify(fields)};`, + ); + } + return `${lines.join("\n")}\n`; +} + +const files = (await readdir(SOURCE_DIR)) + .filter((file) => file.endsWith(".ts")) + .sort(); + +await rm(OUTPUT_DIR, { recursive: true, force: true }); +await mkdir(OUTPUT_DIR, { recursive: true }); + +let count = 0; +for (const file of files) { + const name = basename(file, ".ts"); + const exports: Record = await import( + pathToFileURL(resolve(SOURCE_DIR, file)).href + ); + const schemas = Object.entries(exports).filter( + (entry): entry is [string, GenericSchema] => + entry[0].endsWith("Schema") && isSchema(entry[1]), + ); + if (schemas.length === 0) { + continue; + } + count += schemas.length; + await writeFile(`${OUTPUT_DIR}/${name}.ts`, renderModule(name, schemas)); +} + +console.log(`Generated ${OUTPUT_DIR}/ (${count} output schemas)`); diff --git a/packages/cli/script/generate-sdk.ts b/packages/cli/script/generate-sdk.ts index e26db15be..c91c1bc6a 100644 --- a/packages/cli/script/generate-sdk.ts +++ b/packages/cli/script/generate-sdk.ts @@ -20,7 +20,7 @@ import { writeFile } from "node:fs/promises"; import ts from "typescript"; import { routes } from "../src/app.js"; -import { extractSchemaFields } from "../src/lib/formatters/output.js"; +import type { SchemaFieldInfo } from "../src/lib/formatters/output.js"; import { type Command, type FlagDef, @@ -238,7 +238,7 @@ function derivePositional(command: Command): PositionalInfo { } // --------------------------------------------------------------------------- -// Return Type Generation from __jsonSchema +// Return Type Generation from __jsonFields // --------------------------------------------------------------------------- /** Map a single schema field type name to a TypeScript type node. */ @@ -306,20 +306,16 @@ function propertySignature( } /** - * Build the result type from a command's __jsonSchema. - * Returns null if no schema is attached. + * Build the result type from a command's __jsonFields. + * Returns null if no output schema is attached. */ function buildReturnType( command: Command, typeName: string, ): ts.TypeAliasDeclaration | null { - const schema = (command as any).__jsonSchema; - if (!schema) { - return null; - } - - const fields = extractSchemaFields(schema); - if (fields.length === 0) { + const fields: readonly SchemaFieldInfo[] | undefined = (command as any) + .__jsonFields; + if (!fields?.length) { return null; } @@ -801,7 +797,7 @@ const sdkType = exportedObjectType(SDK_TYPE_NAME, [ /** Sections shared verbatim by the implementation file and the published declarations. */ const sharedTypes = [ - "// --- Return types (derived from __jsonSchema) ---", + "// --- Return types (derived from __jsonFields) ---", "", returnTypes.length > 0 ? printNodes(returnTypes) diff --git a/packages/cli/script/lib/output-schema-fields.ts b/packages/cli/script/lib/output-schema-fields.ts new file mode 100644 index 000000000..c5249c2b5 --- /dev/null +++ b/packages/cli/script/lib/output-schema-fields.ts @@ -0,0 +1,228 @@ +/** + * Read the field metadata of a valibot output schema: the fields `--help`, + * `sentry help ` and the skill references list, and the paths + * `--fields` completes. + * + * Build time only. `script/generate-output-schemas.ts` runs it over the + * schemas in `src/output-schemas/` and writes the result to + * `src/generated/output-schemas/`, which is what the CLI reads at runtime. + */ + +import { type GenericSchema, getDescription } from "valibot"; +import type { SchemaFieldInfo } from "../../src/lib/formatters/output.js"; + +/** Minimal structural view of a valibot schema's runtime shape. */ +type ValibotSchemaNode = { + type: string; + /** Inner schema for wrapper types (optional / nullable / nullish). */ + wrapped?: ValibotSchemaNode; + /** Member schemas for union / variant / picklist. */ + options?: unknown[]; + /** Item schema for array. */ + item?: ValibotSchemaNode; + /** Field schemas for object / loose_object. */ + entries?: Record; + /** + * Pipe steps for a `SchemaWithPipe` (e.g. `pipe(string(), description(...))` + * or the `pipe(unknown(), transform(Number), number())` coercion pattern). + * Each step carries a `kind` of `"schema"`, `"validation"`, `"transformation"`, + * or `"metadata"`. + */ + pipe?: Array<{ type: string; kind: string }>; +}; + +/** + * Resolve a piped schema (`pipe(...)`) to the node whose `type` reflects its + * output — the last step with `kind === "schema"`. For the coercion pattern + * `pipe(unknown(), transform(Number), number())` this is `number()`, not the + * leading `unknown()`. Non-piped schemas are returned unchanged. + */ +function unwrapPipe(schema: ValibotSchemaNode): ValibotSchemaNode { + if (!schema.pipe?.length) { + return schema; + } + const schemaSteps = schema.pipe.filter((step) => step.kind === "schema"); + const last = schemaSteps.at(-1); + return (last as ValibotSchemaNode | undefined) ?? schema; +} + +/** Leaf-type name mapping for {@link valibotTypeToString}. */ +const VALIBOT_TYPE_MAP: Record = { + string: "string", + number: "number", + boolean: "boolean", + object: "object", + loose_object: "object", + array: "array", + record: "object", + null: "null", + unknown: "unknown", + any: "any", + picklist: "string", + enum: "string", + literal: "string", +}; + +/** + * Resolve a valibot `union` into a deduplicated `" | "`-joined type string. + * + * Used by auto-generated `@sentry/api/valibot` schemas that represent nullable + * fields as `union([string(), null_()])` instead of `nullable(string())`. + */ +function resolveValibotUnion(options: ValibotSchemaNode[]): { + type: string; + optional: boolean; +} { + let optional = false; + const parts: string[] = []; + for (const opt of options) { + const resolved = valibotTypeToString(opt); + if (resolved.optional) { + optional = true; + } + if (!parts.includes(resolved.type)) { + parts.push(resolved.type); + } + } + return { type: parts.join(" | "), optional }; +} + +/** + * Map a valibot schema's runtime `type` to a human-readable string. + * + * Unwraps wrapper types (optional, nullable, nullish) and builds a composite + * type string (e.g. "string | null" for `nullable(string())`). Delegates + * union handling to {@link resolveValibotUnion}. + */ +function valibotTypeToString(input: ValibotSchemaNode): { + type: string; + optional: boolean; +} { + // Resolve `pipe(...)` schemas (incl. the coercion pattern) to their output + // schema before inspecting the type. + const schema = input ? unwrapPipe(input) : input; + if (!schema?.type) { + return { type: "unknown", optional: false }; + } + + // Unwrap wrapper types recursively. + if (schema.type === "optional" && schema.wrapped) { + const inner = valibotTypeToString(schema.wrapped); + return { type: inner.type, optional: true }; + } + if (schema.type === "nullable" && schema.wrapped) { + const inner = valibotTypeToString(schema.wrapped); + const nullableType = inner.type.includes(" | null") + ? inner.type + : `${inner.type} | null`; + return { type: nullableType, optional: inner.optional }; + } + if (schema.type === "nullish" && schema.wrapped) { + const inner = valibotTypeToString(schema.wrapped); + const nullableType = inner.type.includes(" | null") + ? inner.type + : `${inner.type} | null`; + return { type: nullableType, optional: true }; + } + if ( + (schema.type === "union" || schema.type === "variant") && + schema.options?.length + ) { + return resolveValibotUnion(schema.options as ValibotSchemaNode[]); + } + + return { type: VALIBOT_TYPE_MAP[schema.type] ?? "unknown", optional: false }; +} + +/** + * Extract field metadata from a valibot object schema. + * + * Returns an array of {@link SchemaFieldInfo} describing each top-level + * field's name, type, description, and optionality. Returns an empty + * array for non-object schemas. + * + * @param schema - A valibot schema (typically `object({...})`) + */ +export function extractSchemaFields(schema: GenericSchema): SchemaFieldInfo[] { + const node = schema as unknown as ValibotSchemaNode; + + if (node.type !== "object" && node.type !== "loose_object") { + return []; + } + + const entries = node.entries; + if (!entries) { + return []; + } + + return Object.entries(entries).map(([name, fieldSchema]) => { + const { type, optional } = valibotTypeToString(fieldSchema); + return { + name, + type, + description: findDescription(fieldSchema), + optional, + }; + }); +} + +/** Wrapper types {@link objectsOf} looks through to the schema they hold. */ +const WRAPPER_TYPES = new Set(["optional", "nullable", "nullish", "array"]); + +/** + * The object schemas a value of `schema` can be: through pipes, wrappers, + * array items (`--fields` paths reach into arrays), and union and variant + * members. + */ +function objectsOf(schema: ValibotSchemaNode): ValibotSchemaNode[] { + const node = unwrapPipe(schema); + if (WRAPPER_TYPES.has(node.type)) { + const inner = node.wrapped ?? node.item; + return inner ? objectsOf(inner) : []; + } + if (node.type === "union" || node.type === "variant") { + return (node.options as ValibotSchemaNode[]).flatMap(objectsOf); + } + return node.entries ? [node] : []; +} + +/** + * Every field path a valibot schema describes, in `--fields` dot notation: + * each top-level field, then the fields of nested objects + * (`metadata.title`), parents before children. + * + * @param schema - A valibot schema (typically `object({...})`) + */ +export function extractSchemaFieldPaths(schema: GenericSchema): string[] { + const paths = new Set(); + const visit = (node: ValibotSchemaNode, prefix: string) => { + for (const { entries = {} } of objectsOf(node)) { + for (const [name, field] of Object.entries(entries)) { + paths.add(`${prefix}${name}`); + visit(field, `${prefix}${name}.`); + } + } + }; + visit(schema as unknown as ValibotSchemaNode, ""); + return [...paths]; +} + +/** + * Find a `description()` pipe action for a field schema. + * + * `getDescription` does not recurse, and the description may sit under one or + * more wrapper schemas — e.g. `optional(nullable(pipe(string(), description(...))))` + * places it two `.wrapped` levels down. Walk the wrapper chain until a + * description is found. + */ +function findDescription(schema: ValibotSchemaNode): string | undefined { + let node: ValibotSchemaNode | undefined = schema; + while (node) { + const description = getDescription(node as unknown as GenericSchema); + if (description !== undefined) { + return description; + } + node = node.wrapped; + } + return; +} diff --git a/packages/cli/src/commands/agent-conversation/list.ts b/packages/cli/src/commands/agent-conversation/list.ts index 68061548b..a77ac7aca 100644 --- a/packages/cli/src/commands/agent-conversation/list.ts +++ b/packages/cli/src/commands/agent-conversation/list.ts @@ -43,10 +43,8 @@ import { type TimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { - type ConversationListItem, - ConversationListItemSchema, -} from "../../types/conversation.js"; +import type { ConversationListItem } from "../../types/conversation.js"; +import { ConversationListItemSchema } from "../../generated/output-schemas/agent-conversation.js"; const CONVERSATION_SORT_FIELDS = [ "conversation.age", diff --git a/packages/cli/src/commands/alert/issues/create.ts b/packages/cli/src/commands/alert/issues/create.ts index 295b37d68..d6f33c4a4 100644 --- a/packages/cli/src/commands/alert/issues/create.ts +++ b/packages/cli/src/commands/alert/issues/create.ts @@ -44,11 +44,11 @@ import { validateIssueActions, validateIssueTriggers, } from "../mutation-utils.js"; -import { - type IssueAlertCreateBody, - type IssueAlertCreateOutput, - IssueAlertCreateOutputSchema, -} from "../output-schemas.js"; +import type { + IssueAlertCreateBody, + IssueAlertCreateOutput, +} from "../../../output-schemas/alert.js"; +import { IssueAlertCreateOutputSchema } from "../../../generated/output-schemas/alert.js"; const USAGE_HINT = "sentry alert issues create --name --condition --action "; diff --git a/packages/cli/src/commands/alert/issues/delete.ts b/packages/cli/src/commands/alert/issues/delete.ts index 963d47c5e..1e91e4906 100644 --- a/packages/cli/src/commands/alert/issues/delete.ts +++ b/packages/cli/src/commands/alert/issues/delete.ts @@ -18,10 +18,8 @@ import { import { resolveProjectBoundTargets } from "../../../lib/resolve-target.js"; import type { AlertRuleArgument } from "../arguments.js"; import { issueRuleParameter, resolveIssueAlertRule } from "./rule-resolve.js"; -import { - type IssueAlertDeleteOutput, - IssueAlertDeleteOutputSchema, -} from "../output-schemas.js"; +import type { IssueAlertDeleteOutput } from "../../../output-schemas/alert.js"; +import { IssueAlertDeleteOutputSchema } from "../../../generated/output-schemas/alert.js"; const USAGE_HINT = "sentry alert issues delete //"; diff --git a/packages/cli/src/commands/alert/issues/edit.ts b/packages/cli/src/commands/alert/issues/edit.ts index dc2dba7b3..5766ea3df 100644 --- a/packages/cli/src/commands/alert/issues/edit.ts +++ b/packages/cli/src/commands/alert/issues/edit.ts @@ -40,10 +40,8 @@ import { } from "../mutation-utils.js"; import type { AlertRuleArgument } from "../arguments.js"; import { issueRuleParameter, resolveIssueAlertRule } from "./rule-resolve.js"; -import { - type IssueAlertEditOutput, - IssueAlertEditOutputSchema, -} from "../output-schemas.js"; +import type { IssueAlertEditOutput } from "../../../output-schemas/alert.js"; +import { IssueAlertEditOutputSchema } from "../../../generated/output-schemas/alert.js"; const USAGE_HINT = "sentry alert issues edit // --name | --status active|disabled"; diff --git a/packages/cli/src/commands/alert/metrics/create.ts b/packages/cli/src/commands/alert/metrics/create.ts index e114fc1d4..15aa155e9 100644 --- a/packages/cli/src/commands/alert/metrics/create.ts +++ b/packages/cli/src/commands/alert/metrics/create.ts @@ -42,11 +42,11 @@ import { validateMetricTimeWindow, } from "../mutation-utils.js"; import { metricAlertStatusLabel } from "./status.js"; -import { - type MetricAlertCreateBody, - type MetricAlertCreateOutput, - MetricAlertCreateOutputSchema, -} from "../output-schemas.js"; +import type { + MetricAlertCreateBody, + MetricAlertCreateOutput, +} from "../../../output-schemas/alert.js"; +import { MetricAlertCreateOutputSchema } from "../../../generated/output-schemas/alert.js"; type CreateFlags = { readonly name: string; diff --git a/packages/cli/src/commands/alert/metrics/delete.ts b/packages/cli/src/commands/alert/metrics/delete.ts index 30a803c10..6b39ca3f7 100644 --- a/packages/cli/src/commands/alert/metrics/delete.ts +++ b/packages/cli/src/commands/alert/metrics/delete.ts @@ -17,10 +17,8 @@ import { import { resolveOrgOnlyTarget } from "../../../lib/resolve-target.js"; import type { AlertRuleArgument } from "../arguments.js"; import { metricRuleParameter, resolveMetricAlertRule } from "./rule-resolve.js"; -import { - type MetricAlertDeleteOutput, - MetricAlertDeleteOutputSchema, -} from "../output-schemas.js"; +import type { MetricAlertDeleteOutput } from "../../../output-schemas/alert.js"; +import { MetricAlertDeleteOutputSchema } from "../../../generated/output-schemas/alert.js"; const USAGE_HINT = "sentry alert metrics delete /"; diff --git a/packages/cli/src/commands/alert/metrics/edit.ts b/packages/cli/src/commands/alert/metrics/edit.ts index ec470a757..0c43ba548 100644 --- a/packages/cli/src/commands/alert/metrics/edit.ts +++ b/packages/cli/src/commands/alert/metrics/edit.ts @@ -44,10 +44,8 @@ import { } from "../mutation-utils.js"; import type { AlertRuleArgument } from "../arguments.js"; import { metricRuleParameter, resolveMetricAlertRule } from "./rule-resolve.js"; -import { - type MetricAlertEditOutput, - MetricAlertEditOutputSchema, -} from "../output-schemas.js"; +import type { MetricAlertEditOutput } from "../../../output-schemas/alert.js"; +import { MetricAlertEditOutputSchema } from "../../../generated/output-schemas/alert.js"; const USAGE_HINT = "sentry alert metrics edit / --name | --status active|disabled"; diff --git a/packages/cli/src/commands/auth/list.ts b/packages/cli/src/commands/auth/list.ts index c26ec12d0..77df081e4 100644 --- a/packages/cli/src/commands/auth/list.ts +++ b/packages/cli/src/commands/auth/list.ts @@ -19,7 +19,7 @@ import { } from "../../lib/formatters/accounts.js"; import { filterFieldsIfSet } from "../../lib/formatters/json.js"; import { CommandOutput } from "../../lib/formatters/output.js"; -import { AccountSummarySchema } from "../../types/account.js"; +import { AccountSummarySchema } from "../../generated/output-schemas/account.js"; export const listCommand = buildCommand({ auth: false, diff --git a/packages/cli/src/commands/dashboard/create.ts b/packages/cli/src/commands/dashboard/create.ts index 1cd6bd49e..a8a96a244 100644 --- a/packages/cli/src/commands/dashboard/create.ts +++ b/packages/cli/src/commands/dashboard/create.ts @@ -4,13 +4,6 @@ * Create a new dashboard in a Sentry organization. */ -import { - description, - type InferOutput, - looseObject, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { createDashboard, getProject } from "../../lib/api-client.js"; import { @@ -36,7 +29,8 @@ import { import { applySentryUrlContext } from "../../lib/sentry-url-parser.js"; import { buildDashboardUrl } from "../../lib/sentry-web-urls.js"; import { setOrgProjectContext } from "../../lib/telemetry.js"; -import { DashboardDetailSchema } from "../../types/dashboard.js"; +import { DashboardCreateOutputSchema } from "../../generated/output-schemas/dashboard.js"; +import type { DashboardCreateOutput } from "../../output-schemas/dashboard.js"; import { withDashboardErrors } from "./resolve.js"; type CreateFlags = { @@ -44,13 +38,7 @@ type CreateFlags = { readonly fields?: string[]; }; -/** JSON output: the created dashboard and its URL. */ -const CreateOutputSchema = looseObject({ - ...DashboardDetailSchema.entries, - url: pipe(string(), description("Dashboard URL")), -}); - -type CreateResult = InferOutput; +type CreateResult = DashboardCreateOutput; /** `dashboard create`'s positionals, parsed: the title and the target. */ type CreateInput = { @@ -194,7 +182,7 @@ export const createCommand = buildCommand({ }, output: { human: formatDashboardCreated, - schema: CreateOutputSchema, + schema: DashboardCreateOutputSchema, }, parameters: { positional: boundArguments({ diff --git a/packages/cli/src/commands/dashboard/list.ts b/packages/cli/src/commands/dashboard/list.ts index 1aa0396fb..71dd3f79f 100644 --- a/packages/cli/src/commands/dashboard/list.ts +++ b/packages/cli/src/commands/dashboard/list.ts @@ -36,16 +36,14 @@ import { buildDashboardsListUrl, buildDashboardUrl, } from "../../lib/sentry-web-urls.js"; -import { - type DashboardListItem, - DashboardListItemSchema, -} from "../../types/dashboard.js"; +import type { DashboardListItem } from "../../types/dashboard.js"; import type { Writer } from "../../types/index.js"; import { type DashboardListArguments, dashboardListArguments, } from "./arguments.js"; import { withDashboardErrors } from "./resolve.js"; +import { DashboardListItemSchema } from "../../generated/output-schemas/dashboard.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "dashboard-list"; diff --git a/packages/cli/src/commands/dashboard/restore.ts b/packages/cli/src/commands/dashboard/restore.ts index c2a172ab9..34f68d73a 100644 --- a/packages/cli/src/commands/dashboard/restore.ts +++ b/packages/cli/src/commands/dashboard/restore.ts @@ -5,7 +5,6 @@ */ import { tableCell } from "@sentry/toolkit-core/markdown"; -import { description, type InferOutput, object, pipe, string } from "valibot"; import type { SentryContext } from "../../context.js"; import { restoreDashboardRevision } from "../../lib/api-client.js"; import { buildCommand } from "../../lib/command.js"; @@ -16,7 +15,8 @@ import { CommandOutput } from "../../lib/formatters/output.js"; import { formatRelativeTime } from "../../lib/formatters/time-utils.js"; import { withProgress } from "../../lib/polling.js"; import { buildDashboardUrl } from "../../lib/sentry-web-urls.js"; -import { DashboardDetailSchema } from "../../types/dashboard.js"; +import { DashboardRestoreOutputSchema } from "../../generated/output-schemas/dashboard.js"; +import type { DashboardRestoreOutput } from "../../output-schemas/dashboard.js"; import { type DashboardArguments, dashboardArguments } from "./arguments.js"; import { withDashboardErrors } from "./resolve.js"; @@ -26,14 +26,7 @@ type RestoreFlags = { readonly fields?: string[]; }; -/** JSON output: the restored dashboard and the revision it was restored to. */ -const RestoreOutputSchema = object({ - dashboard: pipe(DashboardDetailSchema, description("Restored dashboard")), - orgSlug: pipe(string(), description("Organization slug")), - revisionId: pipe(string(), description("Restored revision ID")), -}); - -type RestoreResult = InferOutput; +type RestoreResult = DashboardRestoreOutput; function formatRestoreHuman(result: RestoreResult): string { const d = result.dashboard; @@ -80,7 +73,7 @@ export const restoreCommand = buildCommand({ }, output: { human: formatRestoreHuman, - schema: RestoreOutputSchema, + schema: DashboardRestoreOutputSchema, }, parameters: { positional: dashboardArguments({ diff --git a/packages/cli/src/commands/dashboard/revisions.ts b/packages/cli/src/commands/dashboard/revisions.ts index d8e3eb1b0..dd54647c9 100644 --- a/packages/cli/src/commands/dashboard/revisions.ts +++ b/packages/cli/src/commands/dashboard/revisions.ts @@ -28,13 +28,11 @@ import { import type { ListEnvelope } from "../../lib/org-list.js"; import { withProgress } from "../../lib/polling.js"; import { buildDashboardUrl } from "../../lib/sentry-web-urls.js"; -import { - type DashboardRevision, - DashboardRevisionSchema, -} from "../../types/dashboard.js"; +import type { DashboardRevision } from "../../types/dashboard.js"; import type { Writer } from "../../types/index.js"; import { type DashboardArguments, dashboardArguments } from "./arguments.js"; import { withDashboardErrors } from "./resolve.js"; +import { DashboardRevisionSchema } from "../../generated/output-schemas/dashboard.js"; const PAGINATION_KEY = "dashboard-revisions"; diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index 8c6b9192b..7acc0b65a 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -31,13 +31,13 @@ import { type TimeRange, timeRangeToSeconds, } from "../../lib/time-range.js"; -import { - DashboardViewOutputSchema, - type DashboardWidget, - type WidgetDataResult, +import type { + DashboardWidget, + WidgetDataResult, } from "../../types/dashboard.js"; import { type DashboardArguments, dashboardArguments } from "./arguments.js"; import { withDashboardErrors } from "./resolve.js"; +import { DashboardViewOutputSchema } from "../../generated/output-schemas/dashboard.js"; /** Default auto-refresh interval in seconds */ const DEFAULT_REFRESH_INTERVAL = 60; diff --git a/packages/cli/src/commands/dashboard/widget/add.ts b/packages/cli/src/commands/dashboard/widget/add.ts index c1331dfd9..dc7784ab9 100644 --- a/packages/cli/src/commands/dashboard/widget/add.ts +++ b/packages/cli/src/commands/dashboard/widget/add.ts @@ -25,7 +25,6 @@ import { import { buildDashboardUrl } from "../../../lib/sentry-web-urls.js"; import { assignDefaultLayout, - DashboardWidgetChangeOutputSchema, DEFAULT_WIDGET_TYPE, DISPLAY_TYPES, FALLBACK_LAYOUT, @@ -53,6 +52,7 @@ import { WIDGET_FIELD_COMPLETION, type WidgetQueryFlags, } from "../resolve.js"; +import { DashboardWidgetChangeOutputSchema } from "../../../generated/output-schemas/dashboard.js"; /** What `--query`, `--sort`, and `--group-by` complete: a spans widget's by default. */ const FIELD_COMPLETION: DatasetCompletion = { diff --git a/packages/cli/src/commands/dashboard/widget/delete.ts b/packages/cli/src/commands/dashboard/widget/delete.ts index 803fbb3e3..41c61dff4 100644 --- a/packages/cli/src/commands/dashboard/widget/delete.ts +++ b/packages/cli/src/commands/dashboard/widget/delete.ts @@ -21,11 +21,11 @@ import { buildDeleteCommand } from "../../../lib/mutate-command.js"; import { buildDashboardUrl } from "../../../lib/sentry-web-urls.js"; import { type DashboardWidgetDeleteOutput, - DashboardWidgetDeleteOutputSchema, prepareDashboardForUpdate, } from "../../../types/dashboard.js"; import { type DashboardArguments, dashboardArguments } from "../arguments.js"; import { withDashboardErrors, resolveWidgetIndex } from "../resolve.js"; +import { DashboardWidgetDeleteOutputSchema } from "../../../generated/output-schemas/dashboard.js"; type DeleteFlags = { readonly index?: number; diff --git a/packages/cli/src/commands/dashboard/widget/edit.ts b/packages/cli/src/commands/dashboard/widget/edit.ts index 158f67cda..3b5cbe2dc 100644 --- a/packages/cli/src/commands/dashboard/widget/edit.ts +++ b/packages/cli/src/commands/dashboard/widget/edit.ts @@ -19,7 +19,6 @@ import { CommandOutput } from "../../../lib/formatters/output.js"; import { buildDashboardUrl } from "../../../lib/sentry-web-urls.js"; import { type DashboardWidget, - DashboardWidgetChangeOutputSchema, type DashboardWidgetQuery, DISPLAY_TYPES, FALLBACK_LAYOUT, @@ -47,6 +46,7 @@ import { WIDGET_FIELD_COMPLETION, type WidgetQueryFlags, } from "../resolve.js"; +import { DashboardWidgetChangeOutputSchema } from "../../../generated/output-schemas/dashboard.js"; type EditFlags = WidgetQueryFlags & WidgetLayoutFlags & { diff --git a/packages/cli/src/commands/event/list.ts b/packages/cli/src/commands/event/list.ts index de2b9b9c5..6205e5eb2 100644 --- a/packages/cli/src/commands/event/list.ts +++ b/packages/cli/src/commands/event/list.ts @@ -24,7 +24,6 @@ import { serializeTimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { IssueEventSchema } from "../../types/index.js"; import { type IssueTarget, issuePositional } from "../issue/positional.js"; import { buildCommandHint } from "../issue/utils.js"; import { @@ -35,6 +34,7 @@ import { formatEventsHuman, jsonTransformEvents, } from "./shared-events.js"; +import { IssueEventSchema } from "../../generated/output-schemas/event.js"; // --------------------------------------------------------------------------- // Constants diff --git a/packages/cli/src/commands/event/view.ts b/packages/cli/src/commands/event/view.ts index ecaa5ad5a..48ca7e7e3 100644 --- a/packages/cli/src/commands/event/view.ts +++ b/packages/cli/src/commands/event/view.ts @@ -79,12 +79,10 @@ import { buildEventSearchUrl } from "../../lib/sentry-web-urls.js"; import { getSpanTreeLines } from "../../lib/span-tree.js"; import { setOrgProjectContext } from "../../lib/telemetry.js"; import type { InferOutput } from "valibot"; -import { - type EventViewOutputFields, - EventViewOutputSchema, - type SentryEvent, -} from "../../types/index.js"; +import type { SentryEvent } from "../../types/index.js"; import { findSelectorIssue } from "../issue/utils.js"; +import { EventViewOutputSchema } from "../../generated/output-schemas/event.js"; +import type { EventViewOutputFields } from "../../output-schemas/event.js"; type ViewFlags = { readonly json: boolean; diff --git a/packages/cli/src/commands/feedback/list.ts b/packages/cli/src/commands/feedback/list.ts index 445351a37..6f634a9b0 100644 --- a/packages/cli/src/commands/feedback/list.ts +++ b/packages/cli/src/commands/feedback/list.ts @@ -51,11 +51,8 @@ import { type TimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { - type FeedbackListResult, - type SentryFeedback, - SentryFeedbackSchema, -} from "../../types/index.js"; +import type { FeedbackListResult, SentryFeedback } from "../../types/index.js"; +import { SentryFeedbackSchema } from "../../generated/output-schemas/feedback.js"; const DEFAULT_PERIOD = "14d"; const DEFAULT_STATUS: FeedbackStatus = "unresolved"; diff --git a/packages/cli/src/commands/feedback/resolve.ts b/packages/cli/src/commands/feedback/resolve.ts index d4f4fc294..c163d728d 100644 --- a/packages/cli/src/commands/feedback/resolve.ts +++ b/packages/cli/src/commands/feedback/resolve.ts @@ -7,9 +7,9 @@ import { buildCommand } from "../../lib/command.js"; import { formatResolvedFeedback } from "../../lib/formatters/feedback.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { disableResponseCache } from "../../lib/response-cache.js"; -import { SentryFeedbackSchema } from "../../types/index.js"; import { type FeedbackTarget, feedbackPositional } from "./positional.js"; import { updateFeedbackStatus } from "./utils.js"; +import { SentryFeedbackSchema } from "../../generated/output-schemas/feedback.js"; export const resolveCommand = buildCommand({ docs: { diff --git a/packages/cli/src/commands/feedback/spam.ts b/packages/cli/src/commands/feedback/spam.ts index 5c6ec4c98..061fd861f 100644 --- a/packages/cli/src/commands/feedback/spam.ts +++ b/packages/cli/src/commands/feedback/spam.ts @@ -7,9 +7,9 @@ import { buildCommand } from "../../lib/command.js"; import { formatSpamFeedback } from "../../lib/formatters/feedback.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { disableResponseCache } from "../../lib/response-cache.js"; -import { SentryFeedbackSchema } from "../../types/index.js"; import { type FeedbackTarget, feedbackPositional } from "./positional.js"; import { updateFeedbackStatus } from "./utils.js"; +import { SentryFeedbackSchema } from "../../generated/output-schemas/feedback.js"; export const spamCommand = buildCommand({ docs: { diff --git a/packages/cli/src/commands/feedback/unresolve.ts b/packages/cli/src/commands/feedback/unresolve.ts index a17b77c4e..8e0666234 100644 --- a/packages/cli/src/commands/feedback/unresolve.ts +++ b/packages/cli/src/commands/feedback/unresolve.ts @@ -7,9 +7,9 @@ import { buildCommand } from "../../lib/command.js"; import { formatReopenedFeedback } from "../../lib/formatters/feedback.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { disableResponseCache } from "../../lib/response-cache.js"; -import { SentryFeedbackSchema } from "../../types/index.js"; import { type FeedbackTarget, feedbackPositional } from "./positional.js"; import { updateFeedbackStatus } from "./utils.js"; +import { SentryFeedbackSchema } from "../../generated/output-schemas/feedback.js"; export const unresolveCommand = buildCommand({ docs: { diff --git a/packages/cli/src/commands/feedback/view.ts b/packages/cli/src/commands/feedback/view.ts index ebb08bf6b..dd3fca134 100644 --- a/packages/cli/src/commands/feedback/view.ts +++ b/packages/cli/src/commands/feedback/view.ts @@ -27,8 +27,8 @@ import { getReplayIdFromEvent, } from "../../lib/replay-search.js"; import type { FeedbackViewResult, SentryEvent } from "../../types/index.js"; -import { FeedbackViewOutputSchema } from "../../types/index.js"; import { type FeedbackTarget, feedbackPositional } from "./positional.js"; +import { FeedbackViewOutputSchema } from "../../generated/output-schemas/feedback.js"; const log = logger.withTag("feedback.view"); diff --git a/packages/cli/src/commands/integration/list.ts b/packages/cli/src/commands/integration/list.ts index 17a440406..b26a7c0be 100644 --- a/packages/cli/src/commands/integration/list.ts +++ b/packages/cli/src/commands/integration/list.ts @@ -16,10 +16,8 @@ import { type OrgListCommandDocs, } from "../../lib/list-command.js"; import type { OrgListConfig, WithOrg } from "../../lib/org-list.js"; -import { - type SentryIntegration, - SentryIntegrationSchema, -} from "../../types/index.js"; +import type { SentryIntegration } from "../../types/index.js"; +import { IntegrationListItemSchema } from "../../generated/output-schemas/integration.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "integration-list"; @@ -41,7 +39,7 @@ const INTEGRATION_COLUMNS: Column[] = [ const integrationListConfig: OrgListConfig< SentryIntegration, IntegrationWithOrg, - typeof SentryIntegrationSchema + typeof IntegrationListItemSchema > = { paginationKey: PAGINATION_KEY, entityPlural: "integrations", @@ -54,7 +52,7 @@ const integrationListConfig: OrgListConfig< namesOf: (integration) => [integration.name, integration.provider.name], displayTable: (integrations: IntegrationWithOrg[]) => formatTable(integrations, INTEGRATION_COLUMNS), - schema: SentryIntegrationSchema, + schema: IntegrationListItemSchema, }; const docs: OrgListCommandDocs = { diff --git a/packages/cli/src/commands/issue/events.ts b/packages/cli/src/commands/issue/events.ts index 390fa9ee1..09abcba89 100644 --- a/packages/cli/src/commands/issue/events.ts +++ b/packages/cli/src/commands/issue/events.ts @@ -21,7 +21,6 @@ import { serializeTimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { IssueEventSchema } from "../../types/index.js"; import { appendEventsFlags, EVENTS_ALIASES, @@ -32,6 +31,7 @@ import { } from "../event/shared-events.js"; import { type IssueTarget, issuePositional } from "./positional.js"; import { buildCommandHint } from "./utils.js"; +import { IssueEventSchema } from "../../generated/output-schemas/event.js"; // --------------------------------------------------------------------------- // Constants diff --git a/packages/cli/src/commands/issue/list.ts b/packages/cli/src/commands/issue/list.ts index 4a63a7e64..576d176ca 100644 --- a/packages/cli/src/commands/issue/list.ts +++ b/packages/cli/src/commands/issue/list.ts @@ -101,12 +101,9 @@ import { } from "../../lib/time-range.js"; import { tipsSuppressed } from "../../lib/tips.js"; import { shellQuote } from "../../lib/utils.js"; -import { - type SentryIssue, - SentryIssueSchema, - type Writer, -} from "../../types/index.js"; +import type { SentryIssue, Writer } from "../../types/index.js"; import { resolveIssue } from "./utils.js"; +import { SentryIssueSchema } from "../../generated/output-schemas/issue.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "issue-list"; diff --git a/packages/cli/src/commands/issue/tags.ts b/packages/cli/src/commands/issue/tags.ts index 414a518cf..8554181c7 100644 --- a/packages/cli/src/commands/issue/tags.ts +++ b/packages/cli/src/commands/issue/tags.ts @@ -5,8 +5,6 @@ * because that endpoint ignores them. */ -import { vGetOrganizationIssueTagResponse } from "@sentry/api/valibot"; -import { description, object, pipe } from "valibot"; import type { SentryContext } from "../../context.js"; import { getIssueTag } from "../../lib/api-client.js"; import { buildCommand } from "../../lib/command.js"; @@ -26,6 +24,7 @@ import { requireIssueArgument, } from "./positional.js"; import { buildCommandHint, resolveIssue } from "./utils.js"; +import { IssueTagsOutputSchema } from "../../generated/output-schemas/issue.js"; type TagsFlags = { /** Emit the API response as JSON instead of a human table; defaults to false. */ @@ -73,21 +72,7 @@ export const tagsCommand = buildCommand({ }, output: { human: formatIssueTags, - schema: object({ - ...vGetOrganizationIssueTagResponse.entries, - totalValues: pipe( - vGetOrganizationIssueTagResponse.entries.totalValues, - description( - "Total retained events, including missing tag values; not a lifetime count", - ), - ), - topValues: pipe( - vGetOrganizationIssueTagResponse.entries.topValues, - description( - "Up to 9 values ordered by count, with nullable counts and first/last seen timestamps", - ), - ), - }), + schema: IssueTagsOutputSchema, }, parameters: { positional: { diff --git a/packages/cli/src/commands/issue/view.ts b/packages/cli/src/commands/issue/view.ts index 4af606301..a4865448c 100644 --- a/packages/cli/src/commands/issue/view.ts +++ b/packages/cli/src/commands/issue/view.ts @@ -30,9 +30,9 @@ import { } from "../../lib/replay-search.js"; import { getSpanTreeLines } from "../../lib/span-tree.js"; import type { SentryEvent } from "../../types/index.js"; -import { IssueViewOutputSchema } from "../../types/index.js"; import { type IssuesArguments, issuesPositional } from "./positional.js"; import { mapIssueArgsConcurrently, resolveIssue } from "./utils.js"; +import { IssueViewOutputSchema } from "../../generated/output-schemas/issue.js"; const log = logger.withTag("issue.view"); diff --git a/packages/cli/src/commands/log/list.ts b/packages/cli/src/commands/log/list.ts index 5600ed70f..75efa0d6f 100644 --- a/packages/cli/src/commands/log/list.ts +++ b/packages/cli/src/commands/log/list.ts @@ -79,7 +79,7 @@ import { warnIfNormalized, } from "../../lib/trace-target.js"; import { getUpdateNotification } from "../../lib/version-check.js"; -import { SentryLogSchema } from "../../types/index.js"; +import { SentryLogSchema } from "../../generated/output-schemas/log.js"; type ListFlags = { readonly limit: number; diff --git a/packages/cli/src/commands/monitor/list.ts b/packages/cli/src/commands/monitor/list.ts index a167b9733..6dfcf73b2 100644 --- a/packages/cli/src/commands/monitor/list.ts +++ b/packages/cli/src/commands/monitor/list.ts @@ -20,7 +20,8 @@ import { type OrgListCommandDocs, } from "../../lib/list-command.js"; import type { OrgListConfig, WithOrg } from "../../lib/org-list.js"; -import { type SentryMonitor, SentryMonitorSchema } from "../../types/index.js"; +import type { SentryMonitor } from "../../types/index.js"; +import { MonitorListItemSchema } from "../../generated/output-schemas/monitor.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "monitor-list"; @@ -62,7 +63,7 @@ const MONITOR_COLUMNS: Column[] = [ const monitorListConfig: OrgListConfig< SentryMonitor, MonitorWithOrg, - typeof SentryMonitorSchema + typeof MonitorListItemSchema > = { paginationKey: PAGINATION_KEY, entityPlural: "monitors", @@ -74,7 +75,7 @@ const monitorListConfig: OrgListConfig< searchesNames: true, displayTable: (monitors: MonitorWithOrg[]) => formatTable(monitors, MONITOR_COLUMNS), - schema: SentryMonitorSchema, + schema: MonitorListItemSchema, }; const docs: OrgListCommandDocs = { diff --git a/packages/cli/src/commands/org/list.ts b/packages/cli/src/commands/org/list.ts index 64a047de8..e60013678 100644 --- a/packages/cli/src/commands/org/list.ts +++ b/packages/cli/src/commands/org/list.ts @@ -6,15 +6,7 @@ */ import { tableCell } from "@sentry/toolkit-core/markdown"; -import { - description, - type InferOutput, - looseObject, - object, - optional, - pipe, - string, -} from "valibot"; +import type { InferOutput } from "valibot"; import type { SentryContext } from "../../context.js"; import { resolveAccountSelector } from "../../lib/account-selection.js"; import { listOrganizationsUncached } from "../../lib/api-client.js"; @@ -55,12 +47,16 @@ import { } from "../../lib/list-command.js"; import { logger } from "../../lib/logger.js"; import { withProgress } from "../../lib/polling.js"; -import { - type SentryOrganization, - SentryOrganizationSchema, - type WithOutputFields, - type Writer, +import type { + SentryOrganization, + WithOutputFields, + Writer, } from "../../types/index.js"; +import { OrgListEntrySchema } from "../../generated/output-schemas/org.js"; +import type { + OrgListAccountSchema, + OrgListEntryFields, +} from "../../output-schemas/org.js"; type ListFlags = { readonly limit: number; @@ -70,70 +66,14 @@ type ListFlags = { readonly fields?: string[]; }; -/** - * The account an organization was listed under (no secrets): a stored - * account, or the env token's virtual account. - */ -const OrgListAccountSchema = object({ - /** - * What `--account` accepts: `:`, e.g. - * `jane@acme.com:sentry.io` (just `` when no server is recorded), as - * `sentry auth login` does too; `env:SENTRY_AUTH_TOKEN` for the env token. - */ - name: pipe(string(), description("What --account accepts")), - id: pipe(string(), description("Account ID")), - email: optional(pipe(string(), description("Account email"))), - username: optional(pipe(string(), description("Account username"))), - /** - * The server part of `name`: `host[:port]`, or the full origin such as - * `http://localhost:8000` for a non-HTTPS server. - */ - server: optional(pipe(string(), description("Account server"))), - /** The server's full origin, e.g. `https://sentry.io`. */ - host: optional(pipe(string(), description("Server origin"))), - /** Human label, e.g. `Jane on sentry.io`. */ - label: pipe(string(), description("Human-readable account label")), - /** The variable providing the token, for the env token's account. */ - envVar: optional( - pipe(string(), description("Variable providing the env token")), - ), -}); - type OrgListAccount = InferOutput; -/** - * Fields the list adds to each organization: a region display name and the - * stored account it was listed under. - * - * The `region` field is only present when the user's orgs span multiple - * regions (e.g. both US and EU). `account` is only present when orgs from - * several stored accounts are listed. Both are included in JSON output as - * well, providing context to machine consumers. - */ -const OrgListEntryFields = object({ - region: optional( - pipe(string(), description("Region, when orgs span several (e.g. US, EU)")), - ), - account: optional( - pipe( - OrgListAccountSchema, - description("Account the org was listed under, across accounts"), - ), - ), -}); - /** An organization with the fields of {@link OrgListEntryFields}. */ type OrgListEntry = WithOutputFields< SentryOrganization, typeof OrgListEntryFields >; -/** JSON fields of an {@link OrgListEntry}, for `--fields`. */ -const OrgListEntrySchema = looseObject({ - ...SentryOrganizationSchema.entries, - ...OrgListEntryFields.entries, -}); - /** One account's fetched orgs plus its slug → region URL cache. */ type AccountOrgs = { account?: AccountSummary; diff --git a/packages/cli/src/commands/org/view.ts b/packages/cli/src/commands/org/view.ts index 95a165eca..7a422983c 100644 --- a/packages/cli/src/commands/org/view.ts +++ b/packages/cli/src/commands/org/view.ts @@ -17,7 +17,7 @@ import { } from "../../lib/list-command.js"; import { buildOrgUrl } from "../../lib/sentry-web-urls.js"; import { type OrgTarget, orgTarget } from "../../lib/target-positional.js"; -import { SentryOrganizationSchema } from "../../types/index.js"; +import { SentryOrganizationSchema } from "../../generated/output-schemas/org.js"; type ViewFlags = { readonly json: boolean; diff --git a/packages/cli/src/commands/project/list.ts b/packages/cli/src/commands/project/list.ts index 9009e8551..30d76adf5 100644 --- a/packages/cli/src/commands/project/list.ts +++ b/packages/cli/src/commands/project/list.ts @@ -57,7 +57,6 @@ import { jsonTransformListResult, type ListCommandMeta, type ListResult, - orgListItemSchema, type WithOrg, } from "../../lib/org-list.js"; import { withProgress } from "../../lib/polling.js"; @@ -72,7 +71,8 @@ import { import { getApiBaseUrl } from "../../lib/sentry-client.js"; import type { ListCommandTarget } from "../../lib/target-positional.js"; import { shellQuote } from "../../lib/utils.js"; -import { type SentryProject, SentryProjectSchema } from "../../types/index.js"; +import type { SentryProject } from "../../types/index.js"; +import { ProjectListItemSchema } from "../../generated/output-schemas/project.js"; /** Extended result type with optional title shown above the table. */ type ProjectListResult = ListResult & { title?: string }; @@ -921,7 +921,7 @@ export const listCommand = buildListCommand("project", { }, jsonTransform: (result: ListResult, fields?: string[]) => jsonTransformListResult(result, fields), - schema: orgListItemSchema(SentryProjectSchema), + schema: ProjectListItemSchema, }, parameters: { positional: listTargetPositional({ names: true, multi: true }), diff --git a/packages/cli/src/commands/project/view.ts b/packages/cli/src/commands/project/view.ts index 3a3e2e9b8..66f8ae85f 100644 --- a/packages/cli/src/commands/project/view.ts +++ b/packages/cli/src/commands/project/view.ts @@ -5,14 +5,6 @@ * Supports monorepos with multiple detected projects. */ -import { - description, - looseObject, - nullable, - object, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { getProject, @@ -47,11 +39,9 @@ import { orgProjectTarget, type TargetContext, } from "../../lib/target-positional.js"; -import { - type SentryProject, - SentryProjectSchema, - type WithOutputFields, -} from "../../types/index.js"; +import type { SentryProject, WithOutputFields } from "../../types/index.js"; +import { ProjectViewOutputSchema } from "../../generated/output-schemas/project.js"; +import type { ProjectViewOutputFields } from "../../output-schemas/project.js"; type ViewFlags = { readonly json: boolean; @@ -97,11 +87,6 @@ async function handleWebView(resolvedTargets: ResolvedTarget[]): Promise { ); } -/** The field the command adds to each project in its JSON output. */ -const ProjectViewOutputFields = object({ - dsn: pipe(nullable(string()), description("Primary DSN")), -}); - /** * A project entry enriched with its DSN and optional detection source. * This is the data shape returned by the command for both JSON and human output. @@ -375,10 +360,7 @@ export const viewCommand = buildCommand({ output: { human: formatProjectViewHuman, jsonTransform: jsonTransformProjectView, - schema: looseObject({ - ...SentryProjectSchema.entries, - ...ProjectViewOutputFields.entries, - }), + schema: ProjectViewOutputSchema, }, parameters: { positional: { diff --git a/packages/cli/src/commands/release/archive.ts b/packages/cli/src/commands/release/archive.ts index c41f472d3..d9ac6da89 100644 --- a/packages/cli/src/commands/release/archive.ts +++ b/packages/cli/src/commands/release/archive.ts @@ -17,11 +17,9 @@ import { } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; -import { - type ReleaseUpdateOutput, - ReleaseUpdateOutputSchema, -} from "../../types/index.js"; +import type { ReleaseUpdateOutput } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseUpdateOutputSchema } from "../../generated/output-schemas/release.js"; const USAGE_HINT = "sentry release archive [/]"; diff --git a/packages/cli/src/commands/release/create.ts b/packages/cli/src/commands/release/create.ts index a089e4985..7e0ff224b 100644 --- a/packages/cli/src/commands/release/create.ts +++ b/packages/cli/src/commands/release/create.ts @@ -5,16 +5,6 @@ */ import { inlineCode, text } from "@sentry/toolkit-core/markdown"; -import { - array, - description, - looseObject, - object, - optional, - pipe, - string, - union, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { createRelease } from "../../lib/api-client.js"; import { buildCommand } from "../../lib/command.js"; @@ -30,42 +20,13 @@ import { } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; -import { - DryRunOutputField, - type SentryRelease, - SentryReleaseSchema, - type WithOutputFields, -} from "../../types/index.js"; +import type { SentryRelease, WithOutputFields } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseCreateOutputSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseCreateOutputFields } from "../../output-schemas/release.js"; const USAGE_HINT = "sentry release create [/]"; -/** - * The fields `--dry-run` changes on the release it reports: the `dryRun` - * flag, and `projects` as `{ slug }` objects instead of full projects. - */ -const ReleaseCreateOutputFields = object({ - dryRun: DryRunOutputField, - projects: optional( - pipe( - union([ - SentryReleaseSchema.entries.projects.wrapped, - array(object({ slug: pipe(string(), description("Project slug")) })), - ]), - description("Projects in the release (only slug with --dry-run)"), - ), - ), -}); - -/** - * JSON output: the created release, or with `--dry-run` the release that - * would be created, in the same shape. - */ -const ReleaseCreateOutputSchema = looseObject({ - ...SentryReleaseSchema.entries, - ...ReleaseCreateOutputFields.entries, -}); - /** The release `--dry-run` reports: the request body, shaped like a release. */ type ReleaseCreateDryRun = WithOutputFields< Pick, diff --git a/packages/cli/src/commands/release/delete.ts b/packages/cli/src/commands/release/delete.ts index 5fa4b89a3..d318769a1 100644 --- a/packages/cli/src/commands/release/delete.ts +++ b/packages/cli/src/commands/release/delete.ts @@ -8,14 +8,6 @@ */ import { inlineCode } from "@sentry/toolkit-core/markdown"; -import { - boolean, - description, - type InferOutput, - object, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { deleteRelease, getRelease } from "../../lib/api-client.js"; import { ApiError } from "../../lib/errors.js"; @@ -27,20 +19,13 @@ import { isConfirmationBypassed, } from "../../lib/mutate-command.js"; import { buildReleaseUrl } from "../../lib/sentry-web-urls.js"; -import { DryRunOutputField } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseDeleteOutputSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseDeleteOutput } from "../../output-schemas/release.js"; const USAGE_HINT = "sentry release delete [/]"; -/** JSON output: the release that was (or, with `--dry-run`, would be) deleted. */ -const DeleteOutputSchema = object({ - deleted: pipe(boolean(), description("Whether the release was deleted")), - org: pipe(string(), description("Organization slug")), - version: pipe(string(), description("Release version")), - dryRun: DryRunOutputField, -}); - -type DeleteResult = InferOutput; +type DeleteResult = ReleaseDeleteOutput; function formatReleaseDeleted(result: DeleteResult): string { if (result.dryRun) { @@ -112,7 +97,7 @@ export const deleteCommand = buildDeleteCommand({ }, output: { human: formatReleaseDeleted, - schema: DeleteOutputSchema, + schema: ReleaseDeleteOutputSchema, }, parameters: { positional: { diff --git a/packages/cli/src/commands/release/deploy.ts b/packages/cli/src/commands/release/deploy.ts index 3456c6f06..e1d509594 100644 --- a/packages/cli/src/commands/release/deploy.ts +++ b/packages/cli/src/commands/release/deploy.ts @@ -6,14 +6,6 @@ */ import { inlineCode } from "@sentry/toolkit-core/markdown"; -import { - description, - looseObject, - object, - optional, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { createReleaseDeploy } from "../../lib/api-client.js"; import { buildCommand, numberParser } from "../../lib/command.js"; @@ -27,29 +19,19 @@ import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { formatRelativeTime } from "../../lib/formatters/time-utils.js"; import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; -import { - DryRunOutputField, - type SentryDeploy, - SentryDeploySchema, - type WithOutputFields, -} from "../../types/index.js"; +import type { SentryDeploy, WithOutputFields } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseDeployOutputSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseDeployOutputFields } from "../../output-schemas/release.js"; const USAGE_HINT = "sentry release deploy [/] [name]"; -/** - * Fields `--dry-run` changes: it prints the deploy that would be created, - * which has no `id` yet, with its release `version`. - */ -const DeployOutputFields = object({ - id: optional(SentryDeploySchema.entries.id), - dryRun: DryRunOutputField, - version: optional(pipe(string(), description("Release version (--dry-run)"))), -}); - /** JSON output: the created deploy, or the `--dry-run` preview. */ -type DeployOutput = WithOutputFields; +type DeployOutput = WithOutputFields< + SentryDeploy, + typeof ReleaseDeployOutputFields +>; function formatDeployCreated(deploy: DeployOutput): string { if (deploy.dryRun) { @@ -129,10 +111,7 @@ export const deployCommand = buildCommand({ }, output: { human: formatDeployCreated, - schema: looseObject({ - ...SentryDeploySchema.entries, - ...DeployOutputFields.entries, - }), + schema: ReleaseDeployOutputSchema, }, parameters: { positional: { diff --git a/packages/cli/src/commands/release/deploys.ts b/packages/cli/src/commands/release/deploys.ts index 590466039..35827b5ab 100644 --- a/packages/cli/src/commands/release/deploys.ts +++ b/packages/cli/src/commands/release/deploys.ts @@ -10,8 +10,9 @@ import { buildCommand } from "../../lib/command.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { type Column, formatTable } from "../../lib/formatters/table.js"; import { formatRelativeTime } from "../../lib/formatters/time-utils.js"; -import { type SentryDeploy, SentryDeploySchema } from "../../types/index.js"; +import type { SentryDeploy } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { SentryDeploySchema } from "../../generated/output-schemas/release.js"; const USAGE_HINT = "sentry release deploys [/]"; diff --git a/packages/cli/src/commands/release/finalize.ts b/packages/cli/src/commands/release/finalize.ts index 6c28ceb9f..ca01ac49e 100644 --- a/packages/cli/src/commands/release/finalize.ts +++ b/packages/cli/src/commands/release/finalize.ts @@ -5,14 +5,6 @@ */ import { inlineCode, text } from "@sentry/toolkit-core/markdown"; -import { - description, - looseObject, - object, - optional, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { updateRelease } from "../../lib/api-client.js"; import { buildCommand } from "../../lib/command.js"; @@ -24,28 +16,17 @@ import { } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; -import { - ReleaseUpdateOutputFields, - type SentryRelease, - SentryReleaseSchema, - type WithOutputFields, -} from "../../types/index.js"; +import type { SentryRelease, WithOutputFields } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseFinalizeOutputSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseFinalizeOutputFields } from "../../output-schemas/release.js"; const USAGE_HINT = "sentry release finalize [/]"; -/** Fields `--dry-run` prints instead of the finalized release. */ -const FinalizeOutputFields = object({ - ...ReleaseUpdateOutputFields.entries, - released: optional( - pipe(string(), description("Release date to set (--dry-run)")), - ), -}); - /** JSON output: the finalized release, or the `--dry-run` preview. */ type FinalizeOutput = WithOutputFields< SentryRelease, - typeof FinalizeOutputFields + typeof ReleaseFinalizeOutputFields >; function formatReleaseFinalized(release: FinalizeOutput): string { @@ -91,10 +72,7 @@ export const finalizeCommand = buildCommand({ }, output: { human: formatReleaseFinalized, - schema: looseObject({ - ...SentryReleaseSchema.entries, - ...FinalizeOutputFields.entries, - }), + schema: ReleaseFinalizeOutputSchema, }, parameters: { positional: { diff --git a/packages/cli/src/commands/release/list.ts b/packages/cli/src/commands/release/list.ts index d39030a47..fdcf83040 100644 --- a/packages/cli/src/commands/release/list.ts +++ b/packages/cli/src/commands/release/list.ts @@ -6,14 +6,6 @@ */ import { text } from "@sentry/toolkit-core/markdown"; -import { - description, - looseObject, - object, - optional, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { type ListReleasesOptions, @@ -46,7 +38,6 @@ import { jsonTransformListResult, type ListResult, type OrgListConfig, - OrgListItemOutputFields, } from "../../lib/org-list.js"; import { type ResolvedTarget, @@ -55,25 +46,15 @@ import { } from "../../lib/resolve-target.js"; import { buildReleaseUrl } from "../../lib/sentry-web-urls.js"; import type { ListCommandTarget } from "../../lib/target-positional.js"; -import { - type SentryRelease, - SentryReleaseSchema, - type WithOutputFields, -} from "../../types/index.js"; +import type { SentryRelease, WithOutputFields } from "../../types/index.js"; import { fmtCrashFree } from "./view.js"; +import { ReleaseListItemSchema } from "../../generated/output-schemas/release.js"; +import type { ReleaseListItemOutputFields } from "../../output-schemas/release.js"; const log = logger.withTag("release.list"); export const PAGINATION_KEY = "release-list"; -/** Fields the list adds to each release: its org and, when listing several projects, its project. */ -const ReleaseListItemOutputFields = object({ - ...OrgListItemOutputFields.entries, - targetProject: optional( - pipe(string(), description("Project slug, when listing several")), - ), -}); - type ReleaseWithOrg = WithOutputFields< SentryRelease, typeof ReleaseListItemOutputFields @@ -701,10 +682,7 @@ export const listCommand = buildListCommand("release", { human: formatListHuman, jsonTransform: (result: ListResult, fields?: string[]) => jsonTransformListResult(result, fields), - schema: looseObject({ - ...SentryReleaseSchema.entries, - ...ReleaseListItemOutputFields.entries, - }), + schema: ReleaseListItemSchema, }, parameters: { positional: LIST_ORG_TARGET_POSITIONAL, diff --git a/packages/cli/src/commands/release/restore.ts b/packages/cli/src/commands/release/restore.ts index 52c6f4d0a..96ff504c5 100644 --- a/packages/cli/src/commands/release/restore.ts +++ b/packages/cli/src/commands/release/restore.ts @@ -16,11 +16,9 @@ import { } from "../../lib/formatters/markdown.js"; import { CommandOutput } from "../../lib/formatters/output.js"; import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; -import { - type ReleaseUpdateOutput, - ReleaseUpdateOutputSchema, -} from "../../types/index.js"; +import type { ReleaseUpdateOutput } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { ReleaseUpdateOutputSchema } from "../../generated/output-schemas/release.js"; const USAGE_HINT = "sentry release restore [/]"; diff --git a/packages/cli/src/commands/release/set-commits.ts b/packages/cli/src/commands/release/set-commits.ts index 6e62012ee..e9837c72a 100644 --- a/packages/cli/src/commands/release/set-commits.ts +++ b/packages/cli/src/commands/release/set-commits.ts @@ -34,8 +34,9 @@ import { isShallowRepository, } from "../../lib/git.js"; import { logger } from "../../lib/logger.js"; -import { type SentryRelease, SentryReleaseSchema } from "../../types/index.js"; +import type { SentryRelease } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { SentryReleaseSchema } from "../../generated/output-schemas/release.js"; const log = logger.withTag("release.set-commits"); diff --git a/packages/cli/src/commands/release/view.ts b/packages/cli/src/commands/release/view.ts index e013019ea..aa2b15acf 100644 --- a/packages/cli/src/commands/release/view.ts +++ b/packages/cli/src/commands/release/view.ts @@ -23,8 +23,9 @@ import { FRESH_ALIASES, FRESH_FLAG, } from "../../lib/list-command.js"; -import { type SentryRelease, SentryReleaseSchema } from "../../types/index.js"; +import type { SentryRelease } from "../../types/index.js"; import { type ReleaseTarget, releaseParameter } from "./parse.js"; +import { SentryReleaseSchema } from "../../generated/output-schemas/release.js"; const USAGE_HINT = "sentry release view [/]"; diff --git a/packages/cli/src/commands/replay/list.ts b/packages/cli/src/commands/replay/list.ts index c25df646a..5a5d0e079 100644 --- a/packages/cli/src/commands/replay/list.ts +++ b/packages/cli/src/commands/replay/list.ts @@ -59,11 +59,8 @@ import { type TimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { - REPLAY_LIST_FIELDS, - type ReplayListItem, - ReplayListItemOutputSchema, -} from "../../types/index.js"; +import { REPLAY_LIST_FIELDS, type ReplayListItem } from "../../types/index.js"; +import { ReplayListItemOutputSchema } from "../../generated/output-schemas/replay.js"; type ListFlags = { readonly environment?: readonly string[]; diff --git a/packages/cli/src/commands/replay/view.ts b/packages/cli/src/commands/replay/view.ts index f5ab631f0..8b3a574c8 100644 --- a/packages/cli/src/commands/replay/view.ts +++ b/packages/cli/src/commands/replay/view.ts @@ -51,7 +51,7 @@ import type { ReplayRelatedIssue, ReplayRelatedTrace, } from "../../types/index.js"; -import { ReplayViewOutputSchema } from "../../types/index.js"; +import { ReplayViewOutputSchema } from "../../generated/output-schemas/replay.js"; type ViewFlags = { readonly json: boolean; diff --git a/packages/cli/src/commands/repo/list.ts b/packages/cli/src/commands/repo/list.ts index 377fbef2c..cec1a3f89 100644 --- a/packages/cli/src/commands/repo/list.ts +++ b/packages/cli/src/commands/repo/list.ts @@ -21,10 +21,8 @@ import { type OrgListCommandDocs, } from "../../lib/list-command.js"; import type { OrgListConfig, WithOrg } from "../../lib/org-list.js"; -import { - type SentryRepository, - SentryRepositorySchema, -} from "../../types/index.js"; +import type { SentryRepository } from "../../types/index.js"; +import { RepositoryListItemSchema } from "../../generated/output-schemas/repo.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "repo-list"; @@ -45,7 +43,7 @@ const REPO_COLUMNS: Column[] = [ const repoListConfig: OrgListConfig< SentryRepository, RepositoryWithOrg, - typeof SentryRepositorySchema + typeof RepositoryListItemSchema > = { paginationKey: PAGINATION_KEY, entityPlural: "repositories", @@ -62,7 +60,7 @@ const repoListConfig: OrgListConfig< searchesNames: true, displayTable: (repos: RepositoryWithOrg[]) => formatTable(repos, REPO_COLUMNS), - schema: SentryRepositorySchema, + schema: RepositoryListItemSchema, }; const docs: OrgListCommandDocs = { diff --git a/packages/cli/src/commands/span/list.ts b/packages/cli/src/commands/span/list.ts index 0e5a72b91..c9c5aed5a 100644 --- a/packages/cli/src/commands/span/list.ts +++ b/packages/cli/src/commands/span/list.ts @@ -76,7 +76,7 @@ import { type TraceTargetInput, warnIfNormalized, } from "../../lib/trace-target.js"; -import { FlatSpanSchema } from "../../types/index.js"; +import { FlatSpanSchema } from "../../generated/output-schemas/span.js"; type ListFlags = { readonly limit: number; diff --git a/packages/cli/src/commands/team/list.ts b/packages/cli/src/commands/team/list.ts index b593c5fd0..9dda8cdf3 100644 --- a/packages/cli/src/commands/team/list.ts +++ b/packages/cli/src/commands/team/list.ts @@ -22,7 +22,8 @@ import { type OrgListCommandDocs, } from "../../lib/list-command.js"; import type { OrgListConfig, WithOrg } from "../../lib/org-list.js"; -import { type SentryTeam, SentryTeamSchema } from "../../types/index.js"; +import type { SentryTeam } from "../../types/index.js"; +import { TeamListItemSchema } from "../../generated/output-schemas/team.js"; /** Command key for pagination cursor storage */ export const PAGINATION_KEY = "team-list"; @@ -46,7 +47,7 @@ const TEAM_COLUMNS: Column[] = [ const teamListConfig: OrgListConfig< SentryTeam, TeamWithOrg, - typeof SentryTeamSchema + typeof TeamListItemSchema > = { paginationKey: PAGINATION_KEY, entityPlural: "teams", @@ -58,7 +59,7 @@ const teamListConfig: OrgListConfig< searchesNames: true, displayTable: (teams: TeamWithOrg[]) => formatTable(teams, TEAM_COLUMNS), listForProject: (org, project) => listProjectTeams(org, project), - schema: SentryTeamSchema, + schema: TeamListItemSchema, }; const docs: OrgListCommandDocs = { diff --git a/packages/cli/src/commands/trace/list.ts b/packages/cli/src/commands/trace/list.ts index ae0bba6d8..38b58a82c 100644 --- a/packages/cli/src/commands/trace/list.ts +++ b/packages/cli/src/commands/trace/list.ts @@ -44,10 +44,8 @@ import { type TimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { - type TransactionListItem, - TransactionListItemSchema, -} from "../../types/index.js"; +import type { TransactionListItem } from "../../types/index.js"; +import { TransactionListItemSchema } from "../../generated/output-schemas/trace.js"; type ListFlags = { readonly limit: number; diff --git a/packages/cli/src/commands/trial/list.ts b/packages/cli/src/commands/trial/list.ts index 44f341ce5..dcc985903 100644 --- a/packages/cli/src/commands/trial/list.ts +++ b/packages/cli/src/commands/trial/list.ts @@ -6,16 +6,6 @@ * plan-level upgrade trials. */ -import { - description, - type InferOutput, - nullable, - number, - object, - picklist, - pipe, - string, -} from "valibot"; import type { SentryContext } from "../../context.js"; import { getCustomerTrialInfo } from "../../lib/api-client.js"; import { buildCommand } from "../../lib/command.js"; @@ -32,46 +22,17 @@ import { getTrialStatus, type TrialStatus, } from "../../lib/trials.js"; -import { - type CustomerTrialInfo, - ProductTrialSchema, - type Writer, -} from "../../types/index.js"; +import type { CustomerTrialInfo, Writer } from "../../types/index.js"; +import { TrialListEntrySchema } from "../../generated/output-schemas/trial.js"; +import type { TrialListEntryOutput } from "../../output-schemas/trial.js"; type ListFlags = { readonly json: boolean; readonly fields?: string[]; }; -const { category, isStarted, lengthDays, startDate, endDate } = - ProductTrialSchema.pipe[0].entries; - -/** - * JSON output of one trial: the API trial's fields plus the ones the CLI - * derives (name, status, daysRemaining). - */ -const TrialListEntrySchema = object({ - name: pipe( - string(), - description('CLI trial name (e.g. seer), or "plan" for the plan trial'), - ), - category, - status: pipe( - picklist(["available", "active", "expired"]), - description("Trial status"), - ), - daysRemaining: pipe( - nullable(number()), - description("Days left on an active trial"), - ), - isStarted, - lengthDays, - startDate, - endDate, -}); - /** A trial for display: the JSON fields plus its human-only display name. */ -type TrialListEntry = InferOutput & { +type TrialListEntry = TrialListEntryOutput & { /** Human-readable product name (e.g., "Seer") or plan upgrade name */ displayName: string; }; diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index 03f295630..40464d57b 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -59,8 +59,6 @@ import { CommandOutput, type CommandReturn, type CommandYield, - extractSchemaFieldPaths, - extractSchemaFields, formatSchemaForHelp, type HumanRenderer, type OutputConfig, @@ -430,17 +428,14 @@ export function applyOrgProjectFlags( */ // oxlint-disable-next-line typescript/no-explicit-any -- OutputConfig type is erased at the builder level function buildFieldsFlag(outputConfig?: OutputConfig) { - if (!outputConfig?.schema) { + const schema = outputConfig?.schema; + if (!schema?.fields.length) { return FIELDS_FLAG; } - const schemaFields = extractSchemaFields(outputConfig.schema); - if (schemaFields.length === 0) { - return FIELDS_FLAG; - } - const fieldNames = schemaFields.map((f) => f.name).join(", "); + const fieldNames = schema.fields.map((f) => f.name).join(", "); return { ...FIELDS_FLAG, - parse: choiceListParser(extractSchemaFieldPaths(outputConfig.schema)), + parse: choiceListParser(schema.paths), brief: `${FIELDS_FLAG.brief}. Available: ${fieldNames}`, }; } @@ -455,11 +450,8 @@ function enrichDocsWithSchema( // oxlint-disable-next-line typescript/no-explicit-any -- OutputConfig type is erased at the builder level outputConfig?: OutputConfig, ): CommandDocumentation { - if (!outputConfig?.schema) { - return docs; - } - const schemaFields = extractSchemaFields(outputConfig.schema); - if (schemaFields.length === 0) { + const schemaFields = outputConfig?.schema?.fields; + if (!schemaFields?.length) { return docs; } const jsonFieldsDoc = formatSchemaForHelp(schemaFields); @@ -983,12 +975,12 @@ export function buildCommand< (cmd as unknown as Record).__destructive = true; } - // Attach the JSON schema to the built command as a non-standard property. + // Attach the JSON fields to the built command as a non-standard property. // introspect.ts reads this to populate CommandInfo.jsonFields for help // output and SKILL.md generation. if (outputConfig?.schema) { - (cmd as unknown as Record).__jsonSchema = - outputConfig.schema; + (cmd as unknown as Record).__jsonFields = + outputConfig.schema.fields; } // Expose the unwrapped generator for internal dispatchers (e.g. bare diff --git a/packages/cli/src/lib/db/accounts.ts b/packages/cli/src/lib/db/accounts.ts index 1706f9eed..41b8f70af 100644 --- a/packages/cli/src/lib/db/accounts.ts +++ b/packages/cli/src/lib/db/accounts.ts @@ -10,7 +10,7 @@ import { isSaaSTrustOrigin } from "@sentry/toolkit-core/sentry-origin"; import { uuidv7 } from "uuidv7"; import type { InferOutput } from "valibot"; -import type { AccountSummarySchema } from "../../types/account.js"; +import type { AccountSummarySchema } from "../../output-schemas/account.js"; import { normalizeUrl } from "../constants.js"; import { ValidationError } from "../errors.js"; import { fuzzyMatch } from "../fuzzy.js"; diff --git a/packages/cli/src/lib/formatters/dashboard.ts b/packages/cli/src/lib/formatters/dashboard.ts index cd8c6819a..f783f76b3 100644 --- a/packages/cli/src/lib/formatters/dashboard.ts +++ b/packages/cli/src/lib/formatters/dashboard.ts @@ -14,7 +14,6 @@ import wrapAnsi from "wrap-ansi"; import type { InferOutput } from "valibot"; import type { - DashboardViewOutputSchema, ScalarResult, TableResult, TimeseriesResult, @@ -354,6 +353,7 @@ import { formatCompactWithUnit, formatWithUnit, } from "./numbers.js"; +import type { DashboardViewOutputSchema } from "../../output-schemas/dashboard.js"; /** * Format a value as a short Y-axis tick label (max ~4 chars). diff --git a/packages/cli/src/lib/formatters/issue.ts b/packages/cli/src/lib/formatters/issue.ts index bd2943218..e346ade89 100644 --- a/packages/cli/src/lib/formatters/issue.ts +++ b/packages/cli/src/lib/formatters/issue.ts @@ -3,11 +3,12 @@ */ import type { InferOutput } from "valibot"; -import type { IssueViewOutputFields, SentryIssue } from "../../types/index.js"; +import type { SentryIssue } from "../../types/index.js"; import { getReplayIdFromEvent } from "../replay-search.js"; import { formatEventDetails, formatIssueDetails } from "./human.js"; import { filterFieldsIfSet } from "./json.js"; import { renderMarkdown } from "./markdown.js"; +import type { IssueViewOutputFields } from "../../output-schemas/issue.js"; /** * Data rendered for one issue: the issue, and the fields JSON output adds to diff --git a/packages/cli/src/lib/formatters/output.ts b/packages/cli/src/lib/formatters/output.ts index a347933d2..27178ccfc 100644 --- a/packages/cli/src/lib/formatters/output.ts +++ b/packages/cli/src/lib/formatters/output.ts @@ -19,7 +19,7 @@ * formatter — there is no divergent-data path. */ -import { type GenericSchema, getDescription, type InferOutput } from "valibot"; +import type { GenericSchema, InferOutput } from "valibot"; import type { Writer } from "../../types/index.js"; import { plainSafeMuted } from "./human.js"; import { filterFields, formatJson } from "./json.js"; @@ -209,10 +209,13 @@ type OutputConfigBase = { * When present, `--json` and `--fields` flags are injected and the wrapper * auto-renders yielded {@link CommandOutput} values. * - * `schema` is a valibot schema describing the JSON output. Declare it once - * and derive the command's output type from it; see "Declaring Command - * Output" in `packages/cli/AGENTS.md`. It drives `--help`, `sentry help - * `, `--fields` completion, and the SKILL.md field tables. + * `schema` describes the JSON output: the build-time copy of a valibot + * schema in `src/output-schemas/`, imported from + * `src/generated/output-schemas/` (see {@link OutputSchemaFields}). Declare + * the schema once and derive the command's output type from it; see + * "Declaring Command Output" in `packages/cli/AGENTS.md`. It drives + * `--help`, `sentry help `, `--fields` completion, and the SKILL.md + * field tables. * * Without `jsonTransform`, the data (each item for array data) must satisfy * `schema`, so a documented field the command doesn't produce is a compile @@ -222,7 +225,8 @@ type OutputConfigBase = { * * @typeParam T - Type of data the command yields (used by `human` formatter * and serialized as-is to JSON) - * @typeParam S - Type of `schema`, inferred by the command builders + * @typeParam S - The valibot schema `schema` was read from, inferred by the + * command builders * @typeParam R - Type `jsonTransform` returns, inferred by the builders */ export type OutputConfig< @@ -231,7 +235,10 @@ export type OutputConfig< R = unknown, > = OutputConfigBase & ( - | { jsonTransform?: undefined; schema?: S & SchemaMatches } + | { + jsonTransform?: undefined; + schema?: OutputSchemaFields & SchemaMatches; + } | { /** * Custom JSON serialization transform. @@ -247,7 +254,7 @@ export type OutputConfig< * When `jsonTransform` is set, `jsonExclude` is ignored. */ jsonTransform: (data: T, fields?: string[]) => R; - schema?: S & TransformSchemaMatches; + schema?: OutputSchemaFields & TransformSchemaMatches; } ); @@ -444,9 +451,10 @@ export function renderCommandOutput( // --------------------------------------------------------------------------- /** - * Field metadata extracted from a Zod schema for documentation. + * Metadata of one top-level field of an output schema. * - * Populated by {@link extractSchemaFields} and consumed by: + * Read from the valibot schema at build time (`script/lib/output-schema-fields.ts`) + * and consumed by: * - `introspect.ts` → `CommandInfo.jsonFields` * - `help.ts` → human help output * - `generate-skill.ts` → SKILL.md field tables @@ -462,221 +470,30 @@ export type SchemaFieldInfo = { optional: boolean; }; -/** Minimal structural view of a valibot schema's runtime shape. */ -type ValibotSchemaNode = { - type: string; - /** Inner schema for wrapper types (optional / nullable / nullish). */ - wrapped?: ValibotSchemaNode; - /** Member schemas for union / variant / picklist. */ - options?: unknown[]; - /** Item schema for array. */ - item?: ValibotSchemaNode; - /** Field schemas for object / loose_object. */ - entries?: Record; - /** - * Pipe steps for a `SchemaWithPipe` (e.g. `pipe(string(), description(...))` - * or the `pipe(unknown(), transform(Number), number())` coercion pattern). - * Each step carries a `kind` of `"schema"`, `"validation"`, `"transformation"`, - * or `"metadata"`. - */ - pipe?: Array<{ type: string; kind: string }>; -}; - -/** - * Resolve a piped schema (`pipe(...)`) to the node whose `type` reflects its - * output — the last step with `kind === "schema"`. For the coercion pattern - * `pipe(unknown(), transform(Number), number())` this is `number()`, not the - * leading `unknown()`. Non-piped schemas are returned unchanged. - */ -function unwrapPipe(schema: ValibotSchemaNode): ValibotSchemaNode { - if (!schema.pipe?.length) { - return schema; - } - const schemaSteps = schema.pipe.filter((step) => step.kind === "schema"); - const last = schemaSteps.at(-1); - return (last as ValibotSchemaNode | undefined) ?? schema; -} - -/** Leaf-type name mapping for {@link valibotTypeToString}. */ -const VALIBOT_TYPE_MAP: Record = { - string: "string", - number: "number", - boolean: "boolean", - object: "object", - loose_object: "object", - array: "array", - record: "object", - null: "null", - unknown: "unknown", - any: "any", - picklist: "string", - enum: "string", - literal: "string", -}; - -/** - * Resolve a valibot `union` into a deduplicated `" | "`-joined type string. - * - * Used by auto-generated `@sentry/api/valibot` schemas that represent nullable - * fields as `union([string(), null_()])` instead of `nullable(string())`. - */ -function resolveValibotUnion(options: ValibotSchemaNode[]): { - type: string; - optional: boolean; -} { - let optional = false; - const parts: string[] = []; - for (const opt of options) { - const resolved = valibotTypeToString(opt); - if (resolved.optional) { - optional = true; - } - if (!parts.includes(resolved.type)) { - parts.push(resolved.type); - } - } - return { type: parts.join(" | "), optional }; -} - -/** - * Map a valibot schema's runtime `type` to a human-readable string. - * - * Unwraps wrapper types (optional, nullable, nullish) and builds a composite - * type string (e.g. "string | null" for `nullable(string())`). Delegates - * union handling to {@link resolveValibotUnion}. - */ -function valibotTypeToString(input: ValibotSchemaNode): { - type: string; - optional: boolean; -} { - // Resolve `pipe(...)` schemas (incl. the coercion pattern) to their output - // schema before inspecting the type. - const schema = input ? unwrapPipe(input) : input; - if (!schema?.type) { - return { type: "unknown", optional: false }; - } - - // Unwrap wrapper types recursively. - if (schema.type === "optional" && schema.wrapped) { - const inner = valibotTypeToString(schema.wrapped); - return { type: inner.type, optional: true }; - } - if (schema.type === "nullable" && schema.wrapped) { - const inner = valibotTypeToString(schema.wrapped); - const nullableType = inner.type.includes(" | null") - ? inner.type - : `${inner.type} | null`; - return { type: nullableType, optional: inner.optional }; - } - if (schema.type === "nullish" && schema.wrapped) { - const inner = valibotTypeToString(schema.wrapped); - const nullableType = inner.type.includes(" | null") - ? inner.type - : `${inner.type} | null`; - return { type: nullableType, optional: true }; - } - if ( - (schema.type === "union" || schema.type === "variant") && - schema.options?.length - ) { - return resolveValibotUnion(schema.options as ValibotSchemaNode[]); - } - - return { type: VALIBOT_TYPE_MAP[schema.type] ?? "unknown", optional: false }; -} - /** - * Extract field metadata from a valibot object schema. + * What the CLI needs at runtime from a command's output schema, read from it + * at build time: its top-level fields and every `--fields` path. * - * Returns an array of {@link SchemaFieldInfo} describing each top-level - * field's name, type, description, and optionality. Returns an empty - * array for non-object schemas. + * The schemas themselves live in `src/output-schemas/`, which only the build + * loads. `script/generate-output-schemas.ts` writes one of these for each of + * their exports to `src/generated/output-schemas/`, under the same name. * - * @param schema - A valibot schema (typically `object({...})`) + * @typeParam S - The valibot schema it was read from. Type only: commands + * derive their output type from it, and {@link OutputConfig} checks the + * command's data against it. */ -export function extractSchemaFields(schema: GenericSchema): SchemaFieldInfo[] { - const node = schema as unknown as ValibotSchemaNode; - - if (node.type !== "object" && node.type !== "loose_object") { - return []; - } - - const entries = node.entries; - if (!entries) { - return []; - } - - return Object.entries(entries).map(([name, fieldSchema]) => { - const { type, optional } = valibotTypeToString(fieldSchema); - return { - name, - type, - description: findDescription(fieldSchema), - optional, - }; - }); -} - -/** Wrapper types {@link objectsOf} looks through to the schema they hold. */ -const WRAPPER_TYPES = new Set(["optional", "nullable", "nullish", "array"]); - -/** - * The object schemas a value of `schema` can be: through pipes, wrappers, - * array items (`--fields` paths reach into arrays), and union and variant - * members. - */ -function objectsOf(schema: ValibotSchemaNode): ValibotSchemaNode[] { - const node = unwrapPipe(schema); - if (WRAPPER_TYPES.has(node.type)) { - const inner = node.wrapped ?? node.item; - return inner ? objectsOf(inner) : []; - } - if (node.type === "union" || node.type === "variant") { - return (node.options as ValibotSchemaNode[]).flatMap(objectsOf); - } - return node.entries ? [node] : []; -} - -/** - * Every field path a valibot schema describes, in `--fields` dot notation: - * each top-level field, then the fields of nested objects - * (`metadata.title`), parents before children. - * - * @param schema - A valibot schema (typically `object({...})`) - */ -export function extractSchemaFieldPaths(schema: GenericSchema): string[] { - const paths = new Set(); - const visit = (node: ValibotSchemaNode, prefix: string) => { - for (const { entries = {} } of objectsOf(node)) { - for (const [name, field] of Object.entries(entries)) { - paths.add(`${prefix}${name}`); - visit(field, `${prefix}${name}.`); - } - } - }; - visit(schema as unknown as ValibotSchemaNode, ""); - return [...paths]; -} +export type OutputSchemaFields = { + /** Top-level fields, for `--help`, `sentry help ` and the skill. */ + readonly fields: readonly SchemaFieldInfo[]; + /** Every field path in `--fields` dot notation, parents before children. */ + readonly paths: readonly string[]; + /** Never set; carries the schema's type. */ + readonly "~schema"?: S; +}; -/** - * Find a `description()` pipe action for a field schema. - * - * `getDescription` does not recurse, and the description may sit under one or - * more wrapper schemas — e.g. `optional(nullable(pipe(string(), description(...))))` - * places it two `.wrapped` levels down. Walk the wrapper chain until a - * description is found. - */ -function findDescription(schema: ValibotSchemaNode): string | undefined { - let node: ValibotSchemaNode | undefined = schema; - while (node) { - const description = getDescription(node as unknown as GenericSchema); - if (description !== undefined) { - return description; - } - node = node.wrapped; - } - return; -} +/** The valibot schema type an {@link OutputSchemaFields} was read from. */ +export type SchemaOfFields = + F extends OutputSchemaFields ? S : never; /** * Format schema fields as a help text block for `--help` output. @@ -688,7 +505,9 @@ function findDescription(schema: ValibotSchemaNode): string | undefined { * count (string, optional) — Total event count * ``` */ -export function formatSchemaForHelp(fields: SchemaFieldInfo[]): string { +export function formatSchemaForHelp( + fields: readonly SchemaFieldInfo[], +): string { if (fields.length === 0) { return ""; } diff --git a/packages/cli/src/lib/formatters/replay.ts b/packages/cli/src/lib/formatters/replay.ts index 459799a33..6d1a1ed87 100644 --- a/packages/cli/src/lib/formatters/replay.ts +++ b/packages/cli/src/lib/formatters/replay.ts @@ -13,7 +13,6 @@ import type { ReplayDetails, ReplayRelatedIssue, ReplayRelatedTrace, - ReplayViewOutputFields, } from "../../types/index.js"; import { getReplayUserLabel } from "../replay-search.js"; import { buildReplayUrl } from "../sentry-web-urls.js"; @@ -22,6 +21,7 @@ import { formatDurationCompactMs, formatDurationVerbose, } from "./time-utils.js"; +import type { ReplayViewOutputFields } from "../../output-schemas/replay.js"; /** * Data bag assembled by replay view before rendering: the replay plus the diff --git a/packages/cli/src/lib/formatters/trace.ts b/packages/cli/src/lib/formatters/trace.ts index 56d6d62e2..a9bf21040 100644 --- a/packages/cli/src/lib/formatters/trace.ts +++ b/packages/cli/src/lib/formatters/trace.ts @@ -8,7 +8,6 @@ import { tableCell, text } from "@sentry/toolkit-core/markdown"; import type { InferOutput } from "valibot"; import type { - FlatSpanSchema, SpanListItem, TraceSpan, TransactionListItem, @@ -29,6 +28,7 @@ import { colorizeSql, formatSqlBlock, isDbSpanOp } from "./sql.js"; import { type Column, formatTable } from "./table.js"; import { renderTextTable } from "./text-table.js"; import { computeSpanDurationMs, formatRelativeTime } from "./time-utils.js"; +import type { FlatSpanSchema } from "../../output-schemas/span.js"; /** * Format a duration in milliseconds to a human-readable string. diff --git a/packages/cli/src/lib/introspect.ts b/packages/cli/src/lib/introspect.ts index 7b6f84381..26711cf11 100644 --- a/packages/cli/src/lib/introspect.ts +++ b/packages/cli/src/lib/introspect.ts @@ -21,10 +21,7 @@ import { getCompletionTarget, } from "./completion-target.js"; import type { ApiReference, CommandApiReference } from "./api-schema.js"; -import { - extractSchemaFields, - type SchemaFieldInfo, -} from "./formatters/output.js"; +import type { SchemaFieldInfo } from "./formatters/output.js"; import { fuzzyMatch } from "./fuzzy.js"; // --------------------------------------------------------------------------- @@ -61,11 +58,11 @@ export type Command = { aliases?: Record; }; /** - * JSON output schema attached by `buildCommand` when `output.schema` is set. - * Non-standard property — Stricli doesn't know about it, but introspection - * reads it to populate {@link CommandInfo.jsonFields}. + * JSON output fields attached by `buildCommand` when `output.schema` is + * set. Non-standard property — Stricli doesn't know about it, but + * introspection reads it to populate {@link CommandInfo.jsonFields}. */ - __jsonSchema?: import("valibot").GenericSchema; + __jsonFields?: readonly SchemaFieldInfo[]; /** * Primary Stricli custom usage line, retained by `buildCommand` for * introspection because Stricli does not expose it on the built command. @@ -310,9 +307,6 @@ export function extractFlags( * @param path - Full command path (e.g. "sentry issue list") */ export function buildCommandInfo(cmd: Command, path: string): CommandInfo { - const jsonFields = cmd.__jsonSchema - ? extractSchemaFields(cmd.__jsonSchema) - : undefined; const positionals = extractPositionals(cmd.parameters.positional); const [positional] = positionals; if (cmd.__primaryUsage && positional && positionals.length === 1) { @@ -332,7 +326,7 @@ export function buildCommandInfo(cmd: Command, path: string): CommandInfo { (example) => `# ${example.description}\n${exampleSteps(example).join("\n")}`, ), - jsonFields: jsonFields?.length ? jsonFields : undefined, + jsonFields: cmd.__jsonFields?.length ? [...cmd.__jsonFields] : undefined, ...(cmd.__destructive ? { destructive: true as const } : {}), }; } diff --git a/packages/cli/src/lib/list-command.ts b/packages/cli/src/lib/list-command.ts index 37a5d06fc..758c4a75f 100644 --- a/packages/cli/src/lib/list-command.ts +++ b/packages/cli/src/lib/list-command.ts @@ -33,7 +33,6 @@ import { jsonTransformListResult, type ListResult, type OrgListConfig, - orgListItemSchema, } from "./org-list.js"; import { applyBoundPositionals, @@ -691,7 +690,7 @@ export function buildOrgListCommand( human: (result: ListResult) => formatListHuman(result, config), jsonTransform: (result: ListResult, fields?: string[]) => jsonTransformListResult(result, fields), - schema: config.schema && orgListItemSchema(config.schema), + schema: config.schema, }; return buildListCommand(routeName, { docs, diff --git a/packages/cli/src/lib/org-list.ts b/packages/cli/src/lib/org-list.ts index c6787f9e7..e77b2ad8e 100644 --- a/packages/cli/src/lib/org-list.ts +++ b/packages/cli/src/lib/org-list.ts @@ -30,16 +30,7 @@ * how to render the result — JSON envelope, human table, or custom formatting. */ -import { - description, - type GenericSchema, - looseObject, - type ObjectEntries, - object, - optional, - pipe, - string, -} from "valibot"; +import type { OrgListItemOutputFields } from "../output-schemas/org-list.js"; import type { WithOutputFields } from "../types/index.js"; import { API_MAX_PER_PAGE, @@ -67,7 +58,11 @@ import { withAuthGuard, } from "./errors.js"; import { filterFields } from "./formatters/json.js"; -import type { SchemaMatches } from "./formatters/output.js"; +import type { + OutputSchemaFields, + SchemaMatches, + SchemaOfFields, +} from "./formatters/output.js"; import { paginationHint } from "./list-command.js"; import { fetchByName, @@ -182,32 +177,15 @@ export function jsonTransformListResult( return items; } -/** An object schema (possibly piped) whose entries can be spread. */ -export type OrgListEntitySchema = GenericSchema & { - readonly entries: ObjectEntries; -}; - -/** The field `withOrg` adds to each item of an org-scoped list. */ -export const OrgListItemOutputFields = object({ - orgSlug: optional(pipe(string(), description("Organization slug"))), -}); - -/** An item of an org-scoped list: the entity with the org it came from. */ +/** + * An item of an org-scoped list: the entity with the org it came from. Its + * output schema is `orgListItemSchema(entity)` (`output-schemas/org-list.ts`). + */ export type WithOrg = WithOutputFields< TEntity, typeof OrgListItemOutputFields >; -/** Output schema of an org-scoped list item: the entity's, plus `orgSlug`. */ -export function orgListItemSchema(entity: { - readonly entries: TEntries; -}) { - return looseObject({ - ...entity.entries, - ...OrgListItemOutputFields.entries, - }); -} - /** * Per-target (or per-org) fetch result for budget-aware list commands. * @@ -459,7 +437,7 @@ export type BaseListFlags = { export type OrgListConfig< TEntity, TWithOrg, - TSchema extends OrgListEntitySchema = OrgListEntitySchema, + TSchema extends OutputSchemaFields = OutputSchemaFields, > = ListCommandMeta & { /** * Fetch all entities for one org (non-paginated). @@ -506,13 +484,13 @@ export type OrgListConfig< listForProject?: (orgSlug: string, projectSlug: string) => Promise; /** - * Valibot object schema of the entity. `buildOrgListCommand` adds - * {@link OrgListItemOutputFields} and forwards it to `OutputConfig.schema` - * so `--help`, `sentry help`, and SKILL.md can document available fields. - * `TEntity` must satisfy it, like the data of a command without - * `jsonTransform`. + * Output schema of a list item, `orgListItemSchema(entity)` in + * `src/output-schemas/`. `buildOrgListCommand` forwards it to + * `OutputConfig.schema` so `--help`, `sentry help`, and SKILL.md can + * document available fields. `TEntity` must satisfy it, like the data of a + * command without `jsonTransform`. */ - schema?: TSchema & SchemaMatches; + schema?: TSchema & SchemaMatches>; /** * The names a name filter matches against (e.g. slug and display name). diff --git a/packages/cli/src/types/account.ts b/packages/cli/src/output-schemas/account.ts similarity index 100% rename from packages/cli/src/types/account.ts rename to packages/cli/src/output-schemas/account.ts diff --git a/packages/cli/src/output-schemas/agent-conversation.ts b/packages/cli/src/output-schemas/agent-conversation.ts new file mode 100644 index 000000000..6ea7409e0 --- /dev/null +++ b/packages/cli/src/output-schemas/agent-conversation.ts @@ -0,0 +1,7 @@ +/** + * Output schemas of the `sentry agent-conversation` commands. + */ + +// Also validates the conversations API response at runtime, so it stays in +// `types/conversation.ts`. +export { ConversationListItemSchema } from "../types/conversation.js"; diff --git a/packages/cli/src/commands/alert/output-schemas.ts b/packages/cli/src/output-schemas/alert.ts similarity index 98% rename from packages/cli/src/commands/alert/output-schemas.ts rename to packages/cli/src/output-schemas/alert.ts index 4f45b5884..72c7b72a0 100644 --- a/packages/cli/src/commands/alert/output-schemas.ts +++ b/packages/cli/src/output-schemas/alert.ts @@ -43,8 +43,7 @@ import { string, unknown, } from "valibot"; -import { DryRunOutputField } from "../../types/index.js"; -import type { WithOutputFields } from "../../types/output.js"; +import { DryRunOutputField, type WithOutputFields } from "./output.js"; // Fields the CLI adds to every alert mutation's output. const org = pipe(string(), description("Organization slug")); diff --git a/packages/cli/src/output-schemas/dashboard.ts b/packages/cli/src/output-schemas/dashboard.ts new file mode 100644 index 000000000..8bc53156e --- /dev/null +++ b/packages/cli/src/output-schemas/dashboard.ts @@ -0,0 +1,138 @@ +/** + * Output schemas of the `sentry dashboard` commands. + */ + +import { + array, + boolean, + description, + type InferOutput, + looseObject, + number, + object, + optional, + pipe, + string, +} from "valibot"; +import { + DashboardDetailSchema, + DashboardWidgetLayoutSchema, + DashboardWidgetQuerySchema, + DashboardWidgetSchema, + WidgetDataResultSchema, +} from "../types/dashboard.js"; +import { DryRunOutputField } from "./output.js"; + +// Also validates the revisions API response at runtime, so it stays in +// `types/dashboard.ts`. +export { DashboardRevisionSchema } from "../types/dashboard.js"; + +/** Schema for dashboard list items (lightweight, from GET /dashboards/) */ +export const DashboardListItemSchema = looseObject({ + id: string(), + title: string(), + dateCreated: optional(string()), + createdBy: optional( + object({ + name: optional(string()), + email: optional(string()), + }), + ), + widgetDisplay: optional(array(string())), +}); + +/** + * JSON output of `dashboard view`: the dashboard with each widget's query + * result. The type the command yields is derived from it + * (`DashboardViewData` in `lib/formatters/dashboard.ts`). + */ +export const DashboardViewOutputSchema = object({ + id: pipe(string(), description("Dashboard ID")), + title: pipe(string(), description("Dashboard title")), + period: pipe(string(), description("Time range of the widget data")), + fetchedAt: pipe( + string(), + description("When the data was fetched (ISO 8601)"), + ), + url: pipe(string(), description("Dashboard URL")), + dateCreated: optional( + pipe(string(), description("Creation date (ISO 8601)")), + ), + environment: optional( + pipe(array(string()), description("Environment filter")), + ), + widgets: pipe( + array( + object({ + title: pipe(string(), description("Widget title")), + displayType: pipe(string(), description("Display type")), + widgetType: optional(pipe(string(), description("Dataset"))), + description: optional( + pipe(string(), description("Markdown content of a text widget")), + ), + layout: optional(DashboardWidgetLayoutSchema), + queries: optional(array(DashboardWidgetQuerySchema)), + data: WidgetDataResultSchema, + }), + ), + description("Widgets with their query results"), + ), +}); + +/** + * JSON output of `dashboard widget add` and `dashboard widget edit`, for + * `--fields`: the saved dashboard, the added or edited widget, and its URL. + */ +export const DashboardWidgetChangeOutputSchema = object({ + dashboard: pipe(DashboardDetailSchema, description("The saved dashboard")), + widget: pipe( + DashboardWidgetSchema, + description("The added or edited widget"), + ), + url: pipe(string(), description("Dashboard URL")), +}); + +/** + * JSON output of `dashboard widget delete`: the deleted (or, with + * `--dry-run`, matched) widget and the dashboard's widget count. + */ +export const DashboardWidgetDeleteOutputSchema = object({ + dryRun: DryRunOutputField, + deleted: optional( + pipe(boolean(), description("True when the widget was deleted")), + ), + widgetTitle: pipe(string(), description("Title of the deleted widget")), + widgetCount: pipe( + number(), + description( + "Dashboard widget count after the delete (before it, with --dry-run)", + ), + ), + url: pipe(string(), description("Dashboard URL")), +}); + +/** JSON output of `dashboard create`: the created dashboard and its URL. */ +export const DashboardCreateOutputSchema = looseObject({ + ...DashboardDetailSchema.entries, + url: pipe(string(), description("Dashboard URL")), +}); + +/** JSON output of `dashboard create`. */ +export type DashboardCreateOutput = InferOutput< + typeof DashboardCreateOutputSchema +>; + +/** + * JSON output of `dashboard restore`: the restored dashboard and the + * revision it was restored to. + */ +export const DashboardRestoreOutputSchema = object({ + dashboard: pipe(DashboardDetailSchema, description("Restored dashboard")), + orgSlug: pipe(string(), description("Organization slug")), + revisionId: pipe(string(), description("Restored revision ID")), +}); + +/** JSON output of `dashboard restore`. */ +export type DashboardRestoreOutput = InferOutput< + typeof DashboardRestoreOutputSchema +>; diff --git a/packages/cli/src/output-schemas/event.ts b/packages/cli/src/output-schemas/event.ts new file mode 100644 index 000000000..d807f98e0 --- /dev/null +++ b/packages/cli/src/output-schemas/event.ts @@ -0,0 +1,143 @@ +/** + * Output schemas of the `sentry event` commands, and of `sentry issue events`. + */ + +import { + vEventAttachmentDetailsResponse, + vGroupEventsResponseDict, + vIssueEventDetailsResponse, +} from "@sentry/api/valibot"; +import { + array, + description, + looseObject, + nullable, + object, + optional, + partial, + pipe, + string, + unknown, + url, +} from "valibot"; + +/** Fields `event view` adds to each attachment of the event. */ +export const EventViewAttachmentFields = object({ + download: pipe( + string(), + url(), + description("Absolute authenticated API URL for the attachment bytes"), + ), +}); + +const EventViewAttachmentSchema = looseObject({ + ...vEventAttachmentDetailsResponse.entries, + ...EventViewAttachmentFields.entries, +}); + +/** + * Fields `event view` adds to the event in its JSON output. The command's + * data type (`SingleEventViewData`) is derived from them. + */ +export const EventViewOutputFields = object({ + trace: pipe( + nullable( + object({ + traceId: pipe(string(), description("Trace ID")), + spans: pipe(array(unknown()), description("Span tree data")), + }), + ), + description("Trace context, or null when unavailable"), + ), + attachments: pipe( + array(EventViewAttachmentSchema), + description( + "Event attachments; each includes metadata and an absolute authenticated download URL", + ), + ), +}); + +/** + * Documentation schema for the flattened `event view` JSON output. + * + * Event API fields remain optional because responses vary by event type. The + * CLI always adds {@link EventViewOutputFields}; multi-event output is an + * array of this shape. + */ +export const EventViewOutputSchema = pipe( + looseObject({ + ...partial(vIssueEventDetailsResponse).entries, + eventID: pipe(string(), description("UUID-format event ID")), + ...EventViewOutputFields.entries, + }), + description("Event view output"), +); + +/** + * Valibot schema for {@link IssueEvent} — used for `--fields` documentation in `--help`. + * + * Derived from the auto-generated `vGroupEventsResponseDict` element schema. + * All generated fields are widened to optional via `.partial()`, then the core + * identifiers (id, event.type, eventID) are re-required via `.extend()`. + */ +const _IssueEventElement = vGroupEventsResponseDict.item; +export const IssueEventSchema = pipe( + looseObject({ + ...partial(_IssueEventElement).entries, + id: pipe(string(), description("Internal event ID")), + "event.type": pipe( + string(), + description("Event type (error, default, transaction)"), + ), + groupID: optional( + pipe(_IssueEventElement.entries.groupID, description("Group (issue) ID")), + ), + eventID: pipe(string(), description("UUID-format event ID")), + projectID: optional( + pipe(_IssueEventElement.entries.projectID, description("Project ID")), + ), + message: optional( + pipe(_IssueEventElement.entries.message, description("Event message")), + ), + title: optional( + pipe(_IssueEventElement.entries.title, description("Event title")), + ), + location: optional( + pipe( + _IssueEventElement.entries.location, + description("Source location (file:line)"), + ), + ), + culprit: optional( + pipe( + _IssueEventElement.entries.culprit, + description("Culprit function/module"), + ), + ), + user: optional( + pipe(_IssueEventElement.entries.user, description("User context")), + ), + tags: optional( + pipe(_IssueEventElement.entries.tags, description("Event tags")), + ), + platform: optional( + pipe( + _IssueEventElement.entries.platform, + description("Platform (python, javascript, etc.)"), + ), + ), + dateCreated: optional( + pipe( + _IssueEventElement.entries.dateCreated, + description("ISO 8601 creation timestamp"), + ), + ), + crashFile: optional( + pipe(_IssueEventElement.entries.crashFile, description("Crash file URL")), + ), + metadata: optional( + pipe(_IssueEventElement.entries.metadata, description("Event metadata")), + ), + }), + description("Issue event (list endpoint)"), +); diff --git a/packages/cli/src/output-schemas/feedback.ts b/packages/cli/src/output-schemas/feedback.ts new file mode 100644 index 000000000..d829f09e7 --- /dev/null +++ b/packages/cli/src/output-schemas/feedback.ts @@ -0,0 +1,113 @@ +/** + * Output schemas of the `sentry feedback` commands. + */ + +import { vEventAttachmentDetailsResponse } from "@sentry/api/valibot"; +import { + array, + boolean, + description, + literal, + looseObject, + nullable, + number, + object, + optional, + pipe, + string, +} from "valibot"; +import type { SentryEvent } from "../types/index.js"; +import { SentryIssueSchema } from "./issue.js"; +import { opaque } from "./output.js"; + +/** Documentation schema for Feedback metadata. */ +export const FeedbackMetadataSchema = pipe( + looseObject({ + message: pipe(string(), description("Feedback message")), + contact_email: optional( + nullable(pipe(string(), description("End-user email address"))), + ), + name: optional( + nullable(pipe(string(), description("End-user display name"))), + ), + title: optional(pipe(string(), description("Feedback title"))), + value: optional(pipe(string(), description("Feedback display value"))), + initial_priority: optional( + pipe( + number(), + description("Initial priority assigned when the feedback was created"), + ), + ), + source: optional( + nullable(pipe(string(), description("Feedback capture source"))), + ), + summary: optional( + nullable(pipe(string(), description("AI-generated summary"))), + ), + sdk: optional( + pipe( + object({ + name: pipe(string(), description("SDK name")), + name_normalized: optional( + pipe(string(), description("Normalized SDK name")), + ), + }), + description("SDK that captured the feedback"), + ), + ), + associated_event_id: optional( + pipe(string(), description("Associated error event ID")), + ), + }), + description("Feedback metadata"), +); + +/** Documentation schema for a modern Feedback issue. */ +export const SentryFeedbackSchema = pipe( + looseObject({ + ...SentryIssueSchema.entries, + issueCategory: pipe( + literal("feedback"), + description("Issue category discriminator"), + ), + issueType: pipe( + literal("feedback"), + description("Issue type discriminator"), + ), + metadata: FeedbackMetadataSchema, + hasSeen: optional( + pipe(boolean(), description("Whether the feedback has been read")), + ), + latestEventHasAttachments: optional( + pipe(boolean(), description("Whether the latest event has attachments")), + ), + }), + description("Sentry User Feedback"), +); + +/** + * Fields `feedback view` adds to the Feedback issue in its JSON output; the + * rest of {@link FeedbackViewResult} is derived from them. + */ +export const FeedbackViewOutputFields = object({ + /** Resolved organization slug, or null when unavailable. */ + org: pipe(nullable(string()), description("Organization slug")), + event: pipe( + nullable(opaque()), + description("Latest feedback event"), + ), + replayIds: pipe(array(string()), description("Related Session Replay IDs")), + attachments: pipe( + array(vEventAttachmentDetailsResponse), + description("Attachments on the latest feedback event"), + ), +}); + +/** Documentation schema for flattened `feedback view` JSON output. */ +export const FeedbackViewOutputSchema = pipe( + looseObject({ + ...SentryFeedbackSchema.entries, + ...FeedbackViewOutputFields.entries, + }), + description("Feedback view output"), +); diff --git a/packages/cli/src/output-schemas/integration.ts b/packages/cli/src/output-schemas/integration.ts new file mode 100644 index 000000000..8d01a06c8 --- /dev/null +++ b/packages/cli/src/output-schemas/integration.ts @@ -0,0 +1,52 @@ +/** + * Output schemas of the `sentry integration` commands. + */ + +import { + description, + looseObject, + nullable, + optional, + pipe, + string, +} from "valibot"; +import { orgListItemSchema } from "./org-list.js"; + +/** Provider summary embedded in an installed integration. */ +export const IntegrationProviderSchema = looseObject({ + key: pipe(string(), description("Provider key (e.g. github, slack)")), + name: pipe(string(), description("Provider display name")), +}); + +/** + * An integration installed on a Sentry organization. + * + * Returned by `/organizations/{org}/integrations/`. The list includes + * integrations that are pending deletion, so `organizationIntegrationStatus` + * can be `active`, `disabled`, or `pending_deletion`. + */ +export const SentryIntegrationSchema = pipe( + looseObject({ + id: pipe(string(), description("Integration ID")), + name: pipe(string(), description("Integration name (e.g. GitHub org)")), + domainName: pipe( + nullable(string()), + description("External domain (e.g. github.com/getsentry)"), + ), + provider: pipe(IntegrationProviderSchema, description("Provider")), + status: pipe(string(), description("Integration status")), + organizationIntegrationStatus: pipe( + string(), + description("Status of the install in this organization"), + ), + externalId: optional( + pipe(string(), description("Provider-side installation ID")), + ), + }), + description("Installed Sentry integration"), +); + +/** JSON output of `integration list`: an installed integration and the org it came from. */ +export const IntegrationListItemSchema = orgListItemSchema( + SentryIntegrationSchema, +); diff --git a/packages/cli/src/output-schemas/issue.ts b/packages/cli/src/output-schemas/issue.ts new file mode 100644 index 000000000..b131c928d --- /dev/null +++ b/packages/cli/src/output-schemas/issue.ts @@ -0,0 +1,211 @@ +/** + * Output schemas of the `sentry issue` commands. + */ + +import { + vGetOrganizationIssueResponse, + vGetOrganizationIssueTagResponse, +} from "@sentry/api/valibot"; +import { + array, + boolean, + description, + looseObject, + nullable, + number, + object, + optional, + partial, + pick, + pipe, + string, + unknown, +} from "valibot"; +import type { SentryEvent } from "../types/index.js"; +import { opaque } from "./output.js"; + +/** + * Valibot schema describing the key fields of a {@link SentryIssue} for JSON output. + * + * This is a documentation-oriented schema — it describes the commonly-available + * fields that appear in `--json` output, used by the help system and SKILL.md + * generation to inform agents and users about available `--fields` selections. + * + * Not a validation schema — the actual API response may include additional + * SDK-derived fields not listed here. Fields listed as optional may still be + * present in most responses; optionality reflects the TypeScript type. + */ +/** + * Derived from the auto-generated `vGetOrganizationIssueResponse` schema. + * + * The generated schema makes all API-documented fields required. We widen it + * with `.partial()` so only the core identifiers (id, shortId, title) are + * required — matching how the CLI uses partial API responses and test mocks. + * Extra fields not in the OpenAPI spec (substatus, priority, isUnhandled, + * seerFixabilityScore) are added via `.extend()`. + */ +export const SentryIssueSchema = pipe( + looseObject({ + ...partial( + pick(vGetOrganizationIssueResponse, [ + "id", + "shortId", + "title", + "culprit", + "count", + "userCount", + "firstSeen", + "lastSeen", + "level", + "status", + "permalink", + "project", + "metadata", + "assignedTo", + ]), + ).entries, + id: pipe(string(), description("Numeric issue ID")), + shortId: pipe( + string(), + description("Human-readable short ID (e.g. PROJ-ABC)"), + ), + title: pipe(string(), description("Issue title")), + culprit: optional( + pipe( + vGetOrganizationIssueResponse.entries.culprit, + description("Culprit string"), + ), + ), + count: optional( + pipe( + vGetOrganizationIssueResponse.entries.count, + description("Total event count"), + ), + ), + userCount: optional( + pipe( + vGetOrganizationIssueResponse.entries.userCount, + description("Number of affected users"), + ), + ), + firstSeen: optional( + pipe( + vGetOrganizationIssueResponse.entries.firstSeen, + description("First occurrence (ISO 8601)"), + ), + ), + lastSeen: optional( + pipe( + vGetOrganizationIssueResponse.entries.lastSeen, + description("Most recent occurrence (ISO 8601)"), + ), + ), + level: optional( + pipe( + vGetOrganizationIssueResponse.entries.level, + description("Severity level"), + ), + ), + status: optional( + pipe( + vGetOrganizationIssueResponse.entries.status, + description("Issue status"), + ), + ), + permalink: optional( + pipe( + vGetOrganizationIssueResponse.entries.permalink, + description("URL to the issue in Sentry"), + ), + ), + project: optional( + pipe( + vGetOrganizationIssueResponse.entries.project, + description("Project info"), + ), + ), + metadata: optional( + pipe( + vGetOrganizationIssueResponse.entries.metadata, + description("Issue metadata"), + ), + ), + assignedTo: optional( + pipe( + vGetOrganizationIssueResponse.entries.assignedTo, + description("Assigned user or team"), + ), + ), + priority: optional(pipe(string(), description("Triage priority"))), + platform: optional(pipe(string(), description("Platform"))), + substatus: optional( + pipe(nullable(string()), description("Issue substatus")), + ), + isUnhandled: optional( + pipe(boolean(), description("Whether the issue is unhandled")), + ), + seerFixabilityScore: optional( + pipe(nullable(number()), description("Seer AI fixability score (0-1)")), + ), + }), + description("Sentry issue"), +); + +/** + * Fields `issue view` adds to the issue in its JSON output. The command's + * data type (`SingleIssueViewData`) is derived from them. + */ +export const IssueViewOutputFields = object({ + event: pipe( + nullable(opaque()), + description( + "Latest event for the issue (full detail). Select named fields with " + + "`--fields event.id,event.title` to avoid pulling the whole payload; " + + "the `request` entry may include live session data.", + ), + ), + org: pipe(nullable(string()), description("Organization slug")), + replayIds: pipe(array(string()), description("Related Session Replay IDs")), + trace: pipe( + nullable( + object({ + traceId: pipe(string(), description("Trace ID from the latest event")), + spans: pipe(array(unknown()), description("Span tree data")), + }), + ), + description("Trace context from the latest event's span tree"), + ), +}); + +/** + * Documentation-oriented schema for `issue view` JSON output. + * + * The view command's jsonTransform spreads all issue fields at the top level + * and adds {@link IssueViewOutputFields}. This schema describes that + * flattened shape for `--help`, `sentry help issue view`, and SKILL.md field + * table generation. + */ +export const IssueViewOutputSchema = pipe( + looseObject({ + ...SentryIssueSchema.entries, + ...IssueViewOutputFields.entries, + }), + description("Issue view output"), +); + +/** JSON output of `issue tags`: the tag's top values across retained events. */ +export const IssueTagsOutputSchema = object({ + ...vGetOrganizationIssueTagResponse.entries, + totalValues: pipe( + vGetOrganizationIssueTagResponse.entries.totalValues, + description( + "Total retained events, including missing tag values; not a lifetime count", + ), + ), + topValues: pipe( + vGetOrganizationIssueTagResponse.entries.topValues, + description( + "Up to 9 values ordered by count, with nullable counts and first/last seen timestamps", + ), + ), +}); diff --git a/packages/cli/src/output-schemas/log.ts b/packages/cli/src/output-schemas/log.ts new file mode 100644 index 000000000..02d47bbc9 --- /dev/null +++ b/packages/cli/src/output-schemas/log.ts @@ -0,0 +1,7 @@ +/** + * Output schemas of the `sentry log` commands. + */ + +// Also validates the logs API response at runtime, so it stays in +// `types/sentry.ts`. +export { SentryLogSchema } from "../types/sentry.js"; diff --git a/packages/cli/src/output-schemas/monitor.ts b/packages/cli/src/output-schemas/monitor.ts new file mode 100644 index 000000000..edd16ed9d --- /dev/null +++ b/packages/cli/src/output-schemas/monitor.ts @@ -0,0 +1,120 @@ +/** + * Output schemas of the `sentry monitor` commands. + */ + +import { + array, + boolean, + description, + looseObject, + nullable, + number, + optional, + pipe, + string, + union, +} from "valibot"; +import { orgListItemSchema } from "./org-list.js"; + +/** + * Configuration of a cron monitor's expected schedule and thresholds. + * + * Returned by the `/organizations/{org}/monitors/` endpoint. The `schedule` + * field is either a crontab string (when `schedule_type` is `"crontab"`) or a + * `[value, unit]` tuple (when `"interval"`). Other fields are nullable because + * the API returns `null` for unset thresholds. + */ +export const MonitorConfigSchema = pipe( + looseObject({ + schedule_type: optional( + pipe(string(), description("Schedule type: 'crontab' or 'interval'")), + ), + schedule: optional( + pipe( + union([string(), array(union([string(), number()]))]), + description("Crontab string or [value, unit] interval tuple"), + ), + ), + timezone: optional( + nullable( + pipe(string(), description("Schedule timezone (tz database string)")), + ), + ), + checkin_margin: optional( + nullable( + pipe( + number(), + description("Allowed minutes after the expected check-in time"), + ), + ), + ), + max_runtime: optional( + nullable( + pipe( + number(), + description("Allowed minutes a check-in may run before timing out"), + ), + ), + ), + failure_issue_threshold: optional( + nullable( + pipe( + number(), + description("Consecutive failures before an issue is created"), + ), + ), + ), + recovery_threshold: optional( + nullable( + pipe( + number(), + description("Consecutive successes before an issue is resolved"), + ), + ), + ), + }), + description("Monitor configuration"), +); + +/** + * A cron monitor configured in a Sentry organization. + * + * Cron monitors are not modeled by the `@sentry/api` types this project + * re-exports, so this is a hand-written internal schema (Pattern B). Core + * identifiers (id, slug, name, status) are required; richer fields are widened + * to optional and `.passthrough()` preserves any unmodeled API fields. + */ +export const SentryMonitorSchema = pipe( + looseObject({ + id: pipe(string(), description("Monitor ID")), + slug: pipe(string(), description("Monitor slug")), + name: pipe(string(), description("Monitor name")), + status: pipe( + string(), + description("Monitor status (e.g. active, disabled)"), + ), + isMuted: optional( + pipe(boolean(), description("Whether the monitor is muted")), + ), + config: optional( + pipe(MonitorConfigSchema, description("Schedule configuration")), + ), + dateCreated: optional( + pipe(string(), description("Creation date (ISO 8601)")), + ), + project: optional( + pipe( + looseObject({ + id: optional(pipe(string(), description("Project ID"))), + slug: optional(pipe(string(), description("Project slug"))), + name: optional(pipe(string(), description("Project name"))), + }), + description("Owning project"), + ), + ), + }), + description("Sentry monitor"), +); + +/** JSON output of `monitor list`: a cron monitor and the org it came from. */ +export const MonitorListItemSchema = orgListItemSchema(SentryMonitorSchema); diff --git a/packages/cli/src/output-schemas/org-list.ts b/packages/cli/src/output-schemas/org-list.ts new file mode 100644 index 000000000..e83724150 --- /dev/null +++ b/packages/cli/src/output-schemas/org-list.ts @@ -0,0 +1,29 @@ +/** + * Output schema building blocks of org-scoped lists: each item is the + * entity with the `orgSlug` it came from. + */ + +import { + description, + looseObject, + object, + type ObjectEntries, + optional, + pipe, + string, +} from "valibot"; + +/** The field `withOrg` adds to each item of an org-scoped list. */ +export const OrgListItemOutputFields = object({ + orgSlug: optional(pipe(string(), description("Organization slug"))), +}); + +/** Output schema of an org-scoped list item: the entity's, plus `orgSlug`. */ +export function orgListItemSchema(entity: { + readonly entries: TEntries; +}) { + return looseObject({ + ...entity.entries, + ...OrgListItemOutputFields.entries, + }); +} diff --git a/packages/cli/src/output-schemas/org.ts b/packages/cli/src/output-schemas/org.ts new file mode 100644 index 000000000..31838ff0e --- /dev/null +++ b/packages/cli/src/output-schemas/org.ts @@ -0,0 +1,117 @@ +/** + * Output schemas of the `sentry org` commands. + */ + +import { vOrganizationSummary } from "@sentry/api/valibot"; +import { + description, + looseObject, + object, + optional, + pipe, + string, +} from "valibot"; + +const sdkOrg = vOrganizationSummary.entries; + +/** + * `--fields` / SKILL.md documentation schema for an organization. + * + * Like {@link SentryTeamSchema}, it is not used for runtime validation: it + * curates the user-facing fields of the auto-generated `vOrganizationSummary` + * (the list-organizations item). Only core identifiers are required. + */ +export const SentryOrganizationSchema = looseObject({ + id: pipe(string(), description("Organization ID")), + slug: pipe(string(), description("Organization slug")), + name: pipe(string(), description("Organization name")), + dateCreated: optional( + pipe(sdkOrg.dateCreated, description("Creation date (ISO 8601)")), + ), + status: optional(pipe(sdkOrg.status, description("Organization status"))), + isEarlyAdopter: optional( + pipe( + sdkOrg.isEarlyAdopter, + description("Whether the org is an early adopter"), + ), + ), + require2FA: optional( + pipe(sdkOrg.require2FA, description("Whether members must use 2FA")), + ), + features: optional(pipe(sdkOrg.features, description("Enabled features"))), + avatar: optional(pipe(sdkOrg.avatar, description("Avatar"))), + links: optional( + pipe(sdkOrg.links, description("Organization and region URLs")), + ), + hasAuthProvider: optional( + pipe(sdkOrg.hasAuthProvider, description("Whether SSO is configured")), + ), + allowMemberInvite: optional( + pipe(sdkOrg.allowMemberInvite, description("Whether members can invite")), + ), + allowMemberProjectCreation: optional( + pipe( + sdkOrg.allowMemberProjectCreation, + description("Whether members can create projects"), + ), + ), + orgRole: optional( + pipe(string(), description("Your role in the organization")), + ), +}); + +/** + * The account an organization was listed under (no secrets): a stored + * account, or the env token's virtual account. + */ +export const OrgListAccountSchema = object({ + /** + * What `--account` accepts: `:`, e.g. + * `jane@acme.com:sentry.io` (just `` when no server is recorded), as + * `sentry auth login` does too; `env:SENTRY_AUTH_TOKEN` for the env token. + */ + name: pipe(string(), description("What --account accepts")), + id: pipe(string(), description("Account ID")), + email: optional(pipe(string(), description("Account email"))), + username: optional(pipe(string(), description("Account username"))), + /** + * The server part of `name`: `host[:port]`, or the full origin such as + * `http://localhost:8000` for a non-HTTPS server. + */ + server: optional(pipe(string(), description("Account server"))), + /** The server's full origin, e.g. `https://sentry.io`. */ + host: optional(pipe(string(), description("Server origin"))), + /** Human label, e.g. `Jane on sentry.io`. */ + label: pipe(string(), description("Human-readable account label")), + /** The variable providing the token, for the env token's account. */ + envVar: optional( + pipe(string(), description("Variable providing the env token")), + ), +}); + +/** + * Fields the list adds to each organization: a region display name and the + * stored account it was listed under. + * + * The `region` field is only present when the user's orgs span multiple + * regions (e.g. both US and EU). `account` is only present when orgs from + * several stored accounts are listed. Both are included in JSON output as + * well, providing context to machine consumers. + */ +export const OrgListEntryFields = object({ + region: optional( + pipe(string(), description("Region, when orgs span several (e.g. US, EU)")), + ), + account: optional( + pipe( + OrgListAccountSchema, + description("Account the org was listed under, across accounts"), + ), + ), +}); + +/** JSON output of `org list`: each organization with {@link OrgListEntryFields}. */ +export const OrgListEntrySchema = looseObject({ + ...SentryOrganizationSchema.entries, + ...OrgListEntryFields.entries, +}); diff --git a/packages/cli/src/types/output.ts b/packages/cli/src/output-schemas/output.ts similarity index 86% rename from packages/cli/src/types/output.ts rename to packages/cli/src/output-schemas/output.ts index 6c015efdd..219982acb 100644 --- a/packages/cli/src/types/output.ts +++ b/packages/cli/src/output-schemas/output.ts @@ -1,8 +1,9 @@ /** * Building blocks for command output schemas. * - * A command declares its JSON output once, as a valibot schema - * (`OutputConfig.schema`), and derives the TypeScript type its `func` + * A command declares its JSON output once, as a valibot schema in + * `src/output-schemas/` (build-only: the command's `OutputConfig.schema` is + * the field data generated from it), and derives the TypeScript type its `func` * yields and its `human` formatter takes from that schema, so the * compiler keeps the two in sync. Fields that come from the API keep the * `@sentry/api` SDK type; fields the CLI adds are written once as a valibot diff --git a/packages/cli/src/output-schemas/project.ts b/packages/cli/src/output-schemas/project.ts new file mode 100644 index 000000000..1f2477b00 --- /dev/null +++ b/packages/cli/src/output-schemas/project.ts @@ -0,0 +1,84 @@ +/** + * Output schemas of the `sentry project` commands. + */ + +import { vOrganizationProjectResponseDict } from "@sentry/api/valibot"; +import { + description, + looseObject, + nullable, + object, + optional, + pipe, + string, +} from "valibot"; +import { orgListItemSchema } from "./org-list.js"; + +const sdkProject = vOrganizationProjectResponseDict.item.entries; + +/** + * `--fields` / SKILL.md documentation schema for a project. + * + * Curates the user-facing fields of the auto-generated list-projects item, + * like {@link SentryOrganizationSchema}; not used for runtime validation. + */ +export const SentryProjectSchema = looseObject({ + id: pipe(string(), description("Project ID")), + slug: pipe(string(), description("Project slug")), + name: pipe(string(), description("Project name")), + platform: optional(pipe(sdkProject.platform, description("Platform"))), + platforms: optional( + pipe(sdkProject.platforms, description("Platforms seen in events")), + ), + dateCreated: optional( + pipe(sdkProject.dateCreated, description("Creation date (ISO 8601)")), + ), + firstEvent: optional( + pipe(sdkProject.firstEvent, description("First event date (ISO 8601)")), + ), + status: optional(pipe(string(), description("Project status"))), + isBookmarked: optional( + pipe(sdkProject.isBookmarked, description("Whether you bookmarked it")), + ), + isMember: optional( + pipe(sdkProject.isMember, description("Whether you are a member")), + ), + hasAccess: optional( + pipe(sdkProject.hasAccess, description("Whether you have access")), + ), + features: optional( + pipe(sdkProject.features, description("Enabled features")), + ), + team: optional(pipe(sdkProject.team, description("Owning team"))), + teams: optional(pipe(sdkProject.teams, description("Teams with access"))), + environments: optional( + pipe(sdkProject.environments, description("Environments seen")), + ), + latestRelease: optional( + pipe(sdkProject.latestRelease, description("Latest release")), + ), + organization: optional( + pipe( + looseObject({ + id: pipe(string(), description("Organization ID")), + slug: pipe(string(), description("Organization slug")), + name: optional(pipe(string(), description("Organization name"))), + }), + description("Organization (detail responses only)"), + ), + ), +}); + +/** JSON output of `project list`: a project and the org it came from. */ +export const ProjectListItemSchema = orgListItemSchema(SentryProjectSchema); + +/** The field `project view` adds to each project in its JSON output. */ +export const ProjectViewOutputFields = object({ + dsn: pipe(nullable(string()), description("Primary DSN")), +}); + +/** JSON output of `project view`: the project with its primary DSN. */ +export const ProjectViewOutputSchema = looseObject({ + ...SentryProjectSchema.entries, + ...ProjectViewOutputFields.entries, +}); diff --git a/packages/cli/src/output-schemas/release.ts b/packages/cli/src/output-schemas/release.ts new file mode 100644 index 000000000..ec7da162f --- /dev/null +++ b/packages/cli/src/output-schemas/release.ts @@ -0,0 +1,195 @@ +/** + * Output schemas of the `sentry release` commands. + */ + +import { vDeployResponse, vOrgReleaseResponse } from "@sentry/api/valibot"; +import { + array, + boolean, + description, + type InferOutput, + looseObject, + object, + optional, + pipe, + string, + union, +} from "valibot"; +import { DryRunOutputField } from "./output.js"; +import { OrgListItemOutputFields } from "./org-list.js"; + +const sdkRelease = vOrgReleaseResponse.entries; + +/** + * `--fields` / SKILL.md documentation schema for a release. + * + * Curates the user-facing fields of the auto-generated `vOrgReleaseResponse`, + * like {@link SentryOrganizationSchema}; not used for runtime validation. + */ +export const SentryReleaseSchema = looseObject({ + id: optional(pipe(sdkRelease.id, description("Release ID"))), + version: pipe(string(), description("Release version")), + shortVersion: optional( + pipe(sdkRelease.shortVersion, description("Shortened version")), + ), + versionInfo: optional( + pipe(sdkRelease.versionInfo, description("Parsed version information")), + ), + status: optional( + pipe(sdkRelease.status, description("Release status (open, archived)")), + ), + ref: optional(pipe(sdkRelease.ref, description("VCS reference"))), + url: optional(pipe(sdkRelease.url, description("Release URL"))), + dateCreated: optional( + pipe(sdkRelease.dateCreated, description("Creation date (ISO 8601)")), + ), + dateReleased: optional( + pipe(sdkRelease.dateReleased, description("Release date (ISO 8601)")), + ), + firstEvent: optional( + pipe(sdkRelease.firstEvent, description("First event date (ISO 8601)")), + ), + lastEvent: optional( + pipe(sdkRelease.lastEvent, description("Last event date (ISO 8601)")), + ), + newGroups: optional( + pipe(sdkRelease.newGroups, description("Number of new issues")), + ), + commitCount: optional( + pipe(sdkRelease.commitCount, description("Number of commits")), + ), + deployCount: optional( + pipe(sdkRelease.deployCount, description("Number of deploys")), + ), + lastCommit: optional( + pipe(sdkRelease.lastCommit, description("Most recent commit")), + ), + lastDeploy: optional( + pipe(sdkRelease.lastDeploy, description("Most recent deploy")), + ), + authors: optional(pipe(sdkRelease.authors, description("Commit authors"))), + owner: optional(pipe(sdkRelease.owner, description("Release owner"))), + projects: optional( + pipe(sdkRelease.projects, description("Projects in the release")), + ), + adoptionStages: optional( + pipe(sdkRelease.adoptionStages, description("Adoption stage per project")), + ), +}); + +/** + * Fields the release commands that update a release (`archive`, `restore`, + * `finalize`) add with `--dry-run`, which prints `{ dryRun, version, org }` + * instead of the updated release. + */ +export const ReleaseUpdateOutputFields = object({ + dryRun: DryRunOutputField, + org: optional(pipe(string(), description("Organization slug (--dry-run)"))), +}); + +/** JSON output of `release archive` and `release restore`. */ +export const ReleaseUpdateOutputSchema = looseObject({ + ...SentryReleaseSchema.entries, + ...ReleaseUpdateOutputFields.entries, +}); + +/** `--fields` / SKILL.md documentation schema for a deploy. */ +export const SentryDeploySchema = looseObject({ + id: pipe(string(), description("Deploy ID")), + environment: pipe(string(), description("Environment")), + name: optional(pipe(vDeployResponse.entries.name, description("Name"))), + url: optional(pipe(vDeployResponse.entries.url, description("Deploy URL"))), + dateStarted: optional( + pipe( + vDeployResponse.entries.dateStarted, + description("Start date (ISO 8601)"), + ), + ), + dateFinished: optional( + pipe( + vDeployResponse.entries.dateFinished, + description("Finish date (ISO 8601)"), + ), + ), +}); + +/** + * The fields `--dry-run` changes on the release it reports: the `dryRun` + * flag, and `projects` as `{ slug }` objects instead of full projects. + */ +export const ReleaseCreateOutputFields = object({ + dryRun: DryRunOutputField, + projects: optional( + pipe( + union([ + SentryReleaseSchema.entries.projects.wrapped, + array(object({ slug: pipe(string(), description("Project slug")) })), + ]), + description("Projects in the release (only slug with --dry-run)"), + ), + ), +}); + +/** + * JSON output of `release create`: the created release, or with `--dry-run` the release that + * would be created, in the same shape. + */ +export const ReleaseCreateOutputSchema = looseObject({ + ...SentryReleaseSchema.entries, + ...ReleaseCreateOutputFields.entries, +}); + +/** JSON output of `release delete`: the release that was (or, with `--dry-run`, would be) deleted. */ +export const ReleaseDeleteOutputSchema = object({ + deleted: pipe(boolean(), description("Whether the release was deleted")), + org: pipe(string(), description("Organization slug")), + version: pipe(string(), description("Release version")), + dryRun: DryRunOutputField, +}); + +/** JSON output of `release delete`. */ +export type ReleaseDeleteOutput = InferOutput; + +/** + * Fields `--dry-run` changes: it prints the deploy that would be created, + * which has no `id` yet, with its release `version`. + */ +export const ReleaseDeployOutputFields = object({ + id: optional(SentryDeploySchema.entries.id), + dryRun: DryRunOutputField, + version: optional(pipe(string(), description("Release version (--dry-run)"))), +}); + +/** JSON output of `release deploy`: the created deploy, or the `--dry-run` preview. */ +export const ReleaseDeployOutputSchema = looseObject({ + ...SentryDeploySchema.entries, + ...ReleaseDeployOutputFields.entries, +}); + +/** Fields `release finalize --dry-run` prints instead of the finalized release. */ +export const ReleaseFinalizeOutputFields = object({ + ...ReleaseUpdateOutputFields.entries, + released: optional( + pipe(string(), description("Release date to set (--dry-run)")), + ), +}); + +/** JSON output of `release finalize`: the finalized release, or the `--dry-run` preview. */ +export const ReleaseFinalizeOutputSchema = looseObject({ + ...SentryReleaseSchema.entries, + ...ReleaseFinalizeOutputFields.entries, +}); + +/** Fields `release list` adds to each release: its org and, when listing several projects, its project. */ +export const ReleaseListItemOutputFields = object({ + ...OrgListItemOutputFields.entries, + targetProject: optional( + pipe(string(), description("Project slug, when listing several")), + ), +}); + +/** JSON output of `release list`: each release with {@link ReleaseListItemOutputFields}. */ +export const ReleaseListItemSchema = looseObject({ + ...SentryReleaseSchema.entries, + ...ReleaseListItemOutputFields.entries, +}); diff --git a/packages/cli/src/output-schemas/replay.ts b/packages/cli/src/output-schemas/replay.ts new file mode 100644 index 000000000..54e605c99 --- /dev/null +++ b/packages/cli/src/output-schemas/replay.ts @@ -0,0 +1,148 @@ +/** + * Output schemas of the `sentry replay` commands. + */ + +import { + array, + description, + nullable, + nullish, + number, + object, + optional, + pipe, + record, + string, +} from "valibot"; +import { + buildReplayListItemShape, + ReplayClickSchema, + ReplayOtaUpdatesSchema, + replayStringArray, +} from "../types/replay.js"; + +/** + * Documentation-oriented replay list schema used for `--help` and SKILL docs. + * + * Keeps the field types explicit even though the runtime parser accepts a few + * legacy/nullish payload variants from archived replay rows. + */ +const ReplayListItemOutputSchemaBase = object( + buildReplayListItemShape({ + errorIds: replayStringArray(), + infoIds: replayStringArray(), + otaUpdates: nullish(ReplayOtaUpdatesSchema), + projectId: optional(nullable(string())), + releases: replayStringArray(), + tags: record(string(), array(string())), + traceIds: replayStringArray(), + urls: replayStringArray(), + warningIds: replayStringArray(), + }), +); +export const ReplayListItemOutputSchema = pipe( + ReplayListItemOutputSchemaBase, + description("Replay list row"), +); + +/** Documentation-oriented replay detail schema used for command metadata. */ +export const ReplayDetailsOutputSchema = pipe( + object({ + ...ReplayListItemOutputSchemaBase.entries, + clicks: pipe( + optional(array(ReplayClickSchema)), + description("Replay click summaries"), + ), + replay_type: pipe(optional(nullable(string())), description("Replay type")), + }), + description("Replay details"), +); + +/** A summarized replay activity event extracted from recording segments. */ +export const ReplayActivityEventSchema = pipe( + object({ + timestampMs: pipe( + nullable(number()), + description("Milliseconds since UNIX epoch for the activity event"), + ), + label: pipe(string(), description("Activity label")), + details: pipe( + array(string()), + description("Supplemental activity details"), + ), + }), + description("Summarized replay activity event"), +); + +/** Related issue metadata extracted from replay-linked event IDs. */ +export const ReplayRelatedIssueSchema = pipe( + object({ + eventId: pipe(string(), description("Replay-linked event ID")), + issueId: pipe( + optional(nullable(string())), + description("Resolved issue ID"), + ), + shortId: pipe( + optional(nullable(string())), + description("Resolved issue short ID"), + ), + title: pipe( + optional(nullable(string())), + description("Resolved issue title"), + ), + }), + description("Replay-related issue"), +); + +/** Related trace metadata extracted from replay trace IDs. */ +export const ReplayRelatedTraceSchema = pipe( + object({ + traceId: pipe(string(), description("Replay-linked trace ID")), + errorCount: pipe( + optional(nullable(number())), + description("Trace error count"), + ), + logCount: pipe( + optional(nullable(number())), + description("Trace log count"), + ), + performanceIssueCount: pipe( + optional(nullable(number())), + description("Trace performance issue count"), + ), + spanCount: pipe( + optional(nullable(number())), + description("Trace span count"), + ), + }), + description("Replay-related trace"), +); + +/** + * Fields `replay view` adds to the replay in its JSON output. The command's + * data type (`ReplayViewData`) is derived from them. + */ +export const ReplayViewOutputFields = object({ + org: pipe(string(), description("Organization slug")), + activity: pipe( + array(ReplayActivityEventSchema), + description("Summarized replay activity"), + ), + relatedIssues: pipe( + array(ReplayRelatedIssueSchema), + description("Replay-related issues"), + ), + relatedTraces: pipe( + array(ReplayRelatedTraceSchema), + description("Replay-related traces"), + ), +}); + +/** Replay view output with related context and summarized activity. */ +export const ReplayViewOutputSchema = pipe( + object({ + ...ReplayDetailsOutputSchema.entries, + ...ReplayViewOutputFields.entries, + }), + description("Replay view output"), +); diff --git a/packages/cli/src/output-schemas/repo.ts b/packages/cli/src/output-schemas/repo.ts new file mode 100644 index 000000000..e679b7840 --- /dev/null +++ b/packages/cli/src/output-schemas/repo.ts @@ -0,0 +1,50 @@ +/** + * Output schemas of the `sentry repo` commands. + */ + +import { + description, + looseObject, + nullable, + object, + optional, + pipe, + string, +} from "valibot"; +import { orgListItemSchema } from "./org-list.js"; + +/** Repository provider (e.g., GitHub, GitLab) */ +export const RepositoryProviderSchema = object({ + id: string(), + name: string(), +}); + +/** A repository connected to a Sentry organization */ +export const SentryRepositorySchema = pipe( + looseObject({ + // Core identifiers (required) + id: pipe(string(), description("Repository ID")), + name: pipe(string(), description("Repository name")), + url: pipe(nullable(string()), description("Repository URL")), + provider: pipe( + RepositoryProviderSchema, + description("Version control provider"), + ), + status: pipe(string(), description("Integration status")), + // Optional metadata + dateCreated: optional( + pipe(string(), description("Creation date (ISO 8601)")), + ), + integrationId: optional(pipe(string(), description("Integration ID"))), + externalSlug: optional( + nullable(pipe(string(), description("External slug (e.g. org/repo)"))), + ), + externalId: optional(nullable(pipe(string(), description("External ID")))), + }), + description("Sentry repository"), +); + +/** JSON output of `repo list`: a repository and the org it came from. */ +export const RepositoryListItemSchema = orgListItemSchema( + SentryRepositorySchema, +); diff --git a/packages/cli/src/output-schemas/span.ts b/packages/cli/src/output-schemas/span.ts new file mode 100644 index 000000000..8310a990e --- /dev/null +++ b/packages/cli/src/output-schemas/span.ts @@ -0,0 +1,39 @@ +/** + * Output schemas of the `sentry span` commands. + */ + +import { + description, + looseObject, + nullable, + number, + optional, + pipe, + string, +} from "valibot"; + +/** + * A span as `span list` outputs it: a {@link SpanListItem} with the fields + * `spanListItemToFlatSpan` renames, plus any custom attributes `--fields` + * requested. + */ +export const FlatSpanSchema = pipe( + looseObject({ + span_id: pipe(string(), description("Span ID")), + trace_id: optional(pipe(string(), description("Trace ID"))), + parent_span_id: optional( + nullable(pipe(string(), description("Parent span ID"))), + ), + op: optional( + pipe(string(), description("Span operation (e.g. http.client, db)")), + ), + description: optional( + nullable(pipe(string(), description("Span description"))), + ), + duration_ms: optional(pipe(number(), description("Duration (ms)"))), + start_timestamp: pipe(number(), description("Start time (Unix seconds)")), + project_slug: optional(pipe(string(), description("Project slug"))), + transaction: optional(pipe(string(), description("Transaction name"))), + }), + description("Span list item"), +); diff --git a/packages/cli/src/output-schemas/team.ts b/packages/cli/src/output-schemas/team.ts new file mode 100644 index 000000000..5d64d2f33 --- /dev/null +++ b/packages/cli/src/output-schemas/team.ts @@ -0,0 +1,57 @@ +/** + * Output schemas of the `sentry team` commands. + */ + +import { vBaseTeam } from "@sentry/api/valibot"; +import { + description, + looseObject, + optional, + partial, + pick, + pipe, + string, +} from "valibot"; +import { orgListItemSchema } from "./org-list.js"; + +/** + * A team in a Sentry organization. + * + * Derived from the auto-generated `vBaseTeam` schema, picking only the + * fields used in CLI output. All picked fields are widened to optional via + * `.partial()`, then core identifiers (id, slug, name) are re-required. + */ +export const SentryTeamSchema = looseObject({ + ...partial( + pick(vBaseTeam, [ + "id", + "slug", + "name", + "dateCreated", + "isMember", + "teamRole", + "memberCount", + ]), + ).entries, + id: pipe(string(), description("Team ID")), + slug: pipe(string(), description("Team slug")), + name: pipe(string(), description("Team name")), + dateCreated: optional( + pipe( + vBaseTeam.entries.dateCreated, + description("Creation date (ISO 8601)"), + ), + ), + isMember: optional( + pipe(vBaseTeam.entries.isMember, description("Whether you are a member")), + ), + teamRole: optional( + pipe(vBaseTeam.entries.teamRole, description("Your role in the team")), + ), + memberCount: optional( + pipe(vBaseTeam.entries.memberCount, description("Number of members")), + ), +}); + +/** JSON output of `team list`: a team and the org it came from. */ +export const TeamListItemSchema = orgListItemSchema(SentryTeamSchema); diff --git a/packages/cli/src/output-schemas/trace.ts b/packages/cli/src/output-schemas/trace.ts new file mode 100644 index 000000000..eda1d944d --- /dev/null +++ b/packages/cli/src/output-schemas/trace.ts @@ -0,0 +1,7 @@ +/** + * Output schemas of the `sentry trace` commands. + */ + +// Also validates the transactions API response at runtime, so it stays in +// `types/sentry.ts`. +export { TransactionListItemSchema } from "../types/sentry.js"; diff --git a/packages/cli/src/output-schemas/trial.ts b/packages/cli/src/output-schemas/trial.ts new file mode 100644 index 000000000..caf60c145 --- /dev/null +++ b/packages/cli/src/output-schemas/trial.ts @@ -0,0 +1,45 @@ +/** + * Output schemas of the `sentry trial` commands. + */ + +import { + description, + type InferOutput, + nullable, + number, + object, + picklist, + pipe, + string, +} from "valibot"; +import { ProductTrialSchema } from "../types/sentry.js"; + +const { category, isStarted, lengthDays, startDate, endDate } = + ProductTrialSchema.pipe[0].entries; + +/** + * JSON output of `trial list`, one per trial: the API trial's fields plus the + * ones the CLI derives (name, status, daysRemaining). + */ +export const TrialListEntrySchema = object({ + name: pipe( + string(), + description('CLI trial name (e.g. seer), or "plan" for the plan trial'), + ), + category, + status: pipe( + picklist(["available", "active", "expired"]), + description("Trial status"), + ), + daysRemaining: pipe( + nullable(number()), + description("Days left on an active trial"), + ), + isStarted, + lengthDays, + startDate, + endDate, +}); + +/** JSON output of one trial of `trial list`. */ +export type TrialListEntryOutput = InferOutput; diff --git a/packages/cli/src/types/dashboard.ts b/packages/cli/src/types/dashboard.ts index 4cd311e0b..1a4ea544a 100644 --- a/packages/cli/src/types/dashboard.ts +++ b/packages/cli/src/types/dashboard.ts @@ -37,7 +37,11 @@ import { import { ValidationError } from "../lib/errors.js"; import { logger } from "../lib/logger.js"; -import { DryRunOutputField } from "./output.js"; +import type { + DashboardListItemSchema, + DashboardWidgetChangeOutputSchema, + DashboardWidgetDeleteOutputSchema, +} from "../output-schemas/dashboard.js"; // --------------------------------------------------------------------------- // Widget type and display type enums @@ -133,20 +137,6 @@ export const DashboardWidgetSchema = looseObject({ dateCreated: optional(string()), }); -/** Schema for dashboard list items (lightweight, from GET /dashboards/) */ -export const DashboardListItemSchema = looseObject({ - id: string(), - title: string(), - dateCreated: optional(string()), - createdBy: optional( - object({ - name: optional(string()), - email: optional(string()), - }), - ), - widgetDisplay: optional(array(string())), -}); - /** Schema for full dashboard detail (from GET /dashboards/{id}/) */ export const DashboardDetailSchema = looseObject({ id: string(), @@ -1047,44 +1037,6 @@ export type UnsupportedResult = InferOutput; export type ErrorResult = InferOutput; export type WidgetDataResult = InferOutput; -/** - * JSON output of `dashboard view`: the dashboard with each widget's query - * result. The type the command yields is derived from it - * (`DashboardViewData` in `lib/formatters/dashboard.ts`). - */ -export const DashboardViewOutputSchema = object({ - id: pipe(string(), description("Dashboard ID")), - title: pipe(string(), description("Dashboard title")), - period: pipe(string(), description("Time range of the widget data")), - fetchedAt: pipe( - string(), - description("When the data was fetched (ISO 8601)"), - ), - url: pipe(string(), description("Dashboard URL")), - dateCreated: optional( - pipe(string(), description("Creation date (ISO 8601)")), - ), - environment: optional( - pipe(array(string()), description("Environment filter")), - ), - widgets: pipe( - array( - object({ - title: pipe(string(), description("Widget title")), - displayType: pipe(string(), description("Display type")), - widgetType: optional(pipe(string(), description("Dataset"))), - description: optional( - pipe(string(), description("Markdown content of a text widget")), - ), - layout: optional(DashboardWidgetLayoutSchema), - queries: optional(array(DashboardWidgetQuerySchema)), - data: WidgetDataResultSchema, - }), - ), - description("Widgets with their query results"), - ), -}); - // --------------------------------------------------------------------------- // Dataset mapping // --------------------------------------------------------------------------- @@ -1154,43 +1106,11 @@ export const DashboardRevisionSchema = looseObject({ export type DashboardRevision = InferOutput; -/** - * JSON output of `dashboard widget add` and `dashboard widget edit`, for - * `--fields`: the saved dashboard, the added or edited widget, and its URL. - */ -export const DashboardWidgetChangeOutputSchema = object({ - dashboard: pipe(DashboardDetailSchema, description("The saved dashboard")), - widget: pipe( - DashboardWidgetSchema, - description("The added or edited widget"), - ), - url: pipe(string(), description("Dashboard URL")), -}); - /** JSON output of `dashboard widget add` and `dashboard widget edit`. */ export type DashboardWidgetChangeOutput = InferOutput< typeof DashboardWidgetChangeOutputSchema >; -/** - * JSON output of `dashboard widget delete`: the deleted (or, with - * `--dry-run`, matched) widget and the dashboard's widget count. - */ -export const DashboardWidgetDeleteOutputSchema = object({ - dryRun: DryRunOutputField, - deleted: optional( - pipe(boolean(), description("True when the widget was deleted")), - ), - widgetTitle: pipe(string(), description("Title of the deleted widget")), - widgetCount: pipe( - number(), - description( - "Dashboard widget count after the delete (before it, with --dry-run)", - ), - ), - url: pipe(string(), description("Dashboard URL")), -}); - /** JSON output of `dashboard widget delete`. */ export type DashboardWidgetDeleteOutput = InferOutput< typeof DashboardWidgetDeleteOutputSchema diff --git a/packages/cli/src/types/feedback.ts b/packages/cli/src/types/feedback.ts index dee6b57b6..98eb7b7a6 100644 --- a/packages/cli/src/types/feedback.ts +++ b/packages/cli/src/types/feedback.ts @@ -1,25 +1,11 @@ /** - * Modern Sentry User Feedback types and output schemas. + * Modern Sentry User Feedback types. The output schemas are in + * `src/output-schemas/feedback.ts`. */ -import { vEventAttachmentDetailsResponse } from "@sentry/api/valibot"; -import { - array, - boolean, - description, - type InferOutput, - literal, - looseObject, - nullable, - number, - object, - optional, - pipe, - string, -} from "valibot"; -import type { SentryEvent, SentryIssue } from "./sentry.js"; -import { SentryIssueSchema } from "./sentry.js"; -import { opaque } from "./output.js"; +import type { InferOutput } from "valibot"; +import type { FeedbackViewOutputFields } from "../output-schemas/feedback.js"; +import type { SentryIssue } from "./sentry.js"; /** Metadata stored on a modern Feedback issue group. */ export type FeedbackMetadata = { @@ -92,95 +78,3 @@ export type FeedbackViewResult = InferOutput< /** The modern Feedback issue. */ feedback: SentryFeedback; }; - -/** Documentation schema for Feedback metadata. */ -export const FeedbackMetadataSchema = pipe( - looseObject({ - message: pipe(string(), description("Feedback message")), - contact_email: optional( - nullable(pipe(string(), description("End-user email address"))), - ), - name: optional( - nullable(pipe(string(), description("End-user display name"))), - ), - title: optional(pipe(string(), description("Feedback title"))), - value: optional(pipe(string(), description("Feedback display value"))), - initial_priority: optional( - pipe( - number(), - description("Initial priority assigned when the feedback was created"), - ), - ), - source: optional( - nullable(pipe(string(), description("Feedback capture source"))), - ), - summary: optional( - nullable(pipe(string(), description("AI-generated summary"))), - ), - sdk: optional( - pipe( - object({ - name: pipe(string(), description("SDK name")), - name_normalized: optional( - pipe(string(), description("Normalized SDK name")), - ), - }), - description("SDK that captured the feedback"), - ), - ), - associated_event_id: optional( - pipe(string(), description("Associated error event ID")), - ), - }), - description("Feedback metadata"), -); - -/** Documentation schema for a modern Feedback issue. */ -export const SentryFeedbackSchema = pipe( - looseObject({ - ...SentryIssueSchema.entries, - issueCategory: pipe( - literal("feedback"), - description("Issue category discriminator"), - ), - issueType: pipe( - literal("feedback"), - description("Issue type discriminator"), - ), - metadata: FeedbackMetadataSchema, - hasSeen: optional( - pipe(boolean(), description("Whether the feedback has been read")), - ), - latestEventHasAttachments: optional( - pipe(boolean(), description("Whether the latest event has attachments")), - ), - }), - description("Sentry User Feedback"), -); - -/** - * Fields `feedback view` adds to the Feedback issue in its JSON output; the - * rest of {@link FeedbackViewResult} is derived from them. - */ -export const FeedbackViewOutputFields = object({ - /** Resolved organization slug, or null when unavailable. */ - org: pipe(nullable(string()), description("Organization slug")), - event: pipe( - nullable(opaque()), - description("Latest feedback event"), - ), - replayIds: pipe(array(string()), description("Related Session Replay IDs")), - attachments: pipe( - array(vEventAttachmentDetailsResponse), - description("Attachments on the latest feedback event"), - ), -}); - -/** Documentation schema for flattened `feedback view` JSON output. */ -export const FeedbackViewOutputSchema = pipe( - looseObject({ - ...SentryFeedbackSchema.entries, - ...FeedbackViewOutputFields.entries, - }), - description("Feedback view output"), -); diff --git a/packages/cli/src/types/index.ts b/packages/cli/src/types/index.ts index 746af2401..5b92ad4ca 100644 --- a/packages/cli/src/types/index.ts +++ b/packages/cli/src/types/index.ts @@ -42,7 +42,6 @@ export type { } from "./dashboard.js"; export { DashboardDetailSchema, - DashboardListItemSchema, DashboardWidgetLayoutSchema, DashboardWidgetQuerySchema, DashboardWidgetSchema, @@ -54,11 +53,6 @@ export type { FeedbackViewResult, SentryFeedback, } from "./feedback.js"; -export { - FeedbackMetadataSchema, - FeedbackViewOutputSchema, - SentryFeedbackSchema, -} from "./feedback.js"; // OAuth types and schemas export type { DeviceCodeResponse, @@ -91,25 +85,18 @@ export type { } from "./replay.js"; export { REPLAY_LIST_FIELDS, - ReplayActivityEventSchema, ReplayBrowserSchema, - ReplayDetailsOutputSchema, ReplayDetailsResponseSchema, ReplayDetailsSchema, ReplayDeviceSchema, ReplayGeoSchema, ReplayIdsByResourceSchema, - ReplayListItemOutputSchema, ReplayListItemSchema, ReplayListResponseSchema, ReplayOsSchema, ReplayOtaUpdatesSchema, - ReplayRelatedIssueSchema, - ReplayRelatedTraceSchema, ReplaySdkSchema, ReplayUserSchema, - ReplayViewOutputFields, - ReplayViewOutputSchema, } from "./replay.js"; export type { AutofixResponse, @@ -182,31 +169,12 @@ export { DetailedLogsResponseSchema, DetailedSentryLogSchema, type EventViewAttachment, - EventViewOutputFields, - EventViewOutputSchema, - FlatSpanSchema, ISSUE_LEVELS, ISSUE_STATUSES, - IssueEventSchema, - IssueViewOutputFields, - IssueViewOutputSchema, LogsResponseSchema, - MonitorConfigSchema, ProductTrialSchema, RegionSchema, - ReleaseUpdateOutputFields, - ReleaseUpdateOutputSchema, - RepositoryProviderSchema, - SentryDeploySchema, - SentryIntegrationSchema, - SentryIssueSchema, SentryLogSchema, - SentryMonitorSchema, - SentryOrganizationSchema, - SentryProjectSchema, - SentryReleaseSchema, - SentryRepositorySchema, - SentryTeamSchema, SentryUserSchema, SpansResponseSchema, TraceItemAttributeSchema, @@ -219,7 +187,7 @@ export { UserRegionsResponseSchema, } from "./sentry.js"; -export { DryRunOutputField, opaque, type WithOutputFields } from "./output.js"; +export type { WithOutputFields } from "../output-schemas/output.js"; // I/O types diff --git a/packages/cli/src/types/replay.ts b/packages/cli/src/types/replay.ts index 4d312da5d..234ea63da 100644 --- a/packages/cli/src/types/replay.ts +++ b/packages/cli/src/types/replay.ts @@ -17,6 +17,11 @@ import { union, unknown, } from "valibot"; +import type { + ReplayActivityEventSchema, + ReplayRelatedIssueSchema, + ReplayRelatedTraceSchema, +} from "../output-schemas/replay.js"; export type ReplayTags = Record; @@ -177,7 +182,7 @@ function replayNullishObject( return pipe(nullish(schema), description(descriptionText)); } -function replayStringArray() { +export function replayStringArray() { return array(string()); } @@ -185,7 +190,7 @@ function replayStringArrayWithFallback() { return fallback(replayStringArray(), []); } -function buildReplayListItemShape< +export function buildReplayListItemShape< TErrorIds extends GenericSchema, TInfoIds extends GenericSchema, TOtaUpdates extends GenericSchema, @@ -305,132 +310,6 @@ export const ReplayDetailsResponseSchema = looseObject({ data: ReplayDetailsSchema, }); -/** - * Documentation-oriented replay list schema used for `--help` and SKILL docs. - * - * Keeps the field types explicit even though the runtime parser accepts a few - * legacy/nullish payload variants from archived replay rows. - */ -const ReplayListItemOutputSchemaBase = object( - buildReplayListItemShape({ - errorIds: replayStringArray(), - infoIds: replayStringArray(), - otaUpdates: nullish(ReplayOtaUpdatesSchema), - projectId: optional(nullable(string())), - releases: replayStringArray(), - tags: record(string(), array(string())), - traceIds: replayStringArray(), - urls: replayStringArray(), - warningIds: replayStringArray(), - }), -); -export const ReplayListItemOutputSchema = pipe( - ReplayListItemOutputSchemaBase, - description("Replay list row"), -); - -/** Documentation-oriented replay detail schema used for command metadata. */ -export const ReplayDetailsOutputSchema = pipe( - object({ - ...ReplayListItemOutputSchemaBase.entries, - clicks: pipe( - optional(array(ReplayClickSchema)), - description("Replay click summaries"), - ), - replay_type: pipe(optional(nullable(string())), description("Replay type")), - }), - description("Replay details"), -); - -/** A summarized replay activity event extracted from recording segments. */ -export const ReplayActivityEventSchema = pipe( - object({ - timestampMs: pipe( - nullable(number()), - description("Milliseconds since UNIX epoch for the activity event"), - ), - label: pipe(string(), description("Activity label")), - details: pipe( - array(string()), - description("Supplemental activity details"), - ), - }), - description("Summarized replay activity event"), -); - -/** Related issue metadata extracted from replay-linked event IDs. */ -export const ReplayRelatedIssueSchema = pipe( - object({ - eventId: pipe(string(), description("Replay-linked event ID")), - issueId: pipe( - optional(nullable(string())), - description("Resolved issue ID"), - ), - shortId: pipe( - optional(nullable(string())), - description("Resolved issue short ID"), - ), - title: pipe( - optional(nullable(string())), - description("Resolved issue title"), - ), - }), - description("Replay-related issue"), -); - -/** Related trace metadata extracted from replay trace IDs. */ -export const ReplayRelatedTraceSchema = pipe( - object({ - traceId: pipe(string(), description("Replay-linked trace ID")), - errorCount: pipe( - optional(nullable(number())), - description("Trace error count"), - ), - logCount: pipe( - optional(nullable(number())), - description("Trace log count"), - ), - performanceIssueCount: pipe( - optional(nullable(number())), - description("Trace performance issue count"), - ), - spanCount: pipe( - optional(nullable(number())), - description("Trace span count"), - ), - }), - description("Replay-related trace"), -); - -/** - * Fields `replay view` adds to the replay in its JSON output. The command's - * data type (`ReplayViewData`) is derived from them. - */ -export const ReplayViewOutputFields = object({ - org: pipe(string(), description("Organization slug")), - activity: pipe( - array(ReplayActivityEventSchema), - description("Summarized replay activity"), - ), - relatedIssues: pipe( - array(ReplayRelatedIssueSchema), - description("Replay-related issues"), - ), - relatedTraces: pipe( - array(ReplayRelatedTraceSchema), - description("Replay-related traces"), - ), -}); - -/** Replay view output with related context and summarized activity. */ -export const ReplayViewOutputSchema = pipe( - object({ - ...ReplayDetailsOutputSchema.entries, - ...ReplayViewOutputFields.entries, - }), - description("Replay view output"), -); - /** Replay IDs keyed by resource identifier (issue ID, trace ID, replay ID). */ export const ReplayIdsByResourceSchema = pipe( record(string(), array(string())), diff --git a/packages/cli/src/types/sentry.ts b/packages/cli/src/types/sentry.ts index f38d5b13c..3e6241e24 100644 --- a/packages/cli/src/types/sentry.ts +++ b/packages/cli/src/types/sentry.ts @@ -26,22 +26,22 @@ import type { OrgReleaseResponse as SdkReleaseResponse, BaseTeam as SdkTeam, } from "@sentry/api"; -import { DryRunOutputField, opaque, type WithOutputFields } from "./output.js"; +import type { EventViewAttachmentFields } from "../output-schemas/event.js"; +import type { SentryIntegrationSchema } from "../output-schemas/integration.js"; +import type { + MonitorConfigSchema, + SentryMonitorSchema, +} from "../output-schemas/monitor.js"; +import type { WithOutputFields } from "../output-schemas/output.js"; +import type { ReleaseUpdateOutputFields } from "../output-schemas/release.js"; +import type { + RepositoryProviderSchema, + SentryRepositorySchema, +} from "../output-schemas/repo.js"; import type { SentryIssueIdentity, SentryNamedResource, } from "@sentry/toolkit-core/resource-identity"; -import { - vBaseTeam, - vDeployResponse, - vEventAttachmentDetailsResponse, - vGetOrganizationIssueResponse, - vGroupEventsResponseDict, - vIssueEventDetailsResponse, - vOrganizationProjectResponseDict, - vOrganizationSummary, - vOrgReleaseResponse, -} from "@sentry/api/valibot"; import { array, boolean, @@ -55,7 +55,6 @@ import { object, optional, partial, - pick, pipe, record, string, @@ -91,54 +90,6 @@ export type SentryOrganization = Partial & orgRole?: string; }; -const sdkOrg = vOrganizationSummary.entries; - -/** - * `--fields` / SKILL.md documentation schema for an organization. - * - * Like {@link SentryTeamSchema}, it is not used for runtime validation: it - * curates the user-facing fields of the auto-generated `vOrganizationSummary` - * (the list-organizations item). Only core identifiers are required. - */ -export const SentryOrganizationSchema = looseObject({ - id: pipe(string(), description("Organization ID")), - slug: pipe(string(), description("Organization slug")), - name: pipe(string(), description("Organization name")), - dateCreated: optional( - pipe(sdkOrg.dateCreated, description("Creation date (ISO 8601)")), - ), - status: optional(pipe(sdkOrg.status, description("Organization status"))), - isEarlyAdopter: optional( - pipe( - sdkOrg.isEarlyAdopter, - description("Whether the org is an early adopter"), - ), - ), - require2FA: optional( - pipe(sdkOrg.require2FA, description("Whether members must use 2FA")), - ), - features: optional(pipe(sdkOrg.features, description("Enabled features"))), - avatar: optional(pipe(sdkOrg.avatar, description("Avatar"))), - links: optional( - pipe(sdkOrg.links, description("Organization and region URLs")), - ), - hasAuthProvider: optional( - pipe(sdkOrg.hasAuthProvider, description("Whether SSO is configured")), - ), - allowMemberInvite: optional( - pipe(sdkOrg.allowMemberInvite, description("Whether members can invite")), - ), - allowMemberProjectCreation: optional( - pipe( - sdkOrg.allowMemberProjectCreation, - description("Whether members can create projects"), - ), - ), - orgRole: optional( - pipe(string(), description("Your role in the organization")), - ), -}); - // Project /** Element type of the SDK's list-projects response */ @@ -179,61 +130,6 @@ export type SentryProject = Partial & status?: string; }; -const sdkProject = vOrganizationProjectResponseDict.item.entries; - -/** - * `--fields` / SKILL.md documentation schema for a project. - * - * Curates the user-facing fields of the auto-generated list-projects item, - * like {@link SentryOrganizationSchema}; not used for runtime validation. - */ -export const SentryProjectSchema = looseObject({ - id: pipe(string(), description("Project ID")), - slug: pipe(string(), description("Project slug")), - name: pipe(string(), description("Project name")), - platform: optional(pipe(sdkProject.platform, description("Platform"))), - platforms: optional( - pipe(sdkProject.platforms, description("Platforms seen in events")), - ), - dateCreated: optional( - pipe(sdkProject.dateCreated, description("Creation date (ISO 8601)")), - ), - firstEvent: optional( - pipe(sdkProject.firstEvent, description("First event date (ISO 8601)")), - ), - status: optional(pipe(string(), description("Project status"))), - isBookmarked: optional( - pipe(sdkProject.isBookmarked, description("Whether you bookmarked it")), - ), - isMember: optional( - pipe(sdkProject.isMember, description("Whether you are a member")), - ), - hasAccess: optional( - pipe(sdkProject.hasAccess, description("Whether you have access")), - ), - features: optional( - pipe(sdkProject.features, description("Enabled features")), - ), - team: optional(pipe(sdkProject.team, description("Owning team"))), - teams: optional(pipe(sdkProject.teams, description("Teams with access"))), - environments: optional( - pipe(sdkProject.environments, description("Environments seen")), - ), - latestRelease: optional( - pipe(sdkProject.latestRelease, description("Latest release")), - ), - organization: optional( - pipe( - looseObject({ - id: pipe(string(), description("Organization ID")), - slug: pipe(string(), description("Organization slug")), - name: optional(pipe(string(), description("Organization name"))), - }), - description("Organization (detail responses only)"), - ), - ), -}); - // Issue Constants /** @@ -310,175 +206,6 @@ export type SentryIssue = Omit, "metadata"> & filtered?: SdkIssueList[number]["filtered"]; }; -/** - * Valibot schema describing the key fields of a {@link SentryIssue} for JSON output. - * - * This is a documentation-oriented schema — it describes the commonly-available - * fields that appear in `--json` output, used by the help system and SKILL.md - * generation to inform agents and users about available `--fields` selections. - * - * Not a validation schema — the actual API response may include additional - * SDK-derived fields not listed here. Fields listed as optional may still be - * present in most responses; optionality reflects the TypeScript type. - */ -/** - * Derived from the auto-generated `vGetOrganizationIssueResponse` schema. - * - * The generated schema makes all API-documented fields required. We widen it - * with `.partial()` so only the core identifiers (id, shortId, title) are - * required — matching how the CLI uses partial API responses and test mocks. - * Extra fields not in the OpenAPI spec (substatus, priority, isUnhandled, - * seerFixabilityScore) are added via `.extend()`. - */ -export const SentryIssueSchema = pipe( - looseObject({ - ...partial( - pick(vGetOrganizationIssueResponse, [ - "id", - "shortId", - "title", - "culprit", - "count", - "userCount", - "firstSeen", - "lastSeen", - "level", - "status", - "permalink", - "project", - "metadata", - "assignedTo", - ]), - ).entries, - id: pipe(string(), description("Numeric issue ID")), - shortId: pipe( - string(), - description("Human-readable short ID (e.g. PROJ-ABC)"), - ), - title: pipe(string(), description("Issue title")), - culprit: optional( - pipe( - vGetOrganizationIssueResponse.entries.culprit, - description("Culprit string"), - ), - ), - count: optional( - pipe( - vGetOrganizationIssueResponse.entries.count, - description("Total event count"), - ), - ), - userCount: optional( - pipe( - vGetOrganizationIssueResponse.entries.userCount, - description("Number of affected users"), - ), - ), - firstSeen: optional( - pipe( - vGetOrganizationIssueResponse.entries.firstSeen, - description("First occurrence (ISO 8601)"), - ), - ), - lastSeen: optional( - pipe( - vGetOrganizationIssueResponse.entries.lastSeen, - description("Most recent occurrence (ISO 8601)"), - ), - ), - level: optional( - pipe( - vGetOrganizationIssueResponse.entries.level, - description("Severity level"), - ), - ), - status: optional( - pipe( - vGetOrganizationIssueResponse.entries.status, - description("Issue status"), - ), - ), - permalink: optional( - pipe( - vGetOrganizationIssueResponse.entries.permalink, - description("URL to the issue in Sentry"), - ), - ), - project: optional( - pipe( - vGetOrganizationIssueResponse.entries.project, - description("Project info"), - ), - ), - metadata: optional( - pipe( - vGetOrganizationIssueResponse.entries.metadata, - description("Issue metadata"), - ), - ), - assignedTo: optional( - pipe( - vGetOrganizationIssueResponse.entries.assignedTo, - description("Assigned user or team"), - ), - ), - priority: optional(pipe(string(), description("Triage priority"))), - platform: optional(pipe(string(), description("Platform"))), - substatus: optional( - pipe(nullable(string()), description("Issue substatus")), - ), - isUnhandled: optional( - pipe(boolean(), description("Whether the issue is unhandled")), - ), - seerFixabilityScore: optional( - pipe(nullable(number()), description("Seer AI fixability score (0-1)")), - ), - }), - description("Sentry issue"), -); - -/** - * Fields `issue view` adds to the issue in its JSON output. The command's - * data type (`SingleIssueViewData`) is derived from them. - */ -export const IssueViewOutputFields = object({ - event: pipe( - nullable(opaque()), - description( - "Latest event for the issue (full detail). Select named fields with " + - "`--fields event.id,event.title` to avoid pulling the whole payload; " + - "the `request` entry may include live session data.", - ), - ), - org: pipe(nullable(string()), description("Organization slug")), - replayIds: pipe(array(string()), description("Related Session Replay IDs")), - trace: pipe( - nullable( - object({ - traceId: pipe(string(), description("Trace ID from the latest event")), - spans: pipe(array(unknown()), description("Span tree data")), - }), - ), - description("Trace context from the latest event's span tree"), - ), -}); - -/** - * Documentation-oriented schema for `issue view` JSON output. - * - * The view command's jsonTransform spreads all issue fields at the top level - * and adds {@link IssueViewOutputFields}. This schema describes that - * flattened shape for `--help`, `sentry help issue view`, and SKILL.md field - * table generation. - */ -export const IssueViewOutputSchema = pipe( - looseObject({ - ...SentryIssueSchema.entries, - ...IssueViewOutputFields.entries, - }), - description("Issue view output"), -); - // Event /** @@ -529,64 +256,12 @@ export type SentryEvent = Omit< culprit?: string | null; }; -/** Fields `event view` adds to each attachment of the event. */ -const EventViewAttachmentFields = object({ - download: pipe( - string(), - url(), - description("Absolute authenticated API URL for the attachment bytes"), - ), -}); - -const EventViewAttachmentSchema = looseObject({ - ...vEventAttachmentDetailsResponse.entries, - ...EventViewAttachmentFields.entries, -}); - /** An event attachment with its authenticated download URL. */ export type EventViewAttachment = WithOutputFields< EventAttachmentDetailsResponse, typeof EventViewAttachmentFields >; -/** - * Fields `event view` adds to the event in its JSON output. The command's - * data type (`SingleEventViewData`) is derived from them. - */ -export const EventViewOutputFields = object({ - trace: pipe( - nullable( - object({ - traceId: pipe(string(), description("Trace ID")), - spans: pipe(array(unknown()), description("Span tree data")), - }), - ), - description("Trace context, or null when unavailable"), - ), - attachments: pipe( - array(EventViewAttachmentSchema), - description( - "Event attachments; each includes metadata and an absolute authenticated download URL", - ), - ), -}); - -/** - * Documentation schema for the flattened `event view` JSON output. - * - * Event API fields remain optional because responses vary by event type. The - * CLI always adds {@link EventViewOutputFields}; multi-event output is an - * array of this shape. - */ -export const EventViewOutputSchema = pipe( - looseObject({ - ...partial(vIssueEventDetailsResponse).entries, - eventID: pipe(string(), description("UUID-format event ID")), - ...EventViewOutputFields.entries, - }), - description("Event view output"), -); - // Issue Event (list endpoint) /** @@ -598,75 +273,6 @@ export const EventViewOutputSchema = pipe( */ export type IssueEvent = SdkGroupEventsList[number]; -/** - * Valibot schema for {@link IssueEvent} — used for `--fields` documentation in `--help`. - * - * Derived from the auto-generated `vGroupEventsResponseDict` element schema. - * All generated fields are widened to optional via `.partial()`, then the core - * identifiers (id, event.type, eventID) are re-required via `.extend()`. - */ -const _IssueEventElement = vGroupEventsResponseDict.item; -export const IssueEventSchema = pipe( - looseObject({ - ...partial(_IssueEventElement).entries, - id: pipe(string(), description("Internal event ID")), - "event.type": pipe( - string(), - description("Event type (error, default, transaction)"), - ), - groupID: optional( - pipe(_IssueEventElement.entries.groupID, description("Group (issue) ID")), - ), - eventID: pipe(string(), description("UUID-format event ID")), - projectID: optional( - pipe(_IssueEventElement.entries.projectID, description("Project ID")), - ), - message: optional( - pipe(_IssueEventElement.entries.message, description("Event message")), - ), - title: optional( - pipe(_IssueEventElement.entries.title, description("Event title")), - ), - location: optional( - pipe( - _IssueEventElement.entries.location, - description("Source location (file:line)"), - ), - ), - culprit: optional( - pipe( - _IssueEventElement.entries.culprit, - description("Culprit function/module"), - ), - ), - user: optional( - pipe(_IssueEventElement.entries.user, description("User context")), - ), - tags: optional( - pipe(_IssueEventElement.entries.tags, description("Event tags")), - ), - platform: optional( - pipe( - _IssueEventElement.entries.platform, - description("Platform (python, javascript, etc.)"), - ), - ), - dateCreated: optional( - pipe( - _IssueEventElement.entries.dateCreated, - description("ISO 8601 creation timestamp"), - ), - ), - crashFile: optional( - pipe(_IssueEventElement.entries.crashFile, description("Crash file URL")), - ), - metadata: optional( - pipe(_IssueEventElement.entries.metadata, description("Event metadata")), - ), - }), - description("Issue event (list endpoint)"), -); - // Project Keys (DSN) /** @@ -827,81 +433,6 @@ export type SentryRelease = Partial & { version: string; }; -const sdkRelease = vOrgReleaseResponse.entries; - -/** - * `--fields` / SKILL.md documentation schema for a release. - * - * Curates the user-facing fields of the auto-generated `vOrgReleaseResponse`, - * like {@link SentryOrganizationSchema}; not used for runtime validation. - */ -export const SentryReleaseSchema = looseObject({ - id: optional(pipe(sdkRelease.id, description("Release ID"))), - version: pipe(string(), description("Release version")), - shortVersion: optional( - pipe(sdkRelease.shortVersion, description("Shortened version")), - ), - versionInfo: optional( - pipe(sdkRelease.versionInfo, description("Parsed version information")), - ), - status: optional( - pipe(sdkRelease.status, description("Release status (open, archived)")), - ), - ref: optional(pipe(sdkRelease.ref, description("VCS reference"))), - url: optional(pipe(sdkRelease.url, description("Release URL"))), - dateCreated: optional( - pipe(sdkRelease.dateCreated, description("Creation date (ISO 8601)")), - ), - dateReleased: optional( - pipe(sdkRelease.dateReleased, description("Release date (ISO 8601)")), - ), - firstEvent: optional( - pipe(sdkRelease.firstEvent, description("First event date (ISO 8601)")), - ), - lastEvent: optional( - pipe(sdkRelease.lastEvent, description("Last event date (ISO 8601)")), - ), - newGroups: optional( - pipe(sdkRelease.newGroups, description("Number of new issues")), - ), - commitCount: optional( - pipe(sdkRelease.commitCount, description("Number of commits")), - ), - deployCount: optional( - pipe(sdkRelease.deployCount, description("Number of deploys")), - ), - lastCommit: optional( - pipe(sdkRelease.lastCommit, description("Most recent commit")), - ), - lastDeploy: optional( - pipe(sdkRelease.lastDeploy, description("Most recent deploy")), - ), - authors: optional(pipe(sdkRelease.authors, description("Commit authors"))), - owner: optional(pipe(sdkRelease.owner, description("Release owner"))), - projects: optional( - pipe(sdkRelease.projects, description("Projects in the release")), - ), - adoptionStages: optional( - pipe(sdkRelease.adoptionStages, description("Adoption stage per project")), - ), -}); - -/** - * Fields the release commands that update a release (`archive`, `restore`, - * `finalize`) add with `--dry-run`, which prints `{ dryRun, version, org }` - * instead of the updated release. - */ -export const ReleaseUpdateOutputFields = object({ - dryRun: DryRunOutputField, - org: optional(pipe(string(), description("Organization slug (--dry-run)"))), -}); - -/** JSON output of `release archive` and `release restore`. */ -export const ReleaseUpdateOutputSchema = looseObject({ - ...SentryReleaseSchema.entries, - ...ReleaseUpdateOutputFields.entries, -}); - /** The updated release, or the `--dry-run` preview. */ export type ReleaseUpdateOutput = WithOutputFields< SentryRelease, @@ -923,26 +454,6 @@ export type SentryDeploy = Partial & { environment: string; }; -/** `--fields` / SKILL.md documentation schema for a deploy. */ -export const SentryDeploySchema = looseObject({ - id: pipe(string(), description("Deploy ID")), - environment: pipe(string(), description("Environment")), - name: optional(pipe(vDeployResponse.entries.name, description("Name"))), - url: optional(pipe(vDeployResponse.entries.url, description("Deploy URL"))), - dateStarted: optional( - pipe( - vDeployResponse.entries.dateStarted, - description("Start date (ISO 8601)"), - ), - ), - dateFinished: optional( - pipe( - vDeployResponse.entries.dateFinished, - description("Finish date (ISO 8601)"), - ), - ), -}); - // Issue // Span (for trace tree display) @@ -1409,32 +920,6 @@ export const SpanListItemSchema = pipe( export type SpanListItem = InferOutput; -/** - * A span as `span list` outputs it: a {@link SpanListItem} with the fields - * `spanListItemToFlatSpan` renames, plus any custom attributes `--fields` - * requested. - */ -export const FlatSpanSchema = pipe( - looseObject({ - span_id: pipe(string(), description("Span ID")), - trace_id: optional(pipe(string(), description("Trace ID"))), - parent_span_id: optional( - nullable(pipe(string(), description("Parent span ID"))), - ), - op: optional( - pipe(string(), description("Span operation (e.g. http.client, db)")), - ), - description: optional( - nullable(pipe(string(), description("Span description"))), - ), - duration_ms: optional(pipe(number(), description("Duration (ms)"))), - start_timestamp: pipe(number(), description("Start time (Unix seconds)")), - project_slug: optional(pipe(string(), description("Project slug"))), - transaction: optional(pipe(string(), description("Transaction name"))), - }), - description("Span list item"), -); - /** Response from the spans events endpoint */ export const SpansResponseSchema = object({ data: array(SpanListItemSchema), @@ -1449,226 +934,22 @@ export type SpansResponse = InferOutput; // Repository -/** Repository provider (e.g., GitHub, GitLab) */ -export const RepositoryProviderSchema = object({ - id: string(), - name: string(), -}); - export type RepositoryProvider = InferOutput; -/** A repository connected to a Sentry organization */ -export const SentryRepositorySchema = pipe( - looseObject({ - // Core identifiers (required) - id: pipe(string(), description("Repository ID")), - name: pipe(string(), description("Repository name")), - url: pipe(nullable(string()), description("Repository URL")), - provider: pipe( - RepositoryProviderSchema, - description("Version control provider"), - ), - status: pipe(string(), description("Integration status")), - // Optional metadata - dateCreated: optional( - pipe(string(), description("Creation date (ISO 8601)")), - ), - integrationId: optional(pipe(string(), description("Integration ID"))), - externalSlug: optional( - nullable(pipe(string(), description("External slug (e.g. org/repo)"))), - ), - externalId: optional(nullable(pipe(string(), description("External ID")))), - }), - description("Sentry repository"), -); - export type SentryRepository = InferOutput; // Integrations -/** Provider summary embedded in an installed integration. */ -export const IntegrationProviderSchema = looseObject({ - key: pipe(string(), description("Provider key (e.g. github, slack)")), - name: pipe(string(), description("Provider display name")), -}); - -/** - * An integration installed on a Sentry organization. - * - * Returned by `/organizations/{org}/integrations/`. The list includes - * integrations that are pending deletion, so `organizationIntegrationStatus` - * can be `active`, `disabled`, or `pending_deletion`. - */ -export const SentryIntegrationSchema = pipe( - looseObject({ - id: pipe(string(), description("Integration ID")), - name: pipe(string(), description("Integration name (e.g. GitHub org)")), - domainName: pipe( - nullable(string()), - description("External domain (e.g. github.com/getsentry)"), - ), - provider: pipe(IntegrationProviderSchema, description("Provider")), - status: pipe(string(), description("Integration status")), - organizationIntegrationStatus: pipe( - string(), - description("Status of the install in this organization"), - ), - externalId: optional( - pipe(string(), description("Provider-side installation ID")), - ), - }), - description("Installed Sentry integration"), -); - export type SentryIntegration = InferOutput; // Cron Monitor -/** - * Configuration of a cron monitor's expected schedule and thresholds. - * - * Returned by the `/organizations/{org}/monitors/` endpoint. The `schedule` - * field is either a crontab string (when `schedule_type` is `"crontab"`) or a - * `[value, unit]` tuple (when `"interval"`). Other fields are nullable because - * the API returns `null` for unset thresholds. - */ -export const MonitorConfigSchema = pipe( - looseObject({ - schedule_type: optional( - pipe(string(), description("Schedule type: 'crontab' or 'interval'")), - ), - schedule: optional( - pipe( - union([string(), array(union([string(), number()]))]), - description("Crontab string or [value, unit] interval tuple"), - ), - ), - timezone: optional( - nullable( - pipe(string(), description("Schedule timezone (tz database string)")), - ), - ), - checkin_margin: optional( - nullable( - pipe( - number(), - description("Allowed minutes after the expected check-in time"), - ), - ), - ), - max_runtime: optional( - nullable( - pipe( - number(), - description("Allowed minutes a check-in may run before timing out"), - ), - ), - ), - failure_issue_threshold: optional( - nullable( - pipe( - number(), - description("Consecutive failures before an issue is created"), - ), - ), - ), - recovery_threshold: optional( - nullable( - pipe( - number(), - description("Consecutive successes before an issue is resolved"), - ), - ), - ), - }), - description("Monitor configuration"), -); - export type MonitorConfig = InferOutput; -/** - * A cron monitor configured in a Sentry organization. - * - * Cron monitors are not modeled by the `@sentry/api` types this project - * re-exports, so this is a hand-written internal schema (Pattern B). Core - * identifiers (id, slug, name, status) are required; richer fields are widened - * to optional and `.passthrough()` preserves any unmodeled API fields. - */ -export const SentryMonitorSchema = pipe( - looseObject({ - id: pipe(string(), description("Monitor ID")), - slug: pipe(string(), description("Monitor slug")), - name: pipe(string(), description("Monitor name")), - status: pipe( - string(), - description("Monitor status (e.g. active, disabled)"), - ), - isMuted: optional( - pipe(boolean(), description("Whether the monitor is muted")), - ), - config: optional( - pipe(MonitorConfigSchema, description("Schedule configuration")), - ), - dateCreated: optional( - pipe(string(), description("Creation date (ISO 8601)")), - ), - project: optional( - pipe( - looseObject({ - id: optional(pipe(string(), description("Project ID"))), - slug: optional(pipe(string(), description("Project slug"))), - name: optional(pipe(string(), description("Project name"))), - }), - description("Owning project"), - ), - ), - }), - description("Sentry monitor"), -); - export type SentryMonitor = InferOutput; // Team -/** - * A team in a Sentry organization. - * - * Derived from the auto-generated `vBaseTeam` schema, picking only the - * fields used in CLI output. All picked fields are widened to optional via - * `.partial()`, then core identifiers (id, slug, name) are re-required. - */ -export const SentryTeamSchema = looseObject({ - ...partial( - pick(vBaseTeam, [ - "id", - "slug", - "name", - "dateCreated", - "isMember", - "teamRole", - "memberCount", - ]), - ).entries, - id: pipe(string(), description("Team ID")), - slug: pipe(string(), description("Team slug")), - name: pipe(string(), description("Team name")), - dateCreated: optional( - pipe( - vBaseTeam.entries.dateCreated, - description("Creation date (ISO 8601)"), - ), - ), - isMember: optional( - pipe(vBaseTeam.entries.isMember, description("Whether you are a member")), - ), - teamRole: optional( - pipe(vBaseTeam.entries.teamRole, description("Your role in the team")), - ), - memberCount: optional( - pipe(vBaseTeam.entries.memberCount, description("Number of members")), - ), -}); - /** * A Sentry team. * @@ -1677,7 +958,7 @@ export const SentryTeamSchema = looseObject({ * hasAccess, isPending, memberCount, avatar) are widened to optional so test * mocks and partial list-endpoint responses can omit them. * - * `SentryTeamSchema` above is kept separately as the `--fields` / SKILL.md + * `SentryTeamSchema` (`output-schemas/team.ts`) is the `--fields` / SKILL.md * documentation schema — it is NOT used for runtime validation (team list * responses are cast `as unknown as SentryTeam[]` in `api/teams.ts`), so the * schema and type are allowed to diverge: the schema curates a user-facing diff --git a/packages/cli/test/commands/span/list.test.ts b/packages/cli/test/commands/span/list.test.ts index f67104907..dceee184b 100644 --- a/packages/cli/test/commands/span/list.test.ts +++ b/packages/cli/test/commands/span/list.test.ts @@ -55,11 +55,10 @@ vi.mock("../../../src/lib/resolve-target.js", async (importOriginal) => { }); import { ApiError, ValidationError } from "../../../src/lib/errors.js"; -import { extractSchemaFields } from "../../../src/lib/formatters/output.js"; // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking import * as resolveTarget from "../../../src/lib/resolve-target.js"; import { parsePeriod } from "../../../src/lib/time-range.js"; -import { FlatSpanSchema } from "../../../src/types/index.js"; +import { FlatSpanSchema } from "../../../src/generated/output-schemas/span.js"; const VALID_TRACE_ID = "aaaa1111bbbb2222cccc3333dddd4444"; @@ -622,7 +621,7 @@ describe("listCommand.func (trace mode)", () => { VALID_TRACE_ID, ); - const documented = extractSchemaFields(FlatSpanSchema).map((f) => f.name); + const documented = FlatSpanSchema.fields.map((f) => f.name); const [span] = JSON.parse(getStdout()).data; expect(documented).toEqual(expect.arrayContaining(Object.keys(span))); }); diff --git a/packages/cli/test/lib/api/monitors.test.ts b/packages/cli/test/lib/api/monitors.test.ts index 80e3c822b..040f89e4f 100644 --- a/packages/cli/test/lib/api/monitors.test.ts +++ b/packages/cli/test/lib/api/monitors.test.ts @@ -8,7 +8,7 @@ import { safeParse } from "valibot"; import { describe, expect, test } from "vitest"; -import { SentryMonitorSchema } from "../../../src/types/sentry.js"; +import { SentryMonitorSchema } from "../../../src/output-schemas/monitor.js"; const crontabMonitor = { id: "12345", diff --git a/packages/cli/test/lib/formatters/output.test.ts b/packages/cli/test/lib/formatters/output.test.ts index 7d1e33655..a091593b9 100644 --- a/packages/cli/test/lib/formatters/output.test.ts +++ b/packages/cli/test/lib/formatters/output.test.ts @@ -1,7 +1,5 @@ -import { array, nullable, object, optional, string } from "valibot"; import { describe, expect, test } from "vitest"; import { - extractSchemaFieldPaths, type OutputConfig, renderCommandOutput, resolveRenderer, @@ -362,26 +360,3 @@ describe("renderCommandOutput", () => { expect(renderer.finalize).toBeUndefined(); }); }); - -describe("extractSchemaFieldPaths", () => { - test("lists nested fields in dot notation, through wrappers and arrays", () => { - const schema = object({ - id: string(), - metadata: optional(nullable(object({ title: string() }))), - tags: array(object({ key: string(), value: string() })), - }); - - expect(extractSchemaFieldPaths(schema)).toEqual([ - "id", - "metadata", - "metadata.title", - "tags", - "tags.key", - "tags.value", - ]); - }); - - test("returns nothing for a schema that is not an object", () => { - expect(extractSchemaFieldPaths(string())).toEqual([]); - }); -}); diff --git a/packages/cli/test/script/output-schema-fields.test.ts b/packages/cli/test/script/output-schema-fields.test.ts new file mode 100644 index 000000000..218fc01e0 --- /dev/null +++ b/packages/cli/test/script/output-schema-fields.test.ts @@ -0,0 +1,26 @@ +import { array, nullable, object, optional, string } from "valibot"; +import { describe, expect, test } from "vitest"; +import { extractSchemaFieldPaths } from "../../script/lib/output-schema-fields.js"; + +describe("extractSchemaFieldPaths", () => { + test("lists nested fields in dot notation, through wrappers and arrays", () => { + const schema = object({ + id: string(), + metadata: optional(nullable(object({ title: string() }))), + tags: array(object({ key: string(), value: string() })), + }); + + expect(extractSchemaFieldPaths(schema)).toEqual([ + "id", + "metadata", + "metadata.title", + "tags", + "tags.key", + "tags.value", + ]); + }); + + test("returns nothing for a schema that is not an object", () => { + expect(extractSchemaFieldPaths(string())).toEqual([]); + }); +});