@fluid-app/fluid-cli 0.1.353 → 0.1.355

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":["readAll"],"sources":["../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../src/auth/identity/profiles.ts","../../src/auth/identity/sign-in-path.ts","../../src/auth/pending-login.ts","../../src/auth/profiles.ts","../../src/utils/shell.ts","../../src/commands/login-identity.ts","../../src/commands/login.ts","../../src/commands/signup.ts","../../src/commands/logout.ts","../../src/commands/whoami.ts","../../src/commands/switch.ts","../../src/auth/identity/prime.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 * Ending identity sessions when the profiles that use them go away.\n *\n * `fluid switch` gives each company its own profile, and in identity mode\n * those profiles share the session they were switched from. A session is\n * revoked only once no profile is left that uses it.\n */\n\nimport {\n type FluidConfig,\n type IdentityProfileAuth,\n isIdentityProfile,\n} from \"../../config/types.js\";\nimport { describeIdentityError, signOutIdentity } from \"./session.js\";\n\nfunction sessionsIn(config: FluidConfig): Map<string, IdentityProfileAuth> {\n const found = new Map<string, IdentityProfileAuth>();\n for (const profile of Object.values(config.profiles)) {\n if (!isIdentityProfile(profile)) continue;\n const { auth } = profile;\n found.set(`${auth.identityUrl} ${auth.storageKey}`, auth);\n }\n return found;\n}\n\n/**\n * Revokes every identity session `before` used that `after` no longer does,\n * and deletes its refresh token from the credential store. Resolves with a\n * message for each session that could not be ended cleanly; never rejects.\n */\nexport async function endUnusedSessions(\n before: FluidConfig,\n after: FluidConfig,\n): Promise<string[]> {\n const remaining = sessionsIn(after);\n const problems: string[] = [];\n for (const [key, auth] of sessionsIn(before)) {\n if (remaining.has(key)) continue;\n try {\n await signOutIdentity(auth);\n } catch (error) {\n problems.push(describeIdentityError(error));\n }\n }\n return problems;\n}\n","/**\n * Which way a sign-in completes, as Rails decides it from the company flag\n * (Phase 007 INV-7.1). The CLI never decides it on its own.\n *\n * Mirrors apps/fluid-login: the email step answers every address the same\n * way, and a person whose company is flagged is emailed a sign-in link\n * instead of a code. When a code is confirmed, `confirm_mfa` answers\n * `sign_in_path: \"identity\"` once every company the code covered signs in\n * through the identity service, and hands out no token for them\n * (`Identity::LegacySignInGate`).\n */\n\nimport type { ConfirmMfaResponse } from \"../fluid-api.js\";\n\nexport type SignInPath = \"identity\" | \"legacy\";\n\n/**\n * The path a confirmed code puts the person on. A confirmation that kept any\n * company's legacy token stays on the legacy path: those companies are not\n * flagged, and their tokens are listed exactly as before.\n */\nexport function signInPathFor(confirmation: ConfirmMfaResponse): SignInPath {\n return confirmation.signInPath === \"identity\" ? \"identity\" : \"legacy\";\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, IdentityProfileAuth } 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\ninterface CreateIdentityProfileInput {\n readonly name: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly auth: IdentityProfileAuth;\n readonly storedAt?: string;\n}\n\n/**\n * An identity-mode profile. It holds no token: the refresh token is in the\n * operating system credential store under `auth.storageKey`.\n */\nexport function createIdentityProfile({\n name,\n companyName,\n baseUrl,\n auth,\n storedAt,\n}: CreateIdentityProfileInput): FluidProfile {\n return {\n name,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n auth,\n };\n}\n","// Characters an email, shop or profile name can hold that are safe to paste\n// into a shell. No leading \"-\", which a command would read as a flag.\nconst SHELL_SAFE = /^[\\w@+][\\w.@+-]*$/;\n\n/**\n * The value for a printed command, or the placeholder when it holds\n * characters a shell would act on.\n */\nexport function shellSafe(value: string, placeholder: string): string {\n return SHELL_SAFE.test(value) ? value : placeholder;\n}\n","/**\n * `fluid login` for a company on the identity sign-in path: the browser,\n * a loopback redirect, and a session in the operating system credential\n * store. Reached only when Rails says so (see auth/identity/sign-in-path.ts):\n * a confirmed code answered `sign_in_path: \"identity\"`, or the person pasted\n * the sign-in link Rails emailed them instead of a code.\n *\n * It reports an outcome rather than printing one, so `fluid login` shows it\n * in text or `--json` like every other sign-in.\n */\n\nimport {\n getFluidApiBase,\n redeemIdentityLink,\n type validateToken,\n} from \"../auth/fluid-api.js\";\nimport { resolveIdentityUrl } from \"../auth/identity/environment.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n signInWithBrowser,\n signOutIdentity,\n} from \"../auth/identity/session.js\";\nimport { createIdentityProfile } from \"../auth/profiles.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { CliError } from \"../utils/errors.js\";\n\n/** The query parameter Rails puts the sign-in link's token in. */\nconst IDENTITY_LINK_PARAM = \"identityLink\";\n\n/** The roles the CLI's commands accept, as with a legacy `rep` session. */\nconst STAFF_ROLES = new Set([\"admin\", \"rep\", \"root_admin\"]);\n\n/**\n * The token in a pasted identity sign-in link, or null when the input is not\n * such a link.\n */\nexport function identityLinkToken(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed.includes(`${IDENTITY_LINK_PARAM}=`)) return null;\n try {\n const url = new URL(trimmed);\n return url.searchParams.get(IDENTITY_LINK_PARAM) || null;\n } catch {\n return null;\n }\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\nexport interface IdentityLoginContext {\n /** `--name`: the profile to store, instead of the company's name. */\n readonly profileName?: string;\n /** The API base the sign-in started against. Defaults to the CLI's. */\n readonly apiBase?: string;\n /** Progress lines for the person, the sign-in URL among them. */\n readonly log: (line: string) => void;\n readonly spinner: (text: string) => Spinner;\n readonly validateToken: typeof validateToken;\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n /**\n * Called once a pasted link is spent or reported gone, never on a failure\n * that leaves it redeemable, so a caller tracking the sign-in can keep it\n * for a retry.\n */\n readonly onLinkSettled?: () => void;\n /** Whether an existing profile of this name may be replaced. */\n readonly decideOverwrite: (\n profileName: string,\n ) => Promise<\"replace\" | \"keep\" | \"refuse\">;\n}\n\nexport type IdentityLoginOutcome =\n | {\n readonly status: \"signed_in\";\n readonly profileName: string;\n readonly companyName: string;\n }\n | { readonly status: \"failed\"; readonly error: CliError }\n /** The person chose to keep the existing profile. */\n | { readonly status: \"kept\"; readonly profileName: string }\n /** An existing profile would be replaced and no one could be asked. */\n | { readonly status: \"refused\"; readonly profileName: string };\n\nfunction failed(code: string, message: string): IdentityLoginOutcome {\n return { status: \"failed\", error: { code, message } };\n}\n\n/** Signs in through the identity service and stores the profile. */\nexport async function loginWithIdentity(\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const apiBase = context.apiBase ?? getFluidApiBase();\n let identityUrl: string | null;\n try {\n identityUrl = resolveIdentityUrl(apiBase);\n } catch (error) {\n return failed(\n \"IDENTITY_URL_INVALID\",\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!identityUrl) {\n return failed(\n \"IDENTITY_URL_UNKNOWN\",\n `No Fluid identity service is known for ${apiBase}. Set FLUID_IDENTITY_URL to sign in.`,\n );\n }\n\n context.log(\"Your company signs in through Fluid's identity service.\");\n let signIn: Awaited<ReturnType<typeof signInWithBrowser>>;\n try {\n signIn = await signInWithBrowser({ identityUrl, log: context.log });\n } catch (error) {\n return failed(\"IDENTITY_SIGN_IN_FAILED\", describeIdentityError(error));\n }\n\n // The CLI's commands take an admin or rep session, never a shopper's.\n if (!signIn.facts.roles.some((role) => STAFF_ROLES.has(role))) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"SHOPPER_SESSION\",\n \"This account does not sign in as an admin or rep, so it cannot sign in to the CLI.\",\n );\n }\n\n // The company's display name; the session itself knows only its id.\n const spinner = context.spinner(\"Loading your company...\");\n // Asked of the API the sign-in started against, never the environment's.\n const company = await context.validateToken(signIn.accessToken, {\n baseUrl: apiBase,\n });\n const companyName = company.success\n ? company.value.name\n : (signIn.facts.companyId ?? \"Fluid\");\n spinner.succeed(`Signed in to ${companyName}`);\n\n const profileName = context.profileName ?? companyName;\n const decision = await context.decideOverwrite(profileName);\n if (decision !== \"replace\") {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return decision === \"keep\"\n ? { status: \"kept\", profileName }\n : { status: \"refused\", profileName };\n }\n\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createIdentityProfile({\n name: profileName,\n companyName,\n baseUrl: apiBase,\n auth: signIn.auth,\n }),\n },\n }));\n // A profile this one replaced may have been the last user of its session.\n for (const problem of await endUnusedSessions(before, after)) {\n context.log(problem);\n }\n\n return { status: \"signed_in\", profileName, companyName };\n}\n\n/**\n * Redeems a pasted sign-in link with Rails, which confirms the person's\n * company signs in through the identity service, then signs in.\n */\nexport async function loginWithIdentityLink(\n token: string,\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const spinner = context.spinner(\"Checking the sign-in link...\");\n const redemption = await (context.redeemIdentityLink ?? redeemIdentityLink)(\n token,\n { baseUrl: context.apiBase },\n );\n if (!redemption.success) {\n spinner.fail(redemption.error.message);\n // Only a link Rails reports as gone is settled; any other failure may\n // not have spent it, so the caller keeps what it needs to retry.\n if (redemption.error.code === \"LINK_GONE\") context.onLinkSettled?.();\n return { status: \"failed\", error: redemption.error };\n }\n context.onLinkSettled?.();\n spinner.succeed(\"Sign-in link accepted\");\n return loginWithIdentity(context);\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 * A company on the identity sign-in path is emailed a link instead of a\n * code, and Rails may answer a confirmed code with `sign_in_path:\n * \"identity\"`. Either way the sign-in continues through the browser\n * (commands/login-identity.ts); the CLI never picks the path itself.\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 redeemIdentityLink,\n type CompanyChoice,\n type FluidApiError,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { signInPathFor } from \"../auth/identity/sign-in-path.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\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport {\n identityLinkToken,\n loginWithIdentity,\n loginWithIdentityLink,\n type IdentityLoginContext,\n type IdentityLoginOutcome,\n} from \"./login-identity.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 /** Defaults to the real redemption when a caller does not stand one in. */\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\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\nasync function storeProfile(\n deps: LoginDeps,\n profileName: string,\n token: string,\n companyName: string,\n baseUrl: string = getFluidApiBase(),\n): Promise<void> {\n const before = readConfig();\n const after = 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 // Replacing an identity-mode profile ends its session if nothing else\n // uses it, so no refresh token is left behind in the credential store.\n for (const problem of await endUnusedSessions(before, after)) {\n deps.err(chalk.yellow(problem));\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\n/**\n * What the identity sign-in needs from this run: its output, its overwrite\n * rule, and the API base the sign-in started against. With `--json` the\n * person still needs the sign-in URL, so progress goes to stderr.\n */\nfunction identityContext(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n apiBase?: string,\n): IdentityLoginContext {\n return {\n profileName: opts.name,\n apiBase,\n log: (line) =>\n ui.json\n ? deps.err(line)\n : deps.log(line.startsWith(\"http\") ? line : chalk.cyan(line)),\n spinner: (text) => ui.spinner(text),\n // Every request of this sign-in goes to `apiBase` when it has one: a\n // two-step sign-in's is the API its code was sent from.\n validateToken: (token, options) =>\n deps.api.validateToken(token, { baseUrl: apiBase, ...options }),\n redeemIdentityLink: deps.api.redeemIdentityLink,\n decideOverwrite: (profileName) =>\n overwriteDecision(\n profileName,\n { yes: Boolean(opts.yes), interactive },\n deps,\n ),\n };\n}\n\nfunction identityResult(\n outcome: IdentityLoginOutcome,\n ui: Ui,\n deps: LoginDeps,\n): number {\n switch (outcome.status) {\n case \"signed_in\":\n return loggedIn(ui, deps, outcome.profileName, {\n name: outcome.companyName,\n });\n case \"kept\":\n return cancelled(deps);\n case \"refused\":\n return ui.fail(profileExists(outcome.profileName, false));\n case \"failed\":\n return ui.fail(outcome.error);\n }\n}\n\nconst LINK_HINT =\n \"If the email has a sign-in link instead of a code, paste the link here.\";\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 await storeProfile(deps, 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 if (!ui.json) deps.log(chalk.dim(LINK_HINT));\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 // A flagged company's person is emailed a link, not a code.\n const linkToken = identityLinkToken(code);\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(\n linkToken,\n identityContext(opts, true, ui, deps),\n ),\n ui,\n deps,\n );\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 // Every company the code covered signs in through the identity service,\n // so Rails handed out no token (Phase 007 INV-7.5).\n if (signInPathFor(confirmResult.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity(identityContext(opts, true, ui, deps)),\n ui,\n deps,\n );\n }\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 await storeProfile(deps, 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/**\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 return `fluid login --code --email ${shellSafe(email, \"<email>\")} --shop ${shellSafe(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). For a new signup, `fluid signup` prints it as fluidShop.\",\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 \"If the email has a sign-in link instead of a code, pass the link the same way. \" +\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 \"(pass that link to --code in place of the code). 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 // A flagged company's person is emailed a link, not a code: redeeming it\n // finishes this sign-in through the identity service instead.\n const linkToken = identityLinkToken(code);\n if (!linkToken && !/^\\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 a code, or redeeming a link, uses it up, so a named profile\n // that would be refused is checked first. Without a terminal, the check\n // above has already 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 if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n // The pending sign-in ends only once the link is spent or gone; a\n // failure that may not have spent it keeps it for a retry.\n onLinkSettled: () => deps.pending.remove(email),\n }),\n ui,\n deps,\n );\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 // Rails handed out no token: every company the code covered signs in\n // through the identity service (Phase 007 INV-7.5).\n if (signInPathFor(confirmed.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity(\n identityContext(opts, interactive, ui, deps, record.baseUrl),\n ),\n ui,\n deps,\n );\n }\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 await storeProfile(deps, 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 signup — create a Fluid company with the public signup endpoint\n *\n * Runs before any sign-in, so it calls `POST /api/company` directly rather\n * than through a profile's client. The person behind the email then\n * confirms the signup, by the emailed link or by signing in with the two\n * `fluid login` steps this command prints.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport prompts from \"prompts\";\nimport {\n signup,\n type SignupError,\n type SignupRequest,\n} from \"../auth/fluid-api.js\";\nimport { normaliseEmail } from \"../auth/pending-login.js\";\nimport { shellSafe } from \"../utils/shell.js\";\n\nexport interface SignupOptions {\n readonly email?: string;\n readonly firstName?: string;\n readonly lastName?: string;\n readonly companyName?: string;\n readonly subdomain?: string;\n readonly color?: string;\n readonly yes?: boolean;\n readonly json?: boolean;\n}\n\ninterface Spinner {\n stop(): unknown;\n}\n\n/** Everything `runSignup` reaches outside itself, for tests. */\nexport interface SignupDeps {\n readonly api: { readonly signup: typeof signup };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n /** Shown in text mode while the signup runs, which can take a while. */\n readonly spinner: (text: string) => Spinner;\n readonly log: (line: string) => void;\n readonly isInteractive: () => boolean;\n}\n\nexport const defaultSignupDeps: SignupDeps = {\n api: { signup },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n isInteractive: () => Boolean(process.stdin.isTTY),\n};\n\n// The same DNS-label rule the server validates a new subdomain against.\nconst SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * The subdomain as the server would store it: lowercase, letters, digits\n * and hyphens only, at most 63 characters, no hyphen at either end. The\n * server checks \"is taken\" against the value as sent, before it cleans it\n * up, so sending the clean form keeps that check meaningful.\n */\nexport function normaliseSubdomain(raw: string): string {\n const trimmed = (value: string) => value.replace(/^-+|-+$/g, \"\");\n return trimmed(\n trimmed(raw.toLowerCase())\n .replace(/[^a-z0-9-]/g, \"\")\n .slice(0, 63),\n );\n}\n\n/**\n * The two commands that sign in to the new company and confirm it. The\n * second names its own profile rather than passing `--yes`, which would\n * replace an existing profile that happens to share the company's name.\n * If a profile with that name exists, login refuses `--name` before the code\n * is spent when there is no terminal, and asks first at one.\n */\nexport function nextCommands(\n email: string,\n fluidShop: string,\n subdomain: string,\n): string[] {\n const safeEmail = shellSafe(email, \"<email>\");\n const safeShop = shellSafe(fluidShop, \"<shop>\");\n return [\n `fluid login --send-code --email ${safeEmail} --shop ${safeShop}`,\n `fluid login --code --email ${safeEmail} --shop ${safeShop} --name ${shellSafe(subdomain, \"<profile>\")}`,\n ];\n}\n\nconst REQUIRED_FLAGS: ReadonlyArray<[keyof SignupOptions, string]> = [\n [\"email\", \"--email\"],\n [\"firstName\", \"--first-name\"],\n [\"lastName\", \"--last-name\"],\n [\"companyName\", \"--company-name\"],\n [\"subdomain\", \"--subdomain\"],\n];\n\n/** The request to send, or why the flags can't make one. */\nfunction buildRequest(\n opts: SignupOptions,\n): { request: SignupRequest } | { error: SignupError } {\n const missing = REQUIRED_FLAGS.filter(([key]) => {\n const value = opts[key];\n return typeof value !== \"string\" || value.trim() === \"\";\n }).map(([, flag]) => flag);\n if (missing.length > 0) {\n return {\n error: {\n code: \"FLAGS_REQUIRED\",\n message: `fluid signup needs ${missing.join(\", \")}.`,\n },\n };\n }\n\n const email = normaliseEmail(opts.email ?? \"\");\n if (!EMAIL_PATTERN.test(email)) {\n return {\n error: {\n code: \"INVALID_EMAIL\",\n message: `${email} is not an email address.`,\n },\n };\n }\n\n const subdomain = normaliseSubdomain(opts.subdomain ?? \"\");\n if (!SUBDOMAIN_PATTERN.test(subdomain)) {\n return {\n error: {\n code: \"INVALID_SUBDOMAIN\",\n message:\n \"--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters.\",\n },\n };\n }\n\n const color = opts.color?.trim().replace(/^#/, \"\");\n if (color !== undefined && !COLOR_PATTERN.test(color)) {\n return {\n error: {\n code: \"INVALID_COLOR\",\n message: \"--color must be a 3- or 6-digit hex colour, such as 0C7CF6.\",\n },\n };\n }\n\n return {\n request: {\n email,\n firstName: (opts.firstName ?? \"\").trim(),\n lastName: (opts.lastName ?? \"\").trim(),\n companyName: (opts.companyName ?? \"\").trim(),\n subdomain,\n ...(color ? { color } : {}),\n },\n };\n}\n\n// A plain CliError fits too: every field SignupError adds is optional.\nfunction printFailure(\n error: SignupError,\n json: boolean,\n deps: SignupDeps,\n): number {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.status !== undefined ? { httpStatus: error.status } : {}),\n ...(error.errors ? { errors: error.errors } : {}),\n ...(error.retryAfter !== undefined\n ? { retryAfter: error.retryAfter }\n : {}),\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n deps.log(chalk.red(error.message));\n if (error.errors) deps.log(chalk.dim(JSON.stringify(error.errors)));\n if (error.retryAfter !== undefined) {\n deps.log(chalk.dim(`Retry after ${error.retryAfter} seconds.`));\n }\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n}\n\n/**\n * Run `fluid signup` and return its exit code.\n */\nexport async function runSignup(\n opts: SignupOptions,\n deps: SignupDeps = defaultSignupDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const built = buildRequest(opts);\n if (\"error\" in built) return printFailure(built.error, json, deps);\n const { request } = built;\n\n if (!opts.yes) {\n const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;\n // `--json` is for a program reading the output, which cannot answer a\n // prompt, and a closed stdin never answers one either.\n if (json || !deps.isInteractive()) {\n return printFailure(\n {\n code: \"CONFIRM_REQUIRED\",\n message: `${question} Pass --yes to confirm.`,\n },\n json,\n deps,\n );\n }\n const answer = await deps.prompt({\n type: \"confirm\",\n name: \"ok\",\n message: question,\n initial: false,\n });\n if (!answer[\"ok\"]) {\n return printFailure(\n { code: \"CANCELLED\", message: \"Cancelled.\" },\n json,\n deps,\n );\n }\n }\n\n const spinner = json ? undefined : deps.spinner(\"Signing up...\");\n const result = await deps.api.signup(request);\n spinner?.stop();\n if (!result.success) return printFailure(result.error, json, deps);\n\n const created = result.value;\n const next = nextCommands(\n request.email,\n created.company.fluidShop,\n created.company.subdomain,\n );\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"signed_up\",\n company: created.company,\n userCompany: created.userCompany,\n currentlyDue: created.currentlyDue,\n next,\n },\n null,\n 2,\n ),\n );\n return 0;\n }\n\n deps.log(\n chalk.green(\n `Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`,\n ),\n );\n if (request.subdomain !== (opts.subdomain ?? \"\").trim()) {\n deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));\n }\n deps.log(\n `${request.email} confirms it from the emailed link, or by signing in with the emailed code:`,\n );\n for (const command of next) deps.log(` ${command}`);\n deps.log(\n chalk.dim(\n \"A repeat signup for the same email within an hour normally sends no new email.\",\n ),\n );\n return 0;\n}\n\n/**\n * The `signup` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing up.\n */\nexport function buildSignupCommand(\n run: (opts: SignupOptions) => Promise<number> = (opts) => runSignup(opts),\n): Command {\n return new Command(\"signup\")\n .description(\n \"Create a Fluid company with the public signup; the person behind --email confirms it\",\n )\n .option(\n \"-e, --email <email>\",\n \"The person's email address; Fluid emails it to confirm the signup\",\n )\n .option(\"--first-name <name>\", \"The person's first name\")\n .option(\"--last-name <name>\", \"The person's last name\")\n .option(\"--company-name <name>\", \"The company's name\")\n .option(\n \"--subdomain <subdomain>\",\n \"The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only\",\n )\n .option(\n \"--color <hex>\",\n \"Brand colour as 3 or 6 hex digits, such as 0C7CF6\",\n )\n .option(\"-y, --yes\", \"Sign up without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: SignupOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const signupCommand = buildSignupCommand();\n","/**\n * fluid logout — remove stored auth profile(s)\n *\n * An identity-mode profile's session is revoked at the identity service and\n * its refresh token deleted from the credential store, once no remaining\n * profile uses it. (The identity service's `/signout` is a browser\n * navigation; a native client revokes its refresh token instead.)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\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(async (opts: { all?: boolean }) => {\n const config = readConfig();\n\n if (opts.all) {\n const after = {\n ...config,\n activeProfile: null,\n profiles: {},\n };\n writeConfig(after);\n for (const problem of await endUnusedSessions(config, after)) {\n console.log(chalk.yellow(problem));\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 const after = {\n ...config,\n activeProfile: nextActive,\n profiles: remainingProfiles,\n };\n writeConfig(after);\n for (const problem of await endUnusedSessions(config, after)) {\n console.log(chalk.yellow(problem));\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 * An identity-mode profile is shown from its identity session: the facts\n * come from the identity service's `/userinfo`, never from decoding a token.\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\";\nimport {\n describeIdentityError,\n identityToken,\n} from \"../auth/identity/session.js\";\nimport { type IdentityProfile, isIdentityProfile } from \"../config/types.js\";\n\nasync function whoamiIdentity(profile: IdentityProfile): Promise<void> {\n const spinner = ora(\"Checking your identity session...\").start();\n let facts;\n try {\n ({ facts } = await identityToken(profile.auth));\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (Fluid identity service)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n if (facts.companyId) {\n console.log(` Company ID: ${chalk.dim(facts.companyId)}`);\n }\n console.log(` Subject: ${chalk.dim(facts.subject)}`);\n if (facts.roles.length > 0) {\n console.log(` Roles: ${facts.roles.join(\", \")}`);\n }\n if (facts.impersonating && facts.actor) {\n console.log(` Acting as: ${chalk.yellow(facts.actor)}`);\n }\n console.log(\n ` Signed in: ${chalk.dim(new Date(facts.authTime * 1000).toISOString())}`,\n );\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\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 if (isIdentityProfile(profile)) {\n await whoamiIdentity(profile);\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 * An identity-mode profile switches by token exchange (Phase 007 FR-3): the\n * session it signed in with stays as it is, and the new company's profile\n * remembers the company to exchange into. Nothing secret is written.\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 { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n identityToken,\n sessionFacts,\n} from \"../auth/identity/session.js\";\nimport { createFluidProfile, createIdentityProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport { type IdentityProfile, isIdentityProfile } from \"../config/types.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\nasync function performIdentitySwitch(\n profile: IdentityProfile,\n company: UserCompany,\n baseUrl: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n if (!company.uuidV7) {\n spinner.fail(\n chalk.red(`${company.name} has no identifier to switch to it by.`),\n );\n process.exitCode = 1;\n return;\n }\n\n let org: string | undefined;\n try {\n // Back to the company the session signed in to needs no exchange.\n const home = (await sessionFacts(profile.auth)).companyId;\n org = company.uuidV7 === home ? undefined : company.uuidV7;\n await identityToken(profile.auth, org ?? null);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n\n const { org: _previous, ...session } = profile.auth;\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: company.name,\n profiles: {\n ...config.profiles,\n [company.name]: createIdentityProfile({\n name: company.name,\n companyName: company.name,\n baseUrl,\n auth: org ? { ...session, org } : session,\n }),\n },\n }));\n const problems = await endUnusedSessions(before, after);\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of problems) console.log(chalk.yellow(problem));\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 activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n const identity = isIdentityProfile(activeProfile) ? activeProfile : null;\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n let token = activeProfile.token ?? \"\";\n if (identity) {\n try {\n token = (await identityToken(identity.auth)).accessToken;\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n }\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 (identity\n ? performIdentitySwitch(identity, match, activeBaseUrl)\n : 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 (identity\n ? performIdentitySwitch(identity, selected, activeBaseUrl)\n : performSwitch(token, selected, activeBaseUrl));\n });\n","/**\n * Restores an identity-mode profile's session before a command runs, so the\n * synchronous `getAuthToken()` that plugins call finds a current access\n * token in memory. Legacy profiles and literal tokens are left alone: no\n * credential store is touched and no request is made for them.\n */\n\nimport chalk from \"chalk\";\n\nimport { isIdentityProfile } from \"../../config/types.js\";\nimport { resolveCredentialSource } from \"../token.js\";\nimport { describeIdentityError, primeIdentityProfile } from \"./session.js\";\n\nexport interface CommandCredentialOptions {\n readonly token?: unknown;\n readonly profile?: unknown;\n}\n\n/**\n * Primes the credential a command with these options would use. A session\n * that cannot be restored is reported on stderr, and the command runs on as\n * it would with no stored credential.\n */\nexport async function primeCommandCredential(\n options: CommandCredentialOptions,\n): Promise<void> {\n if (typeof options.token === \"string\" && options.token) return;\n const profileName =\n typeof options.profile === \"string\" && options.profile\n ? options.profile\n : undefined;\n const source = resolveCredentialSource(profileName);\n if (source?.kind !== \"profile\" || !isIdentityProfile(source.profile)) return;\n try {\n await primeIdentityProfile(source.profile);\n } catch (error) {\n process.stderr.write(`${chalk.yellow(describeIdentityError(error))}\\n`);\n }\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 { isStrictConfig } from \"../config/strict.js\";\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 = () =>\n isStrictConfig() ? [] : discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath && !isStrictConfig()\n ? []\n : 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 { signupCommand } from \"../commands/signup.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport {\n exitOnInputsError,\n inputsModeActive,\n registerInputsHook,\n} from \"../inputs/hook.js\";\nimport { primeCommandCredential } from \"../auth/identity/prime.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, and the signup that comes before them\nprogram.addCommand(signupCommand);\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\n// Commands that resolve their own credential, or need none.\nconst selfAuthenticating = new Set(\n [\n signupCommand,\n loginCommand,\n logoutCommand,\n whoamiCommand,\n switchCommand,\n commandsCommand,\n completionCommand,\n completeCommand,\n ].map((command) => command.name()),\n);\n\nregisterInputsHook(program);\n\n// An identity-mode profile's access token lives only in memory, so restore\n// its session before any other command runs; plugins read the token\n// synchronously through getAuthToken().\nprogram.hook(\"preAction\", async (_program, actionCommand) => {\n let topLevel: Command = actionCommand;\n while (topLevel.parent && topLevel.parent !== program) {\n topLevel = topLevel.parent;\n }\n if (selfAuthenticating.has(topLevel.name())) return;\n await primeCommandCredential(actionCommand.opts());\n});\n\nif (!inputsModeActive(process.env)) {\n startUpdateCheck({\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\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\ntry {\n await program.parseAsync(process.argv, { from: \"node\" });\n} catch (error) {\n exitOnInputsError(error);\n throw error;\n}\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,G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C,CAAE;AAC7C,OAAM,uBAAuB,cAAc,MAAM,CAAC;EAClD;AAEF,IAAI,CAAC,iBAAiB,QAAQ,IAAI,CAChC,kBAAiB;CACf,gBAAgB;CAChB,WAAW,cAAc;CACzB,KAAK,QAAQ;CACb,aAAa,QAAQ,QAAQ,OAAO,MAAM;CAC1C,aAAa,QAAQ,QAAQ,OAAO,MAAM;CAC1C,WAAW,aAAa,cAAc,OAAO,KAAK,IAAI,CAAC;CACvD,UAAU,QAAQ;CACnB,CAAC;AAIJ,MAAM,YAAY,SAAS,YAAY;AAEvC,IAAI;AACF,OAAM,QAAQ,WAAW,QAAQ,MAAM,EAAE,MAAM,QAAQ,CAAC;SACjD,OAAO;AACd,mBAAkB,MAAM;AACxB,OAAM"}
1
+ {"version":3,"file":"fluid.mjs","names":["readAll"],"sources":["../../src/commands/commands.ts","../../src/completion/complete.ts","../../src/commands/completion.ts","../../src/auth/identity/profiles.ts","../../src/auth/identity/sign-in-path.ts","../../src/auth/pending-login.ts","../../src/auth/profiles.ts","../../src/utils/shell.ts","../../src/commands/login-identity.ts","../../src/commands/login.ts","../../src/commands/signup.ts","../../src/commands/logout.ts","../../src/commands/whoami.ts","../../src/commands/switch.ts","../../src/auth/identity/prime.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 * Ending identity sessions when the profiles that use them go away.\n *\n * `fluid switch` gives each company its own profile, and in identity mode\n * those profiles share the session they were switched from. A session is\n * revoked only once no profile is left that uses it.\n */\n\nimport {\n type FluidConfig,\n type IdentityProfileAuth,\n isIdentityProfile,\n} from \"../../config/types.js\";\nimport { describeIdentityError, signOutIdentity } from \"./session.js\";\n\nfunction sessionsIn(config: FluidConfig): Map<string, IdentityProfileAuth> {\n const found = new Map<string, IdentityProfileAuth>();\n for (const profile of Object.values(config.profiles)) {\n if (!isIdentityProfile(profile)) continue;\n const { auth } = profile;\n found.set(`${auth.identityUrl} ${auth.storageKey}`, auth);\n }\n return found;\n}\n\n/**\n * Revokes every identity session `before` used that `after` no longer does,\n * and deletes its refresh token from the credential store. Resolves with a\n * message for each session that could not be ended cleanly; never rejects.\n */\nexport async function endUnusedSessions(\n before: FluidConfig,\n after: FluidConfig,\n): Promise<string[]> {\n const remaining = sessionsIn(after);\n const problems: string[] = [];\n for (const [key, auth] of sessionsIn(before)) {\n if (remaining.has(key)) continue;\n try {\n await signOutIdentity(auth);\n } catch (error) {\n problems.push(describeIdentityError(error));\n }\n }\n return problems;\n}\n","/**\n * Which way a sign-in completes, as Rails decides it from the company flag\n * (Phase 007 INV-7.1). The CLI never decides it on its own.\n *\n * Mirrors apps/fluid-login: the email step answers every address the same\n * way, and a person whose company is flagged is emailed a sign-in link\n * instead of a code. When a code is confirmed, `confirm_mfa` answers\n * `sign_in_path: \"identity\"` once every company the code covered signs in\n * through the identity service, and hands out no token for them\n * (`Identity::LegacySignInGate`).\n */\n\nimport type { ConfirmMfaResponse } from \"../fluid-api.js\";\n\nexport type SignInPath = \"identity\" | \"legacy\";\n\n/**\n * The path a confirmed code puts the person on. A confirmation that kept any\n * company's legacy token stays on the legacy path: those companies are not\n * flagged, and their tokens are listed exactly as before.\n */\nexport function signInPathFor(confirmation: ConfirmMfaResponse): SignInPath {\n return confirmation.signInPath === \"identity\" ? \"identity\" : \"legacy\";\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, IdentityProfileAuth } 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\ninterface CreateIdentityProfileInput {\n readonly name: string;\n readonly companyName: string;\n readonly baseUrl: string;\n readonly auth: IdentityProfileAuth;\n readonly storedAt?: string;\n}\n\n/**\n * An identity-mode profile. It holds no token: the refresh token is in the\n * operating system credential store under `auth.storageKey`.\n */\nexport function createIdentityProfile({\n name,\n companyName,\n baseUrl,\n auth,\n storedAt,\n}: CreateIdentityProfileInput): FluidProfile {\n return {\n name,\n companyName,\n storedAt: storedAt ?? new Date().toISOString(),\n baseUrl,\n auth,\n };\n}\n","// Characters an email, shop or profile name can hold that are safe to paste\n// into a shell. No leading \"-\", which a command would read as a flag.\nconst SHELL_SAFE = /^[\\w@+][\\w.@+-]*$/;\n\n/**\n * The value for a printed command, or the placeholder when it holds\n * characters a shell would act on.\n */\nexport function shellSafe(value: string, placeholder: string): string {\n return SHELL_SAFE.test(value) ? value : placeholder;\n}\n","/**\n * `fluid login` for a company on the identity sign-in path: the browser,\n * a loopback redirect, and a session in the operating system credential\n * store. Reached only when Rails says so (see auth/identity/sign-in-path.ts):\n * a confirmed code answered `sign_in_path: \"identity\"`, or the person pasted\n * the sign-in link Rails emailed them instead of a code.\n *\n * It reports an outcome rather than printing one, so `fluid login` shows it\n * in text or `--json` like every other sign-in.\n */\n\nimport {\n getFluidApiBase,\n redeemIdentityLink,\n type validateToken,\n} from \"../auth/fluid-api.js\";\nimport { resolveIdentityUrl } from \"../auth/identity/environment.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n signInWithBrowser,\n signOutIdentity,\n} from \"../auth/identity/session.js\";\nimport { createIdentityProfile } from \"../auth/profiles.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { CliError } from \"../utils/errors.js\";\n\n/** The query parameter Rails puts the sign-in link's token in. */\nconst IDENTITY_LINK_PARAM = \"identityLink\";\n\n/** The roles the CLI's commands accept, as with a legacy `rep` session. */\nconst STAFF_ROLES = new Set([\"admin\", \"rep\", \"root_admin\"]);\n\n/**\n * The token in a pasted identity sign-in link, or null when the input is not\n * such a link.\n */\nexport function identityLinkToken(input: string): string | null {\n const trimmed = input.trim();\n if (!trimmed.includes(`${IDENTITY_LINK_PARAM}=`)) return null;\n try {\n const url = new URL(trimmed);\n return url.searchParams.get(IDENTITY_LINK_PARAM) || null;\n } catch {\n return null;\n }\n}\n\ninterface Spinner {\n succeed(text?: string): unknown;\n fail(text?: string): unknown;\n}\n\nexport interface IdentityLoginContext {\n /** `--name`: the profile to store, instead of the company's name. */\n readonly profileName?: string;\n /** The API base the sign-in started against. Defaults to the CLI's. */\n readonly apiBase?: string;\n /** Progress lines for the person, the sign-in URL among them. */\n readonly log: (line: string) => void;\n readonly spinner: (text: string) => Spinner;\n readonly validateToken: typeof validateToken;\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\n /**\n * Called once a pasted link is spent or reported gone, never on a failure\n * that leaves it redeemable, so a caller tracking the sign-in can keep it\n * for a retry.\n */\n readonly onLinkSettled?: () => void;\n /** Whether an existing profile of this name may be replaced. */\n readonly decideOverwrite: (\n profileName: string,\n ) => Promise<\"replace\" | \"keep\" | \"refuse\">;\n}\n\nexport type IdentityLoginOutcome =\n | {\n readonly status: \"signed_in\";\n readonly profileName: string;\n readonly companyName: string;\n }\n | { readonly status: \"failed\"; readonly error: CliError }\n /** The person chose to keep the existing profile. */\n | { readonly status: \"kept\"; readonly profileName: string }\n /** An existing profile would be replaced and no one could be asked. */\n | { readonly status: \"refused\"; readonly profileName: string };\n\nfunction failed(code: string, message: string): IdentityLoginOutcome {\n return { status: \"failed\", error: { code, message } };\n}\n\n/** Signs in through the identity service and stores the profile. */\nexport async function loginWithIdentity(\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const apiBase = context.apiBase ?? getFluidApiBase();\n let identityUrl: string | null;\n try {\n identityUrl = resolveIdentityUrl(apiBase);\n } catch (error) {\n return failed(\n \"IDENTITY_URL_INVALID\",\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!identityUrl) {\n return failed(\n \"IDENTITY_URL_UNKNOWN\",\n `No Fluid identity service is known for ${apiBase}. Set FLUID_IDENTITY_URL to sign in.`,\n );\n }\n\n context.log(\"Your company signs in through Fluid's identity service.\");\n let signIn: Awaited<ReturnType<typeof signInWithBrowser>>;\n try {\n signIn = await signInWithBrowser({ identityUrl, log: context.log });\n } catch (error) {\n return failed(\"IDENTITY_SIGN_IN_FAILED\", describeIdentityError(error));\n }\n\n // The CLI's commands take an admin or rep session, never a shopper's.\n if (!signIn.facts.roles.some((role) => STAFF_ROLES.has(role))) {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return failed(\n \"SHOPPER_SESSION\",\n \"This account does not sign in as an admin or rep, so it cannot sign in to the CLI.\",\n );\n }\n\n // The company's display name; the session itself knows only its id.\n const spinner = context.spinner(\"Loading your company...\");\n // Asked of the API the sign-in started against, never the environment's.\n const company = await context.validateToken(signIn.accessToken, {\n baseUrl: apiBase,\n });\n const companyName = company.success\n ? company.value.name\n : (signIn.facts.companyId ?? \"Fluid\");\n spinner.succeed(`Signed in to ${companyName}`);\n\n const profileName = context.profileName ?? companyName;\n const decision = await context.decideOverwrite(profileName);\n if (decision !== \"replace\") {\n await signOutIdentity(signIn.auth).catch(() => undefined);\n return decision === \"keep\"\n ? { status: \"kept\", profileName }\n : { status: \"refused\", profileName };\n }\n\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: profileName,\n profiles: {\n ...config.profiles,\n [profileName]: createIdentityProfile({\n name: profileName,\n companyName,\n baseUrl: apiBase,\n auth: signIn.auth,\n }),\n },\n }));\n // A profile this one replaced may have been the last user of its session.\n for (const problem of await endUnusedSessions(before, after)) {\n context.log(problem);\n }\n\n return { status: \"signed_in\", profileName, companyName };\n}\n\n/**\n * Redeems a pasted sign-in link with Rails, which confirms the person's\n * company signs in through the identity service, then signs in.\n */\nexport async function loginWithIdentityLink(\n token: string,\n context: IdentityLoginContext,\n): Promise<IdentityLoginOutcome> {\n const spinner = context.spinner(\"Checking the sign-in link...\");\n const redemption = await (context.redeemIdentityLink ?? redeemIdentityLink)(\n token,\n { baseUrl: context.apiBase },\n );\n if (!redemption.success) {\n spinner.fail(redemption.error.message);\n // Only a link Rails reports as gone is settled; any other failure may\n // not have spent it, so the caller keeps what it needs to retry.\n if (redemption.error.code === \"LINK_GONE\") context.onLinkSettled?.();\n return { status: \"failed\", error: redemption.error };\n }\n context.onLinkSettled?.();\n spinner.succeed(\"Sign-in link accepted\");\n return loginWithIdentity(context);\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 * A company on the identity sign-in path is emailed a link instead of a\n * code, and Rails may answer a confirmed code with `sign_in_path:\n * \"identity\"`. Either way the sign-in continues through the browser\n * (commands/login-identity.ts); the CLI never picks the path itself.\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 redeemIdentityLink,\n type CompanyChoice,\n type FluidApiError,\n} from \"../auth/fluid-api.js\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport { signInPathFor } from \"../auth/identity/sign-in-path.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\";\nimport { shellSafe } from \"../utils/shell.js\";\nimport {\n identityLinkToken,\n loginWithIdentity,\n loginWithIdentityLink,\n type IdentityLoginContext,\n type IdentityLoginOutcome,\n} from \"./login-identity.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 /** Defaults to the real redemption when a caller does not stand one in. */\n readonly redeemIdentityLink?: typeof redeemIdentityLink;\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\nasync function storeProfile(\n deps: LoginDeps,\n profileName: string,\n token: string,\n companyName: string,\n baseUrl: string = getFluidApiBase(),\n): Promise<void> {\n const before = readConfig();\n const after = 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 // Replacing an identity-mode profile ends its session if nothing else\n // uses it, so no refresh token is left behind in the credential store.\n for (const problem of await endUnusedSessions(before, after)) {\n deps.err(chalk.yellow(problem));\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\n/**\n * What the identity sign-in needs from this run: its output, its overwrite\n * rule, and the API base the sign-in started against. With `--json` the\n * person still needs the sign-in URL, so progress goes to stderr.\n */\nfunction identityContext(\n opts: LoginOptions,\n interactive: boolean,\n ui: Ui,\n deps: LoginDeps,\n apiBase?: string,\n): IdentityLoginContext {\n return {\n profileName: opts.name,\n apiBase,\n log: (line) =>\n ui.json\n ? deps.err(line)\n : deps.log(line.startsWith(\"http\") ? line : chalk.cyan(line)),\n spinner: (text) => ui.spinner(text),\n // Every request of this sign-in goes to `apiBase` when it has one: a\n // two-step sign-in's is the API its code was sent from.\n validateToken: (token, options) =>\n deps.api.validateToken(token, { baseUrl: apiBase, ...options }),\n redeemIdentityLink: deps.api.redeemIdentityLink,\n decideOverwrite: (profileName) =>\n overwriteDecision(\n profileName,\n { yes: Boolean(opts.yes), interactive },\n deps,\n ),\n };\n}\n\nfunction identityResult(\n outcome: IdentityLoginOutcome,\n ui: Ui,\n deps: LoginDeps,\n): number {\n switch (outcome.status) {\n case \"signed_in\":\n return loggedIn(ui, deps, outcome.profileName, {\n name: outcome.companyName,\n });\n case \"kept\":\n return cancelled(deps);\n case \"refused\":\n return ui.fail(profileExists(outcome.profileName, false));\n case \"failed\":\n return ui.fail(outcome.error);\n }\n}\n\nconst LINK_HINT =\n \"If the email has a sign-in link instead of a code, paste the link here.\";\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 await storeProfile(deps, 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 if (!ui.json) deps.log(chalk.dim(LINK_HINT));\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 // A flagged company's person is emailed a link, not a code.\n const linkToken = identityLinkToken(code);\n if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(\n linkToken,\n identityContext(opts, true, ui, deps),\n ),\n ui,\n deps,\n );\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 // Every company the code covered signs in through the identity service,\n // so Rails handed out no token (Phase 007 INV-7.5).\n if (signInPathFor(confirmResult.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity(identityContext(opts, true, ui, deps)),\n ui,\n deps,\n );\n }\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 await storeProfile(deps, 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/**\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 return `fluid login --code --email ${shellSafe(email, \"<email>\")} --shop ${shellSafe(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). For a new signup, `fluid signup` prints it as fluidShop.\",\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 \"If the email has a sign-in link instead of a code, pass the link the same way. \" +\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 \"(pass that link to --code in place of the code). 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 // A flagged company's person is emailed a link, not a code: redeeming it\n // finishes this sign-in through the identity service instead.\n const linkToken = identityLinkToken(code);\n if (!linkToken && !/^\\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 a code, or redeeming a link, uses it up, so a named profile\n // that would be refused is checked first. Without a terminal, the check\n // above has already 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 if (linkToken) {\n return identityResult(\n await loginWithIdentityLink(linkToken, {\n ...identityContext(opts, interactive, ui, deps, record.baseUrl),\n // The pending sign-in ends only once the link is spent or gone; a\n // failure that may not have spent it keeps it for a retry.\n onLinkSettled: () => deps.pending.remove(email),\n }),\n ui,\n deps,\n );\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 // Rails handed out no token: every company the code covered signs in\n // through the identity service (Phase 007 INV-7.5).\n if (signInPathFor(confirmed.value) === \"identity\") {\n return identityResult(\n await loginWithIdentity(\n identityContext(opts, interactive, ui, deps, record.baseUrl),\n ),\n ui,\n deps,\n );\n }\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 await storeProfile(deps, 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 signup — create a Fluid company with the public signup endpoint\n *\n * Runs before any sign-in, so it calls `POST /api/company` directly rather\n * than through a profile's client. The person behind the email then\n * confirms the signup, by the emailed link or by signing in with the two\n * `fluid login` steps this command prints.\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\nimport prompts from \"prompts\";\nimport {\n signup,\n type SignupError,\n type SignupRequest,\n} from \"../auth/fluid-api.js\";\nimport { normaliseEmail } from \"../auth/pending-login.js\";\nimport { shellSafe } from \"../utils/shell.js\";\n\nexport interface SignupOptions {\n readonly email?: string;\n readonly firstName?: string;\n readonly lastName?: string;\n readonly companyName?: string;\n readonly subdomain?: string;\n readonly color?: string;\n readonly yes?: boolean;\n readonly json?: boolean;\n}\n\ninterface Spinner {\n stop(): unknown;\n}\n\n/** Everything `runSignup` reaches outside itself, for tests. */\nexport interface SignupDeps {\n readonly api: { readonly signup: typeof signup };\n readonly prompt: (\n question: prompts.PromptObject,\n ) => Promise<prompts.Answers<string>>;\n /** Shown in text mode while the signup runs, which can take a while. */\n readonly spinner: (text: string) => Spinner;\n readonly log: (line: string) => void;\n readonly isInteractive: () => boolean;\n}\n\nexport const defaultSignupDeps: SignupDeps = {\n api: { signup },\n prompt: (question) => prompts(question),\n spinner: (text) => ora(text).start(),\n log: (line) => console.log(line),\n isInteractive: () => Boolean(process.stdin.isTTY),\n};\n\n// The same DNS-label rule the server validates a new subdomain against.\nconst SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst COLOR_PATTERN = /^(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * The subdomain as the server would store it: lowercase, letters, digits\n * and hyphens only, at most 63 characters, no hyphen at either end. The\n * server checks \"is taken\" against the value as sent, before it cleans it\n * up, so sending the clean form keeps that check meaningful.\n */\nexport function normaliseSubdomain(raw: string): string {\n const trimmed = (value: string) => value.replace(/^-+|-+$/g, \"\");\n return trimmed(\n trimmed(raw.toLowerCase())\n .replace(/[^a-z0-9-]/g, \"\")\n .slice(0, 63),\n );\n}\n\n/**\n * The two commands that sign in to the new company and confirm it. The\n * second names its own profile rather than passing `--yes`, which would\n * replace an existing profile that happens to share the company's name.\n * If a profile with that name exists, login refuses `--name` before the code\n * is spent when there is no terminal, and asks first at one.\n */\nexport function nextCommands(\n email: string,\n fluidShop: string,\n subdomain: string,\n): string[] {\n const safeEmail = shellSafe(email, \"<email>\");\n const safeShop = shellSafe(fluidShop, \"<shop>\");\n return [\n `fluid login --send-code --email ${safeEmail} --shop ${safeShop}`,\n `fluid login --code --email ${safeEmail} --shop ${safeShop} --name ${shellSafe(subdomain, \"<profile>\")}`,\n ];\n}\n\nconst REQUIRED_FLAGS: ReadonlyArray<[keyof SignupOptions, string]> = [\n [\"email\", \"--email\"],\n [\"firstName\", \"--first-name\"],\n [\"lastName\", \"--last-name\"],\n [\"companyName\", \"--company-name\"],\n [\"subdomain\", \"--subdomain\"],\n];\n\n/** The request to send, or why the flags can't make one. */\nfunction buildRequest(\n opts: SignupOptions,\n): { request: SignupRequest } | { error: SignupError } {\n const missing = REQUIRED_FLAGS.filter(([key]) => {\n const value = opts[key];\n return typeof value !== \"string\" || value.trim() === \"\";\n }).map(([, flag]) => flag);\n if (missing.length > 0) {\n return {\n error: {\n code: \"FLAGS_REQUIRED\",\n message: `fluid signup needs ${missing.join(\", \")}.`,\n },\n };\n }\n\n const email = normaliseEmail(opts.email ?? \"\");\n if (!EMAIL_PATTERN.test(email)) {\n return {\n error: {\n code: \"INVALID_EMAIL\",\n message: `${email} is not an email address.`,\n },\n };\n }\n\n const subdomain = normaliseSubdomain(opts.subdomain ?? \"\");\n if (!SUBDOMAIN_PATTERN.test(subdomain)) {\n return {\n error: {\n code: \"INVALID_SUBDOMAIN\",\n message:\n \"--subdomain needs at least one letter or digit; it may also hold hyphens, up to 63 characters.\",\n },\n };\n }\n\n const color = opts.color?.trim().replace(/^#/, \"\");\n if (color !== undefined && !COLOR_PATTERN.test(color)) {\n return {\n error: {\n code: \"INVALID_COLOR\",\n message: \"--color must be a 3- or 6-digit hex colour, such as 0C7CF6.\",\n },\n };\n }\n\n return {\n request: {\n email,\n firstName: (opts.firstName ?? \"\").trim(),\n lastName: (opts.lastName ?? \"\").trim(),\n companyName: (opts.companyName ?? \"\").trim(),\n subdomain,\n ...(color ? { color } : {}),\n },\n };\n}\n\n// A plain CliError fits too: every field SignupError adds is optional.\nfunction printFailure(\n error: SignupError,\n json: boolean,\n deps: SignupDeps,\n): number {\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"error\",\n code: error.code,\n message: error.message,\n ...(error.status !== undefined ? { httpStatus: error.status } : {}),\n ...(error.errors ? { errors: error.errors } : {}),\n ...(error.retryAfter !== undefined\n ? { retryAfter: error.retryAfter }\n : {}),\n ...(error.details ? { details: error.details } : {}),\n },\n null,\n 2,\n ),\n );\n return 1;\n }\n deps.log(chalk.red(error.message));\n if (error.errors) deps.log(chalk.dim(JSON.stringify(error.errors)));\n if (error.retryAfter !== undefined) {\n deps.log(chalk.dim(`Retry after ${error.retryAfter} seconds.`));\n }\n if (error.details) deps.log(chalk.dim(error.details));\n return 1;\n}\n\n/**\n * Run `fluid signup` and return its exit code.\n */\nexport async function runSignup(\n opts: SignupOptions,\n deps: SignupDeps = defaultSignupDeps,\n): Promise<number> {\n const json = Boolean(opts.json);\n const built = buildRequest(opts);\n if (\"error\" in built) return printFailure(built.error, json, deps);\n const { request } = built;\n\n if (!opts.yes) {\n const question = `Create ${request.companyName} at subdomain ${request.subdomain}, and email ${request.email} to confirm it?`;\n // `--json` is for a program reading the output, which cannot answer a\n // prompt, and a closed stdin never answers one either.\n if (json || !deps.isInteractive()) {\n return printFailure(\n {\n code: \"CONFIRM_REQUIRED\",\n message: `${question} Pass --yes to confirm.`,\n },\n json,\n deps,\n );\n }\n const answer = await deps.prompt({\n type: \"confirm\",\n name: \"ok\",\n message: question,\n initial: false,\n });\n if (!answer[\"ok\"]) {\n return printFailure(\n { code: \"CANCELLED\", message: \"Cancelled.\" },\n json,\n deps,\n );\n }\n }\n\n const spinner = json ? undefined : deps.spinner(\"Signing up...\");\n const result = await deps.api.signup(request);\n spinner?.stop();\n if (!result.success) return printFailure(result.error, json, deps);\n\n const created = result.value;\n const next = nextCommands(\n request.email,\n created.company.fluidShop,\n created.company.subdomain,\n );\n if (json) {\n deps.log(\n JSON.stringify(\n {\n status: \"signed_up\",\n company: created.company,\n userCompany: created.userCompany,\n currentlyDue: created.currentlyDue,\n next,\n },\n null,\n 2,\n ),\n );\n return 0;\n }\n\n deps.log(\n chalk.green(\n `Signed up ${created.company.name} as ${created.company.fluidShop} (company ${created.company.id}).`,\n ),\n );\n if (request.subdomain !== (opts.subdomain ?? \"\").trim()) {\n deps.log(chalk.dim(`Subdomain sent as ${request.subdomain}.`));\n }\n deps.log(\n `${request.email} confirms it from the emailed link, or by signing in with the emailed code:`,\n );\n for (const command of next) deps.log(` ${command}`);\n deps.log(\n chalk.dim(\n \"A repeat signup for the same email within an hour normally sends no new email.\",\n ),\n );\n return 0;\n}\n\n/**\n * The `signup` command, running `run` with the parsed options. Built by a\n * function so a test can check the flag parsing without signing up.\n */\nexport function buildSignupCommand(\n run: (opts: SignupOptions) => Promise<number> = (opts) => runSignup(opts),\n): Command {\n return new Command(\"signup\")\n .description(\n \"Create a Fluid company with the public signup; the person behind --email confirms it\",\n )\n .option(\n \"-e, --email <email>\",\n \"The person's email address; Fluid emails it to confirm the signup\",\n )\n .option(\"--first-name <name>\", \"The person's first name\")\n .option(\"--last-name <name>\", \"The person's last name\")\n .option(\"--company-name <name>\", \"The company's name\")\n .option(\n \"--subdomain <subdomain>\",\n \"The store's subdomain (acme gives acme.fluid.app); sent lowercase, letters, digits and hyphens only\",\n )\n .option(\n \"--color <hex>\",\n \"Brand colour as 3 or 6 hex digits, such as 0C7CF6\",\n )\n .option(\"-y, --yes\", \"Sign up without asking\")\n .option(\"--json\", \"Print the result as JSON\")\n .action(async (opts: SignupOptions) => {\n const exitCode = await run(opts);\n if (exitCode !== 0) process.exitCode = exitCode;\n });\n}\n\nexport const signupCommand = buildSignupCommand();\n","/**\n * fluid logout — remove stored auth profile(s)\n *\n * An identity-mode profile's session is revoked at the identity service and\n * its refresh token deleted from the credential store, once no remaining\n * profile uses it. (The identity service's `/signout` is a browser\n * navigation; a native client revokes its refresh token instead.)\n */\n\nimport { Command } from \"commander\";\nimport chalk from \"chalk\";\nimport { endUnusedSessions } from \"../auth/identity/profiles.js\";\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(async (opts: { all?: boolean }) => {\n const config = readConfig();\n\n if (opts.all) {\n const after = {\n ...config,\n activeProfile: null,\n profiles: {},\n };\n writeConfig(after);\n for (const problem of await endUnusedSessions(config, after)) {\n console.log(chalk.yellow(problem));\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 const after = {\n ...config,\n activeProfile: nextActive,\n profiles: remainingProfiles,\n };\n writeConfig(after);\n for (const problem of await endUnusedSessions(config, after)) {\n console.log(chalk.yellow(problem));\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 * An identity-mode profile is shown from its identity session: the facts\n * come from the identity service's `/userinfo`, never from decoding a token.\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\";\nimport {\n describeIdentityError,\n identityToken,\n} from \"../auth/identity/session.js\";\nimport { type IdentityProfile, isIdentityProfile } from \"../config/types.js\";\n\nasync function whoamiIdentity(profile: IdentityProfile): Promise<void> {\n const spinner = ora(\"Checking your identity session...\").start();\n let facts;\n try {\n ({ facts } = await identityToken(profile.auth));\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n console.log(chalk.dim(`Profile: ${profile.name}`));\n process.exitCode = 1;\n return;\n }\n\n spinner.succeed(chalk.green(\"Authenticated (Fluid identity service)\"));\n console.log(` Profile: ${chalk.bold(profile.name)}`);\n console.log(` Company: ${chalk.bold(profile.companyName)}`);\n if (facts.companyId) {\n console.log(` Company ID: ${chalk.dim(facts.companyId)}`);\n }\n console.log(` Subject: ${chalk.dim(facts.subject)}`);\n if (facts.roles.length > 0) {\n console.log(` Roles: ${facts.roles.join(\", \")}`);\n }\n if (facts.impersonating && facts.actor) {\n console.log(` Acting as: ${chalk.yellow(facts.actor)}`);\n }\n console.log(\n ` Signed in: ${chalk.dim(new Date(facts.authTime * 1000).toISOString())}`,\n );\n console.log(` Stored: ${chalk.dim(profile.storedAt)}`);\n}\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 if (isIdentityProfile(profile)) {\n await whoamiIdentity(profile);\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 * An identity-mode profile switches by token exchange (Phase 007 FR-3): the\n * session it signed in with stays as it is, and the new company's profile\n * remembers the company to exchange into. Nothing secret is written.\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 { endUnusedSessions } from \"../auth/identity/profiles.js\";\nimport {\n describeIdentityError,\n identityToken,\n sessionFacts,\n} from \"../auth/identity/session.js\";\nimport { createFluidProfile, createIdentityProfile } from \"../auth/profiles.js\";\nimport { getActiveProfile } from \"../auth/token.js\";\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport { type IdentityProfile, isIdentityProfile } from \"../config/types.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\nasync function performIdentitySwitch(\n profile: IdentityProfile,\n company: UserCompany,\n baseUrl: string,\n): Promise<void> {\n const spinner = ora(`Switching to ${chalk.bold(company.name)}...`).start();\n if (!company.uuidV7) {\n spinner.fail(\n chalk.red(`${company.name} has no identifier to switch to it by.`),\n );\n process.exitCode = 1;\n return;\n }\n\n let org: string | undefined;\n try {\n // Back to the company the session signed in to needs no exchange.\n const home = (await sessionFacts(profile.auth)).companyId;\n org = company.uuidV7 === home ? undefined : company.uuidV7;\n await identityToken(profile.auth, org ?? null);\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n\n const { org: _previous, ...session } = profile.auth;\n const before = readConfig();\n const after = updateConfig((config) => ({\n ...config,\n activeProfile: company.name,\n profiles: {\n ...config.profiles,\n [company.name]: createIdentityProfile({\n name: company.name,\n companyName: company.name,\n baseUrl,\n auth: org ? { ...session, org } : session,\n }),\n },\n }));\n const problems = await endUnusedSessions(before, after);\n\n spinner.succeed(\n chalk.green(\n `Switched to ${chalk.bold(company.name)} (profile: ${chalk.bold(company.name)})`,\n ),\n );\n for (const problem of problems) console.log(chalk.yellow(problem));\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 activeCompanyName = activeProfile.companyName;\n const activeBaseUrl = activeProfile.baseUrl ?? getFluidApiBase();\n const identity = isIdentityProfile(activeProfile) ? activeProfile : null;\n\n // Fetch companies from API\n const spinner = ora(\"Fetching companies...\").start();\n let token = activeProfile.token ?? \"\";\n if (identity) {\n try {\n token = (await identityToken(identity.auth)).accessToken;\n } catch (error) {\n spinner.fail(chalk.red(describeIdentityError(error)));\n process.exitCode = 1;\n return;\n }\n }\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 (identity\n ? performIdentitySwitch(identity, match, activeBaseUrl)\n : 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 (identity\n ? performIdentitySwitch(identity, selected, activeBaseUrl)\n : performSwitch(token, selected, activeBaseUrl));\n });\n","/**\n * Restores an identity-mode profile's session before a command runs, so the\n * synchronous `getAuthToken()` that plugins call finds a current access\n * token in memory. Legacy profiles and literal tokens are left alone: no\n * credential store is touched and no request is made for them.\n */\n\nimport chalk from \"chalk\";\n\nimport { isIdentityProfile } from \"../../config/types.js\";\nimport { resolveCredentialSource } from \"../token.js\";\nimport { describeIdentityError, primeIdentityProfile } from \"./session.js\";\n\nexport interface CommandCredentialOptions {\n readonly token?: unknown;\n readonly profile?: unknown;\n}\n\n/**\n * Primes the credential a command with these options would use. A session\n * that cannot be restored is reported on stderr, and the command runs on as\n * it would with no stored credential.\n */\nexport async function primeCommandCredential(\n options: CommandCredentialOptions,\n): Promise<void> {\n if (typeof options.token === \"string\" && options.token) return;\n const profileName =\n typeof options.profile === \"string\" && options.profile\n ? options.profile\n : undefined;\n const source = resolveCredentialSource(profileName);\n if (source?.kind !== \"profile\" || !isIdentityProfile(source.profile)) return;\n try {\n await primeIdentityProfile(source.profile);\n } catch (error) {\n process.stderr.write(`${chalk.yellow(describeIdentityError(error))}\\n`);\n }\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 { isStrictConfig } from \"../config/strict.js\";\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 = () =>\n isStrictConfig() ? [] : discoverFromNodeModules(basePath);\n const installationPlugins = () =>\n cliParent === basePath && !isStrictConfig()\n ? []\n : 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 { createInputsReader } from \"../inputs/reader.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 inputs: createInputsReader(),\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 { signupCommand } from \"../commands/signup.js\";\nimport { logoutCommand } from \"../commands/logout.js\";\nimport { whoamiCommand } from \"../commands/whoami.js\";\nimport { switchCommand } from \"../commands/switch.js\";\nimport {\n exitOnInputsError,\n inputsModeActive,\n registerInputsHook,\n} from \"../inputs/hook.js\";\nimport { primeCommandCredential } from \"../auth/identity/prime.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, and the signup that comes before them\nprogram.addCommand(signupCommand);\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\n// Commands that resolve their own credential, or need none.\nconst selfAuthenticating = new Set(\n [\n signupCommand,\n loginCommand,\n logoutCommand,\n whoamiCommand,\n switchCommand,\n commandsCommand,\n completionCommand,\n completeCommand,\n ].map((command) => command.name()),\n);\n\nregisterInputsHook(program);\n\n// An identity-mode profile's access token lives only in memory, so restore\n// its session before any other command runs; plugins read the token\n// synchronously through getAuthToken().\nprogram.hook(\"preAction\", async (_program, actionCommand) => {\n let topLevel: Command = actionCommand;\n while (topLevel.parent && topLevel.parent !== program) {\n topLevel = topLevel.parent;\n }\n if (selfAuthenticating.has(topLevel.name())) return;\n await primeCommandCredential(actionCommand.opts());\n});\n\nif (!inputsModeActive(process.env)) {\n startUpdateCheck({\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\n// Discover and load all plugins (auto-discovered from node_modules and workspace)\nawait loadPlugins(program, packageRoot);\n\ntry {\n await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