passport-bridge 0.52.0 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/cliHookClassify.js +34 -10
  2. package/dist/cliHookDecide.js +3 -1
  3. package/dist/cliHookParse.d.ts +4 -0
  4. package/dist/cliHookParse.js +13 -2
  5. package/dist/connectorKit/cli.generated.d.ts +8 -2
  6. package/dist/connectorKit/cli.generated.js +131 -46
  7. package/dist/connectorKit/cliTree.generated.d.ts +92 -0
  8. package/dist/connectorKit/cliTree.generated.js +134 -0
  9. package/dist/connectorKit/engine.generated.js +27 -6
  10. package/dist/connectorKit/launchers.generated.d.ts +53 -0
  11. package/dist/connectorKit/launchers.generated.js +109 -0
  12. package/dist/connectorKit/manifest.generated.d.ts +5 -0
  13. package/dist/connectorKit/manifests/railwayCapture.generated.d.ts +5 -0
  14. package/dist/connectorKit/manifests/railwayCapture.generated.js +50 -5
  15. package/dist/connectorKit/manifests/railwayCommands.generated.d.ts +17 -0
  16. package/dist/connectorKit/manifests/railwayCommands.generated.js +268 -0
  17. package/dist/connectorKit/manifests/supabase.generated.js +6 -1
  18. package/dist/connectorKit/manifests/supabaseCli.generated.d.ts +3 -1
  19. package/dist/connectorKit/manifests/supabaseCli.generated.js +91 -2
  20. package/dist/connectorKit/pgParser.d.ts +8 -6
  21. package/dist/connectorKit/pgParser.js +16 -9
  22. package/dist/connectorKit/shell.generated.js +4 -2
  23. package/dist/connectorKit/sources/railway/cli-tree.generated.d.ts +139 -0
  24. package/dist/connectorKit/sources/railway/cli-tree.generated.js +2 -0
  25. package/dist/connectorKit/sources/supabase/cli-flags.generated.d.ts +479 -192
  26. package/dist/connectorKit/sources/supabase/cli-flags.generated.js +1 -1
  27. package/dist/connectorKit/surfaces.generated.d.ts +81 -0
  28. package/dist/connectorKit/surfaces.generated.js +122 -0
  29. package/dist/connectorKit/types.generated.d.ts +2 -0
  30. package/dist/controlPlaneGuard.js +4 -3
  31. package/dist/controlPlaneKubernetes.js +4 -3
  32. package/dist/controlPlaneNpmGuard.js +6 -2
  33. package/dist/controlPlaneRailwayGuard.d.ts +4 -2
  34. package/dist/controlPlaneRailwayGuard.js +20 -73
  35. package/dist/controlPlaneRailwayReach.d.ts +1 -1
  36. package/dist/controlPlaneRailwayReach.js +2 -0
  37. package/dist/controlPlaneSupabase.d.ts +9 -3
  38. package/dist/controlPlaneSupabase.js +18 -3
  39. package/dist/controlPlaneUnnamed.generated.d.ts +10 -1
  40. package/dist/controlPlaneUnnamed.generated.js +6 -0
  41. package/dist/pluginPin.d.ts +1 -1
  42. package/dist/pluginPin.js +1 -1
  43. package/dist/psqlSupabase.d.ts +14 -6
  44. package/dist/psqlSupabase.js +24 -7
  45. package/dist/version.d.ts +1 -1
  46. package/dist/version.js +1 -1
  47. package/npm-shrinkwrap.json +19 -3
  48. package/package.json +3 -2
@@ -11,6 +11,7 @@
11
11
  import { azRisk, azVerb, azVerbKey, parseAzCommand } from "./azureCommands.js";
12
12
  import { basename, INTERPRETERS, normalizeArgv, SHELLS, splitCommands } from "./cliHookParse.js";
13
13
  import { awsVerbKey, parseAwsCommand } from "./awsCommands.js";
14
+ import { packageRun } from "./connectorKit/launchers.generated.js";
14
15
  import { spawnedCommands } from "./connectorKit/spawns.generated.js";
15
16
  import { NPX_PACKAGE_TO_VENDOR, VENDORS } from "./cliHookVendors.js";
16
17
  import { parseKube } from "./kubeCommand.js";
@@ -391,15 +392,40 @@ function classifyVendorVerb(vendor, all, via, envInjected) {
391
392
  }
392
393
  return finding(vendor, verb || positional.slice(0, 2).join(" ") || null, risk, via, verb ? "high" : "low", envInjected);
393
394
  }
