@fluid-app/fluid-cli 0.1.64 → 0.1.65

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.
@@ -1 +1 @@
1
- {"version":3,"file":"fluid.mjs","names":[],"sources":["../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../src/auth/profiles.ts","../../src/commands/login.ts","../../src/commands/logout.ts","../../src/commands/whoami.ts","../../src/commands/switch.ts","../../src/plugins/discovery.ts","../../src/plugins/format-load-line.ts","../../src/plugins/resolve-load-path.ts","../../src/plugins/should-log-plugin-loads.ts","../../src/plugins/loader.ts","../../src/update/notifier.ts","../../src/bin/fluid.ts"],"sourcesContent":["/**\n * fluid commands — list every installed command, or print the catalog as\n * JSON for agents and documentation generators.\n */\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport {\n filterCatalog,\n rootCommand,\n walkCommands,\n type CatalogEntry,\n} from \"../catalog/walk.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\nfunction usage(entry: CatalogEntry): string {\n const args = entry.arguments.map((arg) => {\n const name = arg.variadic ? `${arg.name}...` : arg.name;\n return arg.required ? `<${name}>` : `[${name}]`;\n });\n return [entry.command, ...args].join(\" \");\n}\n\nexport function formatCatalogText(entries: readonly CatalogEntry[]): string {\n const runnable = entries.filter((entry) => entry.runnable);\n const width = Math.min(\n 48,\n Math.max(0, ...runnable.map((entry) => usage(entry).length)),\n );\n return runnable\n .map((entry) => {\n const line = usage(entry);\n const summary = entry.description.split(\"\\n\", 1)[0] ?? \"\";\n return summary ? `${line.padEnd(width)} ${summary}` : line;\n })\n .join(\"\\n\");\n}\n\nexport const commandsCommand = new Command(\"commands\")\n .description(\"List installed commands; --json prints the full catalog\")\n .argument(\"[prefix...]\", \"Only list commands under this one, e.g. `domains`\")\n .option(\"--json\", \"Print the catalog as JSON\", false)\n .action((prefix: string[], opts: { json: boolean }, command: Command) => {\n const root = rootCommand(command);\n\n const entries = filterCatalog(walkCommands(root), root, prefix);\n if (entries.length === 0) {\n process.stderr.write(\n JSON.stringify({ error: `No command named \"${prefix.join(\" \")}\".` }) +\n \"\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n if (opts.json) {\n process.stdout.write(\n JSON.stringify(\n { cli: root.name(), version, commands: entries },\n null,\n 2,\n ) + \"\\n\",\n );\n return;\n }\n process.stdout.write(formatCatalogText(entries) + \"\\n\");\n });\n","/**\n * Shell completion. The scripts `fluid completion <shell>` prints pipe the\n * words typed so far into the hidden `fluid __complete`, so completions come\n * from the plugins actually installed rather than a list frozen at install.\n * The words go over stdin, never argv: a half-typed `--token <value>` must\n * not show up in another user's process list.\n */\n\nimport type { Command, Option } from \"commander\";\nimport { visibleOptions, visibleSubcommands } from \"../catalog/walk.js\";\n\nexport const SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nexport interface Candidate {\n readonly value: string;\n readonly description: string;\n}\n\nfunction findOption(chain: readonly Command[], word: string): Option | null {\n const flag = word.split(\"=\", 1)[0] ?? word;\n for (const command of [...chain].reverse()) {\n const match = command.options.find(\n (option) => option.long === flag || option.short === flag,\n );\n if (match) return match;\n }\n return null;\n}\n\nfunction splitAssignment(word: string): [string, string] {\n const at = word.indexOf(\"=\");\n return [word.slice(0, at), word.slice(at + 1)];\n}\n\nfunction choicesFor(option: Option, typed: string): Candidate[] {\n return (option.argChoices ?? [])\n .filter((choice) => choice.startsWith(typed))\n .map((choice) => ({ value: choice, description: \"\" }));\n}\n\nfunction findSubcommand(command: Command, word: string): Command | null {\n return (\n visibleSubcommands(command).find(\n (sub) => sub.name() === word || sub.aliases().includes(word),\n ) ?? null\n );\n}\n\n/**\n * Complete the last of `words`, the words after the program name.\n * Where a flag's value is expected, offers the flag's choices if it has\n * any; otherwise returns nothing so the shell falls back to files.\n */\nexport function completeWords(\n root: Command,\n words: readonly string[],\n): Candidate[] {\n const partial = words.at(-1) ?? \"\";\n const chain: Command[] = [root];\n let current = root;\n let awaitingValue: Option | null = null;\n let operandsOnly = false;\n // Operands typed for `current`; only the first can name a subcommand.\n let operands = 0;\n\n const prior = words.slice(0, -1);\n for (const [index, word] of prior.entries()) {\n if (awaitingValue) {\n // Bash splits `--flag=value` at the `=`, so the value follows it.\n if (word !== \"=\" || prior[index - 1] === \"=\") awaitingValue = null;\n continue;\n }\n if (!operandsOnly && word === \"--\") {\n operandsOnly = true;\n continue;\n }\n if (!operandsOnly && word.startsWith(\"-\")) {\n const option = findOption(chain, word);\n awaitingValue = option?.required && !word.includes(\"=\") ? option : null;\n continue;\n }\n const sub = operands === 0 ? findSubcommand(current, word) : null;\n if (sub) {\n current = sub;\n chain.push(sub);\n } else {\n operands += 1;\n }\n }\n\n if (awaitingValue) {\n // After bash's split the partial is the bare `=` before any value.\n const typed = partial === \"=\" ? \"\" : partial;\n return choicesFor(awaitingValue, typed);\n }\n\n if (!operandsOnly && partial.startsWith(\"--\") && partial.includes(\"=\")) {\n // zsh and fish keep `--flag=value` as one word, and so must the reply.\n const [flag = \"\", typed = \"\"] = splitAssignment(partial);\n const option = findOption(chain, flag);\n if (!option?.required && !option?.optional) return [];\n return choicesFor(option, typed).map((choice) => ({\n ...choice,\n value: `${flag}=${choice.value}`,\n }));\n }\n\n if (!operandsOnly && partial.startsWith(\"-\")) {\n const seen = new Set<string>();\n const candidates: Candidate[] = [];\n for (const command of [...chain].reverse()) {\n for (const option of visibleOptions(command)) {\n // The program's --version belongs to `fluid` alone.\n if (option.long === \"--version\" && command !== current) continue;\n for (const value of [option.long, option.short]) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n candidates.push({ value, description: option.description });\n }\n }\n }\n candidates.push({ value: \"--help\", description: \"Show help\" });\n return candidates.filter((c) => c.value.startsWith(partial));\n }\n\n const candidates: Candidate[] = [];\n if (operands === 0) {\n for (const sub of visibleSubcommands(current)) {\n for (const name of [sub.name(), ...sub.aliases()]) {\n candidates.push({ value: name, description: sub.description() });\n }\n }\n }\n const args = current.registeredArguments;\n const last = args.at(-1);\n const argument = args[operands] ?? (last?.variadic ? last : undefined);\n for (const choice of argument?.argChoices ?? []) {\n candidates.push({\n value: choice,\n description: argument?.description ?? \"\",\n });\n }\n return candidates.filter((c) => c.value.startsWith(partial));\n}\n\n/**\n * The words the scripts pipe in: each followed by a NUL, the program name\n * first. Returns the words after the program name, at least one.\n */\nexport function parseCompletionInput(input: string): string[] {\n const words = input.split(\"\\0\");\n // The text after the last NUL is the empty tail of the final terminator.\n words.pop();\n const typed = words.slice(1);\n return typed.length > 0 ? typed : [\"\"];\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\", 1)[0]?.trim() ?? \"\";\n}\n\n/** One candidate per line, in the shape each shell's script reads. */\nexport function formatCandidates(\n candidates: readonly Candidate[],\n shell: Shell,\n): string {\n const lines = candidates.map(({ value, description }) => {\n const summary = firstLine(description);\n switch (shell) {\n case \"bash\":\n return value;\n case \"zsh\":\n // _describe splits on the first unescaped colon.\n return summary\n ? `${value.replaceAll(\":\", \"\\\\:\")}:${summary}`\n : value.replaceAll(\":\", \"\\\\:\");\n case \"fish\":\n return summary ? `${value}\\t${summary}` : value;\n }\n });\n return lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\nexport function completionScript(shell: Shell): string {\n switch (shell) {\n case \"bash\":\n // Words are copied one by one: bash 3.2, macOS's /bin/bash, joins\n // a quoted array slice into one word while IFS is a newline.\n return `# fluid bash completion\n_fluid_complete() {\n local -a words\n local i\n for ((i = 0; i <= COMP_CWORD; i++)); do words+=(\"\\${COMP_WORDS[i]}\"); done\n local IFS=$'\\\\n'\n COMPREPLY=($(printf '%s\\\\0' \"\\${words[@]}\" | fluid __complete --shell bash 2>/dev/null))\n}\ncomplete -o default -F _fluid_complete fluid\n`;\n case \"zsh\":\n return `#compdef fluid\n# fluid zsh completion\n_fluid() {\n local -a candidates\n candidates=(\"\\${(@f)$(printf '%s\\\\0' \"\\${(@)words[1,CURRENT]}\" | fluid __complete --shell zsh 2>/dev/null)}\")\n candidates=(\\${candidates:#})\n if (( \\${#candidates} )); then\n _describe -t fluid 'fluid' candidates\n else\n _files\n fi\n}\nif [[ \\${zsh_eval_context[-1]} == loadautofunc ]]; then\n _fluid \"$@\"\nelse\n compdef _fluid fluid\nfi\n`;\n case \"fish\":\n // The current token goes through a variable so an empty one is still\n // sent: a bare (commandline -ct) expands to no argument at all.\n return `# fluid fish completion\nfunction __fluid_complete\n set -l current (commandline -ct)\n set -l candidates (string join0 -- (commandline -opc) \"$current\" | fluid __complete --shell fish 2>/dev/null)\n if set -q candidates[1]\n printf '%s\\\\n' $candidates\n else\n __fish_complete_path \"$current\"\n end\nend\ncomplete -c fluid -f -a '(__fluid_complete)'\n`;\n }\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall:\n bash echo 'eval \"$(fluid completion bash)\"' >> ~/.bashrc\n zsh fluid completion zsh > \"\\${fpath[1]}/_fluid\" (or eval \"$(fluid completion zsh)\" in ~/.zshrc)\n fish fluid completion fish > ~/.config/fish/completions/fluid.fish\n`;\n","/**\n * fluid completion <shell> — print a shell completion script.\n * fluid __complete — the hidden command that script pipes the typed words\n * into on each tab.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { Argument, Command, Option } from \"commander\";\nimport {\n completeWords,\n completionScript,\n COMPLETION_INSTALL_HELP,\n formatCandidates,\n parseCompletionInput,\n SHELLS,\n type Shell,\n} from \"../completion/complete.js\";\nimport { rootCommand } from \"../catalog/walk.js\";\n\nexport const completionCommand = new Command(\"completion\")\n .description(\"Print a shell completion script for bash, zsh or fish\")\n .addArgument(new Argument(\"<shell>\", \"Shell to complete in\").choices(SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: Shell) => {\n process.stdout.write(completionScript(shell));\n });\n\nexport const completeCommand = new Command(\"__complete\")\n .description(\"Print completions for the words typed so far\")\n .addOption(\n new Option(\"--shell <shell>\", \"Output format\")\n .choices(SHELLS)\n .default(\"bash\"),\n )\n .action((opts: { shell: Shell }, command: Command) => {\n // The words arrive on stdin, NUL-terminated, never as arguments.\n const typed = parseCompletionInput(readFileSync(0, \"utf8\"));\n process.stdout.write(\n formatCandidates(completeWords(rootCommand(command), typed), opts.shell),\n );\n });\n","/**\n * Helpers for constructing stored auth profiles.\n */\n\nimport type { FluidProfile } from \"../config/types.js\";\n\ninterface CreateFluidProfileInput {\n readonly name: string;\n readonly token: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly storedAt?: string;\n}\n\nexport function createFluidProfile({\n name,\n token,\n companyName,\n baseUrl,\n storedAt,\n}: CreateFluidProfileInput): FluidProfile {\n return {\n name,\n token,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n };\n}\n","/**\n * fluid login — authenticate via email MFA or API token\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n validateToken,\n sendMfa,\n confirmMfa,\n getFluidApiBase,\n type CompanyChoice,\n} from \"../auth/fluid-api.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { updateConfig, readConfig } from \"../config/config.js\";\n\nasync function confirmOverwrite(profileName: string): Promise<boolean> {\n const existing = readConfig().profiles[profileName];\n if (!existing) return true;\n\n const response = await prompts({\n type: \"confirm\",\n name: \"overwrite\",\n message: `Profile \"${profileName}\" already exists (${existing.companyName}). Overwrite?`,\n initial: false,\n });\n return Boolean(response[\"overwrite\"]);\n}\n\nfunction storeProfile(\n profileName: string,\n token: string,\n companyName: string,\n): void {\n updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createFluidProfile({\n name: profileName,\n token,\n companyName,\n baseUrl: getFluidApiBase(),\n }),\n },\n }));\n}\n\nasync function loginWithToken(\n token: string,\n profileName?: string,\n): Promise<void> {\n const spinner = ora(\"Validating token...\").start();\n const result = await validateToken(token);\n\n if (!result.success) {\n spinner.fail(chalk.red(result.error.message));\n if (result.error.details) {\n console.log(chalk.dim(result.error.details));\n }\n process.exitCode = 1;\n return;\n }\n\n const name = profileName ?? result.value.name;\n\n // Stop spinner before potential interactive prompt to avoid terminal corruption\n spinner.succeed(\n chalk.green(`Token valid — ${chalk.bold(result.value.name)}`),\n );\n\n if (!(await confirmOverwrite(name))) {\n console.log(\n chalk.yellow(\"Login cancelled — existing profile not overwritten.\"),\n );\n return;\n }\n\n storeProfile(name, token, result.value.name);\n console.log(\n chalk.green(\n `Logged in as ${chalk.bold(result.value.name)} (profile: ${chalk.bold(name)})`,\n ),\n );\n}\n\nasync function loginWithEmail(\n initialEmail?: string,\n profileName?: string,\n): Promise<void> {\n // 1. Prompt for email\n let email = initialEmail;\n if (!email) {\n const response = await prompts({\n type: \"text\",\n name: \"email\",\n message: \"Enter your email\",\n });\n email = response[\"email\"] as string | undefined;\n if (!email) {\n console.log(chalk.red(\"No email provided. Aborting.\"));\n process.exitCode = 1;\n return;\n }\n }\n\n // 2. Send MFA code\n const sendSpinner = ora(\"Sending verification code...\").start();\n const sendResult = await sendMfa(email);\n\n if (!sendResult.success) {\n sendSpinner.fail(chalk.red(sendResult.error.message));\n if (sendResult.error.details) {\n console.log(chalk.dim(sendResult.error.details));\n }\n process.exitCode = 1;\n return;\n }\n\n const expiresAt = new Date(sendResult.value.expiresAt);\n const expiresInMs = expiresAt.getTime() - Date.now();\n const expiresInMin = Math.round(expiresInMs / 1000 / 60);\n const expiryNote =\n expiresInMin > 0\n ? `expires in ~${expiresInMin} min`\n : \"code may expire soon — check your email quickly\";\n sendSpinner.succeed(\n `Verification code sent — check your email (${expiryNote})`,\n );\n\n // 3. Prompt for verification code (retry up to 3 times on invalid code)\n const MAX_CODE_ATTEMPTS = 3;\n let confirmResult;\n for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {\n const codeResponse = await prompts({\n type: \"text\",\n name: \"code\",\n message: \"Enter the 6-digit code\",\n });\n const code = codeResponse[\"code\"] as string | undefined;\n if (!code) {\n console.log(chalk.red(\"No code provided. Aborting.\"));\n process.exitCode = 1;\n return;\n }\n if (!/^\\d{6}$/.test(code)) {\n console.log(chalk.red(\"Code must be exactly 6 digits.\"));\n if (attempt < MAX_CODE_ATTEMPTS) continue;\n console.log(chalk.red(\"Too many invalid attempts. Aborting.\"));\n process.exitCode = 1;\n return;\n }\n\n const confirmSpinner = ora(\"Verifying code...\").start();\n confirmResult = await confirmMfa(sendResult.value.uuid, code);\n\n if (confirmResult.success) {\n confirmSpinner.succeed(\"Verified\");\n break;\n }\n\n // Retryable: wrong code, still have attempts left\n if (\n confirmResult.error.code === \"INVALID_CODE\" &&\n attempt < MAX_CODE_ATTEMPTS\n ) {\n confirmSpinner.fail(\n chalk.red(\n `${confirmResult.error.message} (attempt ${attempt}/${MAX_CODE_ATTEMPTS})`,\n ),\n );\n continue;\n }\n\n // Non-retryable (expired, unreachable, etc.) or final attempt\n confirmSpinner.fail(chalk.red(confirmResult.error.message));\n if (confirmResult.error.details) {\n console.log(chalk.dim(confirmResult.error.details));\n }\n process.exitCode = 1;\n return;\n }\n\n if (!confirmResult?.success) return;\n\n const { companies } = confirmResult.value;\n\n if (companies.length === 0) {\n console.log(chalk.red(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n\n // 4. Select company (auto-select if only one)\n let selected: CompanyChoice;\n if (companies.length === 1) {\n const first = companies[0];\n if (!first) {\n console.log(chalk.red(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n selected = first;\n } else {\n // Key on `c.id`, not the array index, and resolve via `.find` —\n // `prompts` autocomplete returns the raw typed string on Enter when\n // the user hasn't arrow-key-highlighted a filtered choice, so an\n // array-index lookup ends up asking for `companies[\"Fluid\"]` and\n // failing with \"Invalid selection\". Same shape as `switch.ts`.\n const companyChoices = companies.map((c) => ({\n title: `${c.name} (${c.shopName})`,\n value: c.id,\n }));\n\n const selectResponse = await prompts({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = selectResponse[\"companyId\"] as number | undefined;\n\n if (companyId === undefined) {\n console.log(chalk.red(\"No company selected. Aborting.\"));\n process.exitCode = 1;\n return;\n }\n const choice = companies.find((c) => c.id === companyId);\n if (!choice) {\n console.log(chalk.red(\"Invalid selection. Aborting.\"));\n process.exitCode = 1;\n return;\n }\n selected = choice;\n }\n\n // 5. Store profile\n const name = profileName ?? selected.name;\n\n if (!(await confirmOverwrite(name))) {\n console.log(\n chalk.yellow(\"Login cancelled — existing profile not overwritten.\"),\n );\n return;\n }\n\n storeProfile(name, selected.jwt, selected.name);\n console.log(\n chalk.green(\n `Logged in as ${chalk.bold(selected.name)} (profile: ${chalk.bold(name)})`,\n ),\n );\n}\n\nexport const loginCommand = new Command(\"login\")\n .description(\"Authenticate with the Fluid API\")\n .option(\n \"-t, --token <token>\",\n \"API token (skips email flow). Prefer FLUID_TOKEN env var to avoid shell history exposure\",\n )\n .option(\"-e, --email <email>\", \"Email address for MFA login\")\n .option(\"-n, --name <name>\", \"Profile name (defaults to company name)\")\n .action(async (opts: { token?: string; email?: string; name?: string }) => {\n // Accept token from env var to avoid shell history / process listing exposure\n const token = opts.token ?? process.env[\"FLUID_TOKEN\"];\n if (token) {\n if (opts.token) {\n console.log(\n chalk.yellow(\n \"Warning: token passed via --token flag is visible in shell history and process listings. \" +\n \"Prefer the FLUID_TOKEN environment variable.\",\n ),\n );\n }\n await loginWithToken(token, opts.name);\n } else {\n await loginWithEmail(opts.email, opts.name);\n }\n });\n","/**\n * fluid logout — remove stored auth profile(s)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { readConfig, writeConfig } from \"../config/config.js\";\n\nexport const logoutCommand = new Command(\"logout\")\n .description(\"Remove stored authentication\")\n .option(\"-a, --all\", \"Remove all profiles\")\n .action((opts: { all?: boolean }) => {\n const config = readConfig();\n\n if (opts.all) {\n writeConfig({\n ...config,\n activeProfile: null,\n profiles: {},\n });\n console.log(chalk.green(\"All profiles removed.\"));\n return;\n }\n\n if (!config.activeProfile) {\n console.log(chalk.yellow(\"Not currently logged in.\"));\n return;\n }\n\n const profileName = config.activeProfile;\n const { [profileName]: _, ...remainingProfiles } = config.profiles;\n\n // Pick the first remaining profile as active, or null\n const nextActive = Object.keys(remainingProfiles)[0] ?? null;\n\n writeConfig({\n ...config,\n activeProfile: nextActive,\n profiles: remainingProfiles,\n });\n\n console.log(\n chalk.green(`Logged out of profile ${chalk.bold(profileName)}.`),\n );\n if (nextActive) {\n console.log(chalk.dim(`Switched to profile ${nextActive}.`));\n }\n });\n","/**\n * fluid whoami — show current auth profile and validate against API\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { validateToken } from \"../auth/fluid-api.js\";\n\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"Show the current authenticated profile\")\n .action(async () => {\n const profile = getActiveProfile();\n\n if (!profile) {\n console.log(\n chalk.yellow(\"Not logged in. Run `fluid login` to authenticate.\"),\n );\n process.exitCode = 1;\n return;\n }\n\n const spinner = ora(\"Verifying token...\").start();\n const result = await validateToken(profile.token);\n\n if (!result.success) {\n spinner.fail(chalk.red(\"Token is no longer valid.\"));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n console.log(chalk.dim(\"Run `fluid login` to re-authenticate.\"));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n });\n","/**\n * fluid switch — switch between companies (fetched from API, with local fallback)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n fetchUserCompanies,\n switchCompany,\n FLUID_API_ERROR,\n getFluidApiBase,\n type UserCompany,\n} from \"../auth/fluid-api.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\n\nasync function localSwitch(profileArg?: string): Promise<void> {\n const config = readConfig();\n const profileNames = Object.keys(config.profiles);\n\n if (profileNames.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n let targetProfile = profileArg;\n\n if (!targetProfile) {\n const profileChoices = profileNames.map((name) => ({\n title: name === config.activeProfile ? `${name} (active)` : name,\n value: name,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"profile\",\n message: \"Select a profile (type to search)\",\n choices: profileChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.value.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n targetProfile = response[\"profile\"] as string | undefined;\n\n if (!targetProfile) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n }\n\n if (!config.profiles[targetProfile]) {\n console.log(chalk.red(`Profile \"${targetProfile}\" not found.`));\n console.log(chalk.dim(`Available: ${profileNames.join(\", \")}`));\n process.exitCode = 1;\n return;\n }\n\n updateConfig((c) => ({ ...c, activeProfile: targetProfile! }));\n console.log(chalk.green(`Switched to profile ${chalk.bold(targetProfile)}.`));\n}\n\nasync function selectCompany(\n companies: UserCompany[],\n activeCompanyName: string | undefined,\n): Promise<UserCompany | undefined> {\n const companyChoices = companies.map((c) => ({\n title:\n c.name === activeCompanyName\n ? `${c.name} ${chalk.dim(\"(active)\")}`\n : c.name,\n value: c.id,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = response[\"companyId\"] as number | undefined;\n if (companyId === undefined) return undefined;\n return companies.find((c) => c.id === companyId);\n}\n\nasync function performSwitch(\n token: string,\n company: UserCompany,\n baseUrl?: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n const result = await switchCompany(token, company.id, baseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n } else {\n spinner.fail(chalk.red(result.error.message));\n if (result.error.details) {\n console.log(chalk.dim(result.error.details));\n }\n }\n process.exitCode = 1;\n return;\n }\n\n const { companyName, jwt } = result.value;\n\n updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createFluidProfile({\n name: companyName,\n token: jwt,\n companyName,\n baseUrl: baseUrl ?? getFluidApiBase(),\n }),\n },\n }));\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`,\n ),\n );\n}\n\nexport const switchCommand = new Command(\"switch\")\n .description(\"Switch between companies\")\n .argument(\"[profile]\", \"Company or profile name to switch to\")\n .action(async (profileArg?: string) => {\n const activeProfile = getActiveProfile();\n\n if (!activeProfile) {\n console.log(chalk.yellow(\"Not logged in. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n const token = activeProfile.token;\n const activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n const result = await fetchUserCompanies(token, activeBaseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n process.exitCode = 1;\n return;\n }\n spinner.warn(\n chalk.yellow(\n `Could not fetch companies from API: ${result.error.message}`,\n ),\n );\n console.log(chalk.dim(\"Falling back to locally stored profiles.\"));\n await localSwitch(profileArg);\n return;\n }\n\n const companies = result.value;\n spinner.succeed(\n `Found ${companies.length} company${companies.length === 1 ? \"\" : \"ies\"}`,\n );\n\n if (companies.length === 0) {\n console.log(chalk.yellow(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n\n // If a profile argument was passed, match against API companies first\n if (profileArg) {\n const match = companies.find(\n (c) => c.name.toLowerCase() === profileArg.toLowerCase(),\n );\n\n if (match) {\n await performSwitch(token, match, activeBaseUrl);\n return;\n }\n\n // Fall back to local profile matching\n const config = readConfig();\n if (config.profiles[profileArg]) {\n updateConfig((c) => ({ ...c, activeProfile: profileArg! }));\n console.log(\n chalk.green(`Switched to profile ${chalk.bold(profileArg)}.`),\n );\n return;\n }\n\n console.log(chalk.red(`Company or profile \"${profileArg}\" not found.`));\n process.exitCode = 1;\n return;\n }\n\n // Interactive selection\n const selected = await selectCompany(companies, activeCompanyName);\n if (!selected) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n\n await performSwitch(token, selected, activeBaseUrl);\n });\n","/**\n * Auto-discover @fluid-app CLI plugins.\n *\n * Three discovery strategies run in order:\n *\n * 1a. **node_modules scan (cwd)** — look in `<cwd>/node_modules/@fluid-app/`\n * for directories whose names match the plugin naming convention.\n * This is the primary mechanism for project-local plugin installs.\n *\n * 1b. **node_modules scan (CLI install location)** — look in the\n * `node_modules/@fluid-app/` directory containing the CLI core package\n * itself. This covers global installs where plugins are sibling packages\n * under the same global `node_modules/`.\n *\n * 2. **Workspace scan** — walk upward from the CLI core package root to the\n * monorepo workspace root, then scan `packages/` for sibling plugin\n * packages. This covers the pnpm-workspace development case where\n * plugins are not symlinked into `node_modules`.\n *\n * Only first-party @fluid-app scoped packages are loaded.\n */\n\nimport { existsSync, readFileSync, readdirSync, realpathSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst PLUGIN_SCOPE = \"@fluid-app\";\n\n/**\n * A plugin package name must match one of these patterns:\n * - @fluid-app/fluid-cli-* (standard)\n * - @fluid-app/*-cli-commands (v2025-06 style)\n */\nfunction isPluginName(packageName: string): boolean {\n if (!packageName.startsWith(`${PLUGIN_SCOPE}/`)) return false;\n const bare = packageName.slice(`${PLUGIN_SCOPE}/`.length);\n return bare.startsWith(\"fluid-cli-\") || bare.endsWith(\"-cli-commands\");\n}\n\n// Strategy 1: node_modules scan (production / published installs)\n\nfunction discoverFromNodeModules(basePath: string): DiscoveredPlugin[] {\n const scopeDir = join(basePath, \"node_modules\", PLUGIN_SCOPE);\n\n if (!existsSync(scopeDir)) return [];\n\n return readdirSync(scopeDir, { withFileTypes: true })\n .filter(\n (entry) =>\n (entry.isDirectory() || entry.isSymbolicLink()) &&\n isPluginName(`${PLUGIN_SCOPE}/${entry.name}`),\n )\n .map((entry) => {\n const name = `${PLUGIN_SCOPE}/${entry.name}`;\n const entryDir = join(scopeDir, entry.name);\n // Resolve symlinks (pnpm workspace links) to file:// URLs so the\n // dynamic import works regardless of pnpm's strict module resolution.\n try {\n const realDir = realpathSync(entryDir);\n const distEntry = join(realDir, \"dist\", \"index.mjs\");\n if (existsSync(distEntry)) {\n return { name, importSpecifier: pathToFileURL(distEntry).href };\n }\n } catch {\n // Broken symlink or other fs error — fall through to bare specifier\n }\n // Fallback to bare specifier for non-workspace (published) installs\n return { name, importSpecifier: name };\n });\n}\n\n// Strategy 2: workspace scan (pnpm monorepo development)\n\nfunction findWorkspaceRoot(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n if (\n existsSync(join(dir, \"pnpm-workspace.yaml\")) ||\n existsSync(join(dir, \"pnpm-workspace.yml\"))\n ) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction readPackageName(dir: string): string | null {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n name?: string;\n };\n return pkg.name ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface DiscoveredPlugin {\n name: string;\n importSpecifier: string;\n}\n\nexport interface PluginDiscoveryOptions {\n /**\n * Prefer plugins installed beside this CLI over same-named packages in the\n * target project's node_modules. Desktop callers use this so an older\n * project-local plugin cannot override the command contract bundled with\n * the app. Normal project-local CLI invocations keep the existing order.\n */\n preferInstallation?: boolean;\n /** Test seam for the directory containing the CLI installation. */\n installationBasePath?: string;\n}\n\nfunction discoverFromWorkspace(startDir: string): DiscoveredPlugin[] {\n const workspaceRoot = findWorkspaceRoot(startDir);\n if (!workspaceRoot) return [];\n\n const results: DiscoveredPlugin[] = [];\n const packagesDir = join(workspaceRoot, \"packages\");\n if (!existsSync(packagesDir)) return [];\n\n // Scan exactly two levels deep under packages/ (e.g. packages/cli/themes,\n // packages/cli/v2025-06). This matches the monorepo convention where all\n // packages live at packages/<domain>/<package>/.\n // If a plugin is added at a different depth, update this scan accordingly.\n let domainDirs: string[];\n try {\n domainDirs = readdirSync(packagesDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(packagesDir, e.name));\n } catch {\n return [];\n }\n\n for (const domainDir of domainDirs) {\n let subDirs: string[];\n try {\n subDirs = readdirSync(domainDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(domainDir, e.name));\n } catch {\n continue;\n }\n\n for (const subDir of subDirs) {\n const name = readPackageName(subDir);\n if (!name || !name.startsWith(`${PLUGIN_SCOPE}/`) || !isPluginName(name))\n continue;\n\n const distEntry = join(subDir, \"dist\", \"index.mjs\");\n if (!existsSync(distEntry)) {\n continue;\n }\n\n results.push({\n name,\n importSpecifier: pathToFileURL(distEntry).href,\n });\n }\n }\n\n return results;\n}\n\n// Exported API\n\n/** Resolved once — the CLI core package root (`packages/cli/core/`). */\nexport const corePackageDir = dirname(\n dirname(dirname(fileURLToPath(import.meta.url))),\n);\n\n/**\n * Discover installed plugin packages. Returns a de-duplicated, sorted list\n * of `{ name, importSpecifier }` objects.\n *\n * @param basePath - Directory to scan for `node_modules/@fluid-app/`\n * @param searchFrom - Starting directory for workspace root detection\n * (walked upward via `findWorkspaceRoot`). Pass `null` to skip workspace\n * scanning (useful in tests). Defaults to `corePackageDir`.\n */\nexport function discoverPlugins(\n basePath: string,\n searchFrom?: string | null,\n options: PluginDiscoveryOptions = {},\n): DiscoveredPlugin[] {\n const seen = new Set<string>();\n const results: DiscoveredPlugin[] = [];\n\n const addPlugins = (plugins: DiscoveredPlugin[]) => {\n for (const plugin of plugins) {\n if (seen.has(plugin.name)) continue;\n seen.add(plugin.name);\n results.push(plugin);\n }\n };\n\n const cliParent =\n options.installationBasePath ?? dirname(dirname(dirname(corePackageDir)));\n const projectPlugins = () => discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath ? [] : discoverFromNodeModules(cliParent);\n const workspacePlugins = () => {\n if (searchFrom === null) return [];\n return discoverFromWorkspace(searchFrom ?? corePackageDir);\n };\n\n if (options.preferInstallation) {\n addPlugins(installationPlugins());\n // In a monorepo development build, resolveFluidBinary() deliberately\n // realpaths the CLI into packages/cli/core. Its sibling plugins are then\n // discovered from the workspace rather than an installation-level\n // node_modules, so they are part of the same trusted CLI installation.\n addPlugins(workspacePlugins());\n addPlugins(projectPlugins());\n } else {\n addPlugins(projectPlugins());\n addPlugins(installationPlugins());\n addPlugins(workspacePlugins());\n }\n\n return results.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Dynamically import a plugin module and return its default export.\n *\n * @internal Not intended for external callers. Only called with specifiers\n * produced by {@link discoverPlugins}:\n * - bare package names (e.g. `@fluid-app/fluid-cli-portal`) from the\n * node_modules scan, validated by {@link isPluginName}.\n * - `file://` URLs from {@link discoverFromWorkspace}, which constructs\n * them internally from validated workspace paths (`packages/` tree,\n * `dist/index.mjs`). These are trusted internal specifiers.\n */\nexport async function importPlugin(specifier: string): Promise<unknown> {\n // file:// URLs are trusted — they originate from discoverFromWorkspace\n // which builds them from validated workspace paths under packages/.\n // For bare package names, verify they match the plugin naming convention.\n if (!specifier.startsWith(\"file://\") && !isPluginName(specifier)) {\n throw new Error(`Refusing to import non-plugin package: ${specifier}`);\n }\n const mod = (await import(specifier)) as Record<string, unknown>;\n return mod[\"default\"] ?? mod;\n}\n","/**\n * Format one-line diagnostics naming a CLI plugin build and where it was\n * resolved from. The resolved path is the load-bearing detail: a workspace\n * build and a published copy share the same name and version, so the path is\n * the only thing that distinguishes them. See CURRENT-3218.\n */\n\nimport { fileURLToPath } from \"node:url\";\n\nexport interface PluginLoadInfo {\n readonly name: string;\n readonly version: string;\n /**\n * Where the plugin was resolved from — an absolute `file://` URL (workspace\n * or published install, resolved upstream) or, only when resolution failed,\n * a bare package name.\n */\n readonly importSpecifier: string;\n /**\n * Whether installation-bundled plugins were preferred over project-local\n * ones (`FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1`, set by Mist).\n */\n readonly preferInstallation: boolean;\n}\n\nexport interface PluginLoadFailureInfo {\n readonly name: string;\n readonly importSpecifier: string;\n readonly preferInstallation: boolean;\n readonly message: string;\n}\n\nexport function modeLabel(preferInstallation: boolean): string {\n return preferInstallation ? \"installation-preferred\" : \"project-first\";\n}\n\n/**\n * Render a specifier for display: `file://` URLs become absolute filesystem\n * paths; anything else is shown verbatim. Never throws — a malformed `file://`\n * specifier falls back to its raw form so a diagnostic can never turn a\n * successful load into a reported failure.\n */\nexport function displaySource(importSpecifier: string): string {\n if (!importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return fileURLToPath(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n\nexport function formatPluginLoadLine(info: PluginLoadInfo): string {\n return `Loaded plugin ${info.name}@${info.version} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]`;\n}\n\nexport function formatPluginLoadFailure(info: PluginLoadFailureInfo): string {\n return `Failed to load plugin ${info.name} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]: ${info.message}`;\n}\n","/**\n * Resolve a plugin import specifier to a concrete path for diagnostics.\n *\n * The node_modules discovery strategy falls back to a bare package name when it\n * cannot realpath a workspace symlink — precisely the published-install case\n * where the path is the only thing that would reveal a stale plugin winning.\n * Resolving the bare specifier recovers that path. See CURRENT-3218.\n */\n\nexport type Resolver = (specifier: string) => string;\n\nconst defaultResolver: Resolver = (specifier) => import.meta.resolve(specifier);\n\n/**\n * Return a `file://` URL for `importSpecifier`. `file://` specifiers (already\n * resolved by discovery) pass through untouched; bare specifiers are resolved\n * via `resolve`. If resolution throws, the bare specifier is returned so a\n * diagnostic degrades gracefully rather than failing the load.\n */\nexport function resolveLoadPath(\n importSpecifier: string,\n resolve: Resolver = defaultResolver,\n): string {\n if (importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return resolve(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n","/**\n * Decide whether to print the per-plugin \"Loaded plugin …\" diagnostics.\n *\n * A monorepo checkout resolves ~a dozen plugin packages, so emitting a line\n * for each on every command (including `--help` and tab-completion, and into\n * Mist's captured stderr dialog) is noise. The success diagnostics are gated\n * behind an explicit opt-in; load *failures* are always surfaced by the loader\n * regardless of this flag. See CURRENT-3218.\n */\n\nfunction isTruthyFlag(value: string | undefined): boolean {\n return value === \"1\" || value === \"true\";\n}\n\nexport function shouldLogPluginLoads(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n if (argv.includes(\"--verbose\")) return true;\n return isTruthyFlag(env[\"FLUID_CLI_DEBUG\"] ?? env[\"FLUID_CLI_VERBOSE\"]);\n}\n","/**\n * Plugin loader — orchestrates discovery and registration\n */\n\nimport type { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport { getAuthToken } from \"../auth/token.js\";\nimport { readConfig } from \"../config/config.js\";\nimport type { FluidPlugin, PluginContext } from \"./types.js\";\nimport { discoverPlugins, importPlugin } from \"./discovery.js\";\nimport {\n formatPluginLoadLine,\n formatPluginLoadFailure,\n} from \"./format-load-line.js\";\nimport { resolveLoadPath } from \"./resolve-load-path.js\";\nimport { shouldLogPluginLoads } from \"./should-log-plugin-loads.js\";\n\nfunction isFluidPlugin(value: unknown): value is FluidPlugin {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj[\"name\"] === \"string\" &&\n typeof obj[\"version\"] === \"string\" &&\n typeof obj[\"register\"] === \"function\"\n );\n}\n\n/**\n * Discover, import, and register all installed plugins\n */\nexport async function loadPlugins(\n program: Command,\n basePath: string,\n): Promise<void> {\n const preferInstallation =\n process.env[\"FLUID_CLI_PREFER_INSTALLATION_PLUGINS\"] === \"1\";\n const discovered = discoverPlugins(basePath, undefined, {\n preferInstallation,\n });\n const { enabledPlugins } = readConfig();\n\n // If enabledPlugins is set, only load explicitly allowed plugins.\n // This acts as an allow-list to prevent accidental supply-chain execution.\n const allowedSet = enabledPlugins !== null ? new Set(enabledPlugins) : null;\n const plugins = allowedSet\n ? discovered.filter((p) => allowedSet.has(p.name))\n : discovered;\n\n if (plugins.length === 0) return;\n\n const ctx: PluginContext = {\n program,\n getAuthToken,\n configDir: getConfigDir(),\n };\n\n // Success diagnostics are opt-in (a checkout resolves ~a dozen plugins);\n // load failures below are always surfaced. See CURRENT-3218.\n const verbose = shouldLogPluginLoads();\n\n for (const { name, importSpecifier } of plugins) {\n // Resolve to a concrete path so a published install is distinguishable\n // from a workspace build at a glance.\n const source = resolveLoadPath(importSpecifier);\n try {\n const exported = await importPlugin(importSpecifier);\n\n if (!isFluidPlugin(exported)) {\n console.warn(\n chalk.yellow(`Warning: ${name} does not export a valid FluidPlugin`),\n );\n continue;\n }\n\n await exported.register(ctx);\n\n if (verbose) {\n console.error(\n chalk.dim(\n formatPluginLoadLine({\n name: exported.name,\n version: exported.version,\n importSpecifier: source,\n preferInstallation,\n }),\n ),\n );\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Always name what failed to load and from where — this is exactly the\n // invisible-artifact failure the diagnostic exists to catch.\n console.warn(\n chalk.yellow(\n `Warning: ${formatPluginLoadFailure({\n name,\n importSpecifier: source,\n preferInstallation,\n message,\n })}`,\n ),\n );\n }\n }\n}\n","/**\n * Tell an interactive user, at most once a day, that a newer fluid CLI is\n * on npm. The check never holds a command open: a run prints what the last\n * check found, and a stale cache is refreshed by a detached child process\n * for next time.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, sep } from \"node:path\";\n\nexport const PACKAGE_NAME = \"@fluid-app/fluid-cli\";\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\n/** The argument the CLI entry point treats as \"refresh the cache and exit\". */\nexport const REFRESH_ARG = \"__refresh-update-check\";\nconst FETCH_TIMEOUT_MS = 5000;\nconst CACHE_FILE = \"update-check.json\";\n\nexport interface UpdateCache {\n /** When a check was last started, successful or not. */\n readonly checkedAt: string;\n /** The newest version any check has seen; null before the first success. */\n readonly latest: string | null;\n}\n\nexport interface UpdateCheckEnvironment {\n readonly env: NodeJS.ProcessEnv;\n readonly stdoutIsTTY: boolean;\n readonly stderrIsTTY: boolean;\n /** Real path of the running CLI entry point. */\n readonly entryPath: string;\n /** `process.versions`; an `electron` entry means a bundling app runs us. */\n readonly versions?: Partial<Record<string, string>>;\n}\n\n/** Whether an Electron app, such as Mist, is running the CLI it bundles. */\nexport function isElectronRun(\n env: NodeJS.ProcessEnv,\n versions: Partial<Record<string, string>> = {},\n): boolean {\n return Boolean(env[\"ELECTRON_RUN_AS_NODE\"] || versions[\"electron\"]);\n}\n\n/**\n * Only an installed CLI used by a person checks. Scripts, CI, piped output\n * (completion and `--json` among them), a workspace build and a copy an\n * Electron app bundles (the app updates it) stay quiet.\n */\nexport function shouldCheckForUpdates({\n env,\n stdoutIsTTY,\n stderrIsTTY,\n entryPath,\n versions,\n}: UpdateCheckEnvironment): boolean {\n if (env[\"FLUID_NO_UPDATE_CHECK\"] || env[\"NO_UPDATE_NOTIFIER\"]) return false;\n if (env[\"CI\"]) return false;\n if (isElectronRun(env, versions)) return false;\n if (!stdoutIsTTY || !stderrIsTTY) return false;\n return entryPath.includes(`${sep}node_modules${sep}`);\n}\n\nfunction parseVersion(version: string): [number, number, number] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version.trim());\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\n/** True when `latest` is a newer release than `current`. Prereleases never count. */\nexport function isNewer(current: string, latest: string): boolean {\n const a = parseVersion(current);\n const b = parseVersion(latest);\n if (!a || !b) return false;\n for (let i = 0; i < 3; i += 1) {\n if (b[i]! !== a[i]!) return b[i]! > a[i]!;\n }\n return false;\n}\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"yarn\" | \"yarn-classic\" | \"bun\";\n\n/** How the running CLI was installed, which decides the update command. */\nexport type InstallKind =\n | { readonly kind: \"global\"; readonly manager: PackageManager }\n | { readonly kind: \"npx\" }\n | {\n readonly kind: \"local\";\n readonly manager: PackageManager;\n readonly projectDir: string;\n };\n\nconst LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n [\"npm-shrinkwrap.json\", \"npm\"],\n];\n\nfunction projectManager(\n projectDir: string,\n exists: (path: string) => boolean,\n): PackageManager {\n // A workspace member has its lockfile at the workspace root, above it.\n for (let dir = projectDir; ; dir = dirname(dir)) {\n for (const [file, manager] of LOCKFILES) {\n if (!exists(join(dir, file))) continue;\n if (manager !== \"yarn\") return manager;\n return exists(join(dir, \".yarnrc.yml\")) ? \"yarn\" : \"yarn-classic\";\n }\n if (dirname(dir) === dir) return \"npm\";\n }\n}\n\n/**\n * Work out from the entry point's real path how the CLI was installed: an\n * npx cache run, a global install (npm's `lib/node_modules`, or npm on\n * Windows, pnpm's and yarn's global directories), or else a project's own\n * `node_modules`.\n */\nexport function detectInstallKind(\n entryPath: string,\n exists: (path: string) => boolean = existsSync,\n): InstallKind {\n const path = entryPath.replaceAll(\"\\\\\", \"/\");\n if (path.includes(\"/_npx/\")) return { kind: \"npx\" };\n if (/\\/pnpm\\/global\\//i.test(path))\n return { kind: \"global\", manager: \"pnpm\" };\n if (/\\/yarn\\/global\\//i.test(path) || path.includes(\"/.yarn-global/\")) {\n return { kind: \"global\", manager: \"yarn-classic\" };\n }\n if (/\\/\\.bun\\/install\\/global\\//.test(path)) {\n return { kind: \"global\", manager: \"bun\" };\n }\n const modules = path.indexOf(\"/node_modules/\");\n const before = modules === -1 ? path : path.slice(0, modules);\n const projectDir = entryPath.slice(0, modules === -1 ? 0 : modules);\n // npm's global root is `<prefix>/lib`, or `%APPDATA%\\npm` on Windows, and\n // neither holds a package.json. A project that happens to live in a\n // directory named `lib` does, and is updated in place.\n const npmGlobalShape = before.endsWith(\"/lib\") || /\\/npm$/i.test(before);\n if (npmGlobalShape && !exists(join(projectDir, \"package.json\"))) {\n return { kind: \"global\", manager: \"npm\" };\n }\n return {\n kind: \"local\",\n manager: projectManager(projectDir, exists),\n projectDir,\n };\n}\n\nconst PLUGINS_NOTE = \"(and any @fluid-app/fluid-cli-* plugins you use)\";\n\nfunction globalCommand(manager: PackageManager): string {\n switch (manager) {\n case \"npm\":\n return `npm install -g ${PACKAGE_NAME}`;\n case \"pnpm\":\n return `pnpm add -g ${PACKAGE_NAME}@latest`;\n case \"yarn\":\n case \"yarn-classic\":\n return `yarn global add ${PACKAGE_NAME}@latest`;\n case \"bun\":\n return `bun add -g ${PACKAGE_NAME}@latest`;\n }\n}\n\nfunction localCommand(manager: PackageManager): string {\n switch (manager) {\n case \"npm\":\n return `npm install ${PACKAGE_NAME}@latest`;\n case \"pnpm\":\n return `pnpm update --latest ${PACKAGE_NAME}`;\n case \"yarn\":\n return `yarn up ${PACKAGE_NAME}@latest`;\n case \"yarn-classic\":\n return `yarn upgrade --latest ${PACKAGE_NAME}`;\n case \"bun\":\n return `bun update --latest ${PACKAGE_NAME}`;\n }\n}\n\nfunction updateInstruction(install: InstallKind): string {\n switch (install.kind) {\n case \"global\":\n return `Run: ${globalCommand(install.manager)} ${PLUGINS_NOTE}\\n`;\n case \"npx\":\n return `Run: npx ${PACKAGE_NAME}@latest to use the latest version\\n`;\n case \"local\":\n return `Run in ${install.projectDir}: ${localCommand(install.manager)} ${PLUGINS_NOTE}\\n`;\n }\n}\n\nexport function updateNotice(\n current: string,\n latest: string,\n install: InstallKind = { kind: \"global\", manager: \"npm\" },\n): string | null {\n if (!isNewer(current, latest)) return null;\n return (\n `\\nUpdate available for fluid: ${current} → ${latest}\\n` +\n updateInstruction(install) +\n `Set FLUID_NO_UPDATE_CHECK=1 to stop these notices.\\n`\n );\n}\n\nexport function readUpdateCache(configDir: string): UpdateCache | null {\n try {\n const data = JSON.parse(\n readFileSync(join(configDir, CACHE_FILE), \"utf8\"),\n ) as Partial<UpdateCache>;\n if (typeof data.checkedAt !== \"string\") return null;\n const latest = typeof data.latest === \"string\" ? data.latest : null;\n return { checkedAt: data.checkedAt, latest };\n } catch {\n return null;\n }\n}\n\n/**\n * Write the cache, reporting whether it landed. The JSON goes to a fresh\n * file opened exclusively, then is renamed over the cache: a rename replaces\n * a symlink planted at the cache path instead of writing through it, so a\n * shared FLUID_CONFIG_DIR can't aim this write at another of the user's files.\n */\nexport function writeUpdateCache(\n configDir: string,\n cache: UpdateCache,\n): boolean {\n const temp = join(\n configDir,\n `.${CACHE_FILE}.${randomBytes(6).toString(\"hex\")}`,\n );\n try {\n mkdirSync(configDir, { recursive: true });\n writeFileSync(temp, JSON.stringify(cache) + \"\\n\", { flag: \"wx\" });\n renameSync(temp, join(configDir, CACHE_FILE));\n return true;\n } catch {\n // A read-only config directory only costs the notice.\n try {\n rmSync(temp, { force: true });\n } catch {\n // Nothing was written if the directory itself is unusable.\n }\n return false;\n }\n}\n\nexport function isStale(cache: UpdateCache | null, now: Date): boolean {\n if (!cache) return true;\n const checkedAt = Date.parse(cache.checkedAt);\n return (\n Number.isNaN(checkedAt) || now.getTime() - checkedAt >= CHECK_INTERVAL_MS\n );\n}\n\nexport async function fetchLatestVersion(\n fetchImpl: typeof fetch = fetch,\n): Promise<string | null> {\n try {\n const response = await fetchImpl(\n `https://registry.npmjs.org/${PACKAGE_NAME}/latest`,\n { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { version?: unknown };\n return typeof body.version === \"string\" ? body.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask npm for the latest version and record it. Runs in the detached child;\n * a failure leaves the last known version and the throttle stamp in place.\n */\nexport async function refreshUpdateCache(\n configDir: string,\n fetchImpl: typeof fetch = fetch,\n now: Date = new Date(),\n): Promise<void> {\n const latest = await fetchLatestVersion(fetchImpl);\n if (latest) {\n writeUpdateCache(configDir, { checkedAt: now.toISOString(), latest });\n }\n}\n\n/** Start `node <entry> __refresh-update-check` detached, so this run never waits on npm. */\nexport function spawnRefresh(entryPath: string): void {\n try {\n const child = spawn(process.execPath, [entryPath, REFRESH_ARG], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // No refresh this time; the throttle stamp retries tomorrow.\n }\n}\n\nexport interface StartUpdateCheckOptions extends UpdateCheckEnvironment {\n readonly currentVersion: string;\n readonly configDir: string;\n readonly now?: Date;\n /** Called with the notice when the process exits. */\n readonly onExit?: (listener: () => void) => void;\n readonly refresh?: (entryPath: string) => void;\n}\n\n/**\n * Print the cached notice when the command finishes and, when the last\n * check started a day ago or more, stamp the cache and refresh it in a\n * detached process. The stamp throttles failed and concurrent checks to one\n * a day while keeping the last known version, and its notice, in place.\n */\nexport function startUpdateCheck(options: StartUpdateCheckOptions): void {\n if (!shouldCheckForUpdates(options)) return;\n\n const now = options.now ?? new Date();\n const cache = readUpdateCache(options.configDir);\n const notice = cache?.latest\n ? updateNotice(\n options.currentVersion,\n cache.latest,\n detectInstallKind(options.entryPath),\n )\n : null;\n if (notice) {\n const onExit =\n options.onExit ??\n ((listener: () => void) => process.once(\"exit\", listener));\n onExit(() => process.stderr.write(notice));\n }\n\n if (!isStale(cache, now)) return;\n const stamped = writeUpdateCache(options.configDir, {\n checkedAt: now.toISOString(),\n latest: cache?.latest ?? null,\n });\n // Without the stamp there is no throttle, and the child couldn't record\n // what it found either, so an unwritable cache never starts a refresh.\n if (stamped) (options.refresh ?? spawnRefresh)(options.entryPath);\n}\n","#!/usr/bin/env node\n\nimport { createRequire } from \"node:module\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { commandsCommand } from \"../commands/commands.js\";\nimport { completeCommand, completionCommand } from \"../commands/completion.js\";\nimport { loginCommand } from \"../commands/login.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport { loadPlugins } from \"../plugins/loader.js\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport {\n REFRESH_ARG,\n refreshUpdateCache,\n startUpdateCheck,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n// The detached update check re-runs this entry point; it only refreshes the\n// cache, without loading plugins or parsing commands.\nif (process.argv[2] === REFRESH_ARG) {\n await refreshUpdateCache(getConfigDir());\n process.exit(0);\n}\n\nconst packageRoot = process.cwd();\n\nconst program = new Command();\n\nprogram.name(\"fluid\").description(\"Fluid Commerce CLI\").version(version);\n\n// Built-in auth commands\nprogram.addCommand(loginCommand);\nprogram.addCommand(logoutCommand);\nprogram.addCommand(whoamiCommand);\nprogram.addCommand(switchCommand);\n\n// Discovery: the command catalog and shell completion\nprogram.addCommand(commandsCommand);\nprogram.addCommand(completionCommand);\nprogram.addCommand(completeCommand, { hidden: true });\n\nstartUpdateCheck({\n currentVersion: version,\n configDir: getConfigDir(),\n env: process.env,\n stdoutIsTTY: Boolean(process.stdout.isTTY),\n stderrIsTTY: Boolean(process.stderr.isTTY),\n entryPath: realpathSync(fileURLToPath(import.meta.url)),\n versions: process.versions,\n});\n\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\nprogram.parse(process.argv, { from: \"node\" });\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,MAAM,EAAE,SAAA,cADQ,cAAc,OAAO,KAAK,IAAI,CAClB,qBAAqB;AAEjD,SAAS,MAAM,OAA6B;CAC1C,MAAM,OAAO,MAAM,UAAU,KAAK,QAAQ;EACxC,MAAM,OAAO,IAAI,WAAW,GAAG,IAAI,KAAK,OAAO,IAAI;AACnD,SAAO,IAAI,WAAW,IAAI,KAAK,KAAK,IAAI,KAAK;GAC7C;AACF,QAAO,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,IAAI;;AAG3C,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,WAAW,QAAQ,QAAQ,UAAU,MAAM,SAAS;CAC1D,MAAM,QAAQ,KAAK,IACjB,IACA,KAAK,IAAI,GAAG,GAAG,SAAS,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,CAAC,CAC7D;AACD,QAAO,SACJ,KAAK,UAAU;EACd,MAAM,OAAO,MAAM,MAAM;EACzB,MAAM,UAAU,MAAM,YAAY,MAAM,MAAM,EAAE,CAAC,MAAM;AACvD,SAAO,UAAU,GAAG,KAAK,OAAO,MAAM,CAAC,IAAI,YAAY;GACvD,CACD,KAAK,KAAK;;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],"sources":["../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../src/auth/pending-login.ts","../../src/auth/profiles.ts","../../src/commands/login.ts","../../src/commands/logout.ts","../../src/commands/whoami.ts","../../src/commands/switch.ts","../../src/plugins/discovery.ts","../../src/plugins/format-load-line.ts","../../src/plugins/resolve-load-path.ts","../../src/plugins/should-log-plugin-loads.ts","../../src/plugins/loader.ts","../../src/update/notifier.ts","../../src/bin/fluid.ts"],"sourcesContent":["/**\n * fluid commands — list every installed command, or print the catalog as\n * JSON for agents and documentation generators.\n */\n\nimport { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport {\n filterCatalog,\n rootCommand,\n walkCommands,\n type CatalogEntry,\n} from \"../catalog/walk.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\nfunction usage(entry: CatalogEntry): string {\n const args = entry.arguments.map((arg) => {\n const name = arg.variadic ? `${arg.name}...` : arg.name;\n return arg.required ? `<${name}>` : `[${name}]`;\n });\n return [entry.command, ...args].join(\" \");\n}\n\nexport function formatCatalogText(entries: readonly CatalogEntry[]): string {\n const runnable = entries.filter((entry) => entry.runnable);\n const width = Math.min(\n 48,\n Math.max(0, ...runnable.map((entry) => usage(entry).length)),\n );\n return runnable\n .map((entry) => {\n const line = usage(entry);\n const summary = entry.description.split(\"\\n\", 1)[0] ?? \"\";\n return summary ? `${line.padEnd(width)} ${summary}` : line;\n })\n .join(\"\\n\");\n}\n\nexport const commandsCommand = new Command(\"commands\")\n .description(\"List installed commands; --json prints the full catalog\")\n .argument(\"[prefix...]\", \"Only list commands under this one, e.g. `domains`\")\n .option(\"--json\", \"Print the catalog as JSON\", false)\n .action((prefix: string[], opts: { json: boolean }, command: Command) => {\n const root = rootCommand(command);\n\n const entries = filterCatalog(walkCommands(root), root, prefix);\n if (entries.length === 0) {\n process.stderr.write(\n JSON.stringify({ error: `No command named \"${prefix.join(\" \")}\".` }) +\n \"\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n if (opts.json) {\n process.stdout.write(\n JSON.stringify(\n { cli: root.name(), version, commands: entries },\n null,\n 2,\n ) + \"\\n\",\n );\n return;\n }\n process.stdout.write(formatCatalogText(entries) + \"\\n\");\n });\n","/**\n * Shell completion. The scripts `fluid completion <shell>` prints pipe the\n * words typed so far into the hidden `fluid __complete`, so completions come\n * from the plugins actually installed rather than a list frozen at install.\n * The words go over stdin, never argv: a half-typed `--token <value>` must\n * not show up in another user's process list.\n */\n\nimport type { Command, Option } from \"commander\";\nimport { visibleOptions, visibleSubcommands } from \"../catalog/walk.js\";\n\nexport const SHELLS = [\"bash\", \"zsh\", \"fish\"] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nexport interface Candidate {\n readonly value: string;\n readonly description: string;\n}\n\nfunction findOption(chain: readonly Command[], word: string): Option | null {\n const flag = word.split(\"=\", 1)[0] ?? word;\n for (const command of [...chain].reverse()) {\n const match = command.options.find(\n (option) => option.long === flag || option.short === flag,\n );\n if (match) return match;\n }\n return null;\n}\n\nfunction splitAssignment(word: string): [string, string] {\n const at = word.indexOf(\"=\");\n return [word.slice(0, at), word.slice(at + 1)];\n}\n\nfunction choicesFor(option: Option, typed: string): Candidate[] {\n return (option.argChoices ?? [])\n .filter((choice) => choice.startsWith(typed))\n .map((choice) => ({ value: choice, description: \"\" }));\n}\n\nfunction findSubcommand(command: Command, word: string): Command | null {\n return (\n visibleSubcommands(command).find(\n (sub) => sub.name() === word || sub.aliases().includes(word),\n ) ?? null\n );\n}\n\n/**\n * Complete the last of `words`, the words after the program name.\n * Where a flag's value is expected, offers the flag's choices if it has\n * any; otherwise returns nothing so the shell falls back to files.\n */\nexport function completeWords(\n root: Command,\n words: readonly string[],\n): Candidate[] {\n const partial = words.at(-1) ?? \"\";\n const chain: Command[] = [root];\n let current = root;\n let awaitingValue: Option | null = null;\n let operandsOnly = false;\n // Operands typed for `current`; only the first can name a subcommand.\n let operands = 0;\n\n const prior = words.slice(0, -1);\n for (const [index, word] of prior.entries()) {\n if (awaitingValue) {\n // Bash splits `--flag=value` at the `=`, so the value follows it.\n if (word !== \"=\" || prior[index - 1] === \"=\") awaitingValue = null;\n continue;\n }\n if (!operandsOnly && word === \"--\") {\n operandsOnly = true;\n continue;\n }\n if (!operandsOnly && word.startsWith(\"-\")) {\n const option = findOption(chain, word);\n awaitingValue = option?.required && !word.includes(\"=\") ? option : null;\n continue;\n }\n const sub = operands === 0 ? findSubcommand(current, word) : null;\n if (sub) {\n current = sub;\n chain.push(sub);\n } else {\n operands += 1;\n }\n }\n\n if (awaitingValue) {\n // After bash's split the partial is the bare `=` before any value.\n const typed = partial === \"=\" ? \"\" : partial;\n return choicesFor(awaitingValue, typed);\n }\n\n if (!operandsOnly && partial.startsWith(\"--\") && partial.includes(\"=\")) {\n // zsh and fish keep `--flag=value` as one word, and so must the reply.\n const [flag = \"\", typed = \"\"] = splitAssignment(partial);\n const option = findOption(chain, flag);\n if (!option?.required && !option?.optional) return [];\n return choicesFor(option, typed).map((choice) => ({\n ...choice,\n value: `${flag}=${choice.value}`,\n }));\n }\n\n if (!operandsOnly && partial.startsWith(\"-\")) {\n const seen = new Set<string>();\n const candidates: Candidate[] = [];\n for (const command of [...chain].reverse()) {\n for (const option of visibleOptions(command)) {\n // The program's --version belongs to `fluid` alone.\n if (option.long === \"--version\" && command !== current) continue;\n for (const value of [option.long, option.short]) {\n if (!value || seen.has(value)) continue;\n seen.add(value);\n candidates.push({ value, description: option.description });\n }\n }\n }\n candidates.push({ value: \"--help\", description: \"Show help\" });\n return candidates.filter((c) => c.value.startsWith(partial));\n }\n\n const candidates: Candidate[] = [];\n if (operands === 0) {\n for (const sub of visibleSubcommands(current)) {\n for (const name of [sub.name(), ...sub.aliases()]) {\n candidates.push({ value: name, description: sub.description() });\n }\n }\n }\n const args = current.registeredArguments;\n const last = args.at(-1);\n const argument = args[operands] ?? (last?.variadic ? last : undefined);\n for (const choice of argument?.argChoices ?? []) {\n candidates.push({\n value: choice,\n description: argument?.description ?? \"\",\n });\n }\n return candidates.filter((c) => c.value.startsWith(partial));\n}\n\n/**\n * The words the scripts pipe in: each followed by a NUL, the program name\n * first. Returns the words after the program name, at least one.\n */\nexport function parseCompletionInput(input: string): string[] {\n const words = input.split(\"\\0\");\n // The text after the last NUL is the empty tail of the final terminator.\n words.pop();\n const typed = words.slice(1);\n return typed.length > 0 ? typed : [\"\"];\n}\n\nfunction firstLine(text: string): string {\n return text.split(\"\\n\", 1)[0]?.trim() ?? \"\";\n}\n\n/** One candidate per line, in the shape each shell's script reads. */\nexport function formatCandidates(\n candidates: readonly Candidate[],\n shell: Shell,\n): string {\n const lines = candidates.map(({ value, description }) => {\n const summary = firstLine(description);\n switch (shell) {\n case \"bash\":\n return value;\n case \"zsh\":\n // _describe splits on the first unescaped colon.\n return summary\n ? `${value.replaceAll(\":\", \"\\\\:\")}:${summary}`\n : value.replaceAll(\":\", \"\\\\:\");\n case \"fish\":\n return summary ? `${value}\\t${summary}` : value;\n }\n });\n return lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\";\n}\n\nexport function completionScript(shell: Shell): string {\n switch (shell) {\n case \"bash\":\n // Words are copied one by one: bash 3.2, macOS's /bin/bash, joins\n // a quoted array slice into one word while IFS is a newline.\n return `# fluid bash completion\n_fluid_complete() {\n local -a words\n local i\n for ((i = 0; i <= COMP_CWORD; i++)); do words+=(\"\\${COMP_WORDS[i]}\"); done\n local IFS=$'\\\\n'\n COMPREPLY=($(printf '%s\\\\0' \"\\${words[@]}\" | fluid __complete --shell bash 2>/dev/null))\n}\ncomplete -o default -F _fluid_complete fluid\n`;\n case \"zsh\":\n return `#compdef fluid\n# fluid zsh completion\n_fluid() {\n local -a candidates\n candidates=(\"\\${(@f)$(printf '%s\\\\0' \"\\${(@)words[1,CURRENT]}\" | fluid __complete --shell zsh 2>/dev/null)}\")\n candidates=(\\${candidates:#})\n if (( \\${#candidates} )); then\n _describe -t fluid 'fluid' candidates\n else\n _files\n fi\n}\nif [[ \\${zsh_eval_context[-1]} == loadautofunc ]]; then\n _fluid \"$@\"\nelse\n compdef _fluid fluid\nfi\n`;\n case \"fish\":\n // The current token goes through a variable so an empty one is still\n // sent: a bare (commandline -ct) expands to no argument at all.\n return `# fluid fish completion\nfunction __fluid_complete\n set -l current (commandline -ct)\n set -l candidates (string join0 -- (commandline -opc) \"$current\" | fluid __complete --shell fish 2>/dev/null)\n if set -q candidates[1]\n printf '%s\\\\n' $candidates\n else\n __fish_complete_path \"$current\"\n end\nend\ncomplete -c fluid -f -a '(__fluid_complete)'\n`;\n }\n}\n\nexport const COMPLETION_INSTALL_HELP = `\nInstall:\n bash echo 'eval \"$(fluid completion bash)\"' >> ~/.bashrc\n zsh fluid completion zsh > \"\\${fpath[1]}/_fluid\" (or eval \"$(fluid completion zsh)\" in ~/.zshrc)\n fish fluid completion fish > ~/.config/fish/completions/fluid.fish\n`;\n","/**\n * fluid completion <shell> — print a shell completion script.\n * fluid __complete — the hidden command that script pipes the typed words\n * into on each tab.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { Argument, Command, Option } from \"commander\";\nimport {\n completeWords,\n completionScript,\n COMPLETION_INSTALL_HELP,\n formatCandidates,\n parseCompletionInput,\n SHELLS,\n type Shell,\n} from \"../completion/complete.js\";\nimport { rootCommand } from \"../catalog/walk.js\";\n\nexport const completionCommand = new Command(\"completion\")\n .description(\"Print a shell completion script for bash, zsh or fish\")\n .addArgument(new Argument(\"<shell>\", \"Shell to complete in\").choices(SHELLS))\n .addHelpText(\"after\", COMPLETION_INSTALL_HELP)\n .action((shell: Shell) => {\n process.stdout.write(completionScript(shell));\n });\n\nexport const completeCommand = new Command(\"__complete\")\n .description(\"Print completions for the words typed so far\")\n .addOption(\n new Option(\"--shell <shell>\", \"Output format\")\n .choices(SHELLS)\n .default(\"bash\"),\n )\n .action((opts: { shell: Shell }, command: Command) => {\n // The words arrive on stdin, NUL-terminated, never as arguments.\n const typed = parseCompletionInput(readFileSync(0, \"utf8\"));\n process.stdout.write(\n formatCandidates(completeWords(rootCommand(command), typed), opts.shell),\n );\n });\n","/**\n * Email sign-ins started with `fluid login --send-code` and not finished yet.\n *\n * The send and finish steps run as separate processes, and the finish step\n * needs the server's id for the sign-in (`uuid`), which only the send step\n * saw. Keeping it here means an agent carries the emailed code alone. The\n * uuid cannot sign anyone in without that code.\n *\n * One record per address, so a new send replaces the last one. Records live\n * under the config dir (`~/.fluid/pending-logins/`), each named by a hash of\n * the address so the file names do not list who is signing in.\n */\n\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getConfigDir } from \"../config/paths.js\";\n\nexport interface PendingLogin {\n readonly uuid: string;\n /** Normalised with `normaliseEmail`. */\n readonly email: string;\n /** The company the code was sent for; the finish step confirms it. */\n readonly shop: string;\n readonly expiresAt: string;\n /** The API the code was sent from; the finish step confirms against it. */\n readonly baseUrl: string;\n}\n\nexport interface PendingLoginStore {\n save(record: PendingLogin): void;\n load(email: string): PendingLogin | null;\n remove(email: string): void;\n}\n\n// A record this long past its expiry can never be finished, so the next\n// save removes it, along with any record it cannot read.\nconst STALE_AFTER_MS = 60 * 60 * 1000;\n\n/** The server compares addresses trimmed and lowercased; so does the store. */\nexport function normaliseEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\nfunction fileName(email: string): string {\n const hash = createHash(\"sha256\").update(normaliseEmail(email)).digest(\"hex\");\n return `${hash}.json`;\n}\n\nfunction isPendingLogin(value: unknown): value is PendingLogin {\n if (typeof value !== \"object\" || value === null) return false;\n const record = value as Record<string, unknown>;\n return (\n typeof record[\"uuid\"] === \"string\" &&\n typeof record[\"email\"] === \"string\" &&\n typeof record[\"shop\"] === \"string\" &&\n typeof record[\"expiresAt\"] === \"string\" &&\n typeof record[\"baseUrl\"] === \"string\"\n );\n}\n\nfunction readRecord(path: string): PendingLogin | null {\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n return isPendingLogin(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction removeStale(dir: string, now: number): void {\n let names: string[];\n try {\n names = readdirSync(dir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.endsWith(\".json\")) continue;\n const path = join(dir, name);\n const record = readRecord(path);\n const expiresAt = record ? Date.parse(record.expiresAt) : NaN;\n if (!record || !(expiresAt + STALE_AFTER_MS > now)) {\n rmSync(path, { force: true });\n }\n }\n}\n\n/**\n * The store, in `dir` or by default `<config dir>/pending-logins`, resolved\n * on each call so a changed `FLUID_CONFIG_DIR` is honoured.\n */\nexport function createPendingLoginStore(dir?: string): PendingLoginStore {\n const storeDir = () => dir ?? join(getConfigDir(), \"pending-logins\");\n\n return {\n save(record) {\n const base = storeDir();\n mkdirSync(base, { recursive: true, mode: 0o700 });\n removeStale(base, Date.now());\n\n // Written to a temp file and renamed over the record, as config.json\n // is, so a crash never leaves half a record and the 0o600 mode applies\n // to every write rather than only the first.\n const tmpPath = join(\n base,\n `.pending-${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n try {\n writeFileSync(tmpPath, JSON.stringify(record, null, 2) + \"\\n\", {\n encoding: \"utf8\",\n mode: 0o600,\n });\n renameSync(tmpPath, join(base, fileName(record.email)));\n } catch (err) {\n try {\n unlinkSync(tmpPath);\n } catch {\n // The temp file may not exist yet.\n }\n throw err;\n }\n },\n\n load(email) {\n const record = readRecord(join(storeDir(), fileName(email)));\n return record && record.email === normaliseEmail(email) ? record : null;\n },\n\n remove(email) {\n rmSync(join(storeDir(), fileName(email)), { force: true });\n },\n };\n}\n","/**\n * Helpers for constructing stored auth profiles.\n */\n\nimport type { FluidProfile } from \"../config/types.js\";\n\ninterface CreateFluidProfileInput {\n readonly name: string;\n readonly token: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly storedAt?: string;\n}\n\nexport function createFluidProfile({\n name,\n token,\n companyName,\n baseUrl,\n storedAt,\n}: CreateFluidProfileInput): FluidProfile {\n return {\n name,\n token,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n };\n}\n","/**\n * fluid login — authenticate via email MFA or API token\n *\n * Besides the interactive sign-in, an email sign-in can run in two steps\n * with no terminal, for an agent: `--send-code` emails the code and saves\n * the server's sign-in id (auth/pending-login.ts), then `--code` redeems\n * it. `--send-code` requires `--shop`, which ties the code to one company:\n * only such a code lets an admin's sign-in confirm a new signup.\n */\n\nimport { text as readAll } from \"node:stream/consumers\";\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n validateToken,\n sendMfa,\n confirmMfa,\n getFluidApiBase,\n type CompanyChoice,\n type FluidApiError,\n} from \"../auth/fluid-api.js\";\nimport {\n createPendingLoginStore,\n normaliseEmail,\n type PendingLoginStore,\n} from \"../auth/pending-login.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { updateConfig, readConfig } from \"../config/config.js\";\nimport type { CliError } from \"../utils/errors.js\";\n\nexport interface LoginOptions {\n readonly token?: string;\n readonly email?: string;\n readonly name?: string;\n readonly shop?: string;\n readonly sendCode?: boolean;\n /**\n * `true` for a bare `--code`, which reads FLUID_LOGIN_CODE; `\"-\"` reads\n * stdin; anything else is the code itself.\n */\n readonly code?: string | boolean;\n readonly yes?: boolean;\n readonly json?: boolean;\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\n/**\n * Everything `runLogin` reaches outside itself, so a test can stand in for\n * the API, the prompts, the terminal and the console without loading\n * commander or reloading this module.\n */\nexport interface LoginDeps {\n readonly api: {\n readonly validateToken: typeof validateToken;\n readonly sendMfa: typeof sendMfa;\n readonly confirmMfa: typeof confirmMfa;\n };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n readonly spinner: (text: string) => Spinner;\n /** stdout: results, and in text mode every message. */\n readonly log: (line: string) => void;\n /** stderr: warnings that must not mix into `--json` output. */\n readonly err: (line: string) => void;\n readonly env: NodeJS.ProcessEnv;\n /**\n * Whether a person can answer a prompt. `prompts` reads stdin, and on a\n * closed stdin (an agent's subprocess) it never settles, so node exits 0\n * having done nothing.\n */\n readonly isInteractive: () => boolean;\n readonly readStdin: () => Promise<string>;\n readonly pending: PendingLoginStore;\n}\n\nexport const defaultLoginDeps: LoginDeps = {\n api: { validateToken, sendMfa, confirmMfa },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n err: (line) => console.error(line),\n env: process.env,\n isInteractive: () => Boolean(process.stdin.isTTY),\n readStdin: () => readAll(process.stdin),\n pending: createPendingLoginStore(),\n};\n\nconst SILENT_SPINNER: Spinner = { succeed: () => {}, fail: () => {} };\n\nconst TWO_STEP_HINT =\n \"Sign in in two steps instead:\\n\" +\n \" fluid login --send-code --email <email> --shop <shop>\\n\" +\n \" fluid login --code --email <email> --yes\\n\" +\n \"with the emailed code in FLUID_LOGIN_CODE (or --code - to read it from stdin). \" +\n \"--yes replaces a profile with the company's name; --name <profile> picks another. Or set FLUID_TOKEN.\";\n\n/** Output for one run: spinners and text, or a single JSON object. */\ninterface Ui {\n readonly json: boolean;\n spinner(text: string): Spinner;\n /** Print the run's JSON result; text mode prints its own lines. */\n result(payload: Record<string, unknown>): void;\n /** Report a failure and return the exit code. */\n fail(error: CliError, spinner?: Spinner): number;\n}\n\nfunction createUi(json: boolean, deps: LoginDeps): Ui {\n return {\n json,\n spinner: (text) => (json ? SILENT_SPINNER : deps.spinner(text)),\n result: (payload) => {\n if (json) deps.log(JSON.stringify(payload, null, 2));\n },\n fail: (error, spinner) => {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n if (spinner) spinner.fail(chalk.red(error.message));\n else deps.log(chalk.red(error.message));\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n },\n };\n}\n\n/** The shop option for an API call, or no argument at all without one. */\nfunction shopArgs(shop: string | undefined): [] | [{ fluidShop: string }] {\n return shop ? [{ fluidShop: shop }] : [];\n}\n\n/** The part of a shop the server matches on: \"acme\" in \"acme.fluid.app\". */\nfunction shopLabel(shop: string): string {\n return (shop.trim().toLowerCase().split(\".\")[0] ?? \"\").trim();\n}\n\nfunction findByShop(\n companies: readonly CompanyChoice[],\n shop: string,\n): CompanyChoice | undefined {\n return companies.find((c) => shopLabel(c.shopName) === shopLabel(shop));\n}\n\n/**\n * Whether the entry's token is an admin or rep session, the only kind the\n * CLI's commands accept. A shopper's code returns a \"member\" or \"customer\"\n * token instead. The server types every entry, so one with no type is\n * refused rather than stored.\n */\nfunction isStaffSession(company: CompanyChoice): boolean {\n return company.authType === \"rep\";\n}\n\nfunction shopperSession(email: string, company: CompanyChoice): CliError {\n return {\n code: \"SHOPPER_SESSION\",\n message: `${email} does not sign in at ${company.shopName} as an admin or rep, so it cannot sign in to the CLI.`,\n };\n}\n\ninterface OverwriteOptions {\n readonly yes: boolean;\n readonly interactive: boolean;\n}\n\n/**\n * What to do about profile `profileName` before writing it: replace it when\n * it is new or with `--yes`, ask in a terminal, and refuse otherwise, since\n * no one could answer the question.\n */\nfunction overwriteRule(\n profileName: string,\n opts: OverwriteOptions,\n): \"replace\" | \"ask\" | \"refuse\" {\n if (!readConfig().profiles[profileName] || opts.yes) return \"replace\";\n return opts.interactive ? \"ask\" : \"refuse\";\n}\n\nasync function overwriteDecision(\n profileName: string,\n opts: OverwriteOptions,\n deps: LoginDeps,\n): Promise<\"replace\" | \"keep\" | \"refuse\"> {\n const rule = overwriteRule(profileName, opts);\n if (rule !== \"ask\") return rule;\n\n const existing = readConfig().profiles[profileName];\n const response = await deps.prompt({\n type: \"confirm\",\n name: \"overwrite\",\n message: `Profile \"${profileName}\" already exists (${existing?.companyName}). Overwrite?`,\n initial: false,\n });\n return response[\"overwrite\"] ? \"replace\" : \"keep\";\n}\n\nfunction profileExists(profileName: string, codeUsed: boolean): CliError {\n return {\n code: \"PROFILE_EXISTS\",\n message:\n `Profile \"${profileName}\" already exists. Pass --yes to replace it` +\n (codeUsed ? \"; the code is used, so send a new one first.\" : \".\"),\n };\n}\n\nfunction storeProfile(\n profileName: string,\n token: string,\n companyName: string,\n baseUrl: string = getFluidApiBase(),\n): void {\n updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createFluidProfile({\n name: profileName,\n token,\n companyName,\n baseUrl,\n }),\n },\n }));\n}\n\nfunction loggedIn(\n ui: Ui,\n deps: LoginDeps,\n profileName: string,\n company: {\n readonly name: string;\n readonly id?: number;\n readonly shop?: string;\n },\n): number {\n ui.result({ status: \"signed_in\", profile: profileName, company });\n if (!ui.json) {\n deps.log(\n chalk.green(\n `Logged in as ${chalk.bold(company.name)} (profile: ${chalk.bold(profileName)})`,\n ),\n );\n }\n return 0;\n}\n\nfunction cancelled(deps: LoginDeps): number {\n deps.log(chalk.yellow(\"Login cancelled — existing profile not overwritten.\"));\n return 0;\n}\n\nasync function loginWithToken(\n token: string,\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n const spinner = ui.spinner(\"Validating token...\");\n const result = await deps.api.validateToken(token);\n\n if (!result.success) return ui.fail(result.error, spinner);\n\n const name = opts.name ?? result.value.name;\n\n // Stop spinner before potential interactive prompt to avoid terminal corruption\n spinner.succeed(\n chalk.green(`Token valid — ${chalk.bold(result.value.name)}`),\n );\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive },\n deps,\n );\n if (decision === \"refuse\") return ui.fail(profileExists(name, false));\n if (decision === \"keep\") return cancelled(deps);\n\n storeProfile(name, token, result.value.name);\n return loggedIn(ui, deps, name, { name: result.value.name });\n}\n\nasync function loginWithEmail(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n // 1. Prompt for email\n let email = opts.email;\n if (!email) {\n const response = await deps.prompt({\n type: \"text\",\n name: \"email\",\n message: \"Enter your email\",\n });\n email = response[\"email\"] as string | undefined;\n if (!email) {\n deps.log(chalk.red(\"No email provided. Aborting.\"));\n return 1;\n }\n }\n\n // 2. Send MFA code\n const sendSpinner = ui.spinner(\"Sending verification code...\");\n const sendResult = await deps.api.sendMfa(email, ...shopArgs(opts.shop));\n\n if (!sendResult.success) return ui.fail(sendResult.error, sendSpinner);\n\n sendSpinner.succeed(\n `Verification code sent — check your email (${expiryNote(sendResult.value.expiresAt)})`,\n );\n\n // 3. Prompt for verification code (retry up to 3 times on invalid code)\n const MAX_CODE_ATTEMPTS = 3;\n let confirmResult;\n for (let attempt = 1; attempt <= MAX_CODE_ATTEMPTS; attempt++) {\n const codeResponse = await deps.prompt({\n type: \"text\",\n name: \"code\",\n message: \"Enter the 6-digit code\",\n });\n const code = codeResponse[\"code\"] as string | undefined;\n if (!code) {\n deps.log(chalk.red(\"No code provided. Aborting.\"));\n return 1;\n }\n if (!/^\\d{6}$/.test(code)) {\n deps.log(chalk.red(\"Code must be exactly 6 digits.\"));\n if (attempt < MAX_CODE_ATTEMPTS) continue;\n deps.log(chalk.red(\"Too many invalid attempts. Aborting.\"));\n return 1;\n }\n\n const confirmSpinner = ui.spinner(\"Verifying code...\");\n confirmResult = await deps.api.confirmMfa(\n sendResult.value.uuid,\n code,\n ...shopArgs(opts.shop),\n );\n\n if (confirmResult.success) {\n confirmSpinner.succeed(\"Verified\");\n break;\n }\n\n // Retryable: wrong code, still have attempts left\n if (\n confirmResult.error.code === \"INVALID_CODE\" &&\n attempt < MAX_CODE_ATTEMPTS\n ) {\n confirmSpinner.fail(\n chalk.red(\n `${confirmResult.error.message} (attempt ${attempt}/${MAX_CODE_ATTEMPTS})`,\n ),\n );\n continue;\n }\n\n // Non-retryable (expired, unreachable, etc.) or final attempt\n return ui.fail(confirmResult.error, confirmSpinner);\n }\n\n if (!confirmResult?.success) return 0;\n\n const { companies } = confirmResult.value;\n\n if (companies.length === 0) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n\n // 4. Select company (auto-select if only one, or the one --shop names)\n const named = opts.shop ? findByShop(companies, opts.shop) : undefined;\n let selected: CompanyChoice;\n if (named) {\n selected = named;\n } else if (companies.length === 1) {\n const first = companies[0];\n if (!first) {\n deps.log(chalk.red(\"No companies found for this account.\"));\n return 1;\n }\n selected = first;\n } else {\n // Key on `c.id`, not the array index, and resolve via `.find` —\n // `prompts` autocomplete returns the raw typed string on Enter when\n // the user hasn't arrow-key-highlighted a filtered choice, so an\n // array-index lookup ends up asking for `companies[\"Fluid\"]` and\n // failing with \"Invalid selection\". Same shape as `switch.ts`.\n const companyChoices = companies.map((c) => ({\n title: `${c.name} (${c.shopName})`,\n value: c.id,\n }));\n\n const selectResponse = await deps.prompt({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = selectResponse[\"companyId\"] as number | undefined;\n\n if (companyId === undefined) {\n deps.log(chalk.red(\"No company selected. Aborting.\"));\n return 1;\n }\n const choice = companies.find((c) => c.id === companyId);\n if (!choice) {\n deps.log(chalk.red(\"Invalid selection. Aborting.\"));\n return 1;\n }\n selected = choice;\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n // 5. Store profile\n const name = opts.name ?? selected.name;\n\n const decision = await overwriteDecision(\n name,\n { yes: Boolean(opts.yes), interactive: true },\n deps,\n );\n if (decision !== \"replace\") return cancelled(deps);\n\n storeProfile(name, selected.jwt, selected.name);\n return loggedIn(ui, deps, name, { name: selected.name });\n}\n\nfunction expiryNote(expiresAtIso: string): string {\n const expiresInMs = new Date(expiresAtIso).getTime() - Date.now();\n const expiresInMin = Math.round(expiresInMs / 1000 / 60);\n return expiresInMin > 0\n ? `expires in ~${expiresInMin} min`\n : \"code may expire soon — check your email quickly\";\n}\n\n// Characters an email or shop can hold that are safe to paste into a shell.\nconst SHELL_SAFE = /^[\\w.@+-]+$/;\n\n/**\n * The command that finishes this sign-in, for a person or agent to run.\n * Values with characters a shell would act on are left as placeholders.\n */\nfunction finishCommand(email: string, shop: string): string {\n const safe = (value: string, placeholder: string) =>\n SHELL_SAFE.test(value) ? value : placeholder;\n return `fluid login --code --email ${safe(email, \"<email>\")} --shop ${safe(shop, \"<shop>\")}`;\n}\n\n/** `fluid login --send-code`: email a code, save the sign-in, exit. */\nasync function sendCodeStep(\n opts: LoginOptions,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--send-code needs --email <address>.\",\n });\n }\n // A code sent without a shop is tied to the person, not to a company, so\n // finishing it signs in without confirming a new company's signup.\n if (!opts.shop) {\n return ui.fail({\n code: \"SHOP_REQUIRED\",\n message:\n \"--send-code needs --shop <shop>, the company to sign in to (acme or acme.fluid.app). A new signup's response names it as fluid_shop.\",\n });\n }\n const email = normaliseEmail(opts.email);\n const shop = opts.shop;\n\n const spinner = ui.spinner(\"Sending verification code...\");\n const sent = await deps.api.sendMfa(email, ...shopArgs(shop));\n if (!sent.success) return ui.fail(sent.error, spinner);\n\n deps.pending.save({\n uuid: sent.value.uuid,\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n baseUrl: getFluidApiBase(),\n });\n\n // The server answers the same whether or not the address can sign in\n // there, so this cannot promise that a code was sent.\n spinner.succeed(\n `If ${email} can sign in at ${shop}, a code is on its way (${expiryNote(sent.value.expiresAt)})`,\n );\n ui.result({\n status: \"code_sent\",\n email,\n shop,\n expiresAt: sent.value.expiresAt,\n });\n if (!ui.json) {\n deps.log(`Finish with: ${finishCommand(email, shop)}`);\n deps.log(\n chalk.dim(\n \"with the code in FLUID_LOGIN_CODE, or add - after --code to read it from stdin. \" +\n \"With no terminal, add --yes to replace a profile with the company's name, or --name <profile>.\",\n ),\n );\n }\n return 0;\n}\n\n/**\n * The code for the finish step. A bare `--code` reads FLUID_LOGIN_CODE,\n * `--code -` reads stdin, and any other value is the code. Stdin is read\n * only when asked for: an agent's stdin may be a pipe that never closes,\n * and reading it uninvited would wait forever.\n */\nasync function readCode(\n opts: LoginOptions,\n deps: LoginDeps,\n): Promise<string | undefined> {\n if (opts.code === \"-\") {\n return (await deps.readStdin()).trim() || undefined;\n }\n if (typeof opts.code === \"string\") {\n deps.err(\n chalk.yellow(\n \"Warning: a code passed via --code is visible in shell history and process listings. \" +\n \"Prefer FLUID_LOGIN_CODE, or --code - to read it from stdin.\",\n ),\n );\n return opts.code.trim();\n }\n return deps.env[\"FLUID_LOGIN_CODE\"]?.trim() || undefined;\n}\n\n/** The server's answer for a code that cannot finish, by error code. */\nfunction finishError(error: FluidApiError, shop: string): CliError {\n if (error.code === \"INVALID_CODE\") {\n return {\n code: error.code,\n message: `${error.message}. Five wrong codes lock this sign-in; then run --send-code again.`,\n };\n }\n if (error.code === \"UUID_NOT_FOUND\") {\n return {\n code: error.code,\n message:\n `This sign-in can't be finished with a code: the shop \"${shop}\" is wrong, ` +\n \"the address is not an admin or rep there, or the company signs in with an emailed link instead. \" +\n \"Check them and run --send-code again.\",\n };\n }\n return error;\n}\n\n/** `fluid login --code`: redeem the code for the saved sign-in. */\nasync function finishStep(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n): Promise<number> {\n if (!opts.email) {\n return ui.fail({\n code: \"EMAIL_REQUIRED\",\n message: \"--code needs --email <address>, the one used with --send-code.\",\n });\n }\n // Without a terminal no one can answer \"replace the profile?\", and the\n // profile's name (the company's) is known only once the code is spent.\n // Asking for the choice now means the code is never spent on a refusal.\n if (!interactive && !opts.yes && !opts.name) {\n return ui.fail({\n code: \"YES_OR_NAME_REQUIRED\",\n message:\n \"With no terminal, --code needs --yes, to replace a profile with the company's name, or --name <profile>.\",\n });\n }\n const email = normaliseEmail(opts.email);\n\n const record = deps.pending.load(email);\n if (!record) {\n return ui.fail({\n code: \"NO_PENDING_LOGIN\",\n message: `No sign-in is waiting for ${email}. Run fluid login --send-code --email ${email} first.`,\n });\n }\n // The code is tied to the shop it was sent for, so that is the one\n // confirmed; a --shop here only has to agree with it.\n const { shop } = record;\n if (opts.shop && shopLabel(opts.shop) !== shopLabel(shop)) {\n return ui.fail({\n code: \"SHOP_MISMATCH\",\n message: `The code for ${email} was sent for ${shop}, not ${opts.shop}.`,\n });\n }\n\n if (!(Date.parse(record.expiresAt) > Date.now())) {\n deps.pending.remove(email);\n return ui.fail({\n code: \"CODE_EXPIRED\",\n message: `The code for ${email} has expired. Run fluid login --send-code again.`,\n });\n }\n\n const code = await readCode(opts, deps);\n if (!code) {\n return ui.fail({\n code: \"NO_CODE\",\n message:\n \"No code given. Put it in FLUID_LOGIN_CODE, pass --code - to read it from stdin, or pass it to --code.\",\n });\n }\n if (!/^\\d{6}$/.test(code)) {\n return ui.fail({\n code: \"INVALID_CODE_FORMAT\",\n message: \"The code must be exactly 6 digits.\",\n });\n }\n\n // Confirming uses the code up, so a named profile that would be refused\n // is checked first. Without a terminal, the check above has already\n // required --yes or --name.\n const overwrite = { yes: Boolean(opts.yes), interactive };\n if (opts.name && overwriteRule(opts.name, overwrite) === \"refuse\") {\n return ui.fail(profileExists(opts.name, false));\n }\n\n const spinner = ui.spinner(\"Verifying code...\");\n const confirmed = await deps.api.confirmMfa(record.uuid, code, {\n fluidShop: shop,\n baseUrl: record.baseUrl,\n });\n if (!confirmed.success) {\n // A wrong code may be retried. A rate limit or an unreachable server\n // may not have spent it, so the sign-in is kept for one more try; if\n // the code was spent after all, that try ends it with a 410. Anything\n // else ends this sign-in now.\n const retryable = [\"INVALID_CODE\", \"RATE_LIMITED\", \"API_UNREACHABLE\"];\n if (!retryable.includes(confirmed.error.code)) deps.pending.remove(email);\n return ui.fail(finishError(confirmed.error, shop), spinner);\n }\n spinner.succeed(\"Verified\");\n deps.pending.remove(email);\n\n const { companies } = confirmed.value;\n const selected = findByShop(companies, shop);\n if (!selected) {\n if (companies.length === 0) {\n return ui.fail({\n code: \"NO_COMPANIES\",\n message: \"No companies found for this account.\",\n });\n }\n const shops = companies.map((c) => c.shopName).join(\", \");\n return ui.fail({\n code: \"SHOP_NOT_FOUND\",\n message: `This account has no company at ${shop}. It has: ${shops}.`,\n });\n }\n\n if (!isStaffSession(selected)) {\n return ui.fail(shopperSession(email, selected));\n }\n\n const name = opts.name ?? selected.name;\n const decision = await overwriteDecision(name, overwrite, deps);\n if (decision === \"refuse\") return ui.fail(profileExists(name, true));\n if (decision === \"keep\") return cancelled(deps);\n\n storeProfile(name, selected.jwt, selected.name, record.baseUrl);\n return loggedIn(ui, deps, name, {\n id: selected.id,\n name: selected.name,\n shop: selected.shopName,\n });\n}\n\n/**\n * Run `fluid login` and return its exit code.\n */\nexport async function runLogin(\n opts: LoginOptions,\n deps: LoginDeps = defaultLoginDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const ui = createUi(json, deps);\n // `--json` is for a program reading the output, which cannot answer a\n // prompt either. Nor can a run that reads the code from stdin with\n // `--code -`: stdin has ended by the time a prompt would read it.\n const interactive = deps.isInteractive() && !json && opts.code !== \"-\";\n\n if (opts.sendCode || opts.code !== undefined) {\n if (opts.token) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"--token cannot be combined with --send-code or --code.\",\n });\n }\n if (opts.sendCode && opts.code !== undefined) {\n return ui.fail({\n code: \"FLAG_CONFLICT\",\n message: \"Run --send-code and --code as two separate commands.\",\n });\n }\n // FLUID_TOKEN is left alone here: an agent may have one exported from\n // an earlier sign-in, and these flags ask for an email sign-in.\n return opts.sendCode\n ? sendCodeStep(opts, ui, deps)\n : finishStep(opts, interactive, ui, deps);\n }\n\n // Accept token from env var to avoid shell history / process listing exposure\n const token = opts.token ?? deps.env[\"FLUID_TOKEN\"];\n if (token) {\n if (opts.token) {\n (json ? deps.err : deps.log)(\n chalk.yellow(\n \"Warning: token passed via --token flag is visible in shell history and process listings. \" +\n \"Prefer the FLUID_TOKEN environment variable.\",\n ),\n );\n }\n return loginWithToken(token, opts, interactive, ui, deps);\n }\n\n if (!interactive) {\n const why = json\n ? \"fluid login --json cannot ask for the email and code.\"\n : \"fluid login needs a terminal to ask for the email and code.\";\n return ui.fail({\n code: \"NOT_INTERACTIVE\",\n message: `${why}\\n${TWO_STEP_HINT}`,\n });\n }\n return loginWithEmail(opts, ui, deps);\n}\n\n/**\n * The `login` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing in.\n */\nexport function buildLoginCommand(\n run: (opts: LoginOptions) => Promise<number> = (opts) => runLogin(opts),\n): Command {\n return new Command(\"login\")\n .description(\"Authenticate with the Fluid API\")\n .option(\n \"-t, --token <token>\",\n \"API token (skips email flow). Prefer FLUID_TOKEN env var to avoid shell history exposure\",\n )\n .option(\n \"-e, --email <email>\",\n \"Email address for MFA login (required with --send-code and --code)\",\n )\n .option(\"-n, --name <name>\", \"Profile name (defaults to company name)\")\n .option(\n \"--shop <shop>\",\n \"Sign in to this company (e.g. acme or acme.fluid.app); required with --send-code. An admin's emailed code also confirms a new signup\",\n )\n .option(\n \"--send-code\",\n \"Email a sign-in code and exit, for use without a terminal; finish with --code\",\n )\n .option(\n \"--code [code]\",\n \"Finish a sign-in started with --send-code. Reads the code from FLUID_LOGIN_CODE, or from stdin with --code -; a code given here is visible in shell history\",\n )\n .option(\"-y, --yes\", \"Replace an existing profile without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: LoginOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const loginCommand = buildLoginCommand();\n","/**\n * fluid logout — remove stored auth profile(s)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { readConfig, writeConfig } from \"../config/config.js\";\n\nexport const logoutCommand = new Command(\"logout\")\n .description(\"Remove stored authentication\")\n .option(\"-a, --all\", \"Remove all profiles\")\n .action((opts: { all?: boolean }) => {\n const config = readConfig();\n\n if (opts.all) {\n writeConfig({\n ...config,\n activeProfile: null,\n profiles: {},\n });\n console.log(chalk.green(\"All profiles removed.\"));\n return;\n }\n\n if (!config.activeProfile) {\n console.log(chalk.yellow(\"Not currently logged in.\"));\n return;\n }\n\n const profileName = config.activeProfile;\n const { [profileName]: _, ...remainingProfiles } = config.profiles;\n\n // Pick the first remaining profile as active, or null\n const nextActive = Object.keys(remainingProfiles)[0] ?? null;\n\n writeConfig({\n ...config,\n activeProfile: nextActive,\n profiles: remainingProfiles,\n });\n\n console.log(\n chalk.green(`Logged out of profile ${chalk.bold(profileName)}.`),\n );\n if (nextActive) {\n console.log(chalk.dim(`Switched to profile ${nextActive}.`));\n }\n });\n","/**\n * fluid whoami — show current auth profile and validate against API\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { validateToken } from \"../auth/fluid-api.js\";\n\nexport const whoamiCommand = new Command(\"whoami\")\n .description(\"Show the current authenticated profile\")\n .action(async () => {\n const profile = getActiveProfile();\n\n if (!profile) {\n console.log(\n chalk.yellow(\"Not logged in. Run `fluid login` to authenticate.\"),\n );\n process.exitCode = 1;\n return;\n }\n\n const spinner = ora(\"Verifying token...\").start();\n const result = await validateToken(profile.token);\n\n if (!result.success) {\n spinner.fail(chalk.red(\"Token is no longer valid.\"));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n console.log(chalk.dim(\"Run `fluid login` to re-authenticate.\"));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(result.value.name)}`);\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n });\n","/**\n * fluid switch — switch between companies (fetched from API, with local fallback)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport prompts from \"prompts\";\nimport ora from \"ora\";\nimport {\n fetchUserCompanies,\n switchCompany,\n FLUID_API_ERROR,\n getFluidApiBase,\n type UserCompany,\n} from \"../auth/fluid-api.js\";\nimport { createFluidProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\n\nasync function localSwitch(profileArg?: string): Promise<void> {\n const config = readConfig();\n const profileNames = Object.keys(config.profiles);\n\n if (profileNames.length === 0) {\n console.log(chalk.yellow(\"No profiles stored. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n let targetProfile = profileArg;\n\n if (!targetProfile) {\n const profileChoices = profileNames.map((name) => ({\n title: name === config.activeProfile ? `${name} (active)` : name,\n value: name,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"profile\",\n message: \"Select a profile (type to search)\",\n choices: profileChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.value.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n targetProfile = response[\"profile\"] as string | undefined;\n\n if (!targetProfile) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n }\n\n if (!config.profiles[targetProfile]) {\n console.log(chalk.red(`Profile \"${targetProfile}\" not found.`));\n console.log(chalk.dim(`Available: ${profileNames.join(\", \")}`));\n process.exitCode = 1;\n return;\n }\n\n updateConfig((c) => ({ ...c, activeProfile: targetProfile! }));\n console.log(chalk.green(`Switched to profile ${chalk.bold(targetProfile)}.`));\n}\n\nasync function selectCompany(\n companies: UserCompany[],\n activeCompanyName: string | undefined,\n): Promise<UserCompany | undefined> {\n const companyChoices = companies.map((c) => ({\n title:\n c.name === activeCompanyName\n ? `${c.name} ${chalk.dim(\"(active)\")}`\n : c.name,\n value: c.id,\n }));\n\n const response = await prompts({\n type: \"autocomplete\",\n name: \"companyId\",\n message: \"Select a company (type to search)\",\n choices: companyChoices,\n suggest: (input, choices) =>\n Promise.resolve(\n input\n ? choices.filter((c) =>\n c.title.toLowerCase().includes(input.toLowerCase()),\n )\n : choices,\n ),\n });\n\n const companyId = response[\"companyId\"] as number | undefined;\n if (companyId === undefined) return undefined;\n return companies.find((c) => c.id === companyId);\n}\n\nasync function performSwitch(\n token: string,\n company: UserCompany,\n baseUrl?: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n const result = await switchCompany(token, company.id, baseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n } else {\n spinner.fail(chalk.red(result.error.message));\n if (result.error.details) {\n console.log(chalk.dim(result.error.details));\n }\n }\n process.exitCode = 1;\n return;\n }\n\n const { companyName, jwt } = result.value;\n\n updateConfig((config) => ({\n ...config,\n activeProfile: companyName,\n profiles: {\n ...config.profiles,\n [companyName]: createFluidProfile({\n name: companyName,\n token: jwt,\n companyName,\n baseUrl: baseUrl ?? getFluidApiBase(),\n }),\n },\n }));\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(companyName)} (profile: ${chalk.bold(companyName)})`,\n ),\n );\n}\n\nexport const switchCommand = new Command(\"switch\")\n .description(\"Switch between companies\")\n .argument(\"[profile]\", \"Company or profile name to switch to\")\n .action(async (profileArg?: string) => {\n const activeProfile = getActiveProfile();\n\n if (!activeProfile) {\n console.log(chalk.yellow(\"Not logged in. Run `fluid login` first.\"));\n process.exitCode = 1;\n return;\n }\n\n const token = activeProfile.token;\n const activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n const result = await fetchUserCompanies(token, activeBaseUrl);\n\n if (!result.success) {\n if (result.error.code === FLUID_API_ERROR.INVALID_TOKEN.code) {\n spinner.fail(\n chalk.red(\n \"Your session has expired. Please run `fluid login` to re-authenticate.\",\n ),\n );\n process.exitCode = 1;\n return;\n }\n spinner.warn(\n chalk.yellow(\n `Could not fetch companies from API: ${result.error.message}`,\n ),\n );\n console.log(chalk.dim(\"Falling back to locally stored profiles.\"));\n await localSwitch(profileArg);\n return;\n }\n\n const companies = result.value;\n spinner.succeed(\n `Found ${companies.length} company${companies.length === 1 ? \"\" : \"ies\"}`,\n );\n\n if (companies.length === 0) {\n console.log(chalk.yellow(\"No companies found for this account.\"));\n process.exitCode = 1;\n return;\n }\n\n // If a profile argument was passed, match against API companies first\n if (profileArg) {\n const match = companies.find(\n (c) => c.name.toLowerCase() === profileArg.toLowerCase(),\n );\n\n if (match) {\n await performSwitch(token, match, activeBaseUrl);\n return;\n }\n\n // Fall back to local profile matching\n const config = readConfig();\n if (config.profiles[profileArg]) {\n updateConfig((c) => ({ ...c, activeProfile: profileArg! }));\n console.log(\n chalk.green(`Switched to profile ${chalk.bold(profileArg)}.`),\n );\n return;\n }\n\n console.log(chalk.red(`Company or profile \"${profileArg}\" not found.`));\n process.exitCode = 1;\n return;\n }\n\n // Interactive selection\n const selected = await selectCompany(companies, activeCompanyName);\n if (!selected) {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n\n await performSwitch(token, selected, activeBaseUrl);\n });\n","/**\n * Auto-discover @fluid-app CLI plugins.\n *\n * Three discovery strategies run in order:\n *\n * 1a. **node_modules scan (cwd)** — look in `<cwd>/node_modules/@fluid-app/`\n * for directories whose names match the plugin naming convention.\n * This is the primary mechanism for project-local plugin installs.\n *\n * 1b. **node_modules scan (CLI install location)** — look in the\n * `node_modules/@fluid-app/` directory containing the CLI core package\n * itself. This covers global installs where plugins are sibling packages\n * under the same global `node_modules/`.\n *\n * 2. **Workspace scan** — walk upward from the CLI core package root to the\n * monorepo workspace root, then scan `packages/` for sibling plugin\n * packages. This covers the pnpm-workspace development case where\n * plugins are not symlinked into `node_modules`.\n *\n * Only first-party @fluid-app scoped packages are loaded.\n */\n\nimport { existsSync, readFileSync, readdirSync, realpathSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nconst PLUGIN_SCOPE = \"@fluid-app\";\n\n/**\n * A plugin package name must match one of these patterns:\n * - @fluid-app/fluid-cli-* (standard)\n * - @fluid-app/*-cli-commands (v2025-06 style)\n */\nfunction isPluginName(packageName: string): boolean {\n if (!packageName.startsWith(`${PLUGIN_SCOPE}/`)) return false;\n const bare = packageName.slice(`${PLUGIN_SCOPE}/`.length);\n return bare.startsWith(\"fluid-cli-\") || bare.endsWith(\"-cli-commands\");\n}\n\n// Strategy 1: node_modules scan (production / published installs)\n\nfunction discoverFromNodeModules(basePath: string): DiscoveredPlugin[] {\n const scopeDir = join(basePath, \"node_modules\", PLUGIN_SCOPE);\n\n if (!existsSync(scopeDir)) return [];\n\n return readdirSync(scopeDir, { withFileTypes: true })\n .filter(\n (entry) =>\n (entry.isDirectory() || entry.isSymbolicLink()) &&\n isPluginName(`${PLUGIN_SCOPE}/${entry.name}`),\n )\n .map((entry) => {\n const name = `${PLUGIN_SCOPE}/${entry.name}`;\n const entryDir = join(scopeDir, entry.name);\n // Resolve symlinks (pnpm workspace links) to file:// URLs so the\n // dynamic import works regardless of pnpm's strict module resolution.\n try {\n const realDir = realpathSync(entryDir);\n const distEntry = join(realDir, \"dist\", \"index.mjs\");\n if (existsSync(distEntry)) {\n return { name, importSpecifier: pathToFileURL(distEntry).href };\n }\n } catch {\n // Broken symlink or other fs error — fall through to bare specifier\n }\n // Fallback to bare specifier for non-workspace (published) installs\n return { name, importSpecifier: name };\n });\n}\n\n// Strategy 2: workspace scan (pnpm monorepo development)\n\nfunction findWorkspaceRoot(startDir: string): string | null {\n let dir = startDir;\n while (true) {\n if (\n existsSync(join(dir, \"pnpm-workspace.yaml\")) ||\n existsSync(join(dir, \"pnpm-workspace.yml\"))\n ) {\n return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nfunction readPackageName(dir: string): string | null {\n const pkgPath = join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return null;\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as {\n name?: string;\n };\n return pkg.name ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface DiscoveredPlugin {\n name: string;\n importSpecifier: string;\n}\n\nexport interface PluginDiscoveryOptions {\n /**\n * Prefer plugins installed beside this CLI over same-named packages in the\n * target project's node_modules. Desktop callers use this so an older\n * project-local plugin cannot override the command contract bundled with\n * the app. Normal project-local CLI invocations keep the existing order.\n */\n preferInstallation?: boolean;\n /** Test seam for the directory containing the CLI installation. */\n installationBasePath?: string;\n}\n\nfunction discoverFromWorkspace(startDir: string): DiscoveredPlugin[] {\n const workspaceRoot = findWorkspaceRoot(startDir);\n if (!workspaceRoot) return [];\n\n const results: DiscoveredPlugin[] = [];\n const packagesDir = join(workspaceRoot, \"packages\");\n if (!existsSync(packagesDir)) return [];\n\n // Scan exactly two levels deep under packages/ (e.g. packages/cli/themes,\n // packages/cli/v2025-06). This matches the monorepo convention where all\n // packages live at packages/<domain>/<package>/.\n // If a plugin is added at a different depth, update this scan accordingly.\n let domainDirs: string[];\n try {\n domainDirs = readdirSync(packagesDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(packagesDir, e.name));\n } catch {\n return [];\n }\n\n for (const domainDir of domainDirs) {\n let subDirs: string[];\n try {\n subDirs = readdirSync(domainDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(domainDir, e.name));\n } catch {\n continue;\n }\n\n for (const subDir of subDirs) {\n const name = readPackageName(subDir);\n if (!name || !name.startsWith(`${PLUGIN_SCOPE}/`) || !isPluginName(name))\n continue;\n\n const distEntry = join(subDir, \"dist\", \"index.mjs\");\n if (!existsSync(distEntry)) {\n continue;\n }\n\n results.push({\n name,\n importSpecifier: pathToFileURL(distEntry).href,\n });\n }\n }\n\n return results;\n}\n\n// Exported API\n\n/** Resolved once — the CLI core package root (`packages/cli/core/`). */\nexport const corePackageDir = dirname(\n dirname(dirname(fileURLToPath(import.meta.url))),\n);\n\n/**\n * Discover installed plugin packages. Returns a de-duplicated, sorted list\n * of `{ name, importSpecifier }` objects.\n *\n * @param basePath - Directory to scan for `node_modules/@fluid-app/`\n * @param searchFrom - Starting directory for workspace root detection\n * (walked upward via `findWorkspaceRoot`). Pass `null` to skip workspace\n * scanning (useful in tests). Defaults to `corePackageDir`.\n */\nexport function discoverPlugins(\n basePath: string,\n searchFrom?: string | null,\n options: PluginDiscoveryOptions = {},\n): DiscoveredPlugin[] {\n const seen = new Set<string>();\n const results: DiscoveredPlugin[] = [];\n\n const addPlugins = (plugins: DiscoveredPlugin[]) => {\n for (const plugin of plugins) {\n if (seen.has(plugin.name)) continue;\n seen.add(plugin.name);\n results.push(plugin);\n }\n };\n\n const cliParent =\n options.installationBasePath ?? dirname(dirname(dirname(corePackageDir)));\n const projectPlugins = () => discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath ? [] : discoverFromNodeModules(cliParent);\n const workspacePlugins = () => {\n if (searchFrom === null) return [];\n return discoverFromWorkspace(searchFrom ?? corePackageDir);\n };\n\n if (options.preferInstallation) {\n addPlugins(installationPlugins());\n // In a monorepo development build, resolveFluidBinary() deliberately\n // realpaths the CLI into packages/cli/core. Its sibling plugins are then\n // discovered from the workspace rather than an installation-level\n // node_modules, so they are part of the same trusted CLI installation.\n addPlugins(workspacePlugins());\n addPlugins(projectPlugins());\n } else {\n addPlugins(projectPlugins());\n addPlugins(installationPlugins());\n addPlugins(workspacePlugins());\n }\n\n return results.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Dynamically import a plugin module and return its default export.\n *\n * @internal Not intended for external callers. Only called with specifiers\n * produced by {@link discoverPlugins}:\n * - bare package names (e.g. `@fluid-app/fluid-cli-portal`) from the\n * node_modules scan, validated by {@link isPluginName}.\n * - `file://` URLs from {@link discoverFromWorkspace}, which constructs\n * them internally from validated workspace paths (`packages/` tree,\n * `dist/index.mjs`). These are trusted internal specifiers.\n */\nexport async function importPlugin(specifier: string): Promise<unknown> {\n // file:// URLs are trusted — they originate from discoverFromWorkspace\n // which builds them from validated workspace paths under packages/.\n // For bare package names, verify they match the plugin naming convention.\n if (!specifier.startsWith(\"file://\") && !isPluginName(specifier)) {\n throw new Error(`Refusing to import non-plugin package: ${specifier}`);\n }\n const mod = (await import(specifier)) as Record<string, unknown>;\n return mod[\"default\"] ?? mod;\n}\n","/**\n * Format one-line diagnostics naming a CLI plugin build and where it was\n * resolved from. The resolved path is the load-bearing detail: a workspace\n * build and a published copy share the same name and version, so the path is\n * the only thing that distinguishes them. See CURRENT-3218.\n */\n\nimport { fileURLToPath } from \"node:url\";\n\nexport interface PluginLoadInfo {\n readonly name: string;\n readonly version: string;\n /**\n * Where the plugin was resolved from — an absolute `file://` URL (workspace\n * or published install, resolved upstream) or, only when resolution failed,\n * a bare package name.\n */\n readonly importSpecifier: string;\n /**\n * Whether installation-bundled plugins were preferred over project-local\n * ones (`FLUID_CLI_PREFER_INSTALLATION_PLUGINS=1`, set by Mist).\n */\n readonly preferInstallation: boolean;\n}\n\nexport interface PluginLoadFailureInfo {\n readonly name: string;\n readonly importSpecifier: string;\n readonly preferInstallation: boolean;\n readonly message: string;\n}\n\nexport function modeLabel(preferInstallation: boolean): string {\n return preferInstallation ? \"installation-preferred\" : \"project-first\";\n}\n\n/**\n * Render a specifier for display: `file://` URLs become absolute filesystem\n * paths; anything else is shown verbatim. Never throws — a malformed `file://`\n * specifier falls back to its raw form so a diagnostic can never turn a\n * successful load into a reported failure.\n */\nexport function displaySource(importSpecifier: string): string {\n if (!importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return fileURLToPath(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n\nexport function formatPluginLoadLine(info: PluginLoadInfo): string {\n return `Loaded plugin ${info.name}@${info.version} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]`;\n}\n\nexport function formatPluginLoadFailure(info: PluginLoadFailureInfo): string {\n return `Failed to load plugin ${info.name} from ${displaySource(\n info.importSpecifier,\n )} [${modeLabel(info.preferInstallation)}]: ${info.message}`;\n}\n","/**\n * Resolve a plugin import specifier to a concrete path for diagnostics.\n *\n * The node_modules discovery strategy falls back to a bare package name when it\n * cannot realpath a workspace symlink — precisely the published-install case\n * where the path is the only thing that would reveal a stale plugin winning.\n * Resolving the bare specifier recovers that path. See CURRENT-3218.\n */\n\nexport type Resolver = (specifier: string) => string;\n\nconst defaultResolver: Resolver = (specifier) => import.meta.resolve(specifier);\n\n/**\n * Return a `file://` URL for `importSpecifier`. `file://` specifiers (already\n * resolved by discovery) pass through untouched; bare specifiers are resolved\n * via `resolve`. If resolution throws, the bare specifier is returned so a\n * diagnostic degrades gracefully rather than failing the load.\n */\nexport function resolveLoadPath(\n importSpecifier: string,\n resolve: Resolver = defaultResolver,\n): string {\n if (importSpecifier.startsWith(\"file://\")) return importSpecifier;\n try {\n return resolve(importSpecifier);\n } catch {\n return importSpecifier;\n }\n}\n","/**\n * Decide whether to print the per-plugin \"Loaded plugin …\" diagnostics.\n *\n * A monorepo checkout resolves ~a dozen plugin packages, so emitting a line\n * for each on every command (including `--help` and tab-completion, and into\n * Mist's captured stderr dialog) is noise. The success diagnostics are gated\n * behind an explicit opt-in; load *failures* are always surfaced by the loader\n * regardless of this flag. See CURRENT-3218.\n */\n\nfunction isTruthyFlag(value: string | undefined): boolean {\n return value === \"1\" || value === \"true\";\n}\n\nexport function shouldLogPluginLoads(\n argv: readonly string[] = process.argv,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n if (argv.includes(\"--verbose\")) return true;\n return isTruthyFlag(env[\"FLUID_CLI_DEBUG\"] ?? env[\"FLUID_CLI_VERBOSE\"]);\n}\n","/**\n * Plugin loader — orchestrates discovery and registration\n */\n\nimport type { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport { getAuthToken } from \"../auth/token.js\";\nimport { readConfig } from \"../config/config.js\";\nimport type { FluidPlugin, PluginContext } from \"./types.js\";\nimport { discoverPlugins, importPlugin } from \"./discovery.js\";\nimport {\n formatPluginLoadLine,\n formatPluginLoadFailure,\n} from \"./format-load-line.js\";\nimport { resolveLoadPath } from \"./resolve-load-path.js\";\nimport { shouldLogPluginLoads } from \"./should-log-plugin-loads.js\";\n\nfunction isFluidPlugin(value: unknown): value is FluidPlugin {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n typeof obj[\"name\"] === \"string\" &&\n typeof obj[\"version\"] === \"string\" &&\n typeof obj[\"register\"] === \"function\"\n );\n}\n\n/**\n * Discover, import, and register all installed plugins\n */\nexport async function loadPlugins(\n program: Command,\n basePath: string,\n): Promise<void> {\n const preferInstallation =\n process.env[\"FLUID_CLI_PREFER_INSTALLATION_PLUGINS\"] === \"1\";\n const discovered = discoverPlugins(basePath, undefined, {\n preferInstallation,\n });\n const { enabledPlugins } = readConfig();\n\n // If enabledPlugins is set, only load explicitly allowed plugins.\n // This acts as an allow-list to prevent accidental supply-chain execution.\n const allowedSet = enabledPlugins !== null ? new Set(enabledPlugins) : null;\n const plugins = allowedSet\n ? discovered.filter((p) => allowedSet.has(p.name))\n : discovered;\n\n if (plugins.length === 0) return;\n\n const ctx: PluginContext = {\n program,\n getAuthToken,\n configDir: getConfigDir(),\n };\n\n // Success diagnostics are opt-in (a checkout resolves ~a dozen plugins);\n // load failures below are always surfaced. See CURRENT-3218.\n const verbose = shouldLogPluginLoads();\n\n for (const { name, importSpecifier } of plugins) {\n // Resolve to a concrete path so a published install is distinguishable\n // from a workspace build at a glance.\n const source = resolveLoadPath(importSpecifier);\n try {\n const exported = await importPlugin(importSpecifier);\n\n if (!isFluidPlugin(exported)) {\n console.warn(\n chalk.yellow(`Warning: ${name} does not export a valid FluidPlugin`),\n );\n continue;\n }\n\n await exported.register(ctx);\n\n if (verbose) {\n console.error(\n chalk.dim(\n formatPluginLoadLine({\n name: exported.name,\n version: exported.version,\n importSpecifier: source,\n preferInstallation,\n }),\n ),\n );\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Always name what failed to load and from where — this is exactly the\n // invisible-artifact failure the diagnostic exists to catch.\n console.warn(\n chalk.yellow(\n `Warning: ${formatPluginLoadFailure({\n name,\n importSpecifier: source,\n preferInstallation,\n message,\n })}`,\n ),\n );\n }\n }\n}\n","/**\n * Tell an interactive user, at most once a day, that a newer fluid CLI is\n * on npm. The check never holds a command open: a run prints what the last\n * check found, and a stale cache is refreshed by a detached child process\n * for next time.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, sep } from \"node:path\";\n\nexport const PACKAGE_NAME = \"@fluid-app/fluid-cli\";\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\n/** The argument the CLI entry point treats as \"refresh the cache and exit\". */\nexport const REFRESH_ARG = \"__refresh-update-check\";\nconst FETCH_TIMEOUT_MS = 5000;\nconst CACHE_FILE = \"update-check.json\";\n\nexport interface UpdateCache {\n /** When a check was last started, successful or not. */\n readonly checkedAt: string;\n /** The newest version any check has seen; null before the first success. */\n readonly latest: string | null;\n}\n\nexport interface UpdateCheckEnvironment {\n readonly env: NodeJS.ProcessEnv;\n readonly stdoutIsTTY: boolean;\n readonly stderrIsTTY: boolean;\n /** Real path of the running CLI entry point. */\n readonly entryPath: string;\n /** `process.versions`; an `electron` entry means a bundling app runs us. */\n readonly versions?: Partial<Record<string, string>>;\n}\n\n/** Whether an Electron app, such as Mist, is running the CLI it bundles. */\nexport function isElectronRun(\n env: NodeJS.ProcessEnv,\n versions: Partial<Record<string, string>> = {},\n): boolean {\n return Boolean(env[\"ELECTRON_RUN_AS_NODE\"] || versions[\"electron\"]);\n}\n\n/**\n * Only an installed CLI used by a person checks. Scripts, CI, piped output\n * (completion and `--json` among them), a workspace build and a copy an\n * Electron app bundles (the app updates it) stay quiet.\n */\nexport function shouldCheckForUpdates({\n env,\n stdoutIsTTY,\n stderrIsTTY,\n entryPath,\n versions,\n}: UpdateCheckEnvironment): boolean {\n if (env[\"FLUID_NO_UPDATE_CHECK\"] || env[\"NO_UPDATE_NOTIFIER\"]) return false;\n if (env[\"CI\"]) return false;\n if (isElectronRun(env, versions)) return false;\n if (!stdoutIsTTY || !stderrIsTTY) return false;\n return entryPath.includes(`${sep}node_modules${sep}`);\n}\n\nfunction parseVersion(version: string): [number, number, number] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version.trim());\n if (!match) return null;\n return [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\n/** True when `latest` is a newer release than `current`. Prereleases never count. */\nexport function isNewer(current: string, latest: string): boolean {\n const a = parseVersion(current);\n const b = parseVersion(latest);\n if (!a || !b) return false;\n for (let i = 0; i < 3; i += 1) {\n if (b[i]! !== a[i]!) return b[i]! > a[i]!;\n }\n return false;\n}\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"yarn\" | \"yarn-classic\" | \"bun\";\n\n/** How the running CLI was installed, which decides the update command. */\nexport type InstallKind =\n | { readonly kind: \"global\"; readonly manager: PackageManager }\n | { readonly kind: \"npx\" }\n | {\n readonly kind: \"local\";\n readonly manager: PackageManager;\n readonly projectDir: string;\n };\n\nconst LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n [\"npm-shrinkwrap.json\", \"npm\"],\n];\n\nfunction projectManager(\n projectDir: string,\n exists: (path: string) => boolean,\n): PackageManager {\n // A workspace member has its lockfile at the workspace root, above it.\n for (let dir = projectDir; ; dir = dirname(dir)) {\n for (const [file, manager] of LOCKFILES) {\n if (!exists(join(dir, file))) continue;\n if (manager !== \"yarn\") return manager;\n return exists(join(dir, \".yarnrc.yml\")) ? \"yarn\" : \"yarn-classic\";\n }\n if (dirname(dir) === dir) return \"npm\";\n }\n}\n\n/**\n * Work out from the entry point's real path how the CLI was installed: an\n * npx cache run, a global install (npm's `lib/node_modules`, or npm on\n * Windows, pnpm's and yarn's global directories), or else a project's own\n * `node_modules`.\n */\nexport function detectInstallKind(\n entryPath: string,\n exists: (path: string) => boolean = existsSync,\n): InstallKind {\n const path = entryPath.replaceAll(\"\\\\\", \"/\");\n if (path.includes(\"/_npx/\")) return { kind: \"npx\" };\n if (/\\/pnpm\\/global\\//i.test(path))\n return { kind: \"global\", manager: \"pnpm\" };\n if (/\\/yarn\\/global\\//i.test(path) || path.includes(\"/.yarn-global/\")) {\n return { kind: \"global\", manager: \"yarn-classic\" };\n }\n if (/\\/\\.bun\\/install\\/global\\//.test(path)) {\n return { kind: \"global\", manager: \"bun\" };\n }\n const modules = path.indexOf(\"/node_modules/\");\n const before = modules === -1 ? path : path.slice(0, modules);\n const projectDir = entryPath.slice(0, modules === -1 ? 0 : modules);\n // npm's global root is `<prefix>/lib`, or `%APPDATA%\\npm` on Windows, and\n // neither holds a package.json. A project that happens to live in a\n // directory named `lib` does, and is updated in place.\n const npmGlobalShape = before.endsWith(\"/lib\") || /\\/npm$/i.test(before);\n if (npmGlobalShape && !exists(join(projectDir, \"package.json\"))) {\n return { kind: \"global\", manager: \"npm\" };\n }\n return {\n kind: \"local\",\n manager: projectManager(projectDir, exists),\n projectDir,\n };\n}\n\nconst PLUGINS_NOTE = \"(and any @fluid-app/fluid-cli-* plugins you use)\";\n\nfunction globalCommand(manager: PackageManager): string {\n switch (manager) {\n case \"npm\":\n return `npm install -g ${PACKAGE_NAME}`;\n case \"pnpm\":\n return `pnpm add -g ${PACKAGE_NAME}@latest`;\n case \"yarn\":\n case \"yarn-classic\":\n return `yarn global add ${PACKAGE_NAME}@latest`;\n case \"bun\":\n return `bun add -g ${PACKAGE_NAME}@latest`;\n }\n}\n\nfunction localCommand(manager: PackageManager): string {\n switch (manager) {\n case \"npm\":\n return `npm install ${PACKAGE_NAME}@latest`;\n case \"pnpm\":\n return `pnpm update --latest ${PACKAGE_NAME}`;\n case \"yarn\":\n return `yarn up ${PACKAGE_NAME}@latest`;\n case \"yarn-classic\":\n return `yarn upgrade --latest ${PACKAGE_NAME}`;\n case \"bun\":\n return `bun update --latest ${PACKAGE_NAME}`;\n }\n}\n\nfunction updateInstruction(install: InstallKind): string {\n switch (install.kind) {\n case \"global\":\n return `Run: ${globalCommand(install.manager)} ${PLUGINS_NOTE}\\n`;\n case \"npx\":\n return `Run: npx ${PACKAGE_NAME}@latest to use the latest version\\n`;\n case \"local\":\n return `Run in ${install.projectDir}: ${localCommand(install.manager)} ${PLUGINS_NOTE}\\n`;\n }\n}\n\nexport function updateNotice(\n current: string,\n latest: string,\n install: InstallKind = { kind: \"global\", manager: \"npm\" },\n): string | null {\n if (!isNewer(current, latest)) return null;\n return (\n `\\nUpdate available for fluid: ${current} → ${latest}\\n` +\n updateInstruction(install) +\n `Set FLUID_NO_UPDATE_CHECK=1 to stop these notices.\\n`\n );\n}\n\nexport function readUpdateCache(configDir: string): UpdateCache | null {\n try {\n const data = JSON.parse(\n readFileSync(join(configDir, CACHE_FILE), \"utf8\"),\n ) as Partial<UpdateCache>;\n if (typeof data.checkedAt !== \"string\") return null;\n const latest = typeof data.latest === \"string\" ? data.latest : null;\n return { checkedAt: data.checkedAt, latest };\n } catch {\n return null;\n }\n}\n\n/**\n * Write the cache, reporting whether it landed. The JSON goes to a fresh\n * file opened exclusively, then is renamed over the cache: a rename replaces\n * a symlink planted at the cache path instead of writing through it, so a\n * shared FLUID_CONFIG_DIR can't aim this write at another of the user's files.\n */\nexport function writeUpdateCache(\n configDir: string,\n cache: UpdateCache,\n): boolean {\n const temp = join(\n configDir,\n `.${CACHE_FILE}.${randomBytes(6).toString(\"hex\")}`,\n );\n try {\n mkdirSync(configDir, { recursive: true });\n writeFileSync(temp, JSON.stringify(cache) + \"\\n\", { flag: \"wx\" });\n renameSync(temp, join(configDir, CACHE_FILE));\n return true;\n } catch {\n // A read-only config directory only costs the notice.\n try {\n rmSync(temp, { force: true });\n } catch {\n // Nothing was written if the directory itself is unusable.\n }\n return false;\n }\n}\n\nexport function isStale(cache: UpdateCache | null, now: Date): boolean {\n if (!cache) return true;\n const checkedAt = Date.parse(cache.checkedAt);\n return (\n Number.isNaN(checkedAt) || now.getTime() - checkedAt >= CHECK_INTERVAL_MS\n );\n}\n\nexport async function fetchLatestVersion(\n fetchImpl: typeof fetch = fetch,\n): Promise<string | null> {\n try {\n const response = await fetchImpl(\n `https://registry.npmjs.org/${PACKAGE_NAME}/latest`,\n { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },\n );\n if (!response.ok) return null;\n const body = (await response.json()) as { version?: unknown };\n return typeof body.version === \"string\" ? body.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask npm for the latest version and record it. Runs in the detached child;\n * a failure leaves the last known version and the throttle stamp in place.\n */\nexport async function refreshUpdateCache(\n configDir: string,\n fetchImpl: typeof fetch = fetch,\n now: Date = new Date(),\n): Promise<void> {\n const latest = await fetchLatestVersion(fetchImpl);\n if (latest) {\n writeUpdateCache(configDir, { checkedAt: now.toISOString(), latest });\n }\n}\n\n/** Start `node <entry> __refresh-update-check` detached, so this run never waits on npm. */\nexport function spawnRefresh(entryPath: string): void {\n try {\n const child = spawn(process.execPath, [entryPath, REFRESH_ARG], {\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // No refresh this time; the throttle stamp retries tomorrow.\n }\n}\n\nexport interface StartUpdateCheckOptions extends UpdateCheckEnvironment {\n readonly currentVersion: string;\n readonly configDir: string;\n readonly now?: Date;\n /** Called with the notice when the process exits. */\n readonly onExit?: (listener: () => void) => void;\n readonly refresh?: (entryPath: string) => void;\n}\n\n/**\n * Print the cached notice when the command finishes and, when the last\n * check started a day ago or more, stamp the cache and refresh it in a\n * detached process. The stamp throttles failed and concurrent checks to one\n * a day while keeping the last known version, and its notice, in place.\n */\nexport function startUpdateCheck(options: StartUpdateCheckOptions): void {\n if (!shouldCheckForUpdates(options)) return;\n\n const now = options.now ?? new Date();\n const cache = readUpdateCache(options.configDir);\n const notice = cache?.latest\n ? updateNotice(\n options.currentVersion,\n cache.latest,\n detectInstallKind(options.entryPath),\n )\n : null;\n if (notice) {\n const onExit =\n options.onExit ??\n ((listener: () => void) => process.once(\"exit\", listener));\n onExit(() => process.stderr.write(notice));\n }\n\n if (!isStale(cache, now)) return;\n const stamped = writeUpdateCache(options.configDir, {\n checkedAt: now.toISOString(),\n latest: cache?.latest ?? null,\n });\n // Without the stamp there is no throttle, and the child couldn't record\n // what it found either, so an unwritable cache never starts a refresh.\n if (stamped) (options.refresh ?? spawnRefresh)(options.entryPath);\n}\n","#!/usr/bin/env node\n\nimport { createRequire } from \"node:module\";\nimport { realpathSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { Command } from \"commander\";\nimport { commandsCommand } from \"../commands/commands.js\";\nimport { completeCommand, completionCommand } from \"../commands/completion.js\";\nimport { loginCommand } from \"../commands/login.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport { loadPlugins } from \"../plugins/loader.js\";\nimport { getConfigDir } from \"../config/paths.js\";\nimport {\n REFRESH_ARG,\n refreshUpdateCache,\n startUpdateCheck,\n} from \"../update/notifier.js\";\n\nconst require = createRequire(import.meta.url);\nconst { version } = require(\"../../package.json\") as { version: string };\n\n// The detached update check re-runs this entry point; it only refreshes the\n// cache, without loading plugins or parsing commands.\nif (process.argv[2] === REFRESH_ARG) {\n await refreshUpdateCache(getConfigDir());\n process.exit(0);\n}\n\nconst packageRoot = process.cwd();\n\nconst program = new Command();\n\nprogram.name(\"fluid\").description(\"Fluid Commerce CLI\").version(version);\n\n// Built-in auth commands\nprogram.addCommand(loginCommand);\nprogram.addCommand(logoutCommand);\nprogram.addCommand(whoamiCommand);\nprogram.addCommand(switchCommand);\n\n// Discovery: the command catalog and shell completion\nprogram.addCommand(commandsCommand);\nprogram.addCommand(completionCommand);\nprogram.addCommand(completeCommand, { hidden: true });\n\nstartUpdateCheck({\n currentVersion: version,\n configDir: getConfigDir(),\n env: process.env,\n stdoutIsTTY: Boolean(process.stdout.isTTY),\n stderrIsTTY: Boolean(process.stderr.isTTY),\n entryPath: realpathSync(fileURLToPath(import.meta.url)),\n versions: process.versions,\n});\n\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\nprogram.parse(process.argv, { from: \"node\" });\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,MAAM,EAAE,SAAA,cADQ,cAAc,OAAO,KAAK,IAAI,CAClB,qBAAqB;AAEjD,SAAS,MAAM,OAA6B;CAC1C,MAAM,OAAO,MAAM,UAAU,KAAK,QAAQ;EACxC,MAAM,OAAO,IAAI,WAAW,GAAG,IAAI,KAAK,OAAO,IAAI;AACnD,SAAO,IAAI,WAAW,IAAI,KAAK,KAAK,IAAI,KAAK;GAC7C;AACF,QAAO,CAAC,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,IAAI;;AAG3C,SAAgB,kBAAkB,SAA0C;CAC1E,MAAM,WAAW,QAAQ,QAAQ,UAAU,MAAM,SAAS;CAC1D,MAAM,QAAQ,KAAK,IACjB,IACA,KAAK,IAAI,GAAG,GAAG,SAAS,KAAK,UAAU,MAAM,MAAM,CAAC,OAAO,CAAC,CAC7D;AACD,QAAO,SACJ,KAAK,UAAU;EACd,MAAM,OAAO,MAAM,MAAM;EACzB,MAAM,UAAU,MAAM,YAAY,MAAM,MAAM,EAAE,CAAC,MAAM;AACvD,SAAO,UAAU,GAAG,KAAK,OAAO,MAAM,CAAC,IAAI,YA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only shopName: string;
163
163
  readonly jwt: string;
164
+ /** "rep" for an admin or rep session; "member" or "customer" for a shopper's. */
165
+ readonly authType?: string;
164
166
  }
165
167
  interface ConfirmMfaResponse {
166
168
  readonly authType: string;
@@ -172,13 +174,26 @@ interface ConfirmMfaResponse {
172
174
  declare function validateToken(token: string): Promise<Result<CompanyInfo, FluidApiError>>;
173
175
  /**
174
176
  * Send a multi-factor authentication code to the given email address.
175
- * Always returns 201 from the API (anti-enumeration).
177
+ * The API answers 201 whether or not the address can sign in
178
+ * (anti-enumeration).
179
+ *
180
+ * With `fluidShop`, the server ties the code to the person's membership in
181
+ * that company, so redeeming it signs in to that company alone and, for an
182
+ * admin's emailed code, confirms a new signup.
176
183
  */
177
- declare function sendMfa(email: string): Promise<Result<MfaResponse, FluidApiError>>;
184
+ declare function sendMfa(email: string, options?: {
185
+ readonly fluidShop?: string;
186
+ }): Promise<Result<MfaResponse, FluidApiError>>;
178
187
  /**
179
188
  * Confirm a multi-factor authentication code and retrieve company JWTs.
189
+ *
190
+ * `baseUrl` is the API the code was sent from; a sign-in finished in a
191
+ * later process passes the one it saved, not the current environment's.
180
192
  */
181
- declare function confirmMfa(uuid: string, code: string): Promise<Result<ConfirmMfaResponse, FluidApiError>>;
193
+ declare function confirmMfa(uuid: string, code: string, options?: {
194
+ readonly fluidShop?: string;
195
+ readonly baseUrl?: string;
196
+ }): Promise<Result<ConfirmMfaResponse, FluidApiError>>;
182
197
  /**
183
198
  * Fetch all companies the authenticated user has access to.
184
199
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/config/types.ts","../src/config/paths.ts","../src/config/config.ts","../src/config/project-config.ts","../src/utils/errors.ts","../src/utils/result.ts","../src/auth/fluid-api.ts","../src/auth/token.ts","../src/plugins/types.ts","../../../platform/api-client-core/src/fetch-client.ts","../src/domain/types.ts","../src/domain/command.ts","../src/domain/context.ts","../src/domain/output.ts","../src/walk/prompter.ts","../src/git-sync/commit-subject.ts","../src/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AAA;ElBHA;EAAA,SkBKA,IAAA;AAAA;AAAA,UAGM,iBAAA;ElBGJ;EAAA,SkBDF,SAAA,YAAqB,eAAA;ElBGX;EAAA,SkBDV,MAAA;AAAA;;;;;iBAWK,eAAA,WAA0B,OAAA,CAAA,CACxC,OAAA,EAAS,CAAA,EACT,UAAA,EAAY,iBAAA,GACX,CAAA;;;UCzBc,aAAA;EAAA,SACN,KAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;EAAA,SACA,WAAA;EnBIA;EAAA,SmBFA,UAAA;EnBIE;EAAA,SmBFF,aAAA;EnBIU;EAAA,SmBFV,QAAA;EAAA,SACA,YAAA;AAAA;AAAA,UAGM,eAAA;EAAA,SACN,IAAA;EAAA,SACA,WAAA;EAAA,SACA,QAAA;EAAA,SACA,QAAA;AAAA;AAAA,UAGM,YAAA;EnBJf;EAAA,SmBMS,OAAA;EAAA,SACA,IAAA;EAAA,SACA,WAAA;EAAA,SACA,OAAA;EAAA,SACA,SAAA,WAAoB,eAAA;EAAA,SACpB,OAAA,WAAkB,aAAA;EnBM3B;EAAA,SmBJS,mBAAA;EAAA,SACA,WAAA;EnBG2B;EAAA,SmBD3B,QAAA;EnBIwB;EAAA,SmBFxB,MAAA;EnBE4B;EAAA,SmBA5B,SAAA,WAAoB,eAAA;AAAA;AAAA,iBAoDf,YAAA,CAAa,IAAA,EAAM,OAAA,GAAU,YAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/config/types.ts","../src/config/paths.ts","../src/config/config.ts","../src/config/project-config.ts","../src/utils/errors.ts","../src/utils/result.ts","../src/auth/fluid-api.ts","../src/auth/token.ts","../src/plugins/types.ts","../../../platform/api-client-core/src/fetch-client.ts","../src/domain/types.ts","../src/domain/command.ts","../src/domain/context.ts","../src/domain/output.ts","../src/walk/prompter.ts","../src/git-sync/commit-subject.ts","../src/git-sync/change-summary.ts","../src/git-sync/actor-cache.ts","../src/catalog/annotations.ts","../src/catalog/walk.ts"],"mappings":";;;;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,YAAA;;;UCzFM,eAAA;EAAA,SACN,MAAA;ElBHA;EAAA,SkBKA,IAAA;AAAA;AAAA,UAGM,iBAAA;ElBGJ;EAAA,SkBDF,SAAA,YAAqB,eAAA;ElBGX;EAAA,SkBDV,MAAA;AAAA;;;;;iBAWK,eAAA,WAA0B,OAAA,CAAA,CACxC,OAAA,EAAS,CAAA,EACT,UAAA,EAAY,iBAAA,GACX,CAAA;;;UCzBc,aAAA;EAAA,SACN,KAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;EAAA,SACA,WAAA;EnBIA;EAAA,SmBFA,UAAA;EnBIE;EAAA,SmBFF,aAAA;EnBIU;EAAA,SmBFV,QAAA;EAAA,SACA,YAAA;AAAA;AAAA,UAGM,eAAA;EAAA,SACN,IAAA;EAAA,SACA,WAAA;EAAA,SACA,QAAA;EAAA,SACA,QAAA;AAAA;AAAA,UAGM,YAAA;EnBJf;EAAA,SmBMS,OAAA;EAAA,SACA,IAAA;EAAA,SACA,WAAA;EAAA,SACA,OAAA;EAAA,SACA,SAAA,WAAoB,eAAA;EAAA,SACpB,OAAA,WAAkB,aAAA;EnBM3B;EAAA,SmBJS,mBAAA;EAAA,SACA,WAAA;EnBG2B;EAAA,SmBD3B,QAAA;EnBIwB;EAAA,SmBFxB,MAAA;EnBE4B;EAAA,SmBA5B,SAAA,WAAoB,eAAA;AAAA;AAAA,iBAoDf,YAAA,CAAa,IAAA,EAAM,OAAA,GAAU,YAAA"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as unwrapOr, C as isSuccess, D as tryCatch, E as success, F as walkCommands, I as describeCommand, O as tryCatchAsync, S as isNodeError, T as mapResult, _ as validateToken, a as readConfig, b as isError, c as getConfigDir, f as confirmMfa, g as switchCompany, h as sendMfa, i as findProjectConfig, k as unwrap, l as getConfigFilePath, m as getFluidApiBase, n as getAuthToken, o as updateConfig, p as fetchUserCompanies, r as listProfileNames, s as writeConfig, t as getActiveProfile, u as createDefaultConfig, v as failure, w as mapError, x as isFailure, y as getErrorMessage } from "./token-6SEVoGMw.mjs";
1
+ import { A as unwrapOr, C as isSuccess, D as tryCatch, E as success, F as walkCommands, I as describeCommand, O as tryCatchAsync, S as isNodeError, T as mapResult, _ as validateToken, a as readConfig, b as isError, c as createDefaultConfig, f as confirmMfa, g as switchCompany, h as sendMfa, i as findProjectConfig, k as unwrap, l as getConfigDir, m as getFluidApiBase, n as getAuthToken, o as updateConfig, p as fetchUserCompanies, r as listProfileNames, s as writeConfig, t as getActiveProfile, u as getConfigFilePath, v as failure, w as mapError, x as isFailure, y as getErrorMessage } from "./token-DnFYT9pe.mjs";
2
2
  import { Command } from "commander";
3
3
  import prompts from "prompts";
4
4
  //#region ../../platform/api-client-core/src/api-error-shape.ts