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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions .github/workflows/publish-cli-v1.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
name: Release CLI v1

on:
pull_request:
branches: [maintenance/cli-v1]
paths:
- releases/cli-v1.json
- .github/workflows/publish-cli-v1.yml
- scripts/cli-v1-release*.mjs
push:
branches: [maintenance/cli-v1]
paths: [releases/cli-v1.json]

concurrency: cli-v1-release-${{ github.ref }}

permissions:
contents: read

jobs:
build:
name: Validate CLI v1 release
runs-on: ubuntu-latest
outputs:
version: ${{ steps.request.outputs.version }}
publish: ${{ steps.request.outputs.publish }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
persist-credentials: false
- run: corepack enable
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version-file: .nvmrc
package-manager-cache: false
- name: Read the release request
id: request
run: node scripts/cli-v1-release.mjs request >> "$GITHUB_OUTPUT"
- name: Require a changed request on the protected v1 branch for publication
if: github.event_name == 'push' && steps.request.outputs.publish == 'true'
env:
BEFORE_SHA: ${{ github.event.before }}
run: |
if [[ "$GITHUB_REF" != refs/heads/maintenance/cli-v1 || "$GITHUB_REF_PROTECTED" != true ]]; then
echo 'CLI v1 can only be published from the protected maintenance/cli-v1 branch.' >&2
exit 1
fi
git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"
changed=$(git diff --name-only "$BEFORE_SHA" "$GITHUB_SHA" -- releases/cli-v1.json)
if [[ "$changed" != releases/cli-v1.json ]]; then
echo 'A live release requires a new release request.' >&2
exit 1
fi
- name: Build, test, and pack only the CLI
run: |
node --test scripts/cli-v1-release.test.mjs
yarn install --immutable
yarn workspace @reflag/cli test
yarn workspace @reflag/cli build
yarn workspace @reflag/cli pack --out "$RUNNER_TEMP/reflag-cli.tgz"
- name: Check the packed version and npm latest tag
env:
CLI_VERSION: ${{ steps.request.outputs.version }}
run: |
set -o pipefail
tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs check
npm publish "$RUNNER_TEMP/reflag-cli.tgz" --registry https://registry.npmjs.org --access public --tag latest --ignore-scripts --dry-run
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: github.event_name == 'push' && steps.request.outputs.publish == 'true'
with:
name: reflag-cli-v1
path: ${{ runner.temp }}/reflag-cli.tgz
if-no-files-found: error
overwrite: true

publish:
name: Publish CLI v1 to npm latest
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance/cli-v1' && needs.build.outputs.publish == 'true'
runs-on: ubuntu-latest
environment: cli-v1-release
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version-file: .nvmrc
registry-url: https://registry.npmjs.org
package-manager-cache: false
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: reflag-cli-v1
path: ${{ runner.temp }}
- name: Recheck the branch and npm latest, then publish the verified tarball
env:
CLI_VERSION: ${{ needs.build.outputs.version }}
run: |
set -o pipefail
head=$(git ls-remote --exit-code origin refs/heads/maintenance/cli-v1 | cut -f1)
if [[ "$GITHUB_REF_PROTECTED" != true || "$head" != "$GITHUB_SHA" ]]; then
echo 'The release commit must still be the head of the protected maintenance/cli-v1 branch.' >&2
exit 1
fi
tar -xOf "$RUNNER_TEMP/reflag-cli.tgz" package/package.json | node scripts/cli-v1-release.mjs check
npm publish "$RUNNER_TEMP/reflag-cli.tgz" --registry https://registry.npmjs.org --access public --tag latest --ignore-scripts
28 changes: 8 additions & 20 deletions packages/cli/commands/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import chalk from "chalk";
import { Command } from "commander";
import ora, { Ora } from "ora";

import { App, getApp } from "../services/apps.js";
import { getApp } from "../services/apps.js";
import { createFlag, Flag, listFlags } from "../services/flags.js";
import { configStore } from "../stores/config.js";
import {
Expand Down Expand Up @@ -44,16 +44,10 @@ export const createFlagAction = async (
handleError(new MissingAppIdError(), "Flags Create");
}

let app: App;
try {
app = await getApp(appId);
} catch (error) {
handleError(error, "Flags Create");
}

const production = app.environments.find((e) => e.isProduction);
const app = await getApp(appId);
const production = app.environments.find((e) => e.isProduction);

try {
console.log(
`Creating flag for app ${chalk.cyan(app.name)} in ${chalk.cyan(app.org.name)}${baseUrlSuffix(baseUrl)}.`,
);
Expand Down Expand Up @@ -143,19 +137,13 @@ export const generateTypesAction = async () => {
handleError(new MissingAppIdError(), "Flags Types");
}

let app: App;
try {
app = await getApp(appId);
} catch (error) {
handleError(error, "Flags Types");
}

const production = app.environments.find((e) => e.isProduction);
if (!production) {
handleError(new MissingEnvIdError(), "Flags Types");
}
const app = await getApp(appId);
const production = app.environments.find((e) => e.isProduction);
if (!production) {
throw new MissingEnvIdError();
}

try {
spinner = ora(
`Loading flags of app ${chalk.cyan(app.name)}${baseUrlSuffix(baseUrl)}...`,
).start();
Expand Down
51 changes: 51 additions & 0 deletions packages/cli/test/gen.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";

import type { Flag } from "../services/flags.js";
import { genTypes } from "../utils/gen.js";
import type { JSONPrimitive } from "../utils/json.js";

function flag(key: string, name: string, payload: JSONPrimitive): Flag {
return {
id: key,
key,
name,
description: null,
stage: null,
remoteConfigs: [{ variants: [{ variant: { payload } }] }],
};
}

describe("SDK v1 generation", () => {
it("emits distinct payload aliases when flag names normalize the same way", () => {
const output = genTypes([
flag("first", "My Flag", 123),
flag("second", "My-Flag", "text"),
flag("third", "My flag", false),
]);

expect(output).toContain(
"first: { config: { payload: MyFlagConfigPayload } };",
);
expect(output).toContain(
"second: { config: { payload: MyFlagConfigPayload_2 } };",
);
expect(output).toContain(
"third: { config: { payload: MyFlagConfigPayload_3 } };",
);
expect(output).toContain("export type MyFlagConfigPayload = number");
expect(output).toContain("export type MyFlagConfigPayload_2 = string");
expect(output).toContain("export type MyFlagConfigPayload_3 = boolean");
});

it("emits valid alias names for digit-leading names and preserves valid Unicode names", () => {
const output = genTypes([
flag("numeric", "42", true),
flag("unicode", "Éclair", true),
]);

expect(output).toContain("payload: _42ConfigPayload");
expect(output).toContain("export type _42ConfigPayload = boolean");
expect(output).toContain("payload: ÉclairConfigPayload");
expect(output).toContain("export type ÉclairConfigPayload = boolean");
});
});
16 changes: 16 additions & 0 deletions packages/cli/test/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,12 @@ describe("JSON utilities", () => {
).toBe(expected);
});

it("should preserve optional properties when merging nested arrays", () => {
expect(JSONToType([[[{ a: 1 }, {}], [{ a: 2 }]]])).toBe(
"(({\n a?: number\n})[])[]",
);
});

it("should merge arrays with nested arrays of mixed element types", () => {
const expected = "((boolean | number | string | {\n id: number\n})[])[]";
expect(JSONToType([[[1, "test"], [true]], [[{ id: 1 }]]])).toBe(expected);
Expand All @@ -431,6 +437,16 @@ describe("JSON utilities", () => {
).toBe(expected);
});

it("should escape quoted keys and preserve empty keys in generated types", () => {
expect(JSONToType([{ 'a"b': 1, "a\\b": true, "": "empty" }])).toBe(
String.raw`{
"a\"b": number,
"a\\b": boolean,
"": string
}`,
);
});

it("should handle complex nested structures", () => {
const expected =
`{\n user: {\n name: string,\n settings: {\n theme?: string,` +
Expand Down
13 changes: 12 additions & 1 deletion packages/cli/utils/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,25 @@ export function genRemoteConfig(remoteConfigs?: RemoteConfig[]) {

export function genTypes(flags: Flag[], format: GenFormat = "react") {
const configDefs = new Map<string, { name: string; definition: string }>();
const aliasCounts = new Map<string, number>();
flags.forEach(({ key, name, remoteConfigs }) => {
const definition = genRemoteConfig(remoteConfigs);

if (!definition) {
return;
}

const configName = `${pascalCase(name)}ConfigPayload`;
const identifier = `${pascalCase(name)}ConfigPayload`.replace(
/[^\p{ID_Continue}$]/gu,
"_",
);
const base = /^[$_\p{ID_Start}]/u.test(identifier)
? identifier
: `_${identifier}`;
const count = (aliasCounts.get(base) ?? 0) + 1;
aliasCounts.set(base, count);
// A numbered suffix cannot collide with another base ending in ConfigPayload.
const configName = count === 1 ? base : `${base}_${count}`;
configDefs.set(key, { name: configName, definition });
});

Expand Down
20 changes: 7 additions & 13 deletions packages/cli/utils/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type UnionAST = { kind: "union"; types: TypeAST[] };
export type TypeAST = PrimitiveAST | ArrayAST | ObjectAST | UnionAST;

// Convert JSON value to TypeAST
export function toTypeAST(value: JSONPrimitive, path: string[] = []): TypeAST {
export function toTypeAST(value: JSONPrimitive): TypeAST {
if (value === null) return { kind: "primitive", type: "null" };

if (Array.isArray(value)) {
Expand All @@ -29,14 +29,9 @@ export function toTypeAST(value: JSONPrimitive, path: string[] = []): TypeAST {
};
}

// 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),
elementType: mergeTypeASTs(value.map(toTypeAST)),
};
}

Expand All @@ -45,7 +40,7 @@ export function toTypeAST(value: JSONPrimitive, path: string[] = []): TypeAST {
kind: "object",
properties: Object.entries(value).map(([key, val]) => ({
key,
type: toTypeAST(val, [...path, key]),
type: toTypeAST(val),
optional: false,
})),
};
Expand Down Expand Up @@ -150,9 +145,8 @@ export function mergeTypeASTs(types: TypeAST[]): TypeAST {
return {
key,
type: mergeTypeASTs(props.map((p) => p.type)),
optional: byKind.object.some(
(obj) => !obj.properties.some((p) => p.key === key),
),
optional:
props.length < byKind.object.length || props.some((p) => p.optional),
};
});

Expand Down Expand Up @@ -198,12 +192,12 @@ export function stringifyTypeAST(ast: TypeAST, nestLevel = 0): string {
}

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 {
if (!json.length) return null;

return stringifyTypeAST(mergeTypeASTs(json.map((item) => toTypeAST(item))));
return stringifyTypeAST(mergeTypeASTs(json.map(toTypeAST)));
}
4 changes: 4 additions & 0 deletions releases/cli-v1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"version": "1.0.5",
"publish": false
}
Loading
Loading