From cb80d0c6d03e84b256b94e8fd00bdd3835797e7f Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Wed, 25 Nov 2026 12:07:52 +0000 Subject: [PATCH] Fix CLI app discovery across organizations --- .changeset/cli-multi-org.md | 5 + packages/cli/README.md | 43 +++--- packages/cli/commands/apps.ts | 15 ++- packages/cli/commands/flags.ts | 13 +- packages/cli/commands/init.ts | 66 ++++++---- packages/cli/commands/new.ts | 30 ++--- packages/cli/index.ts | 32 +---- packages/cli/schema.json | 5 + packages/cli/services/apps.ts | 69 ++++++++++ packages/cli/services/bootstrap.ts | 86 ------------ packages/cli/stores/config.ts | 1 + packages/cli/test/apps.test.ts | 201 +++++++++++++++++++++++++++++ packages/cli/utils/commander.ts | 11 -- packages/cli/utils/options.ts | 5 + 14 files changed, 384 insertions(+), 198 deletions(-) create mode 100644 .changeset/cli-multi-org.md create mode 100644 packages/cli/services/apps.ts delete mode 100644 packages/cli/services/bootstrap.ts create mode 100644 packages/cli/test/apps.test.ts delete mode 100644 packages/cli/utils/commander.ts diff --git a/.changeset/cli-multi-org.md b/.changeset/cli-multi-org.md new file mode 100644 index 000000000..676681925 --- /dev/null +++ b/.changeset/cli-multi-org.md @@ -0,0 +1,5 @@ +--- +"@reflag/cli": patch +--- + +Fix app discovery for users who belong to multiple organizations. `reflag apps list` shows each app's organization, `reflag init` lets you choose an organization, and existing configs resolve their `appId` without requiring an `orgId`. Use `orgId` or `--org-id` to restrict the CLI to one organization. API keys remain scoped to their app. diff --git a/packages/cli/README.md b/packages/cli/README.md index 09fcbde1b..27772d8e6 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -75,7 +75,8 @@ Here are all the configuration options available in the `reflag.config.json` fil "$schema": "https://unpkg.com/@reflag/cli@latest/schema.json", "baseUrl": "https://app.reflag.com", "apiUrl": "https://app.reflag.com/api", - "appId": "ap123456789", + "appId": "ap123456789012", + "orgId": "or123456789012", "typesOutput": [ { "path": "gen/flags.d.ts", @@ -91,39 +92,35 @@ Here are all the configuration options available in the `reflag.config.json` fil | `baseUrl` | Base URL for Reflag services. | "https://app.reflag.com" | | `apiUrl` | API URL for Reflag services (overrides baseUrl for API calls). | "https://app.reflag.com/api" | | `appId` | Your Reflag application ID. | Required | +| `orgId` | Restrict the CLI to one organization. Find the ID with `reflag apps list`. | Optional | | `typesOutput` | Path(s) where TypeScript types will be generated. Can be a string or an array of objects with `path` and `format` properties. Available formats: `react`, `node`, and `vue`. | "gen/flags.ts" with format "react" | -You can override these settings using command-line options for individual commands. +You can override these settings using command-line options. With a personal login and no `orgId`, the CLI finds your configured `appId` across all organizations you can access. With `orgId` set, the CLI rejects apps outside that organization instead of switching to another one. This setting does not scope remote MCP connections. ## Commands ### `reflag init` -Initialize a new Reflag configuration in your project. This creates a `reflag.config.json` file with your settings and prompts for any required information not provided via options. +Initialize a new `reflag.config.json`. If you can access multiple organizations, the CLI asks you to choose an organization and then an app. Pass `--org-id` to pin an organization in the new config, or `--appId` to choose the app directly. ```bash -npx reflag init [--overwrite] +npx reflag init [--overwrite] [--org-id ] [--appId ] ``` -Options: - -- `--overwrite`: Overwrite existing configuration file if one exists. -- `--app-id `: Set the application ID. -- `--key-format `: Set the key format for flags. +Use `--overwrite` to replace an existing configuration. ### `reflag new [flagName]` All-in-one command to get started quickly. This command combines `init`, flag creation, and type generation in a single step. Use this for the fastest way to get up and running with Reflag. ```bash -npx reflag new "My Flag" [--app-id ap123456789] [--key my-flag] [--key-format custom] [--out gen/flags.ts] [--format react] +npx reflag new "My Flag" [--appId ] [--key my-flag] [--out gen/flags.ts] [--format react] ``` Options: - `--key`: Specific key for the flag. -- `--app-id`: App ID to use. -- `--key-format`: Format for flag keys (custom, snake, camel, etc.). +- `--appId`: App ID to use. - `--out`: Path to generate TypeScript types. - `--format`: Format of the generated types (react, node, or vue). @@ -154,44 +151,47 @@ Manage your Reflag flags with these subcommands: Create a new flag in your Reflag app. The command guides you through the flag creation process with interactive prompts if options are not provided. ```bash -npx reflag flags create "My Flag" [--app-id ap123456789] [--key my-flag] [--key-format custom] +npx reflag flags create "My Flag" [--appId ] [--key my-flag] ``` Options: - `--key`: Specific key for the flag. -- `--app-id`: App ID to use. -- `--key-format`: Format for flag keys. +- `--appId`: App ID to use. The app's organization determines the key format. #### `reflag flags list` List all flags for the current app. This helps you visualize what flags are available and their current configurations. ```bash -npx reflag flags list [--app-id ap123456789] +npx reflag flags list [--appId ] ``` Options: -- `--app-id`: App ID to use. +- `--appId`: App ID to use. #### `reflag flags types` Generate TypeScript types for your flags. This ensures type safety when using Reflag flags in your TypeScript/JavaScript applications. ```bash -npx reflag flags types [--app-id ap123456789] [--out gen/flags.ts] [--format react] +npx reflag flags types [--appId ] [--out gen/flags.ts] [--format react] ``` Options: -- `--app-id`: App ID to use. +- `--appId`: App ID to use. - `--out`: Path to generate TypeScript types. - `--format`: Format of the generated types (react, node, or vue). -### `reflag apps` +### `reflag apps list` + +List available apps with their organization names and IDs. Without an organization filter, a personal login lists apps across all your organizations. An API key still lists only its own app. -Commands for managing Reflag apps. +```bash +npx reflag apps list [--org-id ] +``` ## Global Options @@ -201,6 +201,7 @@ These options can be used with any command: - `--base-url `: Set the base URL for Reflag API. - `--api-url `: Set the API URL directly (overrides base URL). - `--api-key `: Reflag API key for non-interactive authentication. +- `--org-id `: Restrict app discovery and commands to one organization. Overrides `orgId` in `reflag.config.json`. - `--help`: Display help information for a command. ## AI-Assisted Development diff --git a/packages/cli/commands/apps.ts b/packages/cli/commands/apps.ts index 209d77d41..923799375 100644 --- a/packages/cli/commands/apps.ts +++ b/packages/cli/commands/apps.ts @@ -2,7 +2,7 @@ import chalk from "chalk"; import { Command } from "commander"; import ora from "ora"; -import { listApps } from "../services/bootstrap.js"; +import { listApps } from "../services/apps.js"; import { configStore } from "../stores/config.js"; import { handleError } from "../utils/errors.js"; @@ -11,9 +11,18 @@ export const listAppsAction = async () => { const spinner = ora(`Loading apps from ${chalk.cyan(baseUrl)}...`).start(); try { - const apps = listApps(); + const apps = await listApps(); + if (!apps.length) throw new Error("No apps found."); spinner.succeed(`Loaded apps from ${chalk.cyan(baseUrl)}.`); - console.table(apps.map(({ name, id, demo }) => ({ name, id, demo }))); + console.table( + apps.map(({ name, id, org, demo }) => ({ + name, + id, + organization: org.name, + orgId: org.id, + demo, + })), + ); } catch (error) { spinner.fail("Failed to list apps."); handleError(error, "Apps List"); diff --git a/packages/cli/commands/flags.ts b/packages/cli/commands/flags.ts index 5a9a39ec0..12e6bc53d 100644 --- a/packages/cli/commands/flags.ts +++ b/packages/cli/commands/flags.ts @@ -5,7 +5,7 @@ import chalk from "chalk"; import { Command } from "commander"; import ora, { Ora } from "ora"; -import { App, getApp, getOrg } from "../services/bootstrap.js"; +import { App, getApp } from "../services/apps.js"; import { createFlag, listFlags, listFlagValues } from "../services/flags.js"; import { configStore } from "../stores/config.js"; import { @@ -47,7 +47,7 @@ export const createFlagAction = async ( let app: App; try { - app = getApp(appId); + app = await getApp(appId); } catch (error) { handleError(error, "Flags Create"); } @@ -55,9 +55,8 @@ export const createFlagAction = async ( const production = app.environments.find((e) => e.isProduction); try { - const org = getOrg(); console.log( - `Creating flag for app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`, + `Creating flag for app ${chalk.cyan(app.name)} in ${chalk.cyan(app.org.name)}${baseUrlSuffix(baseUrl)}.`, ); if (!name) { @@ -68,7 +67,7 @@ export const createFlagAction = async ( } if (!key) { - const keyFormat = org.featureKeyFormat; + const keyFormat = app.org.featureKeyFormat; const keyValidator = KeyFormatPatterns[keyFormat]; key = await input({ message: "New flag key:", @@ -103,7 +102,7 @@ export const listFlagsAction = async () => { } try { - const app = getApp(appId); + const app = await getApp(appId); const production = app.environments.find((e) => e.isProduction); if (!production) { handleError(new MissingEnvIdError(), "Flags Types"); @@ -146,7 +145,7 @@ export const generateTypesAction = async () => { let app: App; try { - app = getApp(appId); + app = await getApp(appId); } catch (error) { handleError(error, "Flags Types"); } diff --git a/packages/cli/commands/init.ts b/packages/cli/commands/init.ts index 25a7dcfdf..b04464f37 100644 --- a/packages/cli/commands/init.ts +++ b/packages/cli/commands/init.ts @@ -5,54 +5,65 @@ import chalk from "chalk"; import { Command } from "commander"; import ora, { Ora } from "ora"; -import { App, listApps } from "../services/bootstrap.js"; +import { getApp, listOrganizations } from "../services/apps.js"; import { configStore } from "../stores/config.js"; import { DEFAULT_TYPES_OUTPUT, TYPE_FORMATS } from "../utils/constants.js"; import { handleError } from "../utils/errors.js"; -import { overwriteOption } from "../utils/options.js"; +import { appIdOption, overwriteOption } from "../utils/options.js"; type InitArgs = { + appId?: string; overwrite?: boolean; }; -export const initAction = async (args: InitArgs = {}) => { +export const initAction = async ({ + appId: requestedAppId, + overwrite, +}: InitArgs = {}) => { let spinner: Ora | undefined; - let apps: App[] = []; try { // Check if config already exists const configPath = configStore.getConfigPath(); - if (configPath && !args.overwrite) { + if (configPath && !overwrite) { throw new Error( "Reflag is already initialized. Use --overwrite to overwrite.", ); } console.log("\nWelcome to ◪ Reflag!\n"); - const baseUrl = configStore.getConfig("baseUrl"); + spinner = ora("Loading organizations and apps...").start(); + let appId = requestedAppId; + if (appId !== undefined) { + await getApp(appId); + spinner.stop(); + } else { + const orgs = await listOrganizations(); + spinner.stop(); + if (!orgs.length) throw new Error("No accessible organizations found."); - // Load apps - spinner = ora(`Loading apps from ${chalk.cyan(baseUrl)}...`).start(); - apps = listApps(); - spinner.succeed(`Loaded apps from ${chalk.cyan(baseUrl)}.`); - } catch (error) { - spinner?.fail("Loading apps failed."); - handleError(error, "Initialization"); - } + const org = + orgs.length === 1 + ? orgs[0] + : await select({ + message: "Select an organization", + choices: orgs.map((candidate) => ({ + name: `${candidate.name} (${candidate.id})`, + value: candidate, + })), + }); - try { - let appId: string | undefined; - const nonDemoApp = apps.find((app) => !app.demo); + if (!org.apps.length) { + throw new Error( + `No apps found in '${org.name}'. Choose another organization or create an app.`, + ); + } - if (apps.length === 0) { - throw new Error("You don't have any apps yet. Please create one."); - } else { - const longestName = Math.max(...apps.map((app) => app.name.length)); appId = await select({ - message: "Select an app", - default: nonDemoApp?.id, - choices: apps.map((app) => ({ - name: `${app.name.padEnd(longestName, " ")}${app.demo ? " [Demo]" : ""}`, + message: `Select an app in ${org.name}`, + default: org.apps.find((app) => !app.demo)?.id, + choices: org.apps.map((app) => ({ + name: `${app.name}${app.demo ? " [Demo]" : ""} (${app.id})`, value: app.id, })), }); @@ -82,13 +93,13 @@ export const initAction = async (args: InitArgs = {}) => { // Create config file spinner = ora("Creating configuration...").start(); - await configStore.saveConfigFile(args.overwrite); + await configStore.saveConfigFile(overwrite); spinner.succeed( `Configuration created at ${chalk.cyan(relative(process.cwd(), configStore.getConfigPath()!))}.`, ); } catch (error) { - spinner?.fail("Configuration creation failed."); + if (spinner?.isSpinning) spinner.fail(); handleError(error, "Initialization"); } }; @@ -98,5 +109,6 @@ export function registerInitCommand(cli: Command) { .command("init") .description("Initialize a new Reflag configuration.") .addOption(overwriteOption) + .addOption(appIdOption) .action(initAction); } diff --git a/packages/cli/commands/new.ts b/packages/cli/commands/new.ts index 8f2216efc..ed6315e53 100644 --- a/packages/cli/commands/new.ts +++ b/packages/cli/commands/new.ts @@ -1,8 +1,7 @@ import { Command } from "commander"; -import { findUp } from "find-up"; import { configStore } from "../stores/config.js"; -import { CONFIG_FILE_NAME } from "../utils/constants.js"; +import type { TypeFormat } from "../utils/constants.js"; import { appIdOption, flagKeyOption, @@ -15,17 +14,23 @@ import { initAction } from "./init.js"; type NewArgs = { appId?: string; - out: string; + out?: string; + format?: TypeFormat; key?: string; }; -export const newAction = async (name: string | undefined, { key }: NewArgs) => { - if (!(await findUp(CONFIG_FILE_NAME))) { - await initAction(); +export const newAction = async ( + name: string | undefined, + { appId, out, format, key }: NewArgs, +) => { + if (!configStore.getConfigPath()) { + await initAction({ appId }); } - await createFlagAction(name, { - key, + configStore.setConfig({ + appId, + typesOutput: out ? [{ path: out, format: format || "react" }] : undefined, }); + await createFlagAction(name, { key }); await generateTypesAction(); }; @@ -41,13 +46,4 @@ export function registerNewCommand(cli: Command) { .addOption(flagKeyOption) .addArgument(flagNameArgument) .action(newAction); - - // Update the config with the cli override values - cli.hook("preAction", (command) => { - const { appId, out, format } = command.opts(); - configStore.setConfig({ - appId, - typesOutput: out ? [{ path: out, format: format || "react" }] : undefined, - }); - }); } diff --git a/packages/cli/index.ts b/packages/cli/index.ts index 30b2cd593..7cc9d568f 100755 --- a/packages/cli/index.ts +++ b/packages/cli/index.ts @@ -1,7 +1,6 @@ #!/usr/bin/env node import chalk from "chalk"; import { program } from "commander"; -import ora from "ora"; import { registerAppCommands } from "./commands/apps.js"; import { registerAuthCommands } from "./commands/auth.js"; @@ -10,27 +9,24 @@ import { registerInitCommand } from "./commands/init.js"; import { registerMcpCommand } from "./commands/mcp.js"; import { registerNewCommand } from "./commands/new.js"; import { registerRulesCommand } from "./commands/rules.js"; -import { bootstrap, getReflagUser } from "./services/bootstrap.js"; import { authStore } from "./stores/auth.js"; import { configStore } from "./stores/config.js"; -import { commandName } from "./utils/commander.js"; -import { handleError } from "./utils/errors.js"; import { apiKeyOption, apiUrlOption, baseUrlOption, debugOption, + orgIdOption, } from "./utils/options.js"; import { stripTrailingSlash } from "./utils/urls.js"; import { checkLatest as checkLatestVersion } from "./utils/version.js"; -const skipBootstrapCommands = [/^login/, /^logout/, /^rules/]; - type Options = { debug?: boolean; baseUrl?: string; apiUrl?: string; apiKey?: string; + orgId?: string; }; async function main() { @@ -52,14 +48,16 @@ async function main() { program.addOption(baseUrlOption); program.addOption(apiUrlOption); program.addOption(apiKeyOption); + program.addOption(orgIdOption); // Pre-action hook - program.hook("preAction", async (_, actionCommand) => { + program.hook("preAction", async () => { const { debug, baseUrl, apiUrl, apiKey: explicitApiKey, + orgId, } = program.opts(); const cleanedBaseUrl = stripTrailingSlash(baseUrl?.trim()); const cleanedApiUrl = stripTrailingSlash(apiUrl?.trim()); @@ -75,28 +73,12 @@ async function main() { authStore.useApiKey(apiKey); } - // Set baseUrl and apiUrl in config store, will skip if undefined configStore.setConfig({ baseUrl: cleanedBaseUrl, apiUrl: cleanedApiUrl || (cleanedBaseUrl && `${cleanedBaseUrl}/api`), + orgId: orgId?.trim(), }); - // Skip bootstrapping for commands that don't require it - if ( - !skipBootstrapCommands.some((cmd) => cmd.test(commandName(actionCommand))) - ) { - const spinner = ora("Bootstrapping...").start(); - - try { - // Load bootstrap data if not already loaded - await bootstrap(); - spinner.stop(); - } catch (error) { - spinner.fail("Bootstrap failed."); - handleError(error, "Connect"); - } - } - const { latestVersion, currentVersion, isNewerAvailable } = await cliVersionCheckPromise; @@ -110,8 +92,6 @@ async function main() { if (debug) { console.debug(chalk.cyan("\nDebug mode enabled.")); - const user = getReflagUser(); - console.debug(`Logged in as ${chalk.cyan(user.name ?? user.email)}.`); console.debug( "Reading config from:", chalk.cyan(configStore.getConfigPath()), diff --git a/packages/cli/schema.json b/packages/cli/schema.json index e5d816ed6..ea41390b8 100644 --- a/packages/cli/schema.json +++ b/packages/cli/schema.json @@ -19,6 +19,11 @@ "maxLength": 14, "description": "Mandatory ID for the Reflag app. You can find it by calling reflag apps list." }, + "orgId": { + "type": "string", + "minLength": 1, + "description": "Optional organization ID to restrict app discovery and commands. You can find it with reflag apps list." + }, "typesOutput": { "type": "array", "description": "List of paths to output the types. The path is relative to the current working directory.", diff --git a/packages/cli/services/apps.ts b/packages/cli/services/apps.ts new file mode 100644 index 000000000..b58b26647 --- /dev/null +++ b/packages/cli/services/apps.ts @@ -0,0 +1,69 @@ +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { authRequest } from "../utils/auth.js"; +import type { KeyFormat } from "../utils/gen.js"; + +type AppSummary = { + id: string; + name: string; + demo: boolean; + environments: { id: string; name: string; isProduction: boolean }[]; +}; + +type OrgSummary = { + id: string; + name: string; + featureKeyFormat: KeyFormat; +}; + +type Organization = OrgSummary & { apps: AppSummary[] }; +export type App = AppSummary & { org: OrgSummary }; + +let organizations: Promise | undefined; + +async function fetchOrganizations(): Promise { + const { isApiKey } = authStore.getToken(configStore.getConfig("baseUrl")); + if (isApiKey) { + // The membership list is only for personal sign-ins. Bootstrap returns + // just the app associated with this key. + const { org } = await authRequest<{ org: Organization | null }>( + "/bootstrap", + ); + return org ? [org] : []; + } + + const { data } = await authRequest<{ data: Organization[] }>("/orgs"); + return data; +} + +export async function listOrganizations(): Promise { + const orgs = await (organizations ??= fetchOrganizations()); + const orgId = configStore.getConfig("orgId"); + if (orgId === undefined) return orgs; + + const org = orgs.find(({ id }) => id === orgId); + if (!org) { + throw new Error( + `Organization '${orgId}' was not found or is not accessible. Check --org-id or orgId in reflag.config.json.`, + ); + } + return [org]; +} + +export async function listApps(): Promise { + return (await listOrganizations()).flatMap( + ({ id, name, featureKeyFormat, apps }) => + apps.map((app) => ({ ...app, org: { id, name, featureKeyFormat } })), + ); +} + +export async function getApp(id: string): Promise { + const app = (await listApps()).find(({ id: appId }) => appId === id); + if (app) return app; + + const orgId = configStore.getConfig("orgId"); + const scope = orgId === undefined ? "" : ` in organization '${orgId}'`; + throw new Error( + `App '${id}' was not found or is not accessible${scope}. Use \`reflag apps list\` to see available apps.`, + ); +} diff --git a/packages/cli/services/bootstrap.ts b/packages/cli/services/bootstrap.ts deleted file mode 100644 index b1132f2c2..000000000 --- a/packages/cli/services/bootstrap.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { authRequest } from "../utils/auth.js"; -import { KeyFormat } from "../utils/gen.js"; - -export type Environment = { - id: string; - name: string; - isProduction: boolean; - order: number; -}; - -export type App = { - id: string; - name: string; - demo: boolean; - environments: Environment[]; -}; - -export type ReflagUser = { - id: string; - email: string; - name: string; -}; - -export type Org = { - id: string; - name: string; - apps: App[]; - featureKeyFormat: KeyFormat; -}; - -export type BootstrapResponse = { - org: Org; - user: ReflagUser; -}; - -let bootstrapResponse: BootstrapResponse | null = null; - -export async function bootstrap(): Promise { - if (!bootstrapResponse) { - bootstrapResponse = await authRequest(`/bootstrap`); - } - return bootstrapResponse; -} - -export function getOrg(): Org { - if (!bootstrapResponse) { - throw new Error("CLI has not been bootstrapped."); - } - if (!bootstrapResponse.org) { - throw new Error("No organization found."); - } - return bootstrapResponse.org; -} - -export function listApps(): App[] { - if (!bootstrapResponse) { - throw new Error("CLI has not been bootstrapped."); - } - const org = bootstrapResponse.org; - if (!org) { - throw new Error("No organization found."); - } - if (!org.apps?.length) { - throw new Error("No apps found."); - } - return bootstrapResponse.org.apps; -} - -export function getApp(id: string): App { - const apps = listApps(); - const app = apps.find((a) => a.id === id); - if (!app) { - throw new Error(`App with id ${id} not found`); - } - return app; -} - -export function getReflagUser(): ReflagUser { - if (!bootstrapResponse) { - throw new Error("CLI has not been bootstrapped."); - } - if (!bootstrapResponse.user) { - throw new Error("No user found."); - } - return bootstrapResponse.user; -} diff --git a/packages/cli/stores/config.ts b/packages/cli/stores/config.ts index 5a5b03851..295368564 100644 --- a/packages/cli/stores/config.ts +++ b/packages/cli/stores/config.ts @@ -33,6 +33,7 @@ type Config = { baseUrl: string; apiUrl: string; appId: string | undefined; + orgId?: string; typesOutput: TypesOutput[]; }; diff --git a/packages/cli/test/apps.test.ts b/packages/cli/test/apps.test.ts new file mode 100644 index 000000000..1958baef8 --- /dev/null +++ b/packages/cli/test/apps.test.ts @@ -0,0 +1,201 @@ +import { input, select } from "@inquirer/prompts"; +import { beforeEach, expect, it, vi } from "vitest"; + +import { authStore } from "../stores/auth.js"; +import { configStore } from "../stores/config.js"; +import { authRequest } from "../utils/auth.js"; + +vi.mock("../utils/auth.js", () => ({ authRequest: vi.fn() })); +vi.mock("@inquirer/prompts", () => ({ input: vi.fn(), select: vi.fn() })); +vi.mock("../stores/auth.js", () => ({ authStore: { getToken: vi.fn() } })); +vi.mock("../stores/config.js", () => ({ + configStore: { + getConfig: vi.fn(), + getConfigPath: vi.fn(), + setConfig: vi.fn(), + saveConfigFile: vi.fn(), + }, +})); + +const orgs = [ + { + id: "org-1", + name: "First", + featureKeyFormat: "kebabCaseLower", + apps: [app("app-1")], + }, + { + id: "org-2", + name: "Second", + featureKeyFormat: "camelCase", + apps: [app("app-2"), app("app-3")], + }, + { + id: "org-3", + name: "Third", + featureKeyFormat: "kebabCaseLower", + apps: [app("app-4")], + }, +]; + +function app(id: string) { + return { + id, + name: "App", + demo: false, + environments: [ + { id: `${id}-prod`, name: "Production", isProduction: true }, + ], + }; +} + +const request = vi.mocked(authRequest); +const choose = vi.mocked(select); +let orgId: string | undefined; + +beforeEach(() => { + vi.resetModules(); + vi.resetAllMocks(); + orgId = undefined; + vi.mocked(authStore.getToken).mockReturnValue({ + token: "token", + isApiKey: false, + }); + vi.mocked(configStore.getConfig).mockImplementation((key) => + key === "orgId" ? orgId : "https://example.com", + ); + request.mockResolvedValue({ data: orgs }); +}); + +it("discovers apps across memberships and resolves an existing app ID without an org pin", async () => { + const { getApp, listApps } = await import("../services/apps.js"); + + expect( + (await listApps()).map(({ name, id, org }) => [name, id, org.name]), + ).toEqual([ + ["App", "app-1", "First"], + ["App", "app-2", "Second"], + ["App", "app-3", "Second"], + ["App", "app-4", "Third"], + ]); + await expect(getApp("app-2")).resolves.toMatchObject({ + org: { id: "org-2", featureKeyFormat: "camelCase" }, + environments: [{ id: "app-2-prod" }], + }); + expect(request).toHaveBeenCalledExactlyOnceWith("/orgs"); +}); + +it("filters both app discovery and explicit app IDs to the selected org", async () => { + orgId = "org-2"; + const { getApp, listApps } = await import("../services/apps.js"); + + expect((await listApps()).map(({ id }) => id)).toEqual(["app-2", "app-3"]); + await expect(getApp("app-1")).rejects.toThrow("in organization 'org-2'"); +}); + +it("rejects an unknown or inaccessible org without falling back", async () => { + orgId = "unavailable-org"; + const { listApps } = await import("../services/apps.js"); + await expect(listApps()).rejects.toThrow( + "Organization 'unavailable-org' was not found or is not accessible", + ); + expect(request).toHaveBeenCalledExactlyOnceWith("/orgs"); +}); + +it("keeps API keys bound to their original app and organization", async () => { + vi.mocked(authStore.getToken).mockReturnValue({ + token: "token", + isApiKey: true, + }); + request.mockResolvedValue({ org: { ...orgs[1], apps: [orgs[1].apps[1]] } }); + const { getApp, listApps } = await import("../services/apps.js"); + + expect((await listApps()).map(({ id }) => id)).toEqual(["app-3"]); + await expect(getApp("app-2")).rejects.toThrow( + "App 'app-2' was not found or is not accessible", + ); + orgId = "org-1"; + await expect(listApps()).rejects.toThrow( + "Organization 'org-1' was not found or is not accessible", + ); + expect(request).toHaveBeenCalledExactlyOnceWith("/bootstrap"); +}); + +function mockConfigCreation() { + vi.mocked(configStore.saveConfigFile).mockImplementation(async () => { + vi.mocked(configStore.getConfigPath).mockReturnValue("reflag.config.json"); + }); + vi.mocked(input).mockResolvedValue("gen/flags.d.ts"); +} + +it("prompts for an org and then shows only its apps during init", async () => { + mockConfigCreation(); + choose + .mockResolvedValueOnce(orgs[1]) + .mockResolvedValueOnce("app-3") + .mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction(); + + expect(choose).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ + message: "Select an organization", + choices: orgs.map((org) => ({ + name: `${org.name} (${org.id})`, + value: org, + })), + }), + ); + expect(choose).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + message: "Select an app in Second", + choices: [ + { name: "App (app-2)", value: "app-2" }, + { name: "App (app-3)", value: "app-3" }, + ], + }), + ); + expect(configStore.setConfig).toHaveBeenCalledWith({ + appId: "app-3", + typesOutput: [{ path: "gen/flags.d.ts", format: "react" }], + }); +}); + +it.each([false, true])( + "skips the org prompt in a one-org scope (pinned: %s)", + async (pinned) => { + mockConfigCreation(); + if (pinned) orgId = "org-2"; + else request.mockResolvedValue({ data: [orgs[1]] }); + choose.mockResolvedValueOnce("app-2").mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction(); + + expect(choose).toHaveBeenCalledTimes(2); + expect(choose).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ message: "Select an app in Second" }), + ); + }, +); + +it("accepts an explicit app ID at init without either picker", async () => { + mockConfigCreation(); + choose.mockResolvedValueOnce("react"); + const { initAction } = await import("../commands/init.js"); + + await initAction({ appId: "app-4" }); + + expect(choose).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: "What is the output format?", + }), + ); + expect(configStore.setConfig).toHaveBeenCalledWith( + expect.objectContaining({ appId: "app-4" }), + ); +}); diff --git a/packages/cli/utils/commander.ts b/packages/cli/utils/commander.ts deleted file mode 100644 index c4d4dcc43..000000000 --- a/packages/cli/utils/commander.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Command } from "commander"; - -export function commandName(command: Command) { - if (command.parent) { - const parentName = command.parent.name(); - if (parentName && parentName !== "index") { - return `${parentName} ${command.name()}`; - } - } - return command.name(); -} diff --git a/packages/cli/utils/options.ts b/packages/cli/utils/options.ts index b886cf74c..dfe287a21 100644 --- a/packages/cli/utils/options.ts +++ b/packages/cli/utils/options.ts @@ -27,6 +27,11 @@ export const appIdOption = new Option( `Reflag App ID. Falls back to appId value in ${CONFIG_FILE_NAME}.`, ); +export const orgIdOption = new Option( + "--org-id ", + `Restrict CLI app discovery and flag commands to an organization. Overrides orgId in ${CONFIG_FILE_NAME}.`, +); + export const overwriteOption = new Option( "--overwrite", "Force initialization and overwrite existing configuration.",