diff --git a/.github/workflows/publish-cli-v1.yml b/.github/workflows/publish-cli-v1.yml new file mode 100644 index 000000000..a43edcd95 --- /dev/null +++ b/.github/workflows/publish-cli-v1.yml @@ -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 diff --git a/packages/cli/commands/flags.ts b/packages/cli/commands/flags.ts index 2033adcf8..2937f7dc2 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 } 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 { @@ -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)}.`, ); @@ -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(); diff --git a/packages/cli/test/gen.test.ts b/packages/cli/test/gen.test.ts new file mode 100644 index 000000000..4518f51ef --- /dev/null +++ b/packages/cli/test/gen.test.ts @@ -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"); + }); +}); diff --git a/packages/cli/test/json.test.ts b/packages/cli/test/json.test.ts index 600f3ae09..11337431f 100644 --- a/packages/cli/test/json.test.ts +++ b/packages/cli/test/json.test.ts @@ -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); @@ -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,` + diff --git a/packages/cli/utils/gen.ts b/packages/cli/utils/gen.ts index 7712f870a..2aa3f06b4 100644 --- a/packages/cli/utils/gen.ts +++ b/packages/cli/utils/gen.ts @@ -95,6 +95,7 @@ export function genRemoteConfig(remoteConfigs?: RemoteConfig[]) { export function genTypes(flags: Flag[], format: GenFormat = "react") { const configDefs = new Map(); + const aliasCounts = new Map(); flags.forEach(({ key, name, remoteConfigs }) => { const definition = genRemoteConfig(remoteConfigs); @@ -102,7 +103,17 @@ export function genTypes(flags: Flag[], format: GenFormat = "react") { 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 }); }); diff --git a/packages/cli/utils/json.ts b/packages/cli/utils/json.ts index 3c9feba5f..b58f206e3 100644 --- a/packages/cli/utils/json.ts +++ b/packages/cli/utils/json.ts @@ -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)) { @@ -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)), }; } @@ -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, })), }; @@ -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), }; }); @@ -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))); } diff --git a/releases/cli-v1.json b/releases/cli-v1.json new file mode 100644 index 000000000..198fd698b --- /dev/null +++ b/releases/cli-v1.json @@ -0,0 +1,4 @@ +{ + "version": "1.0.5", + "publish": false +} diff --git a/scripts/cli-v1-release.mjs b/scripts/cli-v1-release.mjs new file mode 100644 index 000000000..598fdd757 --- /dev/null +++ b/scripts/cli-v1-release.mjs @@ -0,0 +1,85 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const packageName = "@reflag/cli"; +const stableV1 = /^1\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +export function parseReleaseRequest(request) { + if ( + !request || + typeof request.version !== "string" || + !stableV1.test(request.version) || + (Object.hasOwn(request, "publish") && + typeof request.publish !== "boolean") || + Object.keys(request).some((key) => key !== "version" && key !== "publish") + ) { + throw new Error( + "Expected a stable CLI v1 version and an optional publish boolean", + ); + } + return { version: request.version, publish: request.publish ?? false }; +} + +export function assertCliV1Release(manifest, requestedVersion, latest) { + if (manifest.name !== packageName || manifest.private) { + throw new Error(`Expected the public ${packageName} package`); + } + if ( + typeof requestedVersion !== "string" || + !stableV1.test(requestedVersion) || + manifest.version !== requestedVersion + ) { + throw new Error( + "The requested stable CLI v1 version must match the packaged version", + ); + } + + const current = typeof latest === "string" && stableV1.exec(latest); + if (!current) { + throw new Error( + `Refusing to update npm latest: '${latest}' is not a stable CLI v1 version`, + ); + } + const expected = `1.${current[1]}.${BigInt(current[2]) + 1n}`; + if (requestedVersion !== expected) { + throw new Error( + `Expected the next CLI v1 patch (${expected}), not ${requestedVersion}`, + ); + } +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + switch (process.argv[2]) { + case "request": { + const { version, publish } = parseReleaseRequest( + JSON.parse(readFileSync("releases/cli-v1.json", "utf8")), + ); + console.log(`version=${version}\npublish=${publish}`); + break; + } + case "check": { + const manifest = JSON.parse(readFileSync(0, "utf8")); + const response = await fetch( + `https://registry.npmjs.org/-/package/${encodeURIComponent(packageName)}/dist-tags`, + { signal: AbortSignal.timeout(10_000), cache: "no-store" }, + ); + if (!response.ok) { + throw new Error( + `Could not read npm dist-tags (HTTP ${response.status})`, + ); + } + const { latest, next } = await response.json(); + assertCliV1Release(manifest, process.env.CLI_VERSION, latest); + console.log( + `Verified ${packageName} can move npm latest from ${latest} to ${manifest.version} (next: ${next ?? "unset"})`, + ); + break; + } + default: + throw new Error("Expected request or check"); + } +} diff --git a/scripts/cli-v1-release.test.mjs b/scripts/cli-v1-release.test.mjs new file mode 100644 index 000000000..8b70ef94b --- /dev/null +++ b/scripts/cli-v1-release.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { assertCliV1Release, parseReleaseRequest } from "./cli-v1-release.mjs"; + +const cli = { name: "@reflag/cli", version: "1.0.5" }; + +test("defaults to a dry run unless explicitly asked to publish", () => { + for (const request of [ + { version: cli.version }, + { version: cli.version, publish: false }, + ]) { + assert.deepEqual(parseReleaseRequest(request), { + version: cli.version, + publish: false, + }); + } + assert.deepEqual( + parseReleaseRequest({ version: cli.version, publish: true }), + { + version: cli.version, + publish: true, + }, + ); +}); + +test("rejects malformed release requests", () => { + for (const request of [ + null, + {}, + { version: "1.0.5-next.0", publish: true }, + { version: "2.0.0", publish: true }, + { version: "1.0.5\n", publish: true }, + { version: cli.version, publish: "true" }, + { version: cli.version, publish: null }, + { version: cli.version, tag: "next" }, + ]) { + assert.throws( + () => parseReleaseRequest(request), + /Expected a stable CLI v1 version/, + ); + } +}); + +test("accepts the next stable CLI v1 patch", () => { + assert.doesNotThrow(() => assertCliV1Release(cli, "1.0.5", "1.0.4")); +}); + +test("does not let a maintenance release move latest if it no longer points at a stable v1", () => { + for (const latest of [undefined, "0.9.9", "1.0.4-next.1", "2.0.0"]) { + assert.throws( + () => assertCliV1Release(cli, "1.0.5", latest), + /not a stable CLI v1/, + ); + } +}); + +test("rejects skipped patches, already released versions, and downgrades", () => { + for (const latest of ["1.0.3", "1.0.5", "1.0.6", "1.1.1"]) { + assert.throws( + () => assertCliV1Release(cli, "1.0.5", latest), + /Expected the next CLI v1 patch/, + ); + } +}); + +test("rejects unconfirmed, prerelease, and different package versions", () => { + for (const version of [undefined, "1.0.6", "1.0.5-next.0", "2.0.0"]) { + assert.throws( + () => assertCliV1Release(cli, version, "1.0.4"), + /must match the packaged version/, + ); + } +}); + +test("rejects building a different or private package", () => { + for (const manifest of [ + { ...cli, name: "@reflag/node-sdk" }, + { ...cli, private: true }, + ]) { + assert.throws( + () => assertCliV1Release(manifest, "1.0.5", "1.0.4"), + /Expected the public @reflag\/cli package/, + ); + } +});