Skip to content

Emit native Stricli commands and route maps for cf - #774

Draft
irvinebroque wants to merge 8 commits into
mainfrom
codex/migrate-stricli
Draft

irvinebroque wants to merge 8 commits into
mainfrom
codex/migrate-stricli

Conversation

@irvinebroque

@irvinebroque irvinebroque commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Why switch? Three things now come from the same command definition: what cf accepts, what Tab suggests, and what inputs the handler can use. Customers can now complete saved profile names without logging in, and reading help no longer loads the generated code that makes API calls. This is not a smaller install or a promise that every command starts faster.

  • For maintainers: a flag rename can fail the build instead of breaking a command. cf auth create used to declare --scopes once for the parser and again in the handler’s TypeScript interface. Now the handler gets its type from the flag definition. Rename the flag but leave the handler reading argv.scopes, and TypeScript catches it. Generated commands already had some type inference under yargs; the gain here is removing the duplicate declaration in auth.

  • For customers: choose a saved profile when deploying. If your team has a profile named production, type cf deploy --profile pro and press Tab. Before, Tab offered nothing; now it suggests production. The --profile flag tells Stricli where to get valid names, so you don’t have to remember the spelling or stop to run cf auth list. Pressing Tab only reads local profile names; it doesn’t log in, call Cloudflare, or start a deploy.

  • For correctness: we prevent some mistakes, not all of them. Parsing and Tab can still agree on a wrong choice, and a correctly typed handler can still send the wrong API request. The parity checks tell us whether the tested invocations behave like yargs—not whether yargs was right. The reason to switch is that future changes are safer, not that the whole CLI is simpler or guaranteed correct.

What customers see

Try this Before (yargs) After (Stricli)
cf zero-trust devices list --help Loaded the product’s definitions and bundled handler code. Same help text. Loads the product’s definitions, zero generated handlers.
cf zero-trust devices list --dry-run Printed a request preview without making the request. Same preview. Loads one generated handler, not its siblings.
Type cf complete po and press Tab No suggestion, even though powershell was a valid argument. Suggests powershell from the command’s positional choices. Routes, aliases, flags and enum values also come from the parser. Existing bash, zsh, fish and PowerShell scripts work without reinstalling.
With a saved work profile, type cf auth activate wo or cf zones list --profile wo and press Tab You had to remember the name or run cf auth list. Suggests work. Also works for auth create (re-authentication) and auth delete. Only local filenames are listed; no token reads, login, or API calls. If the store is unavailable, Tab stays silent.

The new Tab results are intentional. Against main at 6de4261c2, all 7,206 in-process comparisons matched the yargs result: 4,191 help paths, 2,962 generated dry runs (including 198 matching failures), and 53 other cases. On Linux, macOS, and Windows, a separate check installed both npm tarballs and matched the actual exit status and exact stdout and stderr for five commands: help, a dry run, an invalid flag, repeated --force -f on a dry run, and refusing a delete without --force when stdin is piped. The saved-profile example returned work through all four shell integrations on macOS. These checks don’t exercise live API calls or interactive prompts.

How much difference does it make?

Measurements from the lazy-handler and parser-backed completion revision, before the auth conversion: median wall time from launching bin/cf to exit on one Apple Silicon Mac (Node 24.22.0; two warmups, then 20 fresh processes per build per command, alternating builds; warm filesystem, telemetry off):

Zero Trust example yargs This PR
Device list help 144 ms 141 ms
Device list dry run 136 ms 128 ms
Tab after zero-trust devices li 150 ms 129 ms

Help loads less code; its timing was close. Node loaded 45 built JS modules totaling 1.83 MB for help, down from 60 totaling 2.49 MB. The completion callback was about 21 ms quicker in this sample, despite loading more JS (1.90 vs 1.36 MB); it no longer reads and walks the whole JSON catalog. These results don’t measure a cold install or the time spent waiting for Cloudflare’s API.

How it works

