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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,14 @@ chargebee listen --forward-to http://localhost:3000/webhooks --json

Press `Ctrl+C` to stop listening.

To send a past event (for example, one your handler failed on) to your local handler again:

```bash
chargebee event replay event-id --forward-to http://localhost:3000/webhooks
```

Replay works on test sites only and sends only to this machine (`localhost`, `127.0.0.1`, `::1`). It sends the event as `chargebee event retrieve` returns it now, so fields such as `webhook_status` show its current state. To deliver an event to a deployed endpoint, use **Resend** on the event page in Chargebee.

## Use with AI Agents

Install Chargebee skills for your coding agent:
Expand Down
118 changes: 118 additions & 0 deletions src/commands/event-replay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import type { Command } from "commander";

import { getClient, isLiveSite, resolveAuth } from "../lib/api/sdk.js";
import { handleSdkError } from "../lib/api/print.js";
import { assertResourceId } from "../lib/api/generated-command.js";
import { EXIT_CODES } from "../lib/exit-codes.js";
import { diagnostic, exitCommand, humanLog, jsonResult } from "../lib/output.js";
import { recordTelemetryError } from "../lib/telemetry/error.js";
import * as display from "../lib/tunnel/display.js";
import {
checkLoopbackResolution,
describeHandlerStatus,
ReplayErrorCode,
resolveReplayTarget,
sendReplay,
type ReplayResponse,
} from "../lib/tunnel/replay.js";

const EXAMPLES = [
"",
"\u001b[1mEXAMPLES\u001b[0m",
" chargebee event replay ev_16BHbhF4s42tO2lK --forward-to http://localhost:3000/webhooks",
" chargebee event replay ev_16BHbhF4s42tO2lK -f 3000 --json",
"",
"\u001b[1mNOTES\u001b[0m",
" Available on test sites only. Sends only to this machine (localhost, 127.0.0.1, ::1);",
" to deliver to a deployed endpoint, use Resend on the event page.",
" The body is the event as `chargebee event retrieve` returns it now, so fields such as",
" webhook_status reflect its current state rather than the original delivery.",
"",
].join("\n");

/**
* `chargebee event replay <event-id> --forward-to <url>`.
*
* `event` is a generated command group, so this built-in subcommand is attached
* to it after the generated commands are registered (generated files are never
* edited by hand).
*/
export function registerEventReplayCommand(program: Command): void {
// The generated `event` group always exists; codegen drift is checked in CI.
const eventGroup = program.commands.find((cmd) => cmd.name() === "event")!;

eventGroup
.command("replay")
.argument("<event-id>", "Unique identifier of the event to replay.")
.description("Send a past event to a local webhook handler (test sites only)")
.requiredOption(
"-f, --forward-to <endpoint>",
"Local endpoint to send the event to (localhost, 127.0.0.1 or ::1)",
)
.addHelpText("after", EXAMPLES)
.action(async (eventId: string, opts: { forwardTo: string }, command: Command) => {
assertResourceId(eventId, command);

const target = resolveReplayTarget(opts.forwardTo);
if ("error" in target) {
recordTelemetryError(target.code);
diagnostic(target.error);
exitCommand(EXIT_CODES.ERROR, target.code);
}
const url = target.url;
const resolutionError = await checkLoopbackResolution(url);
if (resolutionError) {
recordTelemetryError(ReplayErrorCode.TARGET_REFUSED);
diagnostic(resolutionError);
exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.TARGET_REFUSED);
}

let site: string;
let apiKey: string;
try {
({ site, apiKey } = await resolveAuth());
} catch (err) {
handleSdkError(err);
}
if (isLiveSite(site, apiKey)) {
recordTelemetryError(ReplayErrorCode.LIVE_SITE_REFUSED);
diagnostic(
`Refusing to replay on live site "${site}".\n\n` +
` Event replay is only available on test sites (name ending in "-test", or a test_ API key).`,
);
exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.LIVE_SITE_REFUSED);
}

let event: Record<string, unknown>;
try {
const client = await getClient();
({ event } = await (client as any).event.retrieve(eventId));
} catch (err) {
handleSdkError(err);
}

const eventType = typeof event.event_type === "string" ? event.event_type : "";
const label = display.sanitizeEventType(eventType) || "unknown type";
const details = { event_id: eventId, event_type: eventType, url };
humanLog(`Replaying ${eventId} (${label}) to ${url}`);

let response: ReplayResponse;
try {
response = await sendReplay(url, event);
} catch (err) {
recordTelemetryError(ReplayErrorCode.UNREACHABLE);
diagnostic((err as Error).message);
exitCommand(EXIT_CODES.NETWORK, ReplayErrorCode.UNREACHABLE, details);
}

const { status, durationMs, location } = response;
const ok = status >= 200 && status < 300;
humanLog(`${eventId} ${label} → ${status} (${durationMs} ms)${ok ? "" : " (non-2xx)"}`);
if (!ok) {
recordTelemetryError(ReplayErrorCode.HANDLER_ERROR);
diagnostic(describeHandlerStatus(url, status, location));
exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.HANDLER_ERROR, { ...details, status, duration_ms: durationMs });
}
jsonResult({ ...details, status, duration_ms: durationMs });
});
}
4 changes: 2 additions & 2 deletions src/lib/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export function finishOutput(exitCode = 0, code = "command_failed", details?: un
}

/** Preserve existing exit codes while flushing the structured outcome first. */
export function exitCommand(code: number, errorCode?: string): never {
finishOutput(code, errorCode);
export function exitCommand(code: number, errorCode?: string, details?: unknown): never {
finishOutput(code, errorCode, details);
// Let the entry point return normally so Node can flush piped JSON in full.
if (isJsonMode()) throw new OutputExit(code);
process.exit(code);
Expand Down
1 change: 1 addition & 0 deletions src/lib/skills/content/references/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ chargebee auth status
|---|---|
| `chargebee docs [resource] [operation]` | Browse API documentation. |
| `chargebee listen --forward-to <url>` | Forward test-site webhooks to a local URL. The URL is required. |
| `chargebee event replay <event-id> --forward-to <url>` | Send a past test-site event to a local handler (loopback URLs only). `--json` prints `event_id`, `event_type`, `url`, `status`, `duration_ms`. |
| `chargebee resources` | List callable API resources. |
| `chargebee skills add\|list\|update\|remove` | Manage installed agent skills. |
| `chargebee alias set\|remove\|show` | Manage the shell alias. |
Expand Down
10 changes: 10 additions & 0 deletions src/lib/skills/content/references/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,15 @@ chargebee listen \

There is no event-type filter; events for the site are forwarded to the configured URL.

Replay a past event to the local handler, for example after fixing a handler that failed on it:

```bash
chargebee event list -d 'webhook_status[is]=failed' -d limit=5
chargebee event replay <event-id> --forward-to localhost:3000/webhook
```

`event replay` is available only for test sites and sends only to `localhost`, `127.0.0.1` or `::1`; there is no override. It exits non-zero when the handler returns a non-2xx status (exit 1) or can't be reached (exit 7). The body is the event's current state, not the exact original delivery. To deliver to a deployed endpoint, the user must use Resend on the event page.

## 9. AI Agent Setup

Install the Chargebee skill:
Expand Down Expand Up @@ -244,4 +253,5 @@ If a project skill path resolves to a global installation, it is global only: pr
| Unknown command/resource | Run `chargebee resources` or `chargebee <resource> --help`. |
| Code sample unavailable | Use `chargebee docs <resource> <operation>` for the API reference and construct the request from the documented parameters. |
| Webhook listen blocked | Use a test site. |
| Event replay target refused | Replay only sends to this machine; use a `localhost` URL, or ask the user to use Resend on the event page. |
| CLI bug or rough edge | Run `chargebee feedback "what happened"`. |
25 changes: 25 additions & 0 deletions src/lib/test-support/_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,31 @@ export function installFakeClient(opts: FakeClientOptions): void {
item: {
list: async () => sdkResult({ list: [{ item: { id: `item_${site}` } }] }),
},
event: {
retrieve: async (id: string) => {
if (id === "ev_missing") {
throw {
message: `Sorry, we couldn't find that resource`,
type: "invalid_request",
api_error_code: "resource_not_found",
http_status_code: 404,
headers: { "content-type": "application/json" },
};
}
return sdkResult({
event: {
id,
occurred_at: 1764374400,
source: "admin_console",
object: "event",
api_version: "v2",
event_type: "subscription_created",
webhook_status: "failed",
content: { subscription: { id: `sub_${site}` } },
},
});
},
},
estimate: {
createSubItemEstimate: async () => sdkResult({ estimate: { id: `est_${site}` } }),
},
Expand Down
23 changes: 19 additions & 4 deletions src/lib/tunnel/forwarder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ export function __setFetchForTest(fn: FetchFn | null): void {

let fetchImpl: FetchFn = globalThis.fetch.bind(globalThis) as FetchFn;

/** Send a request to the developer's local handler (replaced by `__setFetchForTest`). */
export function fetchLocalHandler(url: string, init: RequestInit): Promise<Response> {
return fetchImpl(url, init);
}

export type ForwardTargetResult =
| { url: string; warning?: string }
| { error: string };

/** `localhost`, any 127.0.0.0/8 address, or the IPv6 loopback (brackets already stripped). */
function isLoopbackHost(hostname: string): boolean {
export function isLoopbackHost(hostname: string): boolean {
return (
hostname === "localhost" ||
hostname === "::1" ||
Expand All @@ -36,6 +41,18 @@ const FORWARD_TO_EXAMPLE = "Example: --forward-to http://localhost:3000/webhook"
/** Chargebee event type names are lowercase dotted/underscored slugs; anything else can't be a real one. */
const EVENT_TYPE_HEADER_RE = /^[a-z0-9_.:-]+$/;

/**
* Set `X-Chargebee-Event-Type` so a handler can branch without parsing the body.
* Shared by `listen` and `event replay` so both deliver the same header. A value
* that isn't a valid event-type slug is untrusted and the header is left out
* rather than passed through.
*/
export function setEventTypeHeader(headers: Headers, eventType: unknown): void {
if (typeof eventType === "string" && EVENT_TYPE_HEADER_RE.test(eventType)) {
headers.set("X-Chargebee-Event-Type", eventType);
}
}

/**
* Validate and normalize a `--forward-to` value into an absolute http(s) URL.
*
Expand Down Expand Up @@ -117,9 +134,7 @@ export async function forward(
headers.set(k, v);
}
}
if (EVENT_TYPE_HEADER_RE.test(msg.event_type)) {
headers.set("X-Chargebee-Event-Type", msg.event_type);
}
setEventTypeHeader(headers, msg.event_type);

const resp = await fetchImpl(targetURL, {
method: msg.method,
Expand Down
Loading
Loading