diff --git a/TELEMETRY.md b/TELEMETRY.md index a98f672..e1b5a0b 100644 --- a/TELEMETRY.md +++ b/TELEMETRY.md @@ -66,7 +66,7 @@ A telemetry request has the following structure: |---|---|---| | `client` | Always | Identifies the event as coming from the Chargebee CLI. | | `visitor_id` | Always | Random install ID generated by the CLI. It is not derived from your account, user, or machine. | -| `site_name` | Always | Site name of the active Chargebee profile, or `unconfigured`. | +| `site_name` | Always | Site name of the active Chargebee profile, or `unconfigured`. For `auth add` and `auth switch`, the site that is active once the command succeeds. | | `cli_version` | Always | Installed CLI version. | | `name` | Always | Command path, such as `customer list`. Arguments and values are not included. | | `timestamp` | Always | Time the event was recorded. | diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index 4464085..7eaff43 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -41,7 +41,7 @@ change-case@5.4.4 (MIT) This package ships no LICENSE, LICENCE, or COPYING file. Its package.json declares the SPDX license identifier "MIT". -chargebee@3.34.0 (MIT) +chargebee@3.35.0 (MIT) ---------------------- The MIT License diff --git a/bun.lock b/bun.lock index 223fc17..28c7975 100644 --- a/bun.lock +++ b/bun.lock @@ -97,7 +97,7 @@ "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], - "chargebee": ["chargebee@3.34.0", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-ODO/NvUCRlpvZpMu0jhzsnQ0GG5n4clL5fSqtAzYFbLIm6qoXGiq0O/fPNTLAmkaKt8Ejh42V21H4+15WlK8aw=="], + "chargebee": ["chargebee@3.35.0", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-ioa/XVCOlczBvNDi6wdle6qpdqwuZj39f2SPZIF3op3GiElbO2HcCH1SD6aZ8k+/2U9avpHqw8SW3TJiLwYvSQ=="], "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], diff --git a/src/commands/auth.ts b/src/commands/auth.ts index a8a696b..698ea6a 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -16,6 +16,7 @@ import { setCommandGroup } from "./help.js"; import { sectionTitle } from "../lib/help-style.js"; import { switchProfileAction } from "../lib/config/switch-profile.js"; import { EXIT_CODES } from "../lib/exit-codes.js"; +import { noteActiveSite } from "../lib/telemetry/active-site.js"; const DEFAULT_PROFILE = "default"; @@ -192,6 +193,7 @@ export function registerAuthCommand(program: Command): void { ...(savedRegion === DEFAULT_REGION ? {} : { region: savedRegion }), }); await writeConfig({ domain: site, activeProfile: profileName }); + noteActiveSite(site); jsonResult({ configured: true, profile: profileName, site, region: savedRegion, host: persistableHost(apiHost), product_catalog_version: catalog.productCatalogVersion ?? null, chargebee_response_schema_type: catalog.responseSchemaType ?? null, key_storage: saved.backend }); diff --git a/src/commands/generated/business_entity.ts b/src/commands/generated/business_entity.ts index 349683a..646b189 100644 --- a/src/commands/generated/business_entity.ts +++ b/src/commands/generated/business_entity.ts @@ -5,8 +5,9 @@ import { Option, type Command } from "commander"; import { getClient, ensureWriteAllowed, ensureCatalogAllowed } from "../../lib/api/sdk.js"; import { handleSdkError, printResult } from "../../lib/api/print.js"; -import { handleCodeSample } from "../../lib/api/generated-command.js"; -import { loadOperationParams, readJsonMarker } from "../../lib/api/stdin-params.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { warnBareListFilters } from "../../lib/codesample/index.js"; +import { loadOperationParams, takeResourceId, readJsonMarker, warnBareJsonFilters } from "../../lib/api/stdin-params.js"; import { toSdkParams } from "../../lib/api/params.js"; @@ -16,6 +17,28 @@ export function registerBusinessEntity(parent: Command): void { .alias("business_entity") .description("API operations for business entities"); + cmd + .command("create") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Create a business_entity") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs business-entity create\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "create_a_business_entity", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "business-entity create"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "create_a_business_entity", opIdV1: "", method: "POST", uri: "/business_entities", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + await ensureWriteAllowed("POST", "business-entity create", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).businessEntity.create(params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + cmd .command("create-transfers") .argument("[json]", "'-' reads a JSON object from stdin.") @@ -58,4 +81,75 @@ export function registerBusinessEntity(parent: Command): void { } catch (e) { handleSdkError(e); } }); + cmd + .command("list") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("List business entities") + .option("-d, --data ", "Parameters as key=value. List filters require an operator suffix (id[is]=…). Bare keys: limit, offset, include_deleted.") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mLIST FILTERS\u001b[0m\n Filter fields need an operator suffix: [is], [in], [starts_with], [between], [gt], [lt], ...\n Pagination uses bare keys: -d limit=10\n See https://apidocs.chargebee.com/docs/api/list-ops\n Per-resource Filter Params: chargebee docs business-entity list") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs business-entity list\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_business_entities", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "business-entity list"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_business_entities", opIdV1: "", method: "GET", uri: "/business_entities", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + if (fromStdin) warnBareJsonFilters(params, "business-entity"); + else warnBareListFilters(opts.data ?? [], "business-entity"); + try { + const client = await getClient(); + const result = await (client as any).businessEntity.list(toSdkParams(params, "GET", true)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[business-entity-id]", "A unique and immutable identifier for the business entity.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a business entity") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs business-entity retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_business_entity", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "business-entity retrieve"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_business_entity", opIdV1: "", method: "GET", uri: "/business_entities/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "business-entity-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'business-entity-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).businessEntity.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("update") + .argument("[business-entity-id]", "A unique and immutable identifier for the business entity.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Update business entity") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs business-entity update\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "update_business_entity", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "business-entity update"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "update_business_entity", opIdV1: "", method: "POST", uri: "/business_entities/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "business-entity-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'business-entity-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "business-entity update", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).businessEntity.update(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + } \ No newline at end of file diff --git a/src/commands/generated/collections_payment_promise.ts b/src/commands/generated/collections_payment_promise.ts new file mode 100644 index 0000000..a89f68b --- /dev/null +++ b/src/commands/generated/collections_payment_promise.ts @@ -0,0 +1,129 @@ +// Code generated by src/tools/generate.ts from Chargebee SDK endpoints. DO NOT EDIT. +// Regenerate with: bun run generate + +import { Option, type Command } from "commander"; + +import { getClient, ensureWriteAllowed } from "../../lib/api/sdk.js"; +import { handleSdkError, printResult } from "../../lib/api/print.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { loadOperationParams, takeResourceId, readJsonMarker } from "../../lib/api/stdin-params.js"; + +import { toSdkParams } from "../../lib/api/params.js"; + +export function registerCollectionsPaymentPromise(parent: Command): void { + const cmd = parent + .command("collections-payment-promise") + .alias("collections_payment_promise") + .description("API operations for collections payment promises"); + + cmd + .command("cancel") + .argument("[collections-payment-promise-id]", "Unique identifier of the collections payment promise.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Cancel a collections payment promise") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs collections-payment-promise cancel\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "cancel_a_collections_payment_promise", opIdV1: "cancel_a_collections_payment_promise", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "cancel_a_collections_payment_promise", opIdV1: "cancel_a_collections_payment_promise", method: "POST", uri: "/collections_payment_promises/{id}/cancel", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "collections-payment-promise-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'collections-payment-promise-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "collections-payment-promise cancel", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).collectionsPaymentPromise.cancel(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("create-collections-payment-promise") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Create a collections payment promise") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs collections-payment-promise create-collections-payment-promise\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "create_a_collections_payment_promise", opIdV1: "create_a_collections_payment_promise", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "create_a_collections_payment_promise", opIdV1: "create_a_collections_payment_promise", method: "POST", uri: "/collections_payment_promises", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + await ensureWriteAllowed("POST", "collections-payment-promise create-collections-payment-promise", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).collectionsPaymentPromise.createCollectionsPaymentPromise(params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("list-collections-payment-promises") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("List collections payment promises") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs collections-payment-promise list-collections-payment-promises\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_collections_payment_promises", opIdV1: "list_collections_payment_promises", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_collections_payment_promises", opIdV1: "list_collections_payment_promises", method: "GET", uri: "/collections_payment_promises", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + try { + const client = await getClient(); + const result = await (client as any).collectionsPaymentPromise.listCollectionsPaymentPromises(toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[collections-payment-promise-id]", "Unique identifier of the collections payment promise.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a payment promise") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs collections-payment-promise retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_payment_promise", opIdV1: "retrieve_a_payment_promise", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_payment_promise", opIdV1: "retrieve_a_payment_promise", method: "GET", uri: "/collections_payment_promises/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "collections-payment-promise-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'collections-payment-promise-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).collectionsPaymentPromise.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("update-collections-payment-promise") + .argument("[collections-payment-promise-id]", "Unique identifier of the collections payment promise.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Update a collections payment promise") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs collections-payment-promise update-collections-payment-promise\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "update_a_collections_payment_promise", opIdV1: "update_a_collections_payment_promise", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "update_a_collections_payment_promise", opIdV1: "update_a_collections_payment_promise", method: "POST", uri: "/collections_payment_promises/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "collections-payment-promise-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'collections-payment-promise-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "collections-payment-promise update-collections-payment-promise", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).collectionsPaymentPromise.updateCollectionsPaymentPromise(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/commands/generated/docs-operations.ts b/src/commands/generated/docs-operations.ts index 2303595..8e2123c 100644 --- a/src/commands/generated/docs-operations.ts +++ b/src/commands/generated/docs-operations.ts @@ -113,6 +113,10 @@ export const docsOperationIds: Record", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs invoice remove-payment-schedule-scheme\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "remove_payment_schedule_scheme_from_an_invoice", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "invoice remove-payment-schedule-scheme"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "remove_payment_schedule_scheme_from_an_invoice", opIdV1: "", method: "POST", uri: "/invoices/{id}/remove_payment_schedule_scheme", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "invoice-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'invoice-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "invoice remove-payment-schedule-scheme", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).invoice.removePaymentScheduleScheme(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + cmd .command("remove-tax-withheld") .argument("[invoice-id]", "The invoice number.") diff --git a/src/commands/generated/ledger_account_balance.ts b/src/commands/generated/ledger_account_balance.ts index 05c4e27..f95a624 100644 --- a/src/commands/generated/ledger_account_balance.ts +++ b/src/commands/generated/ledger_account_balance.ts @@ -36,4 +36,26 @@ export function registerLedgerAccountBalance(parent: Command): void { } catch (e) { handleSdkError(e); } }); + cmd + .command("update-overdraft-limit") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Update the overdraft limit") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs ledger-account-balance update-overdraft-limit\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "update_overdraft_limit", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "ledger-account-balance update-overdraft-limit"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "update_overdraft_limit", opIdV1: "", method: "POST", uri: "/ledger_account_balances/update_overdraft_limit", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + await ensureWriteAllowed("POST", "ledger-account-balance update-overdraft-limit", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).ledgerAccountBalance.updateOverdraftLimit(params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + } \ No newline at end of file diff --git a/src/commands/generated/price_ramp.ts b/src/commands/generated/price_ramp.ts new file mode 100644 index 0000000..b396ce1 --- /dev/null +++ b/src/commands/generated/price_ramp.ts @@ -0,0 +1,138 @@ +// Code generated by src/tools/generate.ts from Chargebee SDK endpoints. DO NOT EDIT. +// Regenerate with: bun run generate + +import { Option, type Command } from "commander"; + +import { getClient, ensureWriteAllowed, ensureCatalogAllowed } from "../../lib/api/sdk.js"; +import { handleSdkError, printResult } from "../../lib/api/print.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { warnBareListFilters } from "../../lib/codesample/index.js"; +import { loadOperationParams, takeResourceId, readJsonMarker, warnBareJsonFilters } from "../../lib/api/stdin-params.js"; + +import { toSdkParams } from "../../lib/api/params.js"; + +export function registerPriceRamp(parent: Command): void { + const cmd = parent + .command("price-ramp") + .alias("price_ramp") + .description("API operations for price ramps"); + + cmd + .command("create") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Create a price ramp") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs price-ramp create\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "create_a_price_ramp", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "price-ramp create"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "create_a_price_ramp", opIdV1: "", method: "POST", uri: "/price_ramps", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + await ensureWriteAllowed("POST", "price-ramp create", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).priceRamp.create(params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("delete") + .argument("[price-ramp-id]", "A unique and immutable ID for the price ramp.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Delete a price ramp") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs price-ramp delete\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "delete_a_price_ramp", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "price-ramp delete"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "delete_a_price_ramp", opIdV1: "", method: "POST", uri: "/price_ramps/{id}/delete", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "price-ramp-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'price-ramp-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "price-ramp delete", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).priceRamp.delete(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("list") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("List price ramps") + .option("-d, --data ", "Parameters as key=value. List filters require an operator suffix (id[is]=…). Bare keys: limit, offset, include_deleted.") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mLIST FILTERS\u001b[0m\n Filter fields need an operator suffix: [is], [in], [starts_with], [between], [gt], [lt], ...\n Pagination uses bare keys: -d limit=10\n See https://apidocs.chargebee.com/docs/api/list-ops\n Per-resource Filter Params: chargebee docs price-ramp list") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs price-ramp list\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_price_ramps", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "price-ramp list"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_price_ramps", opIdV1: "", method: "GET", uri: "/price_ramps", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + if (fromStdin) warnBareJsonFilters(params, "price-ramp"); + else warnBareListFilters(opts.data ?? [], "price-ramp"); + try { + const client = await getClient(); + const result = await (client as any).priceRamp.list(toSdkParams(params, "GET", true)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[price-ramp-id]", "A unique and immutable ID for the price ramp.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a price ramp") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs price-ramp retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_price_ramp", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "price-ramp retrieve"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_price_ramp", opIdV1: "", method: "GET", uri: "/price_ramps/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "price-ramp-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'price-ramp-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).priceRamp.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("update") + .argument("[price-ramp-id]", "A unique and immutable ID for the price ramp.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Update a price ramp") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("-y, --yes", "Skip the confirmation prompt for writes on a live site") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs price-ramp update\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; yes?: boolean }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "update_a_price_ramp", opIdV1: "", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample !== "list") await ensureCatalogAllowed("pc2", "price-ramp update"); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "update_a_price_ramp", opIdV1: "", method: "POST", uri: "/price_ramps/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "price-ramp-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'price-ramp-id'"); + assertResourceId(resource.id, command); + await ensureWriteAllowed("POST", "price-ramp update", opts.yes === true); + try { + const client = await getClient(); + const result = await (client as any).priceRamp.update(resource.id, params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/commands/generated/registry.ts b/src/commands/generated/registry.ts index 18d3076..2417ac2 100644 --- a/src/commands/generated/registry.ts +++ b/src/commands/generated/registry.ts @@ -12,6 +12,7 @@ import { registerBusinessEntity } from "./business_entity.js"; import { registerBusinessRule } from "./business_rule.js"; import { registerBusinessRuleset } from "./business_ruleset.js"; import { registerCard } from "./card.js"; +import { registerCollectionsPaymentPromise } from "./collections_payment_promise.js"; import { registerComment } from "./comment.js"; import { registerConfiguration } from "./configuration.js"; import { registerCoupon } from "./coupon.js"; @@ -60,6 +61,7 @@ import { registerPaymentVoucher } from "./payment_voucher.js"; import { registerPersonalizedOffer } from "./personalized_offer.js"; import { registerPlan } from "./plan.js"; import { registerPortalSession } from "./portal_session.js"; +import { registerPriceRamp } from "./price_ramp.js"; import { registerPriceVariant } from "./price_variant.js"; import { registerPricingPageSession } from "./pricing_page_session.js"; import { registerPromotionalCredit } from "./promotional_credit.js"; @@ -70,6 +72,7 @@ import { registerQuoteEntitlement } from "./quote_entitlement.js"; import { registerRamp } from "./ramp.js"; import { registerRecordedPurchase } from "./recorded_purchase.js"; import { registerResourceMigration } from "./resource_migration.js"; +import { registerRetrySegment } from "./retry_segment.js"; import { registerRule } from "./rule.js"; import { registerSiteMigrationDetail } from "./site_migration_detail.js"; import { registerSubscription } from "./subscription.js"; @@ -109,6 +112,8 @@ export function registerAll(rootCmd: Command): void { { const cmd = rootCmd.commands.find(c => c.name() === "business-ruleset"); if (cmd) setCommandGroup(cmd, "resource"); } registerCard(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "card"); if (cmd) setCommandGroup(cmd, "resource"); } + registerCollectionsPaymentPromise(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "collections-payment-promise"); if (cmd) setCommandGroup(cmd, "resource"); } registerComment(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "comment"); if (cmd) setCommandGroup(cmd, "resource"); } registerConfiguration(rootCmd); @@ -205,6 +210,8 @@ export function registerAll(rootCmd: Command): void { { const cmd = rootCmd.commands.find(c => c.name() === "plan"); if (cmd) setCommandGroup(cmd, "resource"); } registerPortalSession(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "portal-session"); if (cmd) setCommandGroup(cmd, "resource"); } + registerPriceRamp(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "price-ramp"); if (cmd) setCommandGroup(cmd, "resource"); } registerPriceVariant(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "price-variant"); if (cmd) setCommandGroup(cmd, "resource"); } registerPricingPageSession(rootCmd); @@ -225,6 +232,8 @@ export function registerAll(rootCmd: Command): void { { const cmd = rootCmd.commands.find(c => c.name() === "recorded-purchase"); if (cmd) setCommandGroup(cmd, "resource"); } registerResourceMigration(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "resource-migration"); if (cmd) setCommandGroup(cmd, "resource"); } + registerRetrySegment(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "retry-segment"); if (cmd) setCommandGroup(cmd, "resource"); } registerRule(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "rule"); if (cmd) setCommandGroup(cmd, "resource"); } registerSiteMigrationDetail(rootCmd); diff --git a/src/commands/generated/retry_segment.ts b/src/commands/generated/retry_segment.ts new file mode 100644 index 0000000..ea7fe8b --- /dev/null +++ b/src/commands/generated/retry_segment.ts @@ -0,0 +1,41 @@ +// Code generated by src/tools/generate.ts from Chargebee SDK endpoints. DO NOT EDIT. +// Regenerate with: bun run generate + +import { Option, type Command } from "commander"; + +import { getClient, ensureWriteAllowed } from "../../lib/api/sdk.js"; +import { handleSdkError, printResult } from "../../lib/api/print.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { loadOperationParams, takeResourceId } from "../../lib/api/stdin-params.js"; + +import { toSdkParams } from "../../lib/api/params.js"; + +export function registerRetrySegment(parent: Command): void { + const cmd = parent + .command("retry-segment") + .alias("retry_segment") + .description("API operations for retry segments"); + + cmd + .command("retrieve") + .argument("[retry-segment-id]", "Retry segment identifier.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a retry segment") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs retry-segment retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_retry_segment", opIdV1: "retrieve_a_retry_segment", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_retry_segment", opIdV1: "retrieve_a_retry_segment", method: "GET", uri: "/retry_segments/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "retry-segment-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'retry-segment-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).retrySegment.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/lib/config/switch-profile.ts b/src/lib/config/switch-profile.ts index a405685..7f94947 100644 --- a/src/lib/config/switch-profile.ts +++ b/src/lib/config/switch-profile.ts @@ -2,6 +2,7 @@ import { humanLog, diagnostic, exitCommand, jsonResult } from "../output.js"; import { assertValidProfileName, listProfiles, loadProfile } from "./profiles.js"; import { readConfig, writeConfig } from "./store.js"; import { siteMode } from "../api/write-gate.js"; +import { noteActiveSite } from "../telemetry/active-site.js"; /** `auth switch`. `domain` is still written as `CHARGEBEE_DOMAIN`. */ export async function switchProfileAction(name?: string): Promise { @@ -66,6 +67,7 @@ export async function switchProfileAction(name?: string): Promise { domain: p.site, activeProfile: chosen, }); + noteActiveSite(p.site); const mode = siteMode(p.site, p.api_key); jsonResult({ active_profile: chosen, site: p.site, mode }); diff --git a/src/lib/telemetry/active-site.ts b/src/lib/telemetry/active-site.ts new file mode 100644 index 0000000..53f4552 --- /dev/null +++ b/src/lib/telemetry/active-site.ts @@ -0,0 +1,23 @@ +/** + * Shared, dependency-free slot for a site the current invocation made active + * (`auth add`, `auth switch`). + * + * Lives in its own module (importing nothing) so commands can set it without + * importing the recorder (`telemetry/index.ts`, which imports `sdk.ts`). The + * recorder reads the active site before the command runs, so without this the + * event would carry the previous site (or `unconfigured`). It reads this slot at + * finalize time and prefers it. + */ +let _site: string | undefined; + +/** Record the site this invocation made active. Call only after it is saved. */ +export function noteActiveSite(site: string): void { + _site = site; +} + +/** Read and clear the noted site. */ +export function takeActiveSite(): string | undefined { + const v = _site; + _site = undefined; + return v; +} diff --git a/src/lib/telemetry/index.ts b/src/lib/telemetry/index.ts index ea31bd4..8659b39 100644 --- a/src/lib/telemetry/index.ts +++ b/src/lib/telemetry/index.ts @@ -18,6 +18,7 @@ import { } from "./constants.js"; import { buildMetadata, normalizeGeneratedResource } from "./metadata.js"; import { recordTelemetryError, takeTelemetryError } from "./error.js"; +import { takeActiveSite } from "./active-site.js"; import { wasInteractive } from "./interactive.js"; import { isTelemetryDisabled, maybeShowFirstRunNotice } from "./optout.js"; import { getVisitorId } from "./identity.js"; @@ -57,6 +58,7 @@ export function __resetTelemetryRecorderForTest(): void { finalized = false; listenLifecycleEmitted = false; _version = "0.0.0"; + takeActiveSite(); if (exitHandler) { process.removeListener("exit", exitHandler); exitHandler = null; @@ -291,7 +293,7 @@ function finalize(exitCode: number): void { const record: SpoolRecord = { env: pending.env, - site_name: pending.siteName, + site_name: takeActiveSite() ?? pending.siteName, visitor_id: pending.visitorId, cli_version: _version, event: { name: pending.command, timestamp: new Date().toISOString(), metadata }, diff --git a/src/lib/test-support/_helpers.ts b/src/lib/test-support/_helpers.ts index b931b8d..087c0d3 100644 --- a/src/lib/test-support/_helpers.ts +++ b/src/lib/test-support/_helpers.ts @@ -1,3 +1,5 @@ +import type { Command } from "commander"; + import { buildProgram } from "../../program.js"; import { __setClientFactory, __resetRuntimeState } from "../api/sdk.js"; @@ -130,9 +132,13 @@ export function createEnvPatcher(): { /** * Run the CLI in-process with the given args. Captures stdout/stderr (both * `console.*` and direct `process.std*.write`) and the exit code, restoring all - * globals afterwards. + * globals afterwards. `configure` runs on the built program before parsing + * (e.g. to install the telemetry recorder, which `buildProgram` leaves out). */ -export async function runCli(args: string[]): Promise { +export async function runCli( + args: string[], + opts: { configure?: (program: Command) => void } = {}, +): Promise { __resetRuntimeState(); let stdout = ""; @@ -173,6 +179,7 @@ export async function runCli(args: string[]): Promise { let exitCode = 0; try { const program = buildProgram("0.0.0-test"); + opts.configure?.(program); await program.parseAsync(args, { from: "user" }); exitCode = Number(process.exitCode ?? 0); } catch (err) { diff --git a/src/tests/integration/telemetry-site-label.test.ts b/src/tests/integration/telemetry-site-label.test.ts new file mode 100644 index 0000000..f9c05f5 --- /dev/null +++ b/src/tests/integration/telemetry-site-label.test.ts @@ -0,0 +1,130 @@ +/** + * The telemetry event for a command that changes the active site (`auth add`, + * `auth switch`) must carry the site that is active after it succeeds, not the + * one that was active before it ran. + */ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { spoolPath } from "../../lib/telemetry/constants.js"; +import { + __finalizeForTest, + __resetTelemetryRecorderForTest, + __setSpawnForTest, + installTelemetry, +} from "../../lib/telemetry/index.js"; +import { writeState } from "../../lib/telemetry/state.js"; +import type { SpoolRecord } from "../../lib/telemetry/types.js"; +import { + clearCiEnv, + createEnvPatcher, + installFakeClient, + runCli, + setStdinIsTTY, + uninstallFakeClient, + type ClientConstruction, +} from "../../lib/test-support/_helpers.js"; + +const env = createEnvPatcher(); +let configDir: string; +let restoreCiEnv: () => void = () => undefined; +let restoreStdin: (() => void) | undefined; + +beforeEach(() => { + restoreCiEnv = clearCiEnv(); + configDir = mkdtempSync(join(tmpdir(), "cb-telemetry-site-")); + env.set("CHARGEBEE_CONFIG_DIR", configDir); + env.set("CHARGEBEE_SITE", undefined); + env.set("CHARGEBEE_API_KEY", undefined); + env.set("DO_NOT_TRACK", undefined); + env.set("CHARGEBEE_CLI_TELEMETRY", undefined); + // A later run: the first-run notice has been shown, so events are recorded. + writeState({ notice_shown: true }); + const constructions: ClientConstruction[] = []; + installFakeClient({ constructions }); + restoreStdin = setStdinIsTTY(false); + __resetTelemetryRecorderForTest(); + __setSpawnForTest(() => ({ unref() {} })); +}); + +afterEach(() => { + __resetTelemetryRecorderForTest(); + __setSpawnForTest(null); + restoreStdin?.(); + uninstallFakeClient(); + env.restore(); + restoreCiEnv(); + rmSync(configDir, { recursive: true, force: true }); +}); + +/** Run one command with the recorder installed and return its spooled event. */ +async function runRecorded(args: string[]): Promise<{ exitCode: number; record: SpoolRecord }> { + const { exitCode } = await runCli(args, { + configure: (program) => installTelemetry(program, "0.0.0-test"), + }); + __finalizeForTest(exitCode); + __resetTelemetryRecorderForTest(); + const lines = readFileSync(spoolPath(), "utf-8").trim().split("\n"); + return { exitCode, record: JSON.parse(lines.at(-1)!) as SpoolRecord }; +} + +/** Save a profile without recording an event. */ +async function addProfile(profile: string, site: string, apiKey: string): Promise { + const { exitCode } = await runCli(["auth", "add", "--profile", profile, "--site", site, "--api-key", apiKey]); + expect(exitCode).toBe(0); +} + +describe("telemetry site label for commands that change the active site", () => { + it("labels the first auth add with the added site, not unconfigured", async () => { + const { exitCode, record } = await runRecorded([ + "auth", "add", "--profile", "dev", "--site", "acme-test", "--api-key", "test_key", + ]); + expect(exitCode).toBe(0); + expect(record.event.name).toBe("auth add"); + expect(record.site_name).toBe("acme-test"); + }); + + it("labels auth add with the new site when another profile was active", async () => { + await addProfile("dev", "acme-test", "test_key"); + const { record } = await runRecorded([ + "auth", "add", "--profile", "other", "--site", "globex-test", "--api-key", "test_key_2", + ]); + expect(record.site_name).toBe("globex-test"); + }); + + it("labels auth switch with the site switched to", async () => { + await addProfile("dev", "acme-test", "test_key"); + await addProfile("other", "globex-test", "test_key_2"); + const { exitCode, record } = await runRecorded(["auth", "switch", "dev"]); + expect(exitCode).toBe(0); + expect(record.event.name).toBe("auth switch"); + expect(record.site_name).toBe("acme-test"); + }); + + it("keeps the previous site when auth add fails", async () => { + await addProfile("dev", "acme-test", "test_key"); + const { exitCode, record } = await runRecorded([ + "auth", "add", "--profile", "bad", "--site", "not a site!", "--api-key", "test_key_2", + ]); + expect(exitCode).toBe(1); + expect(record.site_name).toBe("acme-test"); + }); + + it("labels the next command from the active profile as before", async () => { + await addProfile("dev", "acme-test", "test_key"); + const { record } = await runRecorded(["customer", "list"]); + expect(record.site_name).toBe("acme-test"); + }); + + it("records nothing when telemetry is disabled", async () => { + env.set("CHARGEBEE_CLI_TELEMETRY", "0"); + const { exitCode } = await runCli(["auth", "add", "--profile", "dev", "--site", "acme-test", "--api-key", "test_key"], { + configure: (program) => installTelemetry(program, "0.0.0-test"), + }); + __finalizeForTest(exitCode); + expect(exitCode).toBe(0); + expect(existsSync(spoolPath())).toBe(false); + }); +}); diff --git a/src/tests/unit/lib/telemetry/active-site.test.ts b/src/tests/unit/lib/telemetry/active-site.test.ts new file mode 100644 index 0000000..8b6c898 --- /dev/null +++ b/src/tests/unit/lib/telemetry/active-site.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import { noteActiveSite, takeActiveSite } from "../../../../lib/telemetry/active-site.js"; + +afterEach(() => { + takeActiveSite(); +}); + +describe("active-site slot", () => { + it("is empty by default", () => { + expect(takeActiveSite()).toBeUndefined(); + }); + + it("returns the noted site once, then clears", () => { + noteActiveSite("acme-test"); + expect(takeActiveSite()).toBe("acme-test"); + expect(takeActiveSite()).toBeUndefined(); + }); + + it("keeps the latest noted site", () => { + noteActiveSite("acme-test"); + noteActiveSite("globex-test"); + expect(takeActiveSite()).toBe("globex-test"); + }); +}); diff --git a/src/tests/unit/lib/telemetry/index.test.ts b/src/tests/unit/lib/telemetry/index.test.ts index d2fe77b..41eb5ef 100644 --- a/src/tests/unit/lib/telemetry/index.test.ts +++ b/src/tests/unit/lib/telemetry/index.test.ts @@ -19,6 +19,7 @@ import { appendRecord } from "../../../../lib/telemetry/spool.js"; import { setTelemetryEnabled } from "../../../../lib/telemetry/optout.js"; import { readState, writeState } from "../../../../lib/telemetry/state.js"; import { recordTelemetryError, takeTelemetryError } from "../../../../lib/telemetry/error.js"; +import { noteActiveSite, takeActiveSite } from "../../../../lib/telemetry/active-site.js"; import type { SpoolRecord } from "../../../../lib/telemetry/types.js"; import { __resetKeychainForTest, __setKeychainForTest, type KeychainStore } from "../../../../lib/config/keychain.js"; import { saveProfile } from "../../../../lib/config/profiles.js"; @@ -588,5 +589,23 @@ describe("installTelemetry recorder", () => { const rec = await recordOneCommand(); expect(rec.site_name).toBe("env-test"); }); + + it("prefers a site the command noted as newly active", async () => { + const program = new Command(); + program.exitOverride(); + program.command("connect").action(() => noteActiveSite("globex-test")); + installTelemetry(program, "1.0.0-test"); + await program.parseAsync(["connect"], { from: "user" }); + __finalizeForTest(0); + const rec = JSON.parse(readFileSync(spoolPath(), "utf-8").trim()) as SpoolRecord; + expect(rec.site_name).toBe("globex-test"); + expect(takeActiveSite()).toBeUndefined(); + }); + + it("drops a noted site on recorder reset", () => { + noteActiveSite("globex-test"); + __resetTelemetryRecorderForTest(); + expect(takeActiveSite()).toBeUndefined(); + }); }); });