flowchart LR
  subgraph Before
    Y[Generated yargs builder + handler] --> P[Parse or show help]
    M[Separate JSON catalog] --> T[Tab]
  end
  subgraph After
    D[Command definition] --> H[Help]
    D --> S[Stricli suggestions for all four shells]
    D --> R[Parse and run] --> L[Import selected handler]
  end
Loading

For zones list, abridged:

// Before: the flag and its execution code lived in one module.
yargs.option("direction", { type: "string", choices: ["asc", "desc"] });
type Args = InferArgs<typeof builder>;

// After: changing the choices updates parsing, Tab and the handler’s type.
const parameters = { flags: { direction: { kind: "enum", brief: "Sort direction", values: ["asc", "desc"], optional: true } }, operands: [] } as const;
export type Args = ApiInputs<typeof parameters>;
apiCommand({ command: "list", describe: "List Zones", usage: "$0 zones list", ...parameters, loader: () => import("./list.handler.js") });
// In list.handler.ts, argv.direction is "asc" | "desc" | undefined.

Hand-written commands: All nine cf auth commands now use native definitions too. Previously auth create declared scopes as a string array in a builder and separately declared scopes?: string[] for its handler. Now the handler type comes directly from the flag:

// Abridged from auth create; no separate CreateArgs interface.
flags: { scopes: { kind: "parsed", parse: String, brief: "The set of OAuth scopes to request", optional: true, variadic: true } },
async handler(argv) {
  // argv.scopes is string[] | undefined; removing the flag breaks this use at build time.
  await login({ scopes: argv.scopes, /* ... */ });
}

This catches a mistyped or renamed auth input before release. It doesn’t change the login flow or make authentication faster. Profile names are suggested only where accepted: for example, a saved default is valid for --profile but not for auth activate <name>.

What we take on

  • A larger download. The compressed cf npm package grows from 3.08 MB to 3.37 MB (+288 KB, about 9%; npm pack --dry-run, excluding separately installed dependencies). The production build goes from 274 JS modules (12.40 MB) to 3,246 (13.70 MB). Splitting handlers lets help skip execution code; npm still ships every handler. cf does not run both parsers.
  • cf still owns its help and compatibility rules. Scripts care about repeated flags, error order and destructive confirmations. Moving auth removed its old builders and separate argument interfaces, but did not remove the shared adapter: hand-written families outside auth still need it. Shared parser changes must work for both styles.
  • We keep the shell integrations. Stricli supplies command loaders and completion suggestions, but its installer supports only bash. Keeping cf’s existing scripts lets us use the new suggestions without dropping three shells. Stricli core has no runtime dependencies; this does not make all of cf dependency-free.

@pkg-pr-new

pkg-pr-new Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
npm i https://pkg.pr.new/cf@774

commit: 5c90900

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

cf --help startup

mean stddev min max
PR 272.8 ms 5.0 ms 263.7 ms 284.7 ms
base 296.2 ms 5.1 ms 288.8 ms 307.2 ms

Δ (PR vs base): ↓ -23.4 ms (-7.9%)

Measured with hyperfine on ubuntu-latest (3 warmup runs, 20 timed runs). CI numbers carry ±a few ms of runner jitter; treat small deltas as noise.

