Skip to content

Commit f4504ef

Browse files
committed
fix: move empty-header auto-detection into renderTextTable
Per review feedback, the empty-header detection logic now lives in renderTextTable itself (auto-detects when all headers are empty/whitespace) rather than requiring each caller to detect and pass hideHeaders. renderTableToken in markdown.ts no longer needs special handling — renderTextTable handles it transparently.
1 parent d41b0bd commit f4504ef

File tree

4 files changed

+26
-80
lines changed

4 files changed

+26
-80
lines changed

AGENTS.md

Lines changed: 0 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -781,73 +781,4 @@ mock.module("./some-module", () => ({
781781
| Add documentation | `docs/src/content/docs/` |
782782
783783
<!-- This section is maintained by the coding agent via lore (https://github.com/BYK/opencode-lore) -->
784-
## Long-term Knowledge
785-
786-
### Architecture
787-
788-
<!-- lore:019ce2be-39f1-7ad9-a4c5-4506b62f689c -->
789-
* **api-client.ts split into domain modules under src/lib/api/**: The original monolithic \`src/lib/api-client.ts\` (1,977 lines) was split into 12 focused domain modules under \`src/lib/api/\`: infrastructure.ts (shared helpers, types, raw requests), organizations.ts, projects.ts, teams.ts, repositories.ts, issues.ts, events.ts, traces.ts, logs.ts, seer.ts, trials.ts, users.ts. The original \`api-client.ts\` was converted to a ~100-line barrel re-export file preserving all existing import paths. The \`biome.jsonc\` override for \`noBarrelFile\` already includes \`api-client.ts\`. When adding new API functions, place them in the appropriate domain module under \`src/lib/api/\`, not in the barrel file.
790-
791-
<!-- lore:019cb8ea-c6f0-75d8-bda7-e32b4e217f92 -->
792-
* **CLI telemetry DSN is public write-only — safe to embed in install script**: The CLI's Sentry DSN (\`SENTRY\_CLI\_DSN\` in \`src/lib/constants.ts\`) is a public write-only ingest key already baked into every binary. Safe to hardcode in install scripts. Opt-out: \`SENTRY\_CLI\_NO\_TELEMETRY=1\`.
793-
794-
<!-- lore:019c978a-18b5-7a0d-a55f-b72f7789bdac -->
795-
* **cli.sentry.dev is served from gh-pages branch via GitHub Pages**: \`cli.sentry.dev\` is served from gh-pages branch via GitHub Pages. Craft's gh-pages target runs \`git rm -r -f .\` before extracting docs — persist extra files via \`postReleaseCommand\` in \`.craft.yml\`. Install script supports \`--channel nightly\`, downloading from the \`nightly\` release tag directly. version.json is only used by upgrade/version-check flow.
796-
797-
<!-- lore:019cbe93-19b8-7776-9705-20bbde226599 -->
798-
* **Nightly delta upgrade buildNightlyPatchGraph fetches ALL patch tags — O(N) HTTP calls**: Delta upgrade in \`src/lib/delta-upgrade.ts\` supports stable (GitHub Releases) and nightly (GHCR) channels. \`filterAndSortChainTags\` filters \`patch-\*\` tags by version range using \`Bun.semver.order()\`. GHCR uses \`fetchWithRetry\` (10s timeout + 1 retry; blobs 30s) with optional \`signal?: AbortSignal\` combined via \`AbortSignal.any()\`. \`isExternalAbort(error, signal)\` skips retries for external aborts — critical for background prefetch. Patches cached to \`~/.sentry/patch-cache/\` (file-based, 7-day TTL). \`loadCachedChain\` stitches patches for multi-hop offline upgrades.
799-
800-
<!-- lore:2c3eb7ab-1341-4392-89fd-d81095cfe9c4 -->
801-
* **npm bundle requires Node.js >= 22 due to node:sqlite polyfill**: The npm package (dist/bin.cjs) requires Node.js >= 22 because the bun:sqlite polyfill uses \`node:sqlite\`. A runtime version guard in the esbuild banner catches this early. When writing esbuild banner strings in TS template literals, double-escape: \`\\\\\\\n\` in TS → \`\\\n\` in output → newline at runtime. Single \`\\\n\` produces a literal newline inside a JS string, causing SyntaxError.
802-
803-
<!-- lore:019c972c-9f0f-75cd-9e24-9bdbb1ac03d6 -->
804-
* **Numeric issue ID resolution returns org:undefined despite API success**: Numeric issue ID resolution in \`resolveNumericIssue()\`: (1) try DSN/env/config for org, (2) if found use \`getIssueInOrg(org, id)\` with region routing, (3) else fall back to unscoped \`getIssue(id)\`, (4) extract org from \`issue.permalink\` via \`parseSentryUrl\` as final fallback. \`parseSentryUrl\` handles path-based (\`/organizations/{org}/...\`) and subdomain-style URLs. \`matchSubdomainOrg()\` filters region subdomains by requiring slug length > 2. Self-hosted uses path-based only.
805-
806-
<!-- lore:019ce0bb-f35d-7380-b661-8dc56f9938cf -->
807-
* **Seer trial prompt uses middleware layering in bin.ts error handling chain**: The CLI's error recovery middlewares in \`bin.ts\` are layered: \`main() → executeWithAutoAuth() → executeWithSeerTrialPrompt() → runCommand()\`. Seer trial prompts (for \`no\_budget\`/\`not\_enabled\` errors) are caught by the inner wrapper; auth errors bubble up to the outer wrapper. After successful auth login retry, the retry also goes through \`executeWithSeerTrialPrompt\` (not \`runCommand\` directly) so the full middleware chain applies. Trial check API: \`GET /api/0/customers/{org}/\`\`productTrials\[]\` (prefer \`seerUsers\`, fallback \`seerAutofix\`). Start trial: \`PUT /api/0/customers/{org}/product-trial/\`. The \`/customers/\` endpoint is getsentry SaaS-only; self-hosted 404s gracefully. \`ai\_disabled\` errors are excluded (admin's explicit choice). \`startSeerTrial\` accepts \`category\` from the trial object — don't hardcode it.
808-
809-
### Decision
810-
811-
<!-- lore:019c99d5-69f2-74eb-8c86-411f8512801d -->
812-
* **Raw markdown output for non-interactive terminals, rendered for TTY**: Markdown-first output pipeline: custom renderer in \`src/lib/formatters/markdown.ts\` walks \`marked\` tokens to produce ANSI-styled output. Commands build CommonMark using helpers (\`mdKvTable()\`, \`mdRow()\`, \`colorTag()\`, \`escapeMarkdownCell()\`, \`safeCodeSpan()\`) and pass through \`renderMarkdown()\`. \`isPlainOutput()\` precedence: \`SENTRY\_PLAIN\_OUTPUT\` > \`NO\_COLOR\` > \`FORCE\_COLOR\` > \`!isTTY\`. \`--json\` always outputs JSON. Colors defined in \`COLORS\` object in \`colors.ts\`. Tests run non-TTY so assertions match raw CommonMark; use \`stripAnsi()\` helper for rendered-mode assertions.
813-
814-
<!-- lore:00166785-609d-4ab5-911e-ee205d17b90c -->
815-
* **whoami should be separate from auth status command**: The \`sentry auth whoami\` command should be a dedicated command separate from \`sentry auth status\`. They serve different purposes: \`status\` shows everything about auth state (token, expiry, defaults, org verification), while \`whoami\` just shows user identity (name, email, username, ID) by fetching live from \`/auth/\` endpoint. \`sentry whoami\` should be a top-level alias (like \`sentry issues\`\`sentry issue list\`). \`whoami\` should support \`--json\` for machine consumption and be lightweight — no credential verification, no defaults listing.
816-
817-
### Gotcha
818-
819-
<!-- lore:019c8ab6-d119-7365-9359-98ecf464b704 -->
820-
* **@sentry/api SDK passes Request object to custom fetch — headers lost on Node.js**: @sentry/api SDK calls \`\_fetch(request)\` with no init object. In \`authenticatedFetch\`, \`init\` is undefined so \`prepareHeaders\` creates empty headers — on Node.js this strips Content-Type (HTTP 415). Fix: fall back to \`input.headers\` when \`init\` is undefined. Use \`unwrapPaginatedResult\` (not \`unwrapResult\`) to access the Response's Link header for pagination. \`per\_page\` is not in SDK types; cast query to pass it at runtime.
821-
822-
<!-- lore:019c9e98-7af4-7e25-95f4-fc06f7abf564 -->
823-
* **Bun binary build requires SENTRY\_CLIENT\_ID env var**: The build script (\`script/bundle.ts\`) requires \`SENTRY\_CLIENT\_ID\` environment variable and exits with code 1 if missing. When building locally, use \`bun run --env-file=.env.local build\` or set the env var explicitly. The binary build (\`bun run build\`) also needs it. Without it you get: \`Error: SENTRY\_CLIENT\_ID environment variable is required.\`
824-
825-
<!-- lore:019c9776-e3dd-7632-88b8-358a19506218 -->
826-
* **GitHub immutable releases prevent rolling nightly tag pattern**: getsentry/cli has immutable GitHub releases — assets can't be modified and tags can NEVER be reused. Nightly builds publish to GHCR with versioned tags like \`nightly-0.14.0-dev.1772661724\`, not GitHub Releases or npm. \`fetchManifest()\` throws \`UpgradeError("network\_error")\` for both network failures and non-200 — callers must check message for HTTP 404/403. Craft with no \`preReleaseCommand\` silently skips \`bump-version.sh\` if only target is \`github\`.
827-
828-
<!-- lore:019cb8c2-d7b5-780c-8a9f-d20001bc198f -->
829-
* **Install script: BSD sed and awk JSON parsing breaks OCI digest extraction**: The install script parses OCI manifests with awk (no jq). Key trap: BSD sed \`\n\` is literal, not newline. Fix: single awk pass tracking last-seen \`"digest"\`, printing when \`"org.opencontainers.image.title"\` matches target. The config digest (\`sha256:44136fa...\`) is a 2-byte \`{}\` blob — downloading it instead of the real binary causes \`gunzip: unexpected end of file\`.
830-
831-
<!-- lore:019c969a-1c90-7041-88a8-4e4d9a51ebed -->
832-
* **Multiple mockFetch calls replace each other — use unified mocks for multi-endpoint tests**: Bun test mocking gotchas: (1) \`mockFetch()\` replaces \`globalThis.fetch\` — calling it twice replaces the first mock. Use a single unified fetch mock dispatching by URL pattern. (2) \`mock.module()\` pollutes the module registry for ALL subsequent test files. Tests using it must live in \`test/isolated/\` and run via \`test:isolated\`. This also causes \`delta-upgrade.test.ts\` to fail when run alongside \`test/isolated/delta-upgrade.test.ts\` — the isolated test's \`mock.module()\` replaces \`CLI\_VERSION\` for all subsequent files. (3) For \`Bun.spawn\`, use direct property assignment in \`beforeEach\`/\`afterEach\`.
833-
834-
<!-- lore:019c9741-d78e-73b1-87c2-e360ef6c7475 -->
835-
* **useTestConfigDir without isolateProjectRoot causes DSN scanning of repo tree**: \`useTestConfigDir()\` creates temp dirs under \`.test-tmp/\` in the repo tree. Without \`{ isolateProjectRoot: true }\`, \`findProjectRoot\` walks up and finds the repo's \`.git\`, causing DSN detection to scan real source code and trigger network calls against test mocks (timeouts). Always pass \`isolateProjectRoot: true\` when tests exercise \`resolveOrg\`, \`detectDsn\`, or \`findProjectRoot\`.
836-
837-
### Pattern
838-
839-
<!-- lore:019c972c-9f11-7c0d-96ce-3f8cc2641175 -->
840-
* **Org-scoped SDK calls follow getOrgSdkConfig + unwrapResult pattern**: All org-scoped API calls in src/lib/api-client.ts: (1) call \`getOrgSdkConfig(orgSlug)\` for regional URL + SDK config, (2) spread into SDK function: \`{ ...config, path: { organization\_id\_or\_slug: orgSlug, ... } }\`, (3) pass to \`unwrapResult(result, errorContext)\`. Shared helpers \`resolveAllTargets\`/\`resolveOrgAndProject\` must NOT call \`fetchProjectId\` — commands that need it enrich targets themselves.
841-
842-
<!-- lore:5ac4e219-ea1f-41cb-8e97-7e946f5848c0 -->
843-
* **PR workflow: wait for Seer and Cursor BugBot before resolving**: After pushing a PR in the getsentry/cli repo, the CI pipeline includes Seer Code Review and Cursor Bugbot as advisory checks. Both typically take 2-3 minutes but may not trigger on draft PRs — only ready-for-review PRs reliably get bot reviews. The workflow is: push → wait for all CI (including npm build jobs which test the actual bundle) → check for inline review comments from Seer/BugBot → fix if needed → repeat. Use \`gh pr checks \<PR> --watch\` to monitor. Review comments are fetched via \`gh api repos/OWNER/REPO/pulls/NUM/comments\` and \`gh api repos/OWNER/REPO/pulls/NUM/reviews\`.
844-
845-
<!-- lore:019cb162-d3ad-7b05-ab4f-f87892d517a6 -->
846-
* **Shared pagination infrastructure: buildPaginationContextKey and parseCursorFlag**: List commands with cursor pagination use \`buildPaginationContextKey(type, identifier, flags)\` for composite context keys and \`parseCursorFlag(value)\` accepting \`"last"\` magic value. Critical: \`resolveCursor()\` must be called inside the \`org-all\` override closure, not before \`dispatchOrgScopedList\` — otherwise cursor validation errors fire before the correct mode-specific error.
847-
848-
<!-- lore:019cbd5f-ec35-7e2d-8386-6d3a67adf0cf -->
849-
* **Telemetry instrumentation pattern: withTracingSpan + captureException for handled errors**: For graceful-fallback operations, use \`withTracingSpan\` from \`src/lib/telemetry.ts\` for child spans and \`captureException\` from \`@sentry/bun\` (named import — Biome forbids namespace imports) with \`level: 'warning'\` for non-fatal errors. \`withTracingSpan\` uses \`onlyIfParent: true\` — no-op without active transaction. User-visible fallbacks use \`log.warn()\` not \`log.debug()\`. Several commands bypass telemetry by importing \`buildCommand\` from \`@stricli/core\` directly instead of \`../../lib/command.js\` (trace/list, trace/view, log/view, api.ts, help.ts).
850-
851-
<!-- lore:019cc43d-e651-7154-a88e-1309c4a2a2b6 -->
852-
* **Testing Stricli command func() bodies via spyOn mocking**: To unit-test a Stricli command's \`func()\` body: (1) \`const func = await cmd.loader()\`, (2) \`func.call(mockContext, flags, ...args)\` with mock \`stdout\`, \`stderr\`, \`cwd\`, \`setContext\`. (3) \`spyOn\` namespace imports to mock dependencies (e.g., \`spyOn(apiClient, 'getLogs')\`). The \`loader()\` return type union causes \`.call()\` LSP errors — these are false positives that pass \`tsc --noEmit\`. When API functions are renamed (e.g., \`getLog\`\`getLogs\`), update both spy target name AND mock return shape (single → array). Slug normalization (\`normalizeSlug\`) replaces underscores with dashes but does NOT lowercase — test assertions must match original casing (e.g., \`'CAM-82X'\` not \`'cam-82x'\`).
853784
<!-- End lore-managed section -->

src/lib/formatters/markdown.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -555,9 +555,8 @@ function renderList(list: Tokens.List, depth = 0): string {
555555
* Converts marked's `Tokens.Table` into headers + rows + alignments and
556556
* delegates to `renderTextTable()` for column fitting and box drawing.
557557
*
558-
* When all header cells are empty (e.g. from {@link mdKvTable} without a
559-
* heading), the header row is hidden so the rendered table starts directly
560-
* with data rows — no empty cells or separator line.
558+
* Empty header rows (e.g. from {@link mdKvTable} without a heading) are
559+
* auto-hidden by `renderTextTable` — no explicit detection needed here.
561560
*/
562561
function renderTableToken(table: Tokens.Table): string {
563562
const headers = table.header.map((cell) => renderInline(cell.tokens));
@@ -575,11 +574,7 @@ function renderTableToken(table: Tokens.Table): string {
575574
return "left";
576575
});
577576

578-
// Hide the header row when all cells are empty — avoids rendering a
579-
// visually empty bordered row above the data (common in mdKvTable output).
580-
const hideHeaders = headers.every((h) => h.trim() === "");
581-
582-
return renderTextTable(headers, rows, { alignments, hideHeaders });
577+
return renderTextTable(headers, rows, { alignments });
583578
}
584579

585580
// ──────────────────────── Public API ─────────────────────────────────

src/lib/formatters/text-table.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ export type TextTableOptions = {
6464
* the markdown source requires empty header cells (`| | |`) to satisfy
6565
* table syntax, but the visual output shouldn't show them.
6666
*
67-
* @default false
67+
* When omitted, auto-detects: hides headers when **all** header cells
68+
* are empty or whitespace-only. Pass `true`/`false` explicitly to override.
6869
*/
6970
hideHeaders?: boolean;
7071
/**
@@ -105,7 +106,7 @@ export function renderTextTable(
105106
minWidths = [],
106107
shrinkable = [],
107108
truncate = false,
108-
hideHeaders = false,
109+
hideHeaders = options.hideHeaders ?? headers.every((h) => h.trim() === ""),
109110
rowSeparator = false,
110111
} = options;
111112

test/lib/formatters/text-table.test.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,30 @@ describe("renderTextTable", () => {
131131
expect(topBorderHide).toBe(topBorderShow);
132132
});
133133

134-
test("hideHeaders: false (default) includes header row", () => {
134+
test("auto-hides headers when all cells are empty", () => {
135+
const out = renderTextTable(["", ""], [["Key", "Val"]]);
136+
expect(out).toContain("Key");
137+
expect(out).toContain("Val");
138+
// Should auto-hide: only 1 content line (data row), no empty header row
139+
const lines = out.split("\n").filter((l) => l.includes("\u2502"));
140+
expect(lines).toHaveLength(1);
141+
});
142+
143+
test("does not auto-hide when headers have content", () => {
135144
const out = renderTextTable(["H1", "H2"], [["d1", "d2"]]);
136145
expect(out).toContain("H1");
137146
expect(out).toContain("H2");
138147
});
148+
149+
test("explicit hideHeaders: false overrides auto-detection", () => {
150+
const out = renderTextTable(["", ""], [["Key", "Val"]], {
151+
hideHeaders: false,
152+
});
153+
// Empty header row should be visible (explicit override)
154+
const lines = out.split("\n").filter((l) => l.includes("\u2502"));
155+
// 2 content lines: empty header + data row
156+
expect(lines).toHaveLength(2);
157+
});
139158
});
140159

141160
describe("alignment", () => {

0 commit comments

Comments
 (0)