From 7a19e969bcd24473ed23a45e9b508fc766533a0a Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Wed, 18 Nov 2026 14:01:25 -0700 Subject: [PATCH 1/3] feat(cli): derive flag documentation from flag definitions --- .../command-internal/flag-documentation.ts | 55 ++++++++ apps/cli/src/command-internal/global-flags.ts | 7 + .../command-internal/param-introspection.ts | 17 ++- .../commands/db/advisors/advisors.command.ts | 4 + apps/cli/src/commands/db/lint/lint.command.ts | 3 + apps/cli/src/commands/db/pull/pull.command.ts | 2 + .../schema/declarative/sync/sync.command.ts | 2 + .../functions/deploy/deploy.command.ts | 2 + .../gen/bearer-jwt/bearer-jwt.command.ts | 18 ++- .../src/commands/gen/types/types.languages.ts | 26 ++-- .../gen/types/types.languages.unit.test.ts | 20 ++- apps/cli/src/commands/login/login.command.ts | 5 + .../cli/src/commands/storage/cp/cp.command.ts | 6 +- apps/cli/src/commands/test/new/new.command.ts | 2 + .../activate/activate.command.ts | 2 + .../check-availability.command.ts | 2 + apps/cli/src/docs/docs-spec.tables.ts | 66 +-------- apps/cli/src/docs/docs-spec.ts | 53 +------- apps/cli/src/docs/docs-spec.unit.test.ts | 70 +++++++++- .../shared/cli/version.integration.test.ts | 15 ++- .../flag-defaults-help.integration.test.ts | 126 ++++++++++++++++++ .../src/shared/output/flag-defaults-help.ts | 77 +++++++++++ apps/cli/src/shared/output/text-formatter.ts | 5 +- 23 files changed, 439 insertions(+), 146 deletions(-) create mode 100644 apps/cli/src/command-internal/flag-documentation.ts create mode 100644 apps/cli/src/shared/output/flag-defaults-help.integration.test.ts create mode 100644 apps/cli/src/shared/output/flag-defaults-help.ts diff --git a/apps/cli/src/command-internal/flag-documentation.ts b/apps/cli/src/command-internal/flag-documentation.ts new file mode 100644 index 0000000000..590d7e461c --- /dev/null +++ b/apps/cli/src/command-internal/flag-documentation.ts @@ -0,0 +1,55 @@ +import { Context, Option } from "effect"; +import type { Param } from "effect/cli"; +import type { UnwrappedParam } from "./param-introspection.ts"; + +export interface FlagDocumentationShape { + readonly defaultValue?: string; + readonly choices?: ReadonlyArray; + readonly required?: boolean; + readonly hidden?: boolean; + /** Website compatibility labels need not describe an actual runtime default. */ + readonly helpDefault?: string | false; +} + +export class FlagDocumentation extends Context.Service()( + "supabase/FlagDocumentation", +) {} + +export function flagDocumentation( + single: Param.Single, +): FlagDocumentationShape { + return Context.getOption(single.annotations, FlagDocumentation).pipe( + Option.getOrElse(() => ({})), + ); +} + +/** Only literal scalar and array defaults can be displayed without evaluating user code. */ +export function literalDefault(value: unknown): string | undefined { + if (typeof value === "string") return value; + if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) { + return String(value); + } + if (Array.isArray(value)) { + const values: unknown[] = value; + if ( + values.every( + (item) => + typeof item === "string" || + typeof item === "boolean" || + (typeof item === "number" && Number.isFinite(item)), + ) + ) { + return JSON.stringify(values); + } + } + return undefined; +} + +export function flagDefault(unwrapped: UnwrappedParam): string | undefined { + return ( + flagDocumentation(unwrapped.single).defaultValue ?? + Option.flatMap(unwrapped.defaultValue, (value) => + Option.fromUndefinedOr(literalDefault(value)), + ).pipe(Option.getOrUndefined) + ); +} diff --git a/apps/cli/src/command-internal/global-flags.ts b/apps/cli/src/command-internal/global-flags.ts index 12723088bf..6ff93e1bb5 100644 --- a/apps/cli/src/command-internal/global-flags.ts +++ b/apps/cli/src/command-internal/global-flags.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "./flag-documentation.ts"; import { Effect, Option } from "effect"; import { Flag, GlobalFlag } from "effect/cli"; @@ -32,6 +33,11 @@ export const OutputFlag = GlobalFlag.Setting("output")({ flag: Flag.Literals("output", GLOBAL_OUTPUT_FORMATS).pipe( Flag.withAlias("o"), Flag.withDescription("output format of status variables"), + Flag.annotate(FlagDocumentation, { + defaultValue: "pretty", + helpDefault: false, // Commands select their own format when --output is omitted. + choices: ["env", "pretty", "json", "toml", "yaml"], + }), Flag.optional, ), }); @@ -40,6 +46,7 @@ export const OutputFlag = GlobalFlag.Setting("output")({ export const OutputFormatFlag = GlobalFlag.Setting("output-format")({ flag: Flag.Literals("output-format", ["text", "json", "stream-json"]).pipe( Flag.withDescription("Output format: text (default), json, or stream-json (NDJSON)"), + Flag.annotate(FlagDocumentation, { defaultValue: "text" }), Flag.optional, ), }); diff --git a/apps/cli/src/command-internal/param-introspection.ts b/apps/cli/src/command-internal/param-introspection.ts index a7b48b9980..cf845d9d6f 100644 --- a/apps/cli/src/command-internal/param-introspection.ts +++ b/apps/cli/src/command-internal/param-introspection.ts @@ -14,6 +14,14 @@ function isWrappedParam(param: Param.Any): param is Param.Any & WrappedParam { return "param" in param; } +interface FallbackParam extends WrappedParam { + readonly fallback?: Param.Fallback; +} + +function isFallbackParam(param: Param.Any & WrappedParam): param is Param.Any & FallbackParam { + return param._tag === "Transform" && "fallback" in param; +} + interface VariadicParam { readonly min: Option.Option; } @@ -34,6 +42,7 @@ export interface UnwrappedParam { * this instead of `isVariadic` when determining whether a flag is required. */ readonly variadicMin: number; + readonly defaultValue: Option.Option; } /** @@ -46,10 +55,16 @@ export function unwrapParam(param: Param.Any): UnwrappedParam | undefined { let isOptional = false; let isVariadic = false; let variadicMin = 0; + let defaultValue: Option.Option = Option.none(); while (!Param.isSingle(current)) { if (!isWrappedParam(current)) return undefined; if (current._tag === "Optional") isOptional = true; + if (isFallbackParam(current) && current.fallback) { + isOptional = true; + defaultValue = + current.fallback._tag === "Default" ? Option.some(current.fallback.value) : Option.none(); + } if (current._tag === "Variadic") { isVariadic = true; if (isVariadicParam(current)) { @@ -59,7 +74,7 @@ export function unwrapParam(param: Param.Any): UnwrappedParam | undefined { current = current.param; } - return { single: current, isOptional, isVariadic, variadicMin }; + return { single: current, isOptional, isVariadic, variadicMin, defaultValue }; } /** diff --git a/apps/cli/src/commands/db/advisors/advisors.command.ts b/apps/cli/src/commands/db/advisors/advisors.command.ts index 711dd30c90..4a06ea0bf3 100644 --- a/apps/cli/src/commands/db/advisors/advisors.command.ts +++ b/apps/cli/src/commands/db/advisors/advisors.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts"; @@ -22,14 +23,17 @@ const config = { ...targetFlags({ subject: "database", dbUrl: true }), type: Flag.Literals("type", ["all", "security", "performance"] as const).pipe( Flag.withDescription("Type of advisors to check: all, security, performance."), + Flag.annotate(FlagDocumentation, { defaultValue: "all" }), Flag.optional, ), level: Flag.Literals("level", ["info", "warn", "error"] as const).pipe( Flag.withDescription("Minimum issue level to display: info, warn, error."), + Flag.annotate(FlagDocumentation, { defaultValue: "warn" }), Flag.optional, ), failOn: Flag.Literals("fail-on", ["none", "info", "warn", "error"] as const).pipe( Flag.withDescription("Issue level to exit with non-zero status: none, info, warn, error."), + Flag.annotate(FlagDocumentation, { defaultValue: "none" }), Flag.optional, ), } as const; diff --git a/apps/cli/src/commands/db/lint/lint.command.ts b/apps/cli/src/commands/db/lint/lint.command.ts index 89a98e5a91..f0459f590a 100644 --- a/apps/cli/src/commands/db/lint/lint.command.ts +++ b/apps/cli/src/commands/db/lint/lint.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts"; @@ -29,10 +30,12 @@ const config = { ), level: Flag.Literals("level", ["warning", "error"] as const).pipe( Flag.withDescription("Error level to emit."), + Flag.annotate(FlagDocumentation, { defaultValue: "warning" }), Flag.optional, ), failOn: Flag.Literals("fail-on", ["none", "warning", "error"] as const).pipe( Flag.withDescription("Error level to exit with non-zero status."), + Flag.annotate(FlagDocumentation, { defaultValue: "none" }), Flag.optional, ), } as const; diff --git a/apps/cli/src/commands/db/pull/pull.command.ts b/apps/cli/src/commands/db/pull/pull.command.ts index 0547adb6e2..2c8db65246 100644 --- a/apps/cli/src/commands/db/pull/pull.command.ts +++ b/apps/cli/src/commands/db/pull/pull.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Effect, Layer, Option } from "effect"; import { Argument, Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -44,6 +45,7 @@ const config = { }), diffEngine: Flag.Literals("diff-engine", ["migra", "pg-delta"] as const).pipe( Flag.withDescription("Diff engine to use for migration-style db pull."), + Flag.annotate(FlagDocumentation, { defaultValue: "pg-delta" }), Flag.optional, ), strictCoverage: Flag.Boolean("strict-coverage").pipe( diff --git a/apps/cli/src/commands/db/schema/declarative/sync/sync.command.ts b/apps/cli/src/commands/db/schema/declarative/sync/sync.command.ts index 56b8c1cab1..1d6d5e2074 100644 --- a/apps/cli/src/commands/db/schema/declarative/sync/sync.command.ts +++ b/apps/cli/src/commands/db/schema/declarative/sync/sync.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../../../command-internal/flag-documentation.ts"; import { Effect } from "effect"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -30,6 +31,7 @@ const config = { file: Flag.String("file").pipe( Flag.withAlias("f"), Flag.withDescription("Saves schema diff to a new migration file."), + Flag.annotate(FlagDocumentation, { defaultValue: "declarative_sync" }), Flag.optional, ), name: Flag.String("name").pipe( diff --git a/apps/cli/src/commands/functions/deploy/deploy.command.ts b/apps/cli/src/commands/functions/deploy/deploy.command.ts index 60fa1546ae..b6db8bed5b 100644 --- a/apps/cli/src/commands/functions/deploy/deploy.command.ts +++ b/apps/cli/src/commands/functions/deploy/deploy.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Argument, Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; import { withPermissions } from "../../../command-internal/command-permissions/command-permissions.annotation.ts"; @@ -43,6 +44,7 @@ const config = { (jobs) => `Expected --jobs to be non-negative, got ${jobs}`, ), Flag.withDescription("Maximum number of parallel jobs."), + Flag.annotate(FlagDocumentation, { defaultValue: "1" }), Flag.optional, ), useDocker: Flag.Boolean("use-docker").pipe( diff --git a/apps/cli/src/commands/gen/bearer-jwt/bearer-jwt.command.ts b/apps/cli/src/commands/gen/bearer-jwt/bearer-jwt.command.ts index 95aea2e5dd..898d4ac0a3 100644 --- a/apps/cli/src/commands/gen/bearer-jwt/bearer-jwt.command.ts +++ b/apps/cli/src/commands/gen/bearer-jwt/bearer-jwt.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Layer } from "effect"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -19,11 +20,17 @@ const config = { // `--role` stays optional at parse time so a missing value is enforced in // the handler instead, after telemetry is wired up — see // `GenBearerJwtRoleRequiredError`. - role: Flag.String("role").pipe(Flag.withDescription("Postgres role to use."), Flag.optional), - // The displayed default is cosmetically "anonymous" but the real default - // stays "" — an omitted `--sub` never puts a `sub` claim in the token at - // all. - sub: Flag.String("sub").pipe(Flag.withDescription("User ID to impersonate."), Flag.optional), + role: Flag.String("role").pipe( + Flag.withDescription("Postgres role to use."), + Flag.annotate(FlagDocumentation, { required: true }), + Flag.optional, + ), + // The website retains its compatibility label; an omitted --sub adds no claim. + sub: Flag.String("sub").pipe( + Flag.withDescription("User ID to impersonate."), + Flag.annotate(FlagDocumentation, { defaultValue: "anonymous", helpDefault: false }), + Flag.optional, + ), exp: Flag.String("exp").pipe( Flag.withDescription("Expiry timestamp for this token."), Flag.mapTryCatch( @@ -35,6 +42,7 @@ const config = { validFor: Flag.String("valid-for").pipe( Flag.withDescription("Validity duration for this token."), Flag.withDefault("30m"), + Flag.annotate(FlagDocumentation, { defaultValue: "30m0s" }), Flag.mapTryCatch( (value) => parseBearerJwtValidFor(value), (err) => (err instanceof Error ? err.message : String(err)), diff --git a/apps/cli/src/commands/gen/types/types.languages.ts b/apps/cli/src/commands/gen/types/types.languages.ts index 0c9705b7da..733514ceb8 100644 --- a/apps/cli/src/commands/gen/types/types.languages.ts +++ b/apps/cli/src/commands/gen/types/types.languages.ts @@ -1,5 +1,6 @@ import { languages, type OptionSpec, type OptionValue, type OptionValues } from "@supabase/typegen"; import { Option } from "effect"; +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Flag } from "effect/cli"; /** A user-facing registry option as one CLI flag, merged across the languages that declare it. */ @@ -81,7 +82,17 @@ export const languageFlagsFor = ( `@supabase/typegen declares language flags that collide with CLI flags: ${collisions.join(", ")}`, ); } - return Object.fromEntries(specs.map((spec) => [spec.name, languageFlag(spec)])); + return Object.fromEntries( + specs.map((spec) => [ + spec.name, + languageFlag(spec).pipe( + Flag.annotate( + FlagDocumentation, + spec.default === undefined ? {} : { defaultValue: String(spec.default) }, + ), + ), + ]), + ); }; /** The values the user set, keyed by option name; unset flags are absent. */ @@ -100,16 +111,6 @@ export const optionValuesFor = ( return values; }; -/** Documented defaults keyed the way `DOCS_DEFAULT_OVERRIDES` expects. */ -export const flagDefaultsFor = ( - specs: ReadonlyArray, -): Readonly> => - Object.fromEntries( - specs.flatMap((spec) => - spec.default === undefined ? [] : [[`supabase-gen-types ${spec.name}`, String(spec.default)]], - ), - ); - export const GEN_TYPES_LANGUAGES: ReadonlyArray = languages.map( (language) => language.name, ); @@ -131,8 +132,5 @@ export const GEN_TYPES_LANGUAGE_VALUE_FLAG_NAMES: ReadonlyArray = export const genTypesLanguageFlags = (reservedFlagNames: Iterable) => languageFlagsFor(GEN_TYPES_LANGUAGE_OPTIONS, reservedFlagNames); -export const genTypesLanguageFlagDefaults = (): Readonly> => - flagDefaultsFor(GEN_TYPES_LANGUAGE_OPTIONS); - export const languageOptionValues = (flags: Readonly>): OptionValues => optionValuesFor(GEN_TYPES_LANGUAGE_OPTIONS, flags); diff --git a/apps/cli/src/commands/gen/types/types.languages.unit.test.ts b/apps/cli/src/commands/gen/types/types.languages.unit.test.ts index 2018e97091..7c9d954a1b 100644 --- a/apps/cli/src/commands/gen/types/types.languages.unit.test.ts +++ b/apps/cli/src/commands/gen/types/types.languages.unit.test.ts @@ -1,12 +1,8 @@ import { describe, expect, it } from "@effect/vitest"; import type { OptionSpec } from "@supabase/typegen"; import { Option } from "effect"; -import { - flagDefaultsFor, - languageFlagsFor, - mergeUserOptions, - optionValuesFor, -} from "./types.languages.ts"; +import { languageFlagsFor, mergeUserOptions, optionValuesFor } from "./types.languages.ts"; +import { docsFlagDoc } from "../../../docs/docs-spec.ts"; const level = (choices: ReadonlyArray, fallback: string): OptionSpec => ({ name: "level", @@ -78,11 +74,13 @@ describe("optionValuesFor", () => { }); }); -describe("flagDefaultsFor", () => { +describe("language flag documentation", () => { it("documents a default only when it is unambiguous", () => { - expect(flagDefaultsFor(mergeUserOptions([level(["a"], "a")]))).toEqual({ - "supabase-gen-types level": "a", - }); - expect(flagDefaultsFor(mergeUserOptions([level(["a"], "a"), level(["b"], "b")]))).toEqual({}); + const documented = (specs: ReadonlyArray) => + Object.values(languageFlagsFor(mergeUserOptions(specs), [])).map( + (flag) => docsFlagDoc(["supabase", "gen", "types"], flag)?.default_value, + ); + expect(documented([level(["a"], "a")])).toEqual(["a"]); + expect(documented([level(["a"], "a"), level(["b"], "b")])).toEqual([""]); }); }); diff --git a/apps/cli/src/commands/login/login.command.ts b/apps/cli/src/commands/login/login.command.ts index 62f309f34a..2fbf3fa414 100644 --- a/apps/cli/src/commands/login/login.command.ts +++ b/apps/cli/src/commands/login/login.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../command-internal/flag-documentation.ts"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -17,6 +18,10 @@ const config = { ), name: Flag.String("name").pipe( Flag.withDescription("Name that will be used to store token in your settings."), + Flag.annotate(FlagDocumentation, { + defaultValue: "built-in token name generator", + helpDefault: "generated when omitted", + }), Flag.optional, ), noBrowser: Flag.Boolean("no-browser").pipe( diff --git a/apps/cli/src/commands/storage/cp/cp.command.ts b/apps/cli/src/commands/storage/cp/cp.command.ts index b78ebb93dd..26652dcc24 100644 --- a/apps/cli/src/commands/storage/cp/cp.command.ts +++ b/apps/cli/src/commands/storage/cp/cp.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Effect } from "effect"; import { Argument, Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -16,8 +17,6 @@ import { STORAGE_PERMISSIONS, storageTargetFlags } from "../storage.flags.ts"; import { storageCp } from "./cp.handler.ts"; import { withTargetPolicy } from "../../../command-internal/target/target-policy.ts"; -// Effect CLI renders no flag defaults, so the established `(default …)` tokens are written into -// the descriptions below (`--content-type`'s actual runtime default is `""` for auto-detect). // Flags are declared before `src`/`dst` on purpose: Effect CLI validates flags before positional // args in declaration order, so a malformed `--jobs` must fail before a missing-operand error. const config = { @@ -28,10 +27,12 @@ const config = { ), cacheControl: Flag.String("cache-control").pipe( Flag.withDescription('Custom Cache-Control header for HTTP upload. (default "max-age=3600")'), + Flag.annotate(FlagDocumentation, { defaultValue: "max-age=3600" }), Flag.optional, ), contentType: Flag.String("content-type").pipe( Flag.withDescription('Custom Content-Type header for HTTP upload. (default "auto-detect")'), + Flag.annotate(FlagDocumentation, { defaultValue: "auto-detect" }), Flag.optional, ), jobs: Flag.String("jobs").pipe( @@ -40,6 +41,7 @@ const config = { // `withMetavar` keeps the `--jobs, -j integer` help token. Flag.withMetavar("integer"), Flag.withDescription("Maximum number of parallel jobs. (default 1)"), + Flag.annotate(FlagDocumentation, { defaultValue: "1" }), // `--jobs` is a uint: a non-uint token must fail at parse time, before the // experimental gate, the handler, or any telemetry, with the exact message and original // spelling preserved. `Flag.Int` loses that fidelity (`-0` normalizes to negative zero, diff --git a/apps/cli/src/commands/test/new/new.command.ts b/apps/cli/src/commands/test/new/new.command.ts index 922c989c36..6f3133b25e 100644 --- a/apps/cli/src/commands/test/new/new.command.ts +++ b/apps/cli/src/commands/test/new/new.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Layer } from "effect"; import { Argument, Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -19,6 +20,7 @@ const config = { template: Flag.Literals("template", TEMPLATE_VALUES).pipe( Flag.withAlias("t"), Flag.withDescription("Template framework to generate."), + Flag.annotate(FlagDocumentation, { defaultValue: "pgtap" }), Flag.optional, ), } as const; diff --git a/apps/cli/src/commands/vanity-subdomains/activate/activate.command.ts b/apps/cli/src/commands/vanity-subdomains/activate/activate.command.ts index dfe369822f..3b47fb05e9 100644 --- a/apps/cli/src/commands/vanity-subdomains/activate/activate.command.ts +++ b/apps/cli/src/commands/vanity-subdomains/activate/activate.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Effect } from "effect"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -26,6 +27,7 @@ const config = { // resolution. desiredSubdomain: Flag.String("desired-subdomain").pipe( Flag.withDescription("The desired vanity subdomain to use for your Supabase project."), + Flag.annotate(FlagDocumentation, { required: true }), Flag.optional, ), } as const; diff --git a/apps/cli/src/commands/vanity-subdomains/check-availability/check-availability.command.ts b/apps/cli/src/commands/vanity-subdomains/check-availability/check-availability.command.ts index 2e21251ac1..2a2116e439 100644 --- a/apps/cli/src/commands/vanity-subdomains/check-availability/check-availability.command.ts +++ b/apps/cli/src/commands/vanity-subdomains/check-availability/check-availability.command.ts @@ -1,3 +1,4 @@ +import { FlagDocumentation } from "../../../command-internal/flag-documentation.ts"; import { Effect } from "effect"; import { Command, Flag } from "effect/cli"; import type * as CliCommand from "effect/cli/Command"; @@ -26,6 +27,7 @@ const config = { // resolution. desiredSubdomain: Flag.String("desired-subdomain").pipe( Flag.withDescription("The desired vanity subdomain to use for your Supabase project."), + Flag.annotate(FlagDocumentation, { required: true }), Flag.optional, ), } as const; diff --git a/apps/cli/src/docs/docs-spec.tables.ts b/apps/cli/src/docs/docs-spec.tables.ts index 905ca8f7d3..c2236664b7 100644 --- a/apps/cli/src/docs/docs-spec.tables.ts +++ b/apps/cli/src/docs/docs-spec.tables.ts @@ -1,10 +1,9 @@ import type { DocsFlag } from "./docs-spec.ts"; -import { genTypesLanguageFlagDefaults } from "../commands/gen/types/types.languages.ts"; /** * Static data the Effect command tree cannot express structurally: docs-site section tags, - * `--experimental`-required leaves, deprecated commands, and flag defaults that - * `Flag.withDefault` only captures in a closure. `buildDocsSpec` fails the build on stale keys. + * `--experimental`-required leaves, deprecated commands, argument usage exceptions and + * query-specific output formats. `buildDocsSpec` fails the build on stale keys. */ export interface DocsInfoTag { @@ -111,42 +110,6 @@ export const DOCS_EXCLUDED: ReadonlySet = new Set([ "supabase-inspect-db-unused-indexes", ]); -/** - * Flag defaults that differ from the primitive type's zero value, keyed - * `" "` (root global flags use doc id `supabase`). TS-only - * flags add entries by hand. - */ -export const DOCS_DEFAULT_OVERRIDES: Readonly> = { - ...genTypesLanguageFlagDefaults(), - "supabase agent": "auto", - "supabase dns-resolver": "native", - "supabase output": "pretty", - "supabase output-format": "text", - "supabase profile": "supabase", - "supabase-db-advisors fail-on": "none", - "supabase-db-advisors level": "warn", - "supabase-db-advisors type": "all", - "supabase-db-lint fail-on": "none", - "supabase-db-lint level": "warning", - "supabase-db-pull diff-engine": "pg-delta", - "supabase-db-schema-declarative-sync file": "declarative_sync", - "supabase-functions-deploy jobs": "1", - "supabase-functions-new auth": "apikey", - "supabase-gen-bearer-jwt payload": "{}", - "supabase-gen-bearer-jwt sub": "anonymous", - "supabase-gen-bearer-jwt valid-for": "30m0s", - "supabase-gen-signing-key algorithm": "ES256", - "supabase-gen-types lang": "typescript", - "supabase-gen-types query-timeout": "15s", - "supabase-inspect-report output-dir": ".", - "supabase-login name": "built-in token name generator", - "supabase-migration-down last": "1", - "supabase-storage-cp cache-control": "max-age=3600", - "supabase-storage-cp content-type": "auto-detect", - "supabase-storage-cp jobs": "1", - "supabase-test-new template": "pgtap", -}; - /** * Flag docs injected into specific commands beyond what their Effect config * declares, keyed by doc id. `db query` reuses the global `-o, --output` @@ -169,16 +132,6 @@ export const DOCS_EXTRA_FLAGS: Readonly>> ], }; -export const DOCS_CHOICE_OVERRIDES: Readonly>> = { - "supabase output": ["env", "pretty", "json", "toml", "yaml"], -}; - -/** - * Flags excluded from the published reference, keyed `" "`. Validated at build - * time like the other tables. - */ -export const DOCS_EXCLUDED_FLAGS: ReadonlySet = new Set([]); - /** * Usage argument overrides, keyed by doc id, for commands whose published argument rendering * can't be derived from the Effect tree: the parser accepts zero occurrences here @@ -190,20 +143,5 @@ export const DOCS_ARG_OVERRIDES: Readonly> = { "supabase-storage-rm": " ...", }; -/** - * Flags rendered with a Required badge on the docs site, keyed - * `" "`. Effect optionality cannot express this — several - * of these TS flags are intentionally `Flag.optional` at parse time for - * validation-ordering reasons unrelated to required-ness. - */ -export const DOCS_REQUIRED: ReadonlySet = new Set([ - "supabase-domains-create custom-hostname", - "supabase-gen-bearer-jwt role", - "supabase-migration-repair status", - "supabase-sso-add type", - "supabase-vanity-subdomains-activate desired-subdomain", - "supabase-vanity-subdomains-check-availability desired-subdomain", -]); - export const DOCS_INFO_DESCRIPTION = "Supabase CLI provides you with tools to develop your application locally, and deploy your application to the Supabase platform."; diff --git a/apps/cli/src/docs/docs-spec.ts b/apps/cli/src/docs/docs-spec.ts index e3b440da07..4ef6bb100a 100644 --- a/apps/cli/src/docs/docs-spec.ts +++ b/apps/cli/src/docs/docs-spec.ts @@ -10,20 +10,17 @@ import { userGlobalFlagParams, } from "./docs-introspection.ts"; import { unwrapParam } from "../command-internal/param-introspection.ts"; +import { flagDefault, flagDocumentation } from "../command-internal/flag-documentation.ts"; import { isRemoteFlag } from "../command-internal/target/target-flags.ts"; import { remoteFlagName } from "../shared/output/target-help.ts"; import { DOCS_ARG_OVERRIDES, - DOCS_CHOICE_OVERRIDES, - DOCS_DEFAULT_OVERRIDES, DOCS_EXCLUDED, - DOCS_EXCLUDED_FLAGS, DOCS_EXPERIMENTAL, DOCS_EXPERIMENTAL_OPTIONAL, DOCS_EXTRA_FLAGS, DOCS_INFO_DESCRIPTION, DOCS_INFO_TAGS, - DOCS_REQUIRED, DOCS_TAGS, } from "./docs-spec.tables.ts"; import type { DocsInfoTag } from "./docs-spec.tables.ts"; @@ -190,14 +187,12 @@ export function docsFlagDoc( ); } const { single, isVariadic } = unwrapped; - if (single.hidden) return undefined; - - const docId = commandPath.join("-"); - const overrideKey = `${docId} ${single.name}`; + const documentation = flagDocumentation(single); + if (single.hidden || documentation.hidden) return undefined; let acceptedValues: ReadonlyArray | undefined; let enumType: string | undefined; - const choices = DOCS_CHOICE_OVERRIDES[overrideKey] ?? choiceKeysOf(single.primitiveType); + const choices = documentation.choices ?? choiceKeysOf(single.primitiveType); if (choices !== undefined) { enumType = docsEnumTypeString(choices); const type = enumType; @@ -213,14 +208,15 @@ export function docsFlagDoc( : `${single.name}${varname === undefined ? "" : ` <${varname}>`}`; const name = `${shorthand === undefined ? "" : `-${shorthand}, `}--${longName}`; - const required = DOCS_REQUIRED.has(overrideKey); + const required = + documentation.required ?? (!unwrapped.isOptional && (!isVariadic || unwrapped.variadicMin > 0)); return { id: single.name, name, description: docsNormalizeText(Option.getOrElse(single.description, () => "")), ...(required ? { required: true } : {}), - default_value: DOCS_DEFAULT_OVERRIDES[overrideKey] ?? docsTypeDefault(single, isVariadic), + default_value: flagDefault(unwrapped) ?? docsTypeDefault(single, isVariadic), ...(acceptedValues === undefined ? {} : { accepted_values: acceptedValues }), }; } @@ -343,36 +339,19 @@ export function buildDocsSpec(input: DocsSpecInput): DocsSpec { const commands: Array = []; const emittedIds = new Set(); const skippedExcludedIds = new Set(); - const seenFlagKeys = new Set(rootFlags.map((flag) => `supabase ${flag.id}`)); - const consumedExcludedFlagKeys = new Set(); const consumedArgOverrideIds = new Set(); const consumedExtraFlagIds = new Set(); const consumedExperimentalIds = new Set(); const consumedOverlayPaths = new Set(); const allowedOrphanOverlayPaths = new Set(); - /** - * Builds the visible flag docs for a command's params, dropping hidden flags and - * `DOCS_EXCLUDED_FLAGS` entries. Does not record `seenFlagKeys` itself — callers record - * only the flags that reach the output, so table validation reflects the published spec, - * not intermediate candidates. - */ const flagDocsFor = ( commandPath: ReadonlyArray, params: ReadonlyArray, ): ReadonlyArray => { - const docId = commandPath.join("-"); return params .map((param) => docsFlagDoc(commandPath, param)) .filter((flag) => flag !== undefined) - .filter((flag) => { - const key = `${docId} ${flag.id}`; - if (DOCS_EXCLUDED_FLAGS.has(key)) { - consumedExcludedFlagKeys.add(key); - return false; - } - return true; - }) .toSorted((a, b) => docsCompare(a.id, b.id)); }; @@ -414,7 +393,6 @@ export function buildDocsSpec(input: DocsSpecInput): DocsSpec { } } const own = [...declared, ...(extraFlags ?? [])].toSorted((a, b) => docsCompare(a.id, b.id)); - own.forEach((flag) => seenFlagKeys.add(`${docId} ${flag.id}`)); flags.push(...own); if (DOCS_EXPERIMENTAL.has(docId)) { consumedExperimentalIds.add(docId); @@ -428,7 +406,6 @@ export function buildDocsSpec(input: DocsSpecInput): DocsSpec { const inherited = flagDocsFor(commandPath, inheritedParams).filter( (flag) => !ownIds.has(flag.id) && !rootFlagIds.has(flag.id), ); - inherited.forEach((flag) => seenFlagKeys.add(`${docId} ${flag.id}`)); flags.push(...inherited); } @@ -492,8 +469,6 @@ export function buildDocsSpec(input: DocsSpecInput): DocsSpec { validateDocsTables({ emittedIds, skippedExcludedIds, - seenFlagKeys, - consumedExcludedFlagKeys, consumedArgOverrideIds, consumedExtraFlagIds, consumedExperimentalIds, @@ -546,16 +521,11 @@ export function stringifyDocsSpec(spec: DocsSpec): string { function validateDocsTables(seen: { readonly emittedIds: ReadonlySet; readonly skippedExcludedIds: ReadonlySet; - readonly seenFlagKeys: ReadonlySet; - readonly consumedExcludedFlagKeys: ReadonlySet; readonly consumedArgOverrideIds: ReadonlySet; readonly consumedExtraFlagIds: ReadonlySet; readonly consumedExperimentalIds: ReadonlySet; }): void { const stale: Array = []; - for (const key of Object.keys(DOCS_DEFAULT_OVERRIDES)) { - if (!seen.seenFlagKeys.has(key)) stale.push(`DOCS_DEFAULT_OVERRIDES: "${key}"`); - } for (const id of Object.keys(DOCS_TAGS)) { if (!seen.emittedIds.has(id)) stale.push(`DOCS_TAGS: "${id}"`); } @@ -567,21 +537,12 @@ function validateDocsTables(seen: { stale.push(`DOCS_EXPERIMENTAL_OPTIONAL: "${id}"`); } } - for (const key of Object.keys(DOCS_CHOICE_OVERRIDES)) { - if (!seen.seenFlagKeys.has(key)) stale.push(`DOCS_CHOICE_OVERRIDES: "${key}"`); - } for (const id of Object.keys(DOCS_EXTRA_FLAGS)) { if (!seen.consumedExtraFlagIds.has(id)) stale.push(`DOCS_EXTRA_FLAGS: "${id}"`); } for (const id of DOCS_EXCLUDED) { if (!seen.skippedExcludedIds.has(id)) stale.push(`DOCS_EXCLUDED: "${id}"`); } - for (const key of DOCS_REQUIRED) { - if (!seen.seenFlagKeys.has(key)) stale.push(`DOCS_REQUIRED: "${key}"`); - } - for (const key of DOCS_EXCLUDED_FLAGS) { - if (!seen.consumedExcludedFlagKeys.has(key)) stale.push(`DOCS_EXCLUDED_FLAGS: "${key}"`); - } for (const id of Object.keys(DOCS_ARG_OVERRIDES)) { if (!seen.consumedArgOverrideIds.has(id)) stale.push(`DOCS_ARG_OVERRIDES: "${id}"`); } diff --git a/apps/cli/src/docs/docs-spec.unit.test.ts b/apps/cli/src/docs/docs-spec.unit.test.ts index edc43983c6..d13ce7f7f2 100644 --- a/apps/cli/src/docs/docs-spec.unit.test.ts +++ b/apps/cli/src/docs/docs-spec.unit.test.ts @@ -1,6 +1,7 @@ import { BunServices } from "@effect/platform-bun"; import { beforeAll, describe, expect, it } from "@effect/vitest"; -import { Effect, FileSystem, Path } from "effect"; +import { Config, Effect, FileSystem, Path } from "effect"; +import { FlagDocumentation } from "../command-internal/flag-documentation.ts"; import { Command, Flag } from "effect/cli"; import type { PlatformError } from "effect/PlatformError"; @@ -88,6 +89,73 @@ describe("docsStripOverlayHeading", () => { }); describe("docsFlagDoc", () => { + it.each([ + [Flag.String("value").pipe(Flag.withDefault("custom")), "custom"], + [Flag.Int("value").pipe(Flag.withDefault(42)), "42"], + [Flag.String("value").pipe(Flag.withDefault("inner"), Flag.withDefault("outer")), "inner"], + [ + Flag.String("value").pipe( + Flag.withDefault("inner"), + Flag.withDefault(Effect.die("must not execute")), + ), + "inner", + ], + [Flag.Boolean("value").pipe(Flag.withDefault(true)), "true"], + [Flag.String("value").pipe(Flag.atLeast(0), Flag.withDefault(["public"])), '["public"]'], + [ + Flag.String("value").pipe( + Flag.withDefault("30m"), + Flag.map((value) => value.length), + ), + "30m", + ], + ])("derives literal defaults without parsing: %s", (flag, expected) => { + expect(docsFlagDoc(["supabase", "fixture"], flag)?.default_value).toBe(expected); + expect(docsFlagDoc(["supabase", "fixture"], flag)?.required).toBeUndefined(); + }); + + it("does not run effectful defaults or config lookups to build docs", () => { + const flags = [ + Flag.String("value").pipe( + Flag.withDefault(Effect.die("must not execute")), + Flag.withDefault("outer"), + ), + Flag.String("value").pipe(Flag.withFallbackConfig(Config.String("DOCS_SECRET"))), + ]; + for (const flag of flags) { + expect(docsFlagDoc(["supabase", "fixture"], flag)).toMatchObject({ default_value: "" }); + expect(docsFlagDoc(["supabase", "fixture"], flag)?.required).toBeUndefined(); + } + }); + + it.each([ + [Flag.String("value"), true], + [Flag.String("value").pipe(Flag.optional), undefined], + [Flag.String("value").pipe(Flag.atLeast(0)), undefined], + [Flag.String("value").pipe(Flag.atLeast(2)), true], + ])("derives required badges from flag cardinality: %s", (flag, required) => { + expect(docsFlagDoc(["supabase", "fixture"], flag)?.required).toBe(required); + }); + + it("reads website exceptions from flag-local annotations", () => { + const flag = Flag.Literals("value", ["a", "b"]).pipe( + Flag.optional, + Flag.annotate(FlagDocumentation, { defaultValue: "a", required: true, choices: ["a"] }), + ); + expect(docsFlagDoc(["supabase", "fixture"], flag)).toMatchObject({ + default_value: "a", + required: true, + accepted_values: [{ id: "a", name: "a", type: "[ a ]" }], + }); + expect(docsFlagDoc(["supabase", "fixture"], flag.pipe(Flag.withHidden))).toBeUndefined(); + expect( + docsFlagDoc( + ["supabase", "fixture"], + flag.pipe(Flag.annotate(FlagDocumentation, { hidden: true })), + ), + ).toBeUndefined(); + }); + it("renders --remote with the value hint its declaration carries", () => { const doc = docsFlagDoc(["supabase", "db", "push"], remoteFlag); diff --git a/apps/cli/src/shared/cli/version.integration.test.ts b/apps/cli/src/shared/cli/version.integration.test.ts index 9fc5f45811..5ed50c65c4 100644 --- a/apps/cli/src/shared/cli/version.integration.test.ts +++ b/apps/cli/src/shared/cli/version.integration.test.ts @@ -12,7 +12,7 @@ import { CLI_VERSION } from "./version.ts"; const builtinLayer = (args: ReadonlyArray, console: Console.Console) => Layer.mergeAll( - CliOutput.layer(textCliOutputFormatter()), + CliOutput.layer(textCliOutputFormatter({ rootCommand, args })), Layer.succeed(CliArgs, { args }), Layer.succeed(Console.Console, console), mockOutput({ format: "text" }).layer, @@ -20,6 +20,19 @@ const builtinLayer = (args: ReadonlyArray, console: Console.Console) => ); describe("CLI --help (text)", () => { + it.effect("db query help does not advertise a fixed global output default", () => + Effect.gen(function* () { + const args = ["db", "query", "--help"]; + const { console, calls } = fakeConsole(); + yield* Command.runWith(rootCommand, { version: CLI_VERSION })(args).pipe( + Effect.provide(builtinLayer(args, console)), + ); + const help = calls.join("\n"); + expect(help).toContain("output format of status variables"); + expect(help).not.toContain("(default: pretty)"); + }), + ); + it.effect("source runs describe themselves as a development build", () => Effect.gen(function* () { const { console, calls } = fakeConsole(); diff --git a/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts b/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts new file mode 100644 index 0000000000..0ad081ac64 --- /dev/null +++ b/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from "@effect/vitest"; +import { Config, Console, Effect, Layer, Option, Ref, Schema } from "effect"; +import { CliOutput, Command, Flag, GlobalFlag } from "effect/cli"; +import { emptyEnv, fakeConsole } from "../../../tests/helpers/mocks.ts"; +import { FlagDocumentation } from "../../command-internal/flag-documentation.ts"; +import { textCliOutputFormatter } from "./text-formatter.ts"; +import { jsonCliOutputFormatter } from "./json-formatter.ts"; + +const global = GlobalFlag.Setting("fixture-mode")({ + flag: Flag.String("fixture-mode").pipe(Flag.withDefault("global-mode")), +}); +const child = Command.make( + "child", + { + count: Flag.Int("count").pipe(Flag.withDescription("Count."), Flag.withDefault(42)), + effectful: Flag.String("effectful").pipe(Flag.withDefault(Effect.die("default executed"))), + config: Flag.String("config").pipe(Flag.withFallbackConfig(Config.String("HELP_SECRET"))), + handler: Flag.String("handler").pipe( + Flag.optional, + Flag.annotate(FlagDocumentation, { defaultValue: "handler-value" }), + ), + sub: Flag.String("sub").pipe( + Flag.optional, + Flag.annotate(FlagDocumentation, { defaultValue: "anonymous", helpDefault: false }), + ), + authored: Flag.String("authored").pipe( + Flag.withDefault("old"), + Flag.withDescription("Authored (default old)"), + ), + hidden: Flag.String("hidden").pipe(Flag.withDefault("hidden-value"), Flag.withHidden), + }, + () => Effect.void, +); +const root = Command.make("fixture").pipe( + Command.withSharedFlags({ shared: Flag.String("shared").pipe(Flag.withDefault("shared-value")) }), + Command.withGlobalFlags([global]), + Command.withSubcommands([child]), +); + +const helpFor = (formatter: CliOutput.Formatter) => + Effect.gen(function* () { + const { console, calls } = fakeConsole(); + yield* Command.runWith(root, { version: "test" })(["child", "--help"]).pipe( + Effect.provide( + Layer.mergeAll( + emptyEnv(), + Layer.succeed(Console.Console, console), + CliOutput.layer(formatter), + ), + ), + ); + return calls.join("\n").replace(/^log:/, ""); + }); + +describe("flag defaults in help", () => { + it.effect("keeps documentation exceptions out of parsing and handler values", () => + Effect.gen(function* () { + const observed = yield* Ref.make(undefined); + const command = Command.make( + "fixture", + { + value: Flag.Literals("value", ["a", "b"]).pipe( + Flag.withDefault("b"), + Flag.annotate(FlagDocumentation, { defaultValue: "a", choices: ["a"] }), + ), + omitted: Flag.String("omitted").pipe( + Flag.optional, + Flag.annotate(FlagDocumentation, { required: true }), + ), + }, + (flags) => Ref.set(observed, flags), + ); + yield* Command.runWith(command, { version: "test" })([]).pipe(Effect.provide(emptyEnv())); + expect(yield* Ref.get(observed)).toEqual({ value: "b", omitted: Option.none() }); + yield* Command.runWith(command, { version: "test" })(["--value", "b"]).pipe( + Effect.provide(emptyEnv()), + ); + expect(yield* Ref.get(observed)).toEqual({ value: "b", omitted: Option.none() }); + }), + ); + + it.effect( + "shows literal and handler defaults across local, inherited and global text flags", + () => + Effect.gen(function* () { + const text = yield* helpFor( + textCliOutputFormatter({ rootCommand: root, args: ["child", "--help"] }), + ); + expect(text).toContain("Count. (default: 42)"); + expect(text).toContain("(default: handler-value)"); + expect(text).toContain("(default: shared-value)"); + expect(text).toContain("(default: global-mode)"); + expect(text).toContain("Authored (default old)"); + expect(text).not.toContain("Authored (default old) (default:"); + expect(text).not.toContain("anonymous"); + expect(text).not.toContain("hidden-value"); + expect(text).not.toContain("default executed"); + expect(text).not.toContain("HELP_SECRET"); + }), + ); + + it.effect("keeps JSON help flag fields and descriptions unchanged", () => + Effect.gen(function* () { + const printed = yield* helpFor( + jsonCliOutputFormatter({ rootCommand: root, args: ["child", "--help"] }), + ); + const help = yield* Schema.decodeEffect( + Schema.fromJsonString( + Schema.Struct({ + doc: Schema.Struct({ flags: Schema.Array(Schema.Unknown) }), + }), + ), + )(printed); + expect(help.doc.flags).toContainEqual({ + name: "count", + aliases: [], + type: "integer", + description: { _id: "Option", _tag: "Some", value: "Count." }, + required: false, + }); + expect(printed).not.toContain("default:"); + expect(printed).not.toContain("handler-value"); + expect(printed).not.toContain("anonymous"); + }), + ); +}); diff --git a/apps/cli/src/shared/output/flag-defaults-help.ts b/apps/cli/src/shared/output/flag-defaults-help.ts new file mode 100644 index 0000000000..09e5e0d346 --- /dev/null +++ b/apps/cli/src/shared/output/flag-defaults-help.ts @@ -0,0 +1,77 @@ +import { Option } from "effect"; +import type { Command, HelpDoc, Param } from "effect/cli"; +import { flagDefault, flagDocumentation } from "../../command-internal/flag-documentation.ts"; +import { unwrapParam } from "../../command-internal/param-introspection.ts"; +import { + commandInternals, + flattenSubcommands, + userGlobalFlagParams, +} from "../../docs/docs-introspection.ts"; + +function defaultsFor(params: ReadonlyArray): ReadonlyMap { + const defaults = new Map(); + for (const param of params) { + const unwrapped = unwrapParam(param); + if (unwrapped === undefined) continue; + const { helpDefault } = flagDocumentation(unwrapped.single); + if (helpDefault === false) continue; + const value = helpDefault ?? flagDefault(unwrapped); + if (value !== undefined && value !== "") defaults.set(unwrapped.single.name, value); + } + return defaults; +} + +function withDefaults( + flags: ReadonlyArray, + defaults: ReadonlyMap, +): ReadonlyArray { + return flags.map((flag) => { + const value = defaults.get(flag.name); + if (value === undefined) return flag; + const description = Option.getOrElse(flag.description, () => ""); + // Authored descriptions already carrying a default keep their established wording. + if (/\bdefault\b/i.test(description)) return flag; + return { + ...flag, + description: Option.some(`${description}${description === "" ? "" : " "}(default: ${value})`), + }; + }); +} + +/** Adds display-only defaults to text help without altering the JSON help document. */ +export function withFlagDefaults( + doc: HelpDoc.HelpDoc, + root: Command.Command.Any | undefined, +): HelpDoc.HelpDoc { + if (root === undefined) return doc; + const commandPath: Array = []; + for (const token of doc.commandPath ?? doc.usage.split(" ")) { + if (token.startsWith("[") || token.startsWith("<")) break; + commandPath.push(token); + } + let current = root; + const inherited: Array = []; + const globals: Array = [...userGlobalFlagParams(root)]; + for (const segment of commandPath.slice(1)) { + inherited.push(...commandInternals(current).contextConfig.flags); + const next = flattenSubcommands(current).find( + (child) => child.name === segment || child.alias === segment, + ); + if (next === undefined) return doc; + current = next; + globals.push(...userGlobalFlagParams(current)); + } + return { + ...doc, + flags: withDefaults( + doc.flags, + defaultsFor([...inherited, ...commandInternals(current).config.flags]), + ), + ...(doc.inheritedFlags === undefined + ? {} + : { inheritedFlags: withDefaults(doc.inheritedFlags, defaultsFor(inherited)) }), + ...(doc.globalFlags === undefined + ? {} + : { globalFlags: withDefaults(doc.globalFlags, defaultsFor(globals)) }), + }; +} diff --git a/apps/cli/src/shared/output/text-formatter.ts b/apps/cli/src/shared/output/text-formatter.ts index 41469523b3..eef8904ce7 100644 --- a/apps/cli/src/shared/output/text-formatter.ts +++ b/apps/cli/src/shared/output/text-formatter.ts @@ -1,6 +1,7 @@ import { CliOutput } from "effect/cli"; import { supportsColor, type ColorStream } from "../../command-internal/colors.ts"; import { withHelpMarkdown } from "./help-markdown.ts"; +import { withFlagDefaults } from "./flag-defaults-help.ts"; import { withOptionalSubcommandUsage } from "./optional-subcommand-usage.ts"; import { permissionSectionForHelp, @@ -45,7 +46,9 @@ export function textCliOutputFormatter( const help = CliOutput.defaultFormatter({ colors }); const rendered = withHelpMarkdown( withOptionalSubcommandUsage( - withRemoteFlagUsage(labelSubcommands(doc, context?.rootCommand)), + withRemoteFlagUsage( + withFlagDefaults(labelSubcommands(doc, context?.rootCommand), context?.rootCommand), + ), ), colors, ); From 55f286e45258ac3b105d107f071923589a12c0af Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Wed, 18 Nov 2026 14:31:24 -0700 Subject: [PATCH 2/3] fix(cli): render flag defaults from their declarations --- .../command-internal/flag-documentation.ts | 1 - apps/cli/src/command-internal/global-flags.ts | 4 +- .../command-internal/param-introspection.ts | 4 +- .../experimental/stack/logs/logs.command.ts | 2 +- .../src/commands/gen/types/types.command.ts | 4 +- .../src/commands/gen/types/types.languages.ts | 3 +- apps/cli/src/commands/logs/logs.command.ts | 2 +- .../postgres-config/update/update.command.ts | 2 +- .../cli/src/commands/storage/cp/cp.command.ts | 6 +- apps/cli/src/docs/docs-spec.ts | 2 +- apps/cli/src/docs/docs-spec.unit.test.ts | 15 +- .../shared/cli/version.integration.test.ts | 27 ++-- .../flag-defaults-help.integration.test.ts | 128 ++++++++++++++++-- .../src/shared/output/flag-defaults-help.ts | 41 ++++-- apps/cli/src/shared/output/text-formatter.ts | 11 +- 15 files changed, 190 insertions(+), 62 deletions(-) diff --git a/apps/cli/src/command-internal/flag-documentation.ts b/apps/cli/src/command-internal/flag-documentation.ts index 590d7e461c..5790b9870c 100644 --- a/apps/cli/src/command-internal/flag-documentation.ts +++ b/apps/cli/src/command-internal/flag-documentation.ts @@ -6,7 +6,6 @@ export interface FlagDocumentationShape { readonly defaultValue?: string; readonly choices?: ReadonlyArray; readonly required?: boolean; - readonly hidden?: boolean; /** Website compatibility labels need not describe an actual runtime default. */ readonly helpDefault?: string | false; } diff --git a/apps/cli/src/command-internal/global-flags.ts b/apps/cli/src/command-internal/global-flags.ts index 6ff93e1bb5..43d1b6f36c 100644 --- a/apps/cli/src/command-internal/global-flags.ts +++ b/apps/cli/src/command-internal/global-flags.ts @@ -45,7 +45,7 @@ export const OutputFlag = GlobalFlag.Setting("output")({ /** The TS-only `--output-format` global, accepted on any subcommand. */ export const OutputFormatFlag = GlobalFlag.Setting("output-format")({ flag: Flag.Literals("output-format", ["text", "json", "stream-json"]).pipe( - Flag.withDescription("Output format: text (default), json, or stream-json (NDJSON)"), + Flag.withDescription("Output format: text, json, or stream-json (NDJSON)"), Flag.annotate(FlagDocumentation, { defaultValue: "text" }), Flag.optional, ), @@ -116,7 +116,7 @@ export const CreateTicketFlag = GlobalFlag.Setting("create-ticket")({ export const AgentFlag = GlobalFlag.Setting("agent")({ flag: Flag.Literals("agent", ["auto", "yes", "no"] as const).pipe( - Flag.withDescription("Override agent detection: yes, no, or auto (default auto)"), + Flag.withDescription("Override agent detection: yes, no, or auto"), Flag.withDefault("auto" as const), ), }); diff --git a/apps/cli/src/command-internal/param-introspection.ts b/apps/cli/src/command-internal/param-introspection.ts index cf845d9d6f..ce8955df2c 100644 --- a/apps/cli/src/command-internal/param-introspection.ts +++ b/apps/cli/src/command-internal/param-introspection.ts @@ -59,8 +59,8 @@ export function unwrapParam(param: Param.Any): UnwrappedParam | undefined { while (!Param.isSingle(current)) { if (!isWrappedParam(current)) return undefined; - if (current._tag === "Optional") isOptional = true; - if (isFallbackParam(current) && current.fallback) { + if (!isVariadic && current._tag === "Optional") isOptional = true; + if (!isVariadic && isFallbackParam(current) && current.fallback) { isOptional = true; defaultValue = current.fallback._tag === "Default" ? Option.some(current.fallback.value) : Option.none(); diff --git a/apps/cli/src/commands/experimental/stack/logs/logs.command.ts b/apps/cli/src/commands/experimental/stack/logs/logs.command.ts index 2a2d3a55f9..751a7673b9 100644 --- a/apps/cli/src/commands/experimental/stack/logs/logs.command.ts +++ b/apps/cli/src/commands/experimental/stack/logs/logs.command.ts @@ -33,7 +33,7 @@ const config = { (tail) => `Expected --tail to be 0 or more, got ${tail}`, ), Flag.withDescription( - "Number of retained lines to print across the selected services (default 200); 0 prints none.", + "Number of retained lines to print across the selected services; 0 prints none.", ), Flag.withDefault(200), ), diff --git a/apps/cli/src/commands/gen/types/types.command.ts b/apps/cli/src/commands/gen/types/types.command.ts index bd2b7ee1cd..f11d5dd95f 100644 --- a/apps/cli/src/commands/gen/types/types.command.ts +++ b/apps/cli/src/commands/gen/types/types.command.ts @@ -45,7 +45,7 @@ const config = { ...targetFlags({ subject: "database", dbUrl: true }), projectId: deprecatedProjectIdFlag, lang: Flag.Literals("lang", GEN_TYPES_LANGUAGES).pipe( - Flag.withDescription("Output language of the generated types. (default typescript)"), + Flag.withDescription("Output language of the generated types."), Flag.withDefault("typescript"), ), schema: Flag.String("schema").pipe( @@ -64,7 +64,7 @@ const config = { Flag.withDefault(false), ), queryTimeout: Flag.String("query-timeout").pipe( - Flag.withDescription("Maximum timeout allowed for the database query. (default 15s)"), + Flag.withDescription("Maximum timeout allowed for the database query."), Flag.withDefault("15s"), ), } as const; diff --git a/apps/cli/src/commands/gen/types/types.languages.ts b/apps/cli/src/commands/gen/types/types.languages.ts index 733514ceb8..c1e9378bf9 100644 --- a/apps/cli/src/commands/gen/types/types.languages.ts +++ b/apps/cli/src/commands/gen/types/types.languages.ts @@ -55,8 +55,7 @@ export const mergeUserOptions = ( }; const languageFlag = (spec: LanguageFlagSpec): Flag.Flag => { - const help = - spec.default === undefined ? spec.help : `${spec.help} (default ${String(spec.default)})`; + const { help } = spec; switch (spec.kind) { case "boolean": return Flag.Boolean(spec.name).pipe(Flag.withDescription(help), Flag.optional); diff --git a/apps/cli/src/commands/logs/logs.command.ts b/apps/cli/src/commands/logs/logs.command.ts index d4ddc3ffd8..5f753405f7 100644 --- a/apps/cli/src/commands/logs/logs.command.ts +++ b/apps/cli/src/commands/logs/logs.command.ts @@ -78,7 +78,7 @@ const config = { ), limit: Flag.Int("limit").pipe( Flag.withDescription( - "Initial filtered history count (default 100, maximum 1000). SQL controls its own LIMIT.", + "Initial filtered history count (maximum 1000). SQL controls its own LIMIT.", ), Flag.filter( (value) => value >= 1 && value <= 1000, diff --git a/apps/cli/src/commands/postgres-config/update/update.command.ts b/apps/cli/src/commands/postgres-config/update/update.command.ts index 72671a8af6..3091b2732e 100644 --- a/apps/cli/src/commands/postgres-config/update/update.command.ts +++ b/apps/cli/src/commands/postgres-config/update/update.command.ts @@ -35,7 +35,7 @@ const config = { config: postgresConfigUpdateConfigFlag, replaceExistingOverrides: Flag.Boolean("replace-existing-overrides").pipe( Flag.withDescription( - "If true, replaces all existing overrides with the ones provided. If false (default), merges existing overrides with the ones provided.", + "Replace all existing overrides with the ones provided. Omit this flag to merge overrides instead.", ), Flag.withDefault(false), ), diff --git a/apps/cli/src/commands/storage/cp/cp.command.ts b/apps/cli/src/commands/storage/cp/cp.command.ts index 26652dcc24..8c132f37f2 100644 --- a/apps/cli/src/commands/storage/cp/cp.command.ts +++ b/apps/cli/src/commands/storage/cp/cp.command.ts @@ -26,12 +26,12 @@ const config = { Flag.withDefault(false), ), cacheControl: Flag.String("cache-control").pipe( - Flag.withDescription('Custom Cache-Control header for HTTP upload. (default "max-age=3600")'), + Flag.withDescription("Custom Cache-Control header for HTTP upload."), Flag.annotate(FlagDocumentation, { defaultValue: "max-age=3600" }), Flag.optional, ), contentType: Flag.String("content-type").pipe( - Flag.withDescription('Custom Content-Type header for HTTP upload. (default "auto-detect")'), + Flag.withDescription("Custom Content-Type header for HTTP upload."), Flag.annotate(FlagDocumentation, { defaultValue: "auto-detect" }), Flag.optional, ), @@ -40,7 +40,7 @@ const config = { // Declared as a string, not `Flag.Int`, so the raw token reaches the parser below; // `withMetavar` keeps the `--jobs, -j integer` help token. Flag.withMetavar("integer"), - Flag.withDescription("Maximum number of parallel jobs. (default 1)"), + Flag.withDescription("Maximum number of parallel jobs."), Flag.annotate(FlagDocumentation, { defaultValue: "1" }), // `--jobs` is a uint: a non-uint token must fail at parse time, before the // experimental gate, the handler, or any telemetry, with the exact message and original diff --git a/apps/cli/src/docs/docs-spec.ts b/apps/cli/src/docs/docs-spec.ts index 4ef6bb100a..c4f81a57f0 100644 --- a/apps/cli/src/docs/docs-spec.ts +++ b/apps/cli/src/docs/docs-spec.ts @@ -188,7 +188,7 @@ export function docsFlagDoc( } const { single, isVariadic } = unwrapped; const documentation = flagDocumentation(single); - if (single.hidden || documentation.hidden) return undefined; + if (single.hidden) return undefined; let acceptedValues: ReadonlyArray | undefined; let enumType: string | undefined; diff --git a/apps/cli/src/docs/docs-spec.unit.test.ts b/apps/cli/src/docs/docs-spec.unit.test.ts index d13ce7f7f2..4b43c3e9ca 100644 --- a/apps/cli/src/docs/docs-spec.unit.test.ts +++ b/apps/cli/src/docs/docs-spec.unit.test.ts @@ -114,6 +114,14 @@ describe("docsFlagDoc", () => { expect(docsFlagDoc(["supabase", "fixture"], flag)?.required).toBeUndefined(); }); + it("keeps per-occurrence defaults out of collection documentation", () => { + const flag = Flag.String("value").pipe(Flag.withDefault("first"), Flag.atLeast(2)); + expect(docsFlagDoc(["supabase", "fixture"], flag)).toMatchObject({ + required: true, + default_value: "[]", + }); + }); + it("does not run effectful defaults or config lookups to build docs", () => { const flags = [ Flag.String("value").pipe( @@ -133,6 +141,7 @@ describe("docsFlagDoc", () => { [Flag.String("value").pipe(Flag.optional), undefined], [Flag.String("value").pipe(Flag.atLeast(0)), undefined], [Flag.String("value").pipe(Flag.atLeast(2)), true], + [Flag.String("value").pipe(Flag.withDefault("first"), Flag.atLeast(2)), true], ])("derives required badges from flag cardinality: %s", (flag, required) => { expect(docsFlagDoc(["supabase", "fixture"], flag)?.required).toBe(required); }); @@ -148,12 +157,6 @@ describe("docsFlagDoc", () => { accepted_values: [{ id: "a", name: "a", type: "[ a ]" }], }); expect(docsFlagDoc(["supabase", "fixture"], flag.pipe(Flag.withHidden))).toBeUndefined(); - expect( - docsFlagDoc( - ["supabase", "fixture"], - flag.pipe(Flag.annotate(FlagDocumentation, { hidden: true })), - ), - ).toBeUndefined(); }); it("renders --remote with the value hint its declaration carries", () => { diff --git a/apps/cli/src/shared/cli/version.integration.test.ts b/apps/cli/src/shared/cli/version.integration.test.ts index 5ed50c65c4..b17083b75b 100644 --- a/apps/cli/src/shared/cli/version.integration.test.ts +++ b/apps/cli/src/shared/cli/version.integration.test.ts @@ -20,17 +20,22 @@ const builtinLayer = (args: ReadonlyArray, console: Console.Console) => ); describe("CLI --help (text)", () => { - it.effect("db query help does not advertise a fixed global output default", () => - Effect.gen(function* () { - const args = ["db", "query", "--help"]; - const { console, calls } = fakeConsole(); - yield* Command.runWith(rootCommand, { version: CLI_VERSION })(args).pipe( - Effect.provide(builtinLayer(args, console)), - ); - const help = calls.join("\n"); - expect(help).toContain("output format of status variables"); - expect(help).not.toContain("(default: pretty)"); - }), + it.effect( + "db query help distinguishes the output format default from command-specific output", + () => + Effect.gen(function* () { + const args = ["db", "query", "--help"]; + const { console, calls } = fakeConsole(); + yield* Command.runWith(rootCommand, { version: CLI_VERSION })(args).pipe( + Effect.provide(builtinLayer(args, console)), + ); + const help = calls.join("\n"); + const formatRow = help.split("\n").find((line) => line.includes("--output-format choice")); + expect(formatRow).toContain("(default: text)"); + expect(formatRow?.match(/\(default\b/g)).toHaveLength(1); + expect(help).toContain("output format of status variables"); + expect(help).not.toContain("(default: pretty)"); + }), ); it.effect("source runs describe themselves as a development build", () => diff --git a/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts b/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts index 0ad081ac64..d384195446 100644 --- a/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts +++ b/apps/cli/src/shared/output/flag-defaults-help.integration.test.ts @@ -13,6 +13,22 @@ const child = Command.make( "child", { count: Flag.Int("count").pipe(Flag.withDescription("Count."), Flag.withDefault(42)), + disabled: Flag.Boolean("disabled").pipe(Flag.withDefault(false)), + zero: Flag.Int("zero").pipe(Flag.withDefault(0)), + empty: Flag.String("empty").pipe(Flag.atLeast(0), Flag.withDefault([])), + labeled: Flag.Boolean("labeled").pipe( + Flag.withDefault(false), + Flag.annotate(FlagDocumentation, { helpDefault: "false" }), + ), + stringFalse: Flag.String("string-false").pipe(Flag.withDefault("false")), + stringZero: Flag.String("string-zero").pipe(Flag.withDefault("0")), + stringArray: Flag.String("string-array").pipe(Flag.withDefault("[]")), + branch: Flag.String("branch").pipe( + Flag.withDefault("main"), + Flag.withDescription("Select the default branch for previews"), + ), + literal: Flag.String("literal").pipe(Flag.withDefault("*daily* _raw_ `code` [x](url)")), + repeated: Flag.String("repeated").pipe(Flag.withDefault("first"), Flag.atLeast(2)), effectful: Flag.String("effectful").pipe(Flag.withDefault(Effect.die("default executed"))), config: Flag.String("config").pipe(Flag.withFallbackConfig(Config.String("HELP_SECRET"))), handler: Flag.String("handler").pipe( @@ -23,10 +39,6 @@ const child = Command.make( Flag.optional, Flag.annotate(FlagDocumentation, { defaultValue: "anonymous", helpDefault: false }), ), - authored: Flag.String("authored").pipe( - Flag.withDefault("old"), - Flag.withDescription("Authored (default old)"), - ), hidden: Flag.String("hidden").pipe(Flag.withDefault("hidden-value"), Flag.withHidden), }, () => Effect.void, @@ -37,10 +49,14 @@ const root = Command.make("fixture").pipe( Command.withSubcommands([child]), ); -const helpFor = (formatter: CliOutput.Formatter) => +const helpFor = ( + formatter: CliOutput.Formatter, + command: Command.Command<"fixture", never, unknown> = root, + args: ReadonlyArray = ["child", "--help"], +) => Effect.gen(function* () { const { console, calls } = fakeConsole(); - yield* Command.runWith(root, { version: "test" })(["child", "--help"]).pipe( + yield* Command.runWith(command, { version: "test" })(args).pipe( Effect.provide( Layer.mergeAll( emptyEnv(), @@ -59,7 +75,7 @@ describe("flag defaults in help", () => { const command = Command.make( "fixture", { - value: Flag.Literals("value", ["a", "b"]).pipe( + value: Flag.Literals("value", ["a", "b", "c"]).pipe( Flag.withDefault("b"), Flag.annotate(FlagDocumentation, { defaultValue: "a", choices: ["a"] }), ), @@ -72,10 +88,10 @@ describe("flag defaults in help", () => { ); yield* Command.runWith(command, { version: "test" })([]).pipe(Effect.provide(emptyEnv())); expect(yield* Ref.get(observed)).toEqual({ value: "b", omitted: Option.none() }); - yield* Command.runWith(command, { version: "test" })(["--value", "b"]).pipe( + yield* Command.runWith(command, { version: "test" })(["--value", "c"]).pipe( Effect.provide(emptyEnv()), ); - expect(yield* Ref.get(observed)).toEqual({ value: "b", omitted: Option.none() }); + expect(yield* Ref.get(observed)).toEqual({ value: "c", omitted: Option.none() }); }), ); @@ -87,11 +103,18 @@ describe("flag defaults in help", () => { textCliOutputFormatter({ rootCommand: root, args: ["child", "--help"] }), ); expect(text).toContain("Count. (default: 42)"); + const row = (name: string) => text.split("\n").find((line) => line.includes(`--${name} `)); + for (const name of ["disabled", "zero", "empty", "repeated"]) { + expect(row(name)).toBeDefined(); + expect(row(name)).not.toContain("(default:"); + } + expect(row("labeled")).toContain("(default: false)"); + expect(row("string-false")).toContain("(default: false)"); + expect(row("string-zero")).toContain("(default: 0)"); + expect(row("string-array")).toContain("(default: [])"); expect(text).toContain("(default: handler-value)"); expect(text).toContain("(default: shared-value)"); expect(text).toContain("(default: global-mode)"); - expect(text).toContain("Authored (default old)"); - expect(text).not.toContain("Authored (default old) (default:"); expect(text).not.toContain("anonymous"); expect(text).not.toContain("hidden-value"); expect(text).not.toContain("default executed"); @@ -99,6 +122,89 @@ describe("flag defaults in help", () => { }), ); + it.effect("preserves descriptive prose alongside the default value", () => + Effect.gen(function* () { + const text = yield* helpFor( + textCliOutputFormatter({ rootCommand: root, args: ["child", "--help"] }), + ); + expect(text).toContain("Select the default branch for previews (default: main)"); + }), + ); + + it.effect("appends string defaults literally after Markdown rendering", () => + Effect.gen(function* () { + const text = yield* helpFor( + textCliOutputFormatter({ rootCommand: root, args: ["child", "--help"] }), + ); + expect(text).toContain("(default: *daily* _raw_ `code` [x](url))"); + }), + ); + + it.effect("shows shared defaults on the declaring command's own help", () => + Effect.gen(function* () { + const text = yield* helpFor( + textCliOutputFormatter({ rootCommand: root, args: ["--help"] }), + root, + ["--help"], + ); + expect(text).toContain("--shared"); + expect(text).toContain("(default: shared-value)"); + expect(text).not.toContain("INHERITED FLAGS"); + }), + ); + + it.effect("uses the declaration owning each local and inherited row", () => + Effect.gen(function* () { + const leaf = Command.make("leaf", { + suppressed: Flag.String("suppressed").pipe( + Flag.withDefault("local-suppressed"), + Flag.annotate(FlagDocumentation, { helpDefault: false }), + ), + absent: Flag.String("absent").pipe(Flag.optional), + local: Flag.String("local").pipe(Flag.withDefault("local-value")), + }); + const middle = Command.make("middle").pipe( + Command.withSharedFlags({ + inherited: Flag.String("inherited").pipe(Flag.withDefault("near-value")), + }), + Command.withSubcommands([leaf]), + ); + const fixture = Command.make("fixture").pipe( + Command.withSharedFlags({ + suppressed: Flag.String("suppressed").pipe(Flag.withDefault("ancestor-suppressed")), + absent: Flag.String("absent").pipe(Flag.withDefault("ancestor-absent")), + local: Flag.String("local").pipe(Flag.withDefault("ancestor-local")), + inherited: Flag.String("inherited").pipe(Flag.withDefault("root-value")), + }), + Command.withSubcommands([Command.make("spacer").pipe(Command.withSubcommands([middle]))]), + ); + const text = yield* helpFor( + textCliOutputFormatter({ + rootCommand: fixture, + args: ["spacer", "middle", "leaf", "--help"], + }), + fixture, + ["spacer", "middle", "leaf", "--help"], + ); + expect(text).toContain("--suppressed"); + expect(text).toContain("--absent"); + expect(text).toContain("(default: local-value)"); + expect(text).toContain("(default: root-value)"); + expect(text).not.toContain("ancestor-"); + expect(text).not.toContain("local-suppressed"); + expect(text).not.toContain("near-value"); + }), + ); + + it("rejects direct shared and child name collisions", () => { + expect(() => + Command.make("fixture").pipe( + Command.withSharedFlags({ value: Flag.String("value") }), + Command.withSubcommands([Command.make("child", { value: Flag.String("value") })]), + ), + ).toThrow('Duplicate flag name "value" in parent command "fixture" and subcommand "child"'); + }); + it.effect("keeps JSON help flag fields and descriptions unchanged", () => Effect.gen(function* () { const printed = yield* helpFor( diff --git a/apps/cli/src/shared/output/flag-defaults-help.ts b/apps/cli/src/shared/output/flag-defaults-help.ts index 09e5e0d346..bd352d645a 100644 --- a/apps/cli/src/shared/output/flag-defaults-help.ts +++ b/apps/cli/src/shared/output/flag-defaults-help.ts @@ -8,29 +8,39 @@ import { userGlobalFlagParams, } from "../../docs/docs-introspection.ts"; -function defaultsFor(params: ReadonlyArray): ReadonlyMap { - const defaults = new Map(); +function defaultsFor( + params: ReadonlyArray, +): ReadonlyMap { + const defaults = new Map(); for (const param of params) { const unwrapped = unwrapParam(param); - if (unwrapped === undefined) continue; - const { helpDefault } = flagDocumentation(unwrapped.single); - if (helpDefault === false) continue; - const value = helpDefault ?? flagDefault(unwrapped); - if (value !== undefined && value !== "") defaults.set(unwrapped.single.name, value); + if (unwrapped === undefined || unwrapped.single.hidden) continue; + const { name } = unwrapped.single; + // Row ownership wins even when its declaration has no printable default. + if (defaults.has(name)) continue; + const { helpDefault, defaultValue } = flagDocumentation(unwrapped.single); + const typeDefault = Option.exists( + unwrapped.defaultValue, + (value) => value === false || value === 0 || (Array.isArray(value) && value.length === 0), + ); + const value = + helpDefault === false || + (helpDefault === undefined && defaultValue === undefined && typeDefault) + ? undefined + : (helpDefault ?? flagDefault(unwrapped)); + defaults.set(name, value === "" ? undefined : value); } return defaults; } function withDefaults( flags: ReadonlyArray, - defaults: ReadonlyMap, + defaults: ReadonlyMap, ): ReadonlyArray { return flags.map((flag) => { const value = defaults.get(flag.name); if (value === undefined) return flag; const description = Option.getOrElse(flag.description, () => ""); - // Authored descriptions already carrying a default keep their established wording. - if (/\bdefault\b/i.test(description)) return flag; return { ...flag, description: Option.some(`${description}${description === "" ? "" : " "}(default: ${value})`), @@ -65,13 +75,18 @@ export function withFlagDefaults( ...doc, flags: withDefaults( doc.flags, - defaultsFor([...inherited, ...commandInternals(current).config.flags]), + // Effect prefers local rows, then deduplicates inherited rows root-first. + defaultsFor([...commandInternals(current).config.flags, ...inherited]), ), ...(doc.inheritedFlags === undefined ? {} - : { inheritedFlags: withDefaults(doc.inheritedFlags, defaultsFor(inherited)) }), + : { + inheritedFlags: withDefaults(doc.inheritedFlags, defaultsFor(inherited)), + }), ...(doc.globalFlags === undefined ? {} - : { globalFlags: withDefaults(doc.globalFlags, defaultsFor(globals)) }), + : { + globalFlags: withDefaults(doc.globalFlags, defaultsFor(globals)), + }), }; } diff --git a/apps/cli/src/shared/output/text-formatter.ts b/apps/cli/src/shared/output/text-formatter.ts index eef8904ce7..4c8ea71529 100644 --- a/apps/cli/src/shared/output/text-formatter.ts +++ b/apps/cli/src/shared/output/text-formatter.ts @@ -44,13 +44,14 @@ export function textCliOutputFormatter( formatHelpDoc: (doc) => { const colors = supportsColor(stream, !agentMode); const help = CliOutput.defaultFormatter({ colors }); - const rendered = withHelpMarkdown( - withOptionalSubcommandUsage( - withRemoteFlagUsage( - withFlagDefaults(labelSubcommands(doc, context?.rootCommand), context?.rootCommand), + const rendered = withFlagDefaults( + withHelpMarkdown( + withOptionalSubcommandUsage( + withRemoteFlagUsage(labelSubcommands(doc, context?.rootCommand)), ), + colors, ), - colors, + context?.rootCommand, ); // Effect indents only the first line of the description section. const text = help.formatHelpDoc({ From 9fee35155cab1e19c656d02d99cce3a24c58c912 Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Wed, 18 Nov 2026 14:45:42 -0700 Subject: [PATCH 3/3] chore(cli): keep literal default helper internal --- apps/cli/src/command-internal/flag-documentation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/cli/src/command-internal/flag-documentation.ts b/apps/cli/src/command-internal/flag-documentation.ts index 5790b9870c..8540190cf6 100644 --- a/apps/cli/src/command-internal/flag-documentation.ts +++ b/apps/cli/src/command-internal/flag-documentation.ts @@ -23,7 +23,7 @@ export function flagDocumentation( } /** Only literal scalar and array defaults can be displayed without evaluating user code. */ -export function literalDefault(value: unknown): string | undefined { +function literalDefault(value: unknown): string | undefined { if (typeof value === "string") return value; if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) { return String(value);