Skip to content
Draft
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
5 changes: 5 additions & 0 deletions .changeset/registered-defaults-cli-v2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@reflag/cli": major
---

Move the CLI to the v2 management flag API and generate direct-value declarations from current production-environment multivariate variants instead of legacy config wrappers. Add Vue generation, JSON-safe empty-shape inference and property escaping, and update generated coding-agent instructions for the v2 APIs. The CLI update requires compatible management endpoints and SDK v2; SDK v1 applications must retain the CLI 1.x generator.
2 changes: 2 additions & 0 deletions .github/workflows/package-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ jobs:
- id: build
name: Build the project
run: yarn build
- name: Check generated CLI declarations
run: node packages/cli/test/generated-types.mjs
- name: Build docs
run: yarn docs
- id: test
Expand Down
29 changes: 20 additions & 9 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ Command-line interface for interacting with Reflag services. The CLI allows you
flags, authentication, and generate TypeScript types for your Reflag flags. With this tool,
you can streamline your flagging workflow directly from your terminal.

## SDK v2 generation

CLI v2 generates types for the **Node, React, and Vue v2 SDKs**. If you use SDK v1, stay on CLI 1.x for legacy type generation.

`reflag flags types` reads Boolean flag headers and current multivariate variants in the app's production environment. Generated `Flags` entries are direct value types, not `.config.payload` wrappers. Regenerate old declarations when migrating. Formats are `node`, `react`, and `vue`; you can configure multiple outputs.

Registered non-null defaults are checked against the generated value type, including required and nested fields. Singular return types still widen from the supplied default. Bare/`undefined` reads remain Boolean; explicit `null` requests arbitrary JSON. Generated schemas reflect current authored variants and do not add nested runtime validation; regenerate when values change. Unconfigured multivariate flags and empty shapes retain JSON-capable types rather than silently becoming Boolean or `any`.

## Installation

Install the CLI as a development dependency in your project:
Expand Down Expand Up @@ -77,13 +85,13 @@ Here are all the configuration options available in the `reflag.config.json` fil
}
```

| Option | Description | Default |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `$schema` | Autocompletion for the config. `latest` can be replaced with a specific version. | "https://unpkg.com/@reflag/cli@latest/schema.json" |
| `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 |
| `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` and `node`. | "gen/flags.ts" with format "react" |
| Option | Description | Default |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `$schema` | Autocompletion for the config. `latest` can be replaced with a specific version. | "https://unpkg.com/@reflag/cli@latest/schema.json" |
| `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 |
| `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.

Expand Down Expand Up @@ -117,7 +125,7 @@ Options:
- `--app-id`: App ID to use.
- `--key-format`: Format for flag keys (custom, snake, camel, etc.).
- `--out`: Path to generate TypeScript types.
- `--format`: Format of the generated types (react or node).
- `--format`: Format of the generated types (react, node, or vue).

If you prefer more control over each step, you can use the individual commands (`init`, `flags create`, `flags types`) instead.

Expand Down Expand Up @@ -179,7 +187,7 @@ Options:

- `--app-id`: App ID to use.
- `--out`: Path to generate TypeScript types.
- `--format`: Format of the generated types (react or node).
- `--format`: Format of the generated types (react, node, or vue).

### `reflag apps`

Expand Down Expand Up @@ -284,6 +292,9 @@ Example CI workflow:
# Build the CLI
yarn build

# Test generated declarations against the built Node, React, and Vue SDKs
yarn test:generated-types

# Run the CLI locally
yarn reflag [command]

Expand Down
17 changes: 7 additions & 10 deletions packages/cli/commands/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { Command } from "commander";
import ora, { Ora } from "ora";