395
+ /** The vendor a package runner's word names: a package (`@railway/cli@4`, `vercel@latest`), or a vendor's program. */
396
+ function packageVendor(word, program) {
397
+ const trimmed = word.replace(/@[^/]*$/, (match) => (word.startsWith("@") && match.indexOf("/") === -1 ? match : ""));
398
+ for (const key of [word, trimmed, program])
399
+ if (Object.hasOwn(NPX_PACKAGE_TO_VENDOR, key))
400
+ return NPX_PACKAGE_TO_VENDOR[key];
401
+ return vendorSpec(trimmed) ? trimmed : vendorSpec(program) ? program : null;
402
+ }
403
+ /** A package runner (`launchers.ts`: `npx`, `pnpm exec`, `bun x`, `yarn <program>` …) running a vendor's CLI; null
404
+ * when `argv` isn't a package run, or is a bare run (`pnpm add …`) of no vendor. */
405
+ function classifyPackageRun(argv, via, envInjected) {
406
+ const run = packageRun(argv);
407
+ if (!run)
408
+ return null;
409
+ const word = argv[run.at];
410
+ const rest = run.args;
411
+ const vendor = packageVendor(word, run.program);
412
+ // A bare run's first word may be the runner's own command or a script: a vendor only with a command after it.
413
+ if (run.bare)
414
+ return vendor && /^[a-z]/i.test(rest[0] ?? "")
415
+ ? [classifyVendor(vendor, rest, [...via, run.runner.trim()], envInjected)]
416
+ : null;
417
+ if (vendor)
418
+ return [classifyVendor(vendor, rest, [...via, run.runner.trim()], envInjected)];
419
+ return run.runner === "npx " || run.runner === "bunx "
420
+ ? [opaque([...via, run.runner.trim()], `npx package ${word} not in vendor map`)]
421
+ : [];
422
+ }
394
423
  function classifyPackageRunner(argv, prog, via, envInjected) {
395
424
  const packageIndex = argv.findIndex((arg, index) => index > 0 && !arg.startsWith("-"));
396
425
  if (packageIndex === -1)
397
426
  return [];
398
427
  const raw = argv[packageIndex];
399
- const trimmed = raw.replace(/@[^/]*$/, (match) => (raw.startsWith("@") && match.indexOf("/") === -1 ? match : ""));
400
- const vendor = (Object.hasOwn(NPX_PACKAGE_TO_VENDOR, raw) ? NPX_PACKAGE_TO_VENDOR[raw] : undefined) ??
401
- (Object.hasOwn(NPX_PACKAGE_TO_VENDOR, trimmed) ? NPX_PACKAGE_TO_VENDOR[trimmed] : undefined) ??
402
- (vendorSpec(trimmed) ? trimmed : null);
428
+ const vendor = packageVendor(raw, raw);
403
429
  if (!vendor)
404
430
  return [opaque([...via, prog], `npx package ${raw} not in vendor map`)];
405
431
  return [classifyVendor(vendor, argv.slice(packageIndex + 1), [...via, prog], envInjected)];
@@ -437,14 +463,12 @@ function classifySimpleCommand(argv, via, envInjected, depth) {
437
463
  }
438
464
  if (prog === "xargs")
439
465
  return [];
466
+ const packaged = classifyPackageRun(argv, via, envInjected);
467
+ if (packaged)
468
+ return packaged;
469
+ // `npx -c '…'` (a script): read by its own reader; what this one names is the script's first program.
440
470
  if (prog === "npx" || prog === "bunx")
441
471
  return classifyPackageRunner(argv, prog, via, envInjected);
442
- if ((prog === "pnpm" || prog === "yarn") && argv[1] === "dlx") {
443
- const pkg = argv[2];
444
- const mapped = Object.hasOwn(NPX_PACKAGE_TO_VENDOR, pkg) ? NPX_PACKAGE_TO_VENDOR[pkg] : undefined;
445
- const vendor = mapped ?? (vendorSpec(pkg) ? pkg : null);
446
- return vendor ? [classifyVendor(vendor, argv.slice(3), [...via, `${prog} dlx`], envInjected)] : [];
447
- }
448
472
  if (INTERPRETERS.has(prog))
449
473
  return classifyInterpreter(argv, prog, via);
450
474
  if (prog === "make" || prog === "just" || prog === "task") {
@@ -370,7 +370,9 @@ async function foundOffline(context, missed) {
370
370
  }
371
371
  if (missed.supabase) {
372
372
  const where = { cwd: context.cwd ?? null, env: context.env ?? process.env };
373
- found.push(...(await import("./controlPlaneSupabase.js")).supabaseFound(context.command, where));
373
+ const supabase = await import("./controlPlaneSupabase.js");
374
+ await supabase.readySupabaseSql(context.command);
375
+ found.push(...supabase.supabaseFound(context.command, where));
374
376
  }
375
377
  if (missed.kubernetes) {
376
378
  const where = { cwd: context.cwd ?? null, env: context.env ?? process.env, home: homedir() };
@@ -70,6 +70,10 @@ export type NormalizedArgv = {
70
70
  * the real program, or empty when the words carry no command of their own.
71
71
  */
72
72
  export declare function normalizeArgv(source: string[]): NormalizedArgv;
73
+ /** The program words a package runner runs (`launchers.ts`, the table every reader shares): `npx kubectl …`,
74
+ * `pnpm exec gh …` → the program first. A bare run (`pnpm gh pr merge 1`) counts only for a program `ours` names
75
+ * followed by a command word, since that word may be the runner's own command or a script. Other words unchanged. */
76
+ export declare function runnerArgv(argv: string[], ours: (program: string) => boolean): string[];
73
77
  /** The script a command runs as a line of its own: a shell's `-c`, or a runner's `-c`/`--call`. */
74
78
  export declare function shellScript(argv: readonly string[]): string | null;
75
79
  /** `env -S '…'` (`--split-string`) before the program: the command it splits out, with the words after it. */
@@ -8,7 +8,7 @@
8
8
  * alias/function resolution, runtime variable expansion. Those are the honest
9
9
  * limits of a hook that only ever watches.
10
10
  */
11
- import { launcherEnd, launcherName } from "./connectorKit/launchers.generated.js";
11
+ import { launcherEnd, launcherName, packageArgv } from "./connectorKit/launchers.generated.js";
12
12
  import { spawnedCommands } from "./connectorKit/spawns.generated.js";
13
13
  /** Words before the real command that the bridge alone skips, beyond the shared launchers (`launchers.ts`): `script`
14
14
  * (macOS's `script -q /dev/null cmd`) and `xargs` (the command it runs on each input line). */
@@ -170,8 +170,12 @@ function readDoubleQuoted(state) {
170
170
  let cursor = state.index + 1;
171
171
  let text = "";
172
172
  while (cursor < end && input[cursor] !== '"') {
173
+ // Inside double quotes a backslash escapes only $ ` " \ and a newline; before anything else the shell keeps it
174
+ // (`psql -c "select 1 \gexec"` hands psql `\gexec`).
173
175
  if (input[cursor] === "\\" && cursor + 1 < end) {
174
- text += input[cursor + 1];
176
+ const next = input[cursor + 1];
177
+ if (next !== "\n")
178
+ text += '$`"\\'.includes(next) ? next : `\\${next}`;
175
179
  cursor += 2;
176
180
  continue;
177
181
  }
@@ -508,6 +512,13 @@ export function normalizeArgv(source) {
508
512
  argv[0] = basename(argv[0]);
509
513
  return { argv, via, envInjected };
510
514
  }
515
+ /** The program words a package runner runs (`launchers.ts`, the table every reader shares): `npx kubectl …`,
516
+ * `pnpm exec gh …` → the program first. A bare run (`pnpm gh pr merge 1`) counts only for a program `ours` names
517
+ * followed by a command word, since that word may be the runner's own command or a script. Other words unchanged. */
518
+ export function runnerArgv(argv, ours) {
519
+ const run = packageArgv(argv, (program, args) => ours(program) && /^[a-z]/i.test(args[0] ?? ""));
520
+ return run ? run.argv : argv;
521
+ }
511
522
  /** A shell's `-c` script (`bash -lc '…'`, `bash -c -- '…'`, `fish -c '…'`, `fish --command=…`). */
512
523
  function shellCommand(argv) {
513
524
  let command = false;
@@ -8,9 +8,15 @@ import type { Manifest } from "./manifest.generated.js";
8
8
  import type { Normalized, Value } from "./types.generated.js";
9
9
  /** Every command the manifest knows, longest first. */
10
10
  export declare function knownOps(m: Manifest): string[];
11
+ /** An unknown flag whose name says it may change what the command does: never kept, always fails closed. */
12
+ export declare const EFFECT_FLAG_WORDS: RegExp;
11
13
  export declare const present: (value: Value | undefined) => boolean;
12
14
  export declare const programName: (word: string) => string;
13
15
  /** Strip what runs a program without changing it: env assignments, launchers (`launchers.ts`: env, sudo, timeout,
14
- * time, nice …), package runners. */
15
- export declare function stripLaunchers(words: string[], programs: readonly string[]): void;
16
+ * time, nice …), package runners (`npx`, `pnpm exec`, `bunx` …, and `pnpm <program>` when `bareRun` says what
17
+ * follows is the CLI's command). Returns the folder a runner's option moves the program to (null when the guard
18
+ * can't name it), if one does. */
19
+ export declare function stripLaunchers(words: string[], programs: readonly string[], bareRun?: (args: readonly string[]) => boolean): {
20
+ dir?: string | null;
21
+ };
16
22
  export declare function normalizeCli(m: Manifest, argv: readonly string[], given?: string): Normalized | null;
@@ -5,7 +5,7 @@
5
5
  * framework does, positional arguments as $1..$n. Anything the vendor's spec
6
6
  * wouldn't accept is a `problem`: the request fails closed.
7
7
  */
8
- import { launcherEnd, neverLaunches } from "./launchers.generated.js";
8
+ import { launcherEnd, neverLaunches, packageArgv } from "./launchers.generated.js";
9
9
  const COBRA_TRUE = new Set(["1", "t", "T", "true", "TRUE", "True"]);
10
10
  const COBRA_FALSE = new Set(["0", "f", "F", "false", "FALSE", "False"]);
11
11
  const tables = new WeakMap();
@@ -27,6 +27,27 @@ function tablesOf(m) {
27
27
  tables.set(cli, built);
28
28
  return built;
29
29
  }
30
+ const flagNames = new WeakMap();
31
+ /** Every flag name the manifest knows anywhere (long and short): global, legacy, any command's, local and remote. */
32
+ function manifestFlags(m) {
33
+ const cli = m.capture.cli;
34
+ const hit = flagNames.get(cli);
35
+ if (hit)
36
+ return hit;
37
+ const names = new Set([
38
+ ...cli.localFlags,
39
+ ...cli.remoteFlags,
40
+ ...(cli.contextFlags ?? []),
41
+ ...(cli.infoFlags ?? [])
42
+ ]);
43
+ for (const spec of [...cli.flags.global, ...(cli.legacyFlags ?? []), ...Object.values(cli.flags.commands).flat()]) {
44
+ names.add(spec.long);
45
+ if (spec.short)
46
+ names.add(spec.short);
47
+ }
48
+ flagNames.set(cli, names);
49
+ return names;
50
+ }
30
51
  /** Every command the manifest knows, longest first. */
31
52
  export function knownOps(m) {
32
53
  return tablesOf(m).ops;
@@ -41,10 +62,24 @@ function flagTable(specs) {
41
62
  }
42
63
  return { long, short };
43
64
  }
65
+ /** An unknown flag whose name says it may change what the command does: never kept, always fails closed. */
66
+ export const EFFECT_FLAG_WORDS = /(^|-)(force|delete|del|remove|rm|prune|purge|drop|destroy|wipe|reset|all|recursive|cascade|yes|y|overwrite|replace|no-verify|unsafe|skip|confirm|auto-approve|allow)(-|$)/;
44
67
  /** Parse argv with one flag table, the way cobra (or Vercel's arg) does. */
45
- function parseArgs(words, specs, strict, framework) {
68
+ function parseArgs(words, specs, strict, framework, lenient) {
46
69
  const { long, short } = flagTable(specs);
47
- const out = { positional: [], flags: {} };
70
+ const out = { positional: [], flags: {}, unknown: [], maybeValues: new Set() };
71
+ // Lenient: an unknown flag is recorded; the word after it, unless it is a flag, may be its value.
72
+ // `lenient` holds every flag the manifest knows anywhere: one of those in the wrong place isn't new, it fails.
73
+ const unknownFlag = (name, inline, shown) => {
74
+ if (!lenient || lenient.has(name) || EFFECT_FLAG_WORDS.test(name)) {
75
+ fail(`unknown flag ${shown}`);
76
+ return;
77
+ }
78
+ out.unknown.push(name);
79
+ if (!inline)
80
+ pendingUnknown = true;
81
+ };
82
+ let pendingUnknown = false;
48
83
  const fail = (problem) => {
49
84
  out.problem ??= problem;
50
85
  };
@@ -77,6 +112,8 @@ function parseArgs(words, specs, strict, framework) {
77
112
  };
78
113
  for (let i = 0; i < words.length; i++) {
79
114
  const word = words[i];
115
+ const afterUnknown = pendingUnknown;
116
+ pendingUnknown = false;
80
117
  if (word === "--") {
81
118
  out.positional.push(...words.slice(i + 1));
82
119
  break;
@@ -90,7 +127,7 @@ function parseArgs(words, specs, strict, framework) {
90
127
  const spec = long.get(name);
91
128
  if (!spec) {
92
129
  if (strict)
93
- fail(`unknown flag ${word.slice(0, dashes)}${name}`);
130
+ unknownFlag(name, eq >= 0, `${word.slice(0, dashes)}${name}`);
94
131
  continue;
95
132
  }
96
133
  if (eq >= 0)
@@ -110,8 +147,9 @@ function parseArgs(words, specs, strict, framework) {
110
147
  for (let j = 0; j < letters.length; j++) {
111
148
  const spec = short.get(letters[j]);
112
149
  if (!spec) {
150
+ // Letters after an unknown one may be its value (`-n5`); only a lone unknown letter can take the next word.
113
151
  if (strict)
114
- fail(`unknown flag -${letters[j]}`);
152
+ unknownFlag(letters[j], j + 1 < letters.length, `-${letters[j]}`);
115
153
  break;
116
154
  }
117
155
  if (spec.value === "none") {
@@ -133,6 +171,8 @@ function parseArgs(words, specs, strict, framework) {
133
171
  }
134
172
  continue;
135
173
  }
174
+ if (afterUnknown)
175
+ out.maybeValues.add(out.positional.length);
136
176
  out.positional.push(word);
137
177
  }
138
178
  return out;
@@ -156,32 +196,47 @@ export const programName = (word) => word
156
196
  .replace(/@.*$/, "")
157
197
  .replace(/\.(exe|cmd|ps1)$/i, "");
158
198
  /** Strip what runs a program without changing it: env assignments, launchers (`launchers.ts`: env, sudo, timeout,
159
- * time, nice …), package runners. */
160
- export function stripLaunchers(words, programs) {
161
- const runners = /^(npx|bunx|pnpx)$/;
199
+ * time, nice …), package runners (`npx`, `pnpm exec`, `bunx` …, and `pnpm <program>` when `bareRun` says what
200
+ * follows is the CLI's command). Returns the folder a runner's option moves the program to (null when the guard
201
+ * can't name it), if one does. */
202
+ export function stripLaunchers(words, programs, bareRun) {
203
+ let dir;
162
204
  for (let guard = 0; guard < 32 && words.length; guard++) {
163
205
  const first = words[0];
164
206
  if (programs.includes(programName(first)))
165
- return;
207
+ break;
166
208
  const launcher = launcherEnd(words, 0);
167
- if (launcher !== null)
209
+ if (launcher !== null) {
168
210
  words.splice(0, Math.max(1, launcher));
169
- else if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first))
170
- words.shift();
171
- else if (/^(npm|pnpm|yarn)$/.test(first) && /^(exec|x|dlx)$/.test(words[1] ?? ""))
172
- words.splice(0, 2);
173
- else if (runners.test(first))
174
- words.shift();
175
- else if (first === "--" || /^-/.test(first)) {
176
- // A runner's own option, and its value when it takes one (npx -p supabase, sudo -u admin).
177
- const valued = /^(-p|--package|-u|--user|-g|--group|-C|--chdir|-n)$/.test(first);
211
+ continue;
212
+ }
213
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(first)) {
178
214
  words.shift();
179
- if (valued)
180
- words.shift();
215
+ continue;
181
216
  }
182
- else
183
- return;
217
+ const run = packageArgv(words, (program, args) => programs.includes(program) && (bareRun?.(args) ?? false));
218
+ if (!run)
219
+ break;
220
+ if (run.run.dir !== undefined)
221
+ dir = run.run.dir === null || dir === null ? null : joinFolder(dir, run.run.dir);
222
+ words.splice(0, words.length, ...run.argv);
184
223
  }
224
+ return dir === undefined ? {} : { dir };
225
+ }
226
+ /** `inner` inside `outer` (both relative to the line's folder, or absolute). */
227
+ const joinFolder = (outer, inner) => outer === undefined || inner.startsWith("/")
228
+ ? inner
229
+ : inner === "."
230
+ ? outer
231
+ : `${outer.replace(/\/+$/, "")}/${inner}`;
232
+ /** Whether `args` (after the CLI's name) name a command the CLI knows, or the CLI runs a default command. */
233
+ function commandFollows(m, args) {
234
+ const cli = m.capture.cli;
235
+ if (cli.defaultCommand !== undefined)
236
+ return true;
237
+ const { topWords, anyFlags } = tablesOf(m);
238
+ const named = canonicalWords(parseArgs(args, anyFlags, false, cli.framework).positional, cli.aliases ?? {});
239
+ return named.length > 0 && topWords.has(named[0]);
185
240
  }
186
241
  /** The command the words name (aliases resolved), or the CLI's default command when the first word isn't one. */
187
242
  function findOp(m, words) {
@@ -204,18 +259,9 @@ function findOp(m, words) {
204
259
  function launchedBehind(m, words, programs) {
205
260
  if (!words.length || neverLaunches(programName(words[0]), words.slice(1)))
206
261
  return false;
207
- const cli = m.capture.cli;
208
- const { topWords, anyFlags } = tablesOf(m);
209
- for (let i = 1; i < words.length; i++) {
210
- if (!programs.includes(programName(words[i])))
211
- continue;
212
- const after = words.slice(i + 1);
213
- if (cli.defaultCommand !== undefined)
214
- return true;
215
- const named = canonicalWords(parseArgs(after, anyFlags, false, cli.framework).positional, cli.aliases ?? {});
216
- if (named.length && topWords.has(named[0]))
262
+ for (let i = 1; i < words.length; i++)
263
+ if (programs.includes(programName(words[i])) && commandFollows(m, words.slice(i + 1)))
217
264
  return true;
218
- }
219
265
  return false;
220
266
  }
221
267
  /** More arguments than the vendor's usage line allows means something we can't read rides along. */
@@ -224,11 +270,54 @@ function tooManyArgs(usage, count) {
224
270
  return false;
225
271
  return count > (usage.match(/[<[][^>\]]+[>\]]/g) ?? []).filter((p) => !/flags/.test(p)).length;
226
272
  }
273
+ /** Another folder the command runs in, whose link (not this folder's) decides the target: a context flag's or folder
274
+ * argument's, inside a package runner's folder (`pnpm -C apps/web exec …`) when one names it. */
275
+ function folderOf(cli, flags, folderIndex, args, runnerDir) {
276
+ const contextFlag = (cli.contextFlags ?? []).find((flag) => typeof flags[flag] === "string");
277
+ const named = contextFlag
278
+ ? flags[contextFlag]
279
+ : folderIndex !== undefined
280
+ ? args[folderIndex]
281
+ : undefined;
282
+ return typeof runnerDir === "string" ? joinFolder(runnerDir, named ?? ".") : named;
283
+ }
284
+ /** How many positional arguments the vendor's usage line allows (Infinity for a rest argument or no usage line). */
285
+ function usageMax(usage) {
286
+ if (usage === undefined || usage.includes("..."))
287
+ return Infinity;
288
+ return (usage.match(/[<[][^>\]]+[>\]]/g) ?? []).filter((p) => !/flags|options/i.test(p)).length;
289
+ }
290
+ /**
291
+ * Lenient flags: the words right after an unknown flag written without `=` are its value or an argument. They are
292
+ * values when the command's rules read no argument, or when counting them as arguments would pass the usage line;
293
+ * otherwise the command can't be read (it fails closed, "Couldn't read").
294
+ */
295
+ function keptPositional(m, op, opLength, parsed) {
296
+ if (!parsed.maybeValues.size)
297
+ return { words: parsed.positional };
298
+ const dropped = parsed.positional.filter((_, i) => !parsed.maybeValues.has(i));
299
+ if ([...parsed.maybeValues].some((i) => i < opLength))
300
+ return { words: parsed.positional, problem: "an unknown flag before the command" };
301
+ const readsArgs = m.capture.cli.rules.some((rule) => rule.match === op && rule.args?.length);
302
+ if (!readsArgs)
303
+ return { words: dropped };
304
+ const max = usageMax(m.capture.cli.usage?.[op]);
305
+ if (parsed.positional.length - opLength > max && dropped.length - opLength <= max)
306
+ return { words: dropped };
307
+ return { words: parsed.positional, problem: "an unknown flag may hide an argument" };
308
+ }
309
+ /** The words parsed with the command's flags, strictly, or leniently where the manifest keeps unknown flags. */
310
+ function parseCommand(m, words, specs, op, defaulted, opLength) {
311
+ const cli = m.capture.cli;
312
+ const lenient = cli.unknownFlags === "keep" && op !== undefined && !defaulted ? manifestFlags(m) : undefined;
313
+ const exact = parseArgs(words, specs, true, cli.framework, lenient);
314
+ return { exact, kept: lenient ? keptPositional(m, op, opLength, exact) : { words: exact.positional } };
315
+ }
227
316
  export function normalizeCli(m, argv, given) {
228
317
  const cli = m.capture.cli;
229
318
  const programs = [...cli.programs, ...(cli.aliasPrograms ?? [])];
230
319
  const words = [...argv];
231
- stripLaunchers(words, programs);
320
+ const runner = stripLaunchers(words, programs, (args) => commandFollows(m, args));
232
321
  if (!programs.includes(programName(words[0] ?? ""))) {
233
322
  // The CLI run by a program we don't know: never call it a read.
234
323
  if (launchedBehind(m, words, programs))
@@ -240,9 +329,9 @@ export function normalizeCli(m, argv, given) {
240
329
  const own = op ? (cli.flags.commands[op] ?? []) : [];
241
330
  // Deprecated target flags (--linked, --local, --db-url) still work only where the command takes a target.
242
331
  const legacy = own.some((flag) => flag.long === "remote") ? (cli.legacyFlags ?? []) : [];
243
- const exact = parseArgs(words, [...cli.flags.global, ...legacy, ...own], true, cli.framework);
244
332
  const opWords = op && !defaulted ? op.split(" ") : [];
245
- const positional = canonicalWords(exact.positional, cli.aliases ?? {});
333
+ const { exact, kept } = parseCommand(m, words, [...cli.flags.global, ...legacy, ...own], op, defaulted, opWords.length);
334
+ const positional = canonicalWords(kept.words, cli.aliases ?? {});
246
335
  const args = positional.slice(opWords.length);
247
336
  const params = { ...exact.flags };
248
337
  args.forEach((value, index) => (params[`$${index + 1}`] = value));
@@ -250,19 +339,14 @@ export function normalizeCli(m, argv, given) {
250
339
  const remote = cli.remoteFlags.some((flag) => present(exact.flags[flag]));
251
340
  const problem = given ??
252
341
  exact.problem ??
342
+ kept.problem ??
253
343
  (op && !opWords.every((part, i) => positional[i] === part) ? "flags moved the command" : undefined) ??
254
344
  (op && tooManyArgs(cli.usage?.[op], args.length) ? "more arguments than the command takes" : undefined) ??
255
345
  (remote && localFlagsUsed.some((flag) => flag === "local" || !own.some((spec) => spec.long === flag))
256
346
  ? "remote and local together"
257
- : undefined);
258
- // Another folder: its link, not this folder's, decides the target.
259
- const contextFlag = (cli.contextFlags ?? []).find((flag) => typeof exact.flags[flag] === "string");
260
- const folderIndex = op ? cli.folderArgs?.[op] : undefined;
261
- const folder = contextFlag
262
- ? exact.flags[contextFlag]
263
- : folderIndex !== undefined
264
- ? args[folderIndex]
265
- : undefined;
347
+ : undefined) ??
348
+ (runner.dir === null ? "a package runner's folder the guard cannot name" : undefined);
349
+ const folder = folderOf(cli, exact.flags, op ? cli.folderArgs?.[op] : undefined, args, runner.dir);
266
350
  const info = (cli.infoFlags ?? []).some((flag) => exact.flags[flag] === true);
267
351
  return {
268
352
  iface: "cli",
@@ -271,6 +355,7 @@ export function normalizeCli(m, argv, given) {
271
355
  local: info || localFlagsUsed.length > 0,
272
356
  remote,
273
357
  ...(localFlagsUsed.length ? { localFlagsUsed } : {}),
358
+ ...(exact.unknown.length ? { unknownFlags: [...new Set(exact.unknown)] } : {}),
274
359
  ...(folder ? { folder } : {}),
275
360
  ...(problem ? { problem } : {})
276
361
  };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * A vendor CLI's whole command tree, pinned to one version (docs/design/zero-unknowns.md). `scripts/cli-trees/`
3
+ * crawls the installed binary's help into `sources/<platform>/cli-tree.json`; this module turns it into the
4
+ * manifest's tables (flags, aliases, usage lines) and measures how much of it a manifest names. Pure.
5
+ *
6
+ * Every leaf command of the pinned tree is named: a hand-written rule, a reviewed read, or an entry of the
7
+ * platform's command overlay (`CommandEffect`), which becomes a rule for the platform's "Other change" with the
8
+ * effects the reviewer gave it. A command the tree doesn't have is new (a newer CLI than the pin): "New command".
9
+ */
10
+ import type { Effect } from "../controlPlaneActions.generated.js";
11
+ import type { CaptureRule, CliSpec, FlagSpec, Manifest } from "./manifest.generated.js";
12
+ export type CliTreeCommand = {
13
+ path: string;
14
+ aliases?: readonly string[];
15
+ usage?: string;
16
+ /** Only holds subcommands: run alone it prints help. */
17
+ group?: boolean;
18
+ hidden?: boolean;
19
+ deprecated?: boolean;
20
+ summary?: string;
21
+ flags: readonly FlagSpec[];
22
+ };
23
+ export type CliTree = {
24
+ cli: string;
25
+ version: string;
26
+ framework: string;
27
+ source: string;
28
+ globalFlags: readonly FlagSpec[];
29
+ commands: readonly CliTreeCommand[];
30
+ };
31
+ /**
32
+ * What one operation does, reviewed. Each is explicit; the gate counts an operation with none as missing.
33
+ * - `read`: changes nothing on the platform; the reason is the evidence.
34
+ * - `local`: acts only on this computer (a local dev server, a config file, shell completion).
35
+ * - `rule`: a hand-written capture rule names it (the gate confirms one exists).
36
+ * - `other`: the app's "Other change" on `on`, with this summary and these effects (kind and impact follow them).
37
+ */
38
+ export type OpEffect = {
39
+ read: string;
40
+ } | {
41
+ local: string;
42
+ } | {
43
+ rule: true;
44
+ } | {
45
+ other: string;
46
+ effects: readonly Effect[];
47
+ on: "project" | "service" | "environment";
48
+ };
49
+ /** A CLI command's overlay entry: the same shape as every interface's. */
50
+ export type CommandEffect = OpEffect;
51
+ /** The words a command is known by in the manifest: the vendor's path with the manifest's own renames applied. */
52
+ export declare function renamePath(path: string, rename?: Readonly<Record<string, string>>): string;
53
+ /** Leaf commands (anything a person can run that isn't only a group), renamed. Hidden ones count: they run. */
54
+ export declare function treeLeaves(tree: CliTree, rename?: Readonly<Record<string, string>>): string[];
55
+ /** Groups: run alone they print help, a read. */
56
+ export declare function treeGroups(tree: CliTree, rename?: Readonly<Record<string, string>>): string[];
57
+ /** The manifest's flag table, aliases and usage lines, from the tree. */
58
+ export declare function treeTables(tree: CliTree, rename?: Readonly<Record<string, string>>): Pick<CliSpec, "flags" | "aliases" | "usage">;
59
+ /** Aliases merged (later wins) and followed to the end, so a spelling of a spelling lands on the command. */
60
+ export declare function mergeAliases(...maps: ReadonlyArray<Readonly<Record<string, string>>>): Record<string, string>;
61
+ /** Flags from the tree, with a manifest's own reviewed additions (hand-declared flags win where both name one). */
62
+ export declare function mergeFlags(base: Readonly<Record<string, readonly FlagSpec[]>>, extra: Readonly<Record<string, readonly FlagSpec[]>>): Record<string, FlagSpec[]>;
63
+ /** The capture rules and reads an overlay adds for commands no hand rule names. */
64
+ export declare function overlayCapture(overlay: Readonly<Record<string, CommandEffect>>, other: string, hooks: Readonly<Record<"project" | "service" | "environment", {
65
+ hook: string;
66
+ where: string;
67
+ }>>, ruled?: ReadonlySet<string>): {
68
+ rules: CaptureRule[];
69
+ reads: Record<string, string>;
70
+ };
71
+ /** The (action, summary template, effects) rows an overlay gives the platform's call-effects table. */
72
+ export declare function overlayCallEffects(overlay: Readonly<Record<string, CommandEffect>>, other: string, hooks: Readonly<Record<"project" | "service" | "environment", {
73
+ hook: string;
74
+ where: string;
75
+ }>>): Array<[string, string, readonly Effect[]]>;
76
+ export type CommandCoverage = {
77
+ cli: string;
78
+ version: string;
79
+ /** Leaf commands in the pinned tree. */
80
+ total: number;
81
+ /** Named by a rule, a read or the overlay. */
82
+ named: number;
83
+ /** Leaves nothing names: each would be Unclassified ("New command") today. */
84
+ missing: string[];
85
+ /** Overlay entries saying `rule` with no hand rule behind them. */
86
+ ruleless: string[];
87
+ /** (command, flag) pairs in the tree, and those the manifest's flag table knows. */
88
+ flagPairs: number;
89
+ flagPairsKnown: number;
90
+ };
91
+ /** How much of a pinned tree a manifest names (the ratchet in `cliTree.test.ts`). */
92
+ export declare function commandCoverage(m: Manifest, tree: CliTree, rename?: Readonly<Record<string, string>>, overlay?: Readonly<Record<string, CommandEffect>>): CommandCoverage;