-
Notifications
You must be signed in to change notification settings - Fork 34
feat: add emails metrics command #370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
be893f5
feat: add emails metrics command
dielduarte ead68f6
fix: address cubic review on emails metrics command
dielduarte 5b27531
revert: drop the renderTotalsTable/renderBreakdownTable unit tests
dielduarte 1091bd1
fix: assert the invalid_options error output in the empty --email-id …
dielduarte 0ae1cd7
fix: drop the row number from the card-layout separator
dielduarte 7e6bda7
Revert "fix: drop the row number from the card-layout separator"
dielduarte 8c887b7
docs: add metrics to the agent skill; validate --granularity with cho…
felipefreitag File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import { Command, Option } from '@commander-js/extra-typings'; | ||
| import type { EmailMetricsDataRow, EmailMetricsTotals } from 'resend'; | ||
| import { runGet } from '../../lib/actions'; | ||
| import type { GlobalOpts } from '../../lib/client'; | ||
| import { buildHelpText } from '../../lib/help-text'; | ||
| import { outputError } from '../../lib/output'; | ||
| import { renderTable } from '../../lib/table'; | ||
|
|
||
| function parseList(value: string | undefined): string[] | undefined { | ||
| if (value === undefined) { | ||
| return undefined; | ||
| } | ||
| return value | ||
| .split(',') | ||
| .map((v) => v.trim()) | ||
| .filter((v) => v.length > 0); | ||
| } | ||
|
|
||
| function renderTotalsTable(totals: EmailMetricsTotals): string { | ||
| const rows = Object.entries(totals).map(([metric, value]) => [ | ||
| metric, | ||
| String(value), | ||
| ]); | ||
| return renderTable(['Metric', 'Value'], rows, '(no metrics)'); | ||
| } | ||
|
|
||
| function renderBreakdownTable( | ||
| data: EmailMetricsDataRow[], | ||
| metrics: string[], | ||
| ): string { | ||
| const dimensionKeys = Object.keys(data[0] ?? {}).filter( | ||
| (key) => !metrics.includes(key), | ||
| ); | ||
| const headers = [...dimensionKeys, ...metrics]; | ||
| const rows = data.map((row) => | ||
| headers.map((key) => String(row[key as keyof EmailMetricsDataRow] ?? '')), | ||
| ); | ||
| return renderTable(headers, rows, '(no breakdown rows)'); | ||
| } | ||
|
|
||
| export const metricsCommand = new Command('metrics') | ||
| .description('Retrieve account-level email metrics') | ||
| .option( | ||
| '--start-date <date>', | ||
| 'ISO 8601 date/datetime, defaults to 6 days before --end-date', | ||
| ) | ||
| .option('--end-date <date>', 'ISO 8601 date/datetime, defaults to now') | ||
| .option( | ||
| '--timezone <tz>', | ||
| 'IANA timezone, e.g. America/New_York, defaults to UTC', | ||
| ) | ||
| .addOption( | ||
| new Option( | ||
| '--granularity <granularity>', | ||
| 'Bucket size used when "period" is a dimension (default: daily)', | ||
| ).choices(['hourly', 'daily', 'weekly', 'monthly'] as const), | ||
| ) | ||
| .option( | ||
| '--metrics <list>', | ||
| 'Comma-separated metrics to include, defaults to all', | ||
| ) | ||
| .option( | ||
| '--dimensions <list>', | ||
| 'Comma-separated dimensions to break down by: period, domain, email, broadcast', | ||
| ) | ||
| .option('--domain-id <list>', 'Comma-separated sending domain IDs (max 100)') | ||
| .option( | ||
| '--email-id <list>', | ||
| 'Comma-separated email IDs (max 100). Cannot be combined with the "broadcast" dimension or --broadcast-id', | ||
| ) | ||
| .option( | ||
| '--broadcast-id <list>', | ||
| 'Comma-separated broadcast IDs (max 100). Cannot be combined with the "email" dimension or --email-id', | ||
| ) | ||
| .addHelpText( | ||
| 'after', | ||
| buildHelpText({ | ||
| output: | ||
| ' {"object":"metrics","start_date":"...","end_date":"...","metrics":["sent","delivered"],"dimensions":[],"granularity":"daily","totals":{"sent":100,"delivered":95}}', | ||
| errorCodes: ['auth_error', 'invalid_options', 'fetch_error'], | ||
| examples: [ | ||
| 'resend emails metrics', | ||
| 'resend emails metrics --start-date 2026-07-01 --end-date 2026-07-08', | ||
| 'resend emails metrics --dimensions period,broadcast --broadcast-id <broadcast-id>', | ||
| 'resend emails metrics --json', | ||
| ], | ||
| }), | ||
| ) | ||
| .action(async (opts, cmd) => { | ||
| const globalOpts = cmd.optsWithGlobals() as GlobalOpts; | ||
|
|
||
| const dimensions = parseList(opts.dimensions); | ||
| const emailId = parseList(opts.emailId); | ||
| const broadcastId = parseList(opts.broadcastId); | ||
|
|
||
| const hasEmail = | ||
| (dimensions?.includes('email') ?? false) || opts.emailId !== undefined; | ||
| const hasBroadcast = | ||
| (dimensions?.includes('broadcast') ?? false) || | ||
| opts.broadcastId !== undefined; | ||
|
|
||
| if (hasEmail && hasBroadcast) { | ||
| outputError( | ||
| { | ||
| message: | ||
| 'The "broadcast" dimension/--broadcast-id cannot be combined with the "email" dimension/--email-id.', | ||
| code: 'invalid_options', | ||
| }, | ||
| { json: globalOpts.json }, | ||
| ); | ||
| } | ||
|
|
||
| const metrics = parseList(opts.metrics); | ||
|
|
||
| await runGet( | ||
| { | ||
| loading: 'Fetching email metrics...', | ||
| sdkCall: (resend) => | ||
| resend.emails.metrics({ | ||
| startDate: opts.startDate, | ||
| endDate: opts.endDate, | ||
| timezone: opts.timezone, | ||
| granularity: opts.granularity, | ||
| metrics, | ||
| dimensions, | ||
| domainId: parseList(opts.domainId), | ||
| emailId, | ||
| broadcastId, | ||
| } as Parameters<typeof resend.emails.metrics>[0]), | ||
| onInteractive: (data) => { | ||
| console.log( | ||
| `Metrics for ${data.start_date} to ${data.end_date} (${data.granularity} granularity)`, | ||
| ); | ||
| console.log(); | ||
| console.log('Totals:'); | ||
| console.log(renderTotalsTable(data.totals)); | ||
| if (data.data && data.data.length > 0) { | ||
| console.log(); | ||
| console.log(`Breakdown by ${data.dimensions.join(', ')}:`); | ||
| console.log(renderBreakdownTable(data.data, data.metrics)); | ||
| } | ||
| }, | ||
| }, | ||
| globalOpts, | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| import { | ||
| afterEach, | ||
| beforeEach, | ||
| describe, | ||
| expect, | ||
| it, | ||
| type MockInstance, | ||
| vi, | ||
| } from 'vitest'; | ||
| import { | ||
| captureTestEnv, | ||
| expectExit1, | ||
| mockExitThrow, | ||
| setNonInteractive, | ||
| setupOutputSpies, | ||
| } from '../../helpers'; | ||
|
|
||
| const mockMetrics = vi.fn(async () => ({ | ||
| data: { | ||
|
dielduarte marked this conversation as resolved.
|
||
| object: 'metrics', | ||
| start_date: '2026-07-01T00:00:00.000Z', | ||
| end_date: '2026-07-08T00:00:00.000Z', | ||
| metrics: ['sent', 'delivered'], | ||
| dimensions: [], | ||
| granularity: 'daily', | ||
| totals: { sent: 100, delivered: 95 }, | ||
| }, | ||
| error: null, | ||
| })); | ||
|
|
||
| vi.mock('resend', () => ({ | ||
| Resend: class MockResend { | ||
| constructor(public key: string) {} | ||
| emails = { metrics: mockMetrics }; | ||
| }, | ||
| })); | ||
|
|
||
| describe('emails metrics command', () => { | ||
| const restoreEnv = captureTestEnv(); | ||
| let spies: ReturnType<typeof setupOutputSpies> | undefined; | ||
| let errorSpy: MockInstance | undefined; | ||
| let stderrSpy: MockInstance | undefined; | ||
| let exitSpy: MockInstance | undefined; | ||
|
|
||
| beforeEach(() => { | ||
| process.env.RESEND_API_KEY = 're_test_key'; | ||
| mockMetrics.mockClear(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| restoreEnv(); | ||
| errorSpy?.mockRestore(); | ||
| stderrSpy?.mockRestore(); | ||
| exitSpy?.mockRestore(); | ||
| spies = undefined; | ||
| errorSpy = undefined; | ||
| stderrSpy = undefined; | ||
| exitSpy = undefined; | ||
| }); | ||
|
|
||
| it('calls SDK metrics with no options by default', async () => { | ||
| spies = setupOutputSpies(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await metricsCommand.parseAsync([], { from: 'user' }); | ||
|
|
||
| expect(mockMetrics).toHaveBeenCalledWith({ | ||
| startDate: undefined, | ||
| endDate: undefined, | ||
| timezone: undefined, | ||
| granularity: undefined, | ||
| metrics: undefined, | ||
| dimensions: undefined, | ||
| domainId: undefined, | ||
| emailId: undefined, | ||
| broadcastId: undefined, | ||
| }); | ||
| }); | ||
|
|
||
| it('parses comma-separated dimensions and a filter into arrays', async () => { | ||
| spies = setupOutputSpies(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await metricsCommand.parseAsync( | ||
| ['--dimensions', 'period,broadcast', '--broadcast-id', 'b1,b2'], | ||
| { from: 'user' }, | ||
| ); | ||
|
|
||
| expect(mockMetrics).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| dimensions: ['period', 'broadcast'], | ||
| broadcastId: ['b1', 'b2'], | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('outputs JSON in non-interactive mode', async () => { | ||
| spies = setupOutputSpies(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await metricsCommand.parseAsync([], { from: 'user' }); | ||
|
|
||
| const output = spies.logSpy.mock.calls[0][0] as string; | ||
| const parsed = JSON.parse(output); | ||
| expect(parsed.object).toBe('metrics'); | ||
| expect(parsed.totals.sent).toBe(100); | ||
| }); | ||
|
|
||
| it('rejects combining the email and broadcast dimensions, without calling the SDK', async () => { | ||
| setNonInteractive(); | ||
| errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| stderrSpy = vi | ||
| .spyOn(process.stderr, 'write') | ||
| .mockImplementation(() => true); | ||
| exitSpy = mockExitThrow(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await expectExit1(() => | ||
| metricsCommand.parseAsync(['--dimensions', 'email,broadcast'], { | ||
| from: 'user', | ||
| }), | ||
| ); | ||
|
|
||
| expect(mockMetrics).not.toHaveBeenCalled(); | ||
| const output = errorSpy.mock.calls.map((c) => c[0]).join(' '); | ||
| expect(output).toContain('invalid_options'); | ||
| }); | ||
|
|
||
| it('rejects emailId and broadcastId combined, without calling the SDK', async () => { | ||
| setNonInteractive(); | ||
| errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| stderrSpy = vi | ||
| .spyOn(process.stderr, 'write') | ||
| .mockImplementation(() => true); | ||
| exitSpy = mockExitThrow(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await expectExit1(() => | ||
| metricsCommand.parseAsync(['--email-id', 'e1', '--broadcast-id', 'b1'], { | ||
| from: 'user', | ||
| }), | ||
| ); | ||
|
|
||
| expect(mockMetrics).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rejects an empty --email-id combined with --broadcast-id, without calling the SDK', async () => { | ||
| setNonInteractive(); | ||
| errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| stderrSpy = vi | ||
| .spyOn(process.stderr, 'write') | ||
| .mockImplementation(() => true); | ||
| exitSpy = mockExitThrow(); | ||
|
|
||
| const { metricsCommand } = await import( | ||
| '../../../src/commands/emails/metrics' | ||
| ); | ||
| await expectExit1(() => | ||
| metricsCommand.parseAsync(['--email-id', '', '--broadcast-id', 'b1'], { | ||
| from: 'user', | ||
| }), | ||
| ); | ||
|
|
||
| expect(mockMetrics).not.toHaveBeenCalled(); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| const output = errorSpy.mock.calls.map((c) => c[0]).join(' '); | ||
| expect(output).toContain('invalid_options'); | ||
| }); | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: Because this adds command documentation without changing the skill metadata version, consumers may continue treating version 2.8.0 as current and miss the
metricscapability. Bump the skill version in the frontmatter with this content change.Prompt for AI agents