import { App, getApp, getOrg } from "../services/bootstrap.js";
import { createFlag, Flag, listFlags } from "../services/flags.js";
import { createFlag, listFlags, listFlagValues } from "../services/flags.js";
import { configStore } from "../stores/config.js";
import {
handleError,
MissingAppIdError,
MissingEnvIdError,
} from "../utils/errors.js";
import {
type FlagForTypes,
genFlagKey,
genTypes,
indentLines,
Expand All @@ -27,7 +28,7 @@ import {
typesFormatOption,
typesOutOption,
} from "../utils/options.js";
import { baseUrlSuffix, featureUrl } from "../utils/urls.js";
import { baseUrlSuffix, flagUrl } from "../utils/urls.js";

type CreateFlagOptions = {
key?: string;
Expand Down Expand Up @@ -84,7 +85,7 @@ export const createFlagAction = async (
);
if (production) {
console.log(
indentLines(chalk.magenta(featureUrl(baseUrl, production, flag))),
indentLines(chalk.magenta(flagUrl(baseUrl, production, flag))),
);
}
} catch (error) {
Expand Down Expand Up @@ -134,11 +135,10 @@ export const listFlagsAction = async () => {
};

export const generateTypesAction = async () => {
const { baseUrl, appId } = configStore.getConfig();
const typesOutput = configStore.getConfig("typesOutput");
const { baseUrl, appId, typesOutput } = configStore.getConfig();

let spinner: Ora | undefined;
let flags: Flag[] = [];
let flags: FlagForTypes[];

if (!appId) {
handleError(new MissingAppIdError(), "Flags Types");
Expand All @@ -161,10 +161,7 @@ export const generateTypesAction = async () => {
`Loading flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}...`,
).start();

flags = await listFlags(appId, {
envId: production.id,
includeRemoteConfigs: true,
}).then((res) => res.data);
flags = await listFlagValues(appId, production.id);

spinner.succeed(
`Loaded flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}.`,
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { Command } from "commander";
import ora, { Ora } from "ora";

import { App, listApps } from "../services/bootstrap.js";
import { configStore, typeFormats } from "../stores/config.js";
import { DEFAULT_TYPES_OUTPUT } from "../utils/constants.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";

Expand Down Expand Up @@ -67,7 +67,7 @@ export const initAction = async (args: InitArgs = {}) => {
// Get types output format
const typesFormat = await select({
message: "What is the output format?",
choices: typeFormats.map((format) => ({
choices: TYPE_FORMATS.map((format) => ({
name: format,
value: format,
})),
Expand Down
1 change: 1 addition & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"build": "tsc && shx chmod +x dist/index.js",
"reflag": "yarn build && ./dist/index.js",
"test": "vitest run",
"test:generated-types": "yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build && yarn build && node test/generated-types.mjs",
"test:watch": "vitest",
"test:ci": "yarn test --reporter=default --reporter=junit --outputFile=junit.xml",
"coverage": "vitest run --coverage",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"type": "object",
"properties": {
"path": { "type": "string" },
"format": { "type": "string", "enum": ["react", "node"] }
"format": { "type": "string", "enum": ["react", "node", "vue"] }
},
"required": ["path"]
}
Expand Down
162 changes: 90 additions & 72 deletions packages/cli/services/flags.ts
Original file line number Diff line number Diff line change
@@ -1,94 +1,112 @@
import { z } from "zod";

import { authRequest } from "../utils/auth.js";
import { booleanish, EnvironmentQuerySchema } from "../utils/schemas.js";
import { PaginatedResponse } from "../utils/types.js";
import type { FlagForTypes } from "../utils/gen.js";
import { EnvironmentQuerySchema } from "../utils/schemas.js";

export type Stage = {
id: string;
name: string;
order: number;
};

export type RemoteConfigVariant = {
key?: string;
payload?: any;
};

export type RemoteConfig = {
variants: [
{
variant: RemoteConfigVariant;
},
];
};

export type FlagName = {
id: string;
name: string;
key: string;
};

export type Flag = FlagName & {
description: string | null;
remoteConfigs: RemoteConfig[];
stage: Stage | null;
};

export type FlagsResponse = PaginatedResponse<Flag>;
const FlagSchema = z.object({
id: z.string().min(1),
name: z.string(),
key: z.string().min(1),
flagType: z.enum(["boolean", "multivariate"]),
stage: z.object({ name: z.string() }).optional(),
});
const FlagsResponseSchema = z.object({
data: z.array(FlagSchema),
totalCount: z.number().int().nonnegative(),
});
const MultivariateVersionsSchema = z.object({
flagId: z.string(),
flagType: z.literal("multivariate"),
versions: z.array(
z.object({
environment: z.object({ id: z.string() }),
currentVersion: z.boolean(),
variants: z.record(z.string(), z.json()),
}),
),
});

export const FlagsQuerySchema = EnvironmentQuerySchema.extend({
sortBy: z.string().default("key").describe("Field to sort features by"),
sortOrder: z
.enum(["asc", "desc"])
.default("asc")
.describe("Sort direction (ascending or descending)"),
includeRemoteConfigs: booleanish
.default(false)
.describe("Include remote configuration data"),
sortBy: z
.enum(["key", "name", "stage"])
.default("key")
.describe("Field to sort flags by"),
sortOrder: z.enum(["asc", "desc"]).default("asc").describe("Sort direction"),
}).strict();

export const FlagCreateSchema = z
.object({
name: z
.string()
.min(1, "Flag name is required")
.describe("Name of the flag"),
key: z
.string()
.min(1, "Flag key is required")
.describe("Unique identifier key for the flag"),
description: z
.string()
.optional()
.describe("Optional description of the flag"),
name: z.string().min(1, "Flag name is required"),
key: z.string().min(1, "Flag key is required"),
description: z.string().optional(),
})
.strict();
const flagsPath = (appId: string) => `/apps/${encodeURIComponent(appId)}/flags`;

export type FlagsQuery = z.input<typeof FlagsQuerySchema>;
export type FlagCreate = z.input<typeof FlagCreateSchema>;

export async function listFlags(appId: string, query: FlagsQuery) {
return authRequest<FlagsResponse>(`/apps/${appId}/features`, {
export async function listFlags(
appId: string,
query: z.input<typeof FlagsQuerySchema>,
) {
const response = await authRequest(flagsPath(appId), {
params: FlagsQuerySchema.parse(query),
});
return FlagsResponseSchema.parse(response);
}

type CreateFlagResponse = {
feature: FlagName & {
description: string | null;
};
};
/** Generate schemas from current values in the selected environment, never legacy remote-config wrappers. */
export async function listFlagValues(
appId: string,
envId: string,
): Promise<FlagForTypes[]> {
const { data, totalCount } = await listFlags(appId, { envId });
if (data.length !== totalCount) {
throw new Error("Cannot generate types from an incomplete flag list");
}
const flags: FlagForTypes[] = [];
for (const { id, key, flagType } of data) {
if (flagType === "boolean") {
flags.push({ key, flagType });
continue;
}
const { flagId, versions } = MultivariateVersionsSchema.parse(
await authRequest(
`${flagsPath(appId)}/${encodeURIComponent(id)}/targeting`,
{
params: { envId },
},
),
);
const [version] = versions;
if (
flagId !== id ||
versions.length > 1 ||
(version && (version.environment.id !== envId || !version.currentVersion))
) {
throw new Error(
`Unexpected current-version response for flag ${JSON.stringify(key)}`,
);
}
flags.push({
key,
flagType,
values: Object.values(version?.variants ?? {}),
});
}
return flags;
}

export async function createFlag(appId: string, featureData: FlagCreate) {
return authRequest<CreateFlagResponse>(`/apps/${appId}/features`, {
export async function createFlag(
appId: string,
flag: z.input<typeof FlagCreateSchema>,
) {
const response = await authRequest(flagsPath(appId), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
source: "event",
...FlagCreateSchema.parse(featureData),
flagType: "boolean",
...FlagCreateSchema.parse(flag),
}),
}).then(({ feature }) => feature);
});
return z.object({ flag: FlagSchema }).parse(response).flag;
}
Loading
Loading