@fluid-app/fluid-cli 0.1.799 → 0.1.800

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":"index.mjs","names":[],"sources":["../src/dam/upload.ts","../src/domain/output.ts","../src/domain/context.ts","../src/domain/command.ts","../src/inputs/testing.ts","../src/walk/prompter.ts","../src/git-sync/commit-subject.ts","../src/git-sync/change-summary.ts","../src/git-sync/actor-cache.ts"],"sourcesContent":["/**\n * One upload to the Fluid DAM through the `upload.fluid.app/upload` service,\n * which does the three underlying calls (imagekit_auth, the ImageKit upload\n * and backfill_imagekit) in one request.\n *\n * `fluid assets upload` and `fluid sites media sync` both send their files\n * through this, with the bearer token their own login resolution picked.\n * It has no imports, so the plugins' Jest mocks of this package can re-export\n * it as it is.\n */\n\n/**\n * The upload service. Hard-coded: the bearer sent is the user's Fluid API\n * token, so the destination must be a Fluid-controlled host. A local service\n * is reached through the FLUID_UPLOAD_BASE env var, read from the process\n * environment, never from an argument a user types.\n */\nexport function damUploadBase(): string {\n return (\n process.env[\"FLUID_UPLOAD_BASE\"] ?? \"https://upload.fluid.app\"\n ).replace(/\\/$/, \"\");\n}\n\n/** What one DAM upload sends. Give `file` or `url`, not both. */\nexport interface DamUploadRequest {\n /** The Fluid API token sent as the bearer. */\n token: string;\n /** A local file's bytes and the name to store it under. */\n file?: { bytes: Uint8Array; name: string };\n /** An external address the service fetches the file from. */\n url?: string;\n /** The asset's display name. */\n name?: string;\n description?: string;\n /** Comma-separated tags. */\n tags?: string;\n /** An ImageKit folder override. */\n folder?: string;\n /** ImageKit's useUniqueFileName (default: true). */\n uniqueFilename?: boolean;\n /** Also create a Fluid Media resource. */\n createMedia?: boolean;\n /** Each request line, when verbose. */\n onRequest?: (line: string) => void;\n /** The fetch to send with (default: the global one). */\n fetch?: typeof fetch;\n}\n\n/** A refused or failed upload, with the service's HTTP status and its body's start. */\nexport class DamUploadError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly detail: string,\n ) {\n super(message);\n this.name = \"DamUploadError\";\n }\n\n /**\n * Whether the login may not upload to the DAM at all: the service refused\n * the token, or passed on Fluid's refusal of the upload credential (it\n * answers that as a 500 naming imagekit_auth's own 401 or 403).\n */\n get refused(): boolean {\n if (this.status === 401 || this.status === 403) return true;\n return /imagekit_auth failed \\((401|403)\\)/.test(this.detail);\n }\n}\n\n/**\n * Uploads one file or URL to the DAM and returns the service's JSON answer,\n * whose `asset.default_variant_url` is the asset's CDN address.\n *\n * Throws DamUploadError when the service answers anything but 2xx.\n */\nexport async function uploadToDam(request: DamUploadRequest): Promise<unknown> {\n if (!request.file === !request.url) {\n throw new Error(\"Give a DAM upload a file or a URL, not both or neither.\");\n }\n // Multipart order matters for streaming uploads (over about 100 MB). The\n // service streams `file` straight through to ImageKit, so any field\n // ImageKit needs (`fileName`, `folder`, `useUniqueFileName`) must arrive\n // BEFORE the file part. Fields used after the upload (`name`,\n // `description`, `tags`, `create_media`) can sit anywhere; they go last.\n const form = new FormData();\n if (request.folder) form.append(\"folder\", request.folder);\n if (request.uniqueFilename === false) {\n form.append(\"useUniqueFileName\", \"false\");\n }\n if (request.url) {\n form.append(\"external_asset_url\", request.url);\n } else if (request.file) {\n form.append(\"fileName\", request.file.name);\n // A Blob, so fetch's multipart serializer writes a Content-Disposition\n // with the file name.\n form.append(\n \"file\",\n new Blob([new Uint8Array(request.file.bytes)]),\n request.file.name,\n );\n }\n if (request.name) form.append(\"name\", request.name);\n if (request.description) form.append(\"description\", request.description);\n if (request.tags) form.append(\"tags\", request.tags);\n if (request.createMedia) form.append(\"create_media\", \"true\");\n\n const endpoint = `${damUploadBase()}/upload`;\n request.onRequest?.(`POST ${endpoint}`);\n const send = request.fetch ?? fetch;\n const resp = await send(endpoint, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${request.token}` },\n body: form,\n });\n\n if (!resp.ok) {\n let detail = \"\";\n try {\n detail = (await resp.text()).slice(0, 400);\n } catch {\n // No body, or an unreadable one: the message stays generic.\n }\n throw new DamUploadError(\n `Upload failed (HTTP ${resp.status})${detail ? `: ${detail}` : \"\"}`,\n resp.status,\n detail,\n );\n }\n return (await resp.json()) as unknown;\n}\n\n/** The CDN address in an upload's answer, or null when it has none. */\nexport function damAssetUrlOf(answer: unknown): string | null {\n if (typeof answer !== \"object\" || answer === null) return null;\n const asset = (answer as { asset?: unknown }).asset;\n if (typeof asset !== \"object\" || asset === null) return null;\n const url = (asset as { default_variant_url?: unknown }).default_variant_url;\n return typeof url === \"string\" && url.startsWith(\"https://\") ? url : null;\n}\n\n/** The DAM asset code in an upload's answer, or null when it has none. */\nexport function damAssetCodeOf(answer: unknown): string | null {\n if (typeof answer !== \"object\" || answer === null) return null;\n const asset = (answer as { asset?: unknown }).asset;\n if (typeof asset !== \"object\" || asset === null) return null;\n const code = (asset as { code?: unknown }).code;\n return typeof code === \"string\" && code.length > 0 ? code : null;\n}\n","import type { OutputOptions } from \"./types.js\";\n\nexport function formatOutput(data: unknown, options: OutputOptions): string {\n let result = data;\n\n if (options.jq) {\n result = extractPath(result, options.jq);\n }\n\n if (options.format === \"table\") {\n return formatTable(result);\n }\n\n if (options.compact) {\n return JSON.stringify(result);\n }\n return JSON.stringify(result, null, 2);\n}\n\nfunction extractPath(data: unknown, path: string): unknown {\n const parts = path\n .replace(/^\\.*/, \"\")\n .split(/\\.|\\[/)\n .filter(Boolean)\n .map((p) => p.replace(/\\]$/, \"\"));\n\n let current: any = data;\n for (const part of parts) {\n if (current == null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction formatTable(data: unknown): string {\n if (Array.isArray(data)) {\n if (data.length === 0) return \"(empty)\";\n\n if (typeof data[0] === \"object\" && data[0] !== null) {\n const keys = Object.keys(data[0]);\n const widths = keys.map((k) =>\n Math.max(k.length, ...data.map((row) => String(row[k] ?? \"\").length)),\n );\n\n const header = keys\n .map((k, i) => k.toUpperCase().padEnd(widths[i]!))\n .join(\" \");\n const separator = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const rows = data.map((row) =>\n keys.map((k, i) => String(row[k] ?? \"\").padEnd(widths[i]!)).join(\" \"),\n );\n\n return [header, separator, ...rows].join(\"\\n\");\n }\n\n return data.map(String).join(\"\\n\");\n }\n\n if (typeof data === \"object\" && data !== null) {\n const entries = Object.entries(data);\n const maxKeyLen = Math.max(...entries.map(([k]) => k.length));\n return entries\n .map(([k, v]) => `${k.padEnd(maxKeyLen)} ${JSON.stringify(v)}`)\n .join(\"\\n\");\n }\n\n return String(data);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApiError, createFetchClient } from \"@fluid-app/api-client-core\";\nimport type { FetchClient } from \"@fluid-app/api-client-core\";\n\nimport {\n clientAccessToken,\n invalidateClientToken,\n} from \"../auth/identity/client.js\";\nimport { profileAccessToken } from \"../auth/identity/session.js\";\nimport {\n type CredentialSource,\n resolveCredentialSource,\n} from \"../auth/token.js\";\nimport { isClientProfile, isIdentityProfile } from \"../config/types.js\";\nimport { createInputsReader } from \"../inputs/reader.js\";\nimport { formatOutput } from \"./output.js\";\nimport type { CommandContext, OutputOptions } from \"./types.js\";\n\ninterface SentToken {\n token: string | null;\n}\n\nconst sentToken = new AsyncLocalStorage<SentToken>();\n\nexport function createCommandContext(opts: {\n token?: string;\n baseUrl?: string;\n profile?: string;\n format: \"json\" | \"table\";\n compact: boolean;\n jq?: string;\n verbose: boolean;\n}): CommandContext {\n let clientInstance: FetchClient | null = null;\n\n const outputOptions: OutputOptions = {\n format: opts.format,\n compact: opts.compact,\n jq: opts.jq,\n };\n\n /**\n * The token getter for this command. An identity-mode profile's getter\n * restores and refreshes its session on each call, so a long command never\n * sends an expired token.\n */\n function requireToken(): () => string | Promise<string> {\n const getter = tokenGetter(resolveSource(opts));\n if (getter) return getter;\n if (opts.profile) {\n throw new Error(\n `No API token found for profile \"${opts.profile}\". Run \\`fluid login\\` for that profile or provide --token <token>`,\n );\n }\n throw new Error(\n \"No API token found. Run `fluid login` or provide --token <token>\",\n );\n }\n\n return {\n verbose: opts.verbose,\n inputs: createInputsReader(),\n\n async getClient(): Promise<FetchClient> {\n if (clientInstance) return clientInstance;\n\n const getAuthToken = requireToken();\n const baseUrl =\n opts.baseUrl ??\n process.env[\"FLUID_API_BASE\"] ??\n \"https://api.fluid.app\";\n\n clientInstance = retryingOnce(\n createFetchClient({ baseUrl, getAuthToken }),\n resolveSource(opts),\n );\n\n return clientInstance;\n },\n\n async getClientFor(serviceBaseUrl: string): Promise<FetchClient> {\n const getAuthToken = requireToken();\n return retryingOnce(\n createFetchClient({\n baseUrl: serviceBaseUrl.replace(/\\/$/, \"\"),\n getAuthToken,\n }),\n resolveSource(opts),\n );\n },\n\n output(data: unknown): void {\n const formatted = formatOutput(data, outputOptions);\n process.stdout.write(formatted + \"\\n\");\n },\n\n parseBody(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n throw new Error(`Invalid JSON body: ${raw}`);\n }\n },\n };\n}\n\nfunction resolveSource(opts: {\n token?: string;\n profile?: string;\n}): CredentialSource | null {\n if (opts.token) return { kind: \"token\", token: opts.token };\n return resolveCredentialSource(opts.profile);\n}\n\nfunction tokenGetter(\n source: CredentialSource | null,\n): (() => string | Promise<string>) | null {\n if (!source) return null;\n if (source.kind === \"token\") {\n const token = source.token;\n return () => token;\n }\n const profile = source.profile;\n if (isIdentityProfile(profile)) return () => profileAccessToken(profile);\n if (isClientProfile(profile)) {\n return async () => {\n const token = await clientAccessToken(profile);\n const slot = sentToken.getStore();\n if (slot) slot.token = token;\n return token;\n };\n }\n const token = profile.token;\n return token ? () => token : null;\n}\n\n/**\n * For a client profile, a request the API answers 401 drops the held token\n * and is replayed once with a new one; any other credential is returned as is.\n */\nfunction retryingOnce(\n client: FetchClient,\n source: CredentialSource | null,\n): FetchClient {\n if (source?.kind !== \"profile\" || !isClientProfile(source.profile)) {\n return client;\n }\n const profile = source.profile;\n return new Proxy(client, {\n get(target, property, receiver) {\n const value: unknown = Reflect.get(target, property, receiver);\n if (typeof value !== \"function\") return value;\n return async (...args: unknown[]) => {\n const slot: SentToken = { token: null };\n try {\n return await sentToken.run(slot, () => value.apply(target, args));\n } catch (error) {\n if (!(error instanceof ApiError) || error.status !== 401) throw error;\n invalidateClientToken(profile, slot.token);\n return value.apply(target, args);\n }\n };\n },\n });\n}\n","import { Command } from \"commander\";\n\nimport { createCommandContext } from \"./context.js\";\nimport type { CommandContext } from \"./types.js\";\n\ntype RegisterFn = (parent: Command, ctx: CommandContext) => void;\n\nexport function createDomainCommand(\n name: string,\n description: string,\n register: RegisterFn,\n): Command {\n const cmd = new Command(name)\n .description(description)\n // Keep global domain flags usable before or after nested subcommands.\n .enablePositionalOptions(false)\n .option(\"--token <token>\", \"API authentication token\")\n .option(\"--base-url <url>\", \"API base URL\")\n .option(\"--profile <name>\", \"Config profile name\")\n .option(\"--format <format>\", \"Output format (json|table)\", \"json\")\n .option(\"--compact\", \"Compact JSON output\", false)\n .option(\"--jq <path>\", \"Extract value at JSON path\")\n .option(\"--verbose\", \"Print request details to stderr\", false);\n\n let resolvedCtx: CommandContext | null = null;\n\n function getCtx(): CommandContext {\n if (!resolvedCtx) {\n const opts = cmd.opts();\n resolvedCtx = createCommandContext({\n token: opts.token,\n baseUrl: opts.baseUrl,\n profile: opts.profile,\n format: opts.format as \"json\" | \"table\",\n compact: opts.compact,\n jq: opts.jq,\n verbose: opts.verbose,\n });\n }\n return resolvedCtx;\n }\n\n const lazyCtx: CommandContext = {\n get verbose() {\n return getCtx().verbose;\n },\n getClient() {\n return getCtx().getClient();\n },\n getClientFor(baseUrl: string) {\n return getCtx().getClientFor(baseUrl);\n },\n output(data: unknown) {\n return getCtx().output(data);\n },\n get inputs() {\n return getCtx().inputs;\n },\n parseBody(raw: string) {\n return getCtx().parseBody(raw);\n },\n };\n\n register(cmd, lazyCtx);\n\n return cmd;\n}\n","import fs, { constants } from \"node:fs\";\nimport { syncBuiltinESMExports } from \"node:module\";\nimport { normalize } from \"node:path\";\n\nimport { inInternalRead } from \"./scope.js\";\n\nconst GUARDED = [\n \"readFileSync\",\n \"readFile\",\n \"createReadStream\",\n \"readdirSync\",\n \"readdir\",\n \"statSync\",\n \"stat\",\n \"lstatSync\",\n \"lstat\",\n \"openSync\",\n \"open\",\n \"opendirSync\",\n \"opendir\",\n \"realpathSync\",\n \"existsSync\",\n \"accessSync\",\n \"access\",\n \"openAsBlob\",\n] as const;\n\nconst GUARDED_PROMISES = [\n \"readFile\",\n \"readdir\",\n \"stat\",\n \"lstat\",\n \"open\",\n \"opendir\",\n \"realpath\",\n \"access\",\n] as const;\n\nconst OPENERS = new Set([\"openSync\", \"open\"]);\n\nfunction opensForWriting(flags: unknown): boolean {\n if (typeof flags === \"number\") return (flags & 3) === constants.O_WRONLY;\n return typeof flags === \"string\" && /^[wa][xs]?$/.test(flags);\n}\n\nexport interface UndeclaredReadGuard {\n violations: string[];\n restore(): void;\n}\n\n/**\n * Test harness: makes any filesystem read outside ctx.inputs throw and\n * records it. Write-only opens are not reads and pass; read-write opens stay guarded. Paths under node_modules, node: internals and numeric file\n * descriptors are allowed.\n *\n * options.allow - extra predicate for paths that may be read\n *\n * Returns the recorded violations and a restore function.\n */\nexport function guardUndeclaredReads(\n options: { allow?: (path: string) => boolean } = {},\n): UndeclaredReadGuard {\n const violations: string[] = [];\n const originals: Array<() => void> = [];\n const allowed = (target: unknown): boolean => {\n if (inInternalRead()) return true;\n if (typeof target === \"number\") return true;\n if (typeof target !== \"string\" && !(target instanceof URL)) return false;\n const path = normalize(String(target));\n return (\n path.startsWith(\"node:\") ||\n path.includes(\"/node_modules/\") ||\n Boolean(options.allow?.(path))\n );\n };\n\n const wrap = (\n holder: Record<string, unknown>,\n name: string,\n async = false,\n ): void => {\n const original = holder[name];\n if (typeof original !== \"function\") return;\n holder[name] = function guarded(this: unknown, ...args: unknown[]) {\n if (\n !allowed(args[0]) &&\n !(OPENERS.has(name) && opensForWriting(args[1]))\n ) {\n const message = `${name} read outside ctx.inputs: ${String(args[0])}`;\n violations.push(message);\n const error = new Error(message);\n if (async) return Promise.reject(error);\n throw error;\n }\n return Reflect.apply(original, this, args);\n };\n Object.assign(holder[name] as object, original);\n originals.push(() => {\n holder[name] = original;\n });\n };\n\n for (const name of GUARDED) wrap(fs as never, name);\n wrap(fs.realpathSync as never, \"native\");\n for (const name of GUARDED_PROMISES) wrap(fs.promises as never, name, true);\n syncBuiltinESMExports();\n\n return {\n violations,\n restore() {\n for (const undo of originals.splice(0)) undo();\n syncBuiltinESMExports();\n },\n };\n}\n","// The input side of a plugin's interactive `walk`: ask one question, or show\n// a menu, and report whether the person answered or wants to move around.\n// Plugins drive the walk; this only talks to the terminal.\n\nimport prompts from \"prompts\";\n\nexport type Nav = \"back\" | \"skip\" | \"menu\" | \"quit\";\n\n/** An answer, or a request to move: back a question, skip it, open the\n * menu, or stop (Ctrl-C / Esc). */\nexport type Reply = { value: string } | { nav: Nav };\n\nexport interface Choice {\n title: string;\n value: string;\n description?: string;\n}\n\nexport interface Question {\n /** A line above the prompt, e.g. \"Business Info · 3 left\". */\n section?: string;\n message: string;\n /** `secret` hides the typing; `search` filters a long list as you type. */\n kind: \"text\" | \"secret\" | \"select\" | \"search\";\n choices?: Choice[];\n /** The saved answer, already masked if sensitive. Enter keeps it. */\n current?: string;\n hint?: string;\n canGoBack: boolean;\n}\n\nexport interface MenuItem<T extends string> {\n title: string;\n value: T;\n description?: string;\n disabled?: boolean;\n}\n\nexport interface Prompter {\n ask(question: Question): Promise<Reply>;\n /** Null when the person cancels the menu. */\n menu<T extends string>(\n message: string,\n items: ReadonlyArray<MenuItem<T>>,\n ): Promise<T | null>;\n note(text: string): void;\n}\n\nexport const NAV_HELP =\n \"Type < to go back, > to skip, ? for the menu. Every answer is saved as you go; Ctrl-C stops.\";\n\nconst TYPED_NAV: Record<string, Nav> = {\n \"<\": \"back\",\n \">\": \"skip\",\n \"?\": \"menu\",\n};\n\n/** A typed `<`, `>` or `?` moves instead of answering. */\nexport function parseTyped(raw: string): Reply {\n const nav = TYPED_NAV[raw.trim()];\n return nav ? { nav } : { value: raw };\n}\n\n// Navigation entries appended to a pick list. The NUL prefix keeps them\n// from colliding with a real option value.\nconst NAV_PREFIX = \"\\u0000\";\n\nfunction navChoices(canGoBack: boolean): Choice[] {\n return [\n ...(canGoBack ? [{ title: \"← Back\", value: `${NAV_PREFIX}back` }] : []),\n { title: \"Skip →\", value: `${NAV_PREFIX}skip` },\n { title: \"Menu…\", value: `${NAV_PREFIX}menu` },\n ];\n}\n\nfunction fromChoice(value: string): Reply {\n return value.startsWith(NAV_PREFIX)\n ? { nav: value.slice(NAV_PREFIX.length) as Nav }\n : { value };\n}\n\n/** A prompter on the terminal, built on `prompts`. */\nexport function terminalPrompter(): Prompter {\n let cancelled = false;\n const onCancel = () => {\n cancelled = true;\n return false;\n };\n\n return {\n async ask(q) {\n cancelled = false;\n if (q.section) process.stdout.write(`\\n${q.section}\\n`);\n const message = q.current\n ? `${q.message} (saved: ${q.current})`\n : q.message;\n\n if (q.kind === \"select\" || q.kind === \"search\") {\n const choices = [...(q.choices ?? []), ...navChoices(q.canGoBack)];\n const initial = Math.max(\n 0,\n choices.findIndex(\n (c) => c.title === q.current || c.value === q.current,\n ),\n );\n const { answer } = (await prompts(\n {\n type: q.kind === \"search\" ? \"autocomplete\" : \"select\",\n name: \"answer\",\n message,\n choices,\n initial,\n hint: q.hint,\n ...(q.kind === \"search\"\n ? {\n suggest: async (input: string, all: Choice[]) => {\n const needle = input.trim().toLowerCase();\n return all.filter(\n (c) =>\n c.value.startsWith(NAV_PREFIX) ||\n c.title.toLowerCase().includes(needle) ||\n c.value.toLowerCase().includes(needle),\n );\n },\n }\n : {}),\n } as prompts.PromptObject<\"answer\">,\n { onCancel },\n )) as { answer?: string };\n if (cancelled || answer === undefined) return { nav: \"quit\" };\n return fromChoice(answer);\n }\n\n const { answer } = (await prompts(\n {\n type: q.kind === \"secret\" ? \"password\" : \"text\",\n name: \"answer\",\n message: q.hint ? `${message} — ${q.hint}` : message,\n // A secret's saved value is masked, so it can't pre-fill; Enter on\n // an empty secret keeps what's saved.\n ...(q.kind === \"text\" && q.current ? { initial: q.current } : {}),\n },\n { onCancel },\n )) as { answer?: string };\n if (cancelled || answer === undefined) return { nav: \"quit\" };\n // Enter on a secret that's already saved keeps it: moving on without\n // an answer is a skip, so a walk never saves an empty value over it.\n if (q.kind === \"secret\" && q.current && answer === \"\")\n return { nav: \"skip\" };\n return parseTyped(answer);\n },\n\n async menu(message, items) {\n cancelled = false;\n const { choice } = (await prompts(\n {\n type: \"select\",\n name: \"choice\",\n message,\n choices: items.map((item) => ({\n title: item.title,\n value: item.value,\n description: item.description,\n disabled: item.disabled,\n })),\n },\n { onCancel },\n )) as { choice?: string };\n if (cancelled || choice === undefined) return null;\n return choice as (typeof items)[number][\"value\"];\n },\n\n note(text) {\n process.stdout.write(`${text}\\n`);\n },\n };\n}\n\n/** A walk needs a person at a terminal; scripts and agents use the\n * non-interactive commands it names. */\nexport function assertInteractive(\n alternative: string,\n isTTY: boolean = Boolean(process.stdin.isTTY && process.stdout.isTTY),\n): void {\n if (!isTTY) {\n throw new Error(\n `walk asks questions in a terminal. In a script, use ${alternative}.`,\n );\n }\n}\n","/**\n * The canonical GitSync commit-subject format, shared by every kind of\n * Fluid-managed repository — Mist apps, Themes, Portals and Widgets.\n *\n * Each kind used to invent its own wording, so `git log` across a\n * company's repos read as four unrelated systems and only some commits\n * said who made them. One shape now covers all of them:\n *\n * <Actor Name>: <Action> · <timestamp> (<public_id>)\n * Mike Tingey: Publish portal Acme Portal · 2026-08-06 12:00:00 (0182d21e-…)\n *\n * Name and action come first so `git log --oneline` stays scannable in a\n * narrow terminal; the long UUID sits at the end where truncation eats\n * it instead of the prose. The timestamp is redundant with git's own\n * committer date but is kept inline because it survives cherry-picks,\n * rebases and the hosting providers' deployment feeds, which surface the\n * subject and nothing else.\n *\n * System-authored commits (auto-provisioning, sweeper retries, webhook\n * fan-out, an unreachable `/api/me`) use the literal actor name `Fluid`\n * and carry no UUID, so they parse with the same grammar rather than\n * needing a second one:\n *\n * Fluid: Publish theme Aurora · 2026-08-06 12:00:00\n *\n * The Ruby side mirrors this in `GitSync::CommitSubject`\n * (fluid/app/models/git_sync/commit_subject.rb) and Mist Desktop mirrors\n * the parser in `apps/mist-desktop/src/shared/git-commit-subject.ts`.\n * Change all three together.\n */\n\n/** The person a commit is attributed to. */\nexport interface GitSyncActor {\n /** Display name: full_name → first+last → email → `user-<id>`. */\n readonly name: string;\n /** The user's stable public UUID, rendered as a ` (uuid)` suffix. */\n readonly publicId: string | null;\n}\n\n/** Actor name used when no human triggered the commit. */\nexport const SYSTEM_ACTOR_NAME = \"Fluid\";\n\n/** Parseable fallback when a caller supplies only grammar delimiters or\n * whitespace as the action (for example, `-m \"·\"`). */\nconst DEFAULT_ACTION = \"Sync changes\";\n\n/**\n * A subject broken back into its parts. `publicId` is null for\n * system-authored commits and for actors whose public id was unknown at\n * commit time.\n */\nexport interface ParsedGitSyncSubject {\n readonly actorName: string;\n readonly action: string;\n /** The inline `YYYY-MM-DD HH:MM:SS` stamp, in UTC. */\n readonly timestamp: string;\n readonly publicId: string | null;\n}\n\n/**\n * Matches the canonical shape. The actor group is greedy so a display\n * name containing `\": \"` (e.g. `Tingey: Mike`) splits at the LAST colon\n * before the ` · ` separator — safe because {@link subjectFragment}\n * strips both delimiters out of every value we interpolate into an\n * action.\n */\nconst SUBJECT_RE =\n /^(.+): (.+?) · (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})(?: \\(([^()]+)\\))?$/;\n\n/** `2026-08-06T12:00:00.000Z` → `2026-08-06 12:00:00`. */\nexport function formatCommitTimestamp(when: Date): string {\n return when.toISOString().slice(0, 19).replace(\"T\", \" \");\n}\n\n/**\n * Neutralize the two sequences the grammar splits on, so no value can\n * shift the actor / action / uuid boundaries:\n *\n * `\": \"` separates the actor from the action\n * `\"·\"` separates the action from the timestamp\n *\n * Only those exact sequences are replaced, not every colon — `12:30`\n * and `fix:handle-nulls` survive intact, because neither can be\n * mistaken for a field boundary. A trailing colon is likewise safe: the\n * parser backtracks past it.\n *\n * {@link gitSyncCommitSubject} applies this to every action, so callers\n * don't have to remember. It's idempotent, so calling it yourself on an\n * interpolated resource name (as the CLIs do) costs nothing.\n */\nexport function subjectFragment(value: string): string {\n return value\n .replace(/:\\s/g, \" \")\n .replace(/·/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Build a canonical commit subject.\n *\n * @param action - What happened, e.g. `Publish theme Aurora`. Run any\n * interpolated resource name through {@link subjectFragment} first.\n * @param actor - The signed-in user, or null for system-authored\n * commits (which are attributed to `Fluid`).\n * @param when - Injectable clock, so callers and tests get a stable\n * stamp.\n */\nexport function gitSyncCommitSubject(\n action: string,\n actor: GitSyncActor | null,\n when: Date = new Date(),\n): string {\n // Sanitized HERE rather than at each call site. The action is the one\n // field a user fully controls (`-m`), and a `\": \"` in it would be read\n // back as part of the actor — `-m \"Publish: Acme\"` attributing the\n // commit to \"Mike Tingey: Publish\". Doing it at the choke point means\n // no current or future caller can reintroduce that.\n //\n // The actor name is deliberately NOT sanitized: a real name may\n // contain `\": \"` (`Tingey: Mike`), and the greedy actor group parses\n // that correctly precisely because the action can no longer contain\n // the delimiter.\n const safeAction = subjectFragment(action) || DEFAULT_ACTION;\n const stamp = formatCommitTimestamp(when);\n if (!actor) return `${SYSTEM_ACTOR_NAME}: ${safeAction} · ${stamp}`;\n const idSuffix = actor.publicId ? ` (${actor.publicId})` : \"\";\n return `${actor.name}: ${safeAction} · ${stamp}${idSuffix}`;\n}\n\n/**\n * Split a canonical subject back into its parts, or null when the\n * subject predates the format (legacy CLI wording such as `push @ <iso>`\n * or a hand-written commit). Callers fall back to rendering the raw\n * subject.\n */\nexport function parseGitSyncSubject(\n subject: string | null | undefined,\n): ParsedGitSyncSubject | null {\n if (!subject) return null;\n const match = subject.trim().match(SUBJECT_RE);\n if (!match) return null;\n const [, actorName, action, timestamp, publicId] = match;\n // The regex guarantees these groups, but noUncheckedIndexedAccess\n // types them as possibly-undefined.\n if (!actorName || !action || !timestamp) return null;\n return {\n actorName: actorName.trim(),\n action: action.trim(),\n timestamp,\n publicId: publicId?.trim() || null,\n };\n}\n\n/**\n * The person a canonical subject is attributed to, or null when the\n * subject isn't canonical or was system-authored. Use this for \"who\n * shipped this\" UI — a `Fluid:` commit has no human to name.\n */\nexport function gitSyncSubjectAuthor(\n subject: string | null | undefined,\n): string | null {\n const parsed = parseGitSyncSubject(subject);\n if (!parsed || parsed.actorName === SYSTEM_ACTOR_NAME) return null;\n return parsed.actorName;\n}\n\n/** The `/api/me` fields the actor is derived from. */\ninterface MeUser {\n readonly id?: unknown;\n readonly public_id?: unknown;\n readonly full_name?: unknown;\n readonly first_name?: unknown;\n readonly last_name?: unknown;\n readonly email?: unknown;\n}\n\n/** Some `/api/me` deployments nest the user, others return it flat. */\ninterface MeResponse extends MeUser {\n readonly user?: MeUser;\n}\n\nfunction str(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim().length > 0) return value.trim();\n return null;\n}\n\n/**\n * Resolve an `/api/me` body to a commit actor, with the name fallback\n * chain `full_name → first+last → email → user-<id>`. Returns null when\n * the body carries no usable identity at all, which callers treat the\n * same as an unreachable `/api/me`: a system-authored commit.\n */\nexport function gitSyncActorFromMe(raw: MeResponse): GitSyncActor | null {\n const user = raw.user ?? raw;\n const composed = [str(user.first_name), str(user.last_name)]\n .filter((part): part is string => part !== null)\n .join(\" \")\n .trim();\n const name =\n str(user.full_name) ??\n (composed.length > 0 ? composed : null) ??\n str(user.email) ??\n (typeof user.id === \"number\" && Number.isFinite(user.id)\n ? `user-${user.id}`\n : null);\n if (!name) return null;\n const publicId =\n str(user.public_id) ??\n (typeof user.id === \"number\" && Number.isFinite(user.id)\n ? String(user.id)\n : null);\n return { name, publicId };\n}\n","/**\n * Turn a set of changed paths into the `<Action>` half of a canonical\n * GitSync commit subject (see commit-subject.ts).\n *\n * Publishes used to be stamped with a constant — \"Publish from Mist\n * Desktop\", \"Publish theme Aurora\" — so `git log` told you a publish\n * happened but never what it carried. Every entry in the history looked\n * identical, which made the log useless for finding the commit that\n * introduced something.\n *\n * This derives a short, honest phrase from the staged diff:\n *\n * Update templates/product.liquid\n * Update 3 files in templates\n * Add 2 files, update 3, delete 1\n *\n * It is deliberately mechanical. A caller that knows the INTENT behind a\n * change (Mist Desktop, or a human passing `-m`) should pass that\n * instead — an intent describes why, and no diff can recover that. This\n * is the fallback for when nobody supplied one.\n *\n * Pure: callers collect the diff (each CLI has its own git layer) and\n * hand the entries here, so the wording can't drift between kinds.\n */\n\n/** Git's porcelain status letters, narrowed to what we act on. */\nexport type ChangeStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\n/**\n * What an auto-commit helper accepts as its subject: either a literal\n * (the caller already knows the intent — a `-m` message), or a resolver\n * handed the staged changes so it can describe them.\n *\n * The resolver form exists because staging is decided INSIDE the commit\n * helpers — they `git add -A` and then unstage private paths — so only\n * they know the final file set. A summary built by the caller beforehand\n * would describe a diff the commit doesn't carry.\n *\n * It may return a promise so a caller can start slow work (an `/api/me`\n * identity lookup, say) BEFORE the git reconcile and await it here, at\n * the last possible moment — overlapping it with the fetch/merge instead\n * of paying for it serially up front. Anything awaited here is on the\n * critical path of the commit, so it must be bounded and best-effort:\n * a publish must never hang waiting to describe itself.\n */\nexport type CommitMessage =\n | string\n | ((changes: readonly ChangeEntry[]) => string | Promise<string>);\n\nexport interface ChangeEntry {\n readonly status: ChangeStatus;\n /** Repo-relative path, forward-slashed. */\n readonly path: string;\n}\n\n/** Map a `git diff --name-status` letter to a status. `R`/`C` carry a\n * similarity score (`R100`), so only the leading letter is read.\n * Unknown letters (`U` unmerged, `T` typechange) count as modified —\n * the file did change, and mislabeling the verb is better than\n * dropping it from the count. */\nexport function changeStatusFromCode(code: string): ChangeStatus {\n switch (code.trim().charAt(0).toUpperCase()) {\n case \"A\":\n return \"added\";\n case \"D\":\n return \"deleted\";\n case \"R\":\n return \"renamed\";\n default:\n return \"modified\";\n }\n}\n\n/**\n * Parse `git diff --cached --name-status -z` output.\n *\n * NUL-delimited on purpose: paths containing spaces, quotes or newlines\n * are legal in git and common in themes (`assets/hero image.png`), and\n * the newline-delimited form quotes and escapes them, which would corrupt\n * both the count and the path. With `-z`, records are\n * `status\\0path\\0` — except renames and copies, which are\n * `status\\0from\\0to\\0` and consume an extra field.\n */\nexport function parseNameStatusZ(stdout: string): ChangeEntry[] {\n const fields = stdout.split(\"\\0\").filter((f) => f.length > 0);\n const entries: ChangeEntry[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i];\n if (code === undefined) break;\n const status = changeStatusFromCode(code);\n if (status === \"renamed\") {\n // status, from, to — the destination is the path we report.\n const to = fields[i + 2];\n if (to === undefined) break;\n entries.push({ status, path: to });\n i += 3;\n continue;\n }\n const path = fields[i + 1];\n if (path === undefined) break;\n entries.push({ status, path });\n i += 2;\n }\n return entries;\n}\n\n/** Top-level directory of a path, or null for a repo-root file. */\nfunction topLevelDir(path: string): string | null {\n const slash = path.indexOf(\"/\");\n return slash > 0 ? path.slice(0, slash) : null;\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? \"\" : \"s\"}`;\n}\n\nconst VERB_FOR: Record<ChangeStatus, string> = {\n added: \"Add\",\n modified: \"Update\",\n deleted: \"Delete\",\n renamed: \"Rename\",\n};\n\n/**\n * Build the action phrase for a set of changes, or null when there is\n * nothing to describe — the caller then falls back to its own constant\n * (`Publish theme Aurora`), so an empty diff never produces a subject\n * like \"Update 0 files\".\n *\n * @param entries - The staged changes.\n * @param maxLength - Clip the result to keep `git log --oneline`\n * readable. The subject also carries a name, timestamp and UUID, so\n * the action gets a modest budget.\n */\nexport function summarizeChanges(\n entries: readonly ChangeEntry[],\n maxLength = 72,\n): string | null {\n if (entries.length === 0) return null;\n\n // A single change is the most useful case and the most common one:\n // name the actual file rather than counting to one.\n if (entries.length === 1) {\n const only = entries[0]!;\n return clip(`${VERB_FOR[only.status]} ${only.path}`, maxLength);\n }\n\n // Group by verb, ordered so the dominant kind of change leads.\n const byStatus = new Map<ChangeStatus, number>();\n for (const entry of entries) {\n byStatus.set(entry.status, (byStatus.get(entry.status) ?? 0) + 1);\n }\n\n // All one verb → \"Update 3 files\", plus a location when they share one.\n if (byStatus.size === 1) {\n const status = entries[0]!.status;\n const dirs = new Set(entries.map((e) => topLevelDir(e.path)));\n const only = dirs.size === 1 ? [...dirs][0] : null;\n const phrase = `${VERB_FOR[status]} ${plural(entries.length, \"file\")}`;\n return clip(only ? `${phrase} in ${only}` : phrase, maxLength);\n }\n\n // Mixed → lead with the largest group, then the rest as bare counts:\n // \"Update 3 files, add 2, delete 1\".\n const ordered = [...byStatus.entries()].sort(\n ([aStatus, aCount], [bStatus, bCount]) =>\n bCount - aCount || VERB_FOR[aStatus].localeCompare(VERB_FOR[bStatus]),\n );\n const [leadStatus, leadCount] = ordered[0]!;\n const rest = ordered\n .slice(1)\n .map(([status, count]) => `${VERB_FOR[status].toLowerCase()} ${count}`);\n const head = `${VERB_FOR[leadStatus]} ${plural(leadCount, \"file\")}`;\n return clip([head, ...rest].join(\", \"), maxLength);\n}\n\nfunction clip(text: string, maxLength: number): string {\n return text.length > maxLength\n ? `${text.slice(0, maxLength - 1).trimEnd()}…`\n : text;\n}\n","/**\n * Cache the signed-in user's commit identity on the active profile.\n *\n * Commit subjects are stamped `<name>: <action> · <ts> (<public_id>)`,\n * which needs the user's display name and public id. `/api/me` is the\n * only source, and it can be slow — so paying for it on EVERY push, to\n * learn a name that changes approximately never, is the wrong trade.\n *\n * The identity is stored per profile (profiles are per token + company,\n * so the cache can't leak across accounts) and refreshed only when\n * missing or stale. Login and company-switch write a fresh profile,\n * which drops the cached identity with it.\n *\n * Every failure mode here is non-fatal: an unreadable or unwritable\n * config just means we fall back to the network, and a failed network\n * lookup means a `Fluid:` system commit. A publish must never fail\n * because we couldn't work out whose name to put on it.\n */\n\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { GitSyncActor } from \"./commit-subject.js\";\n\n/**\n * How long a cached identity is trusted. Long, because a display name\n * changing is rare — but not forever, so a rename does eventually reach\n * the commit log without the user having to re-login.\n */\nexport const ACTOR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days\n\n/** Cached identity as persisted on a profile. */\nexport interface CachedGitSyncActor {\n readonly name: string;\n readonly publicId: string | null;\n /** ISO-8601. */\n readonly cachedAt: string;\n}\n\nfunction isFresh(cached: CachedGitSyncActor, now: number): boolean {\n const at = Date.parse(cached.cachedAt);\n // An unparseable timestamp is treated as stale rather than trusted\n // forever — a corrupt field shouldn't pin a wrong name permanently.\n if (Number.isNaN(at)) return false;\n return now - at < ACTOR_CACHE_TTL_MS;\n}\n\n/** The cached identity for the active profile, or null. */\nexport function readCachedActor(now = Date.now()): GitSyncActor | null {\n try {\n const config = readConfig();\n const profileName = config.activeProfile;\n if (!profileName) return null;\n const cached = config.profiles[profileName]?.gitSyncActor;\n if (!cached || !cached.name || !isFresh(cached, now)) return null;\n return { name: cached.name, publicId: cached.publicId ?? null };\n } catch {\n return null;\n }\n}\n\n/** Persist an identity against the active profile. Best-effort. */\nexport function writeCachedActor(actor: GitSyncActor, now = new Date()): void {\n try {\n updateConfig((config) => {\n const profileName = config.activeProfile;\n if (!profileName) return config;\n const profile = config.profiles[profileName];\n if (!profile) return config;\n return {\n ...config,\n profiles: {\n ...config.profiles,\n [profileName]: {\n ...profile,\n gitSyncActor: {\n name: actor.name,\n publicId: actor.publicId,\n cachedAt: now.toISOString(),\n },\n },\n },\n };\n });\n } catch {\n // A read-only or malformed config just means we look it up again\n // next time — never a reason to fail a publish.\n }\n}\n\n/**\n * The commit identity, from cache when possible.\n *\n * @param fetchActor - Network lookup, used only on a cache miss. Each\n * CLI has its own client, so the caller supplies it. It must already\n * be bounded — this function adds no timeout of its own.\n *\n * Returns null when there's no cache and the lookup fails or yields no\n * usable identity; callers then write a `Fluid:` system commit.\n */\nexport async function resolveGitSyncActor(\n fetchActor: () => Promise<GitSyncActor | null>,\n): Promise<GitSyncActor | null> {\n const cached = readCachedActor();\n if (cached) return cached;\n\n const fetched = await fetchActor().catch(() => null);\n if (fetched) writeCachedActor(fetched);\n return fetched;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBAAwB;AACtC,SACE,QAAQ,IAAI,wBAAwB,4BACpC,QAAQ,OAAO,GAAG;;;AA6BtB,IAAa,iBAAb,cAAoC,MAAM;CACxC,YACE,SACA,QACA,QACA;AACA,QAAM,QAAQ;AAHL,OAAA,SAAA;AACA,OAAA,SAAA;AAGT,OAAK,OAAO;;;;;;;CAQd,IAAI,UAAmB;AACrB,MAAI,KAAK,WAAW,OAAO,KAAK,WAAW,IAAK,QAAO;AACvD,SAAO,qCAAqC,KAAK,KAAK,OAAO;;;;;;;;;AAUjE,eAAsB,YAAY,SAA6C;AAC7E,KAAI,CAAC,QAAQ,SAAS,CAAC,QAAQ,IAC7B,OAAM,IAAI,MAAM,0DAA0D;CAO5E,MAAM,OAAO,IAAI,UAAU;AAC3B,KAAI,QAAQ,OAAQ,MAAK,OAAO,UAAU,QAAQ,OAAO;AACzD,KAAI,QAAQ,mBAAmB,MAC7B,MAAK,OAAO,qBAAqB,QAAQ;AAE3C,KAAI,QAAQ,IACV,MAAK,OAAO,sBAAsB,QAAQ,IAAI;UACrC,QAAQ,MAAM;AACvB,OAAK,OAAO,YAAY,QAAQ,KAAK,KAAK;AAG1C,OAAK,OACH,QACA,IAAI,KAAK,CAAC,IAAI,WAAW,QAAQ,KAAK,MAAM,CAAC,CAAC,EAC9C,QAAQ,KAAK,KACd;;AAEH,KAAI,QAAQ,KAAM,MAAK,OAAO,QAAQ,QAAQ,KAAK;AACnD,KAAI,QAAQ,YAAa,MAAK,OAAO,eAAe,QAAQ,YAAY;AACxE,KAAI,QAAQ,KAAM,MAAK,OAAO,QAAQ,QAAQ,KAAK;AACnD,KAAI,QAAQ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pD,KAAI,QAAS,kBAAiB,QAAQ;AACtC,QAAO"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/dam/upload.ts","../src/domain/output.ts","../src/domain/context.ts","../src/domain/command.ts","../src/inputs/testing.ts","../src/walk/prompter.ts","../src/git-sync/commit-subject.ts","../src/git-sync/change-summary.ts","../src/git-sync/actor-cache.ts"],"sourcesContent":["/**\n * One upload to the Fluid DAM through the `upload.fluid.app/upload` service,\n * which does the three underlying calls (imagekit_auth, the ImageKit upload\n * and backfill_imagekit) in one request.\n *\n * `fluid assets upload` and `fluid sites media sync` both send their files\n * through this, with the bearer token their own login resolution picked.\n * It has no imports, so the plugins' Jest mocks of this package can re-export\n * it as it is.\n */\n\n/**\n * The upload service. Hard-coded: the bearer sent is the user's Fluid API\n * token, so the destination must be a Fluid-controlled host. A local service\n * is reached through the FLUID_UPLOAD_BASE env var, read from the process\n * environment, never from an argument a user types.\n */\nexport function damUploadBase(): string {\n return (\n process.env[\"FLUID_UPLOAD_BASE\"] ?? \"https://upload.fluid.app\"\n ).replace(/\\/$/, \"\");\n}\n\n/** What one DAM upload sends. Give `file` or `url`, not both. */\nexport interface DamUploadRequest {\n /** The Fluid API token sent as the bearer. */\n token: string;\n /** A local file's bytes and the name to store it under. */\n file?: { bytes: Uint8Array; name: string };\n /** An external address the service fetches the file from. */\n url?: string;\n /** The asset's display name. */\n name?: string;\n description?: string;\n /** Comma-separated tags. */\n tags?: string;\n /** An ImageKit folder override. */\n folder?: string;\n /** ImageKit's useUniqueFileName (default: true). */\n uniqueFilename?: boolean;\n /** Also create a Fluid Media resource. */\n createMedia?: boolean;\n /** Each request line, when verbose. */\n onRequest?: (line: string) => void;\n /** The fetch to send with (default: the global one). */\n fetch?: typeof fetch;\n}\n\n/** A refused or failed upload, with the service's HTTP status and its body's start. */\nexport class DamUploadError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly detail: string,\n ) {\n super(message);\n this.name = \"DamUploadError\";\n }\n\n /**\n * Whether the login may not upload to the DAM at all: the service refused\n * the token, or passed on Fluid's refusal of the upload credential (it\n * answers that as a 500 naming imagekit_auth's own 401 or 403).\n */\n get refused(): boolean {\n if (this.status === 401 || this.status === 403) return true;\n return /imagekit_auth failed \\((401|403)\\)/.test(this.detail);\n }\n}\n\n/**\n * Uploads one file or URL to the DAM and returns the service's JSON answer,\n * whose `asset.default_variant_url` is the asset's CDN address.\n *\n * Throws DamUploadError when the service answers anything but 2xx.\n */\nexport async function uploadToDam(request: DamUploadRequest): Promise<unknown> {\n if (!request.file === !request.url) {\n throw new Error(\"Give a DAM upload a file or a URL, not both or neither.\");\n }\n // Multipart order matters for streaming uploads (over about 100 MB). The\n // service streams `file` straight through to ImageKit, so any field\n // ImageKit needs (`fileName`, `folder`, `useUniqueFileName`) must arrive\n // BEFORE the file part. Fields used after the upload (`name`,\n // `description`, `tags`, `create_media`) can sit anywhere; they go last.\n const form = new FormData();\n if (request.folder) form.append(\"folder\", request.folder);\n if (request.uniqueFilename === false) {\n form.append(\"useUniqueFileName\", \"false\");\n }\n if (request.url) {\n form.append(\"external_asset_url\", request.url);\n } else if (request.file) {\n form.append(\"fileName\", request.file.name);\n // A Blob, so fetch's multipart serializer writes a Content-Disposition\n // with the file name.\n form.append(\n \"file\",\n new Blob([new Uint8Array(request.file.bytes)]),\n request.file.name,\n );\n }\n if (request.name) form.append(\"name\", request.name);\n if (request.description) form.append(\"description\", request.description);\n if (request.tags) form.append(\"tags\", request.tags);\n if (request.createMedia) form.append(\"create_media\", \"true\");\n\n const endpoint = `${damUploadBase()}/upload`;\n request.onRequest?.(`POST ${endpoint}`);\n const send = request.fetch ?? fetch;\n const resp = await send(endpoint, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${request.token}` },\n body: form,\n });\n\n if (!resp.ok) {\n let detail = \"\";\n try {\n detail = (await resp.text()).slice(0, 400);\n } catch {\n // No body, or an unreadable one: the message stays generic.\n }\n throw new DamUploadError(\n `Upload failed (HTTP ${resp.status})${detail ? `: ${detail}` : \"\"}`,\n resp.status,\n detail,\n );\n }\n return (await resp.json()) as unknown;\n}\n\n/** The CDN address in an upload's answer, or null when it has none. */\nexport function damAssetUrlOf(answer: unknown): string | null {\n if (typeof answer !== \"object\" || answer === null) return null;\n const asset = (answer as { asset?: unknown }).asset;\n if (typeof asset !== \"object\" || asset === null) return null;\n const url = (asset as { default_variant_url?: unknown }).default_variant_url;\n return typeof url === \"string\" && url.startsWith(\"https://\") ? url : null;\n}\n\n/** The DAM asset code in an upload's answer, or null when it has none. */\nexport function damAssetCodeOf(answer: unknown): string | null {\n if (typeof answer !== \"object\" || answer === null) return null;\n const asset = (answer as { asset?: unknown }).asset;\n if (typeof asset !== \"object\" || asset === null) return null;\n const code = (asset as { code?: unknown }).code;\n return typeof code === \"string\" && code.length > 0 ? code : null;\n}\n","import type { OutputOptions } from \"./types.js\";\n\nexport function formatOutput(data: unknown, options: OutputOptions): string {\n let result = data;\n\n if (options.jq) {\n result = extractPath(result, options.jq);\n }\n\n if (options.format === \"table\") {\n return formatTable(result);\n }\n\n if (options.compact) {\n return JSON.stringify(result);\n }\n return JSON.stringify(result, null, 2);\n}\n\nfunction extractPath(data: unknown, path: string): unknown {\n const parts = path\n .replace(/^\\.*/, \"\")\n .split(/\\.|\\[/)\n .filter(Boolean)\n .map((p) => p.replace(/\\]$/, \"\"));\n\n let current: any = data;\n for (const part of parts) {\n if (current == null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction formatTable(data: unknown): string {\n if (Array.isArray(data)) {\n if (data.length === 0) return \"(empty)\";\n\n if (typeof data[0] === \"object\" && data[0] !== null) {\n const keys = Object.keys(data[0]);\n const widths = keys.map((k) =>\n Math.max(k.length, ...data.map((row) => String(row[k] ?? \"\").length)),\n );\n\n const header = keys\n .map((k, i) => k.toUpperCase().padEnd(widths[i]!))\n .join(\" \");\n const separator = widths.map((w) => \"-\".repeat(w)).join(\" \");\n const rows = data.map((row) =>\n keys.map((k, i) => String(row[k] ?? \"\").padEnd(widths[i]!)).join(\" \"),\n );\n\n return [header, separator, ...rows].join(\"\\n\");\n }\n\n return data.map(String).join(\"\\n\");\n }\n\n if (typeof data === \"object\" && data !== null) {\n const entries = Object.entries(data);\n const maxKeyLen = Math.max(...entries.map(([k]) => k.length));\n return entries\n .map(([k, v]) => `${k.padEnd(maxKeyLen)} ${JSON.stringify(v)}`)\n .join(\"\\n\");\n }\n\n return String(data);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { ApiError, createFetchClient } from \"@fluid-app/api-client-core\";\nimport type { FetchClient } from \"@fluid-app/api-client-core\";\n\nimport {\n clientAccessToken,\n invalidateClientToken,\n} from \"../auth/identity/client.js\";\nimport { profileAccessToken } from \"../auth/identity/session.js\";\nimport {\n type CredentialSource,\n describeCredentialSource,\n resolveCredentialSource,\n} from \"../auth/token.js\";\nimport { isClientProfile, isIdentityProfile } from \"../config/types.js\";\nimport { createInputsReader } from \"../inputs/reader.js\";\nimport { formatOutput } from \"./output.js\";\nimport type { CommandContext, OutputOptions } from \"./types.js\";\n\ninterface SentToken {\n token: string | null;\n}\n\nconst sentToken = new AsyncLocalStorage<SentToken>();\n\nlet rejectionWarned = false;\n\n/** Lets the once-per-process rejection warning fire again. For tests. */\nexport function resetRejectionWarningForTests(): void {\n rejectionWarned = false;\n}\n\nfunction warnRejected(source: CredentialSource): void {\n if (rejectionWarned) return;\n const described = describeCredentialSource(source);\n let message: string | null = null;\n if (described.mode === \"token\") {\n if (described.origin === \"fd\" || described.origin === \"env\") {\n message = `The token from ${described.envVar} was rejected (401).`;\n }\n } else if (described.mode === \"legacy\") {\n const where =\n described.origin === \"fluidrc\"\n ? `.fluidrc profile \"${described.profileName}\"`\n : `config.json profile \"${described.profileName}\"`;\n message = `The token from ${where} was rejected (401); run fluid login.`;\n }\n if (!message) return;\n rejectionWarned = true;\n process.stderr.write(`${message}\\n`);\n}\n\nexport function createCommandContext(opts: {\n token?: string;\n baseUrl?: string;\n profile?: string;\n format: \"json\" | \"table\";\n compact: boolean;\n jq?: string;\n verbose: boolean;\n}): CommandContext {\n let clientInstance: FetchClient | null = null;\n\n const outputOptions: OutputOptions = {\n format: opts.format,\n compact: opts.compact,\n jq: opts.jq,\n };\n\n /**\n * The token getter for this command. An identity-mode profile's getter\n * restores and refreshes its session on each call, so a long command never\n * sends an expired token.\n */\n function requireToken(): () => string | Promise<string> {\n const getter = tokenGetter(resolveSource(opts));\n if (getter) return getter;\n if (opts.profile) {\n throw new Error(\n `No API token found for profile \"${opts.profile}\". Run \\`fluid login\\` for that profile or provide --token <token>`,\n );\n }\n throw new Error(\n \"No API token found. Run `fluid login` or provide --token <token>\",\n );\n }\n\n return {\n verbose: opts.verbose,\n inputs: createInputsReader(),\n\n async getClient(): Promise<FetchClient> {\n if (clientInstance) return clientInstance;\n\n const getAuthToken = requireToken();\n const baseUrl =\n opts.baseUrl ??\n process.env[\"FLUID_API_BASE\"] ??\n \"https://api.fluid.app\";\n\n clientInstance = retryingOnce(\n createFetchClient({ baseUrl, getAuthToken }),\n resolveSource(opts),\n );\n\n return clientInstance;\n },\n\n async getClientFor(serviceBaseUrl: string): Promise<FetchClient> {\n const getAuthToken = requireToken();\n return retryingOnce(\n createFetchClient({\n baseUrl: serviceBaseUrl.replace(/\\/$/, \"\"),\n getAuthToken,\n }),\n resolveSource(opts),\n );\n },\n\n output(data: unknown): void {\n const formatted = formatOutput(data, outputOptions);\n process.stdout.write(formatted + \"\\n\");\n },\n\n parseBody(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n throw new Error(`Invalid JSON body: ${raw}`);\n }\n },\n };\n}\n\nfunction resolveSource(opts: {\n token?: string;\n profile?: string;\n}): CredentialSource | null {\n if (opts.token) {\n return { kind: \"token\", token: opts.token, origin: \"explicit\" };\n }\n return resolveCredentialSource(opts.profile);\n}\n\nfunction tokenGetter(\n source: CredentialSource | null,\n): (() => string | Promise<string>) | null {\n if (!source) return null;\n if (source.kind === \"token\") {\n const token = source.token;\n return () => token;\n }\n const profile = source.profile;\n if (isIdentityProfile(profile)) return () => profileAccessToken(profile);\n if (isClientProfile(profile)) {\n return async () => {\n const token = await clientAccessToken(profile);\n const slot = sentToken.getStore();\n if (slot) slot.token = token;\n return token;\n };\n }\n const token = profile.token;\n return token ? () => token : null;\n}\n\n/**\n * A request the API answers 401 is handled by credential kind. A client\n * profile drops its held token and replays once with a new one. A legacy\n * profile from `.fluidrc` or the active config, and a token from the\n * environment, only warn. Every other credential is returned as is.\n */\nfunction retryingOnce(\n client: FetchClient,\n source: CredentialSource | null,\n): FetchClient {\n if (!source) return client;\n const clientProfile =\n source.kind === \"profile\" && isClientProfile(source.profile)\n ? source.profile\n : null;\n const legacyProfile =\n source.kind === \"profile\" &&\n !isClientProfile(source.profile) &&\n !isIdentityProfile(source.profile) &&\n (source.origin === \"fluidrc\" || source.origin === \"active\")\n ? source.profile\n : null;\n const warnOnly =\n source.kind === \"token\" &&\n (source.origin === \"fd\" || source.origin === \"env\");\n if (!clientProfile && !legacyProfile && !warnOnly) return client;\n\n return new Proxy(client, {\n get(target, property, receiver) {\n const value: unknown = Reflect.get(target, property, receiver);\n if (typeof value !== \"function\") return value;\n return async (...args: unknown[]) => {\n const slot: SentToken = { token: null };\n try {\n return await sentToken.run(slot, () => value.apply(target, args));\n } catch (error) {\n if (!(error instanceof ApiError) || error.status !== 401) throw error;\n if (clientProfile) {\n invalidateClientToken(clientProfile, slot.token);\n return value.apply(target, args);\n }\n warnRejected(source);\n throw error;\n }\n };\n },\n });\n}\n","import { Command } from \"commander\";\n\nimport { createCommandContext } from \"./context.js\";\nimport type { CommandContext } from \"./types.js\";\n\ntype RegisterFn = (parent: Command, ctx: CommandContext) => void;\n\nexport function createDomainCommand(\n name: string,\n description: string,\n register: RegisterFn,\n): Command {\n const cmd = new Command(name)\n .description(description)\n // Keep global domain flags usable before or after nested subcommands.\n .enablePositionalOptions(false)\n .option(\"--token <token>\", \"API authentication token\")\n .option(\"--base-url <url>\", \"API base URL\")\n .option(\"--profile <name>\", \"Config profile name\")\n .option(\"--format <format>\", \"Output format (json|table)\", \"json\")\n .option(\"--compact\", \"Compact JSON output\", false)\n .option(\"--jq <path>\", \"Extract value at JSON path\")\n .option(\"--verbose\", \"Print request details to stderr\", false);\n\n let resolvedCtx: CommandContext | null = null;\n\n function getCtx(): CommandContext {\n if (!resolvedCtx) {\n const opts = cmd.opts();\n resolvedCtx = createCommandContext({\n token: opts.token,\n baseUrl: opts.baseUrl,\n profile: opts.profile,\n format: opts.format as \"json\" | \"table\",\n compact: opts.compact,\n jq: opts.jq,\n verbose: opts.verbose,\n });\n }\n return resolvedCtx;\n }\n\n const lazyCtx: CommandContext = {\n get verbose() {\n return getCtx().verbose;\n },\n getClient() {\n return getCtx().getClient();\n },\n getClientFor(baseUrl: string) {\n return getCtx().getClientFor(baseUrl);\n },\n output(data: unknown) {\n return getCtx().output(data);\n },\n get inputs() {\n return getCtx().inputs;\n },\n parseBody(raw: string) {\n return getCtx().parseBody(raw);\n },\n };\n\n register(cmd, lazyCtx);\n\n return cmd;\n}\n","import fs, { constants } from \"node:fs\";\nimport { syncBuiltinESMExports } from \"node:module\";\nimport { normalize } from \"node:path\";\n\nimport { inInternalRead } from \"./scope.js\";\n\nconst GUARDED = [\n \"readFileSync\",\n \"readFile\",\n \"createReadStream\",\n \"readdirSync\",\n \"readdir\",\n \"statSync\",\n \"stat\",\n \"lstatSync\",\n \"lstat\",\n \"openSync\",\n \"open\",\n \"opendirSync\",\n \"opendir\",\n \"realpathSync\",\n \"existsSync\",\n \"accessSync\",\n \"access\",\n \"openAsBlob\",\n] as const;\n\nconst GUARDED_PROMISES = [\n \"readFile\",\n \"readdir\",\n \"stat\",\n \"lstat\",\n \"open\",\n \"opendir\",\n \"realpath\",\n \"access\",\n] as const;\n\nconst OPENERS = new Set([\"openSync\", \"open\"]);\n\nfunction opensForWriting(flags: unknown): boolean {\n if (typeof flags === \"number\") return (flags & 3) === constants.O_WRONLY;\n return typeof flags === \"string\" && /^[wa][xs]?$/.test(flags);\n}\n\nexport interface UndeclaredReadGuard {\n violations: string[];\n restore(): void;\n}\n\n/**\n * Test harness: makes any filesystem read outside ctx.inputs throw and\n * records it. Write-only opens are not reads and pass; read-write opens stay guarded. Paths under node_modules, node: internals and numeric file\n * descriptors are allowed.\n *\n * options.allow - extra predicate for paths that may be read\n *\n * Returns the recorded violations and a restore function.\n */\nexport function guardUndeclaredReads(\n options: { allow?: (path: string) => boolean } = {},\n): UndeclaredReadGuard {\n const violations: string[] = [];\n const originals: Array<() => void> = [];\n const allowed = (target: unknown): boolean => {\n if (inInternalRead()) return true;\n if (typeof target === \"number\") return true;\n if (typeof target !== \"string\" && !(target instanceof URL)) return false;\n const path = normalize(String(target));\n return (\n path.startsWith(\"node:\") ||\n path.includes(\"/node_modules/\") ||\n Boolean(options.allow?.(path))\n );\n };\n\n const wrap = (\n holder: Record<string, unknown>,\n name: string,\n async = false,\n ): void => {\n const original = holder[name];\n if (typeof original !== \"function\") return;\n holder[name] = function guarded(this: unknown, ...args: unknown[]) {\n if (\n !allowed(args[0]) &&\n !(OPENERS.has(name) && opensForWriting(args[1]))\n ) {\n const message = `${name} read outside ctx.inputs: ${String(args[0])}`;\n violations.push(message);\n const error = new Error(message);\n if (async) return Promise.reject(error);\n throw error;\n }\n return Reflect.apply(original, this, args);\n };\n Object.assign(holder[name] as object, original);\n originals.push(() => {\n holder[name] = original;\n });\n };\n\n for (const name of GUARDED) wrap(fs as never, name);\n wrap(fs.realpathSync as never, \"native\");\n for (const name of GUARDED_PROMISES) wrap(fs.promises as never, name, true);\n syncBuiltinESMExports();\n\n return {\n violations,\n restore() {\n for (const undo of originals.splice(0)) undo();\n syncBuiltinESMExports();\n },\n };\n}\n","// The input side of a plugin's interactive `walk`: ask one question, or show\n// a menu, and report whether the person answered or wants to move around.\n// Plugins drive the walk; this only talks to the terminal.\n\nimport prompts from \"prompts\";\n\nexport type Nav = \"back\" | \"skip\" | \"menu\" | \"quit\";\n\n/** An answer, or a request to move: back a question, skip it, open the\n * menu, or stop (Ctrl-C / Esc). */\nexport type Reply = { value: string } | { nav: Nav };\n\nexport interface Choice {\n title: string;\n value: string;\n description?: string;\n}\n\nexport interface Question {\n /** A line above the prompt, e.g. \"Business Info · 3 left\". */\n section?: string;\n message: string;\n /** `secret` hides the typing; `search` filters a long list as you type. */\n kind: \"text\" | \"secret\" | \"select\" | \"search\";\n choices?: Choice[];\n /** The saved answer, already masked if sensitive. Enter keeps it. */\n current?: string;\n hint?: string;\n canGoBack: boolean;\n}\n\nexport interface MenuItem<T extends string> {\n title: string;\n value: T;\n description?: string;\n disabled?: boolean;\n}\n\nexport interface Prompter {\n ask(question: Question): Promise<Reply>;\n /** Null when the person cancels the menu. */\n menu<T extends string>(\n message: string,\n items: ReadonlyArray<MenuItem<T>>,\n ): Promise<T | null>;\n note(text: string): void;\n}\n\nexport const NAV_HELP =\n \"Type < to go back, > to skip, ? for the menu. Every answer is saved as you go; Ctrl-C stops.\";\n\nconst TYPED_NAV: Record<string, Nav> = {\n \"<\": \"back\",\n \">\": \"skip\",\n \"?\": \"menu\",\n};\n\n/** A typed `<`, `>` or `?` moves instead of answering. */\nexport function parseTyped(raw: string): Reply {\n const nav = TYPED_NAV[raw.trim()];\n return nav ? { nav } : { value: raw };\n}\n\n// Navigation entries appended to a pick list. The NUL prefix keeps them\n// from colliding with a real option value.\nconst NAV_PREFIX = \"\\u0000\";\n\nfunction navChoices(canGoBack: boolean): Choice[] {\n return [\n ...(canGoBack ? [{ title: \"← Back\", value: `${NAV_PREFIX}back` }] : []),\n { title: \"Skip →\", value: `${NAV_PREFIX}skip` },\n { title: \"Menu…\", value: `${NAV_PREFIX}menu` },\n ];\n}\n\nfunction fromChoice(value: string): Reply {\n return value.startsWith(NAV_PREFIX)\n ? { nav: value.slice(NAV_PREFIX.length) as Nav }\n : { value };\n}\n\n/** A prompter on the terminal, built on `prompts`. */\nexport function terminalPrompter(): Prompter {\n let cancelled = false;\n const onCancel = () => {\n cancelled = true;\n return false;\n };\n\n return {\n async ask(q) {\n cancelled = false;\n if (q.section) process.stdout.write(`\\n${q.section}\\n`);\n const message = q.current\n ? `${q.message} (saved: ${q.current})`\n : q.message;\n\n if (q.kind === \"select\" || q.kind === \"search\") {\n const choices = [...(q.choices ?? []), ...navChoices(q.canGoBack)];\n const initial = Math.max(\n 0,\n choices.findIndex(\n (c) => c.title === q.current || c.value === q.current,\n ),\n );\n const { answer } = (await prompts(\n {\n type: q.kind === \"search\" ? \"autocomplete\" : \"select\",\n name: \"answer\",\n message,\n choices,\n initial,\n hint: q.hint,\n ...(q.kind === \"search\"\n ? {\n suggest: async (input: string, all: Choice[]) => {\n const needle = input.trim().toLowerCase();\n return all.filter(\n (c) =>\n c.value.startsWith(NAV_PREFIX) ||\n c.title.toLowerCase().includes(needle) ||\n c.value.toLowerCase().includes(needle),\n );\n },\n }\n : {}),\n } as prompts.PromptObject<\"answer\">,\n { onCancel },\n )) as { answer?: string };\n if (cancelled || answer === undefined) return { nav: \"quit\" };\n return fromChoice(answer);\n }\n\n const { answer } = (await prompts(\n {\n type: q.kind === \"secret\" ? \"password\" : \"text\",\n name: \"answer\",\n message: q.hint ? `${message} — ${q.hint}` : message,\n // A secret's saved value is masked, so it can't pre-fill; Enter on\n // an empty secret keeps what's saved.\n ...(q.kind === \"text\" && q.current ? { initial: q.current } : {}),\n },\n { onCancel },\n )) as { answer?: string };\n if (cancelled || answer === undefined) return { nav: \"quit\" };\n // Enter on a secret that's already saved keeps it: moving on without\n // an answer is a skip, so a walk never saves an empty value over it.\n if (q.kind === \"secret\" && q.current && answer === \"\")\n return { nav: \"skip\" };\n return parseTyped(answer);\n },\n\n async menu(message, items) {\n cancelled = false;\n const { choice } = (await prompts(\n {\n type: \"select\",\n name: \"choice\",\n message,\n choices: items.map((item) => ({\n title: item.title,\n value: item.value,\n description: item.description,\n disabled: item.disabled,\n })),\n },\n { onCancel },\n )) as { choice?: string };\n if (cancelled || choice === undefined) return null;\n return choice as (typeof items)[number][\"value\"];\n },\n\n note(text) {\n process.stdout.write(`${text}\\n`);\n },\n };\n}\n\n/** A walk needs a person at a terminal; scripts and agents use the\n * non-interactive commands it names. */\nexport function assertInteractive(\n alternative: string,\n isTTY: boolean = Boolean(process.stdin.isTTY && process.stdout.isTTY),\n): void {\n if (!isTTY) {\n throw new Error(\n `walk asks questions in a terminal. In a script, use ${alternative}.`,\n );\n }\n}\n","/**\n * The canonical GitSync commit-subject format, shared by every kind of\n * Fluid-managed repository — Mist apps, Themes, Portals and Widgets.\n *\n * Each kind used to invent its own wording, so `git log` across a\n * company's repos read as four unrelated systems and only some commits\n * said who made them. One shape now covers all of them:\n *\n * <Actor Name>: <Action> · <timestamp> (<public_id>)\n * Mike Tingey: Publish portal Acme Portal · 2026-08-06 12:00:00 (0182d21e-…)\n *\n * Name and action come first so `git log --oneline` stays scannable in a\n * narrow terminal; the long UUID sits at the end where truncation eats\n * it instead of the prose. The timestamp is redundant with git's own\n * committer date but is kept inline because it survives cherry-picks,\n * rebases and the hosting providers' deployment feeds, which surface the\n * subject and nothing else.\n *\n * System-authored commits (auto-provisioning, sweeper retries, webhook\n * fan-out, an unreachable `/api/me`) use the literal actor name `Fluid`\n * and carry no UUID, so they parse with the same grammar rather than\n * needing a second one:\n *\n * Fluid: Publish theme Aurora · 2026-08-06 12:00:00\n *\n * The Ruby side mirrors this in `GitSync::CommitSubject`\n * (fluid/app/models/git_sync/commit_subject.rb) and Mist Desktop mirrors\n * the parser in `apps/mist-desktop/src/shared/git-commit-subject.ts`.\n * Change all three together.\n */\n\n/** The person a commit is attributed to. */\nexport interface GitSyncActor {\n /** Display name: full_name → first+last → email → `user-<id>`. */\n readonly name: string;\n /** The user's stable public UUID, rendered as a ` (uuid)` suffix. */\n readonly publicId: string | null;\n}\n\n/** Actor name used when no human triggered the commit. */\nexport const SYSTEM_ACTOR_NAME = \"Fluid\";\n\n/** Parseable fallback when a caller supplies only grammar delimiters or\n * whitespace as the action (for example, `-m \"·\"`). */\nconst DEFAULT_ACTION = \"Sync changes\";\n\n/**\n * A subject broken back into its parts. `publicId` is null for\n * system-authored commits and for actors whose public id was unknown at\n * commit time.\n */\nexport interface ParsedGitSyncSubject {\n readonly actorName: string;\n readonly action: string;\n /** The inline `YYYY-MM-DD HH:MM:SS` stamp, in UTC. */\n readonly timestamp: string;\n readonly publicId: string | null;\n}\n\n/**\n * Matches the canonical shape. The actor group is greedy so a display\n * name containing `\": \"` (e.g. `Tingey: Mike`) splits at the LAST colon\n * before the ` · ` separator — safe because {@link subjectFragment}\n * strips both delimiters out of every value we interpolate into an\n * action.\n */\nconst SUBJECT_RE =\n /^(.+): (.+?) · (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})(?: \\(([^()]+)\\))?$/;\n\n/** `2026-08-06T12:00:00.000Z` → `2026-08-06 12:00:00`. */\nexport function formatCommitTimestamp(when: Date): string {\n return when.toISOString().slice(0, 19).replace(\"T\", \" \");\n}\n\n/**\n * Neutralize the two sequences the grammar splits on, so no value can\n * shift the actor / action / uuid boundaries:\n *\n * `\": \"` separates the actor from the action\n * `\"·\"` separates the action from the timestamp\n *\n * Only those exact sequences are replaced, not every colon — `12:30`\n * and `fix:handle-nulls` survive intact, because neither can be\n * mistaken for a field boundary. A trailing colon is likewise safe: the\n * parser backtracks past it.\n *\n * {@link gitSyncCommitSubject} applies this to every action, so callers\n * don't have to remember. It's idempotent, so calling it yourself on an\n * interpolated resource name (as the CLIs do) costs nothing.\n */\nexport function subjectFragment(value: string): string {\n return value\n .replace(/:\\s/g, \" \")\n .replace(/·/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Build a canonical commit subject.\n *\n * @param action - What happened, e.g. `Publish theme Aurora`. Run any\n * interpolated resource name through {@link subjectFragment} first.\n * @param actor - The signed-in user, or null for system-authored\n * commits (which are attributed to `Fluid`).\n * @param when - Injectable clock, so callers and tests get a stable\n * stamp.\n */\nexport function gitSyncCommitSubject(\n action: string,\n actor: GitSyncActor | null,\n when: Date = new Date(),\n): string {\n // Sanitized HERE rather than at each call site. The action is the one\n // field a user fully controls (`-m`), and a `\": \"` in it would be read\n // back as part of the actor — `-m \"Publish: Acme\"` attributing the\n // commit to \"Mike Tingey: Publish\". Doing it at the choke point means\n // no current or future caller can reintroduce that.\n //\n // The actor name is deliberately NOT sanitized: a real name may\n // contain `\": \"` (`Tingey: Mike`), and the greedy actor group parses\n // that correctly precisely because the action can no longer contain\n // the delimiter.\n const safeAction = subjectFragment(action) || DEFAULT_ACTION;\n const stamp = formatCommitTimestamp(when);\n if (!actor) return `${SYSTEM_ACTOR_NAME}: ${safeAction} · ${stamp}`;\n const idSuffix = actor.publicId ? ` (${actor.publicId})` : \"\";\n return `${actor.name}: ${safeAction} · ${stamp}${idSuffix}`;\n}\n\n/**\n * Split a canonical subject back into its parts, or null when the\n * subject predates the format (legacy CLI wording such as `push @ <iso>`\n * or a hand-written commit). Callers fall back to rendering the raw\n * subject.\n */\nexport function parseGitSyncSubject(\n subject: string | null | undefined,\n): ParsedGitSyncSubject | null {\n if (!subject) return null;\n const match = subject.trim().match(SUBJECT_RE);\n if (!match) return null;\n const [, actorName, action, timestamp, publicId] = match;\n // The regex guarantees these groups, but noUncheckedIndexedAccess\n // types them as possibly-undefined.\n if (!actorName || !action || !timestamp) return null;\n return {\n actorName: actorName.trim(),\n action: action.trim(),\n timestamp,\n publicId: publicId?.trim() || null,\n };\n}\n\n/**\n * The person a canonical subject is attributed to, or null when the\n * subject isn't canonical or was system-authored. Use this for \"who\n * shipped this\" UI — a `Fluid:` commit has no human to name.\n */\nexport function gitSyncSubjectAuthor(\n subject: string | null | undefined,\n): string | null {\n const parsed = parseGitSyncSubject(subject);\n if (!parsed || parsed.actorName === SYSTEM_ACTOR_NAME) return null;\n return parsed.actorName;\n}\n\n/** The `/api/me` fields the actor is derived from. */\ninterface MeUser {\n readonly id?: unknown;\n readonly public_id?: unknown;\n readonly full_name?: unknown;\n readonly first_name?: unknown;\n readonly last_name?: unknown;\n readonly email?: unknown;\n}\n\n/** Some `/api/me` deployments nest the user, others return it flat. */\ninterface MeResponse extends MeUser {\n readonly user?: MeUser;\n}\n\nfunction str(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim().length > 0) return value.trim();\n return null;\n}\n\n/**\n * Resolve an `/api/me` body to a commit actor, with the name fallback\n * chain `full_name → first+last → email → user-<id>`. Returns null when\n * the body carries no usable identity at all, which callers treat the\n * same as an unreachable `/api/me`: a system-authored commit.\n */\nexport function gitSyncActorFromMe(raw: MeResponse): GitSyncActor | null {\n const user = raw.user ?? raw;\n const composed = [str(user.first_name), str(user.last_name)]\n .filter((part): part is string => part !== null)\n .join(\" \")\n .trim();\n const name =\n str(user.full_name) ??\n (composed.length > 0 ? composed : null) ??\n str(user.email) ??\n (typeof user.id === \"number\" && Number.isFinite(user.id)\n ? `user-${user.id}`\n : null);\n if (!name) return null;\n const publicId =\n str(user.public_id) ??\n (typeof user.id === \"number\" && Number.isFinite(user.id)\n ? String(user.id)\n : null);\n return { name, publicId };\n}\n","/**\n * Turn a set of changed paths into the `<Action>` half of a canonical\n * GitSync commit subject (see commit-subject.ts).\n *\n * Publishes used to be stamped with a constant — \"Publish from Mist\n * Desktop\", \"Publish theme Aurora\" — so `git log` told you a publish\n * happened but never what it carried. Every entry in the history looked\n * identical, which made the log useless for finding the commit that\n * introduced something.\n *\n * This derives a short, honest phrase from the staged diff:\n *\n * Update templates/product.liquid\n * Update 3 files in templates\n * Add 2 files, update 3, delete 1\n *\n * It is deliberately mechanical. A caller that knows the INTENT behind a\n * change (Mist Desktop, or a human passing `-m`) should pass that\n * instead — an intent describes why, and no diff can recover that. This\n * is the fallback for when nobody supplied one.\n *\n * Pure: callers collect the diff (each CLI has its own git layer) and\n * hand the entries here, so the wording can't drift between kinds.\n */\n\n/** Git's porcelain status letters, narrowed to what we act on. */\nexport type ChangeStatus = \"added\" | \"modified\" | \"deleted\" | \"renamed\";\n\n/**\n * What an auto-commit helper accepts as its subject: either a literal\n * (the caller already knows the intent — a `-m` message), or a resolver\n * handed the staged changes so it can describe them.\n *\n * The resolver form exists because staging is decided INSIDE the commit\n * helpers — they `git add -A` and then unstage private paths — so only\n * they know the final file set. A summary built by the caller beforehand\n * would describe a diff the commit doesn't carry.\n *\n * It may return a promise so a caller can start slow work (an `/api/me`\n * identity lookup, say) BEFORE the git reconcile and await it here, at\n * the last possible moment — overlapping it with the fetch/merge instead\n * of paying for it serially up front. Anything awaited here is on the\n * critical path of the commit, so it must be bounded and best-effort:\n * a publish must never hang waiting to describe itself.\n */\nexport type CommitMessage =\n | string\n | ((changes: readonly ChangeEntry[]) => string | Promise<string>);\n\nexport interface ChangeEntry {\n readonly status: ChangeStatus;\n /** Repo-relative path, forward-slashed. */\n readonly path: string;\n}\n\n/** Map a `git diff --name-status` letter to a status. `R`/`C` carry a\n * similarity score (`R100`), so only the leading letter is read.\n * Unknown letters (`U` unmerged, `T` typechange) count as modified —\n * the file did change, and mislabeling the verb is better than\n * dropping it from the count. */\nexport function changeStatusFromCode(code: string): ChangeStatus {\n switch (code.trim().charAt(0).toUpperCase()) {\n case \"A\":\n return \"added\";\n case \"D\":\n return \"deleted\";\n case \"R\":\n return \"renamed\";\n default:\n return \"modified\";\n }\n}\n\n/**\n * Parse `git diff --cached --name-status -z` output.\n *\n * NUL-delimited on purpose: paths containing spaces, quotes or newlines\n * are legal in git and common in themes (`assets/hero image.png`), and\n * the newline-delimited form quotes and escapes them, which would corrupt\n * both the count and the path. With `-z`, records are\n * `status\\0path\\0` — except renames and copies, which are\n * `status\\0from\\0to\\0` and consume an extra field.\n */\nexport function parseNameStatusZ(stdout: string): ChangeEntry[] {\n const fields = stdout.split(\"\\0\").filter((f) => f.length > 0);\n const entries: ChangeEntry[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i];\n if (code === undefined) break;\n const status = changeStatusFromCode(code);\n if (status === \"renamed\") {\n // status, from, to — the destination is the path we report.\n const to = fields[i + 2];\n if (to === undefined) break;\n entries.push({ status, path: to });\n i += 3;\n continue;\n }\n const path = fields[i + 1];\n if (path === undefined) break;\n entries.push({ status, path });\n i += 2;\n }\n return entries;\n}\n\n/** Top-level directory of a path, or null for a repo-root file. */\nfunction topLevelDir(path: string): string | null {\n const slash = path.indexOf(\"/\");\n return slash > 0 ? path.slice(0, slash) : null;\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? \"\" : \"s\"}`;\n}\n\nconst VERB_FOR: Record<ChangeStatus, string> = {\n added: \"Add\",\n modified: \"Update\",\n deleted: \"Delete\",\n renamed: \"Rename\",\n};\n\n/**\n * Build the action phrase for a set of changes, or null when there is\n * nothing to describe — the caller then falls back to its own constant\n * (`Publish theme Aurora`), so an empty diff never produces a subject\n * like \"Update 0 files\".\n *\n * @param entries - The staged changes.\n * @param maxLength - Clip the result to keep `git log --oneline`\n * readable. The subject also carries a name, timestamp and UUID, so\n * the action gets a modest budget.\n */\nexport function summarizeChanges(\n entries: readonly ChangeEntry[],\n maxLength = 72,\n): string | null {\n if (entries.length === 0) return null;\n\n // A single change is the most useful case and the most common one:\n // name the actual file rather than counting to one.\n if (entries.length === 1) {\n const only = entries[0]!;\n return clip(`${VERB_FOR[only.status]} ${only.path}`, maxLength);\n }\n\n // Group by verb, ordered so the dominant kind of change leads.\n const byStatus = new Map<ChangeStatus, number>();\n for (const entry of entries) {\n byStatus.set(entry.status, (byStatus.get(entry.status) ?? 0) + 1);\n }\n\n // All one verb → \"Update 3 files\", plus a location when they share one.\n if (byStatus.size === 1) {\n const status = entries[0]!.status;\n const dirs = new Set(entries.map((e) => topLevelDir(e.path)));\n const only = dirs.size === 1 ? [...dirs][0] : null;\n const phrase = `${VERB_FOR[status]} ${plural(entries.length, \"file\")}`;\n return clip(only ? `${phrase} in ${only}` : phrase, maxLength);\n }\n\n // Mixed → lead with the largest group, then the rest as bare counts:\n // \"Update 3 files, add 2, delete 1\".\n const ordered = [...byStatus.entries()].sort(\n ([aStatus, aCount], [bStatus, bCount]) =>\n bCount - aCount || VERB_FOR[aStatus].localeCompare(VERB_FOR[bStatus]),\n );\n const [leadStatus, leadCount] = ordered[0]!;\n const rest = ordered\n .slice(1)\n .map(([status, count]) => `${VERB_FOR[status].toLowerCase()} ${count}`);\n const head = `${VERB_FOR[leadStatus]} ${plural(leadCount, \"file\")}`;\n return clip([head, ...rest].join(\", \"), maxLength);\n}\n\nfunction clip(text: string, maxLength: number): string {\n return text.length > maxLength\n ? `${text.slice(0, maxLength - 1).trimEnd()}…`\n : text;\n}\n","/**\n * Cache the signed-in user's commit identity on the active profile.\n *\n * Commit subjects are stamped `<name>: <action> · <ts> (<public_id>)`,\n * which needs the user's display name and public id. `/api/me` is the\n * only source, and it can be slow — so paying for it on EVERY push, to\n * learn a name that changes approximately never, is the wrong trade.\n *\n * The identity is stored per profile (profiles are per token + company,\n * so the cache can't leak across accounts) and refreshed only when\n * missing or stale. Login and company-switch write a fresh profile,\n * which drops the cached identity with it.\n *\n * Every failure mode here is non-fatal: an unreadable or unwritable\n * config just means we fall back to the network, and a failed network\n * lookup means a `Fluid:` system commit. A publish must never fail\n * because we couldn't work out whose name to put on it.\n */\n\nimport { readConfig, updateConfig } from \"../config/config.js\";\nimport type { GitSyncActor } from \"./commit-subject.js\";\n\n/**\n * How long a cached identity is trusted. Long, because a display name\n * changing is rare — but not forever, so a rename does eventually reach\n * the commit log without the user having to re-login.\n */\nexport const ACTOR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days\n\n/** Cached identity as persisted on a profile. */\nexport interface CachedGitSyncActor {\n readonly name: string;\n readonly publicId: string | null;\n /** ISO-8601. */\n readonly cachedAt: string;\n}\n\nfunction isFresh(cached: CachedGitSyncActor, now: number): boolean {\n const at = Date.parse(cached.cachedAt);\n // An unparseable timestamp is treated as stale rather than trusted\n // forever — a corrupt field shouldn't pin a wrong name permanently.\n if (Number.isNaN(at)) return false;\n return now - at < ACTOR_CACHE_TTL_MS;\n}\n\n/** The cached identity for the active profile, or null. */\nexport function readCachedActor(now = Date.now()): GitSyncActor | null {\n try {\n const config = readConfig();\n const profileName = config.activeProfile;\n if (!profileName) return null;\n const cached = config.profiles[profileName]?.gitSyncActor;\n if (!cached || !cached.name || !isFresh(cached, now)) return null;\n return { name: cached.name, publicId: cached.publicId ?? null };\n } catch {\n return null;\n }\n}\n\n/** Persist an identity against the active profile. Best-effort. */\nexport function writeCachedActor(actor: GitSyncActor, now = new Date()): void {\n try {\n updateConfig((config) => {\n const profileName = config.activeProfile;\n if (!profileName) return config;\n const profile = config.profiles[profileName];\n if (!profile) return config;\n return {\n ...config,\n profiles: {\n ...config.profiles,\n [profileName]: {\n ...profile,\n gitSyncActor: {\n name: actor.name,\n publicId: actor.publicId,\n cachedAt: now.toISOString(),\n },\n },\n },\n };\n });\n } catch {\n // A read-only or malformed config just means we look it up again\n // next time — never a reason to fail a publish.\n }\n}\n\n/**\n * The commit identity, from cache when possible.\n *\n * @param fetchActor - Network lookup, used only on a cache miss. Each\n * CLI has its own client, so the caller supplies it. It must already\n * be bounded — this function adds no timeout of its own.\n *\n * Returns null when there's no cache and the lookup fails or yields no\n * usable identity; callers then write a `Fluid:` system commit.\n */\nexport async function resolveGitSyncActor(\n fetchActor: () => Promise<GitSyncActor | null>,\n): Promise<GitSyncActor | null> {\n const cached = readCachedActor();\n if (cached) return cached;\n\n const fetched = await fetchActor().catch(() => null);\n if (fetched) writeCachedActor(fetched);\n return fetched;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBAAwB;AACtC,SACE,QAAQ,IAAI,wBAAwB,4BACpC,QAAQ,OAAO,GAAG;;;AA6BtB,IAAa,iBAAb,cAAoC,MAAM;CACxC,YACE,SACA,QACA,QACA;AACA,QAAM,QAAQ;AAHL,OAAA,SAAA;AACA,OAAA,SAAA;AAGT,OAAK,OAAO;;;;;;;CAQd,IAAI,UAAmB;AACrB,MAAI,KAAK,WAAW,OAAO,KAAK,WAAW,IAAK,QAAO;AACvD,SAA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AG;MACH,cAAc;OACZ,MAAM,MAAM;OACZ,UAAU,MAAM;OAChB,UAAU,IAAI,aAAa;OAC5B;MACF;KACF;IACF;IACD;SACI;;;;;;;;;;;;AAgBV,eAAsB,oBACpB,YAC8B;CAC9B,MAAM,SAAS,iBAAiB;AAChC,KAAI,OAAQ,QAAO;CAEnB,MAAM,UAAU,MAAM,YAAY,CAAC,YAAY,KAAK;AACpD,KAAI,QAAS,kBAAiB,QAAQ;AACtC,QAAO"}
@@ -2727,6 +2727,8 @@ function withConfigLock(fn) {
2727
2727
  const IDENTITY_CLIENT_ID = "fluid-cli";
2728
2728
  /** The credential store service name the CLI files its sessions under. */
2729
2729
  const KEYRING_SERVICE = "fluid-cli";
2730
+ /** Fluid's own company at the identity service, in stage and production. */
2731
+ const IDENTITY_ROOT_COMPANY_ID = "017b4195-f90f-7f66-962b-e5a3e1c9748e";
2730
2732
  const PRODUCTION_IDENTITY_URL = "https://identity.fluid.app";
2731
2733
  const STAGING_IDENTITY_URL = "https://identity.stage.fluid.app";
2732
2734
  const STAGING_API_HOSTS = [/\.stage\.fluid\.app$/];
@@ -3395,11 +3397,13 @@ async function signInWithBrowser(options) {
3395
3397
  await server.close();
3396
3398
  }
3397
3399
  let facts;
3400
+ let recovered = false;
3398
3401
  try {
3399
3402
  facts = await session.completeSignIn(callbackUrl);
3400
3403
  } catch (error) {
3401
3404
  if (!(error instanceof SessionError) || error.code !== "temporarily_unavailable") throw error;
3402
3405
  facts = await finishStoredSignIn(session, error);
3406
+ recovered = true;
3403
3407
  }
3404
3408
  const auth = {
3405
3409
  mode: "identity",
@@ -3413,7 +3417,9 @@ async function signInWithBrowser(options) {
3413
3417
  return {
3414
3418
  auth,
3415
3419
  facts,
3416
- accessToken: await session.getAccessToken()
3420
+ accessToken: await session.getAccessToken(),
3421
+ pickedOrg: session.pickedOrg(),
3422
+ recovered
3417
3423
  };
3418
3424
  }
3419
3425
  /** A sentence for the user about an identity failure. */
@@ -3487,6 +3493,6 @@ async function endUnusedSessions(before, after) {
3487
3493
  return problems;
3488
3494
  }
3489
3495
  //#endregion
3490
- export { isClientProfile as A, readStoredConfig as C, getConfigDir as D, isStrictConfig as E, getConfigFilePath as O, readConfig as S, writeConfig as T, primeClientProfile as _, peekIdentityToken as a, ApiError as b, sessionFacts as c, OrphanedClientSecretError as d, ProfileExistsError as f, peekClientToken as g, invalidateClientToken as h, isRoleNotGrantedError as i, isIdentityProfile as j, createDefaultConfig as k, signInWithBrowser as l, deleteClientSecret as m, describeIdentityError as n, primeIdentityProfile as o, clientAccessToken as p, identityToken as r, profileAccessToken as s, endUnusedSessions as t, signOutIdentity as u, saveClientProfile as v, updateConfig as w, createFetchClient as x, resolveIdentityUrl as y };
3496
+ export { createDefaultConfig as A, readConfig as C, isStrictConfig as D, writeConfig as E, isIdentityProfile as M, getConfigDir as O, createFetchClient as S, updateConfig as T, primeClientProfile as _, peekIdentityToken as a, resolveIdentityUrl as b, sessionFacts as c, OrphanedClientSecretError as d, ProfileExistsError as f, peekClientToken as g, invalidateClientToken as h, isRoleNotGrantedError as i, isClientProfile as j, getConfigFilePath as k, signInWithBrowser as l, deleteClientSecret as m, describeIdentityError as n, primeIdentityProfile as o, clientAccessToken as p, identityToken as r, profileAccessToken as s, endUnusedSessions as t, signOutIdentity as u, saveClientProfile as v, readStoredConfig as w, ApiError as x, IDENTITY_ROOT_COMPANY_ID as y };
3491
3497
 
3492
- //# sourceMappingURL=profiles-Sitg25-8.mjs.map
3498
+ //# sourceMappingURL=profiles-CbMJHi-u.mjs.map