Comment thread packages/cli/src/lib/stricli.ts Outdated
if (negated && inline !== undefined) {
return fail(`Cannot pass a value to --${spelling}`);
}
parsedTokens.push(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Repeated boolean flags such as --force -f and --quiet --quiet are valid yargs invocations, but this now forwards both canonical --force tokens to Stricli, which raises --force can only be specified once. Keep only the final value for a boolean flag before invoking Stricli so repeated flags retain their previous last-value-wins behavior.

Suggested change
parsedTokens.push(
const token = negated
? `${flag}=false`
: value === undefined
? flag
: `${flag}=${value}`;
for (let index = parsedTokens.length - 1; index >= 0; index--) {
if (
parsedTokens[index] === flag ||
parsedTokens[index]?.startsWith(`${flag}=`)
) {
parsedTokens.splice(index, 1);
}
}
parsedTokens.push(token);

/^-[a-zA-Z]{2,}$/.test(arg)
) {
const shortNames = arg.slice(1).split("");
if (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires every member of a grouped short option to be boolean. containers build defines -p as boolean and -t as its required string tag, so the yargs-compatible cf containers build -pt image ./dir is now rejected as an unknown -pt instead of expanding to -p -t image. Permit a value-taking final member after a boolean prefix.

Suggested change
if (
shortNames.slice(0, -1).every(
(name) =>
def.flags.get(names.get(name) ?? "")?.type === "boolean"
) &&
def.flags.has(names.get(shortNames.at(-1) ?? "") ?? "")

Comment thread packages/cli/src/lib/stricli.ts Outdated
if (!previous?.startsWith("-")) {
return true;
}
const key = names.get(previous.replace(/^--?/, ""));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An unknown option is normally parsed as a value-bearing option by yargs. Here its following value is instead treated as the first command token, so cf --bogus value zones list fails route resolution with Unknown commands: value, zones, list rather than resolving zones list and reporting the actual unknown --bogus flag. Skip the immediate token after an unknown option while looking for the command path.

Suggested change
const key = names.get(previous.replace(/^--?/, ""));
return (
key !== undefined &&
def.flags.get(key)?.type === "boolean" &&
!["true", "false"].includes(token)
);

@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Review: 3 findings.

Posted 3 inline suggestion comments.

github run

@irvinebroque irvinebroque changed the title Migrate cf argument parsing from yargs to Stricli Emit native Stricli commands and route maps for cf Nov 24, 2026
@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

  • Warning: packages/cli/src/lib/stricli.ts:792 rejects yargs-compatible -t123 short option values as unknown flags. Recognize numeric suffixes for value-taking short options. Inline review submission was rejected because GitHub could not resolve this path in the oversized PR diff.

github run

@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

No new concerns since the last review.

github run

mkdir "install-$side"
(cd "$side" && pnpm --filter cf build)
(cd "$side/packages/cli" && pnpm pack --pack-destination "../../../install-$side")
(cd "install-$side" && npm install --ignore-scripts --no-audit --no-fund ./*.tgz)
@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

@irvinebroque Bonk workflow was cancelled.

View workflow run · To retry, trigger Bonk again.

@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

When an optional array flag has no value, packages/cli/src/lib/stricli.ts:920 serializes it as an empty-string element. For example, cf tunnels tail <id> --event --level info reaches assign() as event: [""] and is rejected by the EVENTS choice validation, whereas yargs treats the supplied --event as []. Preserve the bare array flag so Stricli produces the same empty-array value.

			const pushValue = (raw: string | undefined) => {
				if (raw === undefined && (opt.array || opt.type === "array")) {
					seen.add(key);
					trackCoercion(opt, []);
					nativeTokens.push(flag);
					parsedTokens.push(flag);
					return;
				}
				if (
					(!opt.array && seen.has(key)) ||
					!raw ||
					/[\r\n\u2028\u2029]/.test(raw) ||
					(opt.choices && !opt.coerce && !opt.choices.includes(raw))
				) {
					native = undefined;
				}
				seen.add(key);
				nativeTokens.push(`--${key}=${raw ?? ""}`);
				if (raw !== undefined || !opt.requiresArg) {
					trackCoercion(opt, raw ?? "");
				}
				parsedTokens.push(flag, raw === undefined ? "" : `:${raw}`);
			};

@ask-bonk

ask-bonk Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

🤖 I've done a thorough review of your PR.

Migrates command definitions, parsing, completion, generated routing, and auth commands to Stricli.

  1. Warning: value-less optional array flags become [""] instead of [], breaking choices such as --event --level info. Posted a suggested fix in the PR comment.

github run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants