diff --git a/.changeset/registered-defaults-cli-v2.md b/.changeset/registered-defaults-cli-v2.md new file mode 100644 index 000000000..d71000c22 --- /dev/null +++ b/.changeset/registered-defaults-cli-v2.md @@ -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. diff --git a/.github/workflows/package-ci.yml b/.github/workflows/package-ci.yml index 5b9a2565f..812ad81e4 100644 --- a/.github/workflows/package-ci.yml +++ b/.github/workflows/package-ci.yml @@ -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 - name: Test documentation publication boundaries diff --git a/packages/cli/README.md b/packages/cli/README.md index 331eead9c..09fcbde1b 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -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: @@ -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. @@ -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. @@ -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` @@ -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] diff --git a/packages/cli/commands/flags.ts b/packages/cli/commands/flags.ts index 27384a6af..5a9a39ec0 100644 --- a/packages/cli/commands/flags.ts +++ b/packages/cli/commands/flags.ts @@ -6,7 +6,7 @@ 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, @@ -14,6 +14,7 @@ import { MissingEnvIdError, } from "../utils/errors.js"; import { + type FlagForTypes, genFlagKey, genTypes, indentLines, @@ -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; @@ -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) { @@ -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"); @@ -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)}.`, diff --git a/packages/cli/commands/init.ts b/packages/cli/commands/init.ts index 053dd79f1..25a7dcfdf 100644 --- a/packages/cli/commands/init.ts +++ b/packages/cli/commands/init.ts @@ -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"; @@ -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, })), diff --git a/packages/cli/package.json b/packages/cli/package.json index 00464bb45..0ace12148 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -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", diff --git a/packages/cli/schema.json b/packages/cli/schema.json index e3e2e2d46..e5d816ed6 100644 --- a/packages/cli/schema.json +++ b/packages/cli/schema.json @@ -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"] } diff --git a/packages/cli/services/flags.ts b/packages/cli/services/flags.ts index b23a80019..519fe18b3 100644 --- a/packages/cli/services/flags.ts +++ b/packages/cli/services/flags.ts @@ -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; +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; -export type FlagCreate = z.input; - -export async function listFlags(appId: string, query: FlagsQuery) { - return authRequest(`/apps/${appId}/features`, { +export async function listFlags( + appId: string, + query: z.input, +) { + 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 { + 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(`/apps/${appId}/features`, { +export async function createFlag( + appId: string, + flag: z.input, +) { + 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; } diff --git a/packages/cli/services/rules.ts b/packages/cli/services/rules.ts index 919bb30f5..3416da980 100644 --- a/packages/cli/services/rules.ts +++ b/packages/cli/services/rules.ts @@ -1,8 +1,8 @@ export function getCursorRules() { return ` --- -description: Guidelines for implementing flagging using Reflag feature management service -globs: "**/*.ts, **/*.tsx, **/*.js, **/*.jsx" +description: Guidelines for Reflag SDK v2 direct-value flags +globs: "**/*.ts, **/*.tsx, **/*.js, **/*.jsx, **/*.vue" --- ${rules} @@ -14,289 +14,78 @@ export function getCopilotInstructions() { } const rules = /* markdown */ ` -# Reflag Flag Management Service for LLMs +# Reflag SDK v2 -Reflag is a comprehensive feature management service offering flags, user feedback collection, adoption tracking, and remote configuration for your applications across various JavaScript frameworks, particularly React, Next.js, Node.js, vanilla browser, CLI, and OpenFeature environments. Follow these best practices for flagging. +These instructions apply to Node, Browser, React, and Vue SDK v2. Native and OpenFeature integrations may still use SDK v1; do not mix their declarations or bootstrap formats with v2. -## Follow Official Documentation +## Direct-value reads -- Refer to [Reflag's official documentation](mdc:https:/docs.reflag.com) for implementation details. -- Adhere to Reflag's recommended patterns for each framework. +- Singular reads return the selected JSON value, not a flag wrapper. Do not use flag .isEnabled, .config.payload, .value, .track(), or feedback methods. Vue's .value is the normal ref API, not a flag wrapper. +- A read without a default requests Boolean with implicit false, even when generated types register a JSON flag. Generated types do not change runtime read categories. +- For other values, pass a JSON default immediately after the key. It selects the top-level category and supplies missing/mismatched-value fallback behavior. +- Non-null defaults must match the registered value schema, if types are generated. Without registration, return types are inferred from the default. Literal values widen, and readonly defaults produce mutable results. +- Explicit null requests arbitrary JSON and returns FlagValue; narrow or validate it before using object properties. It is not a request for a null-only value. +- Preserve authored false, zero, empty strings, empty arrays, and null. Do not substitute defaults with truthiness checks. +- Defaults must be ordinary JSON: no functions, Dates, undefined, or cycles. Objects and arrays returned by the SDK are independent mutable copies. +- Runtime category checks are not nested schema validation. Generated declarations are a snapshot inferred from authored variants; regenerate when flags change and validate externally when stronger runtime guarantees are needed. -## Reflag SDK Usage +## Generated declarations -- Configure \`ReflagProvider\` or \`ReflagClient\` properly at application entry points. -- Leverage Reflag CLI for generating type-safe feature definitions. -- Write clean, type-safe code when applying Reflag flags. -- Follow established patterns in the project. +Use reflag flags types after configuring the project. This CLI targets SDK v2 and loads the current production-environment variants through the management flag API. It does not generate legacy remote-config wrappers. -## Flag Implementation - -- Create reusable hooks and utilities for consistent feature management. -- Write clear comments for usage and checks of a flag. -- Properly handle feature loading states to prevent UI flashing. -- Implement proper error fallbacks when flag services are unavailable. - -## Flag Targeting - -- Use release stages to manage feature rollout (for example, development, staging, production). -- Use targeting modes effectively: - - \`none\`: Flag is disabled for all targets. - - \`some\`: Flag is enabled only for specified targets. - - \`everyone\`: Flag is enabled for all targets. -- Target features to specific users, companies, or segments. - -## Analytics and Feedback - -- Track feature usage with Reflag analytics. -- Collect user feedback on features. -- Monitor feature adoption and health. - -## Common Concepts - -### Targeting Rules - -Targeting rules are entities used in Reflag to describe the target audience of a given feature. The target audience refers to the users who can interact with the feature within your application. Additionally, each targeting rule contains a value that is used for the target audience. - -### Flag Stages - -Release stages in Reflag allow setting up app-wide feature access targeting rules. Each release stage defines targeting rules for each available environment. Later, during the development of new features, you can apply all those rules automatically by selecting an available release stage. - -Release stages are useful tools when a standard release workflow is used in your organization. - -Predefined stages: - -- In development -- Internal -- Beta -- General Availability - -### Segments - -A segment entity in Reflag is a dynamic collection of companies. Segments' dynamic nature results from the fact that they use filters to evaluate which companies are included in them. - -#### Segment filters can be constructed using any combination of the following rules: - -- company attributes -- user feature access -- feature metrics -- other segments - -### Integrations - -Connect Reflag with your existing tools: - -- Linear -- Datadog -- Segment -- PostHog -- Amplitude -- Mixpanel -- AWS S3 -- Slack - -## React SDK Implementation - -### Installation - -\`\`\`bash -npm i @reflag/react-sdk -\`\`\` - -### Key Features - -- Flag toggling with fine-grained targeting -- User feedback collection -- Flag usage tracking -- Remote configuration -- Type-safe feature management - -### Basic Setup - -1. Add the \`ReflagProvider\` to wrap your application: - -\`\`\`jsx -import { ReflagProvider } from "@reflag/react-sdk"; - - - -; -\`\`\` - -1. Create a feature and generate type-safe definitions: - -\`\`\`bash -npm i --save-dev @reflag/cli -npx reflag new "Flag name" -\`\`\` +Example generated shape: \`\`\`typescript -// DO NOT EDIT THIS FILE. IT IS GENERATED BY THE BUCKET CLI AND WILL BE OVERWRITTEN. -// eslint-disable -// prettier-ignore import "@reflag/react-sdk"; - declare module "@reflag/react-sdk" { - export interface Flags { - "flag-key": { - config: { - payload: { - tokens: number; - }; - }; - }; + interface Flags { + huddles: boolean; + "huddle-settings": { tokens: number; model: string }; } } \`\`\` -1. Use features in your components: - -\`\`\`jsx -import { useFlag } from "@reflag/react-sdk"; +## React -function StartHuddleButton() { - const { - isLoading, // true while features are being loaded - isEnabled, // boolean indicating if the feature is enabled - config: { - // feature configuration - key, // string identifier for the config variant - payload, // type-safe configuration object - }, - track, // function to track feature usage - requestFeedback, // function to request feedback for this feature - } = useFlag("huddle"); +Configure ReflagProvider with the publishable key and appropriate user/company context. Never expose a secret key in browser code. - if (isLoading) { - return ; - } - - if (!isEnabled) { - return null; - } +\`\`\`tsx +import { useFlag } from "@reflag/react-sdk"; - return ( - <> - - - - ); +function HuddleButton() { + const enabled = useFlag("huddles"); + const settings = useFlag("huddle-settings", { tokens: 128, model: "quick" }); + if (!enabled) return null; + return ; } \`\`\` -### Core React Hooks +useFlag is non-suspending. Use useFlagSuspense explicitly inside a React Suspense boundary when initialization must complete before reading. Use separate useTrack and feedback hooks rather than methods on flag results. -- \`useFlag()\` - Access feature status, config, and tracking -- \`useTrack()\` - Send custom events to Reflag -- \`useRequestFeedback()\` - Open feedback dialog for a feature -- \`useSendFeedback()\` - Programmatically send feedback -- \`useUpdateUser()\` / \`useUpdateCompany()\` - Update user/company data -- \`useUpdateOtherContext()\` - Update session-only context data -- \`useClient()\` - Access the underlying Reflag client +## Node -## Node.js SDK Implementation - -### Installation - -\`\`\`bash -npm i @reflag/node-sdk -\`\`\` +Initialize the client, then supply context directly or bind a context-specific client. Defaults are the third argument to an unbound getFlag and the second argument to bound or remote getters. -### Key Features - -- Server-side flag evaluation -- User and company context management -- Flexible integration options -- Event tracking - -### Basic Setup - -\`\`\`javascript +\`\`\`typescript import { ReflagClient } from "@reflag/node-sdk"; -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, -}); - -// Check if a feature is enabled -const isEnabled = await client.isEnabled("flag-key", { - user: { id: "user_123", role: "admin" }, - company: { id: "company_456", plan: "enterprise" }, -}); -\`\`\` - -### Context Management - -\`\`\`javascript -// Set user and company context -await client.setContext({ - user: { - id: "user_123", - email: "user@example.com", - role: "admin", - }, - company: { - id: "company_456", - name: "Acme Inc", - plan: "enterprise", - }, -}); - -// Check feature after setting context -const isEnabled = await client.isEnabled("flag-key"); +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY! }); +await client.initialize(); +const context = { user: { id: "user_123" }, company: { id: "company_456" } }; +const enabled = client.getFlag(context, "huddles"); +const bound = client.bindClient(context); +const settings = bound.getFlag("huddle-settings", { tokens: 128, model: "quick" }); \`\`\` -### Flag Configuration +Use getFlagRemote for explicit remote evaluation. getFlags returns a record of values that may be undefined; reading a complete record is not a replacement for choosing a singular read's category/default. -\`\`\`javascript -// Get feature configuration -const config = await client.getConfig("flag-key", { - user: { id: "user_123" }, - company: { id: "company_456" }, -}); - -// Use the configuration -console.log(config.payload.maxDuration); -\`\`\` +## Vue and Browser -### Event Tracking - -\`\`\`javascript -// Track feature usage -await client.track("flag-key", { - user: { id: "user_123" }, - company: { id: "company_456" }, - metadata: { action: "completed" }, -}); - -// Track custom events -await client.trackEvent("custom-event", { - user: { id: "user_123" }, - company: { id: "company_456" }, - metadata: { value: 42 }, -}); -\`\`\` +Vue useFlag has the same default rules and returns a ref; access settings.value.model for an object-valued ref. Browser client.getFlag(key, defaultValue) returns a direct value, not a ref or wrapper. -## Further Resources +## Further resources -- [Official Documentation](mdc:https:/docs.reflag.com) -- [Docs llms.txt](mdc:https:/docs.reflag.com/llms.txt) -- [GitHub Repository](mdc:https:/github.com/reflagcom/javascript) -- [Example React App](mdc:https:/github.com/reflagcom/javascript/tree/main/packages/react-sdk/dev) +- [Documentation](https://docs.reflag.com) +- [Repository](https://github.com/reflagcom/javascript) +- Prefer the installed package README and declarations for the exact SDK version in use. `.trim(); diff --git a/packages/cli/stores/config.ts b/packages/cli/stores/config.ts index 73892e1c8..5a5b03851 100644 --- a/packages/cli/stores/config.ts +++ b/packages/cli/stores/config.ts @@ -17,14 +17,12 @@ import { DEFAULT_TYPES_OUTPUT, MODULE_ROOT, SCHEMA_URL, + type TypeFormat, } from "../utils/constants.js"; import { ConfigValidationError, handleError } from "../utils/errors.js"; import { stripTrailingSlash } from "../utils/urls.js"; import { current as currentVersion } from "../utils/version.js"; -export const typeFormats = ["react", "node"] as const; -export type TypeFormat = (typeof typeFormats)[number]; - export type TypesOutput = { path: string; format: TypeFormat; diff --git a/packages/cli/test/flags.test.ts b/packages/cli/test/flags.test.ts new file mode 100644 index 000000000..c20ae6b39 --- /dev/null +++ b/packages/cli/test/flags.test.ts @@ -0,0 +1,174 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { createFlag, listFlags, listFlagValues } from "../services/flags.js"; +import { authRequest } from "../utils/auth.js"; + +vi.mock("../utils/auth.js", () => ({ authRequest: vi.fn() })); +const request = vi.mocked(authRequest); +const enabled = { + id: "enabled-id", + key: "enabled", + name: "Enabled", + flagType: "boolean", +}; +const settings = { + id: "settings-id", + key: "settings", + name: "Settings", + flagType: "multivariate", +}; +function list(data: unknown[] = [enabled, settings]) { + return { + data, + totalCount: data.length, + pageIndex: 0, + pageSize: data.length, + sortBy: "key", + sortOrder: "asc", + }; +} +function version( + variants: Record, + overrides: Record = {}, +) { + return { + flagId: "settings-id", + flagType: "multivariate", + versions: [ + { + environment: { id: "production" }, + currentVersion: true, + variants, + ...overrides, + }, + ], + }; +} + +beforeEach(() => request.mockReset()); + +describe("v2 flag services", () => { + it("lists both Boolean and multivariate flags from the canonical management API", async () => { + request.mockResolvedValueOnce(list()); + expect((await listFlags("app", { envId: "production" })).data).toEqual([ + enabled, + settings, + ]); + expect(request).toHaveBeenCalledWith("/apps/app/flags", { + params: { envId: "production", sortBy: "key", sortOrder: "asc" }, + }); + }); + + it("fetches current direct values only for multivariate flags in the selected environment", async () => { + const values = { + object: { model: "quality" }, + null: null, + false: false, + zero: 0, + empty: "", + array: [], + }; + request + .mockResolvedValueOnce(list()) + .mockResolvedValueOnce(version(values)); + const result = await listFlagValues("app", "production"); + expect(result).toEqual([ + { key: "enabled", flagType: "boolean" }, + { + key: "settings", + flagType: "multivariate", + values: Object.values(values), + }, + ]); + expect(request).toHaveBeenNthCalledWith( + 2, + "/apps/app/flags/settings-id/targeting", + { params: { envId: "production" } }, + ); + expect(request).toHaveBeenCalledTimes(2); + }); + + it("preserves a missing current version as unknown multivariate data, not Boolean", async () => { + request.mockResolvedValueOnce(list([settings])).mockResolvedValueOnce({ + flagId: "settings-id", + flagType: "multivariate", + versions: [], + }); + expect(await listFlagValues("app", "production")).toEqual([ + { key: "settings", flagType: "multivariate", values: [] }, + ]); + }); + + it.each([ + version({ current: 3 }, { environment: { id: "staging" } }), + version({ old: 3 }, { currentVersion: false }), + { ...version({ current: 3 }), flagId: "another-flag" }, + { + ...version({ current: 3 }), + versions: [ + ...version({ current: 3 }).versions, + ...version({ other: 4 }).versions, + ], + }, + ])( + "rejects unexpected flag/environment/version identities", + async (response) => { + request + .mockResolvedValueOnce(list([settings])) + .mockResolvedValueOnce(response); + await expect(listFlagValues("app", "production")).rejects.toThrow( + "Unexpected current-version response", + ); + }, + ); + + it("rejects incomplete lists rather than silently generating a partial registry", async () => { + request.mockResolvedValueOnce({ ...list(), totalCount: 3 }); + await expect(listFlagValues("app", "production")).rejects.toThrow( + "incomplete flag list", + ); + expect(request).toHaveBeenCalledTimes(1); + }); + + it("propagates fetch failures without fabricating a Boolean schema", async () => { + request + .mockResolvedValueOnce(list([settings])) + .mockRejectedValueOnce(new Error("Service unavailable")); + await expect(listFlagValues("app", "production")).rejects.toThrow( + "Service unavailable", + ); + }); + + it("rejects legacy remote-config variant wrappers", async () => { + request.mockResolvedValueOnce(list([settings])).mockResolvedValueOnce({ + flagId: "settings-id", + flagType: "multivariate", + versions: [ + { + environment: { id: "production" }, + currentVersion: true, + variants: [{ variant: { payload: { model: "quality" } } }], + }, + ], + }); + await expect(listFlagValues("app", "production")).rejects.toThrow(); + }); + + it("creates Boolean flags through the v2 management endpoint", async () => { + request.mockResolvedValueOnce({ flag: enabled }); + expect( + await createFlag("app", { key: "enabled", name: "Enabled" }), + ).toEqual(enabled); + expect(request).toHaveBeenCalledWith("/apps/app/flags", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: expect.any(String), + }); + expect(JSON.parse(request.mock.calls[0][1]!.body as string)).toEqual({ + source: "event", + flagType: "boolean", + key: "enabled", + name: "Enabled", + }); + }); +}); diff --git a/packages/cli/test/gen.test.ts b/packages/cli/test/gen.test.ts new file mode 100644 index 000000000..dac6b198a --- /dev/null +++ b/packages/cli/test/gen.test.ts @@ -0,0 +1,107 @@ +import ts from "typescript"; +import { describe, expect, it } from "vitest"; + +import { genTypes, type FlagForTypes } from "../utils/gen.js"; +import type { JSONValue } from "../utils/json.js"; + +function flag(key: string, values?: JSONValue[]): FlagForTypes { + return values === undefined + ? { key, flagType: "boolean" } + : { key, flagType: "multivariate", values }; +} +function properties(source: string) { + const diagnostics = + ts.transpileModule(source, { + fileName: "generated.ts", + reportDiagnostics: true, + }).diagnostics ?? []; + expect(diagnostics).toEqual([]); + const file = ts.createSourceFile( + "generated.ts", + source, + ts.ScriptTarget.Latest, + true, + ); + const module = file.statements.find(ts.isModuleDeclaration)!; + if (!module.body || !ts.isModuleBlock(module.body)) + throw new Error("Expected an SDK module augmentation"); + const flags = module.body.statements.find(ts.isInterfaceDeclaration)!; + return new Map( + flags.members + .filter(ts.isPropertySignature) + .map((property) => [ + ts.isStringLiteral(property.name) + ? property.name.text + : property.name.getText(file), + property.type!.getText(file), + ]), + ); +} + +describe("SDK v2 generation", () => { + it.each(["node", "react", "vue"] as const)( + "emits direct-value %s declarations", + (format) => { + const output = genTypes( + [ + flag("enabled"), + flag("settings", [ + { model: "quick", prompt: { tone: "concise" }, maxTokens: 0 }, + { model: "quality", prompt: { tone: "detailed" }, maxTokens: 2048 }, + ]), + flag("label", ["", "Express"]), + flag("days", [0, 3]), + flag("methods", [[], ["standard"]]), + flag("nullable", [null, { label: "Ready" }]), + flag("false-value", [false]), + ], + format, + ); + expect(output).toContain(`declare module "@reflag/${format}-sdk"`); + const types = properties(output); + expect(types.get("enabled")).toBe("boolean"); + expect(types.get("settings")).toContain("model: string"); + expect(types.get("settings")).toContain("maxTokens: number"); + expect(types.get("settings")).not.toContain("config:"); + expect(types.get("label")).toBe("string"); + expect(types.get("days")).toBe("number"); + expect(types.get("methods")).toBe("(string)[]"); + expect(types.get("nullable")).toContain("null"); + expect(types.get("nullable")).toContain("label: string"); + expect(types.get("false-value")).toBe("boolean"); + expect(output).not.toContain("ConfigPayload"); + }, + ); + + it("uses SDK JSON values rather than any or Boolean for unknown multivariate shapes", () => { + const types = properties( + genTypes([flag("draft", []), flag("array", [[]]), flag("object", [{}])]), + ); + expect(types.get("draft")).toBe('import("@reflag/react-sdk").FlagValue'); + expect(types.get("array")).toBe( + '(import("@reflag/react-sdk").FlagValue)[]', + ); + expect(types.get("object")).toBe( + 'Record', + ); + }); + + it("escapes arbitrary property names and preserves ordinary config/payload data", () => { + const key = 'quotes"\\line\n'; + const types = properties( + genTypes([ + flag(key, [{ [key]: 3, config: { payload: "ordinary data" } }]), + ]), + ); + expect(types.has(key)).toBe(true); + expect(types.get(key)).toContain("config: {"); + expect(types.get(key)).toContain("payload: string"); + expect(types.get(key)).toContain(`${JSON.stringify(key)}: number`); + }); + + it("rejects duplicate flag keys", () => { + expect(() => genTypes([flag("same"), flag("same", [3])])).toThrow( + "Duplicate flag key", + ); + }); +}); diff --git a/packages/cli/test/generated-types.mjs b/packages/cli/test/generated-types.mjs new file mode 100644 index 000000000..85d632982 --- /dev/null +++ b/packages/cli/test/generated-types.mjs @@ -0,0 +1,155 @@ +import { + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, + readFileSync, +} from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +const root = fileURLToPath(new URL("../../../", import.meta.url)); +const temporary = mkdtempSync(join(tmpdir(), "reflag-generated-types-")); +const require = createRequire(join(root, "package.json")); +const ts = require("typescript"); +const { genTypes } = await import(join(root, "packages/cli/dist/utils/gen.js")); +const fixtures = [ + { key: "enabled", flagType: "boolean" }, + { + key: "settings", + flagType: "multivariate", + values: [ + { + model: "quick", + prompt: { tone: "concise" }, + methods: ["standard"], + maxTokens: 512, + }, + { + model: "quality", + prompt: { tone: "detailed" }, + methods: [], + maxTokens: 0, + }, + ], + }, + { key: "days", flagType: "multivariate", values: [0, 3] }, + { key: "label", flagType: "multivariate", values: ["", "Express"] }, + { key: "methods", flagType: "multivariate", values: [[], ["standard"]] }, + { + key: "nullable", + flagType: "multivariate", + values: [null, { tokens: 128 }], + }, + { key: "draft", flagType: "multivariate", values: [] }, + { key: "empty", flagType: "multivariate", values: [{}] }, +]; +const paths = {}; +for (const sdk of ["node", "react", "vue", "browser"]) { + const dir = join(root, `packages/${sdk}-sdk`); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + paths[`@reflag/${sdk}-sdk`] = [join(dir, pkg.types)]; +} +const results = []; +for (const format of ["node", "react", "vue"]) { + const dir = join(temporary, format); + mkdirSync(dir, { recursive: true }); + const gen = join(dir, "flags.d.ts"); + writeFileSync(gen, genTypes(fixtures, format)); + const call = (args) => + `${format === "node" ? "bound.getFlag" : "useFlag"}(${args})`; + const setup = + format === "node" + ? `import { ReflagClient, type FlagValue } from '@reflag/node-sdk'; + declare const client:ReflagClient;const bound=client.bindClient({});` + : `import { useFlag, type FlagValue ${format === "react" ? ", useFlagSuspense" : ""} } from '@reflag/${format}-sdk';`; + const value = format === "vue" ? ".value" : ""; + const contents = `${setup} + interface Prompt {tone:string;} + interface Settings {model:string;prompt:Prompt;methods:string[];maxTokens:number;} + const fallback:Settings={model:'quick',prompt:{tone:'concise'},methods:['standard'],maxTokens:512}; + const result=${call('"settings",fallback')}; + result${value}.model='quality';result${value}.prompt.tone='detailed';result${value}.methods.push('express'); + const frozen=${call('"settings",{model:"quick",prompt:{tone:"concise"},methods:["standard"],maxTokens:512} as const')}; + frozen${value}.model='quality';frozen${value}.methods.push('express'); + const bare:boolean=${call('"settings"')}${value}; + const explicitUndefined:boolean=${call('"settings",undefined')}${value}; + const raw:FlagValue=${call('"settings",null')}${value}; + const nullable:FlagValue=${call('"nullable",null')}${value}; + const days:number=${call('"days",0')}${value}; + const methods:string[]=${call('"methods",[] as string[]')}${value}; + const draft=${call('"draft",{model:"quick"}')}; + const empty=${call('"empty",{model:"quick"}')}; + // @ts-expect-error unknown keys reject + ${call('"missing",false')}; + // @ts-expect-error wrong top-level category rejects, even with a numeric flag elsewhere + ${call('"settings",3')}; + // @ts-expect-error incomplete defaults reject + ${call('"settings",{model:"quick"}')}; + // @ts-expect-error wrong nested properties reject + ${call('"settings",{...fallback,prompt:{tone:3}}')}; + // @ts-expect-error array elements reject + ${call('"methods",[123]')}; + // @ts-expect-error scalar category rejects + ${call('"label",123')}; + // @ts-expect-error old wrappers reject + result${value}.config.payload; + ${ + format === "node" + ? ` + const remote:Promise=client.getFlagRemote('settings',fallback); + const boundRemote:Promise=bound.getFlagRemote('settings',fallback); + // @ts-expect-error root reads check schemas + client.getFlag({},'settings',123); + // @ts-expect-error remote reads check schemas + client.getFlagRemote('settings',123); + ` + : format === "react" + ? ` + const ready:Settings=useFlagSuspense('settings',fallback); + // @ts-expect-error Suspense reads check schemas + useFlagSuspense('settings',123); + ` + : "" + } + `; + const consumer = join(dir, "consumer.mts"); + writeFileSync(consumer, contents); + const options = { + strict: true, + noEmit: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + jsx: ts.JsxEmit.ReactJSX, + baseUrl: root, + paths, + }; + const program = ts.createProgram([gen, consumer], options); + const diagnostics = ts.getPreEmitDiagnostics(program); + results.push({ + format, + diagnostics: diagnostics.map((d) => ({ + code: d.code, + file: d.file?.fileName, + line: + d.file && d.start !== undefined + ? d.file.getLineAndCharacterOfPosition(d.start).line + 1 + : undefined, + message: ts.flattenDiagnosticMessageText(d.messageText, "\n"), + })), + }); +} +rmSync(temporary, { recursive: true, force: true }); +for (const result of results) { + if (result.diagnostics.length) { + console.error(JSON.stringify(result, null, 2)); + process.exitCode = 1; + } else { + console.log( + `${result.format}: generated declarations and registered-default checks passed`, + ); + } +} diff --git a/packages/cli/test/json.test.ts b/packages/cli/test/json.test.ts index 600f3ae09..537aedc48 100644 --- a/packages/cli/test/json.test.ts +++ b/packages/cli/test/json.test.ts @@ -26,7 +26,7 @@ describe("JSON utilities", () => { expect(toTypeAST([])).toEqual({ kind: "array", - elementType: { kind: "primitive", type: "any" }, + elementType: { kind: "primitive", type: "never" }, }); }); @@ -132,7 +132,7 @@ describe("JSON utilities", () => { describe("mergeTypeASTs", () => { it("should handle empty array", () => { - expect(mergeTypeASTs([])).toEqual({ kind: "primitive", type: "any" }); + expect(mergeTypeASTs([])).toEqual({ kind: "primitive", type: "never" }); }); it("should return the same AST for single item arrays", () => { @@ -298,7 +298,9 @@ describe("JSON utilities", () => { }); it("should stringify empty objects", () => { - expect(stringifyTypeAST({ kind: "object", properties: [] })).toBe("{}"); + expect(stringifyTypeAST({ kind: "object", properties: [] })).toBe( + "Record", + ); }); it("should quote object keys with special characters", () => { @@ -390,6 +392,28 @@ describe("JSON utilities", () => { }); describe("JSONToType", () => { + it("does not let empty arrays erase known element types", () => { + expect(JSONToType([[], ["standard"]])).toBe("(string)[]"); + expect(JSONToType([[[]], [[1]]])).toBe("((number)[])[]"); + expect(JSONToType([[]], "JsonValue")).toBe("(JsonValue)[]"); + expect(JSONToType([{}], "JsonValue")).toBe("Record"); + }); + + it("uses the same merge rules even when variants contain different kinds", () => { + expect(JSONToType([null, [], [1], "", "ready"])).toBe( + "null | string | (number)[]", + ); + expect(JSONToType([null, { a: 1 }, { b: 2 }])).toBe( + "null | {\n a?: number,\n b?: number\n}", + ); + }); + + it("preserves already-optional properties across nested array merges", () => { + expect(JSONToType([[{ a: 1 }, { b: 2 }], [{ a: 3, b: 4 }]])).toBe( + "({\n a?: number,\n b?: number\n})[]", + ); + }); + it("should handle empty arrays", () => { expect(JSONToType([])).toBeNull(); }); @@ -401,7 +425,7 @@ describe("JSON utilities", () => { }); it("should handle arrays with simple mixed element types", () => { - const expected = "(number | string | boolean)[]"; + const expected = "(string | boolean | number)[]"; expect(JSONToType([["a", true], [1]])).toBe(expected); }); @@ -417,7 +441,7 @@ describe("JSON utilities", () => { }); it("should merge arrays with nested arrays of mixed element types", () => { - const expected = "((boolean | number | string | {\n id: number\n})[])[]"; + const expected = "((number | string | boolean | {\n id: number\n})[])[]"; expect(JSONToType([[[1, "test"], [true]], [[{ id: 1 }]]])).toBe(expected); }); @@ -462,6 +486,9 @@ describe("JSON utilities", () => { expect(quoteKey("my.key")).toBe('"my.key"'); expect(quoteKey("123key")).toBe('"123key"'); expect(quoteKey("key")).toBe("key"); + expect(quoteKey("")).toBe('""'); + expect(quoteKey('a"b\\c\n')).toBe(JSON.stringify('a"b\\c\n')); + expect(quoteKey("$key")).toBe("$key"); }); }); }); diff --git a/packages/cli/test/rules.test.ts b/packages/cli/test/rules.test.ts new file mode 100644 index 000000000..856ca3f0c --- /dev/null +++ b/packages/cli/test/rules.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; + +import { getCopilotInstructions, getCursorRules } from "../services/rules.js"; +import { flagUrl } from "../utils/urls.js"; + +describe("v2 workflow helpers", () => { + it("ships matching direct-value guidance for supported coding-agent formats", () => { + const rules = getCopilotInstructions(); + expect(getCursorRules()).toContain(rules); + expect(rules).toContain( + 'useFlag("huddle-settings", { tokens: 128, model: "quick" })', + ); + expect(rules).toContain('client.getFlag(context, "huddles")'); + expect(rules).toContain("reflag flags types"); + expect(rules).toContain("not nested schema validation"); + expect(rules).not.toMatch( + /client\.(isEnabled|getConfig|setContext|trackEvent)\(/, + ); + }); + + it("links by escaped flag key rather than confusing Flag and legacy Feature IDs", () => { + const key = 'some/key " with spaces'; + expect( + flagUrl( + "https://example.invalid", + { id: "env-id", name: "Production" }, + { key }, + ), + ).toBe( + `https://example.invalid/envs/production-env-id/flags/by-key/${encodeURIComponent(key)}`, + ); + }); +}); diff --git a/packages/cli/test/schemas.test.ts b/packages/cli/test/schemas.test.ts index 7a72d7238..0cdbf6353 100644 --- a/packages/cli/test/schemas.test.ts +++ b/packages/cli/test/schemas.test.ts @@ -20,7 +20,6 @@ describe("CLI schemas", () => { envId: "env_test", sortBy: "key", sortOrder: "asc", - includeRemoteConfigs: false, }); }); diff --git a/packages/cli/utils/constants.ts b/packages/cli/utils/constants.ts index a8fadc22e..48cdd082b 100644 --- a/packages/cli/utils/constants.ts +++ b/packages/cli/utils/constants.ts @@ -13,6 +13,8 @@ export const SCHEMA_URL = `https://unpkg.com/@reflag/cli@latest/schema.json`; export const DEFAULT_BASE_URL = "https://app.reflag.com"; export const DEFAULT_API_URL = `${DEFAULT_BASE_URL}/api`; export const DEFAULT_TYPES_OUTPUT = join("gen", "flags.d.ts"); +export const TYPE_FORMATS = ["react", "node", "vue"] as const; +export type TypeFormat = (typeof TYPE_FORMATS)[number]; export const DEFAULT_AUTH_TIMEOUT = 60000; // 60 seconds diff --git a/packages/cli/utils/gen.ts b/packages/cli/utils/gen.ts index 7712f870a..81d2a5058 100644 --- a/packages/cli/utils/gen.ts +++ b/packages/cli/utils/gen.ts @@ -3,10 +3,12 @@ import { dirname, isAbsolute, join } from "node:path"; import { camelCase, kebabCase, pascalCase, snakeCase } from "change-case"; -import { Flag, RemoteConfig } from "../services/flags.js"; -import { JSONToType, quoteKey } from "./json.js"; +import type { TypeFormat } from "./constants.js"; +import { JSONToType, quoteKey, type JSONValue } from "./json.js"; -export type GenFormat = "react" | "node"; +export type FlagForTypes = + | { key: string; flagType: "boolean" } + | { key: string; flagType: "multivariate"; values: JSONValue[] }; // Keep in sync with Reflag main repo export const KeyFormats = [ @@ -85,51 +87,35 @@ export function genFlagKey(input: string, format: KeyFormat): string { return KeyFormatPatterns[format].transform(input); } -export function genRemoteConfig(remoteConfigs?: RemoteConfig[]) { - const variants = remoteConfigs?.[0]?.variants; - if (!variants?.length) return; - return JSONToType( - remoteConfigs![0].variants?.map(({ variant: { payload } }) => payload), - ); -} - -export function genTypes(flags: Flag[], format: GenFormat = "react") { - const configDefs = new Map(); - flags.forEach(({ key, name, remoteConfigs }) => { - const definition = genRemoteConfig(remoteConfigs); - - if (!definition) { - return; - } - - const configName = `${pascalCase(name)}ConfigPayload`; - configDefs.set(key, { name: configName, definition }); - }); +export function genTypes(flags: FlagForTypes[], format: TypeFormat = "react") { + const moduleName = `@reflag/${format}-sdk`; + const jsonValue = `import("${moduleName}").FlagValue`; + const keys = new Set(); + const definitions = flags + .map((flag) => { + const { key } = flag; + if (keys.has(key)) + throw new Error(`Duplicate flag key: ${JSON.stringify(key)}`); + keys.add(key); + const definition = + flag.flagType === "boolean" + ? "boolean" + : (JSONToType(flag.values, jsonValue) ?? jsonValue); + return indentLines(`${quoteKey(key)}: ${definition};`, 4); + }) + .join("\n"); return /* ts */ ` // DO NOT EDIT THIS FILE. IT IS GENERATED BY THE REFLAG CLI AND WILL BE OVERWRITTEN. +// Requires Reflag SDK v2. Values are inferred from current authored variants, not runtime-validated schemas. // eslint-disable // prettier-ignore -import "@reflag/${format}-sdk"; +import "${moduleName}"; -declare module "@reflag/${format}-sdk" { +declare module "${moduleName}" { export interface Flags { -${flags - .map(({ key }) => { - const config = configDefs.get(key); - return indentLines( - `${quoteKey(key)}: ${config?.definition ? `{ config: { payload: ${config.name} } }` : "boolean"};`, - 4, - ); - }) - .join("\n")} +${definitions} } - -${Array.from(configDefs.values()) - .map(({ name, definition }) => { - return indentLines(`export type ${name} = ${definition}`); - }) - .join("\n\n")} } `.trim(); } diff --git a/packages/cli/utils/json.ts b/packages/cli/utils/json.ts index 3c9feba5f..2132f36e6 100644 --- a/packages/cli/utils/json.ts +++ b/packages/cli/utils/json.ts @@ -1,10 +1,10 @@ -export type JSONPrimitive = +export type JSONValue = | number | string | boolean | null - | JSONPrimitive[] - | { [key: string]: JSONPrimitive }; + | JSONValue[] + | { [key: string]: JSONValue }; export type PrimitiveAST = { kind: "primitive"; type: string }; export type ArrayAST = { kind: "array"; elementType: TypeAST }; @@ -17,193 +17,132 @@ export type UnionAST = { kind: "union"; types: TypeAST[] }; // Type AST to represent TypeScript types export type TypeAST = PrimitiveAST | ArrayAST | ObjectAST | UnionAST; -// Convert JSON value to TypeAST -export function toTypeAST(value: JSONPrimitive, path: string[] = []): TypeAST { +export function toTypeAST(value: JSONValue): TypeAST { if (value === null) return { kind: "primitive", type: "null" }; - if (Array.isArray(value)) { - if (value.length === 0) { - return { - kind: "array", - elementType: { kind: "primitive", type: "any" }, - }; - } - - // Process all elements in the array instead of just the first one - const elementTypes = value.map((item, index) => - toTypeAST(item, [...path, index.toString()]), - ); - - return { - kind: "array", - elementType: mergeTypeASTs(elementTypes), - }; + return { kind: "array", elementType: mergeTypeASTs(value.map(toTypeAST)) }; } - if (typeof value === "object") { return { kind: "object", - properties: Object.entries(value).map(([key, val]) => ({ + properties: Object.entries(value).map(([key, propertyValue]) => ({ key, - type: toTypeAST(val, [...path, key]), + type: toTypeAST(propertyValue), optional: false, })), }; } - return { kind: "primitive", type: typeof value }; } -// Merge multiple TypeASTs into one -export function mergeTypeASTs(types: TypeAST[]): TypeAST { - if (types.length === 0) return { kind: "primitive", type: "any" }; - if (types.length === 1) return types[0]; - - // Group ASTs by kind - const byKind = { - union: types.filter((t) => t.kind === "union"), - primitive: types.filter((t) => t.kind === "primitive"), - array: types.filter((t) => t.kind === "array"), - object: types.filter((t) => t.kind === "object"), - }; - - // Create a union for mixed kinds - const hasMixedKinds = - byKind.union.length > 0 || // If we have any unions, treat it as mixed kinds - (byKind.primitive.length > 0 && - (byKind.array.length > 0 || byKind.object.length > 0)) || - (byKind.array.length > 0 && byKind.object.length > 0); - - if (hasMixedKinds) { - // If there are existing unions, flatten them into the current union - if (byKind.union.length > 0) { - // Flatten existing unions and collect types by category - const flattenedTypes: TypeAST[] = []; - const objectsToMerge: ObjectAST[] = [...byKind.object]; - const arraysToMerge: ArrayAST[] = [...byKind.array]; - - // Add primitives directly - flattenedTypes.push(...byKind.primitive); - - // Process union types - for (const unionType of byKind.union) { - for (const type of unionType.types) { - if (type.kind === "object") { - objectsToMerge.push(type); - } else if (type.kind === "array") { - arraysToMerge.push(type); - } else { - flattenedTypes.push(type); - } - } - } - - // Merge objects and arrays if they exist - if (objectsToMerge.length > 0) { - flattenedTypes.push(mergeTypeASTs(objectsToMerge)); - } - - if (arraysToMerge.length > 0) { - flattenedTypes.push(mergeTypeASTs(arraysToMerge)); - } - - return { kind: "union", types: flattenedTypes }; +export function mergeTypeASTs(input: TypeAST[]): TypeAST { + const primitives = new Set(); + const elements: TypeAST[] = []; + const objects: ObjectAST[] = []; + + function collect(ast: TypeAST) { + switch (ast.kind) { + case "primitive": + // Empty arrays do not contribute evidence about their element type. + if (ast.type !== "never") primitives.add(ast.type); + break; + case "array": + elements.push(ast.elementType); + break; + case "object": + objects.push(ast); + break; + case "union": + ast.types.forEach(collect); + break; } - - return { kind: "union", types }; } - - // Handle primitives - if (byKind.primitive.length === types.length) { - const uniqueTypes = [...new Set(byKind.primitive.map((p) => p.type))]; - return uniqueTypes.length === 1 - ? { kind: "primitive", type: uniqueTypes[0] } - : { - kind: "union", - types: uniqueTypes.map((type) => ({ kind: "primitive", type })), - }; - } - - // Merge arrays - if (byKind.array.length === types.length) { - return { - kind: "array", - elementType: mergeTypeASTs(byKind.array.map((a) => a.elementType)), - }; + input.forEach(collect); + + const members: TypeAST[] = Array.from(primitives, (type) => ({ + kind: "primitive", + type, + })); + if (elements.length) { + members.push({ kind: "array", elementType: mergeTypeASTs(elements) }); } + if (objects.length) members.push(mergeObjects(objects)); + if (members.length > 1) return { kind: "union", types: members }; + return members[0] ?? { kind: "primitive", type: "never" }; +} - // Merge objects - if (byKind.object.length === types.length) { - // Get all unique property keys - const allKeys = [ - ...new Set( - byKind.object.flatMap((obj) => obj.properties.map((p) => p.key)), - ), - ]; - - // Merge properties with same keys - const mergedProperties = allKeys.map((key) => { - const props = byKind.object - .map((obj) => obj.properties.find((p) => p.key === key)) - .filter((obj) => !!obj); - - return { - key, - type: mergeTypeASTs(props.map((p) => p.type)), - optional: byKind.object.some( - (obj) => !obj.properties.some((p) => p.key === key), - ), - }; - }); - - return { kind: "object", properties: mergedProperties }; +function mergeObjects(objects: ObjectAST[]): ObjectAST { + const byKey = new Map(); + for (const object of objects) { + for (const prop of object.properties) { + const existing = byKey.get(prop.key); + if (existing) existing.push(prop); + else byKey.set(prop.key, [prop]); + } } - - // Fallback - return { kind: "primitive", type: "any" }; + return { + kind: "object", + properties: Array.from(byKey, ([key, properties]) => ({ + key, + type: mergeTypeASTs(properties.map((prop) => prop.type)), + optional: + properties.length < objects.length || + properties.some((prop) => prop.optional), + })), + }; } // Stringify TypeAST to TypeScript type declaration -export function stringifyTypeAST(ast: TypeAST, nestLevel = 0): string { +export function stringifyTypeAST( + ast: TypeAST, + nestLevel = 0, + unknownType = "unknown", +): string { const indent = " ".repeat(nestLevel * 2); const nextIndent = " ".repeat((nestLevel + 1) * 2); switch (ast.kind) { case "primitive": - return ast.type; + return ast.type === "never" || ast.type === "unknown" + ? unknownType + : ast.type; case "array": - return `(${stringifyTypeAST(ast.elementType, nestLevel)})[]`; + return `(${stringifyTypeAST(ast.elementType, nestLevel, unknownType)})[]`; case "object": - if (ast.properties.length === 0) return "{}"; + if (ast.properties.length === 0) return `Record`; return `{\n${ast.properties .map(({ key, optional, type }) => { return `${nextIndent}${quoteKey(key)}${optional ? "?" : ""}: ${stringifyTypeAST( type, nestLevel + 1, + unknownType, )}`; }) .join(",\n")}\n${indent}}`; case "union": - if (ast.types.length === 0) return "any"; + if (ast.types.length === 0) return unknownType; if (ast.types.length === 1) - return stringifyTypeAST(ast.types[0], nestLevel); + return stringifyTypeAST(ast.types[0], nestLevel, unknownType); return ast.types - .map((type) => stringifyTypeAST(type, nestLevel)) + .map((type) => stringifyTypeAST(type, nestLevel, unknownType)) .join(" | "); } } export function quoteKey(key: string): string { - return /[^a-zA-Z0-9_]/.test(key) || /^[0-9]/.test(key) ? `"${key}"` : key; + return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : JSON.stringify(key); } // Convert JSON array to TypeScript type -export function JSONToType(json: JSONPrimitive[]): string | null { +export function JSONToType( + json: JSONValue[], + unknownType = "unknown", +): string | null { if (!json.length) return null; - return stringifyTypeAST(mergeTypeASTs(json.map((item) => toTypeAST(item)))); + return stringifyTypeAST(mergeTypeASTs(json.map(toTypeAST)), 0, unknownType); } diff --git a/packages/cli/utils/options.ts b/packages/cli/utils/options.ts index a384d98fb..b886cf74c 100644 --- a/packages/cli/utils/options.ts +++ b/packages/cli/utils/options.ts @@ -1,6 +1,6 @@ import { Argument, Option } from "commander"; -import { CONFIG_FILE_NAME } from "./constants.js"; +import { CONFIG_FILE_NAME, TYPE_FORMATS } from "./constants.js"; // Define supported editors directly here or import from a central place if needed elsewhere const SUPPORTED_EDITORS = ["cursor", "vscode"] as const; // Add more later: "claude", "cline", "windsurf" @@ -40,7 +40,7 @@ export const typesOutOption = new Option( export const typesFormatOption = new Option( "-f, --format [format]", "Single output format for generated flag types", -).choices(["react", "node"]); +).choices(TYPE_FORMATS); export const flagNameArgument = new Argument( "[name]", diff --git a/packages/cli/utils/urls.ts b/packages/cli/utils/urls.ts index 5b85944ec..2687d2ce6 100644 --- a/packages/cli/utils/urls.ts +++ b/packages/cli/utils/urls.ts @@ -25,10 +25,10 @@ export function environmentUrl(baseUrl: string, environment: UrlArgs): string { return `${baseUrl}/envs/${slug(environment)}`; } -export function featureUrl( +export function flagUrl( baseUrl: string, env: UrlArgs, - feature: UrlArgs, + flag: { key: string }, ): string { - return `${environmentUrl(baseUrl, env)}/features/${slug(feature)}`; + return `${environmentUrl(baseUrl, env)}/flags/by-key/${encodeURIComponent(flag.key)}`; }