@diafunc/cli 0.29.1 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/commands/auth/login.ts","../src/config/store.ts","../src/config/lock.ts","../src/client/http.ts","../src/client/errors.ts","../src/client/sign-in.ts","../src/client/services/admin.ts","../src/util/errors.ts","../src/output/messages.ts","../src/output/json.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/output/human.ts","../src/output/columns.ts","../src/output/terminal.ts","../src/output/values.ts","../src/output/table.ts","../src/output/formatter.ts","../src/commands/auth/token.ts","../src/client/services/analysis.ts","../src/client/services/storage.ts","../src/client/services/evaluation.ts","../src/client/services/scheduler.ts","../src/client/services/language.ts","../src/client/services/index-search.ts","../src/client/api.ts","../src/commands/auth/index.ts","../src/commands/config/index.ts","../src/commands/project/index.ts","../src/util/hidden-aliases.ts","../src/util/references.ts","../src/commands/bundle-helpers.ts","../src/output/progress.ts","../src/util/function-language.ts","../src/util/project-names.ts","../src/util/entity-attributes.ts","../src/util/project-entity.ts","../src/commands/entity/tags.ts","../src/util/tags.ts","../src/util/confirm.ts","../src/commands/project/transfer.ts","../src/commands/team/index.ts","../src/commands/entity/index.ts","../src/commands/link/index.ts","../src/commands/event/index.ts","../src/commands/branch/index.ts","../src/commands/table/index.ts","../src/util/table-window.ts","../src/util/table-entity.ts","../src/commands/notebook/index.ts","../src/commands/function/index.ts","../src/util/time-uuid.ts","../src/util/function-content.ts","../src/commands/analyze/intent.ts","../src/commands/analyze/columns.ts","../src/commands/analyze/report.ts","../src/prompting/resolvers.ts","../src/commands/trigger/index.ts","../src/commands/schedule/index.ts","../src/commands/chat/index.ts","../src/output/markdown.ts","../src/commands/search/index.ts","../src/commands/admin/index.ts","../src/commands/admin/curated-tags.ts","../src/util/id-list.ts","../src/commands/admin/projects.ts","../src/commands/status/summary.ts","../src/client/services/status.ts","../src/commands/status/component.ts","../src/commands/status/incidents.ts","../src/commands/status/index.ts","../src/commands/analyze/index.ts","../src/commands/analyze/watch-view.ts","../src/client/types/analysis.ts","../src/commands/analyze/copy.ts","../src/commands/analyze/wizard.ts","../src/prompting/prompter.ts","../src/commands/analyze/data-import.ts","../src/commands/analyze/details.ts","../src/commands/analyze/sources.ts","../src/commands/public/index.ts","../src/commands/license/index.ts","../src/commands/data-sources/index.ts","../src/commands/table-exporters/index.ts","../src/commands/skeleton/index.ts","../src/commands/completion/index.ts","../src/commands/whoami/index.ts","../src/commands/utilization/index.ts","../src/commands/entity-branch/index.ts","../src/commands/subscription/index.ts","../src/commands/invoice/index.ts","../src/commands/shell/index.ts","../src/commands/update/index.ts","../src/util/install-method.ts","../src/commands/uninstall/index.ts","../src/prompting/command.ts","../src/prompting/fill.ts","../src/prompting/pickers.ts"],"sourcesContent":["import chalk from 'chalk';\nimport pkg from '../package.json' with { type: 'json' };\nimport { registerAuthCommands } from './commands/auth/index.js';\nimport { registerConfigCommands } from './commands/config/index.js';\nimport { registerProjectCommands } from './commands/project/index.js';\nimport { registerTeamCommands } from './commands/team/index.js';\nimport { registerEntityCommands } from './commands/entity/index.js';\nimport { registerLinkCommands } from './commands/link/index.js';\nimport { registerEventCommands } from './commands/event/index.js';\nimport { registerBranchCommands } from './commands/branch/index.js';\nimport { registerTableCommands } from './commands/table/index.js';\nimport { registerNotebookCommands } from './commands/notebook/index.js';\nimport { registerFunctionCommands } from './commands/function/index.js';\nimport { registerTriggerCommands } from './commands/trigger/index.js';\nimport { registerScheduleCommands } from './commands/schedule/index.js';\nimport { registerChatCommands } from './commands/chat/index.js';\nimport { registerSearchCommands } from './commands/search/index.js';\nimport { registerAdminCommands } from './commands/admin/index.js';\nimport { registerStatusCommands } from './commands/status/index.js';\nimport { registerAnalyzeCommand } from './commands/analyze/index.js';\nimport { registerPublicCommands } from './commands/public/index.js';\nimport { registerLicenseCommands } from './commands/license/index.js';\nimport { registerDataSourcesCommands } from './commands/data-sources/index.js';\nimport { registerTableExportersCommands } from './commands/table-exporters/index.js';\nimport { registerSkeletonCommands } from './commands/skeleton/index.js';\nimport { registerCompletionCommand } from './commands/completion/index.js';\nimport { registerWhoamiCommand } from './commands/whoami/index.js';\nimport { registerUtilizationCommand } from './commands/utilization/index.js';\nimport { registerEntityBranchCommands } from './commands/entity-branch/index.js';\nimport { registerSubscriptionCommand } from './commands/subscription/index.js';\nimport { registerInvoiceCommand } from './commands/invoice/index.js';\nimport { registerShellCommand } from './commands/shell/index.js';\nimport { registerUpdateCommand } from './commands/update/index.js';\nimport { registerUninstallCommand } from './commands/uninstall/index.js';\nimport { setDryRun, setVerbose } from './client/http.js';\nimport { DiafuncCommand, type PromptEnvironment } from './prompting/command.js';\nimport { fillPendingInputs } from './prompting/fill.js';\nimport { HIDDEN_ALIAS_HELP, wireHiddenOptionAliases } from './util/hidden-aliases.js';\n\n/** Shown under `diafunc --help`: the shortest path from an empty terminal to a finished analysis. */\nconst HELP_EPILOGUE = `\nGetting started:\n $ diafunc auth login sign in\n $ diafunc analyze data.csv --targets price run an analysis and follow it\n $ diafunc analyze watch follow the latest run again\n $ diafunc analyze open open the finished notebook\n\nEveryday:\n $ diafunc project list what you have\n $ diafunc search \"housing\" find it across every project\n $ diafunc chat ask the assistant\n $ diafunc status summary is the platform healthy\n\nOutput:\n Add --output json for scripting, or pipe any command to get tab-separated fields.\n Add --verbose to see the requests, --dry-run to preview a mutation.\n\nMissing input:\n In a terminal, leave out a required argument and the command asks for it, offering\n your projects, tables, teams and the like to choose from. --no-interactive never asks.\n\nDocs: https://diafunc.com/documentation\n`;\n\n/**\n * Builds the command tree. `environment` replaces the terminal, the interactive decision and the API\n * client for the missing-input prompts, so a test can drive them without a TTY or the network.\n */\nexport function createProgram(environment: PromptEnvironment = {}): DiafuncCommand {\n const program = new DiafuncCommand();\n program.promptEnvironment = environment;\n\n program\n .name('diafunc')\n .description('Diafunc CLI: the command-line interface for the Diafunc platform')\n .version(pkg.version)\n .option('-p, --profile <name>', 'Profile to use')\n // No default: an unset flag must fall through to `defaults.output` from the config file.\n .option('-o, --output <format>', 'Output format: human, json, table (default: human)')\n // The only declarations of --project and --branch. A subcommand that declared them again never\n // received them, because the program claims its own flags wherever they appear; commands read\n // them through optsWithGlobals(), and every subcommand's help lists them under Global Options.\n .option('--project <id>', 'Project to work in (overrides defaults.project)')\n .option('--branch <name>', 'Project branch (overrides defaults.branch)')\n .option('--dry-run', 'Preview mutating operations without executing them')\n .option('--verbose', 'Echo every HTTP request to stderr')\n .option('--no-color', 'Disable colored output')\n .option('--no-interactive', 'Never prompt: a missing required input fails as it would in a script')\n .showSuggestionAfterError()\n .showHelpAfterError(`(run 'diafunc --help' to see the available commands)`)\n // Set before any subcommand is registered: commander copies help settings to a subcommand when\n // it is created, so a later call would reach none of them.\n // Hidden aliases keep the old British spellings working without showing them anywhere.\n .configureHelp({ showGlobalOptions: true, ...HIDDEN_ALIAS_HELP })\n .configureOutput({\n // Commander writes usage errors to stdout by default, which puts a complaint in the middle\n // of whatever a caller was capturing.\n writeErr: (str) => process.stderr.write(str),\n })\n .hook('preAction', (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (opts.dryRun) setDryRun(true);\n if (opts.verbose) setVerbose(true);\n // Commander maps `--no-color` to `color: false`. chalk fixes its level at import time, so\n // setting an environment variable here would be too late; the level is assigned directly.\n if (opts.color === false) chalk.level = 0;\n })\n // After the settings above, so a prompt already knows whether to colour its output.\n .hook('preAction', (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));\n\n program.addHelpText('after', HELP_EPILOGUE);\n\n registerAuthCommands(program);\n registerConfigCommands(program);\n registerProjectCommands(program);\n registerTeamCommands(program);\n registerEntityCommands(program);\n registerLinkCommands(program);\n registerEventCommands(program);\n registerBranchCommands(program);\n registerTableCommands(program);\n registerNotebookCommands(program);\n registerFunctionCommands(program);\n registerTriggerCommands(program);\n registerScheduleCommands(program);\n registerChatCommands(program);\n registerSearchCommands(program);\n registerAdminCommands(program);\n registerStatusCommands(program);\n registerAnalyzeCommand(program);\n registerPublicCommands(program);\n registerLicenseCommands(program);\n registerDataSourcesCommands(program);\n registerTableExportersCommands(program);\n registerSkeletonCommands(program);\n registerCompletionCommand(program);\n registerWhoamiCommand(program);\n registerUtilizationCommand(program);\n registerEntityBranchCommands(program);\n registerSubscriptionCommand(program);\n registerInvoiceCommand(program);\n registerShellCommand(program);\n registerUpdateCommand(program);\n registerUninstallCommand(program);\n wireHiddenOptionAliases(program);\n\n return program;\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { type Config, type Profile, loadConfig, updateStoredProfile } from '../../config/store.js';\nimport { createHttpClient } from '../../client/http.js';\nimport { createAdminService } from '../../client/services/admin.js';\nimport { handleError } from '../../util/errors.js';\nimport { failure, success } from '../../output/messages.js';\n\nconst DEVICE_CLIENT_ID = 'diafunc-cli';\nconst DEVICE_SCOPE = 'openid profile email user';\nconst ACCESS_TOKEN_LIFETIME_SECONDS = 15 * 60;\n\ninterface DeviceAuthorizationResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete: string;\n expires_in: number;\n interval: number;\n}\n\ninterface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token?: string;\n scope?: string;\n}\n\ninterface TokenErrorResponse {\n error: string;\n error_description?: string;\n}\n\nfunction deriveAuthUrl(endpoint: string): string {\n const trimmed = endpoint.replace(/\\/+$/, '');\n if (trimmed.includes('://auth.')) {\n return trimmed;\n }\n const url = new URL(trimmed);\n url.hostname = `auth.${url.hostname}`;\n url.pathname = '';\n return url.toString().replace(/\\/+$/, '');\n}\n\nexport function registerLoginCommand(parent: Command): void {\n parent\n .command('login')\n .description('Authenticate with the Diafunc platform')\n .option('--token <token>', 'API token (dfat_...) for non-interactive token-based auth')\n .option('--endpoint <url>', 'Override the endpoint URL for this login')\n .action(async (options: { token?: string; endpoint?: string }) => {\n try {\n const config = loadConfig();\n const profile = config.profiles[config.currentProfile];\n if (!profile) {\n failure(`Profile \"${config.currentProfile}\" not found. Run 'diafunc config profile add' first.`);\n process.exit(1);\n }\n\n if (options.endpoint) {\n profile.endpoint = options.endpoint;\n }\n\n if (options.token) {\n profile.auth = { type: 'api-token', token: options.token };\n await storeSignIn(config.currentProfile, profile);\n const client = createHttpClient();\n const admin = createAdminService(client);\n const user = await admin.getMyUser();\n success('Signed in.');\n console.log(` User: ${chalk.bold(user.name)}`);\n console.log(` Email: ${user.email}`);\n console.log(` Profile: ${config.currentProfile}`);\n console.log(` Endpoint: ${profile.endpoint}`);\n return;\n }\n\n await deviceCodeLogin(config, profile);\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/**\n * Stores the new sign-in into the config as it is on disk now. The approval can take minutes, and\n * saving the config loaded before it would put back the tokens every other profile had then,\n * undoing any refresh a running command has stored in the meantime.\n */\nasync function storeSignIn(profileName: string, signedIn: Profile): Promise<void> {\n await updateStoredProfile(profileName, (stored) => {\n stored.endpoint = signedIn.endpoint;\n stored.auth = signedIn.auth;\n });\n}\n\nasync function deviceCodeLogin(config: Config, profile: Profile): Promise<void> {\n const authUrl = deriveAuthUrl(profile.endpoint);\n\n const deviceResponse = await fetch(`${authUrl}/device_authorization`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }).toString(),\n });\n if (!deviceResponse.ok) {\n const text = await deviceResponse.text();\n failure(`The sign-in could not start: ${text || deviceResponse.statusText}`);\n process.exit(1);\n }\n const device = await deviceResponse.json() as DeviceAuthorizationResponse;\n\n console.log('');\n console.log(`Open this URL in a browser: ${chalk.cyan(device.verification_uri)}`);\n console.log(`Enter the code: ${chalk.bold.yellow(device.user_code)}`);\n console.log('');\n console.log(chalk.dim('Or open the full URL to pre-fill:'));\n console.log(chalk.dim(` ${device.verification_uri_complete}`));\n console.log('');\n console.log(chalk.dim(`Waiting for approval (expires in ${Math.floor(device.expires_in / 60)} min)...`));\n\n const deadline = Date.now() + device.expires_in * 1000;\n let interval = Math.max(1, device.interval || 5);\n\n while (Date.now() < deadline) {\n await sleep(interval * 1000);\n const pollResponse = await fetch(`${authUrl}/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: device.device_code,\n client_id: DEVICE_CLIENT_ID,\n }).toString(),\n });\n\n if (pollResponse.ok) {\n const tokens = await pollResponse.json() as TokenResponse;\n profile.auth = {\n type: 'device-code',\n clientId: DEVICE_CLIENT_ID,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n accessTokenExpiry: Date.now() + (tokens.expires_in || ACCESS_TOKEN_LIFETIME_SECONDS) * 1000,\n };\n await storeSignIn(config.currentProfile, profile);\n\n const client = createHttpClient();\n const admin = createAdminService(client);\n const user = await admin.getMyUser();\n success('Signed in.');\n console.log(` User: ${chalk.bold(user.name)}`);\n console.log(` Email: ${user.email}`);\n console.log(` Profile: ${config.currentProfile}`);\n console.log(` Endpoint: ${profile.endpoint}`);\n return;\n }\n\n const errorBody = await pollResponse.json().catch(() => ({ error: 'unknown' })) as TokenErrorResponse;\n if (errorBody.error === 'authorization_pending') {\n continue;\n }\n if (errorBody.error === 'slow_down') {\n interval += 5;\n continue;\n }\n if (errorBody.error === 'expired_token') {\n failure('Code expired before approval. Run `diafunc auth login` again.');\n process.exit(1);\n }\n failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? ': ' + errorBody.error_description : ''}`);\n process.exit(1);\n }\n\n failure('Timed out waiting for approval.');\n process.exit(1);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport * as crypto from 'node:crypto';\nimport { withFileLock } from './lock.js';\n\nexport interface ApiTokenAuth {\n type: 'api-token';\n token: string;\n}\n\n/**\n * OIDC device-code authentication. The refresh token is opaque (issued by the OP's\n * /token endpoint after device-code approval) and rotates on every refresh.\n * `clientId` is pinned to the diafunc-cli OAuth client registered in oauth_clients.\n */\nexport interface DeviceCodeAuth {\n type: 'device-code';\n clientId: string;\n accessToken: string;\n refreshToken: string;\n accessTokenExpiry: number;\n}\n\nexport type AuthConfig = ApiTokenAuth | DeviceCodeAuth;\n\nexport interface Profile {\n endpoint: string;\n auth?: AuthConfig;\n}\n\nexport interface Defaults {\n project?: string;\n branch?: string;\n output?: 'human' | 'json' | 'table';\n}\n\nexport interface Config {\n currentProfile: string;\n profiles: Record<string, Profile>;\n defaults: Defaults;\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.diafunc');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nconst DEFAULT_CONFIG: Config = {\n currentProfile: 'default',\n profiles: {\n default: {\n endpoint: 'https://diafunc.com',\n },\n },\n defaults: {},\n};\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n }\n}\n\nexport function loadConfig(): Config {\n if (!fs.existsSync(CONFIG_FILE)) {\n return structuredClone(DEFAULT_CONFIG);\n }\n const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return JSON.parse(raw) as Config;\n}\n\nexport function saveConfig(config: Config): void {\n ensureConfigDir();\n // The temporary name is unique per writer: several processes may save at the same moment, and a\n // shared name would let one rename the other's half-written file into place.\n const tmp = `${CONFIG_FILE}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;\n try {\n fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\\n', {\n encoding: 'utf-8',\n mode: 0o600,\n });\n renameIntoPlace(tmp, CONFIG_FILE);\n } catch (error) {\n fs.rmSync(tmp, { force: true });\n throw error;\n }\n}\n\n/**\n * Renames over the target. Windows refuses the rename for as long as another process has the\n * target open for reading, which is a matter of milliseconds, so it is tried a few times there.\n */\nfunction renameIntoPlace(from: string, to: string): void {\n for (let attempt = 1; ; attempt++) {\n try {\n fs.renameSync(from, to);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code ?? '';\n if (attempt >= 10 || !['EPERM', 'EACCES', 'EBUSY'].includes(code)) throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20 * attempt);\n }\n }\n}\n\n/** Guards the read-change-write of the config file, which holds every profile. */\nconst STORE_LOCK_FILE = `${CONFIG_FILE}.lock`;\n\n/**\n * Changes one profile in the stored config and leaves everything else as it is on disk.\n *\n * A process that saved the config it loaded at start would write back the tokens of every profile\n * as they were then, undoing a refresh another process has stored since. Sign-in changes therefore\n * go through here: the file is read again under a lock, only the named profile is changed, and the\n * result is written atomically.\n */\nexport async function updateStoredProfile(profileName: string, change: (profile: Profile) => void): Promise<Config> {\n return withFileLock(STORE_LOCK_FILE, () => {\n const config = loadConfig();\n const profile = config.profiles[profileName];\n if (!profile) {\n throw new Error(`Profile \"${profileName}\" not found.`);\n }\n change(profile);\n saveConfig(config);\n return config;\n // Held for one read and one write. A short wait keeps a caller that is itself inside the\n // refresh lock well within that lock's stale bound.\n }, { waitMs: 5_000 });\n}\n\n/** The profile as it is on disk now, not as this process loaded it earlier. */\nexport function readStoredProfile(profileName: string): Profile | undefined {\n return loadConfig().profiles[profileName];\n}\n\n/**\n * A file beside the config that belongs to one profile, such as its refresh lock. Profile names\n * are free text, so the name is reduced to characters every file system accepts and a short digest\n * keeps two names that reduce alike apart.\n */\nexport function profileSidecarFile(profileName: string, suffix: string): string {\n const safe = profileName.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 40);\n const digest = crypto.createHash('sha256').update(profileName).digest('hex').slice(0, 8);\n return `${CONFIG_FILE}.${safe}-${digest}.${suffix}`;\n}\n\nexport function getActiveProfile(config: Config): Profile {\n const profile = config.profiles[config.currentProfile];\n if (!profile) {\n throw new Error(`Profile \"${config.currentProfile}\" not found. Run 'diafunc config profile add' to create one.`);\n }\n return profile;\n}\n\nexport function getActiveProfileName(config: Config): string {\n return config.currentProfile;\n}\n\nexport function resolveEndpoint(config: Config, profileOverride?: string): string {\n const name = profileOverride ?? config.currentProfile;\n const profile = config.profiles[name];\n if (!profile) {\n throw new Error(`Profile \"${name}\" not found.`);\n }\n return profile.endpoint.replace(/\\/+$/, '');\n}\n\nexport function resolveAuth(config: Config, profileOverride?: string): AuthConfig | undefined {\n const name = profileOverride ?? config.currentProfile;\n const profile = config.profiles[name];\n if (!profile) {\n throw new Error(`Profile \"${name}\" not found.`);\n }\n return profile.auth;\n}\n\nexport { CONFIG_DIR, CONFIG_FILE };\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/**\n * A lock several `diafunc` processes can share, made of a file that only one of them can create.\n *\n * Several processes may use one profile at the same time (a few `analyze run` followers, a script\n * and a shell). Whatever they must not do twice, such as spending a single-use refresh token, runs\n * under this lock. The file is created with the exclusive flag, which the operating system grants\n * to exactly one caller, and holds the owner's process id, host and creation time so that a lock\n * left behind by a killed process is recognised and taken over instead of blocking everyone.\n */\n\nexport interface FileLockOptions {\n /** A lock older than this is taken over even when its holder still seems alive. */\n staleMs?: number;\n /** How long to wait for a live holder before giving up with {@link LockTimeoutError}. */\n waitMs?: number;\n /** Upper bound of one pause between two attempts; the pauses are jittered below it. */\n pollMs?: number;\n /** Whether a process id on this host is running. Replaceable so a test can name a dead holder. */\n isAlive?: (pid: number) => boolean;\n}\n\nexport interface FileLock {\n /** Removes the lock file if this holder still owns it. Safe to call more than once. */\n release(): void;\n}\n\nexport class LockTimeoutError extends Error {\n readonly lockPath: string;\n\n constructor(lockPath: string, waitedMs: number) {\n super(`Timed out after ${Math.round(waitedMs / 1000)}s waiting for ${lockPath}.`);\n this.name = 'LockTimeoutError';\n this.lockPath = lockPath;\n }\n}\n\nexport const DEFAULT_STALE_MS = 30_000;\nexport const DEFAULT_WAIT_MS = 25_000;\nconst DEFAULT_POLL_MS = 120;\n\ninterface Holder {\n id: string;\n pid: number;\n host: string;\n createdAt: number;\n}\n\n/** Locks this process holds, so the exit hook can remove them when the process is ended from within. */\nconst held = new Map<string, string>();\nlet exitHookInstalled = false;\n\nfunction installExitHook(): void {\n if (exitHookInstalled) return;\n exitHookInstalled = true;\n // `process.exit()` skips pending `finally` blocks; this hook is what keeps a command that exits\n // while a refresh is in flight from leaving its lock for the others to wait out.\n process.on('exit', () => {\n for (const [lockPath, id] of held) removeIfOwned(lockPath, id);\n });\n}\n\nfunction processIsAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: the process exists and belongs to someone else.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\nfunction readHolder(lockPath: string): Holder | 'absent' | 'unreadable' {\n let raw: string;\n try {\n raw = fs.readFileSync(lockPath, 'utf-8');\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'absent' : 'unreadable';\n }\n try {\n const parsed = JSON.parse(raw) as Partial<Holder>;\n if (typeof parsed.id === 'string' && typeof parsed.pid === 'number' && typeof parsed.createdAt === 'number') {\n return { id: parsed.id, pid: parsed.pid, host: String(parsed.host ?? ''), createdAt: parsed.createdAt };\n }\n } catch { /* an owner between creating the file and writing into it; judged by the file's age below */ }\n return 'unreadable';\n}\n\nfunction isStale(lockPath: string, holder: Holder | 'unreadable', staleMs: number, isAlive: (pid: number) => boolean): boolean {\n if (holder === 'unreadable') {\n try {\n return Date.now() - fs.statSync(lockPath).mtimeMs > staleMs;\n } catch {\n return false;\n }\n }\n if (Date.now() - holder.createdAt > staleMs) return true;\n // A process id only means something on the host that issued it; a home directory shared between\n // machines falls back to the age bound.\n return holder.host === os.hostname() && !isAlive(holder.pid);\n}\n\nfunction removeIfOwned(lockPath: string, id: string): void {\n const holder = readHolder(lockPath);\n if (holder !== 'absent' && holder !== 'unreadable' && holder.id === id) {\n try {\n fs.unlinkSync(lockPath);\n } catch { /* already gone */ }\n }\n}\n\nfunction tryCreate(lockPath: string, content: string): boolean {\n let fd: number;\n try {\n fd = fs.openSync(lockPath, 'wx', 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'EEXIST') return false;\n // Windows answers a create over a file that is just being deleted with a permission error.\n if (process.platform === 'win32' && (code === 'EPERM' || code === 'EACCES' || code === 'EBUSY')) return false;\n if (code === 'ENOENT') {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });\n return tryCreate(lockPath, content);\n }\n throw error;\n }\n try {\n fs.writeSync(fd, content);\n } finally {\n fs.closeSync(fd);\n }\n return true;\n}\n\n/**\n * Removes a lock judged stale, at most one contender at a time.\n *\n * Two waiters that both find the same stale lock must not both delete \"it\": the second delete\n * would remove the lock the first waiter has created in the meantime, and both would then hold it.\n * The removal therefore runs under a second exclusive file, and the staleness is judged again\n * inside it.\n */\nfunction removeStale(lockPath: string, staleMs: number, isAlive: (pid: number) => boolean): void {\n const breaker = `${lockPath}.break`;\n if (!tryCreate(breaker, '')) {\n // A breaker is held for a few file operations; one that has been lying there for longer than\n // the stale bound belonged to a process that died holding it.\n try {\n if (Date.now() - fs.statSync(breaker).mtimeMs > staleMs) fs.unlinkSync(breaker);\n } catch { /* gone already */ }\n return;\n }\n try {\n const holder = readHolder(lockPath);\n if (holder !== 'absent' && isStale(lockPath, holder, staleMs, isAlive)) {\n try {\n fs.unlinkSync(lockPath);\n } catch { /* gone already */ }\n }\n } finally {\n try {\n fs.unlinkSync(breaker);\n } catch { /* gone already */ }\n }\n}\n\nfunction pause(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Takes the lock, waiting for a live holder up to `waitMs`. */\nexport async function acquireFileLock(lockPath: string, options: FileLockOptions = {}): Promise<FileLock> {\n const staleMs = options.staleMs ?? DEFAULT_STALE_MS;\n const waitMs = options.waitMs ?? DEFAULT_WAIT_MS;\n const pollMs = options.pollMs ?? DEFAULT_POLL_MS;\n const isAlive = options.isAlive ?? processIsAlive;\n\n const id = crypto.randomUUID();\n const startedAt = Date.now();\n\n for (;;) {\n const content = JSON.stringify({ id, pid: process.pid, host: os.hostname(), createdAt: Date.now() });\n if (tryCreate(lockPath, content)) {\n installExitHook();\n held.set(lockPath, id);\n let released = false;\n return {\n release(): void {\n if (released) return;\n released = true;\n if (held.get(lockPath) === id) held.delete(lockPath);\n // Only the owner removes the file: after a takeover it belongs to someone else.\n removeIfOwned(lockPath, id);\n },\n };\n }\n\n const waited = Date.now() - startedAt;\n if (waited >= waitMs) throw new LockTimeoutError(lockPath, waited);\n\n const holder = readHolder(lockPath);\n let free = holder === 'absent';\n if (holder !== 'absent' && isStale(lockPath, holder, staleMs, isAlive)) {\n removeStale(lockPath, staleMs, isAlive);\n free = true;\n }\n // Every failed attempt yields before the next one, so no path through this loop can spin.\n // The pauses are jittered, so contenders released by the same event do not retry in step.\n const nap = free ? 1 + 4 * Math.random() : pollMs * (0.25 + 0.75 * Math.random());\n await pause(Math.min(nap, Math.max(1, waitMs - waited)));\n }\n}\n\n/** Runs `work` while holding the lock and releases it whether `work` returns or throws. */\nexport async function withFileLock<T>(lockPath: string, work: () => T | Promise<T>, options: FileLockOptions = {}): Promise<T> {\n const lock = await acquireFileLock(lockPath, options);\n try {\n return await work();\n } finally {\n lock.release();\n }\n}\n","import chalk from 'chalk';\nimport { type AuthConfig, type Config, loadConfig, resolveEndpoint } from '../config/store.js';\nimport { ApiError, NetworkError, type ApiErrorBody } from './errors.js';\nimport { isTokenExpired, sharedSignIn } from './sign-in.js';\nimport pkg from '../../package.json' with { type: 'json' };\n\n/** A request that has not answered by now is treated as failed rather than waited on forever. */\nconst REQUEST_TIMEOUT_MS = 60_000;\n/** Statuses worth trying again: a rolling deploy briefly answers with these. */\nconst RETRYABLE_STATUSES = new Set([502, 503, 504]);\nconst MAX_ATTEMPTS = 3;\n/**\n * Only reads are retried. A gateway 503 does not promise the request never reached the service,\n * so replaying a POST could create a second analysis or send a second invitation; and a multipart\n * upload body cannot be read twice in any case.\n */\nconst RETRYABLE_METHODS = new Set<HttpMethod>(['GET']);\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\nexport interface RequestOptions {\n method: HttpMethod;\n path: string;\n service: string;\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n headers?: Record<string, string>;\n rawBody?: BodyInit;\n contentType?: string;\n}\n\nexport interface HttpClient {\n request<T>(options: RequestOptions): Promise<T>;\n requestRaw(options: RequestOptions): Promise<Response>;\n}\n\nfunction buildUrl(endpoint: string, service: string, path: string, query?: Record<string, string | number | boolean | undefined>): string {\n const base = `${endpoint}/api/v1/${service}${path}`;\n const params = new URLSearchParams();\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n params.set(key, String(value));\n }\n }\n }\n const qs = params.toString();\n return qs ? `${base}?${qs}` : base;\n}\n\nfunction getAuthHeader(auth: AuthConfig | undefined): string | undefined {\n if (!auth) return undefined;\n if (auth.type === 'api-token') {\n return `Bearer ${auth.token}`;\n }\n if (auth.type === 'device-code') {\n return `Bearer ${auth.accessToken}`;\n }\n return undefined;\n}\n\n/**\n * The credentials for this request. An expired device-code sign-in is renewed through the\n * refresher all clients and processes on the profile share; see `sign-in.ts`.\n */\nasync function ensureValidAuth(config: Config, profileOverride?: string): Promise<AuthConfig | undefined> {\n const profileName = profileOverride ?? config.currentProfile;\n const profile = config.profiles[profileName];\n if (!profile?.auth) return undefined;\n\n if (profile.auth.type === 'device-code' && isTokenExpired(profile.auth)) {\n profile.auth = await sharedSignIn.ensureFresh(profileName);\n }\n\n return profile.auth;\n}\n\nasync function parseErrorBody(response: Response): Promise<ApiError> {\n try {\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n const body = await response.json() as ApiErrorBody;\n return ApiError.fromBody(response.status, body);\n }\n // A non-JSON body is a gateway page, not an explanation. ApiError drops markup and falls back\n // to a status-derived sentence, so the reader never sees raw HTML.\n const text = (await response.text()).trim();\n return new ApiError(response.status, text || response.statusText);\n } catch {\n return new ApiError(response.status, response.statusText);\n }\n}\n\nlet _dryRun = false;\nlet _verbose = false;\n\nexport function setDryRun(enabled: boolean): void {\n _dryRun = enabled;\n}\n\n/**\n * Whether `--dry-run` is on. A mutating request is then only printed and answers `{}`, so a command\n * that goes on to use the answer (an id to upload to, a run to follow) has to stop where the preview ends.\n */\nexport function isDryRun(): boolean {\n return _dryRun;\n}\n\n/** Echoes every request to stderr, so a support question can be answered without a proxy. */\nexport function setVerbose(enabled: boolean): void {\n _verbose = enabled;\n}\n\nfunction trace(line: string): void {\n if (_verbose) console.error(chalk.dim(` [http] ${line}`));\n}\n\n/** Connection-level faults worth one more attempt; a timeout is not, the caller waited already. */\nfunction isTransient(error: Error): boolean {\n if (error.name === 'TimeoutError' || error.name === 'AbortError') return false;\n const cause = (error as { cause?: { code?: string } }).cause;\n const code = cause?.code ?? '';\n return ['ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN'].includes(code);\n}\n\nexport function createHttpClient(options: { profileOverride?: string } = {}): HttpClient {\n const config = loadConfig();\n const endpoint = resolveEndpoint(config, options.profileOverride);\n\n async function doRequest(opts: RequestOptions): Promise<Response> {\n if (_dryRun && opts.method !== 'GET') {\n const url = buildUrl(endpoint, opts.service, opts.path, opts.query);\n const bodyPreview = opts.body ? JSON.stringify(opts.body, null, 2) : opts.rawBody ? '(binary)' : '(none)';\n // stderr, so a dry run of a command that also prints data does not corrupt the payload.\n console.error(chalk.yellow(`[dry-run] ${opts.method} ${url}`));\n if (opts.body) {\n console.error(chalk.dim(`[dry-run] Body:\\n${bodyPreview}`));\n }\n return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });\n }\n\n const auth = await ensureValidAuth(config, options.profileOverride);\n const url = buildUrl(endpoint, opts.service, opts.path, opts.query);\n const headers: Record<string, string> = {\n ...opts.headers,\n };\n\n const authHeader = getAuthHeader(auth);\n if (authHeader) {\n headers['Authorization'] = authHeader;\n }\n\n let body: BodyInit | undefined;\n if (opts.rawBody !== undefined) {\n body = opts.rawBody;\n if (opts.contentType) {\n headers['Content-Type'] = opts.contentType;\n }\n } else if (opts.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(opts.body);\n }\n\n headers['User-Agent'] = `diafunc-cli/${pkg.version} (${process.platform}; node ${process.versions.node})`;\n // Names the surface explicitly, so the platform attributes the call to the CLI (usage by surface,\n // analysis run origin) without parsing the User-Agent.\n headers['X-Diafunc-Client'] = `cli/${pkg.version}`;\n\n const retryable = RETRYABLE_METHODS.has(opts.method);\n const maxAttempts = retryable ? MAX_ATTEMPTS : 1;\n\n let lastError: Error | undefined;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const startedAt = Date.now();\n try {\n const response = await fetch(url, {\n method: opts.method,\n headers,\n body,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n trace(`${opts.method} ${url} -> ${response.status} (${Date.now() - startedAt}ms)`);\n // A body can only be read once, so a retryable status is only retried when there is an\n // attempt left; otherwise the response is returned for the caller to parse.\n if (RETRYABLE_STATUSES.has(response.status) && attempt < maxAttempts) {\n trace(`retrying after ${response.status} (attempt ${attempt} of ${maxAttempts})`);\n await delay(attempt * 500);\n continue;\n }\n return response;\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n trace(`${opts.method} ${url} -> ${lastError.name}: ${lastError.message}`);\n if (attempt < maxAttempts && isTransient(lastError)) {\n await delay(attempt * 500);\n continue;\n }\n break;\n }\n }\n\n if (lastError?.name === 'TimeoutError') {\n throw new NetworkError(\n `No response from ${endpoint} within ${REQUEST_TIMEOUT_MS / 1000}s.`,\n lastError,\n );\n }\n throw new NetworkError(\n `Failed to connect to ${endpoint}${lastError ? ` (${lastError.message})` : ''}. ` +\n `Check your network, or the endpoint set by 'diafunc config list'.`,\n lastError,\n );\n }\n\n function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n return {\n async request<T>(opts: RequestOptions): Promise<T> {\n const response = await doRequest(opts);\n if (!response.ok) {\n throw await parseErrorBody(response);\n }\n if (response.status === 204) {\n return undefined as T;\n }\n const contentType = response.headers.get('content-type') ?? '';\n const text = await response.text();\n if (contentType.includes('application/json')) {\n return (text ? JSON.parse(text) : undefined) as T;\n }\n return text as unknown as T;\n },\n\n async requestRaw(opts: RequestOptions): Promise<Response> {\n const response = await doRequest(opts);\n if (!response.ok) {\n throw await parseErrorBody(response);\n }\n return response;\n },\n };\n}\n","export interface ApiErrorBody {\n status: number;\n message: string;\n details?: string;\n /** A code that stays stable, so a client can say it in its own words: `licence_required`. */\n error?: string;\n}\n\n/**\n * The platform's license refusals, each said in one line. The platform's own message is written\n * for the web app, where the license is picked from a list; here the way out is a flag.\n */\nexport const LICENSE_REFUSALS: Readonly<Record<string, string>> = {\n licence_required: 'A public project needs a license. Name one with --license <id>.',\n licence_not_selectable: 'That license cannot be chosen: it is not in the catalog, or it is deprecated or withdrawn.',\n licence_share_alike_mismatch: 'This project is a fork of a share-alike project, so it has to carry the license of the project it was forked from.',\n licence_forbids_fork: 'The license of this project does not allow adaptations, so it cannot be forked.',\n};\n\n/** The refusals the license catalog answers. */\nexport const LICENSE_LIST_REFUSALS: ReadonlySet<string> = new Set(['licence_required', 'licence_not_selectable']);\n\n/**\n * The way out of a project-transfer refusal. The platform's message says what is wrong (for\n * `project_busy` it names what is running); this line says what to do about it.\n */\nexport const PROJECT_TRANSFER_HINTS: Readonly<Record<string, string>> = {\n transfer_open: `The project already has an open transfer. See it with 'diafunc project transfer status <projectId>'.`,\n transfer_not_found: `There is no open transfer for this project. List yours with 'diafunc project transfer list'.`,\n transfer_expired: 'The offer has expired. The owner can offer the project again.',\n transfer_recipient_invalid: 'The recipient needs an active Diafunc account; offers go to existing accounts only.',\n transfer_recipient_not_in_team: `Switch to the team first with 'diafunc team use <teamId>', or accept with --personal.`,\n transfer_team_not_administered: 'A project can only go into a team you own or administer.',\n project_busy: 'The offer stays open. Accept again once the work has finished.',\n project_transfer_in_progress: 'The project is being moved right now. Try again in a minute.',\n team_transfer_pending: 'A team involved has a pending ownership transfer; it has to be completed or canceled first.',\n};\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly details?: string;\n /** The platform's stable error code, when the body carried one. */\n readonly code?: string;\n\n constructor(status: number, message: string, details?: string, code?: string) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.details = details;\n this.code = code;\n }\n\n static fromBody(status: number, body: ApiErrorBody): ApiError {\n return new ApiError(status, body.message, body.details, typeof body.error === 'string' ? body.error : undefined);\n }\n\n toUserMessage(): string {\n const refusal = this.code && Object.prototype.hasOwnProperty.call(LICENSE_REFUSALS, this.code)\n ? LICENSE_REFUSALS[this.code]\n : undefined;\n if (refusal) return refusal;\n const detail = this.readableMessage();\n switch (this.status) {\n case 401:\n return `Authentication failed. Run 'diafunc auth login' to sign in again.`;\n case 403:\n return detail\n ? `Permission denied: ${detail}`\n : `Permission denied. Your account or token lacks the required access.`;\n case 404:\n return detail ? `Not found: ${detail}` : `Not found: the server has no such resource.`;\n case 409:\n return detail ? `Conflict: ${detail}` : `Conflict: the resource changed under this request.`;\n case 429:\n return `Rate limited. Wait a moment and try again.`;\n case 500:\n case 502:\n case 503:\n case 504:\n return detail\n ? `The Diafunc platform returned ${this.status}: ${detail}`\n : `The Diafunc platform returned ${this.status}. Check 'diafunc status summary'.`;\n default:\n return detail || `The request failed with status ${this.status}.`;\n }\n }\n\n /**\n * The server's message, or nothing when what came back was not meant for a person.\n *\n * A gateway answering with its own HTML error page used to be surfaced verbatim, so a missing\n * endpoint read as\n * `Error: Not found: <html><head><title>Error</title></head><body>Not Found</body></html>`.\n * Markup is never the explanation the reader needs, so it is dropped in favour of the\n * status-derived sentence above.\n */\n private readableMessage(): string {\n const message = (this.message ?? '').trim();\n if (!message || looksLikeMarkup(message)) return '';\n const withDetails = this.details && !looksLikeMarkup(this.details)\n ? `${message} (${this.details})`\n : message;\n return withDetails;\n }\n}\n\nfunction looksLikeMarkup(text: string): boolean {\n const head = text.trimStart().slice(0, 200).toLowerCase();\n return head.startsWith('<') || head.includes('<html') || head.includes('<!doctype');\n}\n\nexport class NetworkError extends Error {\n constructor(message: string, cause?: Error) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n }\n}\n","import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport {\n type AuthConfig,\n type DeviceCodeAuth,\n profileSidecarFile,\n readStoredProfile,\n updateStoredProfile,\n} from '../config/store.js';\nimport { LockTimeoutError, withFileLock } from '../config/lock.js';\nimport { ApiError, NetworkError } from './errors.js';\n\n/**\n * Renewing a device-code sign-in that several processes share.\n *\n * The refresh token is single-use: every refresh answers with a new one, and the server treats a\n * second use of an old one as theft and revokes the whole sign-in. Any number of `diafunc`\n * processes may run on one profile, so a refresh is only ever sent\n *\n * - by one process at a time (a lock file beside the config, per profile),\n * - with the token that is on disk at that moment, never the one a process loaded at start,\n * - and only when the tokens on disk are not already fresh, in which case they are adopted.\n *\n * A token the server refused is never sent again, by this process or by another one.\n */\n\n/** Renew this long before the access token runs out, so a request never leaves with a dying token. */\nconst EXPIRY_MARGIN_MS = 30_000;\n/**\n * Bound of one token request. It stays well under the lock's stale bound, so a holder is never\n * taken over while its request is still on the way.\n */\nconst TOKEN_REQUEST_TIMEOUT_MS = 10_000;\n/** Token requests one renewal may send when the service keeps answering \"too many requests\". */\nconst MAX_RATE_LIMITED_ATTEMPTS = 3;\n/** The wait when the service is in trouble but names none. */\nconst DEFAULT_BACKOFF_MS = 5_000;\nconst MIN_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 120_000;\n/** A wait worth telling the reader about. */\nconst NOTICE_THRESHOLD_MS = 2_000;\n\n/** The server no longer accepts the stored sign-in. Final: only `diafunc auth login` changes it. */\nexport class SignInRefusedError extends ApiError {\n constructor(profileName: string) {\n super(401, `The stored sign-in of profile \"${profileName}\" is no longer accepted. Run 'diafunc auth login' to sign in again.`);\n this.name = 'SignInRefusedError';\n }\n\n toUserMessage(): string {\n return this.message;\n }\n}\n\n/**\n * Whether an error means the credentials are not accepted. Waiting does not change that, so a\n * command that polls stops on it instead of asking again.\n */\nexport function isAuthenticationFailure(error: unknown): boolean {\n return error instanceof ApiError && error.status === 401;\n}\n\nexport function isTokenExpired(auth: AuthConfig | undefined): boolean {\n if (!auth) return false;\n if (auth.type === 'device-code') {\n return Date.now() >= auth.accessTokenExpiry - EXPIRY_MARGIN_MS;\n }\n return false;\n}\n\nexport function deriveAuthUrl(endpoint: string): string {\n const trimmed = endpoint.replace(/\\/+$/, '');\n if (trimmed.includes('://auth.')) {\n return trimmed;\n }\n const url = new URL(trimmed);\n url.hostname = `auth.${url.hostname}`;\n url.pathname = '';\n return url.toString().replace(/\\/+$/, '');\n}\n\ninterface OAuthTokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n}\n\nexport interface SignInRefresherOptions {\n sleep?: (ms: number) => Promise<void>;\n /** Told when a wait is long enough that the reader should know why nothing happens. */\n notify?: (message: string) => void;\n lockWaitMs?: number;\n lockStaleMs?: number;\n}\n\nexport interface SignInRefresher {\n /**\n * The credentials to use for the profile now: the stored ones when they are fresh, renewed ones\n * otherwise. Concurrent calls for one profile share a single renewal.\n */\n ensureFresh(profileName: string): Promise<AuthConfig>;\n}\n\ntype Outcome =\n | { kind: 'credentials'; auth: AuthConfig }\n | { kind: 'rate-limited'; retryAfterMs: number };\n\nfunction digestOf(token: string): string {\n return crypto.createHash('sha256').update(token).digest('hex');\n}\n\n/** `Retry-After` as milliseconds; the header carries either seconds or a date. */\nexport function retryAfterMs(header: string | null, now: number = Date.now()): number {\n let wait = DEFAULT_BACKOFF_MS;\n if (header) {\n const seconds = Number(header.trim());\n if (Number.isFinite(seconds)) {\n wait = seconds * 1000;\n } else {\n const at = Date.parse(header);\n if (Number.isFinite(at)) wait = at - now;\n }\n }\n return Math.min(MAX_BACKOFF_MS, Math.max(MIN_BACKOFF_MS, wait));\n}\n\nexport function createSignInRefresher(options: SignInRefresherOptions = {}): SignInRefresher {\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const notify = options.notify ?? ((message: string) => console.error(message));\n const lockOptions = { waitMs: options.lockWaitMs, staleMs: options.lockStaleMs };\n\n /** One renewal per profile at a time inside this process; later callers join it. */\n const inFlight = new Map<string, Promise<AuthConfig>>();\n /** Per profile, the moment before which the token endpoint is not asked again. */\n const notBefore = new Map<string, number>();\n /** Digests of refresh tokens the server refused during this process. */\n const refused = new Set<string>();\n\n /**\n * Where a definitively refused token is recorded for the other processes on the profile: the\n * digest of the token, never the token. Each of them would otherwise send it once more to learn\n * the same answer, and every such request counts as a reuse on the server.\n */\n function refusedMarkerFile(profileName: string): string {\n return profileSidecarFile(profileName, 'refused');\n }\n\n function isKnownRefused(profileName: string, refreshToken: string): boolean {\n const digest = digestOf(refreshToken);\n if (refused.has(digest)) return true;\n try {\n return fs.readFileSync(refusedMarkerFile(profileName), 'utf-8').trim() === digest;\n } catch {\n return false;\n }\n }\n\n function rememberRefused(profileName: string, refreshToken: string, acrossProcesses: boolean): void {\n const digest = digestOf(refreshToken);\n refused.add(digest);\n if (!acrossProcesses) return;\n try {\n fs.writeFileSync(refusedMarkerFile(profileName), digest + '\\n', { encoding: 'utf-8', mode: 0o600 });\n } catch { /* the record spares other processes a request; this one has its answer either way */ }\n }\n\n function forgetRefused(profileName: string): void {\n fs.rmSync(refusedMarkerFile(profileName), { force: true });\n }\n\n async function requestTokens(endpoint: string, auth: DeviceCodeAuth): Promise<Response> {\n try {\n return await fetch(`${deriveAuthUrl(endpoint)}/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: auth.refreshToken,\n client_id: auth.clientId,\n }).toString(),\n signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n throw new NetworkError(\n `Could not reach the sign-in service of ${endpoint} to renew the sign-in.`,\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n /** Runs while this process holds the profile's refresh lock. */\n async function renewUnderLock(profileName: string): Promise<Outcome> {\n const profile = readStoredProfile(profileName);\n const stored = profile?.auth;\n if (!profile || !stored) {\n // Signed out by another process while this one was running.\n throw new SignInRefusedError(profileName);\n }\n // Another process renewed while this one waited for the lock: its tokens are the current ones.\n if (stored.type !== 'device-code' || !isTokenExpired(stored)) {\n return { kind: 'credentials', auth: stored };\n }\n if (isKnownRefused(profileName, stored.refreshToken)) {\n throw new SignInRefusedError(profileName);\n }\n\n let response: Response;\n try {\n response = await requestTokens(profile.endpoint.replace(/\\/+$/, ''), stored);\n } catch (error) {\n notBefore.set(profileName, Date.now() + DEFAULT_BACKOFF_MS);\n throw error;\n }\n\n if (response.ok) {\n const body = await response.json() as OAuthTokenResponse;\n const renewed: DeviceCodeAuth = {\n type: 'device-code',\n clientId: stored.clientId,\n accessToken: body.access_token,\n refreshToken: body.refresh_token ?? stored.refreshToken,\n accessTokenExpiry: Date.now() + body.expires_in * 1000,\n };\n await updateStoredProfile(profileName, (target) => { target.auth = renewed; });\n forgetRefused(profileName);\n return { kind: 'credentials', auth: renewed };\n }\n\n if (response.status === 429) {\n return { kind: 'rate-limited', retryAfterMs: retryAfterMs(response.headers.get('retry-after')) };\n }\n\n if (response.status === 400 || response.status === 401) {\n const reason = await response.json().then((body) => (body as { error?: string }).error, () => undefined);\n // A sign-in written since the request left (`diafunc auth login` in another terminal) replaces\n // the refused one. The read happens once; whatever it finds, the refused token is not sent again.\n const current = readStoredProfile(profileName)?.auth;\n if (current && (current.type !== 'device-code' || current.refreshToken !== stored.refreshToken)) {\n return { kind: 'credentials', auth: current };\n }\n // `invalid_grant` is the server's word that the token is dead for good; any other refusal is\n // remembered for this process only, so a misconfigured gateway cannot lock a profile out.\n rememberRefused(profileName, stored.refreshToken, reason === 'invalid_grant');\n throw new SignInRefusedError(profileName);\n }\n\n notBefore.set(profileName, Date.now() + DEFAULT_BACKOFF_MS);\n throw new ApiError(response.status, `The sign-in service answered ${response.status} while renewing the sign-in.`);\n }\n\n async function waitOutBackoff(profileName: string): Promise<void> {\n const wait = (notBefore.get(profileName) ?? 0) - Date.now();\n if (wait <= 0) return;\n if (wait >= NOTICE_THRESHOLD_MS) {\n notify(`The sign-in service asked to wait; renewing the sign-in in ${Math.ceil(wait / 1000)} s.`);\n }\n // Jittered, so processes told to wait by the same answer do not come back together.\n await sleep(wait + Math.floor(Math.random() * 250));\n }\n\n async function renew(profileName: string): Promise<AuthConfig> {\n for (let attempt = 1; ; attempt++) {\n await waitOutBackoff(profileName);\n\n let outcome: Outcome;\n try {\n // The lock is released before any wait, so one rate-limited process does not keep the\n // others from adopting tokens that arrive in the meantime.\n outcome = await withFileLock(profileSidecarFile(profileName, 'refresh.lock'), () => renewUnderLock(profileName), lockOptions);\n } catch (error) {\n if (!(error instanceof LockTimeoutError)) throw error;\n // Never refresh without the lock. If the holder has stored fresh tokens by now they serve;\n // otherwise this request fails and the next one tries again.\n const stored = readStoredProfile(profileName)?.auth;\n if (stored && !isTokenExpired(stored)) return stored;\n throw new NetworkError('Another diafunc process is still renewing the sign-in of this profile. Try again in a moment.');\n }\n\n if (outcome.kind === 'credentials') return outcome.auth;\n\n notBefore.set(profileName, Date.now() + outcome.retryAfterMs);\n if (attempt >= MAX_RATE_LIMITED_ATTEMPTS) {\n throw new ApiError(429, `The sign-in service is limiting requests from this address. Try again in ${Math.ceil(outcome.retryAfterMs / 1000)} s.`);\n }\n }\n }\n\n return {\n ensureFresh(profileName: string): Promise<AuthConfig> {\n let pending = inFlight.get(profileName);\n if (!pending) {\n pending = renew(profileName).finally(() => inFlight.delete(profileName));\n inFlight.set(profileName, pending);\n }\n return pending;\n },\n };\n}\n\n/** The refresher every HTTP client of this process shares, so they renew a profile once between them. */\nexport const sharedSignIn: SignInRefresher = createSignInRefresher();\n","import type { HttpClient } from '../http.js';\nimport type {\n ApiToken,\n CancelTeamResponse,\n CheckoutSessionResponse,\n CreateApiTokenRequest,\n CreateApiTokenResponse,\n CreateProjectRequest,\n CreateTeamCheckoutRequest,\n InvoicePreview,\n License,\n LicenseCatalogEntry,\n OwnershipTransfer,\n OwnershipTransferAcceptResponse,\n OperatorProjectMoveRequest,\n OperatorProjectMovesRequest,\n OperatorTransferStatusFilter,\n PackChangeResponse,\n Permission,\n PortalSessionResponse,\n Project,\n ProjectMember,\n ProjectMoveBatch,\n ProjectMoveBatchStarted,\n ProjectMovePreflight,\n ProjectTransfer,\n ProjectTransferDirection,\n ProjectTransferOffer,\n RecentProject,\n SeatChangeResponse,\n Team,\n TeamContract,\n TeamContractRequest,\n TeamInvitation,\n TeamMember,\n TeamMemberRole,\n TeamUsage,\n User,\n Utilization,\n} from '../types/admin.js';\n\nconst SERVICE = 'admin';\n\nexport function createAdminService(client: HttpClient) {\n return {\n // Users\n async getMyUser(): Promise<User> {\n return client.request<User>({\n method: 'GET',\n service: SERVICE,\n path: '/myuser/',\n });\n },\n\n async getUsers(): Promise<User[]> {\n return client.request<User[]>({\n method: 'GET',\n service: SERVICE,\n path: '/users/',\n });\n },\n\n async getUserName(userId: string): Promise<string> {\n return client.request<string>({\n method: 'GET',\n service: SERVICE,\n path: `/users/name/${encodeURIComponent(userId)}`,\n });\n },\n\n // Projects\n async getProjects(): Promise<Project[]> {\n return client.request<Project[]>({\n method: 'GET',\n service: SERVICE,\n path: '/projects/',\n });\n },\n\n async getAllProjects(): Promise<Project[]> {\n return client.request<Project[]>({\n method: 'GET',\n service: SERVICE,\n path: '/projects/all',\n });\n },\n\n async getProject(projectId: string): Promise<Project> {\n return client.request<Project>({\n method: 'GET',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}`,\n });\n },\n\n // Licenses: the catalog answers anyone, signed in or not.\n async listLicenses(): Promise<License[]> {\n return client.request<License[]>({\n method: 'GET',\n service: SERVICE,\n path: '/licences',\n });\n },\n\n async getLicense(licenseId: string): Promise<License> {\n return client.request<License>({\n method: 'GET',\n service: SERVICE,\n path: `/licences/${encodeURIComponent(licenseId)}`,\n });\n },\n\n // Managing the catalog: administrators only.\n async listLicenseCatalog(): Promise<LicenseCatalogEntry[]> {\n return client.request<LicenseCatalogEntry[]>({ method: 'GET', service: SERVICE, path: '/licence-catalogue/' });\n },\n\n async createLicense(license: License): Promise<License> {\n return client.request<License>({ method: 'POST', service: SERVICE, path: '/licence-catalogue/', body: license });\n },\n\n async updateLicense(license: License): Promise<License> {\n return client.request<License>({\n method: 'PUT',\n service: SERVICE,\n path: `/licence-catalogue/${encodeURIComponent(license.licenceId)}`,\n body: license,\n });\n },\n\n async deprecateLicense(licenseId: string): Promise<License> {\n return client.request<License>({\n method: 'POST',\n service: SERVICE,\n path: `/licence-catalogue/${encodeURIComponent(licenseId)}/deprecate`,\n });\n },\n\n async reactivateLicense(licenseId: string): Promise<License> {\n return client.request<License>({\n method: 'POST',\n service: SERVICE,\n path: `/licence-catalogue/${encodeURIComponent(licenseId)}/reactivate`,\n });\n },\n\n /** Ends publication under the license: its public projects become private. `expectedAffected` is the\n * number of them the operator confirmed; the platform refuses when the current number differs. */\n async withdrawLicense(licenseId: string, expectedAffected: number): Promise<License> {\n return client.request<License>({\n method: 'POST',\n service: SERVICE,\n path: `/licence-catalogue/${encodeURIComponent(licenseId)}/withdraw`,\n body: { expectedAffected },\n });\n },\n\n async deleteLicense(licenseId: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/licence-catalogue/${encodeURIComponent(licenseId)}`,\n });\n },\n\n async createProject(request: CreateProjectRequest): Promise<Project> {\n return client.request<Project>({\n method: 'POST',\n service: SERVICE,\n path: '/projects/',\n body: request,\n });\n },\n\n async updateProject(project: Project): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: '/projects/',\n body: project,\n });\n },\n\n async deleteProject(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}`,\n });\n },\n\n async lockProject(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/projects/lock/${encodeURIComponent(projectId)}`,\n });\n },\n\n async unlockProject(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/projects/lock/${encodeURIComponent(projectId)}`,\n });\n },\n\n // Project Members\n async getProjectMembers(projectId: string): Promise<ProjectMember[]> {\n return client.request<ProjectMember[]>({\n method: 'GET',\n service: SERVICE,\n path: `/projects/members/${encodeURIComponent(projectId)}`,\n });\n },\n\n async inviteProjectMember(projectId: string, userId: string, role: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/projects/members/invitations/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}/${encodeURIComponent(role)}`,\n });\n },\n\n async joinProject(projectId: string, userId: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/projects/members/joins/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}`,\n });\n },\n\n async removeProjectMember(projectId: string, userId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/projects/members/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}`,\n });\n },\n\n // Permissions\n async getPermissions(projectId: string): Promise<Permission> {\n return client.request<Permission>({\n method: 'GET',\n service: SERVICE,\n path: `/permissions/${encodeURIComponent(projectId)}`,\n });\n },\n\n // API Tokens\n async createApiToken(request: CreateApiTokenRequest): Promise<CreateApiTokenResponse> {\n return client.request<CreateApiTokenResponse>({\n method: 'POST',\n service: SERVICE,\n path: '/api-tokens/',\n body: request,\n });\n },\n\n async getApiTokens(): Promise<ApiToken[]> {\n return client.request<ApiToken[]>({\n method: 'GET',\n service: SERVICE,\n path: '/api-tokens/',\n });\n },\n\n async getApiTokensByResource(resourceId: string): Promise<ApiToken[]> {\n return client.request<ApiToken[]>({\n method: 'GET',\n service: SERVICE,\n path: `/api-tokens/resource/${encodeURIComponent(resourceId)}`,\n });\n },\n\n async revokeApiToken(tokenId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/api-tokens/${encodeURIComponent(tokenId)}`,\n });\n },\n\n // Teams\n async listMyTeams(): Promise<Team[]> {\n return client.request<Team[]>({\n method: 'GET',\n service: SERVICE,\n path: '/me/teams',\n });\n },\n\n async getTeam(teamId: string): Promise<Team> {\n return client.request<Team>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}`,\n });\n },\n\n async setActiveTeam(teamId: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/me/active-team/${encodeURIComponent(teamId)}`,\n });\n },\n\n async startTeamCheckout(request: CreateTeamCheckoutRequest): Promise<CheckoutSessionResponse> {\n return client.request<CheckoutSessionResponse>({\n method: 'POST',\n service: SERVICE,\n path: '/teams/checkout',\n body: request,\n });\n },\n\n async createTeamPortalSession(teamId: string, returnUrl: string): Promise<PortalSessionResponse> {\n return client.request<PortalSessionResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/portal-session`,\n body: { returnUrl },\n });\n },\n\n async cancelTeam(teamId: string): Promise<CancelTeamResponse> {\n return client.request<CancelTeamResponse>({\n method: 'DELETE',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}`,\n });\n },\n\n async getTeamUsage(teamId: string): Promise<TeamUsage> {\n return client.request<TeamUsage>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/usage`,\n });\n },\n\n // Team members\n async listTeamMembers(teamId: string): Promise<TeamMember[]> {\n return client.request<TeamMember[]>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/members`,\n });\n },\n\n async inviteTeamMember(teamId: string, email: string, role: TeamMemberRole): Promise<TeamMember> {\n return client.request<TeamMember>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/members/invite`,\n body: { email, role },\n });\n },\n\n async removeTeamMember(teamId: string, userId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/members/${encodeURIComponent(userId)}`,\n });\n },\n\n async leaveTeam(teamId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/me/teams/${encodeURIComponent(teamId)}`,\n });\n },\n\n // Team invitations\n async listTeamInvitations(teamId: string): Promise<TeamInvitation[]> {\n return client.request<TeamInvitation[]>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/invitations`,\n });\n },\n\n async revokeTeamInvitation(teamId: string, invitationId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/invitations/${encodeURIComponent(invitationId)}`,\n });\n },\n\n async resendTeamInvitation(teamId: string, invitationId: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/invitations/${encodeURIComponent(invitationId)}/resend`,\n });\n },\n\n async acceptTeamInvitation(token: string): Promise<TeamMember> {\n return client.request<TeamMember>({\n method: 'POST',\n service: SERVICE,\n path: `/invitations/${encodeURIComponent(token)}/accept`,\n });\n },\n\n // Seats and extension packs\n async previewTeamSeatCount(teamId: string, seatCount: number): Promise<InvoicePreview> {\n return client.request<InvoicePreview>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/seat-count/preview`,\n body: { seatCount },\n });\n },\n\n async updateTeamSeatCount(teamId: string, seatCount: number): Promise<SeatChangeResponse> {\n return client.request<SeatChangeResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/seat-count`,\n body: { seatCount },\n });\n },\n\n async previewTeamPackCount(teamId: string, packCount: number): Promise<InvoicePreview> {\n return client.request<InvoicePreview>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/pack-count/preview`,\n body: { packCount },\n });\n },\n\n async updateTeamPackCount(teamId: string, packCount: number): Promise<PackChangeResponse> {\n return client.request<PackChangeResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/pack-count`,\n body: { packCount },\n });\n },\n\n // Ownership transfer\n async initiateOwnershipTransfer(teamId: string, newOwnerUserId: string): Promise<OwnershipTransfer> {\n return client.request<OwnershipTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/ownership-transfer`,\n body: { newOwnerUserId },\n });\n },\n\n async getOwnershipTransfer(teamId: string): Promise<OwnershipTransfer | undefined> {\n return client.request<OwnershipTransfer | undefined>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/ownership-transfer`,\n });\n },\n\n async acceptOwnershipTransfer(teamId: string): Promise<OwnershipTransferAcceptResponse> {\n return client.request<OwnershipTransferAcceptResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/ownership-transfer/accept`,\n });\n },\n\n async cancelOwnershipTransfer(teamId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/ownership-transfer`,\n });\n },\n\n // Project ownership transfer: the owner offers, the recipient accepts or declines.\n async offerProjectTransfer(projectId: string, offer: ProjectTransferOffer): Promise<ProjectTransfer> {\n return client.request<ProjectTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}/transfer`,\n body: offer,\n });\n },\n\n /** The open transfer of a project, or `undefined` when there is none (the platform answers 204). */\n async getProjectTransfer(projectId: string): Promise<ProjectTransfer | undefined> {\n return client.request<ProjectTransfer | undefined>({\n method: 'GET',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}/transfer`,\n });\n },\n\n async withdrawProjectTransfer(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}/transfer`,\n });\n },\n\n /** `toTeamId` null takes the project into the recipient's personal account. */\n async acceptProjectTransfer(projectId: string, toTeamId: string | null): Promise<ProjectTransfer> {\n return client.request<ProjectTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}/transfer/accept`,\n body: { toTeamId },\n });\n },\n\n async declineProjectTransfer(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/projects/${encodeURIComponent(projectId)}/transfer/decline`,\n });\n },\n\n async listProjectTransfers(direction: ProjectTransferDirection, status: 'open' | 'all'): Promise<ProjectTransfer[]> {\n return client.request<ProjectTransfer[]>({\n method: 'GET',\n service: SERVICE,\n path: '/project-transfers',\n query: { direction, status },\n });\n },\n\n // Project moves by an operator: no acceptance step, every call carries the reason.\n async moveProject(projectId: string, request: OperatorProjectMoveRequest): Promise<ProjectTransfer> {\n return client.request<ProjectTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/operator/projects/${encodeURIComponent(projectId)}/move`,\n body: request,\n });\n },\n\n /** A preflight answers the verdicts and writes nothing; otherwise the batch starts in the background. */\n async moveProjects(request: OperatorProjectMovesRequest): Promise<ProjectMovePreflight | ProjectMoveBatchStarted> {\n return client.request<ProjectMovePreflight | ProjectMoveBatchStarted>({\n method: 'POST',\n service: SERVICE,\n path: '/operator/projects/moves',\n body: request,\n });\n },\n\n async getProjectMoveBatch(batchId: string): Promise<ProjectMoveBatch> {\n return client.request<ProjectMoveBatch>({\n method: 'GET',\n service: SERVICE,\n path: `/operator/projects/moves/${encodeURIComponent(batchId)}`,\n });\n },\n\n async listOperatorProjectTransfers(status?: OperatorTransferStatusFilter): Promise<ProjectTransfer[]> {\n return client.request<ProjectTransfer[]>({\n method: 'GET',\n service: SERVICE,\n path: '/operator/projects/transfers',\n query: { status },\n });\n },\n\n async resumeProjectTransfer(projectId: string, reason: string): Promise<ProjectTransfer> {\n return client.request<ProjectTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/operator/projects/${encodeURIComponent(projectId)}/transfer/resume`,\n body: { reason },\n });\n },\n\n async abortProjectTransfer(projectId: string, reason: string): Promise<ProjectTransfer> {\n return client.request<ProjectTransfer>({\n method: 'POST',\n service: SERVICE,\n path: `/operator/projects/${encodeURIComponent(projectId)}/transfer/abort`,\n body: { reason },\n });\n },\n\n async cancelProjectTransferAsOperator(projectId: string, reason: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/operator/projects/${encodeURIComponent(projectId)}/transfer`,\n body: { reason },\n });\n },\n\n // Team contracts (super-admin only)\n async issueTeamContract(teamId: string, request: TeamContractRequest): Promise<TeamContract> {\n return client.request<TeamContract>({\n method: 'POST',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/contract`,\n body: request,\n });\n },\n\n async getTeamContract(teamId: string): Promise<TeamContract> {\n return client.request<TeamContract>({\n method: 'GET',\n service: SERVICE,\n path: `/teams/${encodeURIComponent(teamId)}/contract`,\n });\n },\n\n // Settings\n async getSettings(): Promise<unknown> {\n return client.request<unknown>({\n method: 'GET',\n service: SERVICE,\n path: '/settings/',\n });\n },\n\n // The platform expects one { name, value } pair, not a map keyed by the setting name.\n async mergeSetting(setting: { name: string; value: string }): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: '/settings/',\n body: setting,\n });\n },\n\n // Platform settings: the operator-facing catalog, distinct from the per-user settings above.\n // Every entry carries its compiled default, so an unset override reads as null rather than absent.\n async listPlatformSettings(): Promise<unknown> {\n return client.request<unknown>({\n method: 'GET',\n service: SERVICE,\n path: '/platform-settings',\n });\n },\n\n async updatePlatformSetting(key: string, value: string, reason?: string): Promise<unknown> {\n return client.request<unknown>({\n method: 'PUT',\n service: SERVICE,\n path: `/platform-settings/${encodeURIComponent(key)}`,\n body: { value, reason },\n });\n },\n\n // Subscription\n async getCurrentSubscription(): Promise<unknown> {\n return client.request<unknown>({\n method: 'GET',\n service: SERVICE,\n path: '/subscriptions/current',\n });\n },\n\n async getNextSubscription(): Promise<unknown> {\n return client.request<unknown>({\n method: 'GET',\n service: SERVICE,\n path: '/subscriptions/next',\n });\n },\n\n async getSubscriptionPlans(subscriptionToken: string): Promise<unknown> {\n return client.request<unknown>({\n method: 'GET',\n service: SERVICE,\n path: `/subscription-plans/${encodeURIComponent(subscriptionToken)}`,\n });\n },\n\n // Invoices\n async hasInvoices(): Promise<boolean> {\n return client.request<boolean>({\n method: 'GET',\n service: SERVICE,\n path: '/invoices/any',\n });\n },\n\n async getInvoices(): Promise<unknown[]> {\n return client.request<unknown[]>({\n method: 'GET',\n service: SERVICE,\n path: '/invoices/',\n });\n },\n\n async downloadInvoice(invoiceNumber: string, fileName: string): Promise<Response> {\n return client.requestRaw({\n method: 'GET',\n service: SERVICE,\n path: `/invoices/${encodeURIComponent(invoiceNumber)}/documents/${encodeURIComponent(fileName)}`,\n });\n },\n\n // (Backup methods moved to storage service — see src/client/services/storage.ts.\n // Backup endpoints live under @RestApi(\"storage\") on the platform.)\n\n // Analyses moved to the analysis service (see src/client/services/analysis.ts).\n\n // Utilization\n async getActualUtilization(): Promise<Utilization> {\n return client.request<Utilization>({\n method: 'GET',\n service: SERVICE,\n path: '/utilization/actual',\n });\n },\n\n async getUtilizationHistory(): Promise<Utilization[]> {\n return client.request<Utilization[]>({\n method: 'GET',\n service: SERVICE,\n path: '/utilization/history',\n });\n },\n\n // Recent projects\n async getRecentProjects(): Promise<RecentProject[]> {\n return client.request<RecentProject[]>({\n method: 'GET',\n service: SERVICE,\n path: '/recent-projects/',\n });\n },\n };\n}\n\nexport type AdminService = ReturnType<typeof createAdminService>;\n","import chalk from 'chalk';\nimport { ApiError, LICENSE_LIST_REFUSALS, NetworkError, PROJECT_TRANSFER_HINTS } from '../client/errors.js';\nimport { SignInRefusedError } from '../client/sign-in.js';\nimport { failure, hint } from '../output/messages.js';\n\n/**\n * Exit codes.\n *\n * A command that reports a problem must not also report success. `diafunc search foo` used to\n * print its usage complaint on stdout and exit 0, and `analyze watch` exited 0 on a run that\n * FAILED — both of which make `diafunc ... && next-step` run the next step anyway.\n */\nexport const EXIT_OK = 0;\n/** The command ran and the thing it was asked about failed. */\nexport const EXIT_FAILURE = 1;\n/** The command was called wrongly: a missing argument, an unusable flag combination. */\nexport const EXIT_USAGE = 2;\n/** Not signed in, or signed in without the required access. */\nexport const EXIT_AUTH = 3;\n/**\n * The reader interrupted an interactive prompt. 128 + SIGINT, the shell convention, so a wrapper\n * script can tell \"the person stopped this\" apart from \"the command failed\".\n */\nexport const EXIT_CANCELLED = 130;\n\n/** A problem already described to the user; `handleError` prints nothing more. */\nexport class CliError extends Error {\n readonly exitCode: number;\n readonly hint?: string;\n\n constructor(message: string, options: { exitCode?: number; hint?: string } = {}) {\n super(message);\n this.name = 'CliError';\n this.exitCode = options.exitCode ?? EXIT_FAILURE;\n this.hint = options.hint;\n }\n}\n\n/** Reports a usage problem and exits. The message names the flag or argument that would fix it. */\nexport function usageError(message: string, suggestion?: string): never {\n failure(message);\n if (suggestion) hint(suggestion);\n process.exit(EXIT_USAGE);\n}\n\nexport function handleError(error: unknown): never {\n if (error instanceof CliError) {\n failure(error.message);\n if (error.hint) hint(error.hint);\n process.exit(error.exitCode);\n }\n if (error instanceof ApiError) {\n failure(error.toUserMessage());\n // A refused sign-in names the way out in its own sentence.\n if (error.status === 401 && !(error instanceof SignInRefusedError)) hint(`Run 'diafunc auth login' to sign in.`);\n const transferHint = error.code && Object.prototype.hasOwnProperty.call(PROJECT_TRANSFER_HINTS, error.code)\n ? PROJECT_TRANSFER_HINTS[error.code]\n : undefined;\n if (transferHint) hint(transferHint);\n else if (error.status === 404) hint(`Check the id, or list what exists with the matching 'list' command.`);\n if (error.code && LICENSE_LIST_REFUSALS.has(error.code)) hint(`List the licenses that can be chosen with 'diafunc license list'.`);\n process.exit(error.status === 401 || error.status === 403 ? EXIT_AUTH : EXIT_FAILURE);\n }\n if (error instanceof NetworkError) {\n failure(error.message);\n hint(`Run 'diafunc status summary' to check the platform, or 'diafunc config list' for the endpoint in use.`);\n process.exit(EXIT_FAILURE);\n }\n if (error instanceof Error) {\n failure(error.message);\n if (process.env.DIAFUNC_DEBUG && error.stack) console.error(chalk.dim(error.stack));\n process.exit(EXIT_FAILURE);\n }\n failure(String(error));\n process.exit(EXIT_FAILURE);\n}\n\nexport function withErrorHandling<T extends (...args: unknown[]) => Promise<void>>(fn: T): T {\n return (async (...args: unknown[]) => {\n try {\n await fn(...args);\n } catch (error) {\n handleError(error);\n }\n }) as T;\n}\n","import chalk from 'chalk';\nimport { formatJson } from './json.js';\nimport type { OutputFormat } from './formatter.js';\n\n/**\n * The CLI's speaking voice.\n *\n * Before this existed the same event was announced three ways — thirteen sites printed a green\n * `✓ Done`, about twenty printed a bare green sentence, and five appended the word ` done` to a\n * half-written line — and empty results were reported as both \"No data sources.\" and \"No data\n * sources found.\" within one command group. Every command now says these things the same way.\n *\n * Diagnostics go to stderr and data goes to stdout, so `diafunc ... > out.json` captures the\n * payload and nothing else.\n */\n\nconst MARK_OK = '✓';\nconst MARK_WARN = '!';\nconst MARK_FAIL = '✗';\n\n/** An operation completed. In JSON mode this is the payload, so scripts see a result either way. */\nexport function success(message: string, options?: { format?: OutputFormat }): void {\n if (options?.format === 'json') {\n formatJson({ ok: true, message });\n return;\n }\n console.log(`${chalk.green(MARK_OK)} ${message}`);\n}\n\n/** Something the reader should notice that did not stop the command. */\nexport function warn(message: string): void {\n console.error(`${chalk.yellow(MARK_WARN)} ${message}`);\n}\n\n/** The operation did not do what was asked. Callers still own the exit code. */\nexport function failure(message: string): void {\n console.error(`${chalk.red(MARK_FAIL)} ${message}`);\n}\n\n/** Secondary detail under a preceding message. */\nexport function detail(message: string): void {\n console.log(chalk.dim(` ${message}`));\n}\n\n/** A next step the reader can take, such as the command that would fix the problem. */\nexport function hint(message: string): void {\n console.error(chalk.dim(` ${message}`));\n}\n\n/**\n * An empty result. `noun` is the plural thing that was looked for, so call sites read\n * `empty('data sources')` and every one of them produces `No data sources.`\n */\nexport function empty(noun: string, options?: { format?: OutputFormat }): void {\n if (options?.format === 'json') {\n formatJson([]);\n return;\n }\n console.log(chalk.dim(`No ${noun}.`));\n}\n\n/** A section heading inside multi-part output. */\nexport function heading(text: string): void {\n console.log();\n console.log(chalk.bold(text));\n}\n","export function formatJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig, updateStoredProfile } from '../../config/store.js';\nimport { empty, failure, success } from '../../output/messages.js';\n\nfunction deriveAuthUrl(endpoint: string): string {\n const trimmed = endpoint.replace(/\\/+$/, '');\n if (trimmed.includes('://auth.')) {\n return trimmed;\n }\n const url = new URL(trimmed);\n url.hostname = `auth.${url.hostname}`;\n url.pathname = '';\n return url.toString().replace(/\\/+$/, '');\n}\n\nexport function registerLogoutCommand(parent: Command): void {\n parent\n .command('logout')\n .description('Remove stored credentials for the active profile and revoke refresh token if possible')\n .action(async () => {\n const config = loadConfig();\n const profile = config.profiles[config.currentProfile];\n if (!profile) {\n failure(`Profile \"${config.currentProfile}\" not found.`);\n process.exit(1);\n }\n\n if (!profile.auth) {\n empty('credentials stored for this profile');\n return;\n }\n\n // Best-effort revoke before clearing local state. Network failures are non-fatal —\n // the local config is always cleared so the user can re-login.\n if (profile.auth.type === 'device-code') {\n try {\n const authUrl = deriveAuthUrl(profile.endpoint);\n await fetch(`${authUrl}/revoke`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: profile.auth.clientId,\n token: profile.auth.refreshToken,\n token_type_hint: 'refresh_token',\n }).toString(),\n });\n } catch {\n // ignore\n }\n }\n\n // Only this profile changes on disk; the other profiles keep whatever a running command\n // has stored for them since this one started.\n await updateStoredProfile(config.currentProfile, (stored) => { delete stored.auth; });\n success(`Logged out from profile \"${config.currentProfile}\".`);\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createHttpClient } from '../../client/http.js';\nimport { createAdminService } from '../../client/services/admin.js';\nimport { handleError } from '../../util/errors.js';\nimport { type OutputFormat, format } from '../../output/formatter.js';\n\nexport function registerStatusCommand(parent: Command): void {\n parent\n .command('status')\n .description('Show current authentication status')\n .action(async (_options, cmd) => {\n try {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? config.defaults.output ?? 'human';\n const profile = config.profiles[config.currentProfile];\n\n if (!profile?.auth) {\n if (outputFormat === 'json') {\n console.log(JSON.stringify({ authenticated: false, profile: config.currentProfile }));\n } else {\n console.log(chalk.yellow('Not authenticated.'), `Run 'diafunc auth login' to configure credentials.`);\n console.log(` Profile: ${config.currentProfile}`);\n console.log(` Endpoint: ${profile?.endpoint ?? 'not configured'}`);\n }\n return;\n }\n\n const client = createHttpClient();\n const admin = createAdminService(client);\n const user = await admin.getMyUser();\n\n const data = {\n authenticated: true,\n profile: config.currentProfile,\n endpoint: profile.endpoint,\n authType: profile.auth.type,\n userId: user.id,\n userName: user.name,\n email: user.email,\n role: user.role,\n remainingCredits: user.remainingCredits,\n };\n\n format(data, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import chalk from 'chalk';\nimport { headerOf, inferKind, normalizeColumns, recordLabel, type ColumnInput, type ColumnSpec } from './columns.js';\nimport { displayWidth, isInteractive, stripAnsi, terminalWidth, truncate, wrap } from './terminal.js';\nimport { ABSENT, formatInstantAbsolute, renderValue, type ValueKind } from './values.js';\n\nexport { formatInstant } from './values.js';\n\nconst GAP = ' ';\n/** Below this a column is not worth keeping legible; it is truncated instead of shrunk further. */\nconst MIN_COLUMN_WIDTH = 6;\n\nexport function formatHuman(data: unknown, columns?: readonly ColumnInput[]): void {\n if (Array.isArray(data)) {\n renderRows(data as Record<string, unknown>[], columns);\n } else if (data && typeof data === 'object') {\n renderRecord(data as Record<string, unknown>, columns);\n } else {\n console.log(String(data));\n }\n}\n\n/**\n * A list, as a header plus aligned rows.\n *\n * There is deliberately no rule between rows: a nine-row list used to occupy nineteen lines, which\n * made a long listing unreadable and a short one look heavier than the data in it. Off a TTY the\n * alignment padding is dropped entirely in favour of tab separation, so `| grep` and `| awk` see\n * stable fields instead of box-drawing characters.\n */\nfunction renderRows(rows: Record<string, unknown>[], columns?: readonly ColumnInput[]): void {\n if (rows.length === 0) {\n console.log(chalk.dim('No results.'));\n return;\n }\n const specs = resolveSpecs(rows[0], columns);\n\n if (!isInteractive()) {\n console.log(specs.map((s) => headerOf(s)).join('\\t'));\n for (const row of rows) {\n console.log(specs.map((spec) => forPipe(row[spec.key], spec)).join('\\t'));\n }\n return;\n }\n\n let cells = rows.map((row) => specs.map((spec) => renderCell(row, spec)));\n\n // An instant renders as `2026-08-21 21:07 (38m ago)`. When the row does not fit, the relative\n // half is dropped wholesale rather than truncated: `(38…` is noise, the absolute date is not.\n if (naturalWidth(specs, cells) > terminalWidth()) {\n cells = rows.map((row) => specs.map((spec) => renderCell(row, spec, true)));\n }\n\n const widths = budgetWidths(specs, cells);\n console.log(\n specs.map((s, i) => chalk.bold(pad(headerOf(s).toUpperCase(), widths[i]))).join(GAP).trimEnd(),\n );\n for (const row of cells) {\n console.log(row.map((c, i) => pad(truncate(c, widths[i]), widths[i])).join(GAP).trimEnd());\n }\n}\n\n/**\n * A single object, as a label/value block.\n *\n * Values are wrapped inside the remaining width rather than allowed to set it: `analyze get` used\n * to render a ~250-column box because the analysis introduction is a whole markdown document.\n */\nfunction renderRecord(obj: Record<string, unknown>, columns?: readonly ColumnInput[]): void {\n const specs: ColumnSpec[] = columns\n ? normalizeColumns(columns)\n : Object.keys(obj).map((key) => ({ key }));\n if (specs.length === 0) {\n console.log(chalk.dim('No fields.'));\n return;\n }\n\n // Off a TTY the key stays the API's own, so `| grep projectId` keeps working.\n if (!isInteractive()) {\n for (const spec of specs) {\n console.log(`${spec.key}\\t${forPipe(obj[spec.key], spec)}`);\n }\n return;\n }\n\n const labels = specs.map((spec) => spec.header ?? recordLabel(spec.key));\n const labelWidth = Math.min(24, labels.reduce((max, label) => Math.max(max, displayWidth(label)), 0));\n const valueWidth = Math.max(MIN_COLUMN_WIDTH, terminalWidth() - labelWidth - GAP.length);\n\n specs.forEach((spec, i) => {\n const rendered = renderValue(obj[spec.key], spec.kind ?? inferKind(spec.key));\n const label = chalk.bold(pad(truncate(labels[i], labelWidth), labelWidth));\n // Values that already fit are printed untouched so their colour survives; only an overlong\n // one is wrapped, and those are plain text (a markdown introduction, an error message).\n if (!rendered.includes('\\n') && displayWidth(rendered) <= valueWidth) {\n console.log(label + GAP + rendered);\n return;\n }\n // A line with no space in it is a URL or an identifier: broken across lines it can no longer be\n // copied, so it is left for the terminal to fold.\n const lines = rendered.split('\\n').flatMap((line) =>\n displayWidth(line) <= valueWidth || !/\\s/.test(stripAnsi(line).trim()) ? [line] : wrap(stripAnsi(line), valueWidth));\n console.log(label + GAP + (lines[0] ?? ''));\n for (const line of lines.slice(1)) {\n console.log(' '.repeat(labelWidth + GAP.length) + line);\n }\n });\n}\n\nfunction resolveSpecs(sample: Record<string, unknown>, columns?: readonly ColumnInput[]): ColumnSpec[] {\n const specs: ColumnSpec[] = columns\n ? normalizeColumns(columns)\n : Object.keys(sample).map((key) => ({ key }));\n return specs.map((spec) => ({ ...spec, kind: spec.kind ?? inferKind(spec.key) }));\n}\n\nfunction renderCell(row: Record<string, unknown>, spec: ColumnSpec, compactDates = false): string {\n const value = row[spec.key];\n const rendered = compactDates && spec.kind === 'date'\n ? renderCompactDate(value)\n : renderValue(value, spec.kind);\n return spec.maxWidth ? truncate(rendered, spec.maxWidth) : rendered;\n}\n\nfunction renderCompactDate(value: unknown): string {\n if (value === null || value === undefined || value === '') return chalk.dim(ABSENT);\n return formatInstantAbsolute(value);\n}\n\nfunction naturalWidth(specs: ColumnSpec[], cells: string[][]): number {\n const widths = specs.map((spec, i) =>\n Math.max(displayWidth(headerOf(spec)), ...cells.map((row) => displayWidth(row[i]))),\n );\n return widths.reduce((a, b) => a + b, 0) + GAP.length * (specs.length - 1);\n}\n\n/**\n * Order in which columns give up width when the row does not fit.\n *\n * Prose can lose its tail and stay useful; an identifier cannot — a truncated project id is not\n * something the reader can copy into the next command. So free text yields first and identifiers\n * are only cut when nothing else has slack left.\n */\nconst SHRINK_ORDER: ValueKind[] = ['text', 'date', 'state', 'number', 'boolean', 'id'];\n\n/**\n * Distributes the terminal width across columns.\n *\n * Each column starts at its natural width. When the total overflows, width is reclaimed from the\n * widest column of the most-yielding kind still above the floor, so a 93-character `mimeTypes`\n * column shrinks while the id and state columns beside it stay intact.\n */\nfunction budgetWidths(specs: ColumnSpec[], cells: string[][]): number[] {\n const widths = specs.map((spec, i) =>\n Math.max(displayWidth(headerOf(spec)), ...cells.map((row) => displayWidth(row[i]))),\n );\n const budget = terminalWidth() - GAP.length * (specs.length - 1);\n let total = widths.reduce((a, b) => a + b, 0);\n if (total <= budget) return widths;\n\n for (const kind of SHRINK_ORDER) {\n const candidates = specs\n .map((spec, i) => ({ i, kind: spec.kind ?? 'text' }))\n .filter((c) => c.kind === kind)\n .map((c) => c.i);\n while (total > budget) {\n // Take from the widest candidate each time, so several long columns converge rather than\n // one collapsing to the floor while its neighbour keeps its full width.\n let widest = -1;\n for (const i of candidates) {\n if (widths[i] > MIN_COLUMN_WIDTH && (widest < 0 || widths[i] > widths[widest])) widest = i;\n }\n if (widest < 0) break;\n widths[widest] -= 1;\n total -= 1;\n }\n if (total <= budget) break;\n }\n return widths;\n}\n\nfunction pad(text: string, width: number): string {\n const deficit = width - displayWidth(text);\n return deficit > 0 ? text + ' '.repeat(deficit) : text;\n}\n\n/** Off a TTY an absent value is an empty field, not a dash a script would have to strip. */\nfunction forPipe(value: unknown, spec: ColumnSpec): string {\n const rendered = stripAnsi(renderValue(value, spec.kind ?? inferKind(spec.key), true));\n return rendered === ABSENT ? '' : rendered;\n}\n","import type { ValueKind } from './values.js';\n\n/**\n * A declared column.\n *\n * Call sites used to pass a bare `string[]` of keys plus an optional `dateColumns` list. That\n * optional list was wired into exactly one command group, so every other table rendered whatever\n * the API happened to send. Declaring the kind alongside the key removes the choice: a column is\n * described once, and the renderer decides how it looks.\n */\nexport interface ColumnSpec {\n /** Property to read from each row. */\n key: string;\n /** Header text. Defaults to a humanised form of `key`. */\n header?: string;\n /** How the value is rendered. Defaults to `text`. */\n kind?: ValueKind;\n /** Hard cap on rendered width, in cells, before the shared width budget is applied. */\n maxWidth?: number;\n}\n\n/** Accepts either the declared form or a bare key, so short call sites stay short. */\nexport type ColumnInput = ColumnSpec | string;\n\nexport function normalizeColumns(columns: readonly ColumnInput[]): ColumnSpec[] {\n return columns.map((c) => (typeof c === 'string' ? { key: c } : c));\n}\n\n/** `createdAt` -> `created at`, `projectId` -> `project id`, `last_run` -> `last run`. */\nexport function humanizeKey(key: string): string {\n return key\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .toLowerCase();\n}\n\n/** Words a reader expects in capitals: `projectId` reads \"Project ID\", not \"Project id\". */\nconst ACRONYMS = new Map([\n ['id', 'ID'], ['ids', 'IDs'], ['url', 'URL'], ['urls', 'URLs'], ['api', 'API'], ['uuid', 'UUID'],\n ['csv', 'CSV'], ['json', 'JSON'], ['cpu', 'CPU'], ['utm', 'UTM'], ['oidc', 'OIDC'], ['mcp', 'MCP'],\n]);\n\n/**\n * The label a record line shows for a property: `latestRunState` -> `Latest run state`,\n * `projectId` -> `Project ID`. A record is read line by line, so its labels are sentence-cased\n * words rather than the camelCase keys the API happens to use.\n */\nexport function recordLabel(key: string): string {\n const words = humanizeKey(key).split(' ').filter((w) => w.length > 0).map((w) => ACRONYMS.get(w) ?? w);\n const sentence = words.join(' ');\n return sentence.charAt(0).toUpperCase() + sentence.slice(1);\n}\n\nexport function headerOf(spec: ColumnSpec): string {\n return spec.header ?? humanizeKey(spec.key);\n}\n\n/**\n * Infers a kind from a property name for the ad-hoc case where a command renders a whole DTO\n * without declaring columns. It is a fallback, not a substitute for declaring: it catches the\n * common suffixes so a previously-unformatted `…At` field cannot regress to raw epoch millis.\n */\nexport function inferKind(key: string): ValueKind {\n const k = key.toLowerCase();\n // Suffix tests run against the original casing so the camelCase boundary is real: `createdAt`\n // is an instant, `format` is not, even though both end in the letters \"at\".\n if (/[a-z](At|Date|Time|Timestamp)$/.test(key) || DATE_KEYS.has(k)) return 'date';\n if (/[a-z](State|Status)$/.test(key) || k === 'state' || k === 'status') return 'state';\n if (/[a-z]Ids?$/.test(key) || k === 'id') return 'id';\n return 'text';\n}\n\n/** Instant-valued properties whose names carry no camelCase suffix to key off. */\nconst DATE_KEYS = new Set([\n 'created', 'modified', 'started', 'ended', 'issued', 'requested', 'finished', 'submitted',\n 'renewal', 'expires', 'joined', 'invited', 'removed', 'lastaccessed', 'lastcheck',\n]);\n","/**\n * Terminal capability detection.\n *\n * Every renderer asks these questions instead of reaching for `process.stdout` directly, so a\n * command behaves the same whether it is read by a person or by a pipeline. The distinction that\n * matters is not \"does the terminal support colour\" but \"is a human watching\": a human gets\n * aligned columns, rules and a redrawing progress line; a pipe gets stable, greppable rows and\n * append-only progress that survives being written to a log file.\n */\n\n/** True when stdout is attached to a terminal a person is looking at. */\nexport function isInteractive(): boolean {\n return Boolean(process.stdout.isTTY) && process.env.TERM !== 'dumb';\n}\n\n/**\n * Usable width for rendered output. Falls back to 80 off a TTY so a redirected run produces the\n * same layout every time rather than one that depends on the terminal that happened to launch it.\n */\nexport function terminalWidth(): number {\n const columns = process.stdout.columns;\n if (!columns || !Number.isFinite(columns)) return 80;\n // Leave a column free: some terminals wrap eagerly when text reaches the last cell.\n return Math.max(40, columns - 1);\n}\n\n/** Number of visible cells a string occupies, ignoring SGR escape sequences. */\nexport function displayWidth(text: string): number {\n return stripAnsi(text).length;\n}\n\n// Matches SGR sequences (ESC [ ... m), which is all chalk emits. Built from an escape\n// string rather than a literal so the source stays free of control characters.\nconst ANSI_PATTERN = new RegExp('\\\\u001B\\\\[[0-9;]*m', 'g');\n\nexport function stripAnsi(text: string): string {\n return text.replace(ANSI_PATTERN, '');\n}\n\n/**\n * Truncates to `width` visible cells, appending an ellipsis when it had to cut. Escape sequences\n * are dropped rather than sliced, since a half-written sequence would bleed colour into the rest\n * of the line.\n */\nexport function truncate(text: string, width: number): string {\n const plain = stripAnsi(text);\n if (plain.length <= width) return text;\n if (width <= 1) return plain.slice(0, Math.max(0, width));\n return plain.slice(0, width - 1) + '…';\n}\n\n/** Wraps to `width` visible cells, breaking on whitespace where possible. */\nexport function wrap(text: string, width: number): string[] {\n const out: string[] = [];\n for (const paragraph of text.split('\\n')) {\n if (paragraph.length <= width) {\n out.push(paragraph);\n continue;\n }\n let line = '';\n for (const word of paragraph.split(/(\\s+)/)) {\n if (line.length + word.length <= width) {\n line += word;\n continue;\n }\n if (line.trim()) out.push(line.trimEnd());\n // A single word longer than the column is hard-split rather than allowed to overflow.\n let rest = word.trimStart();\n while (rest.length > width) {\n out.push(rest.slice(0, width));\n rest = rest.slice(width);\n }\n line = rest;\n }\n if (line.trim() || out.length === 0) out.push(line.trimEnd());\n }\n return out;\n}\n","import chalk from 'chalk';\n\n/**\n * How a single value is rendered for a human reader.\n *\n * The CLI previously decided this per call site, which is why the same kind of value appeared\n * three different ways: `project get` printed an instant as `1786743661799`, `entity list` printed\n * one as `2026-08-14T22:34:03.914Z`, and `invoice list` managed both in adjacent columns of one\n * table. Rendering is centralised here and selected by a declared column type (see `columns.ts`)\n * so a call site cannot forget to ask for it.\n */\nexport type ValueKind =\n /** Free text. */\n | 'text'\n /** An identifier — dimmed, since it is rarely what the reader is scanning for. */\n | 'id'\n /** An instant, as epoch millis or an ISO-8601 string. */\n | 'date'\n /** A count or measure. */\n | 'number'\n /** A lifecycle state, coloured by outcome. */\n | 'state'\n /** A yes/no flag. */\n | 'boolean';\n\n/** Placeholder for a value the API did not supply. */\nexport const ABSENT = '—';\n\n/**\n * `plain` renders for a pipe rather than a person: no colour, no thousands separators, and an\n * instant without its \"(3m ago)\" suffix. A reader benefits from all three; `| awk '{print $2}'`\n * does not, and `8,607` is not a number any longer.\n */\nexport function renderValue(value: unknown, kind: ValueKind = 'text', plain = false): string {\n const dim = (text: string) => (plain ? text : chalk.dim(text));\n if (value === null || value === undefined || value === '') return dim(ABSENT);\n switch (kind) {\n case 'id':\n return dim(String(value));\n case 'date':\n return plain ? formatInstantAbsolute(value) : formatInstant(value);\n case 'number':\n return renderNumber(value, plain);\n case 'state':\n return plain ? String(value) : renderState(String(value));\n case 'boolean':\n return renderBoolean(value, plain);\n case 'text':\n default:\n if (typeof value === 'boolean') return renderBoolean(value, plain);\n if (typeof value === 'number') return renderNumber(value, plain);\n if (Array.isArray(value)) return renderArray(value, plain, dim);\n if (typeof value === 'object') return renderObject(value as Record<string, unknown>, plain, dim);\n return String(value);\n }\n}\n\nfunction renderNumber(value: unknown, plain: boolean): string {\n const text = typeof value === 'number' && !plain ? formatNumber(value) : String(value);\n return plain ? text : chalk.cyan(text);\n}\n\n/**\n * A list of scalars reads best comma-separated; a list of objects has to be serialised, since\n * `String({})` is `[object Object]` and tells the reader nothing.\n */\nfunction renderArray(value: unknown[], plain: boolean, dim: (t: string) => string): string {\n if (value.length === 0) return dim(ABSENT);\n const allScalar = value.every((v) => v === null || typeof v !== 'object');\n return allScalar ? value.map(String).join(', ') : JSON.stringify(value);\n}\n\n/**\n * A map of scalars reads as `key: value` pairs; an empty one is absent, not `{}`. Anything deeper\n * is serialised.\n */\nfunction renderObject(value: Record<string, unknown>, plain: boolean, dim: (t: string) => string): string {\n const entries = Object.entries(value);\n if (entries.length === 0) return dim(ABSENT);\n const allScalar = entries.every(([, v]) => v === null || typeof v !== 'object');\n return allScalar ? entries.map(([k, v]) => `${k}: ${String(v)}`).join(', ') : JSON.stringify(value);\n}\n\nfunction renderBoolean(value: unknown, plain: boolean): string {\n const truthy = value === true || value === 'true';\n if (plain) return truthy ? 'yes' : 'no';\n return truthy ? chalk.green('yes') : chalk.dim('no');\n}\n\n/** Thousands separators, so a seven-digit credit balance can be read at a glance. */\nexport function formatNumber(value: number): string {\n if (!Number.isFinite(value)) return String(value);\n if (!Number.isInteger(value)) return String(value);\n return value.toLocaleString('en-US');\n}\n\n/**\n * Renders an instant as `YYYY-MM-DD HH:MM` in local time, followed by how long ago it was when\n * that is the more useful half. Accepts epoch millis (what most of the platform sends), epoch\n * seconds, and ISO-8601 strings; anything it cannot parse is passed through untouched rather than\n * replaced with a wrong date.\n */\nexport function formatInstant(value: unknown): string {\n const date = toDate(value);\n if (!date) return String(value);\n const absolute = formatLocal(date);\n const relative = formatRelative(date.getTime());\n return relative ? `${absolute} ${chalk.dim(`(${relative})`)}` : absolute;\n}\n\n/** The absolute half alone, for places that render their own suffix. */\nexport function formatInstantAbsolute(value: unknown): string {\n const date = toDate(value);\n return date ? formatLocal(date) : String(value);\n}\n\nfunction toDate(value: unknown): Date | null {\n if (value === null || value === undefined || value === '') return null;\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n if (typeof value === 'number') {\n // Values below this threshold are seconds, not millis: 10^11 ms is the year 5138, while\n // 10^11 s is well past any plausible timestamp, so the split is unambiguous in practice.\n const millis = value < 100_000_000_000 && value > 0 ? value * 1000 : value;\n const d = new Date(millis);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n if (typeof value === 'string') {\n // A bare date (`2022-11-01`) is already reader-facing; leave it alone.\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) return null;\n if (/^\\d+$/.test(value)) return toDate(Number(value));\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? null : d;\n }\n return null;\n}\n\nfunction formatLocal(date: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0');\n return (\n `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +\n `${pad(date.getHours())}:${pad(date.getMinutes())}`\n );\n}\n\n/** `3m ago` / `in 2h` / null when the instant is far enough away that the absolute date suffices. */\nexport function formatRelative(millis: number, now = Date.now()): string | null {\n const delta = now - millis;\n const abs = Math.abs(delta);\n if (abs < 30_000) return 'just now';\n if (abs > 180 * 24 * 60 * 60 * 1000) return null;\n const span = formatDuration(abs);\n return delta >= 0 ? `${span} ago` : `in ${span}`;\n}\n\n/** Compact duration: `45s`, `12m 30s`, `3h 05m`, `2d 4h`. */\nexport function formatDuration(millis: number): string {\n const seconds = Math.floor(millis / 1000);\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`;\n const days = Math.floor(hours / 24);\n return `${days}d ${hours % 24}h`;\n}\n\n/**\n * A duration in its two largest units with spaced unit words: `45 sec`, `12 min`, `3 h 5 min`,\n * `1 d 4 h`. This is the form the web app prints for a run's elapsed time, what remains of its\n * budget and how long it took, so the analysis commands use it and a reader sees one figure\n * whichever surface they are on. {@link formatDuration} stays the compact form for the rest of\n * the CLI.\n */\nexport function formatDurationPrecise(millis: number): string {\n const total = Math.max(0, Math.trunc(millis));\n const days = Math.floor(total / 86_400_000);\n const hours = Math.floor(total / 3_600_000) % 24;\n const minutes = Math.floor(total / 60_000) % 60;\n const seconds = Math.floor(total / 1000) % 60;\n if (days > 0) return hours > 0 ? `${days} d ${hours} h` : `${days} d`;\n if (hours > 0) return minutes > 0 ? `${hours} h ${minutes} min` : `${hours} h`;\n if (minutes > 0) return `${minutes} min`;\n if (seconds > 0) return `${seconds} sec`;\n return `${total} ms`;\n}\n\nconst GOOD_STATES = new Set([\n 'COMPLETED', 'SUCCEEDED', 'SUCCESS', 'ACTIVE', 'UP', 'OPERATIONAL', 'PAID', 'RESOLVED', 'OK',\n]);\nconst BAD_STATES = new Set([\n 'FAILED', 'FAILURE', 'ERROR', 'DOWN', 'CANCELLED', 'CANCELED', 'EXPIRED', 'REVOKED', 'UNPAID',\n]);\nconst BUSY_STATES = new Set([\n 'RUNNING', 'QUEUED', 'DISPATCHING', 'PENDING', 'IN_PROGRESS', 'DEGRADED', 'OPEN', 'PROCESSING',\n]);\n\n/** Colours a lifecycle state by outcome so a long list can be scanned without reading it. */\nexport function renderState(state: string): string {\n const key = state.toUpperCase();\n if (GOOD_STATES.has(key)) return chalk.green(state);\n if (BAD_STATES.has(key)) return chalk.red(state);\n if (BUSY_STATES.has(key)) return chalk.yellow(state);\n return state;\n}\n","import { headerOf, inferKind, normalizeColumns, type ColumnInput, type ColumnSpec } from './columns.js';\nimport { renderValue, type ValueKind } from './values.js';\n\n/**\n * Tab-separated output for scripts.\n *\n * Unlike human mode this never colours, never pads and never truncates. Instants are still\n * normalised to a readable absolute form rather than passed through as raw epoch millis, because\n * `--output table` is a reporting format; a caller that wants the wire values uses `--output json`.\n */\nexport function formatTable(data: unknown, columns?: readonly ColumnInput[]): void {\n if (Array.isArray(data)) {\n // An empty list used to print nothing at all, which is indistinguishable from a command that\n // failed silently. The header alone says \"this query ran and matched nothing\".\n const specs: ColumnSpec[] = columns\n ? normalizeColumns(columns)\n : Object.keys((data[0] as Record<string, unknown>) ?? {}).map((key) => ({ key }));\n if (specs.length > 0) console.log(specs.map((s) => headerOf(s)).join('\\t'));\n for (const row of data as Record<string, unknown>[]) {\n console.log(specs.map((s) => cell(row[s.key], s.kind ?? inferKind(s.key))).join('\\t'));\n }\n } else if (data && typeof data === 'object') {\n for (const [key, value] of Object.entries(data as Record<string, unknown>)) {\n console.log(`${key}\\t${cell(value, inferKind(key))}`);\n }\n } else {\n console.log(String(data));\n }\n}\n\nfunction cell(value: unknown, kind: ValueKind): string {\n if (value === null || value === undefined) return '';\n return renderValue(value, kind, true);\n}\n","import { formatHuman } from './human.js';\nimport { formatJson } from './json.js';\nimport { formatTable } from './table.js';\nimport type { ColumnInput } from './columns.js';\n\nexport type OutputFormat = 'human' | 'json' | 'table';\n\nexport interface FormatOptions {\n format: OutputFormat;\n /**\n * Columns to render, in order. Each may declare a `kind` so the renderer knows an instant from\n * an identifier; see `columns.ts`. Omit to render every property of the payload.\n */\n columns?: readonly ColumnInput[];\n}\n\nexport function format(data: unknown, options: FormatOptions): void {\n switch (options.format) {\n case 'json':\n formatJson(data);\n break;\n case 'table':\n formatTable(data, options.columns);\n break;\n case 'human':\n default:\n formatHuman(data, options.columns);\n break;\n }\n}\n\nexport type { ColumnInput, ColumnSpec } from './columns.js';\nexport { formatInstant, formatDuration, formatDurationPrecise, formatNumber } from './values.js';\n","import { Command, type Option } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { type OutputFormat, format } from '../../output/formatter.js';\nimport type { ApiTokenResourceType, ApiTokenScope } from '../../client/types/admin.js';\nimport { success } from '../../output/messages.js';\n\nconst VALID_RESOURCE_TYPES: ApiTokenResourceType[] = ['project', 'team', 'user'];\n\n/**\n * `--resource` is required for a project or a team token and not for a personal one, whose resource\n * is the caller's own account. Commander knows only \"always required\", so the create command lets a\n * missing `--resource` pass when the type is `user`; the check runs after the options are parsed.\n */\nfunction requireResourceUnlessPersonal(create: Command): void {\n const internals = create as unknown as { missingMandatoryOptionValue(option: Option): void };\n const report = internals.missingMandatoryOptionValue.bind(create);\n internals.missingMandatoryOptionValue = (option: Option) => {\n const type = String(create.getOptionValue('resourceType') ?? '').trim().toLowerCase();\n if (option.attributeName() === 'resource' && type === 'user') return;\n report(option);\n };\n}\n\nexport const VALID_SCOPES: ApiTokenScope[] = [\n 'project:read',\n 'project:write',\n 'storage:read',\n 'storage:write',\n 'evaluation:read',\n 'evaluation:execute',\n];\n\nconst TOKEN_CREATE_HELP = `\nA project token reaches one project, a team token the projects of one team. A personal token\n(--resource-type user) acts for your own account across the projects you can reach, limited by\nits scopes. No API token reaches account settings: password, sign-in methods, billing and tokens.\n\n $ diafunc auth token create --name ci --resource <projectId> --scopes project:read,storage:read\n $ diafunc auth token create --name assistant --resource-type user --scopes project:read,project:write\n`;\n\nexport function registerTokenCommands(parent: Command): void {\n const token = parent\n .command('token')\n .description('Manage API tokens');\n\n const create = token\n .command('create')\n .description('Create a new API token for a project, a team, or your own account')\n .requiredOption('--name <name>', 'Token name')\n .requiredOption('--resource <id>', 'Project or team ID (not needed with --resource-type user)')\n .requiredOption('--scopes <scopes>', `Comma-separated scopes: ${VALID_SCOPES.join(', ')}`)\n .option('--resource-type <type>', `Resource type: ${VALID_RESOURCE_TYPES.join(', ')}`, 'project')\n .option('--days <days>', 'Validity in days (default: 365)', '365')\n .addHelpText('after', TOKEN_CREATE_HELP);\n requireResourceUnlessPersonal(create);\n create\n .action(async (options, cmd) => {\n try {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? config.defaults.output ?? 'human';\n\n const resourceType = options.resourceType.trim().toLowerCase() as ApiTokenResourceType;\n if (!VALID_RESOURCE_TYPES.includes(resourceType)) {\n console.error(\n chalk.red(`Invalid resource type: \"${options.resourceType}\".`),\n `Valid resource types: ${VALID_RESOURCE_TYPES.join(', ')}`,\n );\n process.exit(1);\n }\n\n const scopes = options.scopes.split(',').map((s: string) => s.trim()) as ApiTokenScope[];\n for (const scope of scopes) {\n if (!VALID_SCOPES.includes(scope)) {\n console.error(chalk.red(`Invalid scope: \"${scope}\".`), `Valid scopes: ${VALID_SCOPES.join(', ')}`);\n process.exit(1);\n }\n }\n\n const api = createApiClient();\n const result = await api.admin.createApiToken({\n name: options.name,\n // A personal token's resource is the caller's own account, which the platform fills in.\n // A given id is passed on; the platform refuses one that is not the caller's.\n ...(options.resource !== undefined ? { resourceId: options.resource } : {}),\n resourceType,\n scopes,\n validityDays: parseInt(options.days, 10),\n });\n\n if (outputFormat === 'human') {\n success('API token created.');\n console.log();\n console.log(` Token: ${chalk.bold(result.token)}`);\n console.log(` Token ID: ${result.tokenId}`);\n console.log(` Name: ${result.name}`);\n console.log(` Expires: ${result.expiresAt}`);\n console.log();\n console.log(chalk.yellow('Save this token. It will not be shown again.'));\n } else {\n format(result, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n token\n .command('list')\n .description('List API tokens')\n .option('--resource <id>', 'Filter by resource ID')\n .action(async (options, cmd) => {\n try {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? config.defaults.output ?? 'human';\n\n const api = createApiClient();\n const tokens = options.resource\n ? await api.admin.getApiTokensByResource(options.resource)\n : await api.admin.getApiTokens();\n\n format(tokens, {\n format: outputFormat,\n columns: ['tokenId', 'name', 'resourceType', 'resourceId', 'scopes', 'createdAt', 'expiresAt'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n token\n .command('revoke')\n .description('Revoke an API token')\n .argument('<tokenId>', 'Token ID to revoke')\n .action(async (tokenId: string) => {\n try {\n const api = createApiClient();\n await api.admin.revokeApiToken(tokenId);\n success(`Token ${tokenId} revoked.`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import type { HttpClient } from '../http.js';\nimport type {\n AnalysisColumn,\n AnalysisDepth,\n AnalysisDepthDefault,\n AnalysisNavigation,\n AnalysisPreset,\n AnalysisResponse,\n AnalysisRun,\n AnalysisRunOutput,\n AnalysisTrigger,\n AttachDataSourceRequest,\n CreateAnalysisRequest,\n NewAnalysisRequest,\n CreateAnalysisTriggerRequest,\n OptAnalysisPreset,\n OptAnalysisResponse,\n OptAnalysisRun,\n PatchBudgetRequest,\n PatchConfirmedInputsRequest,\n PatchDescriptionRequest,\n PatchInputExclusionsRequest,\n PatchHoursRequest,\n PatchIntroductionRequest,\n PatchNameRequest,\n PatchQuestionsRequest,\n PatchSegmentRequest,\n PatchIntentRequest,\n PatchShapeExpectationsRequest,\n PatchRequestedPairsRequest,\n PatchFocusFamiliesRequest,\n IntentInterpretRequest,\n IntentInterpretation,\n IntentDecisionsRequest,\n PatchTargetsRequest,\n PatchVisibilityRequest,\n UpdateAnalysisRequest,\n UpdateAnalysisTriggerRequest,\n UploadDataInlineRequest,\n AnalysisSource,\n TableShape,\n CombinedRecipe,\n CombinedPlan,\n AnalysisDataBuild,\n UploadDataUrlRequest,\n DataImportStatus,\n PublicAnalysesPage,\n} from '../types/analysis.js';\n\nconst SERVICE = 'analyses';\nconst RUNS_SERVICE = 'runs';\nconst PRESETS_SERVICE = 'analysis-presets';\nconst TRIGGERS_SERVICE = 'triggers';\nconst PUBLIC_SERVICE = 'public-analyses';\n\nexport function createAnalysisService(client: HttpClient) {\n return {\n // ----- Lifecycle: create / read / replace / delete --------------------------------\n\n async create(request: NewAnalysisRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'POST',\n service: SERVICE,\n path: '/',\n body: request,\n });\n },\n\n async update(analysisId: string, request: UpdateAnalysisRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PUT',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}`,\n body: request,\n });\n },\n\n async delete(analysisId: string): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'DELETE',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}`,\n });\n },\n\n async getLast(): Promise<OptAnalysisResponse> {\n return client.request<OptAnalysisResponse>({\n method: 'GET',\n service: SERVICE,\n path: '/last',\n });\n },\n\n async getRecent(count = 20): Promise<AnalysisResponse[]> {\n return client.request<AnalysisResponse[]>({\n method: 'GET',\n service: SERVICE,\n path: '/recent',\n query: { count },\n });\n },\n\n async get(analysisId: string): Promise<OptAnalysisResponse> {\n return client.request<OptAnalysisResponse>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}`,\n });\n },\n\n /** The depth the platform would give the caller's next analysis if its creation named none. */\n /** The depths an analysis is offered at, shallowest first: the one list every surface shows. */\n async getDepths(): Promise<AnalysisDepth[]> {\n return client.request<AnalysisDepth[]>({\n method: 'GET',\n service: SERVICE,\n path: '/depths',\n });\n },\n\n async getDepthDefault(): Promise<AnalysisDepthDefault> {\n return client.request<AnalysisDepthDefault>({\n method: 'GET',\n service: SERVICE,\n path: '/depth-default',\n });\n },\n\n // ----- Public analyses: readable without signing in --------------------------------\n\n /** One page of the public analyses. `cursor` is the `nextCursor` of the page before. */\n async listPublic(page: { cursor?: string; limit?: number } = {}): Promise<PublicAnalysesPage> {\n return client.request<PublicAnalysesPage>({\n method: 'GET',\n service: PUBLIC_SERVICE,\n path: '',\n query: { cursor: page.cursor, limit: page.limit },\n });\n },\n\n // ----- Typed PATCH per editable field --------------------------------------------\n\n async patchName(analysisId: string, request: PatchNameRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/name`,\n body: request,\n });\n },\n\n async patchDescription(analysisId: string, request: PatchDescriptionRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/description`,\n body: request,\n });\n },\n\n async patchVisibility(analysisId: string, request: PatchVisibilityRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/visibility`,\n body: request,\n });\n },\n\n async patchIntroduction(analysisId: string, request: PatchIntroductionRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/introduction`,\n body: request,\n });\n },\n\n async patchHours(analysisId: string, request: PatchHoursRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/hours`,\n body: request,\n });\n },\n\n async patchBudget(analysisId: string, request: PatchBudgetRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/budget`,\n body: request,\n });\n },\n\n async patchTargets(analysisId: string, request: PatchTargetsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/targets`,\n body: request,\n });\n },\n\n async patchQuestions(analysisId: string, request: PatchQuestionsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/questions`,\n body: request,\n });\n },\n\n async patchInputExclusions(analysisId: string, request: PatchInputExclusionsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/input-exclusions`,\n body: request,\n });\n },\n\n async patchConfirmedInputs(analysisId: string, request: PatchConfirmedInputsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/confirmed-inputs`,\n body: request,\n });\n },\n\n async patchSegment(analysisId: string, request: PatchSegmentRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/segment`,\n body: request,\n });\n },\n\n // ----- The owner's notes (\"What you know and what matters\") ------------------------\n\n /** Stores the notes only; reading them into proposals is {@link interpretIntent}. */\n async patchIntent(analysisId: string, request: PatchIntentRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/intent`,\n body: request,\n });\n },\n\n /** Reads the notes against the setup in the body; nothing is applied. */\n async interpretIntent(\n analysisId: string,\n request: IntentInterpretRequest,\n options: { force?: boolean; refine?: boolean } = {},\n ): Promise<IntentInterpretation> {\n const query: Record<string, string> = {};\n if (options.force) query.force = 'true';\n if (options.refine) query.refine = 'true';\n return client.request<IntentInterpretation>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/intent/interpretation`,\n query,\n body: request,\n });\n },\n\n async getIntentInterpretation(analysisId: string): Promise<IntentInterpretation> {\n return client.request<IntentInterpretation>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/intent/interpretation`,\n });\n },\n\n /** Confirms (applies), declines or re-proposes proposals of the stored interpretation. */\n async decideIntentItems(analysisId: string, request: IntentDecisionsRequest): Promise<IntentInterpretation> {\n return client.request<IntentInterpretation>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/intent/interpretation/items`,\n body: request,\n });\n },\n\n async patchShapeExpectations(analysisId: string, request: PatchShapeExpectationsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/shape-expectations`,\n body: request,\n });\n },\n\n async patchRequestedPairs(analysisId: string, request: PatchRequestedPairsRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/requested-pairs`,\n body: request,\n });\n },\n\n async patchFocusFamilies(analysisId: string, request: PatchFocusFamiliesRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/focus-families`,\n body: request,\n });\n },\n\n // ----- Data ingest ----------------------------------------------------------------\n\n async uploadDataMultipart(analysisId: string, formData: FormData): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/data`,\n rawBody: formData,\n });\n },\n\n // ----- Several files: sources ------------------------------------------------------\n\n async addSource(analysisId: string, formData: FormData): Promise<AnalysisSource> {\n return client.request<AnalysisSource>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources`,\n rawBody: formData,\n });\n },\n\n /**\n * Makes a data source one of the files the analysis's data is built from: the platform fetches once and\n * stores the file as a source. The data is not built here; see `planSources` and `buildSources`.\n */\n async attachDataSource(analysisId: string, body: AttachDataSourceRequest): Promise<AnalysisSource> {\n return client.request<AnalysisSource>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/data-source`,\n body,\n });\n },\n\n async listSources(analysisId: string): Promise<AnalysisSource[]> {\n return client.request<AnalysisSource[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources`,\n });\n },\n\n /** Sets whether a source is read as uploaded, rather than through the reshape its shape suggests. */\n async updateSource(analysisId: string, sourceId: string, changes: { asUploaded?: boolean }): Promise<AnalysisSource> {\n return client.request<AnalysisSource>({\n method: 'PATCH',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/${encodeURIComponent(sourceId)}`,\n body: changes,\n });\n },\n\n async removeSource(analysisId: string, sourceId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/${encodeURIComponent(sourceId)}`,\n });\n },\n\n /**\n * The tables of the analysis's files that do not look like one row per observation, read from their\n * first rows only. Empty when the data is as it should be.\n */\n async sourceShapes(analysisId: string): Promise<TableShape[]> {\n return client.request<TableShape[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/shapes`,\n });\n },\n\n /** What building from the sources would yield: for `recipe`, or for the platform's proposal when it is null. */\n async planSources(analysisId: string, recipe: CombinedRecipe | null): Promise<CombinedPlan> {\n return client.request<CombinedPlan>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/plan`,\n body: recipe,\n });\n },\n\n async buildSources(analysisId: string, recipe: CombinedRecipe): Promise<AnalysisDataBuild> {\n return client.request<AnalysisDataBuild>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/sources/build`,\n body: recipe,\n });\n },\n\n async uploadDataUrl(analysisId: string, request: UploadDataUrlRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/data/url`,\n body: request,\n });\n },\n\n async uploadDataInline(analysisId: string, request: UploadDataInlineRequest): Promise<AnalysisResponse> {\n return client.request<AnalysisResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/data/inline`,\n body: request,\n });\n },\n\n /** How the import of the analysis's data stands. `dataImport` null means it finished and the counts are final. */\n async getDataImport(analysisId: string): Promise<DataImportStatus> {\n return client.request<DataImportStatus>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/data/import`,\n });\n },\n\n /** Stops the running import. The platform waits a while for it to end and answers `STOPPING` when it has not yet. */\n async stopDataImport(analysisId: string): Promise<DataImportStatus> {\n return client.request<DataImportStatus>({\n method: 'DELETE',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/data/import`,\n });\n },\n\n async getColumns(analysisId: string): Promise<AnalysisColumn[]> {\n return client.request<AnalysisColumn[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/columns`,\n });\n },\n\n async getNavigation(analysisId: string): Promise<AnalysisNavigation> {\n return client.request<AnalysisNavigation>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/navigation`,\n });\n },\n\n /**\n * The report as Markdown. Without `chapter`: the summary and the outline of chapter titles.\n * `chapter` is a title, or a path of titles separated by `>` (`Age > Correlation`). `maxBytes` is\n * clamped by the platform to 4-256 KiB, 32 KiB when absent. A chapter that does not fit comes in\n * parts; `part` (from 1) names the one to read and is ignored without `chapter`.\n */\n async getReportMarkdown(\n analysisId: string,\n options: { chapter?: string; part?: number; maxBytes?: number } = {},\n ): Promise<string> {\n return client.request<string>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/report.md`,\n query: { chapter: options.chapter, part: options.part, maxBytes: options.maxBytes },\n });\n },\n\n /** The model of one target as source code or a formula in `language`; `target` is needed when there are several. */\n async exportModel(analysisId: string, options: { language: string; target?: string }): Promise<string> {\n return client.request<string>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/model-export`,\n query: { language: options.language, target: options.target },\n });\n },\n\n // ----- Runs -----------------------------------------------------------------------\n\n async runAnalysis(analysisId: string): Promise<AnalysisRun> {\n return client.request<AnalysisRun>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/runs`,\n });\n },\n\n async getRunsForAnalysis(analysisId: string, count = 20): Promise<AnalysisRun[]> {\n return client.request<AnalysisRun[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/runs`,\n query: { count },\n });\n },\n\n async getRun(runId: string): Promise<OptAnalysisRun> {\n return client.request<OptAnalysisRun>({\n method: 'GET',\n service: RUNS_SERVICE,\n path: `/${encodeURIComponent(runId)}`,\n });\n },\n\n async cancelRun(runId: string): Promise<AnalysisRun> {\n return client.request<AnalysisRun>({\n method: 'POST',\n service: RUNS_SERVICE,\n path: `/${encodeURIComponent(runId)}/cancel`,\n });\n },\n\n async getRunOutputs(analysisId: string, runId: string): Promise<AnalysisRunOutput[]> {\n return client.request<AnalysisRunOutput[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/runs/${encodeURIComponent(runId)}/outputs`,\n });\n },\n\n // ----- Presets --------------------------------------------------------------------\n\n async getPresets(): Promise<AnalysisPreset[]> {\n return client.request<AnalysisPreset[]>({\n method: 'GET',\n service: PRESETS_SERVICE,\n path: '/',\n });\n },\n\n async getPreset(presetId: string): Promise<OptAnalysisPreset> {\n return client.request<OptAnalysisPreset>({\n method: 'GET',\n service: PRESETS_SERVICE,\n path: `/${encodeURIComponent(presetId)}`,\n });\n },\n\n async savePreset(preset: AnalysisPreset): Promise<AnalysisPreset> {\n return client.request<AnalysisPreset>({\n method: 'POST',\n service: PRESETS_SERVICE,\n path: '/',\n body: preset,\n });\n },\n\n async deletePreset(presetId: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: PRESETS_SERVICE,\n path: `/${encodeURIComponent(presetId)}`,\n });\n },\n\n // ----- Triggers -------------------------------------------------------------------\n\n async createTrigger(analysisId: string, body: CreateAnalysisTriggerRequest): Promise<AnalysisTrigger> {\n return client.request<AnalysisTrigger>({\n method: 'POST',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/triggers`,\n body,\n });\n },\n\n async listTriggers(analysisId: string): Promise<AnalysisTrigger[]> {\n return client.request<AnalysisTrigger[]>({\n method: 'GET',\n service: SERVICE,\n path: `/${encodeURIComponent(analysisId)}/triggers`,\n });\n },\n\n async updateTrigger(triggerId: string, body: UpdateAnalysisTriggerRequest): Promise<AnalysisTrigger> {\n return client.request<AnalysisTrigger>({\n method: 'PATCH',\n service: TRIGGERS_SERVICE,\n path: `/${encodeURIComponent(triggerId)}`,\n body,\n });\n },\n\n async deleteTrigger(triggerId: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: TRIGGERS_SERVICE,\n path: `/${encodeURIComponent(triggerId)}`,\n });\n },\n };\n}\n\nexport type AnalysisService = ReturnType<typeof createAnalysisService>;\n","import type { HttpClient } from '../http.js';\nimport type {\n CellMerge,\n CreateDataSourceRequest,\n CreateSkeletonRequest,\n DataSource,\n DataSourceDashboard,\n DataSourceRun,\n Entity,\n EntityBranchRequest,\n EntityReference,\n Event,\n ForkRequest,\n Link,\n LinkDirection,\n MergeRequest,\n ProjectBranchRequest,\n Skeleton,\n StorageExport,\n StorageImport,\n SupportedExportFormatsResponse,\n SupportedImportFormatsResponse,\n BundleExport,\n BundleExportRequest,\n BundleImportPreviewResponse,\n BundleImportResponse,\n TableSnapshot,\n TagTransaction,\n UserDefinedExporter,\n TableSnapshotRequest,\n UpdateDataSourceRequest,\n UpdateSkeletonRequest,\n} from '../types/storage.js';\n\nconst SERVICE = 'storage';\n\nexport interface TableExportOptions {\n compression?: string;\n archive?: string;\n fromRow?: number;\n toRow?: number;\n fromColumn?: number;\n toColumn?: number;\n delimiter?: string;\n quote?: string;\n nullValue?: string;\n quoteAll?: boolean;\n}\n\nfunction enc(s: string): string {\n return encodeURIComponent(s);\n}\n\nfunction entityPath(ref: EntityReference): string {\n return `/${enc(ref.projectId)}/${enc(ref.projectBranch)}/${enc(ref.entityId)}/${enc(ref.entityBranch)}`;\n}\n\nfunction exportTableQuery(options: TableExportOptions): Record<string, string> {\n const query: Record<string, string> = {};\n if (options.compression) query.compression = options.compression;\n if (options.archive) query.archive = options.archive;\n if (options.fromRow !== undefined && options.fromRow !== null) query.fromRow = String(options.fromRow);\n if (options.toRow !== undefined && options.toRow !== null) query.toRow = String(options.toRow);\n if (options.fromColumn !== undefined && options.fromColumn !== null) query.fromColumn = String(options.fromColumn);\n if (options.toColumn !== undefined && options.toColumn !== null) query.toColumn = String(options.toColumn);\n if (options.delimiter !== undefined) query.delimiter = options.delimiter;\n if (options.quote !== undefined) query.quote = options.quote;\n if (options.nullValue !== undefined) query.nullValue = options.nullValue;\n if (options.quoteAll !== undefined) query.quoteAll = String(options.quoteAll);\n return query;\n}\n\nexport function createStorageService(client: HttpClient) {\n return {\n // --- Entities ---\n\n async entityExists(ref: EntityReference): Promise<boolean> {\n return client.request<boolean>({\n method: 'GET',\n service: SERVICE,\n path: `/entities/exists${entityPath(ref)}`,\n });\n },\n\n async getEntity(ref: EntityReference, content = false): Promise<Entity> {\n return client.request<Entity>({\n method: 'GET',\n service: SERVICE,\n path: `/entities/actual${entityPath(ref)}`,\n query: content ? { content: true } : undefined,\n });\n },\n\n async getEntityContent(ref: EntityReference): Promise<Response> {\n return client.requestRaw({\n method: 'GET',\n service: SERVICE,\n path: `/entities/contents/actual${entityPath(ref)}`,\n });\n },\n\n async saveEntities(entities: Entity[]): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: '/entities/actual',\n body: entities,\n });\n },\n\n async deleteEntity(ref: EntityReference): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/entities/actual${entityPath(ref)}`,\n });\n },\n\n async saveEntityContentBase64(ref: EntityReference, base64Content: string): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/entities/contents/actual${entityPath(ref)}`,\n rawBody: base64Content,\n contentType: 'text/plain',\n });\n },\n\n async uploadEntityContent(ref: EntityReference, formData: FormData): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/entities/contents/actual${entityPath(ref)}`,\n rawBody: formData,\n });\n },\n\n async deleteEntityContent(ref: EntityReference): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/entities/contents/actual${entityPath(ref)}`,\n });\n },\n\n async getEntityHistory(ref: EntityReference, version: number): Promise<Entity> {\n return client.request<Entity>({\n method: 'GET',\n service: SERVICE,\n path: `/entities/history${entityPath(ref)}/${version}`,\n });\n },\n\n async getEntityHistoryRange(ref: EntityReference, fromVersion: number, toVersion: number): Promise<Entity[]> {\n return client.request<Entity[]>({\n method: 'GET',\n service: SERVICE,\n path: `/entities/history${entityPath(ref)}/${fromVersion}/${toVersion}`,\n });\n },\n\n async renameEntity(ref: EntityReference, newEntityId: string): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/entities/ids${entityPath(ref)}/${enc(newEntityId)}`,\n });\n },\n\n async revertEntity(ref: EntityReference, version: number): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/entities/revert${entityPath(ref)}/${version}`,\n });\n },\n\n /**\n * Adds tags to an entity and takes others off, in one storage transaction. The platform applies\n * the removals, then the additions, and counts a tag that is already there (or already gone) as\n * nothing to do; nothing else of the entity is touched.\n *\n * A transaction writes an entity that does not exist yet, so a caller that means to change an\n * existing one reads it first.\n */\n async changeEntityTags(ref: EntityReference, change: { addTags?: string[]; removeTags?: string[] }): Promise<void> {\n const transaction: TagTransaction = {\n projectId: ref.projectId,\n projectBranch: ref.projectBranch,\n consistency: 'WEAK',\n entityDeltas: {\n [`${ref.entityId}/${ref.entityBranch}`]: {\n ...(change.addTags?.length ? { addTags: change.addTags } : {}),\n ...(change.removeTags?.length ? { removeTags: change.removeTags } : {}),\n },\n },\n };\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/transactions/',\n body: transaction,\n });\n },\n\n // --- Entity Sets ---\n\n async searchEntityIds(projectId: string, projectBranch: string, body: unknown): Promise<string[]> {\n return client.request<string[]>({\n method: 'POST',\n service: SERVICE,\n path: '/entity-ids/search',\n body,\n });\n },\n\n // --- Linked Entities ---\n\n async getLinkedEntities(direction: string, ref: EntityReference, linkId?: string): Promise<Entity[]> {\n const byLink = linkId ? `/${enc(linkId)}` : '';\n return client.request<Entity[]>({\n method: 'GET',\n service: SERVICE,\n path: `/linked-entities/${enc(direction)}${entityPath(ref)}${byLink}`,\n });\n },\n\n async saveLinkedEntities(ref: EntityReference, linkId: string, entities: Entity[]): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/linked-entities/${enc(ref.projectId)}/${enc(ref.projectBranch)}/${enc(ref.entityId)}/${enc(ref.entityBranch)}/${enc(linkId)}`,\n body: entities,\n });\n },\n\n // --- Links ---\n\n async getLinks(direction: LinkDirection, ref: EntityReference): Promise<Link[]> {\n return client.request<Link[]>({\n method: 'GET',\n service: SERVICE,\n path: `/links/actual/${enc(direction)}${entityPath(ref)}`,\n });\n },\n\n async getLinkIds(direction: LinkDirection, ref: EntityReference): Promise<string[]> {\n return client.request<string[]>({\n method: 'GET',\n service: SERVICE,\n path: `/links/ids/actual/${enc(direction)}${entityPath(ref)}`,\n });\n },\n\n async createLink(\n projectId: string, projectBranch: string,\n sourceEntityId: string, sourceEntityBranch: string,\n linkId: string,\n targetEntityId: string, targetEntityBranch: string,\n link?: Partial<Link>,\n ): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}/${enc(targetEntityId)}/${enc(targetEntityBranch)}`,\n body: link,\n });\n },\n\n async deleteLink(\n projectId: string, projectBranch: string,\n sourceEntityId: string, sourceEntityBranch: string,\n linkId: string,\n targetEntityId?: string, targetEntityBranch?: string,\n ): Promise<void> {\n let path = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;\n if (targetEntityId && targetEntityBranch) {\n path += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;\n }\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path,\n });\n },\n\n // --- Events ---\n\n async getEvents(ref: EntityReference): Promise<Event[]> {\n return client.request<Event[]>({\n method: 'GET',\n service: SERVICE,\n path: `/events/actual${entityPath(ref)}`,\n });\n },\n\n async getEvent(ref: EntityReference, eventId: string, occurrenceId: string): Promise<Event> {\n return client.request<Event>({\n method: 'GET',\n service: SERVICE,\n path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`,\n });\n },\n\n async createEvents(events: Event[]): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/events/',\n body: events,\n });\n },\n\n async consumeEvents(body: unknown): Promise<Event[]> {\n return client.request<Event[]>({\n method: 'POST',\n service: SERVICE,\n path: '/events/consume',\n body,\n });\n },\n\n async deleteEvent(ref: EntityReference, eventId: string, occurrenceId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`,\n });\n },\n\n // --- Tables ---\n\n async getTableSnapshot(ref: EntityReference, request?: TableSnapshotRequest): Promise<TableSnapshot> {\n return client.request<TableSnapshot>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/snapshots`,\n body: request ?? {},\n });\n },\n\n async appendRow(ref: EntityReference): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/rows`,\n });\n },\n\n async insertRow(ref: EntityReference, rowIndex: number): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/rows/${rowIndex}/insert`,\n });\n },\n\n async removeRow(ref: EntityReference, rowIndex: number): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/rows/${rowIndex}`,\n });\n },\n\n async deleteRow(ref: EntityReference, rowIndex: number): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/rows/${rowIndex}/delete`,\n });\n },\n\n async appendColumn(ref: EntityReference): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/columns`,\n });\n },\n\n async insertColumn(ref: EntityReference, columnIndex: number): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/columns/${columnIndex}/insert`,\n });\n },\n\n async removeColumn(ref: EntityReference, columnIndex: number): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/columns/${columnIndex}`,\n });\n },\n\n async deleteColumn(ref: EntityReference, columnIndex: number): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/columns/${columnIndex}/delete`,\n });\n },\n\n async mergeCells(ref: EntityReference, cells: CellMerge[]): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/cells`,\n body: cells,\n });\n },\n\n async removeCell(ref: EntityReference, rowIndex: number, columnIndex: number): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/cells/${rowIndex}/${columnIndex}`,\n });\n },\n\n async clearTable(ref: EntityReference): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/tables${entityPath(ref)}/clear`,\n });\n },\n\n // --- Table Import/Export ---\n\n async importTable(ref: EntityReference, formData: FormData, selection?: string): Promise<string> {\n const query: Record<string, string> = {};\n if (selection) query.selection = selection;\n return client.request<string>({\n method: 'PUT',\n service: SERVICE,\n path: `/table-imports${entityPath(ref)}`,\n query: Object.keys(query).length > 0 ? query : undefined,\n rawBody: formData,\n });\n },\n\n async getSupportedImportFormats(): Promise<SupportedImportFormatsResponse> {\n return client.request<SupportedImportFormatsResponse>({\n method: 'GET',\n service: SERVICE,\n path: `/table-imports/supported-formats`,\n });\n },\n\n async getImport(ref: EntityReference, importId: string): Promise<StorageImport> {\n return client.request<StorageImport>({\n method: 'GET',\n service: SERVICE,\n path: `/imports${entityPath(ref)}/${enc(importId)}`,\n });\n },\n\n /**\n * Async (queue) export. Server returns the exportId as plain text; the\n * caller polls progress via {@code getExport} / {@code listExports}.\n * For streaming bytes back synchronously, use {@link streamExport}.\n */\n async exportTable(ref: EntityReference, format: string, options: TableExportOptions = {}): Promise<string> {\n const query = exportTableQuery(options);\n return client.request<string>({\n method: 'POST',\n service: SERVICE,\n path: `/table-exports${entityPath(ref)}/${enc(format)}`,\n query: Object.keys(query).length > 0 ? query : undefined,\n });\n },\n\n /**\n * Streaming download via the synchronous {@code /stream} endpoint.\n * Server runs the exporter and writes chunk-encoded bytes back; the CLI\n * pipes them straight to a file (no async {@code ExportRow}, no progress\n * polling). Default for {@code diafunc table export} unless {@code\n * --async} is passed.\n */\n async streamExport(ref: EntityReference, format: string, options: TableExportOptions = {}): Promise<Response> {\n const query = exportTableQuery(options);\n return client.requestRaw({\n method: 'POST',\n service: SERVICE,\n path: `/table-exports${entityPath(ref)}/${enc(format)}/stream`,\n query: Object.keys(query).length > 0 ? query : undefined,\n });\n },\n\n async exportTableCsv(ref: EntityReference): Promise<string> {\n return this.exportTable(ref, 'csv');\n },\n\n async exportTableExcel(ref: EntityReference): Promise<string> {\n return this.exportTable(ref, 'excel');\n },\n\n async getSupportedExportFormats(): Promise<SupportedExportFormatsResponse> {\n return client.request<SupportedExportFormatsResponse>({\n method: 'GET',\n service: SERVICE,\n path: `/table-exports/supported-formats`,\n });\n },\n\n /** List all async exports for an entity (see ExportsResource#getExports). */\n async listExports(ref: EntityReference): Promise<StorageExport[]> {\n return client.request<StorageExport[]>({\n method: 'GET',\n service: SERVICE,\n path: `/exports${entityPath(ref)}`,\n });\n },\n\n /**\n * Download the bytes of a completed async export.\n * Path mirrors ExportsResource#getContent: /exports/{entity}/{exportId}/{filename}.\n * The {filename} segment is part of the server URL but is not used for lookup —\n * only exportId determines the row; pass StorageExport.filename verbatim.\n */\n async downloadExport(ref: EntityReference, exportId: string, filename: string): Promise<Response> {\n return client.requestRaw({\n method: 'GET',\n service: SERVICE,\n path: `/exports${entityPath(ref)}/${enc(exportId)}/${enc(filename)}`,\n });\n },\n\n // --- Branches ---\n\n async getProjectBranches(projectId: string): Promise<string[]> {\n return client.request<string[]>({\n method: 'GET',\n service: SERVICE,\n path: `/project-branches/${enc(projectId)}`,\n });\n },\n\n async createProjectBranch(request: ProjectBranchRequest): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/project-branches/',\n body: request,\n });\n },\n\n async deleteProjectBranch(projectId: string, projectBranch: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/project-branches/${enc(projectId)}/${enc(projectBranch)}`,\n });\n },\n\n async getEntityBranches(projectId: string, projectBranch: string, entityId: string): Promise<string[]> {\n return client.request<string[]>({\n method: 'GET',\n service: SERVICE,\n path: `/entity-branches/${enc(projectId)}/${enc(projectBranch)}/${enc(entityId)}`,\n });\n },\n\n async createEntityBranch(request: EntityBranchRequest): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/entity-branches/',\n body: request,\n });\n },\n\n // --- Merge & Fork ---\n\n async merge(request: MergeRequest): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/merge/',\n body: request,\n });\n },\n\n async fork(request: ForkRequest): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/fork/',\n body: request,\n });\n },\n\n // --- Project Search ---\n\n async searchProject(projectId: string, projectBranch: string, body: unknown): Promise<unknown> {\n return client.request<unknown>({\n method: 'POST',\n service: SERVICE,\n path: `/project-searches/${enc(projectId)}/${enc(projectBranch)}`,\n body,\n });\n },\n\n // --- Backups ---\n\n async createShortTermProjectBackup(): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/project/short-term/create',\n });\n },\n\n async createLongTermProjectBackup(): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/project/long-term/create',\n });\n },\n\n async restoreProjectBackup(request: {\n projectId: string; projectBranch: string; bucketName: string; objectName: string;\n }): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/project/restore',\n body: request,\n });\n },\n\n async createShortTermFullBackup(): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/full/short-term/create',\n });\n },\n\n async createLongTermFullBackup(): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/full/long-term/create',\n });\n },\n\n async restoreFullBackup(request: {\n bucketName: string; objectName: string;\n }): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/backups/full/restore',\n body: request,\n });\n },\n\n // --- Event write ops (moved from read-only block) ---\n // NOTE: createEvents / consumeEvents already exist above in the Events section.\n\n // --- User-defined exporters (UDE) ---\n\n async listUserDefinedExporters(): Promise<UserDefinedExporter[]> {\n return client.request<UserDefinedExporter[]>({\n method: 'GET',\n service: SERVICE,\n path: `/table-exporters`,\n });\n },\n\n async registerUserDefinedExporter(request: UserDefinedExporter): Promise<UserDefinedExporter> {\n return client.request<UserDefinedExporter>({\n method: 'POST',\n service: SERVICE,\n path: `/table-exporters`,\n body: request,\n });\n },\n\n async deleteUserDefinedExporter(id: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/table-exporters/${enc(id)}`,\n });\n },\n\n // --- Data sources ---\n\n async createDataSource(request: CreateDataSourceRequest): Promise<DataSource> {\n return client.request<DataSource>({\n method: 'POST',\n service: SERVICE,\n path: `/data-sources`,\n body: request,\n });\n },\n\n async listDataSources(projectId?: string): Promise<DataSource[]> {\n return client.request<DataSource[]>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources`,\n query: projectId ? { projectId } : undefined,\n });\n },\n\n async getDataSourceDashboard(projectId: string): Promise<DataSourceDashboard> {\n return client.request<DataSourceDashboard>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources/dashboard`,\n query: { projectId },\n });\n },\n\n async getDataSource(id: string): Promise<DataSource> {\n return client.request<DataSource>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources/${enc(id)}`,\n });\n },\n\n async updateDataSource(id: string, request: UpdateDataSourceRequest): Promise<DataSource> {\n return client.request<DataSource>({\n method: 'PUT',\n service: SERVICE,\n path: `/data-sources/${enc(id)}`,\n body: request,\n });\n },\n\n async deleteDataSource(id: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/data-sources/${enc(id)}`,\n });\n },\n\n async refreshDataSource(id: string): Promise<DataSourceRun> {\n return client.request<DataSourceRun>({\n method: 'POST',\n service: SERVICE,\n path: `/data-sources/${enc(id)}/refresh`,\n });\n },\n\n async listDataSourceRuns(id: string, limit?: number): Promise<DataSourceRun[]> {\n return client.request<DataSourceRun[]>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources/${enc(id)}/runs`,\n query: limit !== undefined ? { limit } : undefined,\n });\n },\n\n async getDataSourceRun(id: string, runId: string): Promise<DataSourceRun> {\n return client.request<DataSourceRun>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources/${enc(id)}/runs/${enc(runId)}`,\n });\n },\n\n async listDataSourceConnectorTypes(): Promise<string[]> {\n return client.request<string[]>({\n method: 'GET',\n service: SERVICE,\n path: `/data-sources/types`,\n });\n },\n\n // --- Skeletons ---\n\n async createSkeleton(request: CreateSkeletonRequest): Promise<Skeleton> {\n return client.request<Skeleton>({\n method: 'POST',\n service: SERVICE,\n path: `/skeletons`,\n body: request,\n });\n },\n\n async listSkeletons(projectId: string): Promise<Skeleton[]> {\n return client.request<Skeleton[]>({\n method: 'GET',\n service: SERVICE,\n path: `/skeletons`,\n query: { projectId },\n });\n },\n\n async getSkeleton(id: string): Promise<Skeleton> {\n return client.request<Skeleton>({\n method: 'GET',\n service: SERVICE,\n path: `/skeletons/${enc(id)}`,\n });\n },\n\n async updateSkeleton(id: string, request: UpdateSkeletonRequest): Promise<Skeleton> {\n return client.request<Skeleton>({\n method: 'PUT',\n service: SERVICE,\n path: `/skeletons/${enc(id)}`,\n body: request,\n });\n },\n\n async deleteSkeleton(id: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/skeletons/${enc(id)}`,\n });\n },\n\n // --- Notebook bundles ---\n\n /** Queue an async bundle export; returns the bundleId for polling. */\n async exportBundle(projectId: string, projectBranch: string, request: BundleExportRequest): Promise<string> {\n return client.request<string>({\n method: 'POST',\n service: SERVICE,\n path: `/notebook-bundles/${enc(projectId)}/${enc(projectBranch)}/export`,\n body: request,\n });\n },\n\n /** Streaming download via the synchronous /stream endpoint; pipe bytes to disk. */\n async streamBundle(projectId: string, projectBranch: string, request: BundleExportRequest): Promise<Response> {\n return client.requestRaw({\n method: 'POST',\n service: SERVICE,\n path: `/notebook-bundles/${enc(projectId)}/${enc(projectBranch)}/export/stream`,\n body: request,\n });\n },\n\n /** Queue an async whole-project (.dfproj) export (async-only; poll + download the result). */\n async exportProjectBundle(projectId: string, projectBranch: string): Promise<string> {\n return client.request<string>({\n method: 'POST',\n service: SERVICE,\n path: `/project-bundles/${enc(projectId)}/${enc(projectBranch)}/export`,\n });\n },\n\n /** Queue an async entity-subset (.dfset) export; returns the bundleId for polling. */\n async exportEntitySubset(projectId: string, projectBranch: string, request: BundleExportRequest): Promise<string> {\n return client.request<string>({\n method: 'POST',\n service: SERVICE,\n path: `/entity-subset-bundles/${enc(projectId)}/${enc(projectBranch)}/export`,\n body: request,\n });\n },\n\n /** Streaming download of an entity-subset bundle via the synchronous /stream endpoint. */\n async streamEntitySubset(projectId: string, projectBranch: string, request: BundleExportRequest): Promise<Response> {\n return client.requestRaw({\n method: 'POST',\n service: SERVICE,\n path: `/entity-subset-bundles/${enc(projectId)}/${enc(projectBranch)}/export/stream`,\n body: request,\n });\n },\n\n async getBundles(projectId: string, projectBranch: string): Promise<BundleExport[]> {\n return client.request<BundleExport[]>({\n method: 'GET',\n service: SERVICE,\n path: `/bundles/${enc(projectId)}/${enc(projectBranch)}`,\n });\n },\n\n /** Download a finished bundle's bytes. */\n async getBundleContent(projectId: string, projectBranch: string, bundleId: string, filename: string): Promise<Response> {\n return client.requestRaw({\n method: 'GET',\n service: SERVICE,\n path: `/bundles/${enc(projectId)}/${enc(projectBranch)}/${enc(bundleId)}/${enc(filename)}`,\n });\n },\n\n async stopBundle(projectId: string, projectBranch: string, bundleId: string, filename: string): Promise<void> {\n await client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/bundles/${enc(projectId)}/${enc(projectBranch)}/${enc(bundleId)}/${enc(filename)}`,\n });\n },\n\n /** Non-committing inventory of an uploaded bundle. */\n async previewBundleImport(projectId: string, projectBranch: string, formData: FormData): Promise<BundleImportPreviewResponse> {\n return client.request<BundleImportPreviewResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/notebook-bundle-imports/${enc(projectId)}/${enc(projectBranch)}/preview`,\n rawBody: formData,\n });\n },\n\n /** Commit an uploaded bundle into the target project. */\n async importBundle(projectId: string, projectBranch: string, formData: FormData, onConflict: string = 'copy'): Promise<BundleImportResponse> {\n return client.request<BundleImportResponse>({\n method: 'POST',\n service: SERVICE,\n path: `/notebook-bundle-imports/${enc(projectId)}/${enc(projectBranch)}/import`,\n query: { onConflict },\n rawBody: formData,\n });\n },\n };\n}\n\nexport type StorageService = ReturnType<typeof createStorageService>;\n","import type { HttpClient } from '../http.js';\nimport type {\n CallRequest,\n CallResult,\n Evaluation,\n OutputEntry,\n Trigger,\n} from '../types/evaluation.js';\n\nconst SERVICE = 'evaluation';\n\nfunction enc(s: string): string {\n return encodeURIComponent(s);\n}\n\nexport function createEvaluationService(client: HttpClient) {\n return {\n // Calls\n async call(request: CallRequest, async = false): Promise<CallResult> {\n return client.request<CallResult>({\n method: 'POST',\n service: SERVICE,\n path: '/calls/',\n body: request,\n query: async ? { async: true } : undefined,\n });\n },\n\n // Evaluations\n async getEvaluations(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n year: number, month: number, day: number, hour: number,\n ): Promise<Evaluation[]> {\n return client.request<Evaluation[]>({\n method: 'GET',\n service: SERVICE,\n path: `/evaluations/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${year}/${month}/${day}/${hour}`,\n });\n },\n\n async getEvaluation(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n year: number, month: number, day: number, hour: number,\n evaluationId: string,\n result = false,\n ): Promise<Evaluation> {\n return client.request<Evaluation>({\n method: 'GET',\n service: SERVICE,\n path: `/evaluations/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${year}/${month}/${day}/${hour}/${enc(evaluationId)}`,\n query: result ? { result: true } : undefined,\n });\n },\n\n // Last Evaluation\n async getLastEvaluation(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n ): Promise<Evaluation> {\n return client.request<Evaluation>({\n method: 'GET',\n service: SERVICE,\n path: `/last-evaluation/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}`,\n });\n },\n\n // Outputs\n async getOutputs(projectId: string, evaluationId: string): Promise<OutputEntry[]> {\n return client.request<OutputEntry[]>({\n method: 'GET',\n service: SERVICE,\n path: `/output/${enc(projectId)}/${enc(evaluationId)}`,\n });\n },\n\n // Logs\n async getLogs(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n year: number, month: number, day: number, hour: number,\n ): Promise<unknown[]> {\n return client.request<unknown[]>({\n method: 'GET',\n service: SERVICE,\n path: `/log/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${year}/${month}/${day}/${hour}`,\n });\n },\n\n // Source Code\n async getSourceCode(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n sourceCodeHash: string, sourceCodeId: string,\n ): Promise<string> {\n return client.request<string>({\n method: 'GET',\n service: SERVICE,\n path: `/sourcecodes/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${enc(sourceCodeHash)}/${enc(sourceCodeId)}`,\n });\n },\n\n // Stop\n async stopEvaluation(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n year: number, month: number, day: number, hour: number,\n evaluationId: string,\n ): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/stop/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${year}/${month}/${day}/${hour}/${enc(evaluationId)}`,\n });\n },\n\n // Triggers\n async getTriggers(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n ): Promise<Trigger[]> {\n return client.request<Trigger[]>({\n method: 'GET',\n service: SERVICE,\n path: `/triggers/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}`,\n });\n },\n\n async getTrigger(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n triggerId: string,\n ): Promise<Trigger> {\n return client.request<Trigger>({\n method: 'GET',\n service: SERVICE,\n path: `/triggers/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${enc(triggerId)}`,\n });\n },\n\n async saveTrigger(trigger: Trigger): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: '/triggers/',\n body: trigger,\n });\n },\n\n async deleteTrigger(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n triggerId: string,\n ): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/triggers/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${enc(triggerId)}`,\n });\n },\n };\n}\n\nexport type EvaluationService = ReturnType<typeof createEvaluationService>;\n","import type { HttpClient } from '../http.js';\nimport type { CallRequest, CallResult } from '../types/evaluation.js';\n\nconst SERVICE = 'scheduler';\n\nfunction enc(s: string): string {\n return encodeURIComponent(s);\n}\n\nexport function createSchedulerService(client: HttpClient) {\n return {\n async scheduleCall(request: CallRequest): Promise<CallResult> {\n return client.request<CallResult>({\n method: 'POST',\n service: SERVICE,\n path: '/calls/',\n body: request,\n });\n },\n\n async stopScheduled(\n projectId: string, projectBranch: string,\n functionId: string, functionBranch: string,\n year: number, month: number, day: number, hour: number,\n evaluationId: string,\n ): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/stop/${enc(projectId)}/${enc(projectBranch)}/${enc(functionId)}/${enc(functionBranch)}/${year}/${month}/${day}/${hour}/${enc(evaluationId)}`,\n });\n },\n };\n}\n\nexport type SchedulerService = ReturnType<typeof createSchedulerService>;\n","import type { HttpClient } from '../http.js';\nimport type {\n ChatRequest,\n ChatResponse,\n ChatSession,\n ChatSessionDetail,\n TokenUsageResponse,\n} from '../types/language.js';\n\nconst SERVICE = 'language';\n\nfunction enc(s: string): string {\n return encodeURIComponent(s);\n}\n\nexport function createLanguageService(client: HttpClient) {\n return {\n // Chat (blocking)\n async chat(request: ChatRequest): Promise<ChatResponse> {\n return client.request<ChatResponse>({\n method: 'POST',\n service: SERVICE,\n path: '/chat/',\n body: request,\n });\n },\n\n // Chat (streaming) — returns raw response for SSE parsing\n async chatStream(request: ChatRequest): Promise<Response> {\n return client.requestRaw({\n method: 'POST',\n service: SERVICE,\n path: '/chat/stream',\n body: request,\n });\n },\n\n // File upload\n async upload(formData: FormData): Promise<string> {\n return client.request<string>({\n method: 'POST',\n service: SERVICE,\n path: '/upload/',\n rawBody: formData,\n });\n },\n\n // Token usage\n async getUsage(): Promise<TokenUsageResponse> {\n return client.request<TokenUsageResponse>({\n method: 'GET',\n service: SERVICE,\n path: '/usage/',\n });\n },\n\n // Sessions\n async getSessions(): Promise<ChatSession[]> {\n return client.request<ChatSession[]>({\n method: 'GET',\n service: SERVICE,\n path: '/sessions/',\n });\n },\n\n async getSession(sessionId: string): Promise<ChatSessionDetail> {\n return client.request<ChatSessionDetail>({\n method: 'GET',\n service: SERVICE,\n path: `/sessions/${enc(sessionId)}`,\n });\n },\n\n async deleteSession(sessionId: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/sessions/${enc(sessionId)}`,\n });\n },\n\n async getSessionMessages(sessionId: string): Promise<unknown[]> {\n return client.request<unknown[]>({\n method: 'GET',\n service: SERVICE,\n path: `/sessions/${enc(sessionId)}/messages`,\n });\n },\n\n async renameSession(sessionId: string, title: string): Promise<void> {\n return client.request<void>({\n method: 'PUT',\n service: SERVICE,\n path: `/sessions/${enc(sessionId)}/title`,\n rawBody: title,\n contentType: 'text/plain',\n });\n },\n };\n}\n\nexport type LanguageService = ReturnType<typeof createLanguageService>;\n","import type { HttpClient } from '../http.js';\nimport type { CuratedTag, CuratedTagRequest, SearchPageQuery, SearchPageResponse } from '../types/index-search.js';\n\nconst SERVICE = 'index';\n\nfunction enc(s: string): string {\n return encodeURIComponent(s);\n}\n\nexport function createIndexService(client: HttpClient) {\n return {\n /**\n * Cross-project search. Scoped to one project by passing `projectId`; unscoped it searches\n * everything the caller can see, which is what the command's description has always promised.\n */\n async searchPage(query: SearchPageQuery): Promise<SearchPageResponse> {\n return client.request<SearchPageResponse>({\n method: 'GET',\n service: SERVICE,\n path: '/search/page',\n query: {\n query: query.query,\n limit: query.limit ?? 20,\n cursor: query.cursor ?? undefined,\n contentType: query.contentType ?? undefined,\n projectId: query.projectId ?? undefined,\n projectBranch: query.projectBranch ?? undefined,\n sort: query.sort && query.sort !== 'best' ? query.sort : undefined,\n },\n });\n },\n\n /**\n * The curated tags in their order. Public: no account is needed. With `counts` each also says\n * how many public projects carry it.\n */\n async getCuratedTags(counts = false): Promise<CuratedTag[]> {\n return client.request<CuratedTag[]>({\n method: 'GET',\n service: SERVICE,\n path: '/tags/curated',\n query: counts ? { counts: true } : undefined,\n });\n },\n\n /** Administrators only. The platform stores the tag in its canonical form. */\n async createCuratedTag(request: CuratedTagRequest): Promise<CuratedTag> {\n return client.request<CuratedTag>({\n method: 'POST',\n service: SERVICE,\n path: '/admin/curated-tags',\n body: request,\n });\n },\n\n /** Administrators only. A field left out of the request keeps what is stored. */\n async updateCuratedTag(tag: string, request: CuratedTagRequest): Promise<CuratedTag> {\n return client.request<CuratedTag>({\n method: 'PUT',\n service: SERVICE,\n path: `/admin/curated-tags/${enc(tag)}`,\n body: request,\n });\n },\n\n /** Administrators only. Projects that carry the tag keep it; it only stops being curated. */\n async deleteCuratedTag(tag: string): Promise<void> {\n return client.request<void>({\n method: 'DELETE',\n service: SERVICE,\n path: `/admin/curated-tags/${enc(tag)}`,\n });\n },\n\n async rebuildAll(): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: '/indexes/rebuild',\n });\n },\n\n async rebuildProject(projectId: string): Promise<void> {\n return client.request<void>({\n method: 'POST',\n service: SERVICE,\n path: `/indexes/rebuild/${enc(projectId)}`,\n });\n },\n };\n}\n\nexport type IndexService = ReturnType<typeof createIndexService>;\n","import { createHttpClient, type HttpClient } from './http.js';\nimport { createAdminService, type AdminService } from './services/admin.js';\nimport { createAnalysisService, type AnalysisService } from './services/analysis.js';\nimport { createStorageService, type StorageService } from './services/storage.js';\nimport { createEvaluationService, type EvaluationService } from './services/evaluation.js';\nimport { createSchedulerService, type SchedulerService } from './services/scheduler.js';\nimport { createLanguageService, type LanguageService } from './services/language.js';\nimport { createIndexService, type IndexService } from './services/index-search.js';\n\nexport interface ApiClient {\n http: HttpClient;\n admin: AdminService;\n analysis: AnalysisService;\n storage: StorageService;\n evaluation: EvaluationService;\n scheduler: SchedulerService;\n language: LanguageService;\n index: IndexService;\n}\n\nexport function createApiClient(options: { profileOverride?: string } = {}): ApiClient {\n const http = createHttpClient(options);\n return {\n http,\n admin: createAdminService(http),\n analysis: createAnalysisService(http),\n storage: createStorageService(http),\n evaluation: createEvaluationService(http),\n scheduler: createSchedulerService(http),\n language: createLanguageService(http),\n index: createIndexService(http),\n };\n}\n","import { Command } from 'commander';\nimport { registerLoginCommand } from './login.js';\nimport { registerLogoutCommand } from './logout.js';\nimport { registerStatusCommand } from './status.js';\nimport { registerTokenCommands } from './token.js';\n\nexport function registerAuthCommands(program: Command): void {\n const auth = program\n .command('auth')\n .description('Authentication and credential management')\n .addHelpText('after', `\nExamples:\n $ diafunc auth login sign in with a browser\n $ diafunc auth status who you are signed in as\n $ diafunc auth token create a token for scripts and CI\n $ diafunc auth logout\n`);;\n\n registerLoginCommand(auth);\n registerLogoutCommand(auth);\n registerStatusCommand(auth);\n registerTokenCommands(auth);\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig, saveConfig, CONFIG_FILE } from '../../config/store.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { failure, success } from '../../output/messages.js';\n\nexport function registerConfigCommands(program: Command): void {\n const config = program\n .command('config')\n .description('Manage CLI configuration')\n .addHelpText('after', `\nSetting a default project lets every command that takes one omit it.\n\nExamples:\n $ diafunc config list\n $ diafunc config set defaults.project <id>\n $ diafunc config set defaults.output json\n $ diafunc config profile add staging --endpoint https://staging.diafunc.com\n`);;\n\n config\n .command('set')\n .description('Set a configuration value')\n .argument('<key>', 'Config key (e.g., defaults.project, defaults.branch, defaults.output)')\n .argument('<value>', 'Config value')\n .action((key: string, value: string) => {\n const cfg = loadConfig();\n setNestedValue(cfg as unknown as Record<string, unknown>, key, value);\n saveConfig(cfg);\n success(`Set ${key} = ${value}`);\n });\n\n config\n .command('get')\n .description('Get a configuration value')\n .argument('<key>', 'Config key')\n .action((key: string) => {\n const cfg = loadConfig();\n const value = getNestedValue(cfg as unknown as Record<string, unknown>, key);\n if (value === undefined) {\n console.log(chalk.dim('(not set)'));\n } else {\n console.log(String(value));\n }\n });\n\n config\n .command('list')\n .description('Show all configuration')\n .action((_options, cmd) => {\n const cfg = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? 'human';\n\n if (outputFormat === 'human') {\n console.log(chalk.bold('Config file:'), CONFIG_FILE);\n console.log(chalk.bold('Active profile:'), cfg.currentProfile);\n console.log();\n console.log(chalk.bold('Profiles:'));\n for (const [name, profile] of Object.entries(cfg.profiles)) {\n const active = name === cfg.currentProfile ? chalk.green(' (active)') : '';\n const authType = profile.auth?.type ?? 'none';\n console.log(` ${chalk.bold(name)}${active}`);\n console.log(` Endpoint: ${profile.endpoint}`);\n console.log(` Auth: ${authType}`);\n }\n if (Object.keys(cfg.defaults).length > 0) {\n console.log();\n console.log(chalk.bold('Defaults:'));\n for (const [key, value] of Object.entries(cfg.defaults)) {\n console.log(` ${key}: ${value}`);\n }\n }\n } else {\n format(cfg, { format: outputFormat });\n }\n });\n\n // Profile subcommands\n const profile = config\n .command('profile')\n .description('Manage profiles');\n\n profile\n .command('add')\n .description('Add a new profile')\n .argument('<name>', 'Profile name')\n .option('--endpoint <url>', 'API endpoint URL', 'https://diafunc.com')\n .option('--token <token>', 'API token to store')\n .action((name: string, options: { endpoint: string; token?: string }) => {\n const cfg = loadConfig();\n if (cfg.profiles[name]) {\n failure(`Profile \"${name}\" already exists. Use 'diafunc config profile use' to switch to it.`);\n process.exit(1);\n }\n cfg.profiles[name] = {\n endpoint: options.endpoint,\n ...(options.token ? { auth: { type: 'api-token' as const, token: options.token } } : {}),\n };\n saveConfig(cfg);\n success(`Profile \"${name}\" added.`);\n });\n\n profile\n .command('use')\n .description('Switch to a profile')\n .argument('<name>', 'Profile name')\n .action((name: string) => {\n const cfg = loadConfig();\n if (!cfg.profiles[name]) {\n failure(`Profile \"${name}\" not found.`);\n console.log(`Available profiles: ${Object.keys(cfg.profiles).join(', ')}`);\n process.exit(1);\n }\n cfg.currentProfile = name;\n saveConfig(cfg);\n success(`Switched to profile \"${name}\".`);\n });\n\n profile\n .command('list')\n .description('List all profiles')\n .action((_options, cmd) => {\n const cfg = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? cfg.defaults.output ?? 'human';\n\n const profiles = Object.entries(cfg.profiles).map(([name, p]) => ({\n name,\n endpoint: p.endpoint,\n auth: p.auth?.type ?? 'none',\n active: name === cfg.currentProfile,\n }));\n\n format(profiles, {\n format: outputFormat,\n columns: ['name', 'endpoint', 'auth', 'active'],\n });\n });\n\n profile\n .command('remove')\n .description('Remove a profile')\n .argument('<name>', 'Profile name')\n .action((name: string) => {\n const cfg = loadConfig();\n if (!cfg.profiles[name]) {\n failure(`Profile \"${name}\" not found.`);\n process.exit(1);\n }\n if (name === cfg.currentProfile) {\n failure(`Cannot remove the active profile. Switch to another profile first.`);\n process.exit(1);\n }\n delete cfg.profiles[name];\n saveConfig(cfg);\n success(`Profile \"${name}\" removed.`);\n });\n}\n\nfunction setNestedValue(obj: Record<string, unknown>, path: string, value: string): void {\n const keys = path.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n if (!(key in current) || typeof current[key] !== 'object' || current[key] === null) {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n}\n\nfunction getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const keys = path.split('.');\n let current: unknown = obj;\n for (const key of keys) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined;\n }\n current = (current as Record<string, unknown>)[key];\n }\n return current;\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { hiddenOptionAlias } from '../../util/hidden-aliases.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseProjectReference } from '../../util/references.js';\nimport { pollUntilFinished, runBundleImport, streamResponseToFile } from '../bundle-helpers.js';\nimport type { Visibility } from '../../client/types/admin.js';\nimport { DEFAULT_FUNCTION_LANGUAGE } from '../../util/function-language.js';\nimport { success } from '../../output/messages.js';\nimport { projectNames } from '../../util/project-names.js';\nimport { buildProjectRootEntity, withProjectTexts } from '../../util/project-entity.js';\nimport { registerTagCommands } from '../entity/tags.js';\nimport { registerProjectTransferCommands } from './transfer.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerProjectCommands(program: Command): void {\n const project = program\n .command('project')\n .description('Manage projects');\n\n project\n .command('list')\n .description('List projects')\n .option('--all', 'List every project on the platform (admin)')\n .option('--limit <n>', 'Maximum projects to show; 0 for all', '20')\n .addHelpText('after', `\nExamples:\n $ diafunc project list the twenty most recent\n $ diafunc project list --limit 0 every one of them\n $ diafunc search \"housing\" --type project find a project by name\n`)\n .action(async (options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const projects = options.all\n ? await api.admin.getAllProjects()\n : await api.admin.getProjects();\n\n // Without a cap this printed all 272 rows. A listing nobody can read is not a listing.\n const limit = Number.parseInt(options.limit, 10);\n const capped = Number.isFinite(limit) && limit > 0 ? projects.slice(0, limit) : projects;\n\n // A project's name lives on its main entity, not on the project row; the index has it. A\n // name is a convenience, so a listing without one still prints, with its ids.\n let names = new Map<string, string>();\n try {\n names = await projectNames(api, capped.map((p) => p.projectId));\n } catch {\n console.error(chalk.dim('Project names are unavailable right now; showing ids.'));\n }\n const rows = capped.map((p) => ({ name: names.get(p.projectId) ?? null, ...p }));\n\n format(rows, {\n format: outputFormat,\n columns: [\n { key: 'name' },\n { key: 'projectId', kind: 'id' },\n { key: 'teamName', header: 'team' },\n { key: 'visibility' },\n { key: 'language' },\n { key: 'active', kind: 'boolean' },\n { key: 'locked', kind: 'boolean' },\n { key: 'created', kind: 'date' },\n ],\n });\n if (capped.length < projects.length) {\n // A note, not data: on stderr, so JSON and tab-separated output stay parseable.\n console.error(chalk.dim(\n `\\nShowing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`,\n ));\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('get')\n .description('Get project details')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const p = await api.admin.getProject(projectId);\n format(p, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('create')\n .description('Create a new project')\n .option('--name <name>', \"The project's name; without one, a project bundle imported into it names it\")\n .option('--description <text>', \"The project's description\")\n .option('--visibility <visibility>', 'Project visibility (PRIVATE or PUBLIC)', 'PRIVATE')\n .option('--language <language>', \"The project's default language for functions (Java, Kotlin, Python, JavaScript, Scala)\", DEFAULT_FUNCTION_LANGUAGE)\n .option('--license <licenseId>', \"License a public project is published under, an id of the license catalog (see 'diafunc license list')\")\n .addOption(hiddenOptionAlias('--licence <licenseId>', 'license'))\n .addHelpText('after', `\nExamples:\n $ diafunc project create a private project\n $ diafunc project create --name \"Vineyard yield\" a private project with a name\n $ diafunc project import <projectId> guide.dfproj an unnamed one takes the bundle's name\n $ diafunc project create --visibility PUBLIC --license CC-BY-4.0 a public one, open for reuse with attribution\n $ diafunc license list the licenses that can be chosen\n`)\n .action(async (options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const p = await api.admin.createProject({\n visibility: options.visibility.toUpperCase() as Visibility,\n language: options.language,\n active: true,\n ...(options.license ? { licenceId: options.license } : {}),\n });\n // A project row alone is not a usable project: entities live under a project branch, and deleting a\n // project sweeps its branches. Creating the project without its main branch left the entities written\n // into it beyond the reach of the deletion, so the branch is created here, as the app does.\n await api.storage.createProjectBranch({\n projectId: p.projectId,\n sourceProjectBranch: null,\n targetProjectBranch: 'main',\n });\n // The root entity carries the project's name and is where its notebooks attach; the app writes it\n // right after the branch, and so does this.\n await api.storage.saveEntities([buildProjectRootEntity({\n projectId: p.projectId,\n name: options.name,\n description: options.description,\n })]);\n\n if (outputFormat === 'human') {\n success('Project created.');\n if (options.name) console.log(` Name: ${options.name}`);\n console.log(` Project ID: ${chalk.bold(p.projectId)}`);\n console.log(` Visibility: ${p.visibility}`);\n console.log(` Language: ${p.language}`);\n if (p.licenceId) console.log(` License: ${p.licenceId}`);\n } else {\n format(p, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('update')\n .description('Update a project')\n .argument('<projectId>', 'Project ID')\n .option('--name <name>', \"The project's name, shown on Explore and in the project header\")\n .option('--description <text>', \"The project's description, shown on Explore; an empty value removes it\")\n .option('--visibility <visibility>', 'PRIVATE or PUBLIC')\n .option('--language <language>', 'Project language')\n .option('--active <bool>', 'Whether the project is active (true/false)')\n .option('--license <licenseId>', 'License a public project is published under, an id of the license catalog (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)')\n .addOption(hiddenOptionAlias('--licence <licenseId>', 'license'))\n .option('--data-source-name <name>', 'Who published the data the project analyzes; an empty value clears it')\n .option('--data-source-url <url>', 'Where the data was obtained, an http(s) address; an empty value clears it')\n .addHelpText('after', `\nExamples:\n $ diafunc project update <projectId> --name \"Vineyard yield\" rename the project\n $ diafunc project update <projectId> --description \"Yield per hectare\" set the text Explore shows\n $ diafunc project update <projectId> --license CC-BY-4.0 publish it under another license\n`)\n .action(async (projectId: string, options) => {\n try {\n const api = createApiClient();\n const projectOptions = ['visibility', 'language', 'active', 'license', 'dataSourceName', 'dataSourceUrl'];\n const changesProject = projectOptions.some((key) => options[key] !== undefined);\n const changesTexts = options.name !== undefined || options.description !== undefined;\n if (!changesProject && !changesTexts) {\n throw new Error('Nothing to update: give at least one option (see --help).');\n }\n if (options.name !== undefined && !options.name.trim()) {\n throw new Error('A project name cannot be empty.');\n }\n if (changesTexts) {\n // The name and the description live on the project's root entity, not on the project record.\n const root = await api.storage.getEntity({\n projectId, projectBranch: 'main', entityId: projectId, entityBranch: 'main',\n });\n await api.storage.saveEntities([withProjectTexts(root, {\n name: options.name,\n description: options.description,\n })]);\n }\n if (!changesProject) {\n success(`Project \"${projectId}\" updated.`);\n return;\n }\n const current = await api.admin.getProject(projectId);\n const updated = {\n ...current,\n ...(options.visibility ? { visibility: options.visibility.toUpperCase() as Visibility } : {}),\n ...(options.language ? { language: options.language } : {}),\n ...(options.active !== undefined ? { active: options.active === 'true' } : {}),\n ...(options.license ? { licenceId: options.license } : {}),\n ...(options.dataSourceName !== undefined ? { dataSourceName: options.dataSourceName } : {}),\n ...(options.dataSourceUrl !== undefined ? { dataSourceUrl: options.dataSourceUrl } : {}),\n };\n await api.admin.updateProject(updated);\n success(`Project \"${projectId}\" updated.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('recent')\n .description('List recently accessed projects')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const recent = await api.admin.getRecentProjects();\n format(recent, {\n format: outputFormat,\n columns: [\n { key: 'projectId', kind: 'id' },\n { key: 'projectBranch', header: 'branch' },\n { key: 'lastAccessed', kind: 'date' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('delete')\n .description('Delete a project')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string) => {\n try {\n const api = createApiClient();\n await api.admin.deleteProject(projectId);\n success(`Project \"${projectId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('lock')\n .description('Lock a project')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string) => {\n try {\n const api = createApiClient();\n await api.admin.lockProject(projectId);\n success(`Project \"${projectId}\" locked.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('unlock')\n .description('Unlock a project')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string) => {\n try {\n const api = createApiClient();\n await api.admin.unlockProject(projectId);\n success(`Project \"${projectId}\" unlocked.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n registerTagCommands(project, 'project');\n\n registerProjectTransferCommands(project);\n\n // Members subcommands\n const members = project\n .command('members')\n .description('Manage project members');\n\n members\n .command('list')\n .description('List project members')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const memberList = await api.admin.getProjectMembers(projectId);\n format(memberList, {\n format: outputFormat,\n columns: ['userId', 'role', 'joined', 'invitedByUserId'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n members\n .command('invite')\n .description('Invite a user to a project')\n .argument('<projectId>', 'Project ID')\n .argument('<userId>', 'User ID to invite')\n .argument('<role>', 'Role (OWNER, ADMIN, DEVELOPER, GUEST)')\n .action(async (projectId: string, userId: string, role: string) => {\n try {\n const api = createApiClient();\n await api.admin.inviteProjectMember(projectId, userId, role.toUpperCase());\n success(`Invited ${userId} to \"${projectId}\" as ${role.toUpperCase()}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n members\n .command('join')\n .description('Join a project')\n .argument('<projectId>', 'Project ID')\n .argument('<userId>', 'User ID')\n .action(async (projectId: string, userId: string) => {\n try {\n const api = createApiClient();\n await api.admin.joinProject(projectId, userId);\n success(`Joined project \"${projectId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n members\n .command('remove')\n .description('Remove a member from a project')\n .argument('<projectId>', 'Project ID')\n .argument('<userId>', 'User ID to remove')\n .action(async (projectId: string, userId: string) => {\n try {\n const api = createApiClient();\n await api.admin.removeProjectMember(projectId, userId);\n success(`Removed ${userId} from \"${projectId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Bundle subcommands — whole-project (.dfproj) export/import.\n\n project\n .command('export')\n .description('Export a whole project (entities, links, skeletons, analysis recipe) to a .dfproj bundle')\n .argument('<project>', 'Project reference (projectId or projectId/branch)')\n .option('--out <file>', 'Output file (defaults to project.dfproj)')\n .option('--async', 'Queue the background job and return immediately instead of waiting for the file')\n .action(async (project: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n\n // A project export is async-only on the server (the closure is materialized before packing).\n const bundleId = await api.storage.exportProjectBundle(ref.projectId, ref.projectBranch);\n if (options.async) {\n success(`Project export queued (bundle ID: ${bundleId}).`);\n console.log(`Poll progress: diafunc notebook bundles ${project}`);\n return;\n }\n\n console.log(chalk.dim(`Project export queued (bundle ID: ${bundleId}); waiting for it to finish…`));\n const job = await pollUntilFinished(api.storage, ref.projectId, ref.projectBranch, bundleId);\n const response = await api.storage.getBundleContent(ref.projectId, ref.projectBranch, bundleId, job.filename);\n const outFile = options.out ?? 'project.dfproj';\n const bytes = await streamResponseToFile(response, outFile);\n success(`Bundle written to ${outFile} (${bytes} bytes, ${job.entityCount ?? '?'} entities).`);\n } catch (error) {\n handleError(error);\n }\n });\n\n project\n .command('import')\n .description('Import a .dfproj (or any) bundle into a project')\n .argument('<project>', 'Target project reference (projectId or projectId/branch)')\n .argument('<file>', 'Path to the bundle')\n .option('--on-conflict <policy>', 'copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip', 'copy')\n .option('--preview', 'Show the bundle inventory without importing')\n .action(async (project: string, file: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n await runBundleImport(api.storage, ref.projectId, ref.projectBranch, file, options, outputFormat);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command, Help, Option } from 'commander';\n\n/**\n * Old spellings that still work but are never shown. The CLI spells US (`license`); scripts written\n * against the earlier British names (`licence`, `--licence`) keep running, while help, usage lines\n * and completion only ever teach the current name.\n */\nconst hidden = new WeakMap<Command, Set<string>>();\n\n/** Commander's alias list. It has no public way to read aliases without also showing them in help. */\ntype WithAliases = { _aliases: string[] };\n\n/** Accepts `alias` as another name for `cmd`, left out of every help text. */\nexport function hiddenAlias(cmd: Command, alias: string): Command {\n cmd.alias(alias);\n const names = hidden.get(cmd) ?? new Set<string>();\n names.add(alias);\n hidden.set(cmd, names);\n return cmd;\n}\n\n/** The aliases of `cmd` that help may show. */\nexport function visibleAliases(cmd: Command): string[] {\n const names = hidden.get(cmd);\n return cmd.aliases().filter((alias) => !names?.has(alias));\n}\n\nfunction withVisibleAliasesOnly<T>(cmd: Command, render: () => T): T {\n const target = cmd as unknown as WithAliases;\n const all = target._aliases;\n target._aliases = visibleAliases(cmd);\n try {\n return render();\n } finally {\n target._aliases = all;\n }\n}\n\n/**\n * Help overrides that leave hidden aliases out of the command list (`license [options]`, not\n * `license|licence [options]`) and out of the usage line. Passed to the program's `configureHelp`\n * before any subcommand exists, since commander copies the help configuration on creation.\n */\nexport const HIDDEN_ALIAS_HELP: Partial<Help> = {\n subcommandTerm(this: Help, cmd: Command): string {\n return withVisibleAliasesOnly(cmd, () => Help.prototype.subcommandTerm.call(this, cmd));\n },\n commandUsage(this: Help, cmd: Command): string {\n return withVisibleAliasesOnly(cmd, () => Help.prototype.commandUsage.call(this, cmd));\n },\n};\n\n/** Hidden options that stand for another option, by the attribute the value is stored under. */\nconst optionTargets = new WeakMap<Option, string>();\n\n/**\n * A hidden spelling of another option: `hiddenOptionAlias('--licence <licenseId>', 'license')`. Help\n * never lists it, and once `wireHiddenOptionAliases` has run, a value given to it lands under\n * `target`, where the action reads the current flag.\n */\nexport function hiddenOptionAlias(oldFlags: string, target: string): Option {\n const option = new Option(oldFlags).hideHelp();\n optionTargets.set(option, target);\n return option;\n}\n\n/** Routes every hidden option alias in the command tree to the option it stands for. */\nexport function wireHiddenOptionAliases(cmd: Command): void {\n for (const option of cmd.options) {\n const target = optionTargets.get(option);\n if (!target) continue;\n cmd.on(`option:${option.name()}`, (value: unknown) => {\n cmd.setOptionValue(target, value);\n });\n }\n for (const sub of cmd.commands) wireHiddenOptionAliases(sub);\n}\n","import { loadConfig } from '../config/store.js';\n\nexport interface ResolvedReference {\n projectId: string;\n projectBranch: string;\n entityId: string;\n entityBranch: string;\n}\n\nexport interface ResolvedProjectReference {\n projectId: string;\n projectBranch: string;\n}\n\n/**\n * Parse a compact entity reference string into its 4 components.\n *\n * Supported formats:\n * \"entityId\" → defaults for project, both branches\n * \"entityId:entityBranch\" → defaults for project, project branch\n * \"projectId/projectBranch/entityId/entityBranch\" → fully explicit\n * \"projectId//entityId\" → explicit project, default branches\n * \"projectId/projectBranch/entityId\" → explicit project+branch, default entity branch\n */\nexport function parseEntityReference(\n ref: string,\n overrides?: { project?: string; branch?: string },\n): ResolvedReference {\n const config = loadConfig();\n const defaultProject = overrides?.project ?? config.defaults.project;\n const defaultBranch = overrides?.branch ?? config.defaults.branch ?? 'main';\n\n // Check for colon syntax: \"entityId:entityBranch\"\n if (!ref.includes('/') && ref.includes(':')) {\n const [entityId, entityBranch] = ref.split(':');\n if (!defaultProject) {\n throw new Error('No default project configured. Set one with: diafunc config set defaults.project <id>');\n }\n return {\n projectId: defaultProject,\n projectBranch: defaultBranch,\n entityId,\n entityBranch: entityBranch || defaultBranch,\n };\n }\n\n const parts = ref.split('/');\n\n // Single part: just entityId\n if (parts.length === 1) {\n if (!defaultProject) {\n throw new Error('No default project configured. Set one with: diafunc config set defaults.project <id>');\n }\n return {\n projectId: defaultProject,\n projectBranch: defaultBranch,\n entityId: parts[0],\n entityBranch: defaultBranch,\n };\n }\n\n // Two parts: \"projectId//entityId\" (empty middle)\n // or could be ambiguous — treat as \"projectId/entityId\" with default branches\n if (parts.length === 2) {\n return {\n projectId: parts[0],\n projectBranch: defaultBranch,\n entityId: parts[1],\n entityBranch: defaultBranch,\n };\n }\n\n // Three parts: \"projectId//entityId\" (split gives ['projectId', '', 'entityId'])\n // or \"projectId/projectBranch/entityId\"\n if (parts.length === 3) {\n if (parts[1] === '') {\n // \"projectId//entityId\"\n return {\n projectId: parts[0],\n projectBranch: defaultBranch,\n entityId: parts[2],\n entityBranch: defaultBranch,\n };\n }\n return {\n projectId: parts[0],\n projectBranch: parts[1],\n entityId: parts[2],\n entityBranch: defaultBranch,\n };\n }\n\n // Four parts: fully explicit\n if (parts.length === 4) {\n return {\n projectId: parts[0],\n projectBranch: parts[1] || defaultBranch,\n entityId: parts[2],\n entityBranch: parts[3] || defaultBranch,\n };\n }\n\n throw new Error(\n `Invalid entity reference: \"${ref}\". Expected format: entityId, entityId:branch, or projectId/projectBranch/entityId/entityBranch`,\n );\n}\n\n/**\n * Parse a project reference: \"projectId\" or \"projectId/branch\"\n */\nexport function parseProjectReference(\n ref: string,\n overrides?: { project?: string; branch?: string },\n): ResolvedProjectReference {\n const config = loadConfig();\n const defaultProject = overrides?.project ?? config.defaults.project;\n const defaultBranch = overrides?.branch ?? config.defaults.branch ?? 'main';\n\n if (!ref.includes('/')) {\n return {\n projectId: ref || defaultProject!,\n projectBranch: defaultBranch,\n };\n }\n\n const parts = ref.split('/');\n return {\n projectId: parts[0],\n projectBranch: parts[1] || defaultBranch,\n };\n}\n\nexport function refPath(ref: ResolvedReference): string {\n return `${ref.projectId}/${ref.projectBranch}/${ref.entityId}/${ref.entityBranch}`;\n}\n\nexport function projectRefPath(ref: ResolvedProjectReference): string {\n return `${ref.projectId}/${ref.projectBranch}`;\n}\n","/*\n * (C) Copyright by Markus Pollak, diafunc.com - All Rights Reserved\n *\n * diafunc.com, Markus Pollak, 7083 Purbach, Austria\n *\n * All information contained herein is, and remains the property of Markus Pollak. The intellectual\n * and technical concepts contained herein are proprietary to Markus Pollak (diafunc.com) and are\n * protected by trade secret or copyright law. Dissemination of this information or reproduction of\n * this material is strictly forbidden unless prior written permission is obtained from Markus Pollak.\n */\n\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { format, type OutputFormat } from '../output/formatter.js';\nimport type { StorageService } from '../client/services/storage.js';\nimport type { BundleExport, BundleImportPreviewResponse, BundleImportResponse } from '../client/types/storage.js';\nimport { hint, success, warn } from '../output/messages.js';\nimport { SPINNER, Status, bar, percent } from '../output/progress.js';\nimport { formatDuration } from '../output/values.js';\n\n/** Write a streamed bundle response to disk; returns the byte count. */\nexport async function streamResponseToFile(response: Response, outFile: string): Promise<number> {\n const buffer = Buffer.from(await response.arrayBuffer());\n fs.writeFileSync(outFile, buffer);\n return buffer.length;\n}\n\n/** What the bundle format could not carry. A caveat on the result, so it goes to stderr. */\nfunction printLossiness(notes?: string[]): void {\n if (!notes || notes.length === 0) return;\n warn(notes.length === 1 ? 'One detail could not be carried in the bundle:' : 'Some details could not be carried in the bundle:');\n for (const note of notes) hint(`- ${note}`);\n}\n\n/** Human-readable rendering of a non-committing import preview, including project-bundle sections. */\nexport function printImportPreview(preview: BundleImportPreviewResponse): void {\n console.log(chalk.bold(`${preview.kind} bundle · ${preview.entityCount} entities`));\n if (preview.projectName) {\n console.log(chalk.dim(preview.projectName));\n }\n if (preview.sourceProjectId) {\n console.log(chalk.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` +\n (preview.createdBy ? ` · by ${preview.createdBy}` : '')));\n }\n const counts = new Map<string, number>();\n for (const e of preview.entities ?? []) {\n counts.set(e.type, (counts.get(e.type) ?? 0) + 1);\n }\n for (const [type, count] of [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n console.log(` ${type}: ${count}`);\n }\n if (preview.hasAnalysis) {\n console.log(' analysis recipe: included');\n }\n if (preview.skeletonCount) {\n console.log(` skeletons: ${preview.skeletonCount}`);\n }\n if (preview.redactedDataSourceCount) {\n console.log(` data sources: ${preview.redactedDataSourceCount} (credentials redacted)`);\n }\n printLossiness(preview.lossinessNotes);\n}\n\n/** Human-readable rendering of a committed import result, including project-bundle section outcomes. */\nexport function printImportResult(result: BundleImportResponse): void {\n success(`Imported ${result.entityCount} entities, ${result.linkCount} links.`);\n if (result.skeletonCount) {\n console.log(`Skeletons: ${result.skeletonCount}`);\n }\n if (result.dataSourceCount) {\n console.log(`Data sources: ${result.dataSourceCount} (re-authenticate before refreshing)`);\n }\n if (result.analysisOutcome && result.analysisOutcome !== 'none') {\n console.log(`Analysis recipe: ${result.analysisOutcome}`);\n }\n if (result.rootEntityIds.length > 0) {\n console.log(`Root id(s): ${result.rootEntityIds.join(', ')}`);\n }\n printLossiness(result.lossinessNotes);\n}\n\n/**\n * Shared preview-or-commit import flow for any bundle kind (the server reads the manifest's kind). Used\n * by {@code project import} and {@code entity import}; mirrors {@code notebook import}.\n */\nexport async function runBundleImport(\n storage: StorageService,\n projectId: string,\n projectBranch: string,\n file: string,\n options: { preview?: boolean; onConflict?: string },\n outputFormat: OutputFormat,\n): Promise<void> {\n const fileBuffer = fs.readFileSync(file);\n const blob = new Blob([fileBuffer]);\n const formData = new FormData();\n formData.append('content', blob, path.basename(file));\n\n if (options.preview) {\n const preview = await storage.previewBundleImport(projectId, projectBranch, formData);\n if (outputFormat === 'json') {\n format(preview, { format: outputFormat });\n return;\n }\n printImportPreview(preview);\n return;\n }\n\n const result = await storage.importBundle(projectId, projectBranch, formData, options.onConflict);\n if (outputFormat === 'json') {\n format(result, { format: outputFormat });\n return;\n }\n printImportResult(result);\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));\n\n/**\n * Poll an async export job until it finishes (the project export is async-only). Resolves to the finished\n * job row so the caller can download its bytes; throws if it errors or does not finish within the budget.\n */\nexport async function pollUntilFinished(\n storage: StorageService,\n projectId: string,\n projectBranch: string,\n bundleId: string,\n intervalMs = 2000,\n maxAttempts = 150,\n): Promise<BundleExport> {\n // An export of a large project runs for minutes. Waiting in silence is indistinguishable from a\n // hung command, so the job's own progress is shown while it works.\n const status = new Status();\n status.start();\n const startedAt = Date.now();\n try {\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const bundles = await storage.getBundles(projectId, projectBranch);\n const job = bundles.find(b => b.bundleId === bundleId);\n if (job && job.finished) {\n if (job.succeeded === false) {\n throw new Error(`Export failed: ${job.error || 'unknown error'}`);\n }\n return job;\n }\n status.set([progressLine('Exporting', job?.progress, Date.now() - startedAt)]);\n await sleep(intervalMs);\n }\n } finally {\n status.stop();\n }\n throw new Error(\n `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)}. ` +\n `Check it with 'diafunc notebook bundles ${projectId}'.`,\n );\n}\n\n/**\n * One line of wait feedback: a determinate bar when the job reports a fraction, elapsed time\n * otherwise. Shared by the export and import waits so both look the same.\n */\nexport function progressLine(label: string, progress: number | null | undefined, elapsedMs: number): string {\n const elapsed = chalk.dim(formatDuration(elapsedMs));\n if (progress === null || progress === undefined) {\n return ` ${chalk.cyan(SPINNER)} ${label} ${elapsed}`;\n }\n // Jobs report either 0..1 or 0..100 depending on the surface; both are normalised here.\n const fraction = progress > 1 ? progress / 100 : progress;\n return ` ${chalk.cyan(SPINNER)} ${label} ${bar(fraction, 20)} ${percent(fraction)} ${elapsed}`;\n}\n","import chalk from 'chalk';\nimport { isInteractive, terminalWidth, truncate } from './terminal.js';\n\n// Built from escape strings rather than literals so the source carries no control characters.\nconst ESC = '\\u001B[';\n/** Move the cursor up `n` rows. */\nconst CURSOR_UP = (n: number) => `${ESC}${n}A`;\n/** Erase from the cursor to the end of the screen. */\nconst CLEAR_BELOW = `${ESC}0J`;\n\n/**\n * Transient status output.\n *\n * One object owns the bottom of the screen. Anything that wants to print a durable line goes\n * through {@link Status.log}, which erases the transient block first and repaints it afterwards.\n * That contract is the whole point: `analyze watch` used to write a progress bar with a bare `\\r`\n * and then `console.log` an output line on top of it, producing rows like\n * `running [#### ] 42% Output: {\"name\":\"analysis.job.progress\",...}`.\n *\n * Off a TTY nothing is redrawn. A pipe or a CI log gets an append-only line whenever the caption\n * actually changes, so the transcript stays readable and never fills with escape sequences.\n */\n/**\n * Placeholder a caller embeds where the animated glyph belongs. The frame is substituted at paint\n * time rather than at {@link Status.set} time: callers refresh their lines only when the data\n * changes — every couple of seconds for a run — so a glyph baked in at that point would sit\n * motionless between updates and the spinner would not spin.\n */\nexport const SPINNER = '\\u0000spinner\\u0000';\n\nexport class Status {\n private lines: string[] = [];\n private painted = 0;\n private lastLogged = '';\n private spinnerIndex = 0;\n private timer: NodeJS.Timeout | null = null;\n\n private static readonly FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\n /** Replaces the transient block. Repaints only when the content actually changed. */\n set(lines: string[]): void {\n const next = lines.filter((l) => l !== undefined);\n if (!isInteractive()) {\n const joined = next.map((l) => l.split(SPINNER).join('').trim()).filter(Boolean).join(' · ');\n if (joined && joined !== this.lastLogged) {\n this.lastLogged = joined;\n console.log(joined);\n }\n this.lines = next;\n return;\n }\n this.lines = next;\n this.repaint();\n }\n\n /** Prints a durable line above the transient block. */\n log(line: string): void {\n if (!isInteractive()) {\n console.log(line);\n return;\n }\n this.erase();\n console.log(line);\n this.repaint();\n }\n\n /**\n * Starts the spinner animation. The caller still drives content through {@link set}; this only\n * advances the frame so a long wait does not look like a hung process.\n */\n start(): void {\n if (this.timer || !isInteractive()) return;\n this.timer = setInterval(() => {\n this.spinnerIndex = (this.spinnerIndex + 1) % Status.FRAMES.length;\n this.repaint();\n }, 80);\n // Do not hold the event loop open on the spinner alone.\n this.timer.unref?.();\n }\n\n /** Stops the animation and clears the transient block for good. */\n stop(): void {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n this.erase();\n this.lines = [];\n }\n\n /** The current spinner glyph, for a caller that wants one frame rather than an animation. */\n spinner(): string {\n return isInteractive() ? Status.FRAMES[this.spinnerIndex] : '·';\n }\n\n private frame(line: string): string {\n return line.includes(SPINNER) ? line.split(SPINNER).join(this.spinner()) : line;\n }\n\n private repaint(): void {\n this.erase();\n const width = terminalWidth();\n for (const line of this.lines) {\n process.stdout.write(truncate(this.frame(line), width) + '\\n');\n }\n this.painted = this.lines.length;\n }\n\n private erase(): void {\n if (this.painted === 0) return;\n // Move up over what was painted and clear each row, leaving the cursor where the block began.\n process.stdout.write(CURSOR_UP(this.painted) + CLEAR_BELOW);\n this.painted = 0;\n }\n}\n\n/**\n * Runs `work` while showing a spinner captioned `label`, then reports the outcome on one line.\n * Replaces the `process.stdout.write('Doing thing ...')` / `console.log(' done')` pattern, which\n * showed no sign of life during the wait it was meant to explain.\n */\nexport async function withStatus<T>(label: string, work: () => Promise<T>): Promise<T> {\n const status = new Status();\n status.set([`${chalk.cyan(SPINNER)} ${label}`]);\n status.start();\n const startedAt = Date.now();\n try {\n const result = await work();\n status.stop();\n console.log(`${chalk.green('✓')} ${label} ${chalk.dim(`(${Date.now() - startedAt}ms)`)}`);\n return result;\n } catch (error) {\n status.stop();\n console.error(`${chalk.red('✗')} ${label}`);\n throw error;\n }\n}\n\n/** A determinate bar, `[████████░░░░░░░░]`, sized to `width` cells. */\nexport function bar(fraction: number, width = 28): string {\n const clamped = Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0));\n const filled = Math.round(clamped * width);\n return chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(width - filled));\n}\n\n/** `16%`, padded so a bar beside it does not jitter as the number gains digits. */\nexport function percent(fraction: number): string {\n const clamped = Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0));\n return `${Math.round(clamped * 100)}%`.padStart(4);\n}\n\n/** The most decimals a quality is ever read at. */\nconst QUALITY_MAX_DECIMALS = 4;\n\n/**\n * A quality, a unit fraction, as the web app reads it while a search runs: a percentage with as many\n * decimals as it takes to show where it moves, one, and one more while the decimals shown are all\n * nines, up to four. Floored, never rounded up, so only an exact result reads 100%. 0.6134 reads\n * 61.3%, 0.999751 reads 99.97%, 0.999951 reads 99.995%. The same rule as the app's `qualityPercent`\n * (`app/src/app/common/run-progress.ts`), pinned by the same figures, so the two surfaces never show\n * one search at two qualities.\n */\nexport function qualityPercent(quality: number): string {\n const unit = Math.max(0, Math.min(Number.isFinite(quality) ? quality : 0, 1));\n if (unit >= 1) return '100%';\n let decimals = 1;\n let shown = flooredPercent(unit, decimals);\n while (decimals < QUALITY_MAX_DECIMALS && /\\.9+$/.test(shown)) {\n decimals++;\n shown = flooredPercent(unit, decimals);\n }\n return `${decimals > 1 ? shown.replace(/0+$/, '') : shown}%`;\n}\n\n/**\n * A unit fraction floored as a percentage with the given decimals. Floored on the fraction, in\n * decimal, before scaling, so a binary product such as 0.999751 × 100 = 99.97509999 cannot shift the\n * last digit shown.\n */\nfunction flooredPercent(unit: number, decimals: number): string {\n return (shift(Math.floor(shift(unit, decimals + 2)), -(decimals + 2)) * 100).toFixed(decimals);\n}\n\n/** Multiplies by ten to the given power exactly in decimal, using exponent notation. */\nfunction shift(value: number, exponent: number): number {\n const [mantissa, magnitude] = value.toExponential().split('e');\n return Number(`${mantissa}e${Number(magnitude) + exponent}`);\n}\n","import type { ApiClient } from '../client/api.js';\n\n/** The languages a function can be written in, in the order the platform offers them. */\nexport const FUNCTION_LANGUAGES = ['Java', 'Kotlin', 'Python', 'JavaScript', 'Scala'] as const;\n\n/**\n * The language a function runs in when neither the function nor its project names one. The platform\n * applies the same fallback server-side, so this only decides what the CLI displays and sends.\n */\nexport const DEFAULT_FUNCTION_LANGUAGE = 'Java';\n\n/**\n * Resolves the language to evaluate in: an explicit `--language` wins, then the project's default,\n * then Java. A project that predates the language setting carries none, hence the final fallback.\n *\n * A project that cannot be read (no permission, transient failure) must not stop the command, so\n * this falls back rather than throwing.\n */\nexport async function resolveLanguage(\n api: ApiClient,\n projectId: string,\n explicit?: string | null,\n): Promise<string> {\n if (explicit) {\n return explicit;\n }\n try {\n const project = await api.admin.getProject(projectId);\n if (project?.language) {\n return project.language;\n }\n } catch {\n // Fall through to the default.\n }\n return DEFAULT_FUNCTION_LANGUAGE;\n}\n","import type { ApiClient } from '../client/api.js';\nimport type { SearchItem } from '../client/types/index-search.js';\n\n/**\n * Project names, which the project rows do not carry.\n *\n * A project's name lives on its main entity, and the search index is where names are readable in\n * bulk. The index's newest-first project page answers most listings in one call; a project older\n * than that page is asked for by id. The index matches whole words only, so a name cannot be found\n * by searching for it; it is always looked up by project.\n */\n\nconst FIRST_PAGE = 100;\nconst CONCURRENCY = 8;\n\n/**\n * Names for `projectIds`, by id. An id the index does not know is simply absent. A failure to read\n * the first page rejects, so the caller can say the names are missing; a failed lookup for one\n * project only leaves that project unnamed.\n */\nexport async function projectNames(\n api: Pick<ApiClient, 'index'>,\n projectIds: readonly string[],\n): Promise<Map<string, string>> {\n const wanted = new Set(projectIds);\n const names = new Map<string, string>();\n if (wanted.size === 0) return names;\n\n const take = (items: readonly SearchItem[]) => {\n for (const item of items) {\n if (item.contentType !== 'project' || !item.name || !wanted.has(item.projectId)) continue;\n if (!names.has(item.projectId)) names.set(item.projectId, item.name);\n }\n };\n\n take((await api.index.searchPage({ query: '*', contentType: 'project', limit: FIRST_PAGE })).items);\n\n const missing = [...wanted].filter((id) => !names.has(id));\n for (let i = 0; i < missing.length; i += CONCURRENCY) {\n const pages = await Promise.all(missing.slice(i, i + CONCURRENCY).map((projectId) =>\n api.index.searchPage({ query: '*', contentType: 'project', projectId, projectBranch: 'main', limit: 5 })\n .catch(() => null)));\n for (const page of pages) if (page) take(page.items);\n }\n return names;\n}\n","/**\n * Entity attribute values travel as base64-encoded bytes, the way the platform's serializers store them: text\n * as UTF-8, an integer as an 8-byte big-endian long. A plain string sent as an attribute value is read as\n * base64 on the server, which either rejects it or stores other bytes than the ones meant.\n */\n\nexport function encodeTextAttribute(value: string): string {\n return Buffer.from(value, 'utf-8').toString('base64');\n}\n\nexport function decodeTextAttribute(value: string | null | undefined): string | null {\n if (value === null || value === undefined) return null;\n return Buffer.from(value, 'base64').toString('utf-8');\n}\n\nexport function encodeLongAttribute(value: number): string {\n if (!Number.isSafeInteger(value)) {\n throw new RangeError(`Not an integer attribute value: ${value}`);\n }\n const bytes = Buffer.alloc(8);\n bytes.writeBigInt64BE(BigInt(value));\n return bytes.toString('base64');\n}\n","import type { Entity } from '../client/types/storage.js';\nimport { encodeTextAttribute } from './entity-attributes.js';\n\n/**\n * A project's root entity: the entity whose id is the project id, on the main branch. The project's name and\n * description live on it, and its notebooks hang off it under the `main` link, so a project without one has\n * no name and nothing to attach to. Without a name the root stays unnamed, and a project bundle imported\n * into it afterwards names it.\n */\nexport function buildProjectRootEntity(args: {\n projectId: string;\n name?: string;\n description?: string;\n}): Entity {\n const now = Date.now();\n const attributes: Record<string, string> = {};\n const attributeTypes: Record<string, string> = {};\n if (args.name) {\n attributes.name = encodeTextAttribute(args.name);\n attributeTypes.name = 'text';\n }\n if (args.description) {\n attributes.description = encodeTextAttribute(args.description);\n attributeTypes.description = 'text';\n }\n return {\n projectId: args.projectId,\n projectBranch: 'main',\n entityId: args.projectId,\n entityBranch: 'main',\n head: true,\n version: 1,\n type: 'project',\n attributes,\n attributeTypes,\n metaAttributes: {},\n metaAttributeTypes: {},\n tags: [],\n modified: now,\n created: now,\n versioned: false,\n versionTtl: null,\n retain: false,\n contentAvailable: false,\n contentLoaded: false,\n contentType: null,\n contentSize: null,\n content: null,\n };\n}\n\n/**\n * The root entity as read, with a new name and/or description. Everything else it carries is kept, because a\n * save removes the attributes and tags it does not send; its content (the project image) is left out, which\n * leaves the stored image as it is. An empty description removes it.\n */\nexport function withProjectTexts(root: Entity, texts: { name?: string; description?: string }): Entity {\n const attributes: Record<string, string> = { ...(root.attributes ?? {}) };\n const attributeTypes: Record<string, string> = { ...(root.attributeTypes ?? {}) };\n if (texts.name !== undefined) {\n attributes.name = encodeTextAttribute(texts.name.trim());\n attributeTypes.name = 'text';\n }\n if (texts.description !== undefined) {\n const description = texts.description.trim();\n if (description) {\n attributes.description = encodeTextAttribute(description);\n attributeTypes.description = 'text';\n } else {\n delete attributes.description;\n delete attributeTypes.description;\n }\n }\n return { ...root, attributes, attributeTypes, content: null };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { isDryRun } from '../../client/http.js';\nimport { handleError, usageError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, success } from '../../output/messages.js';\nimport { parseEntityReference, parseProjectReference, type ResolvedReference } from '../../util/references.js';\nimport { canonicalTags, planTagChange, sortTags, TagError, type TagOperation } from '../../util/tags.js';\n\n/**\n * `entity tags` and `project tags`: the same four commands on two ways of naming an entity.\n *\n * A project's own tags are the tags of its project entity, the entity whose id is the project's id.\n * They are the ones Explore's \"data domain\" filter and the search index read, so `project tags` is\n * `entity tags` with that entity filled in.\n */\nexport type TagTarget = 'entity' | 'project';\n\n/** What a tag command prints with `--output json`. `added` and `removed` are absent on `get`. */\nexport interface TagsResult extends ResolvedReference {\n /** The tags the entity carries now, sorted; under `--dry-run`, the ones it would carry. */\n tags: string[];\n added?: string[];\n removed?: string[];\n dryRun?: true;\n}\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction resolve(target: TagTarget, ref: string, cmd: Command): ResolvedReference {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n const overrides = { project: opts.project, branch: opts.branch };\n if (target === 'entity') return parseEntityReference(ref, overrides);\n const project = parseProjectReference(ref, overrides);\n return { ...project, entityId: project.projectId, entityBranch: 'main' };\n}\n\nfunction printTags(result: TagsResult, outputFormat: OutputFormat): void {\n if (outputFormat === 'json') {\n format(result, { format: outputFormat });\n } else if (outputFormat === 'table') {\n format(result.tags.map((tag) => ({ tag })), { format: outputFormat, columns: ['tag'] });\n } else if (result.tags.length === 0) {\n empty('tags');\n } else {\n console.log(result.tags.join(', '));\n }\n}\n\nfunction describeChange(added: string[], removed: string[]): string {\n const parts = [\n ...(added.length ? [`added ${added.join(', ')}`] : []),\n ...(removed.length ? [`removed ${removed.join(', ')}`] : []),\n ];\n return parts.join('; ');\n}\n\nasync function show(target: TagTarget, ref: string, cmd: Command): Promise<void> {\n const resolved = resolve(target, ref, cmd);\n const entity = await createApiClient().storage.getEntity(resolved);\n printTags({ ...resolved, tags: sortTags(entity.tags ?? []) }, getOutputFormat(cmd));\n}\n\nasync function change(target: TagTarget, operation: TagOperation, ref: string, given: string | string[], cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const resolved = resolve(target, ref, cmd);\n const { tags, renamed } = canonicalTags(Array.isArray(given) ? given : [given]);\n if (tags.length === 0 && operation !== 'set') {\n usageError('No tags given.', `Name at least one: diafunc ${target} tags ${operation} ${ref} <tag> [<tag>...]`);\n }\n // On stderr: a note about the input, not part of the result.\n for (const [typed, tag] of renamed) {\n console.error(chalk.dim(`\"${typed}\" is written as \"${tag}\", the form tags are searched by.`));\n }\n\n const api = createApiClient();\n // Read first, also under --dry-run: the write is the difference to what is there, and a\n // transaction would create an entity that does not exist instead of reporting it.\n const current = (await api.storage.getEntity(resolved)).tags ?? [];\n const plan = planTagChange(operation, current, tags);\n const noun = target === 'project' ? `project \"${resolved.projectId}\"` : `entity \"${resolved.entityId}\"`;\n\n if (plan.addTags.length === 0 && plan.removeTags.length === 0) {\n if (outputFormat === 'human') success(`Tags of ${noun} are already as asked; nothing changed.`);\n printTags({ ...resolved, tags: sortTags(current), added: [], removed: [] }, outputFormat);\n return;\n }\n\n await api.storage.changeEntityTags(resolved, { addTags: plan.addTags, removeTags: plan.removeTags });\n\n const outcome = { added: plan.addTags, removed: plan.removeTags };\n if (isDryRun()) {\n // Nothing was written, so there is nothing to read back: this is the set the request leads to.\n if (outputFormat === 'human') console.log(chalk.dim(`Would leave ${noun} with:`));\n printTags({ ...resolved, tags: plan.result, ...outcome, dryRun: true }, outputFormat);\n return;\n }\n\n const stored = (await api.storage.getEntity(resolved)).tags ?? [];\n if (outputFormat === 'human') success(`Tags of ${noun} updated: ${describeChange(plan.addTags, plan.removeTags)}.`);\n printTags({ ...resolved, tags: sortTags(stored), ...outcome }, outputFormat);\n}\n\nfunction guarded(run: () => Promise<void>): Promise<void> {\n return run().catch((error: unknown) => {\n if (error instanceof TagError) usageError(error.message);\n handleError(error);\n });\n}\n\nconst NORMALISATION = `\nTags are written in the form they are searched by: lowercase, accents dropped,\nspaces and underscores as \"-\", punctuation removed (\"Machine Learning\" becomes\n\"machine-learning\"). Tags beginning with \"auto-analysis-staging\" or \"staging-run\"\nare reserved for analysis runs and are refused.`;\n\nexport function registerTagCommands(parent: Command, target: TagTarget): void {\n const argName = target === 'project' ? '<projectId>' : '<ref>';\n const argHelp = target === 'project' ? 'Project ID (or projectId/branch)' : 'Entity reference';\n const example = target === 'project' ? 'diafunc project tags' : 'diafunc entity tags';\n const sample = target === 'project' ? '<projectId>' : '<project>/main/<entity>/main';\n\n const tags = parent\n .command('tags')\n .description(target === 'project'\n ? \"Show and change a project's tags, the ones Explore and the search filter by\"\n : \"Show and change an entity's tags\")\n .addHelpText('after', `${target === 'project' ? `\nA project's tags are the tags of its project entity, so this is 'diafunc entity tags'\non <projectId>/main/<projectId>/main. Changing them needs edit access to the project.\n` : ''}${NORMALISATION}\n\nExamples:\n $ ${example} get ${sample}\n $ ${example} add ${sample} health \"Machine Learning\"\n $ ${example} remove ${sample} health\n $ ${example} set ${sample} energy climate exactly these two\n $ ${example} set ${sample} \"\" no tags at all\n $ diafunc admin curated-tags list the tags Explore offers as data domains\n`);\n\n tags\n .command('get')\n .description(`Show the tags of ${target === 'project' ? 'a project' : 'an entity'}`)\n .argument(argName, argHelp)\n .addHelpText('after', `\nExamples:\n $ ${example} get ${sample}\n $ ${example} get ${sample} -o json { ..., \"tags\": [\"energy\", \"health\"] }\n`)\n .action((ref: string, _options, cmd: Command) => guarded(() => show(target, ref, cmd)));\n\n tags\n .command('add')\n .description('Add tags; one that is already there is left as it is')\n .argument(argName, argHelp)\n .argument('<tags...>', 'Tags to add, as separate arguments or comma-separated')\n .addHelpText('after', `${NORMALISATION}\n\nExamples:\n $ ${example} add ${sample} health\n $ ${example} add ${sample} health energy \"Machine Learning\"\n $ ${example} add ${sample} health --dry-run print the request, send nothing\n`)\n .action((ref: string, given: string[], _options, cmd: Command) => guarded(() => change(target, 'add', ref, given, cmd)));\n\n tags\n .command('remove')\n .description('Remove tags; one that is not there is ignored')\n .argument(argName, argHelp)\n .argument('<tags...>', 'Tags to remove, as separate arguments or comma-separated')\n .addHelpText('after', `\nA tag is matched in any spelling of the same tag: \"Health\" also removes a stored \"health\".\n\nExamples:\n $ ${example} remove ${sample} health\n $ ${example} remove ${sample} health,energy --dry-run\n`)\n .action((ref: string, given: string[], _options, cmd: Command) => guarded(() => change(target, 'remove', ref, given, cmd)));\n\n tags\n .command('set')\n .description('Replace the tags: afterwards exactly the given ones are there')\n .argument(argName, argHelp)\n .argument('<tags...>', 'The complete tag set, as separate arguments or comma-separated (a single empty string removes every tag)')\n .addHelpText('after', `${NORMALISATION}\n\nEvery tag that is not named is taken off, including ones the platform set itself\n(an analysis marks what it generates with \"auto-analysis\", for example).\n\nExamples:\n $ ${example} set ${sample} energy climate\n $ ${example} set ${sample} \"\" no tags at all\n $ ${example} set ${sample} energy --dry-run print the request, send nothing\n`)\n .action((ref: string, given: string[], _options, cmd: Command) => guarded(() => change(target, 'set', ref, given, cmd)));\n}\n","/**\n * Tags as the platform reads them.\n *\n * Storage keeps a tag exactly as it was written. The search index does not: it folds every tag to\n * one canonical form before a filter, a facet count or a curated tag is matched against it, and it\n * keeps a small family of internal markers out of the index altogether. A tag written as\n * `Machine Learning` is therefore found as `machine-learning`, and one written as `staging-run:4af2`\n * is never found. The CLI writes the canonical form to begin with, so what a reader sees on the\n * entity is what Explore filters by.\n *\n * `normalizeTag` mirrors `TagNormalizer.java` and `isReservedTag` mirrors `ReservedTags.java`\n * (platform, `services/index/core/.../tag/`); the cases of `tags.test.ts` are the platform's own\n * (`services/index/doc/tag-normalization.md`). A change on either side has to reach the other.\n */\n\nconst NON_SPACING_MARK = /^\\p{Mn}$/u;\nconst LETTER_OR_DIGIT = /^[\\p{L}\\p{Nd}]$/u;\nconst SPACE_SEPARATOR = /^[\\p{Zs}\\p{Zl}\\p{Zp}]$/u;\n/** Space separators Java's `Character.isWhitespace` does not count: the non-breaking ones. */\nconst NON_BREAKING = new Set([' ', ' ', ' ']);\nconst CONTROL_WHITESPACE = /^[\\t\\n\\u000B\\f\\r\\u001C-\\u001F]$/;\n\nfunction isWhitespace(ch: string): boolean {\n return CONTROL_WHITESPACE.test(ch) || (SPACE_SEPARATOR.test(ch) && !NON_BREAKING.has(ch));\n}\n\n/**\n * The canonical form of a tag: lowercase, diacritics stripped, letters and digits of any script\n * kept, runs of whitespace, `-` and `_` collapsed to one `-` between them, everything else dropped.\n * Empty when nothing of the tag survives.\n */\nexport function normalizeTag(raw: string): string {\n const decomposed = raw.normalize('NFD');\n let out = '';\n let lastWasDash = false;\n // By UTF-16 unit, as the platform walks it: a character outside the basic plane is two units,\n // neither of which is a letter, so it is dropped on both sides.\n for (let i = 0; i < decomposed.length; i++) {\n const ch = decomposed[i];\n if (NON_SPACING_MARK.test(ch)) continue;\n const lowered = ch.toLowerCase();\n const lower = lowered.length === 1 ? lowered : ch;\n if (LETTER_OR_DIGIT.test(lower)) {\n out += lower;\n lastWasDash = false;\n } else if (lower === '-' || lower === '_' || isWhitespace(lower)) {\n if (out.length > 0 && !lastWasDash) {\n out += '-';\n lastWasDash = true;\n }\n }\n }\n return lastWasDash ? out.slice(0, -1) : out;\n}\n\n/** Canonical-tag prefixes of the markers an analysis run stamps on its staging content. */\nconst RESERVED_PREFIXES = ['auto-analysis-staging', 'staging-run'];\n\n/** Whether a canonical tag is an internal marker the index keeps off every public surface. */\nexport function isReservedTag(normalized: string): boolean {\n return RESERVED_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** A tag the CLI will not write, with the reason in words the reader can act on. */\nexport class TagError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TagError';\n }\n}\n\nexport interface CanonicalTags {\n /** The canonical tags, in the order given, each once. */\n tags: string[];\n /** The tags that were written differently from their canonical form, as `[typed, canonical]`. */\n renamed: Array<[string, string]>;\n}\n\n/**\n * The canonical form of the tags a command was given. A tag may itself be a comma-separated list,\n * so `add ref health,energy` and `add ref health energy` mean the same.\n *\n * @throws TagError for a tag nothing of which survives, and for a reserved one.\n */\nexport function canonicalTags(given: readonly string[]): CanonicalTags {\n const tags: string[] = [];\n const renamed: Array<[string, string]> = [];\n for (const typed of given.flatMap((entry) => entry.split(',')).map((entry) => entry.trim())) {\n if (typed === '') continue;\n const tag = normalizeTag(typed);\n if (tag === '') {\n throw new TagError(`\"${typed}\" is not a usable tag: a tag needs at least one letter or digit.`);\n }\n if (isReservedTag(tag)) {\n throw new TagError(\n `\"${typed}\" is reserved: tags beginning with ${RESERVED_PREFIXES.map((p) => `\"${p}\"`).join(' or ')} ` +\n `mark the staging content of an analysis run and are never searchable.`,\n );\n }\n if (tag !== typed) renamed.push([typed, tag]);\n if (!tags.includes(tag)) tags.push(tag);\n }\n return { tags, renamed };\n}\n\nexport type TagOperation = 'add' | 'remove' | 'set';\n\nexport interface TagChange {\n /** Tags to write, canonical. Empty when the entity has them all. */\n addTags: string[];\n /** Tags to take off, exactly as the entity stores them. Empty when it has none of them. */\n removeTags: string[];\n /** The tag set the entity has once the change is applied, sorted. */\n result: string[];\n}\n\n/**\n * What has to be written so that an entity carrying `current` ends up as asked.\n *\n * Only the difference is written, which is what makes a repeated `add` or `remove` a quiet no-op\n * rather than a new version of the entity. `remove` and `set` also take off a tag that is stored in\n * another spelling of the same canonical tag (`Health` for `health`): that is the tag the reader\n * means, and the platform removes by exact text only.\n */\nexport function planTagChange(operation: TagOperation, current: readonly string[], tags: readonly string[]): TagChange {\n const wanted = new Set(tags);\n let addTags: string[] = [];\n let removeTags: string[] = [];\n if (operation === 'add') {\n addTags = tags.filter((tag) => !current.includes(tag));\n } else if (operation === 'remove') {\n removeTags = current.filter((stored) => wanted.has(stored) || wanted.has(normalizeTag(stored)));\n } else {\n addTags = tags.filter((tag) => !current.includes(tag));\n removeTags = current.filter((stored) => !wanted.has(stored));\n }\n const result = [...current.filter((stored) => !removeTags.includes(stored)), ...addTags];\n return { addTags, removeTags, result: sortTags(result) };\n}\n\nexport function sortTags(tags: readonly string[]): string[] {\n return [...tags].sort((a, b) => a.localeCompare(b));\n}\n","import * as readline from 'node:readline';\nimport chalk from 'chalk';\n\nexport interface ConfirmOpts {\n /** Bypass the prompt (--yes / -y flag). Safe for CI / non-interactive use. */\n yes?: boolean;\n /**\n * The exact string the user must type to proceed.\n * When omitted the user must type the word \"yes\".\n */\n resourceId?: string;\n}\n\n/**\n * Guard for destructive CLI commands.\n *\n * Behaviour:\n * - Non-interactive stdin OR `opts.yes` is true → returns immediately.\n * - Interactive TTY → prints a warning and prompts the user to type the\n * resource id (or \"yes\" if no resourceId given). Calls `process.exit(1)`\n * when the answer does not match.\n */\nexport async function confirmDestructive(message: string, opts: ConfirmOpts = {}): Promise<void> {\n if (!process.stdin.isTTY || opts.yes) return;\n\n const expected = opts.resourceId ?? 'yes';\n const hint = opts.resourceId ? `\"${opts.resourceId}\"` : '\"yes\"';\n\n console.log(chalk.yellow(`! ${message}`));\n\n const answer = await new Promise<string>((resolve) => {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n rl.question(` Type ${hint} to confirm: `, (ans) => {\n rl.close();\n resolve(ans);\n });\n });\n\n if (answer.trim() !== expected) {\n console.log(chalk.dim('Aborted.'));\n process.exit(1);\n }\n}\n","import { Command } from 'commander';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { isDryRun } from '../../client/http.js';\nimport type {\n PreviousOwnerRole,\n ProjectTransfer,\n ProjectTransferDirection,\n ProjectTransferOffer,\n} from '../../client/types/admin.js';\nimport { format, formatInstant, formatNumber, type ColumnInput, type OutputFormat } from '../../output/formatter.js';\nimport { detail, empty, hint, success } from '../../output/messages.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { CliError, EXIT_USAGE, handleError } from '../../util/errors.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/** One transfer, read top to bottom: the project, who gives it to whom, and what it costs. */\nexport const TRANSFER_RECORD: readonly ColumnInput[] = [\n { key: 'projectName', header: 'project' },\n { key: 'projectId', kind: 'id' },\n { key: 'status', kind: 'state' },\n { key: 'fromUserName', header: 'from' },\n { key: 'toUserName', header: 'to' },\n { key: 'toUserId', kind: 'id' },\n { key: 'toTeamName', header: 'into team' },\n { key: 'previousOwnerRole', header: 'previous owner keeps' },\n { key: 'message' },\n { key: 'visibility' },\n { key: 'licenceId', header: 'license' },\n { key: 'storageCreditsPerMonth', header: 'storage credits per month', kind: 'number' },\n { key: 'lastRunCredits', header: 'last run credits', kind: 'number' },\n { key: 'offeredAt', kind: 'date' },\n { key: 'expiresAt', kind: 'date' },\n { key: 'completedAt', kind: 'date' },\n];\n\nconst TRANSFER_ROWS: readonly ColumnInput[] = [\n { key: 'projectName', header: 'project' },\n { key: 'projectId', kind: 'id' },\n { key: 'status', kind: 'state' },\n { key: 'fromUserName', header: 'from' },\n { key: 'toUserName', header: 'to' },\n { key: 'toTeamName', header: 'team' },\n { key: 'expiresAt', kind: 'date' },\n];\n\n/** `NONE` unless the owner asked to stay on the project as a maintainer. */\nexport function previousOwnerRole(keep: boolean | undefined): PreviousOwnerRole {\n return keep ? 'MAINTAINER' : 'NONE';\n}\n\n/**\n * The offer's body. The recipient is named by user id or by e-mail address; an address is told\n * apart by its `@`, which a user id never contains.\n */\nexport function buildOffer(\n recipient: string,\n options: { team?: string; keepMe?: boolean; message?: string },\n): ProjectTransferOffer {\n const who = recipient.trim();\n if (!who) throw new CliError('Name the new owner by user ID or e-mail address.', { exitCode: EXIT_USAGE });\n return {\n ...(who.includes('@') ? { toEmail: who } : { toUserId: who }),\n ...(options.team ? { toTeamId: options.team } : {}),\n previousOwnerRole: previousOwnerRole(options.keepMe),\n ...(options.message !== undefined && options.message.trim() ? { message: options.message.trim() } : {}),\n };\n}\n\n/** The sentence the owner confirms before an offer goes out. */\nexport function offerWarning(projectId: string, offer: ProjectTransferOffer): string {\n const to = offer.toEmail ?? offer.toUserId;\n const into = offer.toTeamId ? ` (suggested team: ${offer.toTeamId})` : '';\n const after = offer.previousOwnerRole === 'MAINTAINER'\n ? 'you stay on it as a maintainer, with edit rights'\n : 'you lose access to it';\n return `This will offer project \"${projectId}\" to ${to}${into}. Once they accept, the project, its analyses `\n + `and their costs move to them, and ${after}.`;\n}\n\n/**\n * The team the accepted project goes into: `--team`, `--personal` (no team), or else the team the\n * owner suggested in the offer. The platform reads an absent `toTeamId` as \"personal\", so the\n * suggestion is sent explicitly rather than left out.\n */\nexport function acceptDestination(\n transfer: Pick<ProjectTransfer, 'toTeamId'>,\n options: { team?: string; personal?: boolean },\n): string | null {\n if (options.team && options.personal) {\n throw new CliError('Give --team or --personal, not both.', { exitCode: EXIT_USAGE });\n }\n if (options.personal) return null;\n if (options.team) return options.team;\n return transfer.toTeamId ?? null;\n}\n\n/** What the recipient takes on, said before they accept. */\nexport function acceptWarning(transfer: ProjectTransfer, toTeamId: string | null): string {\n const name = transfer.projectName ? `\"${transfer.projectName}\" (${transfer.projectId})` : `\"${transfer.projectId}\"`;\n const into = toTeamId\n ? ` into team ${toTeamId === transfer.toTeamId && transfer.toTeamName ? transfer.toTeamName : toTeamId}`\n : ' into your personal account';\n const costs: string[] = [];\n if (typeof transfer.storageCreditsPerMonth === 'number') {\n costs.push(`its storage costs ${formatNumber(transfer.storageCreditsPerMonth)} credits per month`);\n }\n if (typeof transfer.lastRunCredits === 'number') {\n costs.push(`its last analysis run cost ${formatNumber(transfer.lastRunCredits)} credits`);\n }\n const cost = costs.length > 0 ? ` From now on you pay for it: ${costs.join(', and ')}.` : ' From now on you pay for it.';\n return `This will make you the owner of project ${name}${into}.${cost}`;\n}\n\n/** Both directions, each row marked with its own, when the reader asked for neither. */\nexport function directionsFor(options: { incoming?: boolean; outgoing?: boolean }): ProjectTransferDirection[] {\n if (options.incoming && options.outgoing) {\n throw new CliError('Give --incoming or --outgoing, not both; leave both out to see either kind.', { exitCode: EXIT_USAGE });\n }\n if (options.incoming) return ['incoming'];\n if (options.outgoing) return ['outgoing'];\n return ['incoming', 'outgoing'];\n}\n\nexport function registerProjectTransferCommands(project: Command): void {\n const transfer = project\n .command('transfer')\n .description('Hand a project over to another account, or take one that is offered to you');\n\n transfer\n .command('start')\n .description('Offer a project to a new owner, who then accepts or declines it')\n .argument('<projectId>', 'Project ID')\n .argument('<userIdOrEmail>', \"The new owner's user ID or the e-mail address of their account\")\n .option('--team <teamId>', 'Suggest a team of the new owner the project goes into; they can choose another when accepting')\n .option('--keep-me', 'Stay on the project as a maintainer, with edit rights, after the move')\n .option('--message <text>', 'A note the new owner sees with the offer')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .addHelpText('after', `\nThe offer stays open for 14 days. The project goes on working normally until it is accepted.\n\nExamples:\n $ diafunc project transfer start <projectId> ana@example.com hand it over and leave it\n $ diafunc project transfer start <projectId> <userId> --keep-me hand it over and stay as a maintainer\n $ diafunc project transfer start <projectId> <userId> --team <teamId> -y suggest a team, no prompt\n`)\n .action(async (projectId: string, recipient: string, options: { team?: string; keepMe?: boolean; message?: string; yes?: boolean }, cmd) => {\n try {\n const offer = buildOffer(recipient, options);\n await confirmDestructive(offerWarning(projectId, offer), { yes: options.yes, resourceId: projectId });\n const api = createApiClient();\n const created = await api.admin.offerProjectTransfer(projectId, offer);\n if (isDryRun()) return;\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat !== 'human') {\n format(created, { format: outputFormat });\n return;\n }\n success(`Offered project \"${projectId}\" to ${created.toUserName ?? offer.toEmail ?? offer.toUserId}.`);\n if (created.expiresAt) detail(`The offer is open until ${formatInstant(created.expiresAt)}.`);\n hint(`Withdraw it with 'diafunc project transfer cancel ${projectId}'.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('status', { isDefault: true })\n .description('Show the open transfer of a project')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const open = await api.admin.getProjectTransfer(projectId);\n const outputFormat = getOutputFormat(cmd);\n if (!open) {\n if (outputFormat === 'json') {\n format(null, { format: outputFormat });\n } else {\n console.log(`No open transfer for project \"${projectId}\".`);\n }\n return;\n }\n format(open, { format: outputFormat, columns: outputFormat === 'json' ? undefined : TRANSFER_RECORD });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('accept')\n .description('Accept a project offered to you; it moves to your account at once')\n .argument('<projectId>', 'Project ID')\n .option('--team <teamId>', 'Take the project into this team, which you own or administer and have active')\n .option('--personal', 'Take the project into your personal account, whatever team the offer suggests')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .addHelpText('after', `\nWithout --team or --personal the project goes where the offer suggests. The move is refused while\nan analysis of the project runs or waits, or a table import or refresh is running; the offer then\nstays open, so accept again once that work has finished.\n\nExamples:\n $ diafunc project transfer list --incoming the projects offered to you\n $ diafunc project transfer status <projectId> what it costs, before you accept\n $ diafunc project transfer accept <projectId> --personal take it into your own account\n`)\n .action(async (projectId: string, options: { team?: string; personal?: boolean; yes?: boolean }, cmd) => {\n try {\n const api = createApiClient();\n const open = await api.admin.getProjectTransfer(projectId);\n if (!open) {\n throw new CliError(`No open transfer for project \"${projectId}\".`, {\n hint: `List the projects offered to you with 'diafunc project transfer list --incoming'.`,\n });\n }\n const toTeamId = acceptDestination(open, options);\n await confirmDestructive(acceptWarning(open, toTeamId), { yes: options.yes, resourceId: projectId });\n const accepted = await api.admin.acceptProjectTransfer(projectId, toTeamId);\n if (isDryRun()) return;\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat !== 'human') {\n format(accepted, { format: outputFormat });\n return;\n }\n if (accepted.status === 'COMPLETED') {\n success(`You now own project \"${accepted.projectName ?? projectId}\".`);\n } else {\n success(`Project transfer ${accepted.status}.`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('decline')\n .description('Decline a project offered to you')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.declineProjectTransfer(projectId);\n success(`Declined the transfer of project \"${projectId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('cancel')\n .description('Withdraw an offer you made, while it is still open')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.withdrawProjectTransfer(projectId);\n success(`Withdrew the transfer of project \"${projectId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('list')\n .description('List the project transfers offered to you and by you')\n .option('--incoming', 'Only the projects offered to you')\n .option('--outgoing', 'Only the projects you offered')\n .option('--all', 'Include finished transfers: accepted, declined, withdrawn and expired')\n .action(async (options: { incoming?: boolean; outgoing?: boolean; all?: boolean }, cmd) => {\n try {\n const directions = directionsFor(options);\n const status = options.all ? 'all' : 'open';\n const api = createApiClient();\n const lists = await Promise.all(directions.map(async (direction) =>\n (await api.admin.listProjectTransfers(direction, status) ?? []).map((t) => ({ direction, ...t }))));\n const rows = lists.flat();\n const outputFormat = getOutputFormat(cmd);\n if (rows.length === 0) {\n empty(options.all ? 'project transfers' : 'open project transfers', { format: outputFormat });\n return;\n }\n const columns = directions.length > 1 ? [{ key: 'direction' }, ...TRANSFER_ROWS] : TRANSFER_ROWS;\n format(rows, { format: outputFormat, columns });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { success } from '../../output/messages.js';\nimport type { BillingInterval, InvoicePreview, TeamMemberRole } from '../../client/types/admin.js';\n\nconst ROLES: TeamMemberRole[] = ['OWNER', 'ADMIN', 'MEMBER'];\nconst INTERVALS: BillingInterval[] = ['MONTHLY', 'YEARLY'];\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function parseRole(value: string): TeamMemberRole {\n const role = value.trim().toUpperCase() as TeamMemberRole;\n if (!ROLES.includes(role)) {\n throw new Error(`Invalid role \"${value}\". Expected one of: ${ROLES.join(', ')}.`);\n }\n return role;\n}\n\nexport function parseInterval(value: string): BillingInterval {\n const interval = value.trim().toUpperCase() as BillingInterval;\n if (!INTERVALS.includes(interval)) {\n throw new Error(`Invalid billing interval \"${value}\". Expected one of: ${INTERVALS.join(', ')}.`);\n }\n return interval;\n}\n\nexport function parseCount(value: string, label: string): number {\n const count = Number(value);\n if (!Number.isInteger(count) || count < 0) {\n throw new Error(`Invalid ${label} \"${value}\". Expected a non-negative whole number.`);\n }\n return count;\n}\n\n/** Renders the money in an invoice preview, including the line items that explain it. */\nexport function formatMoney(cents: number, currency: string): string {\n const sign = cents < 0 ? '-' : '';\n const abs = Math.abs(cents);\n return `${sign}${(abs / 100).toFixed(2)} ${currency.toUpperCase()}`;\n}\n\nfunction printInvoicePreview(preview: InvoicePreview, outputFormat: OutputFormat): void {\n if (outputFormat === 'json') {\n format(preview, { format: outputFormat });\n return;\n }\n format(\n preview.lineItems.map(item => ({\n description: item.description,\n amount: formatMoney(item.amountCents, preview.currency),\n })),\n { format: outputFormat, columns: ['description', 'amount'] },\n );\n console.log(`Total: ${formatMoney(preview.totalCents, preview.currency)}`);\n if (preview.nextBillingDate) {\n const next = preview.nextBillingAmountCents;\n console.log(\n `Next bill: ${preview.nextBillingDate}` +\n (next !== null && next !== undefined ? ` for ${formatMoney(next, preview.currency)}` : ''),\n );\n }\n}\n\nexport function registerTeamCommands(program: Command): void {\n const team = program\n .command('team')\n .description('Manage teams: membership, invitations, seats, billing, and ownership')\n .addHelpText('after', `\nExamples:\n $ diafunc team list the teams you belong to\n $ diafunc team use <teamId> work under one\n $ diafunc team usage <teamId> credits, by member\n $ diafunc team members invite <teamId> <email> MEMBER\n`);;\n\n team\n .command('list', { isDefault: true })\n .description('List the teams you belong to')\n .action(async (_options, cmd) => {\n try {\n const api = createApiClient();\n const teams = await api.admin.listMyTeams();\n format(teams, {\n format: getOutputFormat(cmd),\n columns: ['id', 'name', 'planId', 'seatCount', 'packCount', 'renewal'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('get')\n .description('Show a team')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n format(await api.admin.getTeam(teamId), {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('use')\n .description('Set your active team (new projects are created under it)')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.setActiveTeam(teamId);\n success(`Active team set to \"${teamId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('usage')\n .description('Show credit usage for a team, broken down by member')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const usage = await api.admin.getTeamUsage(teamId);\n if (outputFormat === 'json') {\n format(usage, { format: outputFormat });\n return;\n }\n console.log(\n `${usage.year}-${String(usage.month).padStart(2, '0')} ` +\n `${usage.totalCredits} credits used of ${usage.baselineCredits} included`,\n );\n format(usage.members, {\n format: outputFormat,\n columns: ['userId', 'name', 'email', 'credits'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('create')\n .description('Start checkout for a new team and print the URL to complete it in a browser')\n .requiredOption('--name <name>', 'Team name')\n .requiredOption('--plan <planId>', 'Plan ID')\n .requiredOption('--seats <count>', 'Number of seats')\n .option('--interval <interval>', 'Billing interval (MONTHLY, YEARLY)', 'MONTHLY')\n .option('--packs <count>', 'Number of credit extension packs')\n .option('--currency <currency>', 'Billing currency (e.g. EUR, USD)')\n .action(async (options: {\n name: string;\n plan: string;\n seats: string;\n interval: string;\n packs?: string;\n currency?: string;\n }, cmd) => {\n try {\n const api = createApiClient();\n const session = await api.admin.startTeamCheckout({\n name: options.name,\n planId: options.plan,\n billingInterval: parseInterval(options.interval),\n seatCount: parseCount(options.seats, 'seat count'),\n ...(options.packs !== undefined ? { packCount: parseCount(options.packs, 'pack count') } : {}),\n ...(options.currency !== undefined ? { currency: options.currency.toUpperCase() } : {}),\n });\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat === 'json') {\n format(session, { format: outputFormat });\n return;\n }\n console.log('Open this URL to complete checkout:');\n console.log(chalk.cyan(session.url));\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('portal')\n .description('Open the billing portal for a team and print the URL')\n .argument('<teamId>', 'Team ID')\n .option('--return-url <url>', 'Where the portal returns to when done', 'https://diafunc.com/team')\n .action(async (teamId: string, options: { returnUrl: string }, cmd) => {\n try {\n const api = createApiClient();\n const session = await api.admin.createTeamPortalSession(teamId, options.returnUrl);\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat === 'json') {\n format(session, { format: outputFormat });\n return;\n }\n console.log('Open this URL to manage billing:');\n console.log(chalk.cyan(session.url));\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('cancel')\n .description(\"Cancel a team's subscription at the end of the current period\")\n .argument('<teamId>', 'Team ID')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(\n `This will cancel team \"${teamId}\" at the end of the current billing period.`,\n { yes: options.yes, resourceId: teamId },\n );\n const api = createApiClient();\n const response = await api.admin.cancelTeam(teamId);\n success(\n `Team \"${teamId}\" canceled. Access ends ${response.endsAt ?? 'at the end of the period'}.`,\n { format: getOutputFormat(cmd) },\n );\n } catch (error) {\n handleError(error);\n }\n });\n\n team\n .command('leave')\n .description('Leave a team you are a member of')\n .argument('<teamId>', 'Team ID')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will remove you from team \"${teamId}\".`, {\n yes: options.yes,\n resourceId: teamId,\n });\n const api = createApiClient();\n await api.admin.leaveTeam(teamId);\n success(`Left team \"${teamId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n registerMemberCommands(team);\n registerInvitationCommands(team);\n registerSeatCommands(team);\n registerPackCommands(team);\n registerOwnershipCommands(team);\n}\n\nfunction registerMemberCommands(team: Command): void {\n const members = team.command('members').description('Manage team members');\n\n members\n .command('list', { isDefault: true })\n .description('List team members')\n .argument('<teamId>', 'Team ID')\n .option('--all', 'Include members who have been removed from the team')\n .action(async (teamId: string, options: { all?: boolean }, cmd) => {\n try {\n const api = createApiClient();\n const all = await api.admin.listTeamMembers(teamId);\n const shown = options.all ? all : all.filter(m => !m.removedAt);\n format(shown, {\n format: getOutputFormat(cmd),\n columns: options.all\n ? ['userId', 'name', 'email', 'role', 'joinedAt', 'removedAt']\n : ['userId', 'name', 'email', 'role', 'joinedAt'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n members\n .command('invite')\n .description('Invite someone to the team by email')\n .argument('<teamId>', 'Team ID')\n .argument('<email>', 'Email address to invite')\n .option('--role <role>', 'Team role (OWNER, ADMIN, MEMBER)', 'MEMBER')\n .action(async (teamId: string, email: string, options: { role: string }, cmd) => {\n try {\n const role = parseRole(options.role);\n const api = createApiClient();\n await api.admin.inviteTeamMember(teamId, email, role);\n success(`Invited ${email} to team \"${teamId}\" as ${role}.`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n members\n .command('remove')\n .description('Remove a member from the team')\n .argument('<teamId>', 'Team ID')\n .argument('<userId>', 'User ID to remove')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, userId: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will remove ${userId} from team \"${teamId}\".`, {\n yes: options.yes,\n resourceId: userId,\n });\n const api = createApiClient();\n await api.admin.removeTeamMember(teamId, userId);\n success(`Removed ${userId} from team \"${teamId}\".`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction registerInvitationCommands(team: Command): void {\n const invitations = team.command('invitations').description('Manage pending team invitations');\n\n invitations\n .command('list', { isDefault: true })\n .description('List pending invitations')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n format(await api.admin.listTeamInvitations(teamId), {\n format: getOutputFormat(cmd),\n columns: ['invitationId', 'email', 'role', 'invitedBy', 'expiresAt'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n invitations\n .command('revoke')\n .description('Revoke a pending invitation')\n .argument('<teamId>', 'Team ID')\n .argument('<invitationId>', 'Invitation ID')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, invitationId: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will revoke invitation \"${invitationId}\".`, {\n yes: options.yes,\n resourceId: invitationId,\n });\n const api = createApiClient();\n await api.admin.revokeTeamInvitation(teamId, invitationId);\n success(`Revoked invitation \"${invitationId}\".`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n invitations\n .command('resend')\n .description('Resend a pending invitation email')\n .argument('<teamId>', 'Team ID')\n .argument('<invitationId>', 'Invitation ID')\n .action(async (teamId: string, invitationId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.resendTeamInvitation(teamId, invitationId);\n success(`Resent invitation \"${invitationId}\".`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n invitations\n .command('accept')\n .description('Accept a team invitation you received by email')\n .argument('<token>', 'Invitation token from the email link')\n .action(async (token: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const member = await api.admin.acceptTeamInvitation(token);\n success(`Joined the team as ${member.role}.`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction registerSeatCommands(team: Command): void {\n const seats = team.command('seats').description(\"Change a team's seat count\");\n\n seats\n .command('preview')\n .description('Preview the invoice for a seat-count change without applying it')\n .argument('<teamId>', 'Team ID')\n .argument('<count>', 'New seat count')\n .action(async (teamId: string, count: string, _options, cmd) => {\n try {\n const api = createApiClient();\n printInvoicePreview(\n await api.admin.previewTeamSeatCount(teamId, parseCount(count, 'seat count')),\n getOutputFormat(cmd),\n );\n } catch (error) {\n handleError(error);\n }\n });\n\n seats\n .command('set')\n .description('Change the seat count and bill the difference')\n .argument('<teamId>', 'Team ID')\n .argument('<count>', 'New seat count')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, count: string, options: { yes?: boolean }, cmd) => {\n try {\n const seatCount = parseCount(count, 'seat count');\n await confirmDestructive(\n `This will change the seat count of team \"${teamId}\" to ${seatCount} and adjust billing.`,\n { yes: options.yes, resourceId: teamId },\n );\n const api = createApiClient();\n const change = await api.admin.updateTeamSeatCount(teamId, seatCount);\n success(`Seats changed from ${change.oldSeatCount} to ${change.newSeatCount}.`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction registerPackCommands(team: Command): void {\n const packs = team.command('packs').description(\"Change a team's credit extension packs\");\n\n packs\n .command('preview')\n .description('Preview the invoice for a pack-count change without applying it')\n .argument('<teamId>', 'Team ID')\n .argument('<count>', 'New pack count')\n .action(async (teamId: string, count: string, _options, cmd) => {\n try {\n const api = createApiClient();\n printInvoicePreview(\n await api.admin.previewTeamPackCount(teamId, parseCount(count, 'pack count')),\n getOutputFormat(cmd),\n );\n } catch (error) {\n handleError(error);\n }\n });\n\n packs\n .command('set')\n .description('Change the pack count and bill the difference')\n .argument('<teamId>', 'Team ID')\n .argument('<count>', 'New pack count')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, count: string, options: { yes?: boolean }, cmd) => {\n try {\n const packCount = parseCount(count, 'pack count');\n await confirmDestructive(\n `This will change the extension packs of team \"${teamId}\" to ${packCount} and adjust billing.`,\n { yes: options.yes, resourceId: teamId },\n );\n const api = createApiClient();\n const change = await api.admin.updateTeamPackCount(teamId, packCount);\n success(`Packs changed from ${change.oldPackCount} to ${change.newPackCount}.`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction registerOwnershipCommands(team: Command): void {\n const transfer = team\n .command('transfer')\n .description('Transfer ownership of a team to another member');\n\n transfer\n .command('start')\n .description('Offer ownership to another member')\n .argument('<teamId>', 'Team ID')\n .argument('<userId>', 'User ID of the new owner')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, userId: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(\n `This will offer ownership of team \"${teamId}\" to ${userId}.`,\n { yes: options.yes, resourceId: teamId },\n );\n const api = createApiClient();\n format(await api.admin.initiateOwnershipTransfer(teamId, userId), {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('status', { isDefault: true })\n .description('Show the pending ownership transfer')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const pending = await api.admin.getOwnershipTransfer(teamId);\n const outputFormat = getOutputFormat(cmd);\n if (!pending) {\n if (outputFormat === 'json') {\n format(null, { format: outputFormat });\n } else {\n console.log(`No pending ownership transfer for team \"${teamId}\".`);\n }\n return;\n }\n format(pending, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('accept')\n .description('Accept an ownership transfer offered to you')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const response = await api.admin.acceptOwnershipTransfer(teamId);\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat === 'json') {\n format(response, { format: outputFormat });\n return;\n }\n success(`Ownership transfer ${response.status}.`);\n if (response.checkoutUrl) {\n console.log('Open this URL to complete the billing handover:');\n console.log(chalk.cyan(response.checkoutUrl));\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n transfer\n .command('cancel')\n .description('Cancel a pending ownership transfer')\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.cancelOwnershipTransfer(teamId);\n success(`Canceled the ownership transfer for team \"${teamId}\".`, {\n format: getOutputFormat(cmd),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference, parseProjectReference } from '../../util/references.js';\nimport { runBundleImport, streamResponseToFile } from '../bundle-helpers.js';\nimport { success } from '../../output/messages.js';\nimport { registerTagCommands } from './tags.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerEntityCommands(program: Command): void {\n const entity = program\n .command('entity')\n .description('Manage entities')\n .addHelpText('after', `\nAn entity reference is <project>/<branch>/<entity>/<entityBranch>. With\n'diafunc config set defaults.project <id>' the leading parts can be omitted.\n\nExamples:\n $ diafunc entity list <projectId>\n $ diafunc entity get <project>/main/<entity>/main\n $ diafunc entity history <project>/main/<entity>/main\n $ diafunc entity tags add <project>/main/<entity>/main health\n`);;\n\n entity\n .command('list')\n .description('List entities in a project (via linked entities from project root)')\n .argument('<projectRef>', 'Project reference (projectId or projectId/branch)')\n .action(async (projectRef: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const ref = parseEntityReference(projectRef + '/' + projectRef, overrides);\n const api = createApiClient();\n const entities = await api.storage.getLinkedEntities('FORWARD', {\n projectId: ref.projectId,\n projectBranch: ref.projectBranch,\n entityId: ref.projectId,\n entityBranch: ref.projectBranch,\n });\n const summary = entities.map(e => ({\n entityId: e.entityId,\n type: e.type,\n tags: e.tags.join(', '),\n version: e.version,\n modified: new Date(e.modified).toISOString(),\n }));\n format(summary, {\n format: outputFormat,\n columns: ['entityId', 'type', 'tags', 'version', 'modified'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('get')\n .description('Get entity metadata')\n .argument('<ref>', 'Entity reference')\n .option('--content', 'Include content')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const e = await api.storage.getEntity(resolved, options.content);\n\n if (outputFormat === 'human') {\n const summary: Record<string, unknown> = {\n projectId: e.projectId,\n projectBranch: e.projectBranch,\n entityId: e.entityId,\n entityBranch: e.entityBranch,\n type: e.type,\n tags: e.tags.join(', ') || '—',\n version: e.version,\n head: e.head,\n created: new Date(e.created).toISOString(),\n modified: new Date(e.modified).toISOString(),\n contentAvailable: e.contentAvailable,\n contentType: e.contentType,\n contentSize: e.contentSize,\n };\n format(summary, { format: outputFormat });\n } else {\n format(e, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('delete')\n .description('Delete an entity')\n .argument('<ref>', 'Entity reference')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (ref: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will permanently delete entity \"${ref}\".`, { yes: options.yes, resourceId: ref });\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.deleteEntity(resolved);\n success(`Entity \"${resolved.entityId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('history')\n .description('Get entity version history')\n .argument('<ref>', 'Entity reference')\n .option('--from <version>', 'From version')\n .option('--to <version>', 'To version')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n if (options.from && options.to) {\n const entities = await api.storage.getEntityHistoryRange(\n resolved,\n parseInt(options.from, 10),\n parseInt(options.to, 10),\n );\n const summary = entities.map(e => ({\n version: e.version,\n modified: new Date(e.modified).toISOString(),\n head: e.head,\n }));\n format(summary, { format: outputFormat, columns: ['version', 'modified', 'head'] });\n } else if (options.from) {\n const e = await api.storage.getEntityHistory(resolved, parseInt(options.from, 10));\n format(e, { format: outputFormat });\n } else {\n // Get current entity to show version info\n const e = await api.storage.getEntity(resolved);\n console.log(`Current version: ${e.version}, head: ${e.head}`);\n console.log(`Use --from <v> --to <v> to view a version range.`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('revert')\n .description('Revert an entity to a previous version')\n .argument('<ref>', 'Entity reference')\n .argument('<version>', 'Version to revert to')\n .action(async (ref: string, version: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.revertEntity(resolved, parseInt(version, 10));\n success(`Entity \"${resolved.entityId}\" reverted to version ${version}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('rename')\n .description('Rename an entity')\n .argument('<ref>', 'Entity reference')\n .argument('<newId>', 'New entity ID')\n .action(async (ref: string, newId: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.renameEntity(resolved, newId);\n success(`Entity renamed from \"${resolved.entityId}\" to \"${newId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n registerTagCommands(entity, 'entity');\n\n // Content subcommands\n const content = entity\n .command('content')\n .description('Manage entity content');\n\n content\n .command('get')\n .description('Download entity content')\n .argument('<ref>', 'Entity reference')\n .option('--out <file>', 'Output file (defaults to stdout)')\n .action(async (ref: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const response = await api.storage.getEntityContent(resolved);\n\n if (options.out) {\n const buffer = Buffer.from(await response.arrayBuffer());\n fs.writeFileSync(options.out, buffer);\n success(`Content saved to ${options.out}`);\n } else {\n const text = await response.text();\n process.stdout.write(text);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n content\n .command('set')\n .description('Upload entity content from a file')\n .argument('<ref>', 'Entity reference')\n .argument('<file>', 'File to upload')\n .action(async (ref: string, file: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const fileBuffer = fs.readFileSync(file);\n const base64 = fileBuffer.toString('base64');\n await api.storage.saveEntityContentBase64(resolved, base64);\n success(`Content uploaded from \"${file}\" to entity \"${resolved.entityId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n content\n .command('delete')\n .description('Delete entity content')\n .argument('<ref>', 'Entity reference')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (ref: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will permanently delete the content of entity \"${ref}\".`, { yes: options.yes, resourceId: ref });\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.deleteEntityContent(resolved);\n success(`Content deleted from entity \"${resolved.entityId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Bundle subcommands — arbitrary entity-subset (.dfset) export/import.\n\n entity\n .command('export')\n .description('Export a subset of entities (plus their closure) to a .dfset bundle')\n .argument('<project>', 'Project reference (projectId or projectId/branch)')\n .argument('<entityIds...>', 'Entity id(s) to export')\n .option('--out <file>', 'Output file (defaults to entities.dfset)')\n .option('--data <encoding>', 'Embedded table-data encoding: csv (default) or parquet', 'csv')\n .option('--async', 'Queue a background job instead of streaming the download now')\n .action(async (project: string, entityIds: string[], options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n const request = { rootEntityIds: entityIds, dataFormat: options.data };\n\n if (options.async) {\n const bundleId = await api.storage.exportEntitySubset(ref.projectId, ref.projectBranch, request);\n success(`Export queued (bundle ID: ${bundleId}).`);\n console.log(`Poll progress: diafunc notebook bundles ${project}`);\n return;\n }\n\n const response = await api.storage.streamEntitySubset(ref.projectId, ref.projectBranch, request);\n const outFile = options.out ?? 'entities.dfset';\n const bytes = await streamResponseToFile(response, outFile);\n success(`Bundle written to ${outFile} (${bytes} bytes, ${entityIds.length} entity(ies)).`);\n } catch (error) {\n handleError(error);\n }\n });\n\n entity\n .command('import')\n .description('Import a .dfset (or any) bundle into a project')\n .argument('<project>', 'Target project reference (projectId or projectId/branch)')\n .argument('<file>', 'Path to the bundle')\n .option('--on-conflict <policy>', 'copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip', 'copy')\n .option('--preview', 'Show the bundle inventory without importing')\n .action(async (project: string, file: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n await runBundleImport(api.storage, ref.projectId, ref.projectBranch, file, options, outputFormat);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport type { LinkDirection } from '../../client/types/storage.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerLinkCommands(program: Command): void {\n const link = program\n .command('link')\n .description('Manage links between entities');\n\n link\n .command('list')\n .description('List links for an entity')\n .argument('<ref>', 'Source entity reference')\n .option('--direction <dir>', 'Link direction: FORWARD or BACKWARD', 'FORWARD')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const direction = options.direction.toUpperCase() as LinkDirection;\n const links = await api.storage.getLinks(direction, resolved);\n\n const summary = links.map(l => ({\n linkId: l.linkId,\n targetEntityId: l.targetEntityId,\n targetEntityBranch: l.targetEntityBranch,\n type: l.type,\n version: l.version,\n }));\n format(summary, {\n format: outputFormat,\n columns: ['linkId', 'targetEntityId', 'targetEntityBranch', 'type', 'version'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n link\n .command('create')\n .description('Create a link between two entities')\n .argument('<sourceRef>', 'Source entity reference')\n .argument('<linkId>', 'Link ID')\n .argument('<targetRef>', 'Target entity reference')\n .action(async (sourceRef: string, linkId: string, targetRef: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const source = parseEntityReference(sourceRef, overrides);\n const target = parseEntityReference(targetRef, overrides);\n const api = createApiClient();\n await api.storage.createLink(\n source.projectId, source.projectBranch,\n source.entityId, source.entityBranch,\n linkId,\n target.entityId, target.entityBranch,\n );\n success(`Link \"${linkId}\" created: ${source.entityId} → ${target.entityId}`);\n } catch (error) {\n handleError(error);\n }\n });\n\n link\n .command('delete')\n .description('Delete a link')\n .argument('<sourceRef>', 'Source entity reference')\n .argument('<linkId>', 'Link ID')\n .argument('[targetRef]', 'Target entity reference (optional, deletes all targets if omitted)')\n .action(async (sourceRef: string, linkId: string, targetRef: string | undefined, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const source = parseEntityReference(sourceRef, overrides);\n const api = createApiClient();\n\n if (targetRef) {\n const target = parseEntityReference(targetRef, overrides);\n await api.storage.deleteLink(\n source.projectId, source.projectBranch,\n source.entityId, source.entityBranch,\n linkId,\n target.entityId, target.entityBranch,\n );\n success(`Link \"${linkId}\" deleted: ${source.entityId} → ${target.entityId}`);\n } else {\n await api.storage.deleteLink(\n source.projectId, source.projectBranch,\n source.entityId, source.entityBranch,\n linkId,\n );\n success(`All links with ID \"${linkId}\" from \"${source.entityId}\" deleted.`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerEventCommands(program: Command): void {\n const event = program\n .command('event')\n .description('Manage events');\n\n event\n .command('list')\n .description('List events for an entity')\n .argument('<ref>', 'Entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const events = await api.storage.getEvents(resolved);\n\n const summary = events.map(e => ({\n eventId: e.eventId,\n occurrenceId: e.occurrenceId,\n type: e.type,\n duration: e.duration,\n created: new Date(e.created).toISOString(),\n }));\n format(summary, {\n format: outputFormat,\n columns: ['eventId', 'occurrenceId', 'type', 'duration', 'created'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n event\n .command('get')\n .description('Get a specific event')\n .argument('<ref>', 'Entity reference')\n .argument('<eventId>', 'Event ID')\n .argument('<occurrenceId>', 'Occurrence ID')\n .action(async (ref: string, eventId: string, occurrenceId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const event = await api.storage.getEvent(resolved, eventId, occurrenceId);\n format(event, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n event\n .command('create')\n .description('Create one or more events (body from JSON file or stdin)')\n .argument('[file]', 'JSON file containing a BareEvent array; defaults to stdin')\n .action(async (file: string | undefined) => {\n try {\n const fs = await import('node:fs');\n const body = file\n ? fs.readFileSync(file, 'utf-8')\n : await new Promise<string>((resolve, reject) => {\n let data = '';\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (chunk) => { data += chunk; });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', reject);\n });\n const events = JSON.parse(body);\n const api = createApiClient();\n const arr = Array.isArray(events) ? events : [events];\n await api.storage.createEvents(arr);\n success(`${arr.length} event(s) created.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n event\n .command('consume')\n .description('Consume events for a given project and consumer')\n .argument('<projectRef>', 'Project reference (projectId or projectId/branch)')\n .requiredOption('--consumer-type <type>', 'Consumer type')\n .requiredOption('--consumer-id <id>', 'Consumer ID')\n .option('--events <json>', 'Event references as JSON array', '[]')\n .action(async (projectRef: string, options) => {\n try {\n const [projectId, projectBranch = 'main'] = projectRef.split('/');\n const api = createApiClient();\n const events = await api.storage.consumeEvents({\n projectId,\n projectBranch,\n eventReferences: JSON.parse(options.events),\n consumerType: options.consumerType,\n consumerId: options.consumerId,\n });\n console.log(JSON.stringify(events, null, 2));\n } catch (error) {\n handleError(error);\n }\n });\n\n event\n .command('delete')\n .description('Delete an event')\n .argument('<ref>', 'Entity reference')\n .argument('<eventId>', 'Event ID')\n .argument('<occurrenceId>', 'Occurrence ID')\n .action(async (ref: string, eventId: string, occurrenceId: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.deleteEvent(resolved, eventId, occurrenceId);\n success(`Event \"${eventId}/${occurrenceId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { failure, success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerBranchCommands(program: Command): void {\n const branch = program\n .command('branch')\n .description('Manage branches')\n .addHelpText('after', `\nExamples:\n $ diafunc branch list <projectId>\n $ diafunc branch create <projectId> experiment\n $ diafunc branch merge --source <projectId>/experiment/<entityId>/main --target <projectId>/main\n`);;\n\n branch\n .command('list')\n .description('List branches for a project')\n .argument('[projectId]', 'Project ID (uses default if omitted)')\n .action(async (projectId: string | undefined, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const config = loadConfig();\n const pid = projectId ?? overrides.project ?? config.defaults.project;\n if (!pid) {\n failure('No project specified. Pass a project ID or set defaults.project.');\n process.exit(1);\n }\n const api = createApiClient();\n const branches = await api.storage.getProjectBranches(pid);\n\n if (outputFormat === 'json') {\n format(branches, { format: outputFormat });\n } else {\n for (const b of branches) {\n console.log(b);\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n branch\n .command('create')\n .description('Create a new project branch')\n .argument('<projectId>', 'Project ID')\n .argument('<branchName>', 'New branch name')\n .option('--source <branch>', 'Source branch to copy from', 'main')\n .action(async (projectId: string, branchName: string, options) => {\n try {\n const api = createApiClient();\n await api.storage.createProjectBranch({\n projectId,\n sourceProjectBranch: options.source,\n targetProjectBranch: branchName,\n });\n success(`Branch \"${branchName}\" created in project \"${projectId}\" from \"${options.source}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n branch\n .command('delete')\n .description('Delete a project branch')\n .argument('<projectId>', 'Project ID')\n .argument('<branchName>', 'Branch name to delete')\n .action(async (projectId: string, branchName: string) => {\n try {\n const api = createApiClient();\n await api.storage.deleteProjectBranch(projectId, branchName);\n success(`Branch \"${branchName}\" deleted from project \"${projectId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n branch\n .command('merge')\n .description('Merge an entity from one branch to another')\n .requiredOption('--source <ref>', 'Source entity reference (projectId/branch/entityId/entityBranch)')\n .requiredOption('--target <ref>', 'Target project reference (projectId/branch)')\n .option('--link-id <linkId>', 'Link ID for the merge', 'main')\n .option('--deep', 'Deep merge (include linked entities)', false)\n .action(async (options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const source = parseEntityReference(options.source, overrides);\n const targetParts = options.target.split('/');\n const api = createApiClient();\n await api.storage.merge({\n sourceEntityReference: source,\n targetProjectReference: {\n projectId: targetParts[0],\n projectBranch: targetParts[1] || 'main',\n },\n linkFromEntityReference: null,\n linkId: options.linkId,\n deepMerge: options.deep,\n });\n success('Merge completed.');\n } catch (error) {\n handleError(error);\n }\n });\n\n branch\n .command('fork')\n .description('Fork a project (source branch: the global --branch, default main)')\n .argument('<projectId>', 'Source project ID')\n .argument('<forkProjectId>', 'New forked project ID')\n .option('--name <name>', 'Forked project name')\n .option('--description <desc>', 'Forked project description', '')\n .action(async (projectId: string, forkProjectId: string, options, cmd: Command) => {\n try {\n const api = createApiClient();\n await api.storage.fork({\n projectId,\n projectBranch: getOverrides(cmd).branch ?? 'main',\n forkProjectId,\n forkProjectName: options.name ?? forkProjectId,\n forkProjectDescription: options.description,\n });\n success(`Project \"${projectId}\" forked to \"${forkProjectId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { CliError, EXIT_FAILURE, EXIT_USAGE, handleError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference, type ResolvedReference } from '../../util/references.js';\nimport { decodeCellValue, decodeLongAttribute, defaultWindow, describeWindow, fetchWindow, parseRange, tableDimensions, type TableWindow } from '../../util/table-window.js';\nimport { buildTableEntity } from '../../util/table-entity.js';\nimport { ApiError } from '../../client/errors.js';\nimport { randomUUID } from 'node:crypto';\nimport { empty, failure, hint, success } from '../../output/messages.js';\nimport { Status, withStatus } from '../../output/progress.js';\nimport { formatDuration } from '../../output/values.js';\nimport { progressLine } from '../bundle-helpers.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nfunction deriveOutFile(entityId: string, extension: string, archive?: string, compression?: string): string {\n let name = `${entityId}${extension}`;\n if (archive === 'zip') {\n name += '.zip';\n } else if (archive === 'tar') {\n name += '.tar';\n }\n if (archive !== 'zip' && compression) {\n const suffix: Record<string, string> = { gzip: '.gz', bzip2: '.bz2', xz: '.xz', zstd: '.zst' };\n name += suffix[compression as keyof typeof suffix] ?? '';\n }\n return name;\n}\n\ninterface Placement {\n parent: ResolvedReference;\n linkId: string;\n index?: number;\n}\n\n/** At project level: linked from the project's root entity, as the Lab does for a data source's new table. */\nfunction projectPlacement(table: ResolvedReference): Placement {\n return {\n parent: { projectId: table.projectId, projectBranch: table.projectBranch, entityId: table.projectId, entityBranch: 'main' },\n linkId: 'main',\n };\n}\n\n/** As the last section of a notebook or chapter, after every section it already has. */\nasync function notebookPlacement(api: ReturnType<typeof createApiClient>, notebook: string,\n table: ResolvedReference): Promise<Placement> {\n const parent = parseEntityReference(notebook, { project: table.projectId, branch: table.projectBranch });\n if (parent.projectId !== table.projectId || parent.projectBranch !== table.projectBranch) {\n throw new CliError('The notebook must be in the same project and branch as the table.');\n }\n const entity = await api.storage.getEntity(parent, false).catch((error: unknown) => {\n if (error instanceof ApiError && error.status === 404) {\n throw new CliError(`There is no notebook \"${parent.entityId}\".`, {\n hint: `List what the project holds with 'diafunc entity list ${parent.projectId}/${parent.projectBranch}'.`,\n });\n }\n throw error;\n });\n if (entity.type !== 'notebook' && entity.type !== 'chapter') {\n throw new CliError(`\"${parent.entityId}\" is a ${entity.type ?? 'untyped entity'}, not a notebook or chapter.`);\n }\n const sections = await api.storage.getLinkedEntities('FORWARD', parent, 'sections');\n const last = sections\n .map((section) => decodeLongAttribute(section.attributes?.index))\n .filter((index): index is number => index !== null)\n .reduce((highest, index) => Math.max(highest, index), -1);\n return { parent, linkId: 'sections', index: last + 1 };\n}\n\nfunction formatReference(ref: ResolvedReference): string {\n return `${ref.projectId}/${ref.projectBranch}/${ref.entityId}/${ref.entityBranch}`;\n}\n\nexport function registerTableCommands(program: Command): void {\n const table = program\n .command('table')\n .description('Manage tables')\n .addHelpText('after', `\nExamples:\n $ diafunc table create sales an empty table named \"sales\"\n $ diafunc table view <ref> --rows 0:20 the first twenty rows\n $ diafunc table import <ref> data.csv load a file\n $ diafunc table export <ref> parquet write one out\n $ diafunc table import-formats what can be loaded\n`);;\n\n table\n .command('view')\n .description('View table data')\n .argument('<ref>', 'Table entity reference')\n .option('--rows <range>', 'Rows to show, half-open: 0:10 is the first ten, 6490: runs to the end (default: up to 100)')\n .option('--cols <range>', 'Columns to show, half-open: 0:5 is the first five (default: up to 50)')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n // The snapshot endpoint returns exactly the cells a request names and nothing for a request\n // that names none, so the table's size comes first, from its entity's attributes.\n const { rows: totalRows, columns: totalColumns } = tableDimensions(await api.storage.getEntity(resolved, false));\n if (totalRows === 0 || totalColumns === 0) {\n if (outputFormat === 'json') {\n format({ rows: [], columns: [], cells: [], totalRows, totalColumns, window: null }, { format: outputFormat });\n } else {\n console.log(chalk.dim('Empty table.'));\n }\n return;\n }\n\n const initial = defaultWindow(totalRows, totalColumns);\n const window: TableWindow = {\n rows: options.rows ? parseRange(options.rows, totalRows, 'Row') : initial.rows,\n columns: options.cols ? parseRange(options.cols, totalColumns, 'Column') : initial.columns,\n };\n // A window larger than one request may return is asked for in parts and joined.\n const snapshot = await fetchWindow(\n (range) => api.storage.getTableSnapshot(resolved, { cellRanges: [range] }), window);\n\n if (outputFormat === 'json') {\n // Each cell keeps its raw `value` and gains `text`, the value decoded for reading.\n const cells = snapshot.cells.map((cell) => ({ ...cell, text: decodeCellValue(cell.value, cell.type) }));\n format({ ...snapshot, cells, totalRows, totalColumns, window }, { format: outputFormat });\n return;\n }\n\n // Build a grid for human/table output\n const colMap = new Map(snapshot.columns.map(c => [c.index, c]));\n const sortedCols = [...snapshot.columns].sort((a, b) => a.index - b.index);\n const colNames = sortedCols.map(c => c.name || `col${c.index}`);\n\n // Build cell lookup\n const cellMap = new Map<string, string>();\n for (const cell of snapshot.cells) {\n cellMap.set(`${cell.rowIndex}:${cell.columnIndex}`, decodeCellValue(cell.value, cell.type));\n }\n\n const sortedRows = [...snapshot.rows].sort((a, b) => a.index - b.index);\n const tableData = sortedRows.map(row => {\n const obj: Record<string, string> = {};\n for (const col of sortedCols) {\n obj[col.name || `col${col.index}`] = cellMap.get(`${row.index}:${col.index}`) ?? '';\n }\n return obj;\n });\n\n if (outputFormat === 'table') {\n console.log(colNames.join('\\t'));\n for (const row of tableData) {\n console.log(colNames.map(c => row[c] ?? '').join('\\t'));\n }\n } else {\n // Explicit headers: a column is named by its data, and must not be reworded (\"pH\", not \"p h\").\n format(tableData, { format: outputFormat, columns: colNames.map((name) => ({ key: name, header: name })) });\n console.log(chalk.dim(describeWindow(window, totalRows, totalColumns)));\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('create')\n .description('Create an empty table, at project level or as a section of a notebook')\n .argument('[ref]', 'The new table\\'s entity reference (default: a new id in the default project)')\n .option('--name <name>', 'Display name (defaults to the entity id, or \"Table\" for a generated id)')\n .option('--notebook <ref>', 'Add the table as a section of this notebook or chapter instead of at project level')\n .addHelpText('after', `\nA table at project level is linked from the project, where 'diafunc entity list' shows it. With --notebook it\nbecomes the notebook's last section, as Add Table in the Lab does. Either way it starts empty; load it with\n'diafunc table import <ref> <file>'.\n\nExamples:\n $ diafunc table create sales --name \"Sales 2026\"\n $ diafunc table create --notebook <notebookId>\n`)\n .action(async (ref: string | undefined, options: { name?: string; notebook?: string }, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref ?? randomUUID(), overrides);\n if (resolved.entityId.includes('.partition.')) {\n throw new CliError(`\"${resolved.entityId}\" contains \".partition.\", which names a table's storage blocks.`, {\n exitCode: EXIT_USAGE,\n hint: 'Choose an id without it.',\n });\n }\n const api = createApiClient();\n if (await api.storage.entityExists(resolved)) {\n throw new CliError(`An entity \"${resolved.entityId}\" already exists in this project.`, {\n hint: `Import into it with 'diafunc table import ${formatReference(resolved)} <file>', or choose another id.`,\n });\n }\n const name = options.name ?? (ref ? resolved.entityId : 'Table');\n const placement = options.notebook\n ? await notebookPlacement(api, options.notebook, resolved)\n : projectPlacement(resolved);\n const entity = buildTableEntity({ ...resolved, name, index: placement.index });\n await api.storage.saveLinkedEntities(placement.parent, placement.linkId, [entity]);\n\n const created = formatReference(resolved);\n if (outputFormat === 'json') {\n format({ ...resolved, name, parent: placement.parent.entityId, linkId: placement.linkId, index: placement.index ?? null },\n { format: outputFormat });\n return;\n }\n success(`Table \"${name}\" created: ${created}`);\n hint(`Load data with 'diafunc table import ${created} <file>'.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('import')\n .description('Import data from a file (any supported format; see `table import-formats`)')\n .argument('<ref>', 'Table entity reference')\n .argument('<file>', 'File to import')\n .option('--selection <id>', 'Pin a sheet / inner-table id for multi-table sources (Excel sheets, SQLite tables, archive entries)')\n .action(async (ref: string, file: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n\n if (!fs.existsSync(file)) {\n failure(`File not found: ${file}`);\n process.exit(EXIT_USAGE);\n }\n\n const api = createApiClient();\n const fileBuffer = fs.readFileSync(file);\n const blob = new Blob([fileBuffer]);\n const formData = new FormData();\n formData.append('content', blob, path.basename(file));\n\n const importId = await withStatus(\n `Uploading ${path.basename(file)}`,\n () => api.storage.importTable(resolved, formData, options.selection),\n ).catch((error: unknown) => {\n // An import only fills a table that exists; the platform refuses one into an id that names nothing.\n if (error instanceof ApiError && error.status === 404) {\n throw new CliError(`There is no table \"${resolved.entityId}\" to import into.`, {\n hint: `Create it first with 'diafunc table create ${ref}', then import again.`,\n });\n }\n throw error;\n });\n\n // A large import runs for minutes. The wait used to print one line and then nothing, which\n // is indistinguishable from a hung command.\n const pollInterval = 1000;\n const maxAttempts = 300; // 5 minutes\n const status = new Status();\n status.start();\n const startedAt = Date.now();\n try {\n for (let i = 0; i < maxAttempts; i++) {\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n const imp = await api.storage.getImport(resolved, importId);\n if (imp.finished !== null) {\n status.stop();\n if (imp.succeeded) {\n success(`Imported in ${formatDuration(imp.duration)}.`);\n return;\n }\n failure(`Import failed: ${imp.error}`);\n process.exit(EXIT_FAILURE);\n }\n status.set([progressLine('Importing', imp.progress, Date.now() - startedAt)]);\n }\n } finally {\n status.stop();\n }\n // Still running after the budget: the import is not lost, but this command cannot claim it\n // succeeded, so it no longer exits as though it had.\n failure(`Import ${importId} is still running after ${formatDuration(pollInterval * maxAttempts)}.`);\n hint(`It continues on the server. Check again with 'diafunc table view ${ref}'.`);\n process.exit(EXIT_FAILURE);\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('import-formats')\n .description('List supported import formats')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const response = await api.storage.getSupportedImportFormats();\n if (outputFormat === 'json') {\n format(response, { format: outputFormat });\n return;\n }\n const rows = response.formats.map(f => ({\n id: f.id,\n displayName: f.displayName,\n category: f.category,\n extensions: f.extensions.join(', '),\n mimeTypes: f.mimeTypes.join(', '),\n multiTable: f.multiTable,\n userDefined: f.userDefined,\n }));\n format(rows, {\n format: outputFormat,\n columns: [\n { key: 'id' },\n { key: 'displayName', header: 'name' },\n { key: 'category' },\n { key: 'extensions' },\n // The longest of these runs to 93 characters and would otherwise set the table width.\n { key: 'mimeTypes', header: 'mime types', maxWidth: 40 },\n { key: 'multiTable', header: 'multi-table', kind: 'boolean' },\n { key: 'userDefined', header: 'user-defined', kind: 'boolean' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('export')\n .description('Export table data in any supported format (see `table export-formats`)')\n .argument('<ref>', 'Table entity reference')\n .argument('<format>', 'Export format (csv, tsv, excel, parquet, arrow, orc, avro, json, jsonl, yaml, xml, html, pdf, sqlite, duckdb, hdf5, netcdf, ...)')\n .option('--out <file>', 'Output file')\n .option('--compression <algorithm>', 'Compression wrapper: gzip, bzip2, xz, or zstd')\n .option('--archive <algorithm>', 'Archive wrapper: zip or tar')\n .option('--rows <range>', 'Row range, half-open (e.g. 0:1000)')\n .option('--cols <range>', 'Column range, half-open (e.g. 0:5)')\n .option('--delimiter <char>', 'CSV/TSV only: single-character delimiter override')\n .option('--quote <char>', 'CSV/TSV only: quote character (use \"\" for empty)')\n .option('--null <token>', 'CSV/TSV only: null token (default \"?\")')\n .option('--no-quote-all', 'CSV/TSV only: only quote fields when necessary (default quotes every field)')\n .option('--async', 'Queue an async export (with progress + later re-download) instead of streaming directly to disk', false)\n .action(async (ref: string, fmt: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n const formats = await api.storage.getSupportedExportFormats();\n const format = formats.formats.find(f => f.id.toLowerCase() === fmt.toLowerCase());\n if (!format) {\n failure(`Unknown format: \"${fmt}\". Run \\`diafunc table export-formats\\` to see the catalog.`);\n process.exit(1);\n }\n if (options.compression && !formats.compressionAlgorithms.includes(options.compression)) {\n failure(`Unknown compression: \"${options.compression}\". Use one of ${formats.compressionAlgorithms.join(', ')}.`);\n process.exit(1);\n }\n if (options.archive && !formats.archiveAlgorithms.includes(options.archive)) {\n failure(`Unknown archive: \"${options.archive}\". Use one of ${formats.archiveAlgorithms.join(', ')}.`);\n process.exit(1);\n }\n\n const exportOptions: Record<string, unknown> = {\n compression: options.compression,\n archive: options.archive,\n };\n if (options.rows) {\n const [from, to] = String(options.rows).split(':').map(Number);\n if (!isNaN(from)) exportOptions.fromRow = from;\n if (!isNaN(to)) exportOptions.toRow = to;\n }\n if (options.cols) {\n const [from, to] = String(options.cols).split(':').map(Number);\n if (!isNaN(from)) exportOptions.fromColumn = from;\n if (!isNaN(to)) exportOptions.toColumn = to;\n }\n const csvLike = format.id === 'csv' || format.id === 'tsv';\n if (csvLike) {\n if (options.delimiter !== undefined) exportOptions.delimiter = options.delimiter;\n if (options.quote !== undefined) exportOptions.quote = options.quote;\n if (options.null !== undefined) exportOptions.nullValue = options.null;\n if (options.quoteAll === false) exportOptions.quoteAll = false;\n }\n\n const useStream = !options.async;\n if (useStream) {\n const response = await api.storage.streamExport(resolved, format.id, exportOptions);\n const outFile = options.out ?? deriveOutFile(resolved.entityId, format.extension, options.archive, options.compression);\n const buffer = Buffer.from(await response.arrayBuffer());\n fs.writeFileSync(outFile, buffer);\n success(`Table streamed to ${outFile}`);\n } else {\n // Async path: server returns just the exportId, no bytes. The\n // client polls (or the user runs `diafunc table exports get`\n // later). Don't try to write the empty response body to disk.\n const exportId = await api.storage.exportTable(resolved, format.id, exportOptions);\n success(`Export queued (ID: ${exportId}).`);\n console.log(`Poll progress: diafunc table exports get ${exportId} --ref ${ref}`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('export-formats')\n .description('List supported export formats')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const response = await api.storage.getSupportedExportFormats();\n if (outputFormat === 'json') {\n format(response, { format: outputFormat });\n return;\n }\n const rows = response.formats.map(f => ({\n id: f.id,\n displayName: f.displayName,\n category: f.category,\n extension: f.extension,\n mimeType: f.mimeType,\n knownLimitations: f.knownLimitations.join(' / '),\n }));\n format(rows, { format: outputFormat, columns: ['id', 'displayName', 'category', 'extension', 'mimeType', 'knownLimitations'] });\n console.log(chalk.dim(`Compression: ${response.compressionAlgorithms.join(', ')}`));\n console.log(chalk.dim(`Archive: ${response.archiveAlgorithms.join(', ')}`));\n } catch (error) {\n handleError(error);\n }\n });\n\n // Async export tracking subcommands\n const exportsCmd = table.command('exports').description('Track and download async table exports');\n\n exportsCmd\n .command('list')\n .description('List async exports for a table entity')\n .argument('<ref>', 'Table entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const exports = await api.storage.listExports(resolved);\n if (outputFormat === 'json') {\n format(exports, { format: outputFormat });\n return;\n }\n if (exports.length === 0) {\n empty('exports found');\n return;\n }\n const rows = exports.map(e => ({\n exportId: e.exportId,\n filename: e.filename,\n progress: `${Math.round((e.progress ?? 0) * 100)}%`,\n succeeded: e.succeeded === true ? 'yes' : e.succeeded === false ? 'no' : '—',\n duration: e.duration != null ? `${e.duration}ms` : '—',\n error: e.error ?? '',\n }));\n format(rows, { format: outputFormat, columns: ['exportId', 'filename', 'progress', 'succeeded', 'duration', 'error'] });\n } catch (error) {\n handleError(error);\n }\n });\n\n exportsCmd\n .command('get')\n .description('Get async export status; download the file once the export has succeeded')\n .argument('<exportId>', 'Export ID returned by `table export --async`')\n .requiredOption('--ref <ref>', 'Table entity reference')\n .option('--out <file>', 'Output file path (defaults to the original export filename)')\n .action(async (exportId: string, options: { ref: string; out?: string }, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(options.ref, overrides);\n const api = createApiClient();\n const exports = await api.storage.listExports(resolved);\n const exp = exports.find(e => e.exportId === exportId);\n if (!exp) {\n failure(`Export ${exportId} not found for ref ${options.ref}.`);\n process.exit(1);\n }\n\n if (outputFormat === 'json') {\n format(exp, { format: outputFormat });\n return;\n }\n\n if (exp.finished === null) {\n const pct = Math.round((exp.progress ?? 0) * 100);\n console.log(chalk.dim(`Export in progress: ${pct}%. Check again later.`));\n return;\n }\n\n if (!exp.succeeded) {\n failure(`Export failed: ${exp.error}`);\n process.exit(1);\n }\n\n // Export completed — download bytes\n const outFile = options.out ?? exp.filename;\n console.log(`Downloading ${exp.filename} ...`);\n const response = await api.storage.downloadExport(resolved, exportId, exp.filename);\n const buffer = Buffer.from(await response.arrayBuffer());\n fs.writeFileSync(outFile, buffer);\n success(`Export saved to ${outFile}`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Row subcommands\n const row = table.command('row').description('Manage table rows');\n\n row\n .command('add')\n .description('Append a row to a table')\n .argument('<ref>', 'Table entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.appendRow(resolved);\n success('Row appended.');\n } catch (error) {\n handleError(error);\n }\n });\n\n row\n .command('insert')\n .description('Insert an empty row at the given index, shifting existing rows down')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Row index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.insertRow(resolved, parseInt(index, 10));\n success(`Row inserted at index ${index}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n row\n .command('remove')\n .description('Remove a row in place (blanks the row; no shift)')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Row index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.removeRow(resolved, parseInt(index, 10));\n success(`Row ${index} removed.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n row\n .command('delete')\n .description('Delete a row and shift the rows below up by one')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Row index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.deleteRow(resolved, parseInt(index, 10));\n success(`Row ${index} deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Column subcommands\n const column = table.command('column').description('Manage table columns');\n\n column\n .command('add')\n .description('Append a column to a table')\n .argument('<ref>', 'Table entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.appendColumn(resolved);\n success('Column appended.');\n } catch (error) {\n handleError(error);\n }\n });\n\n column\n .command('insert')\n .description('Insert an empty column at the given index, shifting existing columns right')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Column index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.insertColumn(resolved, parseInt(index, 10));\n success(`Column inserted at index ${index}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n column\n .command('remove')\n .description('Remove a column in place (blanks the column; no shift)')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Column index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.removeColumn(resolved, parseInt(index, 10));\n success(`Column ${index} removed.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n column\n .command('delete')\n .description('Delete a column and shift the columns to its right left by one')\n .argument('<ref>', 'Table entity reference')\n .argument('<index>', 'Column index')\n .action(async (ref: string, index: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.deleteColumn(resolved, parseInt(index, 10));\n success(`Column ${index} deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Cell subcommands\n const cell = table.command('cell').description('Manage table cells');\n\n cell\n .command('set')\n .description('Set a cell value')\n .argument('<ref>', 'Table entity reference')\n .argument('<row>', 'Row index')\n .argument('<col>', 'Column index')\n .argument('<value>', 'Cell value')\n .action(async (ref: string, row: string, col: string, value: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.mergeCells(resolved, [{\n rowIndex: parseInt(row, 10),\n columnIndex: parseInt(col, 10),\n value,\n type: 'text',\n }]);\n success(`Cell [${row}, ${col}] set to \"${value}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n cell\n .command('delete')\n .description('Delete a cell value')\n .argument('<ref>', 'Table entity reference')\n .argument('<row>', 'Row index')\n .argument('<col>', 'Column index')\n .action(async (ref: string, row: string, col: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.removeCell(resolved, parseInt(row, 10), parseInt(col, 10));\n success(`Cell [${row}, ${col}] deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n table\n .command('clear')\n .description('Clear all data from a table')\n .argument('<ref>', 'Table entity reference')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (ref: string, options: { yes?: boolean }, cmd) => {\n try {\n await confirmDestructive(`This will permanently delete all data in table \"${ref}\".`, { yes: options.yes, resourceId: ref });\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.clearTable(resolved);\n success('Table cleared.');\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import type { CellRangeRequest, Entity, TableSnapshot } from '../client/types/storage.js';\nimport { CliError, EXIT_USAGE } from './errors.js';\n\n/**\n * Which part of a table to ask the platform for.\n *\n * The snapshot endpoint returns exactly the cells a request names, as `cellRanges` with inclusive\n * ends, and nothing for a request that names none. So the table's size has to be known first: it\n * is on the table entity, as the `rows` and `columns` attributes. The default window uses the same\n * budget as the Assistant's snapshot tool (`TableToolCore` on the platform), so both show a reader\n * the same first view of a table.\n */\n\nexport const WINDOW_MAX_ROWS = 100;\nexport const WINDOW_MAX_COLUMNS = 50;\nexport const WINDOW_MAX_CELLS = 2000;\n\n/** A half-open range `[from, to)` of row or column indexes. */\nexport interface Span {\n from: number;\n to: number;\n}\n\nexport interface TableWindow {\n rows: Span;\n columns: Span;\n}\n\n/**\n * The value of an entity attribute holding a long: eight big-endian bytes, base64-encoded.\n * `AAAAAAAAGWE=` is 6497. Anything else, or a value too large to count with, is `null`.\n */\nexport function decodeLongAttribute(value: string | undefined): number | null {\n if (!value) return null;\n const bytes = Buffer.from(value, 'base64');\n if (bytes.length !== 8) return null;\n const decoded = bytes.readBigInt64BE(0);\n return decoded >= 0n && decoded <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(decoded) : null;\n}\n\n/** The table's size, from its entity's `rows` and `columns` attributes. Missing reads as empty. */\nexport function tableDimensions(entity: Pick<Entity, 'attributes'>): { rows: number; columns: number } {\n return {\n rows: decodeLongAttribute(entity.attributes?.rows) ?? 0,\n columns: decodeLongAttribute(entity.attributes?.columns) ?? 0,\n };\n}\n\n/**\n * The first window of a table: up to 50 columns, then as many rows as fit a 2000-cell budget, at\n * most 100. A wide table therefore shows fewer rows rather than cutting a row short.\n */\nexport function defaultWindow(rows: number, columns: number): TableWindow {\n const shownColumns = Math.min(columns, WINDOW_MAX_COLUMNS);\n const budgeted = Math.max(1, Math.floor(WINDOW_MAX_CELLS / Math.max(1, shownColumns)));\n const shownRows = Math.min(rows, WINDOW_MAX_ROWS, budgeted);\n return { rows: { from: 0, to: shownRows }, columns: { from: 0, to: shownColumns } };\n}\n\n/**\n * A `--rows` / `--cols` value: `a:b` is half-open, so `0:10` is the first ten; an omitted start is\n * 0 and an omitted end is the end of the table. An end past the table is clamped to it; a range\n * that selects nothing, or starts past the table, is a usage error rather than an empty view.\n */\nexport function parseRange(text: string, size: number, label: 'Row' | 'Column'): Span {\n const noun = label === 'Row' ? 'rows' : 'columns';\n const match = /^\\s*(\\d*)\\s*:\\s*(\\d*)\\s*$/.exec(text);\n if (!match || (match[1] === '' && match[2] === '')) {\n throw new CliError(`${label} range \"${text}\" is not two numbers like 0:10.`, { exitCode: EXIT_USAGE });\n }\n const from = match[1] === '' ? 0 : Number(match[1]);\n const to = match[2] === '' ? size : Math.min(Number(match[2]), size);\n if (from >= size) {\n throw new CliError(`${label} range \"${text}\" starts past the table, which has ${size} ${noun}.`, { exitCode: EXIT_USAGE });\n }\n if (to <= from) {\n throw new CliError(`${label} range \"${text}\" selects no ${noun}.`, { exitCode: EXIT_USAGE });\n }\n return { from, to };\n}\n\n/**\n * The most cells the platform returns for one snapshot request (`TableSnapshotRequest.MAX_CELLS` on the\n * platform, which answers 413 above it). A window larger than this is asked for in parts.\n */\nexport const SNAPSHOT_MAX_CELLS = 65_536;\n\n/**\n * The window cut into parts that each stay within one snapshot request, in reading order: whole rows\n * as long as a row fits a request, and a row's columns in runs when it does not.\n */\nexport function windowParts(window: TableWindow, maxCells: number = SNAPSHOT_MAX_CELLS): TableWindow[] {\n const columns = window.columns.to - window.columns.from;\n const columnsPerPart = Math.max(1, Math.min(columns, maxCells));\n const rowsPerPart = Math.max(1, Math.floor(maxCells / columnsPerPart));\n const parts: TableWindow[] = [];\n for (let row = window.rows.from; row < window.rows.to; row += rowsPerPart) {\n for (let column = window.columns.from; column < window.columns.to; column += columnsPerPart) {\n parts.push({\n rows: { from: row, to: Math.min(row + rowsPerPart, window.rows.to) },\n columns: { from: column, to: Math.min(column + columnsPerPart, window.columns.to) },\n });\n }\n }\n return parts;\n}\n\n/** The window as the platform's request asks for it: inclusive ends. */\nexport function cellRange(window: TableWindow): CellRangeRequest {\n return {\n fromRowIndex: window.rows.from,\n toRowIndex: window.rows.to - 1,\n fromColumnIndex: window.columns.from,\n toColumnIndex: window.columns.to - 1,\n };\n}\n\n/**\n * The window's cells, fetched part by part and joined into one snapshot. Rows and columns that several\n * parts return are kept once.\n */\nexport async function fetchWindow(\n fetchPart: (range: CellRangeRequest) => Promise<TableSnapshot>,\n window: TableWindow,\n maxCells: number = SNAPSHOT_MAX_CELLS,\n): Promise<TableSnapshot> {\n const rows = new Map<number, TableSnapshot['rows'][number]>();\n const columns = new Map<number, TableSnapshot['columns'][number]>();\n const cells: TableSnapshot['cells'] = [];\n for (const part of windowParts(window, maxCells)) {\n const snapshot = await fetchPart(cellRange(part));\n for (const row of snapshot.rows) rows.set(row.index, row);\n for (const column of snapshot.columns) columns.set(column.index, column);\n for (const cell of snapshot.cells) cells.push(cell);\n }\n return { rows: [...rows.values()], columns: [...columns.values()], cells };\n}\n\n/** The line under the table saying what part of it is shown, and how to see the rest. */\nexport function describeWindow(window: TableWindow, rows: number, columns: number): string {\n const whole = window.rows.from === 0 && window.rows.to === rows\n && window.columns.from === 0 && window.columns.to === columns;\n const line = `Rows ${window.rows.from} to ${window.rows.to - 1} of ${rows} · columns ${window.columns.from} to ${window.columns.to - 1} of ${columns}`;\n return whole ? line : `${line} · use --rows/--cols for more`;\n}\n\n/**\n * A cell's value as text. The snapshot carries each value base64-encoded in the form its type is\n * stored in: `text` as UTF-8, `integer` as an 8-byte long, `number` as an 8-byte double, `bool` as one\n * byte. Any other type, or a typed value of the wrong length, is read as UTF-8 text, which is what the\n * platform falls back to as well.\n */\nexport function decodeCellValue(value: string | null | undefined, type: string | null | undefined): string {\n if (!value) return '';\n const bytes = Buffer.from(value, 'base64');\n switch (type) {\n case 'integer':\n if (bytes.length === 8) return bytes.readBigInt64BE(0).toString();\n break;\n case 'number':\n if (bytes.length === 8) return String(bytes.readDoubleBE(0));\n break;\n case 'bool':\n if (bytes.length === 1) return bytes[0] !== 0 ? 'true' : 'false';\n break;\n }\n return bytes.toString('utf-8');\n}\n","import type { Entity } from '../client/types/storage.js';\nimport { encodeLongAttribute, encodeTextAttribute } from './entity-attributes.js';\n\n/**\n * A new, empty table entity. Its cells, rows and columns come later, from an import or from cell writes; a table\n * without `rows` and `columns` attributes reads as empty.\n *\n * `index` orders the table among a notebook's sections, the way the Lab's Add Table does; a table at project\n * level has none.\n */\nexport function buildTableEntity(args: {\n projectId: string;\n projectBranch: string;\n entityId: string;\n entityBranch: string;\n name: string;\n index?: number;\n}): Entity {\n const now = Date.now();\n const attributes: Record<string, string> = { name: encodeTextAttribute(args.name) };\n const attributeTypes: Record<string, string> = { name: 'text' };\n if (args.index !== undefined) {\n attributes.index = encodeLongAttribute(args.index);\n attributeTypes.index = 'integer';\n }\n return {\n projectId: args.projectId,\n projectBranch: args.projectBranch,\n entityId: args.entityId,\n entityBranch: args.entityBranch,\n head: true,\n version: 1,\n type: 'table',\n attributes,\n attributeTypes,\n metaAttributes: {},\n metaAttributeTypes: {},\n tags: [],\n modified: now,\n created: now,\n versioned: false,\n versionTtl: null,\n retain: false,\n contentAvailable: false,\n contentLoaded: false,\n contentType: null,\n contentSize: null,\n content: null,\n };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseProjectReference } from '../../util/references.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerNotebookCommands(program: Command): void {\n const notebook = program\n .command('notebook')\n .description('Export and import notebook bundles')\n .addHelpText('after', `\nExamples:\n $ diafunc notebook export <project> <notebookId> --out notebook.dfnb\n $ diafunc notebook import <project> notebook.dfnb --preview\n $ diafunc notebook import <project> notebook.dfnb\n`);;\n\n notebook\n .command('export')\n .description('Export one or more notebooks (plus their closure) to a .dfnb bundle')\n .argument('<project>', 'Project reference (projectId or projectId/branch)')\n .argument('<notebookIds...>', 'Entity id(s) of the notebook(s) to export')\n .option('--out <file>', 'Output file (defaults to notebooks.dfnb)')\n .option('--data <encoding>', 'Embedded table-data encoding: csv (default) or parquet', 'csv')\n .option('--async', 'Queue a background job instead of streaming the download now')\n .action(async (project: string, notebookIds: string[], options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n const request = { rootEntityIds: notebookIds, dataFormat: options.data };\n\n if (options.async) {\n const bundleId = await api.storage.exportBundle(ref.projectId, ref.projectBranch, request);\n success(`Export queued (bundle ID: ${bundleId}).`);\n console.log(`Poll progress: diafunc notebook bundles ${project}`);\n return;\n }\n\n const response = await api.storage.streamBundle(ref.projectId, ref.projectBranch, request);\n const outFile = options.out ?? 'notebooks.dfnb';\n const buffer = Buffer.from(await response.arrayBuffer());\n fs.writeFileSync(outFile, buffer);\n success(`Bundle written to ${outFile} (${buffer.length} bytes, ${notebookIds.length} notebook(s)).`);\n } catch (error) {\n handleError(error);\n }\n });\n\n notebook\n .command('import')\n .description('Import a .dfnb bundle into a project')\n .argument('<project>', 'Target project reference (projectId or projectId/branch)')\n .argument('<file>', 'Path to the .dfnb bundle')\n .option('--on-conflict <policy>', 'copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip', 'copy')\n .option('--preview', 'Show the bundle inventory without importing')\n .action(async (project: string, file: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n\n const fileBuffer = fs.readFileSync(file);\n const blob = new Blob([fileBuffer]);\n const formData = new FormData();\n formData.append('content', blob, path.basename(file));\n\n if (options.preview) {\n const preview = await api.storage.previewBundleImport(ref.projectId, ref.projectBranch, formData);\n if (outputFormat === 'json') {\n format(preview, { format: outputFormat });\n return;\n }\n console.log(chalk.bold(`${preview.kind} bundle · ${preview.entityCount} entities`));\n if (preview.sourceProjectId) {\n console.log(chalk.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` +\n (preview.createdBy ? ` · by ${preview.createdBy}` : '')));\n }\n const counts = new Map<string, number>();\n for (const e of preview.entities ?? []) {\n counts.set(e.type, (counts.get(e.type) ?? 0) + 1);\n }\n for (const [type, count] of [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n console.log(` ${type}: ${count}`);\n }\n if (preview.lossinessNotes && preview.lossinessNotes.length > 0) {\n console.log(chalk.yellow('Lossiness:'));\n for (const note of preview.lossinessNotes) {\n console.log(chalk.yellow(` - ${note}`));\n }\n }\n return;\n }\n\n const result = await api.storage.importBundle(ref.projectId, ref.projectBranch, formData, options.onConflict);\n if (outputFormat === 'json') {\n format(result, { format: outputFormat });\n return;\n }\n success(`Imported ${result.entityCount} entities, ${result.linkCount} links.`);\n console.log(`Notebook id(s): ${result.rootEntityIds.join(', ')}`);\n } catch (error) {\n handleError(error);\n }\n });\n\n notebook\n .command('bundles')\n .description('List notebook-bundle export jobs for a project')\n .argument('<project>', 'Project reference (projectId or projectId/branch)')\n .action(async (project: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const ref = parseProjectReference(project, overrides);\n const api = createApiClient();\n const bundles = await api.storage.getBundles(ref.projectId, ref.projectBranch);\n if (outputFormat === 'json') {\n format(bundles, { format: outputFormat });\n return;\n }\n const rows = bundles.map(b => ({\n bundleId: b.bundleId,\n kind: b.kind,\n filename: b.filename,\n entities: b.entityCount ?? '',\n progress: b.progress,\n succeeded: b.succeeded ?? '',\n error: b.error ?? '',\n }));\n format(rows, {\n format: outputFormat,\n columns: ['bundleId', 'kind', 'filename', 'entities', 'progress', 'succeeded', 'error'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { randomUUID } from 'node:crypto';\nimport { timeUuid } from '../../util/time-uuid.js';\nimport {\n buildFunctionEntity,\n decodeFunctionSource,\n encodeFunctionSource,\n resultText,\n} from '../../util/function-content.js';\nimport { decodeTextAttribute } from '../../util/entity-attributes.js';\nimport { DEFAULT_FUNCTION_LANGUAGE, FUNCTION_LANGUAGES, resolveLanguage } from '../../util/function-language.js';\nimport { empty, success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\n/**\n * An evaluation id plus the time buckets the platform partitions evaluations by. The id must be a\n * version 1 UUID: the scheduler reads the timestamp out of it.\n */\nfunction createTimeUuid(): { evaluationId: string; year: number; month: number; day: number; hour: number } {\n const now = new Date();\n return {\n evaluationId: timeUuid(now.getTime()),\n year: now.getUTCFullYear(),\n month: now.getUTCMonth() + 1,\n day: now.getUTCDate(),\n hour: now.getUTCHours(),\n };\n}\n\nexport function registerFunctionCommands(program: Command): void {\n const fn = program\n .command('function')\n .description('Execute and manage functions')\n .addHelpText('after', `\nExamples:\n $ diafunc function call <ref> --args '{\"x\": 1}' run one\n $ diafunc function edit <ref> edit the source in $EDITOR\n $ diafunc function logs <ref> what the last run printed\n $ diafunc function languages what it can be written in\n`);;\n\n fn\n .command('call')\n .description('Execute a function')\n .argument('<ref>', 'Function entity reference')\n .option('--async', 'Execute asynchronously')\n .option('--args <json>', 'Arguments as JSON object')\n .option('--target <ref>', 'Target entity reference')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n const time = createTimeUuid();\n let args: Record<string, unknown> | null = null;\n let types: Record<string, string> | null = null;\n\n if (options.args) {\n args = JSON.parse(options.args);\n types = {};\n for (const [key, value] of Object.entries(args!)) {\n if (typeof value === 'number') types[key] = 'number';\n else if (typeof value === 'boolean') types[key] = 'bool';\n else types[key] = 'string';\n }\n }\n\n let targetEntityId: string | null = null;\n let targetEntityBranch: string | null = null;\n if (options.target) {\n const targetRef = parseEntityReference(options.target, overrides);\n targetEntityId = targetRef.entityId;\n targetEntityBranch = targetRef.entityBranch;\n }\n\n const isAsync = !!options.async;\n\n if (isAsync && outputFormat === 'human') {\n console.log('Launching function asynchronously ...');\n }\n\n const result = await api.evaluation.call({\n evaluationId: time.evaluationId,\n projectId: resolved.projectId,\n projectBranch: resolved.projectBranch,\n functionId: resolved.entityId,\n functionBranch: resolved.entityBranch,\n targetEntityId,\n targetEntityBranch,\n arguments: args,\n types,\n requested: Date.now(),\n provideOutputs: true,\n removeFunction: false,\n }, isAsync);\n\n if (isAsync) {\n if (outputFormat === 'human') {\n success('Function launched.');\n console.log(` Evaluation ID: ${result.evaluationId}`);\n } else {\n format({ evaluationId: result.evaluationId }, { format: outputFormat });\n }\n } else {\n if (outputFormat === 'human') {\n if (result.successful) {\n success('Function completed.');\n if (result.result) {\n console.log(` Result: ${resultText(result.result, result.resultEncoding)}`);\n }\n const duration = result.completed - result.started;\n console.log(` Duration: ${duration}ms`);\n } else {\n console.log(chalk.red('Function failed.'));\n console.log(` Error: ${result.error}`);\n if (result.lineNumber > 0) {\n console.log(` Line: ${result.lineNumber}, Column: ${result.columnNumber}`);\n }\n }\n if (result.outputs?.length) {\n console.log();\n console.log(chalk.bold('Outputs:'));\n for (const out of result.outputs) {\n console.log(` [${out.type}] ${out.output}`);\n }\n }\n } else {\n format(result, { format: outputFormat });\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('evaluations')\n .description('List evaluations for a function')\n .argument('<ref>', 'Function entity reference')\n .requiredOption('--date <date>', 'Date and hour (YYYY-MM-DD-HH in UTC)')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n const parts = options.date.split('-').map(Number);\n const [year, month, day, hour] = parts;\n const evaluations = await api.evaluation.getEvaluations(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n year, month, day, hour,\n );\n\n const summary = evaluations.map(e => ({\n evaluationId: e.evaluationId,\n active: e.active,\n successful: e.successful,\n language: e.language,\n started: e.started ? new Date(e.started).toISOString() : '—',\n duration: e.completed && e.started ? `${e.completed - e.started}ms` : '—',\n }));\n format(summary, {\n format: outputFormat,\n columns: [\n { key: 'evaluationId', kind: 'id' },\n { key: 'active', kind: 'boolean' },\n { key: 'successful', kind: 'boolean' },\n { key: 'language' },\n { key: 'started', kind: 'date' },\n { key: 'duration', kind: 'number' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('outputs')\n .description('Get outputs for an evaluation')\n .argument('<projectId>', 'Project ID')\n .argument('<evaluationId>', 'Evaluation ID')\n .action(async (projectId: string, evaluationId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const outputs = await api.evaluation.getOutputs(projectId, evaluationId);\n\n if (outputFormat === 'human') {\n if (outputs.length === 0) {\n empty('outputs');\n }\n for (const out of outputs) {\n const time = new Date(out.timestamp).toISOString();\n console.log(`${chalk.dim(time)} [${out.type}] ${out.output}`);\n }\n } else {\n format(outputs, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('logs')\n .description('Get logs for a function evaluation')\n .argument('<ref>', 'Function entity reference')\n .requiredOption('--date <date>', 'Date and hour (YYYY-MM-DD-HH in UTC)')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n const parts = options.date.split('-').map(Number);\n const [year, month, day, hour] = parts;\n const logs = await api.evaluation.getLogs(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n year, month, day, hour,\n );\n format(logs, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('stop')\n .description('Stop a running evaluation')\n .argument('<ref>', 'Function entity reference')\n .requiredOption('--date <date>', 'Date and hour (YYYY-MM-DD-HH in UTC)')\n .argument('<evaluationId>', 'Evaluation ID')\n .action(async (ref: string, evaluationId: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n const parts = options.date.split('-').map(Number);\n const [year, month, day, hour] = parts;\n await api.evaluation.stopEvaluation(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n year, month, day, hour,\n evaluationId,\n );\n success(`Evaluation ${evaluationId} stopped.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n // Replaces the `engines` command, which called GET /evaluation/engines/ — an endpoint the\n // platform does not have and, going by its history, never did: every invocation answered 404.\n .command('languages')\n .description('List the languages a function can be written in')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n format(\n FUNCTION_LANGUAGES.map((language) => ({\n language,\n default: language === DEFAULT_FUNCTION_LANGUAGE,\n })),\n { format: outputFormat, columns: [{ key: 'language' }, { key: 'default', kind: 'boolean' }] },\n );\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('last-evaluation')\n .description('Show the most recent evaluation of a function')\n .argument('<ref>', 'Function entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const evaluation = await api.evaluation.getLastEvaluation(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n );\n format(evaluation, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('create')\n .description('Create a new function entity')\n .argument('<ref>', 'Function entity reference')\n .option('--language <lang>', 'Function language (Java, Kotlin, Python, JavaScript, Scala); defaults to the project\\'s language')\n .option('--source <file>', 'Initial source code file')\n .option('--name <name>', 'Display name (defaults to entityId)')\n .action(async (ref: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const sourceCode = options.source ? fs.readFileSync(options.source, 'utf-8') : '';\n // Without an explicit --language the function carries no language attribute at all, so it\n // follows the project's default the way one created in the Lab does.\n const entity = buildFunctionEntity({\n projectId: resolved.projectId,\n projectBranch: resolved.projectBranch,\n entityId: resolved.entityId,\n entityBranch: resolved.entityBranch,\n name: options.name ?? resolved.entityId,\n language: options.language ?? null,\n sourceCode,\n });\n await api.storage.saveEntities([entity]);\n const effective = options.language\n ? options.language\n : `${await resolveLanguage(api, resolved.projectId)}, the project's language`;\n success(`Function \"${resolved.entityId}\" created (${effective}).`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // --- function source get/set ---\n const source = fn.command('source').description('Get or set function source code');\n\n source\n .command('get')\n .description('Print the function source code')\n .argument('<ref>', 'Function entity reference')\n .option('--out <file>', 'Write source to this file instead of stdout')\n .action(async (ref: string, options: { out?: string }, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const entity = await api.storage.getEntity(resolved, true);\n const sourceCode = decodeFunctionSource(entity);\n if (options.out) {\n fs.writeFileSync(options.out, sourceCode);\n success(`Source written to ${options.out}`);\n } else {\n process.stdout.write(sourceCode);\n if (!sourceCode.endsWith('\\n')) process.stdout.write('\\n');\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n source\n .command('set')\n .description('Replace the function source code from a file or stdin')\n .argument('<ref>', 'Function entity reference')\n .argument('[file]', 'Source file; defaults to stdin')\n .action(async (ref: string, file: string | undefined, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const sourceCode = file\n ? fs.readFileSync(file, 'utf-8')\n : await new Promise<string>((resolve, reject) => {\n let data = '';\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (chunk) => { data += chunk; });\n process.stdin.on('end', () => resolve(data));\n process.stdin.on('error', reject);\n });\n await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(sourceCode));\n success(`Source updated for \"${resolved.entityId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n fn\n .command('edit')\n .description('Open the function source in $EDITOR and save on exit')\n .argument('<ref>', 'Function entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const entity = await api.storage.getEntity(resolved, true);\n const currentSource = decodeFunctionSource(entity);\n const language = decodeTextAttribute(entity.attributes?.['language']) ?? 'txt';\n const ext = extensionFor(language);\n const tmpFile = path.join(os.tmpdir(), `diafunc-${resolved.entityId}-${randomUUID()}.${ext}`);\n fs.writeFileSync(tmpFile, currentSource);\n\n const editor = process.env.VISUAL ?? process.env.EDITOR ?? 'vi';\n await new Promise<void>((resolve, reject) => {\n const child = spawn(editor, [tmpFile], { stdio: 'inherit' });\n child.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`Editor exited with code ${code}`))));\n child.on('error', reject);\n });\n\n const newSource = fs.readFileSync(tmpFile, 'utf-8');\n fs.unlinkSync(tmpFile);\n\n if (newSource === currentSource) {\n empty('changes');\n return;\n }\n await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(newSource));\n success(`Source updated for \"${resolved.entityId}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction extensionFor(language: string): string {\n const l = language.toLowerCase();\n if (l === 'java') return 'java';\n if (l === 'javascript' || l === 'js') return 'js';\n if (l === 'kotlin') return 'kt';\n if (l === 'python') return 'py';\n if (l === 'scala') return 'scala';\n return 'txt';\n}\n","import { randomBytes } from 'node:crypto';\n\n/**\n * RFC 4122 version 1 (time-based) UUIDs.\n *\n * The platform addresses evaluations, runs and analyses by TimeUUID: Cassandra orders on the\n * embedded timestamp, and the scheduler calls `UUID.timestamp()` on the id it is handed. A version\n * 4 id has no timestamp, so that call throws `UnsupportedOperationException: Not a time-based\n * UUID`, the evaluation service answers 500, and the caller is told only that the request failed.\n *\n * The CLI minted ids with `crypto.randomUUID()` — which is version 4 — from a helper named\n * `createTimeUuid`, so `function call`, `schedule call` and `shell` all failed against production.\n */\n\n/** 100-nanosecond intervals between the Gregorian epoch (1582-10-15) and the Unix epoch. */\nconst GREGORIAN_OFFSET = 122_192_928_000_000_000n;\n\n/** Ids one generator can mint inside a single millisecond before the clock sequence advances. */\nconst INTERVALS_PER_MILLI = 10_000n;\n\nexport interface TimeUuidGenerator {\n (now?: number): string;\n}\n\n/**\n * Builds an independent generator.\n *\n * Uniqueness requires state — a node id, a clock sequence, and how far into the current\n * millisecond the last id sat — and holding it on a generator rather than in module scope keeps\n * the instant a caller asks for meaningful, since one generator's history cannot clamp another's.\n */\nexport function createTimeUuidGenerator(): TimeUuidGenerator {\n // RFC 4122 §4.5 allows a random node id in place of a MAC address provided the multicast bit is\n // set, which is what distinguishes it from a real hardware address.\n const node = randomBytes(6);\n node[0] |= 0x01;\n const nodeHex = node.toString('hex');\n\n let clockSequence = randomBytes(2).readUInt16BE(0) & 0x3fff;\n let lastTimestamp = 0n;\n let intervalsWithinMilli = 0n;\n\n return function generate(now: number = Date.now()): string {\n let timestamp = BigInt(now) * 10_000n + GREGORIAN_OFFSET;\n\n if (timestamp !== lastTimestamp) {\n lastTimestamp = timestamp;\n intervalsWithinMilli = 0n;\n } else {\n // `Date.now()` has millisecond resolution, so successive calls inside one millisecond would\n // otherwise collide. The sub-millisecond counter fills the gap; on overflow the clock\n // sequence advances, which is what RFC 4122 §4.2.1 prescribes for a clock that has not moved.\n intervalsWithinMilli += 1n;\n if (intervalsWithinMilli >= INTERVALS_PER_MILLI) {\n clockSequence = (clockSequence + 1) & 0x3fff;\n intervalsWithinMilli = 0n;\n }\n timestamp = lastTimestamp + intervalsWithinMilli;\n }\n\n const timeLow = Number(timestamp & 0xffff_ffffn);\n const timeMid = Number((timestamp >> 32n) & 0xffffn);\n const timeHiAndVersion = Number((timestamp >> 48n) & 0x0fffn) | 0x1000;\n const clockSeqHi = ((clockSequence >> 8) & 0x3f) | 0x80;\n const clockSeqLow = clockSequence & 0xff;\n\n return [\n hex(timeLow, 8),\n hex(timeMid, 4),\n hex(timeHiAndVersion, 4),\n hex(clockSeqHi, 2) + hex(clockSeqLow, 2),\n nodeHex,\n ].join('-');\n };\n}\n\n/** The generator the CLI mints evaluation ids from. */\nexport const timeUuid: TimeUuidGenerator = createTimeUuidGenerator();\n\nfunction hex(value: number, width: number): string {\n return value.toString(16).padStart(width, '0');\n}\n\n/** The UUID version nibble, for asserting which kind of id a value is. */\nexport function uuidVersion(uuid: string): number {\n return Number.parseInt(uuid.charAt(14), 16);\n}\n\n/** The instant encoded in a version 1 UUID, in epoch milliseconds. */\nexport function timeUuidInstant(uuid: string): number {\n const parts = uuid.split('-');\n const timestamp =\n (BigInt(Number.parseInt(parts[2], 16) & 0x0fff) << 48n) |\n (BigInt(Number.parseInt(parts[1], 16)) << 32n) |\n BigInt(Number.parseInt(parts[0], 16));\n return Number((timestamp - GREGORIAN_OFFSET) / 10_000n);\n}\n","import type { Entity } from '../client/types/storage.js';\nimport { encodeTextAttribute } from './entity-attributes.js';\n\n/**\n * Decodes the base64 JSON content of a function entity and returns the\n * sourceCode string. Returns an empty string if the entity has no content.\n */\nexport function decodeFunctionSource(entity: Entity): string {\n if (!entity.content) return '';\n const json = Buffer.from(entity.content, 'base64').toString('utf-8');\n try {\n const parsed = JSON.parse(json) as { sourceCode?: string };\n return parsed.sourceCode ?? '';\n } catch {\n // Older function entities may store raw source directly.\n return json;\n }\n}\n\n/**\n * Wraps `sourceCode` in the `{ sourceCode: \"...\" }` envelope and returns the\n * base64-encoded string expected by the server in `content`.\n */\nexport function encodeFunctionSource(sourceCode: string): string {\n return Buffer.from(JSON.stringify({ sourceCode })).toString('base64');\n}\n\nexport function buildFunctionEntity(args: {\n projectId: string;\n projectBranch: string;\n entityId: string;\n entityBranch: string;\n name?: string | null;\n /**\n * The language to pin on the function. Pass null to leave the attribute off entirely, which makes\n * the function follow its project's default language instead of freezing one in.\n */\n language: string | null;\n sourceCode: string;\n}): Entity {\n const now = Date.now();\n const attributes: Record<string, string> = {};\n const attributeTypes: Record<string, string> = {};\n if (args.language !== null && args.language !== undefined) {\n attributes.language = encodeTextAttribute(args.language);\n attributeTypes.language = 'text';\n }\n if (args.name !== null && args.name !== undefined) {\n attributes.name = encodeTextAttribute(args.name);\n attributeTypes.name = 'text';\n }\n return {\n projectId: args.projectId,\n projectBranch: args.projectBranch,\n entityId: args.entityId,\n entityBranch: args.entityBranch,\n head: true,\n version: 1,\n type: 'function',\n attributes,\n attributeTypes,\n metaAttributes: {},\n metaAttributeTypes: {},\n tags: [],\n modified: now,\n created: now,\n versioned: false,\n versionTtl: null,\n retain: false,\n contentAvailable: true,\n contentLoaded: true,\n contentType: 'application/script',\n contentSize: null,\n content: encodeFunctionSource(args.sourceCode),\n };\n}\n\n/**\n * A function's result as the platform sends it: once, in the form it has. A JSON result is JSON, a text result\n * a string, bytes that are not text a base64 string, and `resultEncoding` says which. Without `resultEncoding`\n * the result is in the earlier form, a base64 string; it is read for exactly one release.\n *\n * Returns the result as text for the terminal: JSON as compact JSON, text as it is, base64 decoded as UTF-8 when\n * it is text and left as base64 when it is not. Null when there is no result.\n */\nexport function resultText(result: unknown, resultEncoding?: string | null): string | null {\n if (result === null || result === undefined) return null;\n if (resultEncoding === 'json') return typeof result === 'string' ? result : JSON.stringify(result);\n if (resultEncoding === 'text') return String(result);\n const bytes = Buffer.from(String(result), 'base64');\n const text = bytes.toString('utf-8');\n return Buffer.from(text, 'utf-8').equals(bytes) ? text : String(result);\n}\n\n","import * as fs from 'node:fs';\nimport chalk from 'chalk';\nimport { ApiError } from '../../client/errors.js';\nimport { CliError, EXIT_USAGE, usageError } from '../../util/errors.js';\nimport { detail, heading, hint, warn } from '../../output/messages.js';\nimport type { Prompter } from '../../prompting/prompter.js';\nimport type {\n AnalysisResponse,\n IntentDecision,\n IntentInterpretation,\n IntentInterpretRequest,\n IntentItem,\n RequestedChartKind,\n RequestedPair,\n} from '../../client/types/analysis.js';\nimport { parseColumnList, quoteColumn, resolveColumnArgument, resolveColumnNames } from './columns.js';\n\n/**\n * \"What you know and what matters\": the owner's private notes, and the three recipe fields that\n * can come from them or be set directly (expectations about a target's shape, charts asked for at\n * launch, the question families that matter most).\n *\n * The platform reads the notes into proposals, each with a sentence the platform writes. Nothing\n * changes until the owner confirms a proposal. An expectation is checked (verified and reported) by\n * default and steers which model is delivered only when the owner says so, per expectation.\n *\n * The rules and the limits are the platform's (`services/analysis/doc/intent.md` in the platform\n * repo); the CLI checks the shape of what is typed before anything is created, so a typing mistake\n * does not leave a half-configured analysis behind, and the platform checks the rest.\n */\n\n/** The notes are at most this many characters. */\nexport const MAX_INTENT_LENGTH = 8_000;\n\n/** At most this many charts can be asked for. */\nexport const MAX_PAIRS = 12;\n\n/** At most this many question families can be in focus. */\nexport const MAX_FOCUS = 3;\n\nexport const CHART_KINDS: readonly RequestedChartKind[] = ['scatter', 'groups', 'counts'];\n\n/** The kinds of shape expectation, in the technology's printed form. */\nconst SHAPE_KINDS = ['increasing', 'decreasing', 'convex', 'concave', 'range'] as const;\n\n/**\n * The question families a focus can name, with how each reads to a person. The platform's\n * `QuestionFamily` is the source; it refuses an id it does not know.\n */\nexport const FOCUS_FAMILIES: readonly { id: string; label: string }[] = [\n { id: 'formula', label: 'the formula' },\n { id: 'accuracy', label: 'how accurate the model is' },\n { id: 'input_importance', label: 'which inputs matter most' },\n { id: 'search', label: 'how the search went' },\n { id: 'baselines', label: 'the comparison with simple baselines' },\n { id: 'partial_dependence', label: 'how each input moves the prediction' },\n { id: 'extrapolation', label: 'behavior outside the observed range' },\n { id: 'what_if', label: 'what-if scenarios and sensitivity' },\n { id: 'interactions', label: 'interactions between inputs' },\n { id: 'term_ablation', label: 'what each term of the formula adds' },\n { id: 'residuals', label: 'errors and prediction intervals' },\n { id: 'temporal', label: 'behavior over time' },\n { id: 'classification', label: 'classification performance' },\n { id: 'rating_levels', label: 'the rating levels' },\n { id: 'count_distribution', label: 'the distribution of counts' },\n { id: 'segments', label: 'differences between groups' },\n { id: 'fairness', label: 'fairness across groups of people' },\n { id: 'out_of_distribution', label: 'inputs unlike the training data' },\n { id: 'causality', label: 'whether the relationships are causal' },\n { id: 'deployment', label: 'whether the model is ready to use' },\n { id: 'multiple_targets', label: 'how the targets relate to each other' },\n { id: 'columns', label: 'what each column holds' },\n { id: 'correlations', label: 'how the columns move together' },\n { id: 'leakage', label: 'columns that give the answer away' },\n { id: 'duplicates', label: 'duplicate rows' },\n { id: 'trends', label: 'trends over time in the data' },\n { id: 'geography', label: 'where the rows are located' },\n];\n\n// ---------- the notes ----------\n\n/**\n * The notes `--intent <text>` or `--intent-file <path>` give, or undefined when neither was given.\n * An empty text is an empty string, which clears the notes where that means something.\n */\nexport function notesFromOptions(options: { intent?: string; intentFile?: string }): string | undefined {\n if (options.intent !== undefined && options.intentFile !== undefined) {\n usageError('Give the notes with --intent or with --intent-file, not both.');\n }\n let text = options.intent;\n if (options.intentFile !== undefined) {\n if (!fs.existsSync(options.intentFile)) {\n throw new CliError(`File not found: ${options.intentFile}`, { exitCode: EXIT_USAGE });\n }\n text = fs.readFileSync(options.intentFile, 'utf8');\n }\n if (text === undefined) return undefined;\n checkNotesLength(text);\n return text.trim();\n}\n\nexport function checkNotesLength(text: string): void {\n if (text.length > MAX_INTENT_LENGTH) {\n usageError(`The notes are ${text.length.toLocaleString('en-US')} characters long; at most `\n + `${MAX_INTENT_LENGTH.toLocaleString('en-US')} are kept.`, 'Shorten them and run it again.');\n }\n}\n\n// ---------- expectations ----------\n\n/**\n * Checks that `statement` is one shape expectation in the printed form, with `check:` or `require:`\n * in front or no mode at all (a check). Returns it trimmed. The platform reads it with the\n * technology's own parser and checks the columns; this only refuses what can never be one.\n */\nexport function checkedStatement(statement: string): string {\n const text = statement.trim();\n const refuse = (why: string): never => usageError(`'${statement}' is not a shape expectation: ${why}.`,\n 'Write one of increasing(input), decreasing(input, from, to), convex(input), concave(input) or range(lower, upper), '\n + \"with 'check:' (the default) or 'require:' in front.\");\n if (text.length === 0) refuse('it is empty');\n if (/[;\\n]/.test(text)) refuse('give one expectation per statement');\n let body = text;\n const colon = text.indexOf(':');\n const open = text.indexOf('(');\n if (colon > 0 && (open < 0 || colon < open)) {\n const mode = text.slice(0, colon).trim().toLowerCase();\n if (mode !== 'check' && mode !== 'require') refuse(`the mode '${mode}' is neither check nor require`);\n body = text.slice(colon + 1).trim();\n }\n const kindEnd = body.indexOf('(');\n if (kindEnd <= 0 || !body.endsWith(')')) refuse('it has no kind(arguments) form');\n const kind = body.slice(0, kindEnd).trim().toLowerCase();\n if (!(SHAPE_KINDS as readonly string[]).includes(kind)) refuse(`'${kind}' is not a kind of expectation`);\n return text;\n}\n\n/**\n * One `--shape <target>=<statement>`. The target is everything before the last `=`, since a\n * statement holds none, so a target whose name holds `=` still works.\n */\nexport function parseShapeFlag(given: string): { target: string; statement: string } {\n const equals = given.lastIndexOf('=');\n if (equals <= 0) {\n usageError(`'${given}' names no target.`, \"Write --shape <target>=<statement>, for example --shape 'price=increasing(size_m2)'.\");\n }\n const target = given.slice(0, equals).trim();\n if (target.length === 0) usageError(`'${given}' names no target.`);\n return { target, statement: checkedStatement(given.slice(equals + 1)) };\n}\n\n/** Every `--shape`, by target in the order given, or null when none was given. */\nexport function shapesOf(given: string[] | undefined): Record<string, string[]> | null {\n if (given === undefined || given.length === 0) return null;\n const byTarget: Record<string, string[]> = {};\n for (const flag of given) {\n const { target, statement } = parseShapeFlag(flag);\n (byTarget[target] ??= []);\n if (!byTarget[target].includes(statement)) byTarget[target].push(statement);\n }\n return byTarget;\n}\n\n/** The expectations with each target read against the analysis's columns; none are known before an upload. */\nexport function resolveShapeTargets(\n byTarget: Record<string, string[]>,\n columns: readonly string[],\n analysisId?: string,\n): Record<string, string[]> {\n const resolved: Record<string, string[]> = {};\n for (const [target, statements] of Object.entries(byTarget)) {\n const column = resolveColumnArgument(target, columns, analysisId);\n resolved[column] = [...(resolved[column] ?? []), ...statements.filter((s) => !(resolved[column] ?? []).includes(s))];\n }\n return resolved;\n}\n\n/** How a bound reads: `inf` as no bound, a whole number without its `.0`. */\nfunction boundText(text: string): string {\n const trimmed = text.trim();\n const n = Number(trimmed);\n return Number.isFinite(n) ? n.toLocaleString('en-US', { maximumFractionDigits: 6 }) : trimmed;\n}\n\nfunction isOpen(text: string | undefined): boolean {\n if (text === undefined) return true;\n const t = text.trim().toLowerCase();\n return t === '' || t === 'inf' || t === '+inf' || t === '-inf' || t === 'infinity' || t === '-infinity';\n}\n\n/**\n * One stored expectation as a sentence: what it says about the target, the window it covers, and\n * whether it is checked or also steers. A statement that does not read is shown as stored.\n */\nexport function expectationText(target: string, statement: string): string {\n const read = /^\\s*(?:(check|require)\\s*:)?\\s*([a-z]+)\\s*\\((.*)\\)\\s*$/i.exec(statement);\n if (!read) return `${target}: ${statement}`;\n const steer = (read[1] ?? 'check').toLowerCase() === 'require';\n const kind = read[2].toLowerCase();\n const args = read[3].split(',').map((a) => a.trim());\n const mode = steer ? 'Steers the model' : 'Checked';\n if (kind === 'range') {\n const [lower, upper] = args;\n const sentence = !isOpen(lower) && !isOpen(upper) ? `${target} stays between ${boundText(lower)} and ${boundText(upper)}`\n : !isOpen(lower) ? `${target} is never below ${boundText(lower)}`\n : !isOpen(upper) ? `${target} is never above ${boundText(upper)}`\n : `${target} has no bound`;\n return `${sentence}. ${mode}.`;\n }\n const input = args[0];\n const shape = kind === 'increasing' ? `does not fall as ${input} grows`\n : kind === 'decreasing' ? `does not rise as ${input} grows`\n : kind === 'convex' ? `curves upward as ${input} grows`\n : kind === 'concave' ? `levels off as ${input} grows`\n : null;\n if (!shape) return `${target}: ${statement}`;\n const window = args.length === 3 && !(isOpen(args[1]) && isOpen(args[2]))\n ? ` (${input} ${boundText(args[1])} to ${boundText(args[2])})`\n : args.length === 1 ? ` (across the observed ${input} values)` : '';\n return `${target} ${shape}${window}. ${mode}.`;\n}\n\n/** Every stored expectation as a sentence, target by target. */\nexport function expectationLines(byTarget: Record<string, string[]> | null | undefined): string[] {\n if (!byTarget) return [];\n return Object.entries(byTarget).flatMap(([target, statements]) => statements.map((s) => expectationText(target, s)));\n}\n\n// ---------- charts ----------\n\n/**\n * One chart as typed: `first,second` or `first,second,kind`, read as a list with the CLI's quoting,\n * so a column whose name holds a comma goes in double quotes: `'\"a, b\",price,scatter'`.\n */\nexport function parsePair(given: string): RequestedPair {\n const entries = parseColumnList(given);\n const usage = `Write <first>,<second> or <first>,<second>,<kind> with kind one of ${CHART_KINDS.join(', ')}; `\n + `a column whose name holds a comma goes in double quotes: '\"a, b\",price'.`;\n if (entries.length < 2 || entries.length > 3) {\n usageError(`'${given}' is not a chart: it names ${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}.`, usage);\n }\n let kind: RequestedChartKind | null = null;\n if (entries.length === 3) {\n const typed = entries[2].trim().toLowerCase();\n if (!(CHART_KINDS as readonly string[]).includes(typed)) {\n usageError(`'${entries[2]}' is not a chart kind.`, usage);\n }\n kind = typed as RequestedChartKind;\n }\n if (entries[0] === entries[1]) usageError(`'${given}' names the same column twice; a chart needs two different columns.`);\n return { first: entries[0], second: entries[1], kind };\n}\n\n/** Every chart given, in order and each once, or null when none was given; more than {@link MAX_PAIRS} is refused. */\nexport function pairsOf(given: string[] | undefined): RequestedPair[] | null {\n if (given === undefined) return null;\n const pairs: RequestedPair[] = [];\n for (const entry of given) {\n if (entry.trim().length === 0) continue;\n const pair = parsePair(entry);\n if (!pairs.some((p) => p.first === pair.first && p.second === pair.second && p.kind === pair.kind)) pairs.push(pair);\n }\n if (pairs.length > MAX_PAIRS) usageError(`${pairs.length} charts are asked for; at most ${MAX_PAIRS} can be.`);\n return pairs;\n}\n\n/** The charts with their columns read against the analysis's columns; none are known before an upload. */\nexport function resolvePairs(pairs: RequestedPair[], columns: readonly string[], analysisId?: string): RequestedPair[] {\n return pairs.map((pair) => {\n const [first, second] = resolveColumnNames([pair.first, pair.second], columns, analysisId);\n if (second === undefined) {\n usageError(`${quoteColumn(pair.first)} and ${quoteColumn(pair.second)} are the same column; a chart needs two different columns.`);\n }\n return { first, second, kind: pair.kind };\n });\n}\n\nexport function pairText(pair: RequestedPair): string {\n const how = pair.kind === 'scatter' ? ' as a scatter plot' : pair.kind === 'groups' ? ' by group'\n : pair.kind === 'counts' ? ' as counts' : '';\n return `${pair.second} against ${pair.first}${how}`;\n}\n\n// ---------- focus ----------\n\n/** A family as the platform reads one: any case, `-` or a space for `_`. */\nfunction familyId(typed: string): string {\n return typed.trim().toLowerCase().replace(/[- ]/g, '_');\n}\n\n/**\n * The families given, most important first and each once, or null when none was given. A flag may\n * hold several, comma-separated. An unknown family and more than {@link MAX_FOCUS} are refused.\n */\nexport function focusOf(given: string[] | undefined): string[] | null {\n if (given === undefined) return null;\n const families: string[] = [];\n const unknown: string[] = [];\n for (const typed of given.flatMap((g) => g.split(','))) {\n if (typed.trim().length === 0) continue;\n const id = familyId(typed);\n if (!FOCUS_FAMILIES.some((f) => f.id === id)) unknown.push(typed.trim());\n else if (!families.includes(id)) families.push(id);\n }\n if (unknown.length > 0) {\n usageError(`${unknown.map((u) => `'${u}'`).join(', ')} ${unknown.length === 1 ? 'is not a question family' : 'are not question families'}.`,\n `The families are: ${FOCUS_FAMILIES.map((f) => f.id).join(', ')}.`);\n }\n if (families.length > MAX_FOCUS) {\n usageError(`${families.length} families are named; at most ${MAX_FOCUS} can be in focus.`, 'Name the ones that matter most.');\n }\n return families;\n}\n\nexport function focusText(id: string): string {\n return FOCUS_FAMILIES.find((f) => f.id === id)?.label ?? id;\n}\n\n// ---------- the recipe, as a reader sees it ----------\n\n/** The lines the wizard's summary and `analyze get` show for what came from the notes. */\nexport function intentRecipeLines(analysis: Pick<AnalysisResponse, 'shapeExpectations' | 'requestedPairs' | 'focusFamilies'>): string[] {\n const lines: string[] = [];\n const statements = Object.values(analysis.shapeExpectations ?? {}).flat();\n if (statements.length > 0) {\n const steering = statements.filter((s) => /^\\s*require\\s*:/i.test(s)).length;\n const checked = statements.length - steering;\n const parts = [checked > 0 ? `${checked} checked` : null, steering > 0 ? `${steering} ${steering === 1 ? 'steers' : 'steer'} the model` : null]\n .filter(Boolean);\n lines.push(`Expectations: ${parts.join(', ')}`);\n }\n const pairs = analysis.requestedPairs ?? [];\n if (pairs.length > 0) lines.push(`Charts: ${pairs.map(pairText).join('; ')}`);\n const focus = analysis.focusFamilies ?? [];\n if (focus.length > 0) lines.push(`Focus: ${focus.map(focusText).join(', ')}`);\n return lines;\n}\n\n// ---------- reading the notes ----------\n\n/** The body of a read: the notes against the setup the analysis holds. */\nexport function interpretRequestOf(analysis: AnalysisResponse, intent: string): IntentInterpretRequest {\n return {\n intent,\n targets: analysis.targets ?? [],\n segment: analysis.segment ?? null,\n inputExclusions: analysis.inputExclusions ?? [],\n targetKinds: analysis.targetKinds ?? {},\n };\n}\n\n/** How often, and how far apart, a read or a save waits for the data's profile after an upload. */\nexport const PROFILE_ATTEMPTS = 10;\nexport const PROFILE_INTERVAL_MS = 2000;\n\nfunction waitingForProfile(interpretation: IntentInterpretation): boolean {\n return interpretation.status === 'UNAVAILABLE'\n && (interpretation.findings ?? []).some((f) => /profiled/i.test(f.text ?? ''));\n}\n\n/** Whether a refusal is the platform saying the data's profile is not there yet. */\nexport function isProfilePending(error: unknown): boolean {\n return error instanceof ApiError && error.status === 400 && /profiled/i.test(error.message);\n}\n\nconst pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Reads the notes. Right after an upload the data's profile can still be on its way, and the\n * platform answers that it reads the notes once it is there; the read is asked again a few times.\n */\nexport async function readNotes(\n api: { analysis: { interpretIntent(id: string, request: IntentInterpretRequest, options?: { force?: boolean; refine?: boolean }): Promise<IntentInterpretation> } },\n analysisId: string,\n request: IntentInterpretRequest,\n options: { force?: boolean; refine?: boolean } = {},\n): Promise<IntentInterpretation> {\n let interpretation = await api.analysis.interpretIntent(analysisId, request, options);\n for (let attempt = 1; attempt < PROFILE_ATTEMPTS && waitingForProfile(interpretation); attempt++) {\n await pause(PROFILE_INTERVAL_MS);\n interpretation = await api.analysis.interpretIntent(analysisId, request, options);\n }\n return interpretation;\n}\n\n/** Runs a save that needs the data's profile, asking again while the platform says it is not there yet. */\nexport async function whenProfiled<T>(save: () => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await save();\n } catch (error) {\n if (attempt >= PROFILE_ATTEMPTS || !isProfilePending(error)) throw error;\n await pause(PROFILE_INTERVAL_MS);\n }\n }\n}\n\n// ---------- proposals, as a reader sees them ----------\n\n/** What a proposal does, in the words the web app uses. */\nexport function effectLabel(item: IntentItem): string {\n switch (item.effect) {\n case 'checks':\n return item.steer ? 'Steers the model' : 'Checks the model';\n case 'changes':\n return 'Changes what is analyzed';\n case 'presents':\n return item.kind === 'pair' ? 'Adds a chart'\n : item.kind === 'question' ? 'Adds a question'\n : item.kind === 'focus' ? 'Sets the focus'\n : 'Changes what the report shows';\n case 'note':\n return 'A note only';\n case 'unavailable':\n return 'Not possible on this run';\n default:\n return item.effect;\n }\n}\n\nexport function stateLabel(state: IntentItem['state']): string {\n return state === 'CONFIRMED' ? 'Used' : state === 'DECLINED' ? 'Not used' : 'Proposed';\n}\n\n/** The order proposals are shown in: what bears on the model and the data first, then the report, then notes. */\nfunction groupOf(item: IntentItem): number {\n if (item.effect === 'checks' || item.effect === 'changes') return 0;\n if (item.effect === 'presents') return 1;\n if (item.effect === 'note') return 2;\n return 3;\n}\n\nconst GROUP_HEADINGS = [\n 'About the model and the data',\n 'What the report shows',\n 'Notes for the report',\n 'Not possible on this run',\n];\n\nexport function orderedItems(items: readonly IntentItem[]): IntentItem[] {\n return [...items].sort((a, b) => groupOf(a) - groupOf(b));\n}\n\n/**\n * Prints an interpretation for a person: each proposal with its id, state, effect, the platform's\n * sentence and the owner's words it came from; then what was not understood, what was not used and\n * why, and the findings.\n */\nexport function printInterpretation(interpretation: IntentInterpretation, analysisId: string): void {\n const items = orderedItems(interpretation.items ?? []);\n if (interpretation.status === 'EMPTY') {\n console.log(chalk.dim('No notes to read.'));\n hint(`Write them with 'diafunc analyze intent ${analysisId} \"<text>\"'.`);\n return;\n }\n if (interpretation.status === 'UNAVAILABLE') {\n for (const finding of interpretation.findings ?? []) warn(finding.text);\n if ((interpretation.findings ?? []).length === 0) warn('Your notes could not be read just now. Nothing was changed.');\n return;\n }\n if (items.length === 0) console.log(chalk.dim('Nothing in the notes could be turned into a proposal.'));\n let group = -1;\n for (const item of items) {\n if (groupOf(item) !== group) {\n group = groupOf(item);\n heading(GROUP_HEADINGS[group]);\n }\n console.log(` ${chalk.cyan(item.id)} ${stateLabel(item.state)} · ${effectLabel(item)}`);\n console.log(` ${item.statement}`);\n if (item.quote) detail(` from: \"${item.quote}\"`);\n }\n const notUnderstood = interpretation.notUnderstood ?? [];\n if (notUnderstood.length > 0) {\n heading('Not understood');\n for (const note of notUnderstood) console.log(` \"${note.quote}\"${note.reason ? `: ${note.reason}` : ''}`);\n }\n const rejections = interpretation.rejections ?? [];\n if (rejections.length > 0) {\n heading('Not used');\n for (const note of rejections) console.log(` \"${note.quote}\"${note.reason ? `: ${note.reason}` : ''}`);\n }\n const findings = interpretation.findings ?? [];\n if (findings.length > 0) {\n heading('Before you launch');\n for (const finding of findings) console.log(` ${finding.title ? `${finding.title}: ` : ''}${finding.text}`);\n }\n if (items.some((item) => item.state === 'PROPOSED' && item.effect !== 'unavailable')) {\n console.log();\n hint('Nothing changes until you confirm a proposal. Expectations are checked; add --steer to let one steer the model.');\n hint(`Use one with 'diafunc analyze intent confirm ${analysisId} <proposalId...>', or 'decline' it.`);\n }\n}\n\n/**\n * Asks about each proposal still open, one at a time: charts, focus and questions are offered as\n * used (they change only what the report presents), everything else as not used. A confirmed\n * expectation is then asked separately whether it may also steer the model, and the answer offered\n * is no: checking alone verifies it and reports the verdict.\n *\n * Returns the decisions to send; a proposal the reader already decided on, or one that cannot be\n * applied on this run, is not asked about.\n */\nexport async function promptIntentDecisions(prompter: Prompter, interpretation: IntentInterpretation): Promise<IntentDecision[]> {\n const decisions: IntentDecision[] = [];\n for (const item of orderedItems(interpretation.items ?? [])) {\n if (item.state !== 'PROPOSED' || item.effect === 'unavailable') continue;\n if (item.quote) detail(`from your notes: \"${item.quote}\"`);\n const use = await prompter.confirm({\n message: `${item.statement} (${effectLabel(item)}) Use it?`,\n default: item.effect === 'presents',\n });\n if (!use) {\n decisions.push({ id: item.id, state: 'DECLINED', steer: null });\n continue;\n }\n const steer = item.effect === 'checks'\n ? await prompter.confirm({\n message: 'Also use it to steer the model? Without steering it is checked and reported, and never decides which model is delivered.',\n default: false,\n })\n : null;\n decisions.push({ id: item.id, state: 'CONFIRMED', steer });\n }\n return decisions;\n}\n\n/** The unavailable proposals and the reasons, said once before the questions. */\nexport function printUnavailable(interpretation: IntentInterpretation): void {\n for (const item of interpretation.items ?? []) {\n if (item.effect === 'unavailable') warn(item.statement);\n }\n}\n","import { CliError, EXIT_USAGE } from '../../util/errors.js';\n\n/**\n * Column names on the command line.\n *\n * A column name is whatever the data's header says. It can hold a comma, a quote, or a space at\n * either end (\"Concrete compressive strength(MPa, megapascals) \" is a real one), and the platform\n * stores and compares it exactly. So a name is never cut at a comma on sight. When the analysis's\n * columns are known, what was typed is read against them; when they are not known yet, it is read\n * as a list with the usual CSV quoting.\n *\n * One argument (or one occurrence of a flag) is read in this order, and the first reading that\n * works is the one taken:\n *\n * 1. the whole argument is a column, exactly;\n * 2. the whole argument is one column once both are trimmed and compared without regard to case;\n * 3. the argument is a comma-separated list, each entry matched by 1 and then 2.\n *\n * In a list a double-quoted entry keeps its commas and its spaces, and `\"\"` inside it is a quote.\n * An unquoted entry is trimmed. A name that matches nothing, or more than one column, is an error\n * that says which columns there are, and nothing is sent.\n */\n\n/** How many column names an error spells out before it points at `analyze columns`. */\nconst MAX_COLUMNS_LISTED = 30;\n\n/** How many near matches an error offers for one unknown name. */\nconst MAX_NEAR_MATCHES = 3;\n\n/**\n * Reads one comma-separated list of names.\n *\n * A double-quoted entry is taken as written, commas and spaces included, with `\"\"` for a quote. An\n * unquoted entry is trimmed and may hold a quote anywhere but at its start. Empty entries are\n * dropped, so a trailing comma or an empty string names nothing.\n */\nexport function parseColumnList(text: string): string[] {\n const names: string[] = [];\n let i = 0;\n while (i < text.length) {\n while (i < text.length && isSpace(text[i])) i++;\n if (i >= text.length) break;\n if (text[i] === '\"') {\n let name = '';\n let closed = false;\n i++;\n while (i < text.length) {\n if (text[i] === '\"' && text[i + 1] === '\"') {\n name += '\"';\n i += 2;\n } else if (text[i] === '\"') {\n closed = true;\n i++;\n break;\n } else {\n name += text[i++];\n }\n }\n if (!closed) {\n throw new CliError(`A double quote is opened and never closed in: ${text}`, {\n exitCode: EXIT_USAGE,\n hint: QUOTING_HINT,\n });\n }\n while (i < text.length && isSpace(text[i])) i++;\n if (i < text.length && text[i] !== ',') {\n throw new CliError(`Text follows a closing double quote without a comma in: ${text}`, {\n exitCode: EXIT_USAGE,\n hint: QUOTING_HINT,\n });\n }\n i++;\n if (name.length > 0) names.push(name);\n } else {\n const end = text.indexOf(',', i);\n const name = text.slice(i, end === -1 ? text.length : end).trim();\n i = end === -1 ? text.length : end + 1;\n if (name.length > 0) names.push(name);\n }\n }\n return names;\n}\n\nconst QUOTING_HINT =\n `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '\"a, b\",c'.`;\n\nfunction isSpace(char: string): boolean {\n return char === ' ' || char === '\\t';\n}\n\n/** A name as an error shows it and as a list takes it: double-quoted, so a space at either end is visible. */\nexport function quoteColumn(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction loose(name: string): string {\n return name.trim().toLowerCase();\n}\n\ntype Match =\n | { kind: 'column'; column: string }\n | { kind: 'ambiguous'; candidates: string[] }\n | { kind: 'unknown' };\n\n/** The column `name` means: itself when it is one, else the only column equal to it trimmed and without regard to case. */\nfunction matchColumn(name: string, columns: readonly string[]): Match {\n if (columns.includes(name)) return { kind: 'column', column: name };\n const wanted = loose(name);\n const candidates = columns.filter((column) => loose(column) === wanted);\n if (candidates.length === 1) return { kind: 'column', column: candidates[0] };\n return candidates.length > 1 ? { kind: 'ambiguous', candidates } : { kind: 'unknown' };\n}\n\n/** Columns that look like `name`: one contains the other, or they differ by a couple of characters. */\nfunction nearMatches(name: string, columns: readonly string[]): string[] {\n const wanted = loose(name);\n if (wanted.length === 0) return [];\n return columns\n .map((column) => ({ column, distance: distanceTo(wanted, loose(column)) }))\n .filter((scored) => scored.distance !== null)\n .sort((a, b) => (a.distance as number) - (b.distance as number))\n .slice(0, MAX_NEAR_MATCHES)\n .map((scored) => scored.column);\n}\n\nfunction distanceTo(wanted: string, column: string): number | null {\n const edits = editDistance(wanted, column);\n if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;\n if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {\n return 100 + Math.abs(column.length - wanted.length);\n }\n return null;\n}\n\nfunction editDistance(a: string, b: string): number {\n let previous = Array.from({ length: b.length + 1 }, (_, j) => j);\n for (let i = 1; i <= a.length; i++) {\n const current = [i];\n for (let j = 1; j <= b.length; j++) {\n current[j] = Math.min(\n previous[j] + 1,\n current[j - 1] + 1,\n previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n );\n }\n previous = current;\n }\n return previous[b.length];\n}\n\ninterface Problems {\n unknown: string[];\n ambiguous: { name: string; candidates: string[] }[];\n /** Whether an argument was read as a list and one of its entries failed, which is when quoting is worth explaining. */\n fromList: boolean;\n}\n\nfunction take(name: string, columns: readonly string[], into: string[], problems: Problems): boolean {\n const match = matchColumn(name, columns);\n if (match.kind === 'column') {\n if (!into.includes(match.column)) into.push(match.column);\n return true;\n }\n if (match.kind === 'ambiguous') problems.ambiguous.push({ name, candidates: match.candidates });\n else problems.unknown.push(name);\n return false;\n}\n\nfunction refuse(problems: Problems, columns: readonly string[], analysisId?: string): never {\n const sentences: string[] = [];\n if (problems.unknown.length === 1) {\n sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);\n } else if (problems.unknown.length > 1) {\n sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(', ')}.`);\n }\n for (const { name, candidates } of problems.ambiguous) {\n sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(', ')}. `\n + 'Type the one you mean exactly.');\n }\n\n const hints: string[] = [];\n const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];\n if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(' or ')}?`);\n const listed = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(', ');\n const more = columns.length > MAX_COLUMNS_LISTED\n ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ''}`\n : '';\n hints.push(`The columns are: ${listed}${more}.`);\n if (problems.fromList) {\n hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '\"a, b\",c'.`);\n }\n throw new CliError(sentences.join(' '), { exitCode: EXIT_USAGE, hint: hints.join('\\n ') });\n}\n\n/**\n * The columns the given arguments name, in the order given and each once.\n *\n * With `columns` empty (the analysis holds no data yet) every argument is read as a list and the\n * names are returned as typed: there is nothing to match them against, and the platform checks them\n * when the analysis is run.\n *\n * @throws CliError naming what matched nothing or more than one column, with the columns there are\n */\nexport function resolveColumnArguments(\n given: readonly string[],\n columns: readonly string[],\n analysisId?: string,\n): string[] {\n const resolved: string[] = [];\n if (columns.length === 0) {\n for (const name of given.flatMap(parseColumnList)) {\n if (!resolved.includes(name)) resolved.push(name);\n }\n return resolved;\n }\n\n const problems: Problems = { unknown: [], ambiguous: [], fromList: false };\n for (const argument of given) {\n if (argument.trim().length === 0) continue;\n const whole = matchColumn(argument, columns);\n if (whole.kind === 'column') {\n if (!resolved.includes(whole.column)) resolved.push(whole.column);\n continue;\n }\n const names = parseColumnList(argument);\n const single = names.length === 1 && names[0] === argument.trim();\n for (const name of names) {\n if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;\n }\n }\n if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);\n return resolved;\n}\n\n/**\n * The columns that exact names mean, for names that are already a list (a preset's targets): no\n * argument is parsed, each name is one column.\n */\nexport function resolveColumnNames(\n names: readonly string[],\n columns: readonly string[],\n analysisId?: string,\n): string[] {\n if (columns.length === 0) return [...names];\n const resolved: string[] = [];\n const problems: Problems = { unknown: [], ambiguous: [], fromList: false };\n for (const name of names) take(name, columns, resolved, problems);\n if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);\n return resolved;\n}\n\n/** The one column an argument names. Never read as a list: a segment is a single column. */\nexport function resolveColumnArgument(given: string, columns: readonly string[], analysisId?: string): string {\n if (columns.length === 0) return given;\n return resolveColumnNames([given], columns, analysisId)[0];\n}\n\n/** A flag's value as the list of its occurrences, whether commander collected it or a prompt answered it. */\nexport function occurrences(value: string | string[] | undefined): string[] | undefined {\n if (value === undefined) return undefined;\n return Array.isArray(value) ? value : [value];\n}\n\n/** Collects a repeatable column flag, one entry per occurrence. */\nexport function collectColumns(value: string, previous: string[] = []): string[] {\n return previous.concat([value]);\n}\n","import { createApiClient } from '../../client/api.js';\nimport { usageError } from '../../util/errors.js';\n\n/**\n * Reading a finished analysis as text: the report as Markdown and the model of one target as code.\n *\n * Both answers are written through `process.stdout.write`, never `console.log`: the released binary\n * is built with Bun, which cuts a `console.log` larger than a pipe's buffer at 65,536 bytes, and a\n * report chapter or an exported model can be larger than that (see `doc/analyze.md`).\n */\n\n/** The languages `analyze export-model` writes a model in, as the platform names them. */\nexport const EXPORT_LANGUAGES = [\n 'formula',\n 'python',\n 'r',\n 'sql',\n 'javascript',\n 'java',\n 'kotlin',\n 'c',\n 'latex',\n] as const;\n\nexport type ExportLanguage = (typeof EXPORT_LANGUAGES)[number];\n\n/** Writes a text answer whole, ending in one newline so a shell prompt does not follow on its last line. */\nexport function writeText(text: string): void {\n if (text.length === 0) return;\n process.stdout.write(text);\n if (!text.endsWith('\\n')) process.stdout.write('\\n');\n}\n\n/** `--max-bytes`: a whole number of bytes. The platform clamps it to 4-256 KiB. */\nexport function parseMaxBytes(given: string | undefined): number | undefined {\n if (given === undefined) return undefined;\n const trimmed = given.trim();\n if (!/^\\d+$/.test(trimmed) || Number(trimmed) <= 0) {\n usageError(`--max-bytes must be a whole number of bytes, not \"${given}\".`,\n 'The platform reads between 4096 and 262144; without the flag it reads 32768.');\n }\n return Number(trimmed);\n}\n\n/** `--part`: a whole number from 1, and only together with `--chapter`, the one read that comes in parts. */\nexport function parsePart(given: string | undefined, chapter: string | undefined): number | undefined {\n if (given === undefined) return undefined;\n const trimmed = given.trim();\n if (!/^\\d+$/.test(trimmed) || Number(trimmed) < 1) {\n usageError(`--part must be a whole number from 1, not \"${given}\".`);\n }\n if (chapter === undefined) {\n usageError('--part reads one part of a chapter, so it needs --chapter.',\n 'Without --chapter the command prints the summary, which does not come in parts.');\n }\n return Number(trimmed);\n}\n\n/** `--language`, matched without regard to case; anything else stops the command before a request is sent. */\nexport function parseExportLanguage(given: string): ExportLanguage {\n const language = given.trim().toLowerCase();\n if (!(EXPORT_LANGUAGES as readonly string[]).includes(language)) {\n usageError(`\"${given}\" is not a language a model can be exported in.`,\n `Choose one of: ${EXPORT_LANGUAGES.join(', ')}.`);\n }\n return language as ExportLanguage;\n}\n\nexport async function printReport(\n analysisId: string,\n options: { chapter?: string; part?: string; maxBytes?: string },\n): Promise<void> {\n const maxBytes = parseMaxBytes(options.maxBytes);\n const chapter = options.chapter?.trim() || undefined;\n const part = parsePart(options.part, chapter);\n const api = createApiClient();\n const markdown = await api.analysis.getReportMarkdown(analysisId, { chapter, part, maxBytes });\n writeText(markdown);\n}\n\nexport async function printModelExport(\n analysisId: string,\n options: { language: string; target?: string },\n): Promise<void> {\n const language = parseExportLanguage(options.language);\n const target = options.target?.trim() || undefined;\n const api = createApiClient();\n const source = await api.analysis.exportModel(analysisId, { language, target });\n writeText(source);\n}\n\nexport const REPORT_HELP = `\nWithout --chapter it prints the summary of the report and the titles of its chapters. Name a\nchapter to read it whole with the chapters below it. A title several chapters share is narrowed\nby naming chapters above it, separated by \">\":\n\n $ diafunc analyze report <id>\n $ diafunc analyze report <id> --chapter \"Age > Correlation\"\n $ diafunc analyze report <id> --max-bytes 131072 > report.md\n\nA chapter larger than --max-bytes comes in parts. Each part ends with a line naming the next;\nread it with --part:\n\n $ diafunc analyze report <id> --chapter Data --part 2\n\nA title no chapter carries prints a sentence saying so, followed by the titles there are.\nFigures are not drawn; the numbers behind them are in the chapter's tables and values.\n`;\n\nexport const EXPORT_MODEL_HELP = `\nPrints the model the analysis found for one target, as a formula or as source code. With\nseveral targets, name one with --target. Public analyses can be exported too.\n\n $ diafunc analyze export-model <id> --language formula\n $ diafunc analyze export-model <id> --language python --target price > model.py\n`;\n","import { VALID_SCOPES } from '../commands/auth/token.js';\nimport { FOCUS_FAMILIES } from '../commands/analyze/intent.js';\nimport { EXPORT_LANGUAGES } from '../commands/analyze/report.js';\nimport type { PendingInput } from './command.js';\n\n/**\n * What kind of question each required input becomes.\n *\n * Resolution is by input name, refined by the command group where a name means different things:\n * `<id>` is an analysis under `analyze`, a data source under `data-sources`, a skeleton under\n * `skeleton`. An input with no rule resolves to `null`; at run time that still gets a plain text\n * prompt, but `command-tree.test.ts` fails on it, so a new command cannot ship without deciding.\n */\n\nexport type EntityContentType = 'table' | 'function' | 'notebook';\n\nexport type InputSpec =\n /** A project; `withBranch` lets the answer carry a branch (`projectId/branch`). */\n | { kind: 'project'; withBranch: boolean }\n /**\n * An entity inside a project. `form: 'ref'` answers `project/branch/entity`; `form: 'id'` answers\n * the bare entity id and reads the project from the input named by `projectFrom`.\n */\n | { kind: 'entity'; form: 'ref' | 'id'; contentType?: EntityContentType; projectFrom?: string; multiple?: boolean }\n | { kind: 'team' }\n | { kind: 'teamMember' }\n | { kind: 'projectMember' }\n | { kind: 'teamInvitation' }\n | { kind: 'analysis' }\n | { kind: 'analysisRun' }\n | { kind: 'preset' }\n | { kind: 'analysisTrigger' }\n | { kind: 'analysisColumns'; multiple: boolean; allowEmpty: boolean }\n | { kind: 'evaluation' }\n | { kind: 'functionTrigger' }\n | { kind: 'chatSession' }\n | { kind: 'apiToken' }\n | { kind: 'tokenResource' }\n | { kind: 'dataSource' }\n | { kind: 'dataSourceRun' }\n | { kind: 'skeleton' }\n | { kind: 'tableExporter' }\n | { kind: 'tableExport' }\n | { kind: 'invoice' }\n | { kind: 'invoiceDocument' }\n | { kind: 'projectBranch'; projectFrom: string }\n | { kind: 'event' }\n | { kind: 'occurrence' }\n | { kind: 'link' }\n | { kind: 'exportFormat' }\n | { kind: 'connectorType' }\n | { kind: 'profile' }\n | { kind: 'statusComponent' }\n | { kind: 'license' }\n /** One of a fixed set. */\n | { kind: 'choice'; choices: readonly string[] }\n /** Several of a fixed set, answered comma-separated. */\n | { kind: 'choices'; choices: readonly string[] }\n | { kind: 'file' }\n | { kind: 'number'; min: number; integer: boolean; exclusive?: boolean }\n /** `YYYY-MM-DD-HH` in UTC, defaulting to the current hour. */\n | { kind: 'date' }\n | { kind: 'text'; allowEmpty?: boolean; email?: boolean; defaultValue?: string };\n\nexport const PROJECT_ROLES = ['OWNER', 'ADMIN', 'DEVELOPER', 'GUEST'] as const;\nexport const TRIGGER_TYPES = ['CRON', 'INTERVAL', 'CONTINUOUS', 'EVENT'] as const;\nexport const ANALYSIS_TRIGGER_KINDS = ['ONCE', 'CRON'] as const;\nexport const VISIBILITIES = ['PRIVATE', 'PUBLIC'] as const;\nexport const SHELLS = ['bash', 'zsh', 'fish'] as const;\nexport const CONFIG_KEYS = ['defaults.project', 'defaults.branch', 'defaults.output'] as const;\n\n/** The entity type a command group works on, where the group implies one. */\nconst ENTITY_TYPE_BY_GROUP: Record<string, EntityContentType> = {\n table: 'table',\n function: 'function',\n trigger: 'function',\n schedule: 'function',\n};\n\nconst TEXT: InputSpec = { kind: 'text' };\nconst TEXT_OR_EMPTY: InputSpec = { kind: 'text', allowEmpty: true };\nconst POSITIVE: InputSpec = { kind: 'number', min: 0, integer: false, exclusive: true };\nconst INDEX: InputSpec = { kind: 'number', min: 0, integer: true };\n\n/**\n * Rules for one command, by the input's token: `<name>` for an argument, `--flag` for an option.\n * Consulted before the name rules, for the inputs whose meaning depends on the command.\n */\nconst BY_COMMAND: Record<string, Record<string, InputSpec>> = {\n 'analyze segment': { '<name>': { kind: 'analysisColumns', multiple: false, allowEmpty: true } },\n 'analyze targets': { '<column>': { kind: 'analysisColumns', multiple: true, allowEmpty: false } },\n 'analyze input-exclusions': { '<column>': { kind: 'analysisColumns', multiple: true, allowEmpty: true } },\n 'analyze confirmed-inputs': { '<column>': { kind: 'analysisColumns', multiple: true, allowEmpty: true } },\n 'analyze questions': { '<question>': TEXT_OR_EMPTY },\n 'analyze description': { '<text>': TEXT_OR_EMPTY },\n 'analyze introduction': { '<markdown>': TEXT_OR_EMPTY },\n 'analyze intent confirm': { '<proposalId>': TEXT },\n 'analyze intent decline': { '<proposalId>': TEXT },\n 'analyze intent reset': { '<proposalId>': TEXT },\n 'analyze charts': { '<pair>': TEXT_OR_EMPTY },\n 'analyze focus': { '<family>': { kind: 'choices', choices: FOCUS_FAMILIES.map((f) => f.id) } },\n // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.\n 'public show': { '<analysisId>': TEXT },\n 'analyze export-model': { '--language': { kind: 'choice', choices: EXPORT_LANGUAGES } },\n 'analyze presets save': { '--targets': TEXT, '--hours': POSITIVE, '--budget': POSITIVE },\n 'branch merge': {\n '--source': { kind: 'entity', form: 'ref' },\n '--target': { kind: 'project', withBranch: true },\n },\n 'branch create': { '<branchName>': TEXT },\n 'branch delete': { '<branchName>': { kind: 'projectBranch', projectFrom: 'projectId' } },\n 'admin backup restore-project': { '<projectBranch>': { kind: 'projectBranch', projectFrom: 'projectId' } },\n 'data-sources create': {\n '--project-id': { kind: 'project', withBranch: false },\n '--project-branch': { kind: 'projectBranch', projectFrom: 'projectId' },\n '--target-entity-id': { kind: 'entity', form: 'id', contentType: 'table', projectFrom: 'projectId' },\n '--target-entity-branch': { kind: 'text', defaultValue: 'main' },\n '--type': { kind: 'connectorType' },\n },\n 'table-exporters create': {\n '--function-project': { kind: 'project', withBranch: false },\n '--function-entity': { kind: 'entity', form: 'id', contentType: 'function', projectFrom: 'functionProject' },\n '--format': TEXT,\n },\n 'table exports get': { '--ref': { kind: 'entity', form: 'ref', contentType: 'table' } },\n 'table export': { '<format>': { kind: 'exportFormat' } },\n 'entity export': { '<entityIds>': { kind: 'entity', form: 'id', projectFrom: 'project', multiple: true } },\n 'notebook export': {\n '<notebookIds>': { kind: 'entity', form: 'id', contentType: 'notebook', projectFrom: 'project', multiple: true },\n },\n 'entity tags set': { '<tags>': TEXT_OR_EMPTY },\n 'project tags set': { '<tags>': TEXT_OR_EMPTY },\n 'admin curated-tags create': { '--display-name': TEXT },\n 'link delete': { '<linkId>': { kind: 'link' } },\n 'link create': { '<linkId>': TEXT },\n 'config profile use': { '<name>': { kind: 'profile' } },\n 'config profile remove': { '<name>': { kind: 'profile' } },\n 'config get': { '<key>': { kind: 'choice', choices: CONFIG_KEYS } },\n 'config set': { '<key>': { kind: 'choice', choices: CONFIG_KEYS } },\n 'project members invite': { '<userId>': TEXT, '<role>': { kind: 'choice', choices: PROJECT_ROLES } },\n 'project members join': { '<userId>': TEXT },\n 'license create': { '<licenseId>': TEXT, '--name': TEXT, '--flags': TEXT },\n 'trigger create': { '--type': { kind: 'choice', choices: TRIGGER_TYPES } },\n 'analyze triggers create': { '--kind': { kind: 'choice', choices: ANALYSIS_TRIGGER_KINDS } },\n 'function outputs': { '<evaluationId>': TEXT },\n 'admin project move': { '--to': TEXT },\n 'team create': { '--seats': { kind: 'number', min: 1, integer: true } },\n 'team seats preview': { '<count>': { kind: 'number', min: 1, integer: true } },\n 'team seats set': { '<count>': { kind: 'number', min: 1, integer: true } },\n};\n\n/** Rules by input name alone, for names that mean the same thing everywhere. */\nconst BY_NAME: Record<string, InputSpec> = {\n projectId: { kind: 'project', withBranch: false },\n projectRef: { kind: 'project', withBranch: true },\n project: { kind: 'project', withBranch: true },\n teamId: { kind: 'team' },\n invitationId: { kind: 'teamInvitation' },\n analysisId: { kind: 'analysis' },\n licenseId: { kind: 'license' },\n sessionId: { kind: 'chatSession' },\n tokenId: { kind: 'apiToken' },\n resource: { kind: 'tokenResource' },\n scopes: { kind: 'choices', choices: VALID_SCOPES },\n evaluationId: { kind: 'evaluation' },\n eventId: { kind: 'event' },\n occurrenceId: { kind: 'occurrence' },\n exportId: { kind: 'tableExport' },\n invoiceNumber: { kind: 'invoice' },\n fileName: { kind: 'invoiceDocument' },\n shell: { kind: 'choice', choices: SHELLS },\n vis: { kind: 'choice', choices: VISIBILITIES },\n kind: { kind: 'choice', choices: ANALYSIS_TRIGGER_KINDS },\n date: { kind: 'date' },\n file: { kind: 'file' },\n email: { kind: 'text', email: true },\n index: INDEX,\n row: INDEX,\n col: INDEX,\n count: INDEX,\n version: { kind: 'number', min: 1, integer: true },\n hours: POSITIVE,\n credits: POSITIVE,\n seats: { kind: 'number', min: 1, integer: true },\n value: TEXT_OR_EMPTY,\n // Free text: names, messages and ids the reader is creating rather than choosing.\n name: TEXT,\n tag: TEXT,\n tags: TEXT,\n newId: TEXT,\n message: TEXT,\n query: TEXT,\n title: TEXT,\n token: TEXT,\n subscriptionToken: TEXT,\n forkProjectId: TEXT,\n targetBranch: TEXT,\n bucketName: TEXT,\n objectName: TEXT,\n template: TEXT,\n plan: TEXT,\n schedule: TEXT,\n consumerType: TEXT,\n consumerId: TEXT,\n format: TEXT,\n key: TEXT,\n reason: TEXT,\n batchId: TEXT,\n userIdOrEmail: TEXT,\n};\n\n/** The input's token as it appears in help: `<name>` for an argument, `--flag` for an option. */\nexport function tokenOf(input: PendingInput): string {\n return input.kind === 'option' ? (input.flag ?? `--${input.name}`) : `<${input.name}>`;\n}\n\n/**\n * The question for `input` on the command at `path` (`table view`, without the program name), or\n * `null` when no rule covers it.\n */\nexport function specFor(path: string, input: PendingInput): InputSpec | null {\n const exact = BY_COMMAND[path]?.[tokenOf(input)];\n if (exact) return exact;\n\n const group = path.split(' ')[0];\n const sub = path.split(' ').slice(0, 2).join(' ');\n\n switch (input.name) {\n case 'ref':\n case 'sourceRef':\n case 'targetRef':\n return { kind: 'entity', form: 'ref', contentType: ENTITY_TYPE_BY_GROUP[group] };\n case 'userId':\n return group === 'team' ? { kind: 'teamMember' } : { kind: 'projectMember' };\n case 'id':\n if (sub === 'analyze presets') return { kind: 'preset' };\n if (group === 'analyze') return { kind: 'analysis' };\n if (group === 'data-sources') return { kind: 'dataSource' };\n if (group === 'skeleton') return { kind: 'skeleton' };\n if (group === 'table-exporters') return { kind: 'tableExporter' };\n if (group === 'status') return { kind: 'statusComponent' };\n return null;\n case 'runId':\n if (group === 'analyze') return { kind: 'analysisRun' };\n if (group === 'data-sources') return { kind: 'dataSourceRun' };\n return null;\n case 'triggerId':\n if (group === 'analyze') return { kind: 'analysisTrigger' };\n if (group === 'trigger') return { kind: 'functionTrigger' };\n return null;\n case 'role':\n return { kind: 'choice', choices: PROJECT_ROLES };\n case 'type':\n return null;\n default:\n return BY_NAME[input.name] ?? null;\n }\n}\n\n/**\n * The inputs a question reads its context from, so they are asked first: a member picker needs\n * the team, an evaluation picker needs the function and the hour.\n */\nexport function dependencies(spec: InputSpec): string[] {\n switch (spec.kind) {\n case 'teamMember':\n case 'teamInvitation':\n return ['teamId'];\n case 'projectMember':\n return ['projectId'];\n case 'analysisColumns':\n return ['id'];\n case 'evaluation':\n return ['ref', 'date'];\n case 'functionTrigger':\n case 'event':\n case 'tableExport':\n return ['ref'];\n case 'occurrence':\n return ['ref', 'eventId'];\n case 'link':\n return ['sourceRef'];\n case 'tokenResource':\n return ['resourceType'];\n case 'dataSourceRun':\n return ['id'];\n case 'invoiceDocument':\n return ['invoiceNumber'];\n case 'projectBranch':\n return [spec.projectFrom];\n case 'entity':\n return spec.projectFrom ? [spec.projectFrom] : [];\n default:\n return [];\n }\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { success } from '../../output/messages.js';\nimport { TRIGGER_TYPES } from '../../prompting/resolvers.js';\nimport type { TriggerType } from '../../client/types/evaluation.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerTriggerCommands(program: Command): void {\n const trigger = program\n .command('trigger')\n .description('Manage function triggers')\n .addHelpText('after', `\nExamples:\n $ diafunc trigger list <ref>\n $ diafunc trigger create <ref> --type CRON --expression '0 0 6 * * ?' every day at 06:00 (Quartz cron)\n $ diafunc trigger create <ref> --type INTERVAL --expression '15min' every 15 minutes\n $ diafunc trigger delete <ref> <triggerId>\n`);\n\n trigger\n .command('list')\n .description('List triggers for a function')\n .argument('<ref>', 'Function entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const triggers = await api.evaluation.getTriggers(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n );\n\n const summary = triggers.map(t => ({\n triggerId: t.triggerId,\n type: t.type,\n active: t.active,\n expression: t.expression ?? '—',\n fired: t.fired,\n persistent: t.persistent,\n createdBy: t.createdBy ? t.createdBy : 'paused (save it again to resume)',\n }));\n format(summary, {\n format: outputFormat,\n columns: ['triggerId', 'type', 'active', 'expression', 'fired', 'persistent', 'createdBy'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n trigger\n .command('get')\n .description('Get a specific trigger')\n .argument('<ref>', 'Function entity reference')\n .argument('<triggerId>', 'Trigger ID')\n .action(async (ref: string, triggerId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const t = await api.evaluation.getTrigger(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n triggerId,\n );\n format(t, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n trigger\n .command('delete')\n .description('Delete a trigger')\n .argument('<ref>', 'Function entity reference')\n .argument('<triggerId>', 'Trigger ID')\n .action(async (ref: string, triggerId: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.evaluation.deleteTrigger(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n triggerId,\n );\n success(`Trigger \"${triggerId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n trigger\n .command('create')\n .description('Create or update a trigger on a function')\n .argument('<ref>', 'Function entity reference')\n .requiredOption('--type <type>', `Trigger type (${TRIGGER_TYPES.join(', ')})`)\n .option('--trigger-id <id>', 'Trigger ID (auto-generated if omitted)')\n .option('--expression <expr>', \"CRON: a Quartz cron expression ('0 0 6 * * ?'); INTERVAL: a duration ('15min', '1h 30min')\")\n .option('--origin <ref>', 'Origin entity reference (for EVENT)')\n .option('--count <n>', 'Runs started each time the trigger fires', '1')\n .option('--persistent', 'Persistent trigger (survives after first fire)')\n .option('--inactive', 'Create the trigger inactive')\n .option('--max <n>', 'Maximum fire count (0 = unlimited)', '0')\n .option('--args <json>', 'Arguments passed on fire (JSON object)')\n .action(async (ref: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const fn = parseEntityReference(ref, overrides);\n const type = String(options.type).toUpperCase();\n if (!(TRIGGER_TYPES as readonly string[]).includes(type)) {\n throw new Error(`Unknown trigger type \"${options.type}\": use one of ${TRIGGER_TYPES.join(', ')}.`);\n }\n const count = Number(options.count);\n if (!Number.isInteger(count) || count < 1) {\n throw new Error(`--count must be a whole number of at least 1, not \"${options.count}\".`);\n }\n const api = createApiClient();\n const args = options.args ? JSON.parse(options.args) as Record<string, unknown> : null;\n const types = args ? Object.fromEntries(\n Object.entries(args).map(([k, v]) =>\n [k, typeof v === 'number' ? 'number' : typeof v === 'boolean' ? 'bool' : 'string']),\n ) : null;\n let originEntityId: string | null = null;\n let originEntityBranch: string | null = null;\n if (options.origin) {\n const o = parseEntityReference(options.origin, overrides);\n originEntityId = o.entityId;\n originEntityBranch = o.entityBranch;\n }\n await api.evaluation.saveTrigger({\n projectId: fn.projectId,\n projectBranch: fn.projectBranch,\n functionId: fn.entityId,\n functionBranch: fn.entityBranch,\n triggerId: options.triggerId ?? null,\n bucketId: null,\n type: type as TriggerType,\n expression: options.expression ?? null,\n conditions: null,\n conditionTypes: null,\n originEntityId,\n originEntityBranch,\n active: !options.inactive,\n quantity: count,\n fired: 0,\n maximum: options.max ? parseInt(options.max, 10) || null : null,\n evaluationIds: null,\n arguments: args,\n types,\n persistent: !!options.persistent,\n removeFunction: false,\n modified: null,\n created: null,\n scheduler: null,\n heartbeat: null,\n });\n success('Trigger saved.');\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { timeUuid } from '../../util/time-uuid.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerScheduleCommands(program: Command): void {\n const schedule = program\n .command('schedule')\n .description('Schedule function execution');\n\n schedule\n .command('call')\n .description('Schedule a function call')\n .argument('<ref>', 'Function entity reference')\n .option('--args <json>', 'Arguments as JSON object')\n .option('--target <ref>', 'Target entity reference')\n .action(async (ref: string, options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n\n let args: Record<string, unknown> | null = null;\n let types: Record<string, string> | null = null;\n if (options.args) {\n args = JSON.parse(options.args);\n types = {};\n for (const [key, value] of Object.entries(args!)) {\n if (typeof value === 'number') types[key] = 'number';\n else if (typeof value === 'boolean') types[key] = 'bool';\n else types[key] = 'string';\n }\n }\n\n let targetEntityId: string | null = null;\n let targetEntityBranch: string | null = null;\n if (options.target) {\n const targetRef = parseEntityReference(options.target, overrides);\n targetEntityId = targetRef.entityId;\n targetEntityBranch = targetRef.entityBranch;\n }\n\n const result = await api.scheduler.scheduleCall({\n evaluationId: timeUuid(),\n projectId: resolved.projectId,\n projectBranch: resolved.projectBranch,\n functionId: resolved.entityId,\n functionBranch: resolved.entityBranch,\n targetEntityId,\n targetEntityBranch,\n arguments: args,\n types,\n requested: Date.now(),\n provideOutputs: true,\n removeFunction: false,\n });\n\n if (outputFormat === 'human') {\n success('Function scheduled.');\n } else {\n format(result, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n schedule\n .command('stop')\n .description('Stop a scheduled function evaluation')\n .argument('<ref>', 'Function entity reference')\n .argument('<evaluationId>', 'Evaluation ID to stop')\n .requiredOption('--date <date>', 'Evaluation date/hour (YYYY-MM-DD-HH in UTC)')\n .action(async (ref: string, evaluationId: string, options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const [year, month, day, hour] = options.date.split('-').map(Number);\n await api.scheduler.stopScheduled(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n year, month, day, hour,\n evaluationId,\n );\n success(`Scheduled evaluation ${evaluationId} stopped.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n schedule\n .command('list')\n .description('List persistent triggers (scheduled functions are modeled as triggers)')\n .argument('<ref>', 'Function entity reference')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const triggers = await api.evaluation.getTriggers(\n resolved.projectId, resolved.projectBranch,\n resolved.entityId, resolved.entityBranch,\n );\n const scheduled = triggers.filter((t) => t.type === 'CRON' || t.type === 'INTERVAL');\n const rows = scheduled.map((t) => ({\n triggerId: t.triggerId,\n expression: t.expression,\n active: t.active,\n fired: t.fired,\n maximum: t.maximum,\n persistent: t.persistent,\n }));\n format(rows, {\n format: outputFormat,\n columns: ['triggerId', 'expression', 'active', 'fired', 'maximum', 'persistent'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport type { ChatStreamEvent } from '../../client/types/language.js';\nimport { failure, hint, success } from '../../output/messages.js';\nimport { SPINNER, Status } from '../../output/progress.js';\nimport { MarkdownRenderer, renderMarkdown } from '../../output/markdown.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\ninterface ChatReplOptions {\n session?: string;\n project?: string;\n branch: string;\n}\n\n/**\n * Streams one assistant turn onto the terminal.\n *\n * Two things the previous version did not do. The reply is markdown — the platform's assistant\n * writes headings, lists and fenced code — and it was written to the terminal verbatim, so the\n * reader saw the asterisks and backticks rather than the emphasis they denote. And nothing was\n * shown between pressing enter and the first token arriving, so the terminal simply sat there.\n *\n * `signal` aborts the turn without ending the session, which is what Ctrl-C should mean here.\n */\nasync function streamOneTurn(\n message: string,\n sessionId: string | undefined,\n projectId: string | undefined,\n branch: string,\n signal?: AbortSignal,\n): Promise<{ sessionId: string; input: number; output: number }> {\n const api = createApiClient();\n const status = new Status();\n status.set([` ${chalk.magenta(SPINNER)} ${chalk.dim('thinking')}`]);\n status.start();\n\n let response: Response;\n try {\n response = await api.language.chatStream({\n message,\n sessionId,\n projectId,\n projectBranch: projectId ? branch : undefined,\n });\n } catch (error) {\n status.stop();\n throw error;\n }\n\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n const markdown = new MarkdownRenderer();\n let buffer = '';\n let finalSession = sessionId ?? '';\n let input = 0;\n let output = 0;\n let started = false;\n\n const emit = (lines: string[]) => {\n if (lines.length === 0) return;\n if (!started) {\n started = true;\n status.stop();\n }\n for (const line of lines) console.log(line);\n };\n\n const onAbort = () => { void reader.cancel(); };\n signal?.addEventListener('abort', onAbort, { once: true });\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n for (const line of lines) {\n if (!line.startsWith('data:')) continue;\n const data = line.slice(5).trim();\n if (!data) continue;\n try {\n const event: ChatStreamEvent = JSON.parse(data);\n if (event.type === 'token' && event.content) {\n emit(markdown.push(event.content));\n } else if (event.type === 'done') {\n finalSession = event.sessionId ?? finalSession;\n input = event.inputTokens;\n output = event.outputTokens;\n } else if (event.type === 'error') {\n emit(markdown.flush());\n failure(event.content ?? 'The assistant reported an error.');\n }\n } catch {\n /* a partial or malformed event is skipped rather than shown as noise */\n }\n }\n }\n emit(markdown.flush());\n } finally {\n signal?.removeEventListener('abort', onAbort);\n status.stop();\n }\n return { sessionId: finalSession, input, output };\n}\n\nconst HELP = [\n ' /new start a fresh session',\n ' /session [id] show the current session, or switch to another',\n ' /clear clear the screen',\n ' /help this list',\n ' /quit leave (Ctrl-D also works)',\n];\n\nasync function runChatRepl(options: ChatReplOptions): Promise<void> {\n const { input: promptInput } = await import('@inquirer/prompts');\n const { getUpdateNotice } = await import('../../util/update-check.js');\n let sessionId: string | undefined = options.session;\n let lastReportedSession: string | undefined;\n\n console.log(chalk.bold('Diafunc chat') + chalk.dim(' · /help for commands, /quit to exit'));\n if (options.project) console.log(chalk.dim(`Project context: ${options.project}`));\n if (sessionId) console.log(chalk.dim(`Continuing session ${sessionId}`));\n const notice = await getUpdateNotice();\n if (notice) console.log(chalk.dim(notice));\n console.log();\n\n for (;;) {\n let line: string;\n try {\n line = await promptInput({ message: chalk.cyan.bold('you >') });\n } catch {\n // Ctrl-C or Ctrl-D at the prompt: leave.\n console.log();\n return;\n }\n\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n if (trimmed.startsWith('/')) {\n const [cmd, ...rest] = trimmed.slice(1).split(/\\s+/);\n const arg = rest.join(' ');\n switch (cmd) {\n case 'quit': case 'exit': case 'q':\n return;\n case 'new':\n sessionId = undefined;\n lastReportedSession = undefined;\n console.log(chalk.dim('Started a new session.'));\n continue;\n case 'clear':\n console.clear();\n continue;\n case 'session':\n if (!arg) {\n console.log(chalk.dim(`Current session: ${sessionId ?? '(new)'}`));\n } else {\n sessionId = arg;\n lastReportedSession = undefined;\n console.log(chalk.dim(`Switched to session ${sessionId}`));\n }\n continue;\n case 'help': case 'h': case '?':\n for (const l of HELP) console.log(chalk.dim(l));\n continue;\n default:\n console.log(chalk.dim(`Unknown command: /${cmd}. Try /help.`));\n continue;\n }\n }\n\n // Ctrl-C during a reply cancels that reply and returns to the prompt, rather than killing the\n // session the way an unhandled SIGINT would.\n const controller = new AbortController();\n const onSigint = () => controller.abort();\n process.on('SIGINT', onSigint);\n\n console.log();\n try {\n const result = await streamOneTurn(trimmed, sessionId, options.project, options.branch, controller.signal);\n sessionId = result.sessionId || sessionId;\n console.log();\n if (controller.signal.aborted) {\n console.log(chalk.dim(' (canceled)'));\n } else {\n // The session id is printed when it changes, not after every turn: it is the same\n // identifier each time and repeating it crowds out the answer above it.\n const parts = [`${result.input} in / ${result.output} out`];\n if (sessionId && sessionId !== lastReportedSession) {\n parts.push(`session ${sessionId}`);\n lastReportedSession = sessionId;\n }\n console.log(chalk.dim(` ${parts.join(' · ')}`));\n }\n console.log();\n } catch (error) {\n if (controller.signal.aborted) {\n console.log(chalk.dim(' (canceled)'));\n console.log();\n } else {\n failure(`Request failed: ${(error as Error).message}`);\n hint(`Check 'diafunc status summary' if this keeps happening.`);\n }\n } finally {\n process.off('SIGINT', onSigint);\n }\n }\n}\n\n/**\n * Project context for a chat turn, from the program's global `--project` and `--branch`.\n *\n * Unlike most commands, chat does not fall back to `defaults.project`: a project in context changes\n * what the assistant retrieves and answers about, so it is attached only when asked for. The branch\n * defaults to `main`, which is what the API received before these flags were read from the globals.\n */\nfunction chatContext(cmd: Command): { project?: string; branch: string } {\n const globals = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: globals.project, branch: globals.branch ?? 'main' };\n}\n\nexport function registerChatCommands(program: Command): void {\n const chat = program\n .command('chat')\n .description('Ask the Diafunc assistant')\n .addHelpText('after', `\nExamples:\n $ diafunc chat interactive session\n $ diafunc chat --project <id> with a project in context\n $ diafunc chat send \"how do I add a table?\" one question, one answer\n`);\n\n // The interactive REPL is the default subcommand, so `diafunc chat` still opens it, rather than an\n // action on `chat` itself: commander lets a parent claim its flags wherever they appear, and a\n // parent owning `--session` took it from `send` and `stream`. `--project` and `--branch` are the\n // program's global options, read through `optsWithGlobals()` as every other command reads them;\n // declared again here they were shadowed by the root and never arrived.\n // Slash-commands: /new, /session <id>, /help, /quit.\n chat\n .command('repl', { isDefault: true })\n .description('Interactive chat session (the default: `diafunc chat`)')\n .option('--session <id>', 'Continue an existing session')\n .action(async (options: { session?: string }, cmd: Command) => {\n try {\n const context = chatContext(cmd);\n await runChatRepl({ session: options.session, project: context.project, branch: context.branch });\n } catch (error) {\n handleError(error);\n }\n });\n\n chat\n .command('send')\n .description('Send a chat message (blocking). Project context: the global --project and --branch')\n .argument('<message>', 'Message to send')\n .option('--session <id>', 'Session ID to continue')\n .action(async (message: string, options: { session?: string }, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const context = chatContext(cmd);\n const response = await api.language.chat({\n message,\n sessionId: options.session,\n projectId: context.project,\n projectBranch: context.branch,\n });\n\n if (outputFormat === 'human') {\n console.log(renderMarkdown(response.content));\n console.log();\n console.log(chalk.dim(\n ` session ${response.sessionId} · ${response.inputTokens} in / ${response.outputTokens} out`,\n ));\n } else {\n format(response, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n chat\n .command('stream')\n .description('Send a chat message (streaming). Project context: the global --project and --branch')\n .argument('<message>', 'Message to send')\n .option('--session <id>', 'Session ID to continue')\n .action(async (message: string, options: { session?: string }, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const context = chatContext(cmd);\n const response = await api.language.chatStream({\n message,\n sessionId: options.session,\n projectId: context.project,\n projectBranch: context.branch,\n });\n\n if (outputFormat === 'json') {\n // Collect all events and output as JSON\n const events: ChatStreamEvent[] = [];\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n const data = line.slice(5).trim();\n if (data) {\n try {\n events.push(JSON.parse(data));\n } catch { /* skip malformed */ }\n }\n }\n }\n }\n format(events, { format: 'json' });\n } else {\n // Stream tokens to stdout\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n let sessionId = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data:')) {\n const data = line.slice(5).trim();\n if (!data) continue;\n try {\n const event: ChatStreamEvent = JSON.parse(data);\n if (event.type === 'token' && event.content) {\n process.stdout.write(event.content);\n } else if (event.type === 'done') {\n sessionId = event.sessionId ?? '';\n console.log();\n console.log();\n console.log(chalk.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));\n } else if (event.type === 'error') {\n failure(`Error: ${event.content}`);\n }\n } catch { /* skip malformed */ }\n }\n }\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n chat\n .command('upload')\n .description('Upload a file for chat context')\n .argument('<file>', 'File to upload')\n .action(async (file: string) => {\n try {\n if (!fs.existsSync(file)) {\n failure(`File not found: ${file}`);\n process.exit(1);\n }\n const api = createApiClient();\n const fileBuffer = fs.readFileSync(file);\n const blob = new Blob([fileBuffer]);\n const formData = new FormData();\n formData.append('file', blob, path.basename(file));\n const result = await api.language.upload(formData);\n success(`File uploaded: ${result}`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Session subcommands\n const session = chat\n .command('session')\n .description('Manage chat sessions');\n\n session\n .command('list')\n .description('List chat sessions')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const sessions = await api.language.getSessions();\n format(sessions, {\n format: outputFormat,\n columns: ['sessionId', 'title', 'projectId', 'modified'],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n session\n .command('delete')\n .description('Delete a chat session')\n .argument('<sessionId>', 'Session ID')\n .action(async (sessionId: string) => {\n try {\n const api = createApiClient();\n await api.language.deleteSession(sessionId);\n success(`Session \"${sessionId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n session\n .command('show')\n .description('Show the message history of a chat session')\n .argument('<sessionId>', 'Session ID')\n .action(async (sessionId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const detail = await api.language.getSession(sessionId);\n if (outputFormat === 'human') {\n console.log(chalk.bold(detail.title) + chalk.dim(` (${detail.sessionId})`));\n console.log();\n for (const msg of detail.messages) {\n const role = msg.role === 'user' ? chalk.cyan.bold('You') : chalk.magenta.bold('Diafunc');\n console.log(`${role} ${chalk.dim(msg.created)}`);\n console.log(msg.content);\n console.log();\n }\n } else {\n format(detail, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n session\n .command('rename')\n .description('Rename a chat session')\n .argument('<sessionId>', 'Session ID')\n .argument('<title>', 'New title')\n .action(async (sessionId: string, title: string) => {\n try {\n const api = createApiClient();\n await api.language.renameSession(sessionId, title);\n success(`Session \"${sessionId}\" renamed to \"${title}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n chat\n .command('usage')\n .description('Show token usage')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const usage = await api.language.getUsage();\n format(usage, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import chalk from 'chalk';\nimport { isInteractive, terminalWidth, wrap } from './terminal.js';\n\n/**\n * Renders the assistant's markdown for a terminal.\n *\n * The platform's assistant answers in markdown — the web app renders it, the CLI streamed it\n * verbatim, so a reply arrived as `## Heading`, `**bold**` and unfenced ``` blocks. This is a\n * deliberately small renderer: headings, emphasis, inline code, fenced code, lists, block quotes\n * and rules. Anything it does not recognise passes through unchanged, which is the right failure\n * mode for prose.\n *\n * Off a TTY nothing is styled and the source is emitted as written, so redirecting a reply to a\n * file yields the markdown the assistant actually produced.\n */\n\n/** Sentinel wrapping an extracted code span. NUL cannot occur in the assistant's text. */\nconst CODE_OPEN = '\\u0000c';\nconst CODE_CLOSE = '\\u0000';\n\n/**\n * Line-at-a-time renderer.\n *\n * Fenced code is a multi-line construct, so the fence state has to outlive a single line. Keeping\n * it on an object is also what lets the reply render while it streams: chunks arrive, complete\n * lines are rendered and printed, and the tail waits for its newline.\n */\nexport class MarkdownRenderer {\n private inFence = false;\n private pending = '';\n\n constructor(private readonly width: number = terminalWidth()) {}\n\n /** Renders whatever complete lines `chunk` completes. The remainder is held for the next call. */\n push(chunk: string): string[] {\n if (!isInteractive()) return this.pushPlain(chunk);\n this.pending += chunk;\n const parts = this.pending.split('\\n');\n this.pending = parts.pop() ?? '';\n return parts.flatMap((line) => this.line(line));\n }\n\n /** Renders the held remainder, if any. Call once the stream has ended. */\n flush(): string[] {\n if (this.pending === '') return [];\n const rest = this.pending;\n this.pending = '';\n return isInteractive() ? this.line(rest) : [rest];\n }\n\n private pushPlain(chunk: string): string[] {\n this.pending += chunk;\n const parts = this.pending.split('\\n');\n this.pending = parts.pop() ?? '';\n return parts;\n }\n\n private line(line: string): string[] {\n const fence = line.match(/^\\s*```(\\w*)\\s*$/);\n if (fence) {\n const opening = !this.inFence;\n this.inFence = !this.inFence;\n return opening && fence[1] ? [chalk.dim(` ${fence[1]}`)] : [];\n }\n if (this.inFence) {\n // Code is never wrapped or styled inside: breaking a line would change what it means.\n return [chalk.cyan(` ${line}`)];\n }\n\n const heading = line.match(/^(#{1,6})\\s+(.*)$/);\n if (heading) {\n const text = inline(heading[2]);\n return ['', heading[1].length <= 2 ? chalk.bold.underline(text) : chalk.bold(text)];\n }\n\n if (/^\\s*([-*_])\\1{2,}\\s*$/.test(line)) {\n return [chalk.dim('─'.repeat(Math.min(this.width, 60)))];\n }\n\n const quote = line.match(/^\\s*>\\s?(.*)$/);\n if (quote) return [chalk.dim(` │ ${inline(quote[1])}`)];\n\n const bullet = line.match(/^(\\s*)[-*+]\\s+(.*)$/);\n if (bullet) {\n return wrapWithIndent(`${bullet[1]}${chalk.cyan('•')} ${inline(bullet[2])}`,\n bullet[1].length + 2, this.width);\n }\n\n const numbered = line.match(/^(\\s*)(\\d+)\\.\\s+(.*)$/);\n if (numbered) {\n return wrapWithIndent(`${numbered[1]}${chalk.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,\n numbered[1].length + numbered[2].length + 2, this.width);\n }\n\n if (line.trim() === '') return [''];\n return wrapWithIndent(inline(line), 0, this.width);\n }\n}\n\n/** Renders a complete markdown document in one call. */\nexport function renderMarkdown(source: string, width = terminalWidth()): string {\n if (!isInteractive()) return source;\n const renderer = new MarkdownRenderer(width);\n return [...renderer.push(source), ...renderer.flush()].join('\\n');\n}\n\n/** Wraps a rendered line, indenting continuations to sit under the first character of the text. */\nfunction wrapWithIndent(text: string, indent: number, width: number): string[] {\n return wrap(text, width).map((l, i) => (i === 0 ? l : ' '.repeat(indent) + l));\n}\n\n/**\n * Span-level markup. Inline code is lifted out first so emphasis markers inside a code span stay\n * the literal characters they are.\n */\nexport function inline(text: string): string {\n const codeSpans: string[] = [];\n let working = text.replace(/`([^`]+)`/g, (_m, code: string) => {\n codeSpans.push(code);\n return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;\n });\n\n working = working\n .replace(/\\*\\*([^*]+)\\*\\*/g, (_m, t: string) => chalk.bold(t))\n .replace(/__([^_]+)__/g, (_m, t: string) => chalk.bold(t))\n .replace(/(^|[^*])\\*([^*\\n]+)\\*/g, (_m, lead: string, t: string) => lead + chalk.italic(t))\n .replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_m, label: string, url: string) =>\n `${chalk.underline(label)} ${chalk.dim(`(${url})`)}`);\n\n return working.replace(\n new RegExp(`${CODE_OPEN}(\\\\d+)${CODE_CLOSE}`, 'g'),\n (_m, i: string) => chalk.yellow(codeSpans[Number(i)]),\n );\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError, usageError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty } from '../../output/messages.js';\nimport { isInteractive } from '../../output/terminal.js';\nimport { percent } from '../../output/progress.js';\nimport type { SearchItem, SearchSort } from '../../client/types/index-search.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\ninterface SearchOptions {\n type?: string;\n limit: string;\n sort: string;\n}\n\n/** The orders the index offers for hits that match equally well. */\nexport function parseSort(raw: string): SearchSort {\n if (raw === 'best' || raw === 'newest') return raw;\n return usageError(`Unknown sort \"${raw}\".`, 'Use --sort best or --sort newest.');\n}\n\nexport function registerSearchCommands(program: Command): void {\n program\n .command('search')\n .description('Search across every project you can see')\n .argument('<query>', 'Search query')\n .option('--type <contentType>', 'Limit to one content type, e.g. project, notebook, table, function')\n .option('--limit <n>', 'Maximum results', '20')\n .option('--sort <order>', 'Order of equally relevant results: best (model quality) or newest', 'best')\n .addHelpText('after', `\nExamples:\n $ diafunc search \"housing\" everything matching, across projects\n $ diafunc search \"housing\" --type project only projects\n $ diafunc search \"medv\" --project <id> only inside one project\n $ diafunc search \"housing\" --sort newest most recently changed first among equal matches\n $ diafunc search \"housing\" --output json for scripting\n\nResults are ordered by how well they match. Among results that match equally well, the project\nwhose discovered model has the better quality comes first; inside one project the newer one does.\n`)\n .action(async (query: string, options: SearchOptions, cmd: Command) => {\n const sort = parseSort(options.sort);\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = cmd.optsWithGlobals() as { project?: string; branch?: string };\n const config = loadConfig();\n const api = createApiClient();\n\n // The global --project wins; otherwise a configured default scopes the search, and with\n // neither the search is global — which is what the command has always claimed to do.\n const projectId = overrides.project ?? config.defaults.project ?? null;\n const limit = Number.parseInt(options.limit, 10);\n\n const page = await api.index.searchPage({\n query,\n limit: Number.isFinite(limit) && limit > 0 ? limit : 20,\n contentType: options.type ?? null,\n projectId,\n projectBranch: projectId ? (overrides.branch ?? config.defaults.branch ?? 'main') : null,\n sort,\n });\n\n const items = dedupe(page.items);\n\n // JSON is always the page, so a script reads one shape whether or not anything matched.\n if (outputFormat === 'json') {\n format({ ...page, items }, { format: outputFormat });\n return;\n }\n\n if (items.length === 0) {\n empty('matches', { format: outputFormat });\n return;\n }\n\n if (isInteractive()) {\n renderResults(items);\n } else {\n format(items, {\n format: outputFormat,\n columns: [\n { key: 'contentType', header: 'type' },\n { key: 'name' },\n { key: 'quality' },\n { key: 'projectId', kind: 'id' },\n { key: 'entityId', kind: 'id' },\n ],\n });\n }\n\n if (page.nextCursor && isInteractive()) {\n console.log(chalk.dim(`More results available. Raise --limit to see them.`));\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/**\n * Collapses index rows that address the same thing.\n *\n * The index currently holds more than one row per project — two rows whose `itemId`s differ only\n * in their node suffix, so a search for \"housing\" returns each project twice. Until that is fixed\n * upstream the reader should not be shown the same result twice.\n */\nfunction dedupe(items: SearchItem[]): SearchItem[] {\n const seen = new Set<string>();\n const out: SearchItem[] = [];\n for (const item of items) {\n const key = [item.contentType, item.projectId, item.projectBranch, item.entityId, item.entityBranch].join('|');\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(item);\n }\n return out;\n}\n\n/**\n * A hit is a thing with a name, not a row of identifiers. The name leads, the matching text sits\n * under it, and the reference that addresses the result comes last, dimmed.\n */\nfunction renderResults(items: SearchItem[]): void {\n for (const item of items) {\n const name = item.name || '(unnamed)';\n console.log();\n console.log(`${chalk.dim(`[${item.contentType}]`)} ${chalk.bold(name)}${qualityNote(item)}`);\n\n // A snippet whose match is in the name would only repeat the heading above it.\n const raw = item.snippetField === 'name' ? item.description : (item.snippet ?? item.description);\n const line = raw ? collapse(raw) : null;\n if (line && stripHighlight(line) !== name) console.log(` ${highlight(line)}`);\n\n const ref = item.entityId\n ? `${item.projectId}/${item.projectBranch}/${item.entityId}/${item.entityBranch ?? 'main'}`\n : item.projectId;\n console.log(` ${chalk.dim(ref)}`);\n }\n console.log();\n}\n\n/**\n * The quality a project is ranked by, beside its own hit. An entity hit carries its project's\n * figure too, but the figure describes the project's model, so only the project says it.\n */\nexport function qualityNote(item: SearchItem): string {\n if (item.contentType !== 'project' || typeof item.quality !== 'number' || !Number.isFinite(item.quality)) {\n return '';\n }\n return chalk.dim(` quality ${percent(item.quality).trim()}`);\n}\n\nconst HIGHLIGHT_OPEN = /<mark>/g;\nconst HIGHLIGHT_CLOSE = /<\\/mark>/g;\n\n/**\n * The index marks matched terms with `<mark>` tags. They are markup for a browser; a terminal\n * needs the emphasis itself, not the tags around it.\n */\nfunction highlight(text: string): string {\n const parts = text.split(HIGHLIGHT_OPEN);\n return parts\n .map((part, i) => {\n if (i === 0) return chalk.dim(part);\n const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);\n return chalk.bold.cyan(marked) + chalk.dim(rest.join(''));\n })\n .join('');\n}\n\nfunction stripHighlight(text: string): string {\n return text.replace(HIGHLIGHT_OPEN, '').replace(HIGHLIGHT_CLOSE, '');\n}\n\n/** Index snippets carry newlines and runs of whitespace; a result line should be one line. */\nfunction collapse(text: string): string {\n const flat = text.replace(/\\s+/g, ' ').trim();\n return flat.length > 160 ? `${flat.slice(0, 159)}…` : flat;\n}\n","import { readFile } from 'node:fs/promises';\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport type { TeamContractRequest } from '../../client/types/admin.js';\nimport { success } from '../../output/messages.js';\nimport { registerCuratedTagCommands } from './curated-tags.js';\nimport { registerAdminProjectCommands } from './projects.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function registerAdminCommands(program: Command): void {\n const admin = program\n .command('admin')\n .description('Administration commands');\n\n // Users\n const users = admin.command('users').description('Manage users');\n\n users\n .command('list')\n .description('List all users (admin)')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const userList = await api.admin.getUsers();\n const summary = userList.map(u => ({\n id: u.id,\n name: u.name,\n email: u.email,\n role: u.role,\n remainingCredits: u.remainingCredits,\n }));\n format(summary, {\n format: outputFormat,\n columns: [\n { key: 'id', kind: 'id' },\n { key: 'name' },\n { key: 'email' },\n { key: 'role' },\n { key: 'remainingCredits', header: 'credits', kind: 'number' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n users\n .command('get')\n .description('Get current user details')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const user = await api.admin.getMyUser();\n format(user, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n // Subscription\n admin\n .command('subscription')\n .description('Show current subscription')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const sub = await api.admin.getCurrentSubscription();\n format(sub, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n // Settings\n const settings = admin.command('settings').description('Manage settings');\n\n settings\n .command('get')\n .description('Get current settings')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const s = await api.admin.getSettings();\n format(s, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n settings\n .command('set')\n .description('Update a setting')\n .argument('<key>', 'Setting key')\n .argument('<value>', 'Setting value')\n .action(async (key: string, value: string) => {\n try {\n const api = createApiClient();\n // The endpoint takes one { name, value } pair. Sending a map keyed by the setting name left\n // the platform with no name at all, which reached Cassandra as a null partition key and came\n // back as a 500, so this command had never once worked.\n await api.admin.mergeSetting({ name: key, value });\n success(`Setting \"${key}\" updated.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Platform settings are the operator-facing knobs (admission caps, load shedding). The `settings`\n // commands above are the signed-in user's own preferences: separate endpoint, separate storage,\n // so they get their own commands rather than a flag on those.\n const platformSettings = admin\n .command('platform-settings')\n .description('Manage platform-wide settings (admin only)');\n\n platformSettings\n .command('list')\n .description('Show every platform setting with its default and current override')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const settingsList = await api.admin.listPlatformSettings();\n format(settingsList, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n platformSettings\n .command('set')\n .description('Override one platform setting (an empty value restores the default)')\n .argument('<key>', 'Setting key, as shown by `platform-settings list`')\n .argument('<value>', 'New value; an empty string restores the compiled default')\n .option('--reason <reason>', 'Why it was changed; stored alongside the override')\n .action(async (key: string, value: string, options: { reason?: string }) => {\n try {\n const api = createApiClient();\n await api.admin.updatePlatformSetting(key, value, options.reason);\n success(`Platform setting \"${key}\" set to \"${value}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Backup\n const backup = admin.command('backup').description('Manage backups');\n\n backup\n .command('create-full')\n .description('Create a full system short-term backup')\n .option('--long-term', 'Create a long-term backup instead')\n .action(async (options: { longTerm?: boolean }) => {\n try {\n const api = createApiClient();\n if (options.longTerm) {\n await api.storage.createLongTermFullBackup();\n success('Full long-term backup initiated.');\n } else {\n await api.storage.createShortTermFullBackup();\n success('Full short-term backup initiated.');\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n backup\n .command('project')\n .description('Create a project short-term backup (use --long-term for long-term)')\n .option('--long-term', 'Create a long-term backup instead')\n .action(async (options: { longTerm?: boolean }) => {\n try {\n const api = createApiClient();\n if (options.longTerm) {\n await api.storage.createLongTermProjectBackup();\n success('Project long-term backup initiated.');\n } else {\n await api.storage.createShortTermProjectBackup();\n success('Project short-term backup initiated.');\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n backup\n .command('restore-project')\n .description('Restore a project from a backup bucket+object')\n .argument('<projectId>', 'Project ID')\n .argument('<projectBranch>', 'Project branch')\n .argument('<bucketName>', 'Backup bucket name')\n .argument('<objectName>', 'Backup object name')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (projectId: string, projectBranch: string, bucketName: string, objectName: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(\n `This will overwrite project \"${projectId}/${projectBranch}\" with backup ${bucketName}/${objectName}.`,\n { yes: options.yes },\n );\n const api = createApiClient();\n await api.storage.restoreProjectBackup({ projectId, projectBranch, bucketName, objectName });\n success(`Restore initiated for ${projectId}/${projectBranch} from ${bucketName}/${objectName}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n backup\n .command('restore-full')\n .description('Restore a full system backup from a bucket+object')\n .argument('<bucketName>', 'Backup bucket name')\n .argument('<objectName>', 'Backup object name')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (bucketName: string, objectName: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(\n `This will overwrite the ENTIRE system with backup ${bucketName}/${objectName}.`,\n { yes: options.yes },\n );\n const api = createApiClient();\n await api.storage.restoreFullBackup({ bucketName, objectName });\n success(`Full restore started from ${bucketName}/${objectName}.`);\n } catch (error) {\n handleError(error);\n }\n });\n\n // Index\n admin\n .command('index-rebuild')\n .description('Rebuild all search indexes (or a specific project with the global --project)')\n .action(async (_options, cmd: Command) => {\n try {\n const api = createApiClient();\n // The flag only, never defaults.project: a configured default must not quietly narrow a\n // rebuild of every index to a rebuild of one project.\n const { project } = cmd.optsWithGlobals() as { project?: string };\n if (project) {\n await api.index.rebuildProject(project);\n success(`Index rebuild started for project \"${project}\".`);\n } else {\n await api.index.rebuildAll();\n success('Index rebuild started for all projects.');\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n registerCuratedTagCommands(admin);\n\n registerAdminProjectCommands(admin);\n\n // Permissions\n admin\n .command('permissions')\n .description('Show your permissions on a project')\n .argument('<projectId>', 'Project ID')\n .action(async (projectId: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const perm = await api.admin.getPermissions(projectId);\n // The endpoint answers with a bare string. Printed as-is it was a lone word — `EDIT` —\n // with nothing saying what it referred to.\n format({ projectId, permission: perm }, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n // Team contracts (super-admin only)\n const team = admin.command('team').description('Team administration');\n const contract = team.command('contract').description('Issue and inspect negotiated team contracts');\n\n contract\n .command('get', { isDefault: true })\n .description(\"Show a team's contract\")\n .argument('<teamId>', 'Team ID')\n .action(async (teamId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n format(await api.admin.getTeamContract(teamId), { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n contract\n .command('issue')\n .description('Issue or replace a negotiated contract for a team')\n .argument('<teamId>', 'Team ID')\n .requiredOption('--file <path>', 'JSON file holding the contract request')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (teamId: string, options: { file: string; yes?: boolean }, cmd) => {\n try {\n const request = JSON.parse(await readFile(options.file, 'utf8')) as TeamContractRequest;\n await confirmDestructive(\n `This will replace the contract of team \"${teamId}\" with the terms in ${options.file}.`,\n { yes: options.yes, resourceId: teamId },\n );\n const api = createApiClient();\n format(await api.admin.issueTeamContract(teamId, request), { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { isDryRun } from '../../client/http.js';\nimport { handleError, usageError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, success } from '../../output/messages.js';\nimport { isReservedTag, normalizeTag } from '../../util/tags.js';\nimport type { CuratedTagRequest } from '../../client/types/index-search.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nconst COLUMNS = [\n { key: 'tag' },\n { key: 'displayName', header: 'name' },\n { key: 'description' },\n { key: 'sortOrder', header: 'order', kind: 'number' },\n { key: 'projectCount', header: 'public projects', kind: 'number' },\n] as const;\n\n/**\n * The canonical form of a curated tag, which is what the platform stores and looks it up by. Says so\n * on stderr when it differs from what was typed, so the reader knows which tag a project must carry.\n */\nexport function curatedTagOf(typed: string): string {\n const tag = normalizeTag(typed);\n if (tag === '') usageError(`\"${typed}\" is not a usable tag: a tag needs at least one letter or digit.`);\n if (tag !== typed) console.error(chalk.dim(`\"${typed}\" is written as \"${tag}\", the form tags are searched by.`));\n return tag;\n}\n\n/** `--sort-order` as a whole number; anything else is refused before the platform is asked. */\nexport function parseSortOrder(raw: string): number {\n if (!/^-?\\d+$/.test(raw.trim())) usageError(`Invalid --sort-order \"${raw}\": a whole number is expected.`);\n return Number.parseInt(raw, 10);\n}\n\ninterface CuratedTagOptions {\n displayName?: string;\n description?: string;\n sortOrder?: string;\n}\n\nexport function registerCuratedTagCommands(admin: Command): void {\n const curated = admin\n .command('curated-tags')\n .description('The curated tags: the \"data domain\" filter of Explore')\n .addHelpText('after', `\nA curated tag gives a tag a name and a place in Explore's data-domain filter; a project\nappears under it when it carries the tag (see 'diafunc project tags'). Anyone can list\nthem; creating, updating and deleting need a platform administrator.\n\nExamples:\n $ diafunc admin curated-tags list\n $ diafunc admin curated-tags create health --display-name \"Health\" --sort-order 1\n $ diafunc admin curated-tags update health --description \"Medicine, public health, biology\"\n $ diafunc admin curated-tags delete health\n`);\n\n curated\n .command('list')\n .description('List the curated tags in their order, with the number of public projects under each')\n .addHelpText('after', `\nNeeds no account. The counts are of public projects only and can be a minute behind.\n\nExamples:\n $ diafunc admin curated-tags list\n $ diafunc admin curated-tags list -o json\n`)\n .action(async (_options, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const tags = await createApiClient().index.getCuratedTags(true);\n if (tags.length === 0) {\n empty('curated tags', { format: outputFormat });\n return;\n }\n format(tags, { format: outputFormat, columns: COLUMNS });\n } catch (error) {\n handleError(error);\n }\n });\n\n curated\n .command('create')\n .description('Create a curated tag (admin)')\n .argument('<tag>', 'The tag projects carry, stored in its canonical form (\"Machine Learning\" becomes \"machine-learning\")')\n .requiredOption('--display-name <name>', 'The name Explore shows for it')\n .option('--description <text>', 'What belongs under it')\n .option('--sort-order <n>', 'Position in the filter, lowest first; tags without one come last')\n .addHelpText('after', `\nExamples:\n $ diafunc admin curated-tags create health --display-name \"Health\" --sort-order 1\n $ diafunc admin curated-tags create \"Machine Learning\" --display-name \"Machine learning\" --dry-run\n`)\n .action(async (typed: string, options: CuratedTagOptions, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const tag = curatedTagOf(typed);\n if (isReservedTag(tag)) {\n usageError(`\"${tag}\" is reserved for the staging content of analysis runs and is never searchable.`);\n }\n const displayName = (options.displayName ?? '').trim();\n if (displayName === '') usageError('--display-name must not be empty.');\n const request: CuratedTagRequest = {\n tag,\n displayName,\n ...(options.description !== undefined && options.description.trim() !== '' ? { description: options.description } : {}),\n ...(options.sortOrder !== undefined ? { sortOrder: parseSortOrder(options.sortOrder) } : {}),\n };\n const created = await createApiClient().index.createCuratedTag(request);\n if (isDryRun()) return;\n if (outputFormat === 'human') {\n success(`Curated tag \"${created.tag}\" created.`);\n } else {\n format(created, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n curated\n .command('update')\n .description('Change the name, description or position of a curated tag (admin)')\n .argument('<tag>', 'The curated tag')\n .option('--display-name <name>', 'The name Explore shows for it')\n .option('--description <text>', 'What belongs under it; an empty value clears it')\n .option('--sort-order <n>', 'Position in the filter, lowest first')\n .addHelpText('after', `\nOnly what is given changes. The tag itself cannot be renamed: delete it and create the new one.\n\nExamples:\n $ diafunc admin curated-tags update health --display-name \"Health and medicine\"\n $ diafunc admin curated-tags update health --description \"\" clears the description\n $ diafunc admin curated-tags update health --sort-order 3 --dry-run\n`)\n .action(async (typed: string, options: CuratedTagOptions, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const tag = curatedTagOf(typed);\n if (options.displayName === undefined && options.description === undefined && options.sortOrder === undefined) {\n usageError('Nothing to change.', 'Pass at least one of --display-name, --description, --sort-order.');\n }\n if (options.displayName !== undefined && options.displayName.trim() === '') {\n usageError('--display-name must not be empty.');\n }\n const request: CuratedTagRequest = {\n ...(options.displayName !== undefined ? { displayName: options.displayName.trim() } : {}),\n ...(options.description !== undefined ? { description: options.description } : {}),\n ...(options.sortOrder !== undefined ? { sortOrder: parseSortOrder(options.sortOrder) } : {}),\n };\n const updated = await createApiClient().index.updateCuratedTag(tag, request);\n if (isDryRun()) return;\n if (outputFormat === 'human') {\n success(`Curated tag \"${tag}\" updated.`);\n } else {\n format(updated, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n curated\n .command('delete')\n .description('Delete a curated tag (admin); projects that carry the tag keep it')\n .argument('<tag>', 'The curated tag')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .addHelpText('after', `\nExamples:\n $ diafunc admin curated-tags delete health\n $ diafunc admin curated-tags delete health --yes --dry-run\n`)\n .action(async (typed: string, options: { yes?: boolean }, cmd: Command) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const tag = curatedTagOf(typed);\n if (!isDryRun()) {\n await confirmDestructive(`This removes \"${tag}\" from Explore's data-domain filter.`, { yes: options.yes, resourceId: tag });\n }\n await createApiClient().index.deleteCuratedTag(tag);\n if (isDryRun()) return;\n success(`Curated tag \"${tag}\" deleted.`, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { readFile } from 'node:fs/promises';\n\n/**\n * A list of ids from a file or from stdin, for the commands that act on many objects at once.\n *\n * Ids are separated by whitespace, commas or new lines, so one id per line and a pasted\n * comma-separated row both work. A `#` starts a comment that runs to the end of its line.\n * Duplicates are dropped, keeping the first occurrence's place, so the count an operator confirms is the count of distinct objects.\n */\nexport function parseIdList(text: string): string[] {\n const ids = text\n .split(/\\r?\\n/)\n .map((line) => line.replace(/#.*$/, ''))\n .flatMap((line) => line.split(/[\\s,]+/))\n .map((id) => id.trim())\n .filter((id) => id.length > 0);\n return [...new Set(ids)];\n}\n\n/** Reads `source`, a file path or `-` for stdin, and parses it with {@link parseIdList}. */\nexport async function readIdList(source: string, stdin: NodeJS.ReadableStream = process.stdin): Promise<string[]> {\n const text = source === '-' ? await readAll(stdin) : await readFile(source, 'utf-8');\n return parseIdList(text);\n}\n\nfunction readAll(stream: NodeJS.ReadableStream): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let data = '';\n stream.setEncoding('utf-8');\n stream.on('data', (chunk) => { data += chunk; });\n stream.on('end', () => resolve(data));\n stream.on('error', reject);\n });\n}\n\n/** Merges ids given as arguments with ids read from a list, without duplicates. */\nexport function mergeIds(...lists: string[][]): string[] {\n return [...new Set(lists.flat().map((id) => id.trim()).filter((id) => id.length > 0))];\n}\n","import { Command } from 'commander';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { isDryRun } from '../../client/http.js';\nimport type {\n OperatorProjectMoveRequest,\n OperatorTransferStatusFilter,\n ProjectMoveBatch,\n ProjectMoveBatchStarted,\n ProjectMovePreflight,\n ProjectMoveVerdict,\n} from '../../client/types/admin.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, hint, success, warn } from '../../output/messages.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { CliError, EXIT_FAILURE, EXIT_USAGE, handleError } from '../../util/errors.js';\nimport { mergeIds, readIdList } from '../../util/id-list.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/** The most projects one bulk request may name; the platform refuses more. */\nexport const MAX_PROJECTS_PER_MOVE = 500;\n\nexport const OPERATOR_TRANSFER_STATUSES: readonly OperatorTransferStatusFilter[] = ['open', 'moving', 'failed'];\n\ninterface MoveOptions {\n to: string;\n team?: string;\n reason: string;\n idsFile?: string;\n keepPreviousOwner?: boolean;\n notify: boolean;\n preflight?: boolean;\n yes?: boolean;\n}\n\n/** The project ids of a move: the arguments plus the ids file, distinct, within the request limit. */\nexport async function collectProjectIds(args: string[], idsFile?: string): Promise<string[]> {\n const fromFile = idsFile ? await readIdList(idsFile) : [];\n const ids = mergeIds(args, fromFile);\n if (ids.length === 0) {\n throw new CliError('Name the projects to move, as arguments or with --ids-file <path|->.', { exitCode: EXIT_USAGE });\n }\n if (ids.length > MAX_PROJECTS_PER_MOVE) {\n throw new CliError(\n `${ids.length} projects named; one move takes at most ${MAX_PROJECTS_PER_MOVE}. Split the list.`,\n { exitCode: EXIT_USAGE },\n );\n }\n return ids;\n}\n\nexport function moveRequest(options: MoveOptions): OperatorProjectMoveRequest {\n const reason = options.reason.trim();\n if (!reason) throw new CliError('A move needs a reason: --reason <text>.', { exitCode: EXIT_USAGE });\n const toUserId = options.to.trim();\n if (!toUserId) throw new CliError('Name the new owner with --to <userId>.', { exitCode: EXIT_USAGE });\n return {\n toUserId,\n ...(options.team ? { toTeamId: options.team } : {}),\n previousOwnerRole: options.keepPreviousOwner ? 'MAINTAINER' : 'NONE',\n reason,\n notify: options.notify,\n };\n}\n\n/** The sentence an operator confirms before projects change hands. */\nexport function moveWarning(projectIds: string[], request: OperatorProjectMoveRequest): string {\n const what = projectIds.length === 1 ? `project \"${projectIds[0]}\"` : `${projectIds.length} projects`;\n const into = request.toTeamId ? ` into team ${request.toTeamId}` : '';\n const previous = request.previousOwnerRole === 'MAINTAINER'\n ? 'Each previous owner stays on as a maintainer'\n : 'Each previous owner loses access';\n const mail = request.notify ? 'both owners are told' : 'nobody is notified';\n return `This will move ${what} to user ${request.toUserId}${into} without asking anyone. ${previous}; ${mail}.`;\n}\n\n/** The verdicts of a preflight, whether the platform wraps them in `items` or sends the list itself. */\nexport function preflightVerdicts(result: ProjectMovePreflight | ProjectMoveVerdict[] | undefined): ProjectMoveVerdict[] {\n if (!result) return [];\n if (Array.isArray(result)) return result;\n return Array.isArray(result.items) ? result.items : [];\n}\n\nexport function isMovable(verdict: ProjectMoveVerdict): boolean {\n return verdict.verdict === 'ok';\n}\n\nexport function parseOperatorStatus(value: string | undefined): OperatorTransferStatusFilter | undefined {\n if (value === undefined) return undefined;\n const status = value.trim().toLowerCase() as OperatorTransferStatusFilter;\n if (!OPERATOR_TRANSFER_STATUSES.includes(status)) {\n throw new CliError(`Invalid status \"${value}\". Use one of: ${OPERATOR_TRANSFER_STATUSES.join(', ')}.`, { exitCode: EXIT_USAGE });\n }\n return status;\n}\n\n/** `GET` answers a batch with its rows; a reader wants the progress first and the rows below it. */\nexport function splitBatch(batch: ProjectMoveBatch): { summary: Record<string, unknown>; items: Record<string, unknown>[] } {\n const { items, ...summary } = batch;\n return { summary, items: (items ?? []) as unknown as Record<string, unknown>[] };\n}\n\nexport function registerAdminProjectCommands(admin: Command): void {\n const project = admin.command('project').description('Move projects between accounts and repair stuck transfers (admin)');\n\n project\n .command('move')\n .description('Move projects to another owner at once, without an offer or acceptance')\n .argument('[projectIds...]', 'Project IDs; more can come from --ids-file')\n .requiredOption('--to <userId>', 'User ID of the new owner')\n .requiredOption('--reason <text>', 'Why the projects move; stored in the activity log')\n .option('--team <teamId>', \"Put the projects into this team of the new owner instead of the new owner's active team\")\n .option('--ids-file <path>', 'Read project IDs from a file, or from stdin with \"-\": one per line, or separated by spaces or commas; \"#\" starts a comment')\n .option('--keep-previous-owner', 'Keep each previous owner on their project as a maintainer, with edit rights')\n .option('--no-notify', 'Send no notification or e-mail to the previous and the new owner')\n .option('--preflight', 'Only check: print what each project would do and change nothing')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .addHelpText('after', `\nA single project moves right away and the command prints the finished transfer. Several move as a\nbatch in the background (at most ${MAX_PROJECTS_PER_MOVE} per call; super-admin only); follow it with\n'diafunc admin project moves status <batchId>'.\n\n--preflight prints one verdict per project: ok, busy:<what is running>, not_found, already_owner or\nopen_transfer, and exits 1 if any project could not move.\n\nExamples:\n $ diafunc admin project move <projectId> --to <userId> --reason \"Support ticket 4711\"\n $ diafunc admin project move --ids-file examples.txt --to <userId> --reason \"Examples account\" --no-notify --preflight\n $ cat examples.txt | diafunc admin project move --ids-file - --to <userId> --reason \"Examples account\" --no-notify -y\n`)\n .action(async (args: string[], options: MoveOptions, cmd) => {\n let blocked = 0;\n try {\n const projectIds = await collectProjectIds(args, options.idsFile);\n const request = moveRequest(options);\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n\n if (options.preflight) {\n const result = await api.admin.moveProjects({\n ...request, projectIds, preflight: true, expectedCount: projectIds.length,\n });\n if (isDryRun()) return;\n const verdicts = preflightVerdicts(result as ProjectMovePreflight);\n blocked = verdicts.filter((v) => !isMovable(v)).length;\n if (outputFormat !== 'human') {\n format(result, { format: outputFormat });\n } else {\n format(verdicts, { format: outputFormat, columns: [{ key: 'projectId', kind: 'id' }, { key: 'verdict' }] });\n console.log('');\n const movable = verdicts.length - blocked;\n if (blocked === 0) success(`All ${movable} projects can move. Nothing was changed.`);\n else warn(`${movable} of ${verdicts.length} projects can move; ${blocked} cannot. Nothing was changed.`);\n }\n } else if (projectIds.length === 1) {\n await confirmDestructive(moveWarning(projectIds, request), { yes: options.yes, resourceId: projectIds[0] });\n const moved = await api.admin.moveProject(projectIds[0], request);\n if (isDryRun()) return;\n if (outputFormat !== 'human') {\n format(moved, { format: outputFormat });\n } else {\n success(`Moved project \"${moved.projectName ?? projectIds[0]}\" to ${moved.toUserName ?? request.toUserId}.`);\n }\n } else {\n await confirmDestructive(moveWarning(projectIds, request), {\n yes: options.yes, resourceId: String(projectIds.length),\n });\n const started = await api.admin.moveProjects({\n ...request, projectIds, preflight: false, expectedCount: projectIds.length,\n }) as ProjectMoveBatchStarted;\n if (isDryRun()) return;\n if (outputFormat !== 'human') {\n format(started, { format: outputFormat });\n } else {\n success(`Started moving ${projectIds.length} projects (batch ID: ${started.batchId}).`);\n hint(`Follow it with 'diafunc admin project moves status ${started.batchId}'.`);\n }\n }\n } catch (error) {\n handleError(error);\n }\n if (blocked > 0) process.exit(EXIT_FAILURE);\n });\n\n const moves = project.command('moves').description('Follow bulk moves');\n\n moves\n .command('status', { isDefault: true })\n .description('Show the progress of a bulk move and each project in it')\n .argument('<batchId>', 'Batch ID, as printed when the move started')\n .action(async (batchId: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const batch = await api.admin.getProjectMoveBatch(batchId);\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat !== 'human') {\n format(batch, { format: outputFormat });\n return;\n }\n const { summary, items } = splitBatch(batch);\n format(summary, { format: outputFormat });\n if (items.length > 0) {\n console.log('');\n format(items, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n const transfers = project.command('transfers').description('Inspect and repair project transfers');\n\n transfers\n .command('list', { isDefault: true })\n .description('List open offers and transfers that are moving or failed')\n .option('--status <status>', `Only transfers in this state: ${OPERATOR_TRANSFER_STATUSES.join(', ')}`)\n .action(async (options: { status?: string }, cmd) => {\n try {\n const status = parseOperatorStatus(options.status);\n const api = createApiClient();\n const list = (await api.admin.listOperatorProjectTransfers(status)) ?? [];\n const outputFormat = getOutputFormat(cmd);\n if (list.length === 0) {\n empty('project transfers', { format: outputFormat });\n return;\n }\n format(list, {\n format: outputFormat,\n columns: [\n { key: 'projectName', header: 'project' },\n { key: 'projectId', kind: 'id' },\n { key: 'transferId', kind: 'id' },\n { key: 'status', kind: 'state' },\n { key: 'kind' },\n { key: 'fromUserName', header: 'from' },\n { key: 'toUserName', header: 'to' },\n { key: 'offeredAt', kind: 'date' },\n { key: 'expiresAt', kind: 'date' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfers\n .command('resume')\n .description('Run a transfer that is stuck while moving again, from the first step it has not done')\n .argument('<projectId>', 'Project ID')\n .requiredOption('--reason <text>', 'Why it is resumed; stored in the activity log')\n .action(async (projectId: string, options: { reason: string }, cmd) => {\n try {\n const api = createApiClient();\n await api.admin.resumeProjectTransfer(projectId, requireReason(options.reason));\n success(`Resumed the transfer of project \"${projectId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfers\n .command('abort')\n .description('Undo a stuck transfer that has not reached its commit step; past it, resume instead')\n .argument('<projectId>', 'Project ID')\n .requiredOption('--reason <text>', 'Why it is aborted; stored in the activity log')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (projectId: string, options: { reason: string; yes?: boolean }, cmd) => {\n try {\n const reason = requireReason(options.reason);\n await confirmDestructive(\n `This will undo the steps the transfer of project \"${projectId}\" has done and leave it with its previous owner.`,\n { yes: options.yes, resourceId: projectId },\n );\n const api = createApiClient();\n await api.admin.abortProjectTransfer(projectId, reason);\n success(`Aborted the transfer of project \"${projectId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n\n transfers\n .command('cancel')\n .description(\"Cancel an open offer on the owner's behalf\")\n .argument('<projectId>', 'Project ID')\n .requiredOption('--reason <text>', 'Why it is canceled; stored in the activity log')\n .option('-y, --yes', 'Skip the confirmation prompt')\n .action(async (projectId: string, options: { reason: string; yes?: boolean }, cmd) => {\n try {\n const reason = requireReason(options.reason);\n await confirmDestructive(\n `This will cancel the open offer of project \"${projectId}\". The owner can offer it again.`,\n { yes: options.yes, resourceId: projectId },\n );\n const api = createApiClient();\n await api.admin.cancelProjectTransferAsOperator(projectId, reason);\n success(`Canceled the open offer of project \"${projectId}\".`, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction requireReason(reason: string): string {\n const trimmed = reason.trim();\n if (!trimmed) throw new CliError('Give a reason with --reason <text>.', { exitCode: EXIT_USAGE });\n return trimmed;\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createStatusService } from '../../client/services/status.js';\nimport { handleError } from '../../util/errors.js';\nimport { type OutputFormat, format } from '../../output/formatter.js';\nimport { formatInstant } from '../../output/values.js';\n\nconst STATE_COLORS: Record<string, (s: string) => string> = {\n UP: chalk.green,\n DEGRADED: chalk.yellow,\n DOWN: chalk.red,\n UNKNOWN: chalk.gray,\n};\n\nfunction stateColor(state: string): (s: string) => string {\n return STATE_COLORS[state] ?? chalk.gray;\n}\n\nfunction stateSymbol(state: string): string {\n switch (state) {\n case 'UP': return chalk.green('●');\n case 'DEGRADED': return chalk.yellow('●');\n case 'DOWN': return chalk.red('●');\n default: return chalk.gray('○');\n }\n}\n\nexport function registerSummaryCommand(parent: Command): void {\n parent\n .command('summary', { isDefault: true })\n .description('Show overall platform status')\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? 'human';\n const status = createStatusService();\n\n const [summary, version] = await Promise.all([\n status.getSummary(),\n status.getVersion(),\n ]);\n\n if (outputFormat !== 'human') {\n format({ ...summary, version }, { format: outputFormat });\n return;\n }\n\n const overallLabel = summary.overall === 'UP' ? 'All Systems Operational'\n : summary.overall === 'DEGRADED' ? 'Partial Degradation'\n : summary.overall === 'DOWN' ? 'Major Outage'\n : 'Unknown';\n\n console.log();\n console.log(` ${stateSymbol(summary.overall)} ${stateColor(summary.overall)(overallLabel)}`);\n console.log();\n\n // The domain names are what a reader recognises, but `status component` is addressed by\n // component id. Printing the ids under each domain is what makes the drill-down usable;\n // without them the summary named things the next command could not accept.\n for (const domain of summary.domains) {\n const label = stateColor(domain.state)(domain.state.padEnd(10));\n console.log(` ${stateSymbol(domain.state)} ${label} ${domain.name}`);\n if (domain.componentIds.length > 0) {\n console.log(` ${chalk.dim(domain.componentIds.join(', '))}`);\n }\n }\n\n console.log();\n if (summary.openIncidents > 0) {\n console.log(chalk.yellow(` ${summary.openIncidents} active incident(s)`));\n } else {\n console.log(chalk.dim(' No active incidents'));\n }\n\n console.log(chalk.dim(\n `\\n Platform v${version.platformVersion} · checked ${formatInstant(summary.timestamp)}`,\n ));\n console.log(chalk.dim(` Drill into one with 'diafunc status component <id>'.`));\n console.log();\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { loadConfig, resolveEndpoint } from '../../config/store.js';\n\nexport interface StatusSummary {\n timestamp: string;\n overall: string;\n domains: StatusDomain[];\n openIncidents: number;\n}\n\nexport interface StatusDomain {\n id: string;\n name: string;\n state: string;\n componentIds: string[];\n degradedCount: number;\n downCount: number;\n}\n\nexport interface StatusComponent {\n id: string;\n domainId: string;\n state: string;\n version: string | null;\n lastCheckAt: string | null;\n checks: StatusCheck[];\n}\n\nexport interface StatusCheck {\n name: string;\n state: string;\n category: string | null;\n}\n\nexport interface StatusIncident {\n id: string;\n severity: string;\n startedAt: string | null;\n resolvedAt: string | null;\n affectedDomains: string[];\n summary: string;\n updates: StatusIncidentUpdate[];\n}\n\nexport interface StatusIncidentUpdate {\n at: string;\n status: string;\n message: string;\n}\n\nexport interface StatusVersion {\n platformVersion: string;\n frontendMinVersion: string;\n}\n\nexport function createStatusService() {\n const config = loadConfig();\n const endpoint = resolveEndpoint(config);\n\n async function fetchJson<T>(path: string): Promise<T> {\n const url = `${endpoint}/status/v1${path}`;\n const response = await fetch(url, {\n headers: { 'Accept': 'application/json' },\n });\n if (!response.ok) {\n throw new Error(`Status API error: HTTP ${response.status} from ${url}`);\n }\n return response.json() as Promise<T>;\n }\n\n return {\n getSummary: () => fetchJson<StatusSummary>('/summary'),\n getComponents: () => fetchJson<StatusComponent[]>('/components'),\n getIncidents: (window = '24h') => fetchJson<StatusIncident[]>(`/incidents?window=${window}`),\n getVersion: () => fetchJson<StatusVersion>('/version'),\n };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createStatusService } from '../../client/services/status.js';\nimport { EXIT_USAGE, handleError } from '../../util/errors.js';\nimport { type OutputFormat, format } from '../../output/formatter.js';\nimport { failure, hint } from '../../output/messages.js';\nimport { formatInstant, renderState } from '../../output/values.js';\n\nfunction stateSymbol(state: string): string {\n switch (state) {\n case 'UP': return chalk.green('●');\n case 'DEGRADED': return chalk.yellow('●');\n case 'DOWN': return chalk.red('●');\n default: return chalk.gray('○');\n }\n}\n\nexport function registerComponentCommand(parent: Command): void {\n parent\n .command('component <id>')\n .description('Show detailed status of a specific component')\n .action(async (id: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? 'human';\n const status = createStatusService();\n\n const components = await status.getComponents();\n const wanted = id.toLowerCase();\n const match = components.find((c) => {\n const cid = c.id.toLowerCase();\n // `storage`, `storage-service` and `Storage Service` all address the same component;\n // insisting on the exact wire id made the summary's own labels unusable here.\n return cid === wanted\n || cid === `${wanted}-service`\n || cid.replace(/-service$/, '') === wanted.replace(/[\\s-]*service$/, '').replace(/\\s+/g, '-');\n });\n\n if (!match) {\n failure(`No component called \"${id}\".`);\n hint(`Available: ${components.map(c => c.id).join(', ')}`);\n process.exit(EXIT_USAGE);\n }\n\n if (outputFormat !== 'human') {\n format(match, { format: outputFormat });\n return;\n }\n\n console.log();\n console.log(` ${stateSymbol(match.state)} ${chalk.bold(match.id)} ${match.version ? chalk.dim('v' + match.version) : ''}`);\n console.log(` State: ${renderState(match.state)}`);\n if (match.lastCheckAt) {\n console.log(` Last check: ${formatInstant(match.lastCheckAt)}`);\n }\n\n if (match.checks.length > 0) {\n console.log();\n console.log(' Checks:');\n for (const check of match.checks) {\n const cat = check.category ? chalk.dim(` (${check.category})`) : '';\n console.log(` ${stateSymbol(check.state)} ${check.name}${cat}`);\n }\n }\n console.log();\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { createStatusService } from '../../client/services/status.js';\nimport { handleError } from '../../util/errors.js';\nimport { type OutputFormat, format } from '../../output/formatter.js';\n\nconst SEVERITY_COLORS: Record<string, (s: string) => string> = {\n ERROR: chalk.red,\n WARNING: chalk.yellow,\n INFO: chalk.blue,\n MAINTENANCE: chalk.cyan,\n};\n\nexport function registerIncidentsCommand(parent: Command): void {\n parent\n .command('incidents')\n .description('List recent incidents')\n .option('-w, --window <window>', 'Time window (e.g. 24h, 48h)', '24h')\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? 'human';\n const status = createStatusService();\n\n const incidents = await status.getIncidents(options.window);\n\n if (outputFormat !== 'human') {\n format(incidents, { format: outputFormat });\n return;\n }\n\n if (incidents.length === 0) {\n console.log(chalk.dim(`\\n No incidents in the last ${options.window}.\\n`));\n return;\n }\n\n console.log();\n for (const incident of incidents) {\n const color = SEVERITY_COLORS[incident.severity] ?? chalk.gray;\n const severity = color(incident.severity.padEnd(8));\n const time = incident.startedAt ? new Date(incident.startedAt).toLocaleString() : '';\n const resolved = incident.resolvedAt ? chalk.green(' [resolved]') : chalk.yellow(' [open]');\n console.log(` ${severity} ${incident.summary}${resolved}`);\n console.log(chalk.dim(` ${time}`));\n\n for (const update of incident.updates) {\n const updateTime = new Date(update.at).toLocaleTimeString();\n console.log(chalk.dim(` ${updateTime} ${update.status} ${update.message}`));\n }\n console.log();\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport { registerSummaryCommand } from './summary.js';\nimport { registerComponentCommand } from './component.js';\nimport { registerIncidentsCommand } from './incidents.js';\n\nexport function registerStatusCommands(program: Command): void {\n const status = program\n .command('status')\n .description('Platform health and status')\n .addHelpText('after', `\nExamples:\n $ diafunc status summary everything, at a glance\n $ diafunc status component storage one service in detail\n $ diafunc status incidents --window 168h\n`);;\n\n registerSummaryCommand(status);\n registerComponentCommand(status);\n registerIncidentsCommand(status);\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient, type ApiClient } from '../../client/api.js';\nimport { ApiError } from '../../client/errors.js';\nimport { isDryRun } from '../../client/http.js';\nimport { isAuthenticationFailure } from '../../client/sign-in.js';\nimport { CliError, EXIT_FAILURE, EXIT_USAGE, handleError, usageError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { hiddenOptionAlias } from '../../util/hidden-aliases.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { Status, withStatus } from '../../output/progress.js';\nimport { formatDurationPrecise } from '../../output/values.js';\nimport { detail, empty, failure, heading, hint, success, warn } from '../../output/messages.js';\nimport { renderWatchBlock } from './watch-view.js';\nimport {\n STARTING_DEPTH_RULE,\n depthLabel,\n depthOf,\n findDepth,\n explainMissingRunFields,\n missingRunFields,\n promptCreationFields,\n promptRunFields,\n summaryLines,\n suppliedFromAnalysis,\n type Depth,\n type DepthPreset,\n type RunPromptInput,\n} from './wizard.js';\nimport {\n PromptCanceled,\n canPrompt,\n createInquirerPrompter,\n whyNoPrompt,\n type Prompter,\n} from '../../prompting/prompter.js';\nimport {\n cancelSentence,\n importingLabel,\n isImporting,\n latestRunSentence,\n verdictLabel,\n verdictSentence,\n runCredits,\n runPhaseCell,\n terminalSentence,\n} from './copy.js';\nimport { queueRun, sendData, stopImport, type DataAnswer, type ImportContext } from './data-import.js';\nimport { isInteractive } from '../../output/terminal.js';\nimport { analysisDetails } from './details.js';\nimport { EXPORT_LANGUAGES, EXPORT_MODEL_HELP, REPORT_HELP, printModelExport, printReport } from './report.js';\nimport { reshapeSingle, sourcesAsUploaded, uploadSeveral, type StackChoices } from './sources.js';\nimport {\n checkNotesLength,\n checkedStatement,\n expectationLines,\n focusOf,\n focusText,\n intentRecipeLines,\n interpretRequestOf,\n MAX_FOCUS,\n MAX_INTENT_LENGTH,\n MAX_PAIRS,\n notesFromOptions,\n pairsOf,\n pairText,\n parseShapeFlag,\n printInterpretation,\n printUnavailable,\n promptIntentDecisions,\n readNotes,\n resolvePairs,\n resolveShapeTargets,\n shapesOf,\n whenProfiled,\n FOCUS_FAMILIES,\n} from './intent.js';\n\nimport {\n collectColumns,\n occurrences,\n resolveColumnArgument,\n resolveColumnArguments,\n resolveColumnNames,\n} from './columns.js';\nimport type { Visibility } from '../../client/types/admin.js';\nimport type {\n AnalysisColumn,\n AnalysisPreset,\n AnalysisResponse,\n AnalysisRun,\n AnalysisRunState,\n AnalysisTrigger,\n AnalysisTriggerKind,\n UpdateAnalysisTriggerRequest,\n CreateAnalysisRequest,\n IntentDecision,\n IntentFields,\n IntentItemState,\n RequestedPair,\n} from '../../client/types/analysis.js';\n\n// ---------- helpers ----------\n\n/** How often the run row is re-read while watching. */\nconst POLL_INTERVAL_MS = 2000;\n\n/** Polls in a row that find no run before the watch gives up: a run that does not exist never will. */\nconst MISSING_RUN_POLLS = 5;\n\n/** How hard the wizard tries to read the uploaded table's header before it asks for typed names. */\nconst COLUMN_READ_ATTEMPTS = 3;\nconst COLUMN_READ_INTERVAL_MS = 1000;\n\nfunction openUrl(url: string): void {\n const cmd = process.platform === 'darwin' ? 'open'\n : process.platform === 'win32' ? 'cmd'\n : 'xdg-open';\n const args = process.platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url];\n spawn(cmd, args, { detached: true, stdio: 'ignore' }).unref();\n}\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/** The program's global `--no-interactive`. */\nfunction noInteractiveFlag(cmd: Command): boolean {\n return (cmd.optsWithGlobals() as { interactive?: boolean }).interactive === false;\n}\n\n/**\n * How the commands that send data deal with an import that outlasts the upload. The wait is a line\n * that redraws only for a person at a terminal; `--no-interactive`, a pipe and a machine format get\n * plain lines.\n */\nfunction importContext(\n api: ApiClient,\n analysisId: string,\n cmd: Command,\n machineReport: ImportContext['machineReport'],\n): ImportContext {\n const outputFormat = getOutputFormat(cmd);\n const noInteractive = noInteractiveFlag(cmd);\n return {\n api,\n analysisId,\n outputFormat,\n live: outputFormat === 'human' && !noInteractive && isInteractive(),\n prompter: canPrompt(outputFormat, noInteractive) ? createInquirerPrompter() : null,\n machineReport,\n };\n}\n\n/** Collects a repeatable `--question`. */\nfunction collectQuestion(value: string, previous: string[] = []): string[] {\n return previous.concat([value]);\n}\n\n/**\n * The questions as given, one per entry: trimmed, blanks dropped, and never split. A question is free\n * text (\"Which ratios matter, and which hardly at all?\"), so a comma inside it is part of it.\n */\nexport function questionsOf(given: string[] | undefined): string[] | null {\n if (given === undefined) return null;\n return given.map((question) => question.trim()).filter((question) => question.length > 0);\n}\n\nfunction parseVisibility(value: string): Visibility {\n const upper = value.toUpperCase();\n if (upper !== 'PRIVATE' && upper !== 'PUBLIC') {\n throw new Error(`Invalid visibility \"${value}\". Use PRIVATE or PUBLIC.`);\n }\n return upper as Visibility;\n}\n\nfunction isTerminalState(state: AnalysisRunState): boolean {\n return state === 'COMPLETED' || state === 'FAILED' || state === 'CANCELLED';\n}\n\n/**\n * The part of a depth the command line or a saved preset named, as the fields of a creation.\n *\n * A value that was not named is left out of the request, not sent empty: the platform then gives\n * the analysis the account's starting depth and answers with what it stored.\n */\nfunction namedDepth(options: { hours?: string; budget?: string }): Pick<CreateAnalysisRequest, 'hours' | 'budget'> {\n const depth: Pick<CreateAnalysisRequest, 'hours' | 'budget'> = {};\n if (options.hours?.trim()) depth.hours = options.hours.trim();\n if (options.budget?.trim()) depth.budget = options.budget.trim();\n return depth;\n}\n\n/**\n * What the figures of a run and of a finished analysis mean, in the words of the glossary\n * (`/documentation/glossary`), for the commands that print them.\n */\nconst REPORT_TERMS_HELP = `\nTerms:\n Quality How well the model predicts on held-out rows, marked down for the size of its\n formula. 0% is no better than always predicting the average, 100% is exact.\n While a search runs, the same measure on the training rows.\n Error How far the predictions lie from the held-out values, as a share of the miss of\n always predicting the average. 0% is exact.\n Complexity How long the formula is. A bound limits the formulas the search may return.\n Generation One round of the search: candidates are varied, measured and selected.\n\n Every term: https://diafunc.com/documentation/glossary\n`;\n\n/** The analysis's time limit as a number of hours, or null when it is not a number. */\nfunction budgetHoursOf(hours: string | null | undefined): number | null {\n if (hours === null || hours === undefined) return null;\n const parsed = Number(hours);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction multipartFromFile(file: string): FormData {\n const buffer = fs.readFileSync(file);\n const blob = new Blob([buffer]);\n const formData = new FormData();\n formData.append('content', blob, path.basename(file));\n return formData;\n}\n\n/**\n * `handleError`, except for the reader stopping a prompt: that is not an error, and the program\n * reports it once, for every command, where `parseAsync` is awaited.\n */\nfunction reportCommandError(error: unknown): never {\n if (error instanceof PromptCanceled) throw error;\n handleError(error);\n}\n\nconst DEPTH_HELP = 'A step of the depth ladder, by name or credits (for example standard, deep or 32000); '\n + 'not together with --hours and --budget';\n\n// ---------- subcommand: <file> (default: create + upload + run) ----------\n\ninterface RunOptions {\n name?: string;\n description?: string;\n visibility?: string;\n license?: string;\n /** `--depth`: a step of the ladder by name or credits; resolved into `hours` and `budget`. */\n depth?: string;\n hours?: string;\n budget?: string;\n /** One entry per `--targets`, as typed: read against the file's columns once it is uploaded. */\n targets?: string[];\n /** One entry per `--question`; a question is free text and may hold commas. */\n question?: string[];\n segment?: string;\n introduction?: string;\n /** A saved preset applied as defaults; explicit flags override it. */\n preset?: string;\n /** Commander's negated flag: false when `--no-file-column` was passed. */\n fileColumn?: boolean;\n keepDuplicates?: boolean;\n rowsOf?: string;\n /** `--as-uploaded`: true for every file, or the files named. */\n asUploaded?: true | string[];\n /** `--intent` / `--intent-file`: the owner's notes, private to them. */\n intent?: string;\n intentFile?: string;\n /** One entry per `--shape <target>=<statement>`. */\n shape?: string[];\n /** One entry per `--pair <first>,<second>[,<kind>]`. */\n pair?: string[];\n /** One entry per `--focus <family>`. */\n focus?: string[];\n}\n\n/** What `--intent`, `--shape`, `--pair` and `--focus` give, read and checked before anything is created. */\ninterface LaunchIntent {\n notes: string | undefined;\n shapes: Record<string, string[]> | null;\n pairs: RequestedPair[] | null;\n focus: string[] | null;\n}\n\nfunction launchIntentOf(options: { intent?: string; intentFile?: string; shape?: string[]; pair?: string[]; focus?: string[] }): LaunchIntent {\n return {\n notes: notesFromOptions(options),\n shapes: shapesOf(options.shape),\n pairs: pairsOf(options.pair),\n focus: focusOf(options.focus),\n };\n}\n\n/**\n * The part of a launch the creation carries: the notes and the focus, which name no column. The\n * expectations and the charts name columns, so `analyze <file>` saves them once the data is in.\n */\nfunction creationIntent(launch: LaunchIntent): IntentFields {\n const fields: IntentFields = {};\n if (launch.notes) fields.intent = launch.notes;\n if (launch.focus && launch.focus.length > 0) fields.focusFamilies = launch.focus;\n return fields;\n}\n\n/**\n * Saves the expectations and the charts the command line gave, read against the uploaded columns.\n * The expectations wait for the data's profile, which binds a window left open to the observed range.\n * A refusal stops the command with how to pick the analysis up, since by now it exists and holds the data.\n */\nasync function saveLaunchFields(api: ApiClient, analysisId: string, columns: AnalysisColumn[], launch: LaunchIntent): Promise<void> {\n const names = columns.map((c) => c.name).filter((name) => name && name.length > 0);\n const pickUp = (what: string, command: string) => (error: unknown): never => {\n const message = error instanceof ApiError ? error.toUserMessage() : error instanceof Error ? error.message : String(error);\n throw new CliError(message, {\n exitCode: error instanceof CliError ? error.exitCode : EXIT_FAILURE,\n hint: [\n error instanceof CliError ? error.hint : undefined,\n `Analysis ${analysisId} is created and holds the data. Set the ${what} with '${command}'`\n + ` and start it with 'diafunc analyze rerun ${analysisId}'.`,\n ].filter(Boolean).join('\\n '),\n });\n };\n if (launch.shapes) {\n try {\n const byTarget = resolveShapeTargets(launch.shapes, names, analysisId);\n await withStatus('Saving the expectations', () => whenProfiled(\n () => api.analysis.patchShapeExpectations(analysisId, { byTarget })));\n } catch (error) {\n pickUp('expectations', `diafunc analyze expectations ${analysisId} --target <target> <statement...>`)(error);\n }\n }\n if (launch.pairs && launch.pairs.length > 0) {\n try {\n const pairs = resolvePairs(launch.pairs, names, analysisId);\n await withStatus('Saving the charts', () => api.analysis.patchRequestedPairs(analysisId, { pairs }));\n } catch (error) {\n pickUp('charts', `diafunc analyze charts ${analysisId} <first>,<second>[,<kind>]...`)(error);\n }\n }\n}\n\n/**\n * Reads the notes without asking anything: the proposals are printed, nothing is confirmed, and the\n * hint names the command that confirms them. Off a terminal the run goes on; it reads the recipe,\n * which no unconfirmed proposal is part of.\n */\nasync function readNotesUnattended(api: ApiClient, analysis: AnalysisResponse, notes: string, outputFormat: OutputFormat): Promise<void> {\n const reading = () => readNotes(api, analysis.analysisId, interpretRequestOf(analysis, notes));\n const interpretation = outputFormat === 'human' ? await withStatus('Reading your notes', reading) : await reading();\n if (outputFormat !== 'human') {\n process.stdout.write(JSON.stringify({ type: 'intent', ...interpretation }) + '\\n');\n return;\n }\n printInterpretation(interpretation, analysis.analysisId);\n console.log();\n}\n\n/**\n * Create, upload, configure and run: the whole automatic analysis in one command.\n *\n * The order is forced by the data: `targets` is required to run and its legal values are the\n * uploaded file's column names, so the analysis has to exist and hold the data before the question\n * can be asked. In a terminal the reader is asked; off one the command refuses before creating\n * anything, rather than leaving a configured-but-unrunnable analysis behind.\n */\nasync function runAnalysis(files: string[], options: RunOptions, cmd: Command): Promise<void> {\n for (const candidate of files) {\n if (!fs.existsSync(candidate)) {\n failure(`File not found: ${candidate}`);\n process.exit(EXIT_FAILURE);\n }\n }\n const file = files[0];\n\n const outputFormat = getOutputFormat(cmd);\n const noInteractive = noInteractiveFlag(cmd);\n const interactive = canPrompt(outputFormat, noInteractive);\n // Read before anything is created: a typing mistake in them must not leave an analysis behind.\n const launch = launchIntentOf(options);\n const api = createApiClient();\n // `--depth` is resolved before a preset is applied: a flag typed for this run wins over a saved default.\n applyDepthOption(options, options.depth === undefined ? [] : await readDepths(api));\n\n // A preset's targets are column names already, so they are kept apart from what `--targets` typed.\n let presetTargets: string[] | undefined;\n\n // CL6: load preset and apply as defaults before anything else\n if (options.preset) {\n const opt = await api.analysis.getPreset(options.preset);\n if (!opt.preset) {\n failure(`Preset not found: ${options.preset}`);\n hint(`List your presets with 'diafunc analyze presets list'.`);\n process.exit(EXIT_FAILURE);\n }\n const p = opt.preset;\n if (options.targets === undefined && p.targets.length > 0) presetTargets = p.targets;\n if (options.question === undefined && p.questions.length > 0) options.question = [...p.questions];\n if (options.segment === undefined && p.segmentKey) options.segment = p.segmentKey;\n if (options.hours === undefined && p.time?.trim()) options.hours = p.time;\n if (options.budget === undefined && p.budget?.trim()) options.budget = p.budget;\n }\n\n const typedTargets = occurrences(options.targets)?.filter((entry) => entry.trim().length > 0);\n const targetsGiven = (typedTargets?.length ?? 0) > 0 || (presetTargets?.length ?? 0) > 0;\n if (!interactive && !targetsGiven) {\n // Refuse now. Creating the analysis and uploading the file first would only move this failure\n // past the two steps that leave state behind.\n usageError(\n `Target columns are required, and ${whyNoPrompt(outputFormat, noInteractive)}.`,\n `Pass --targets <columns> or --preset <id>. The names are the column headers of ${files.length > 1 ? 'the files' : path.basename(file)}.`,\n );\n }\n\n const prompter = createInquirerPrompter();\n const fallbackName = path.basename(file, path.extname(file));\n const creation = interactive\n ? await promptCreationFields(prompter, {\n name: options.name,\n description: options.description,\n visibility: options.visibility === undefined ? undefined : parseVisibility(options.visibility),\n licenceId: options.license,\n }, fallbackName, () => api.admin.listLicenses())\n : {\n name: options.name ?? fallbackName,\n description: options.description?.trim() || null,\n visibility: options.visibility === undefined ? ('PRIVATE' as Visibility) : parseVisibility(options.visibility),\n licenceId: options.license,\n };\n\n const request: CreateAnalysisRequest = {\n name: creation.name,\n description: creation.description,\n visibility: creation.visibility,\n introduction: options.introduction ?? null,\n ...namedDepth(options),\n // The targets and the segment are column names, and the columns exist only once the file is\n // uploaded. They are set below, read against the real header.\n targets: null,\n questions: questionsOf(options.question),\n segment: null,\n };\n\n // The license belongs to the project the creation provisions; it is sent with the creation only,\n // and not with the later saves of the recipe.\n const created = await withStatus(`Creating analysis \"${creation.name}\"`, () => api.analysis.create({\n ...request,\n ...creationIntent(launch),\n ...(creation.licenceId ? { licenceId: creation.licenceId } : {}),\n }));\n if (isDryRun()) {\n hint(`Dry run: nothing was created. A real run would upload ${path.basename(file)}, queue the analysis and follow it.`);\n return;\n }\n detail(`analysisId: ${created.analysisId}`);\n\n // From here on the depth is the one the analysis holds: what was named, or what the platform\n // gave it. Every later write carries it, so a save of the other settings never clears it.\n const stored = depthOf(created.hours, created.budget);\n const recipe: CreateAnalysisRequest = { ...request, hours: created.hours, budget: created.budget };\n if (!interactive) {\n if (!stored) {\n // A platform that predates the starting depth stores none, and would refuse the run.\n throw new CliError(\n `The platform gave analysis ${created.analysisId} no depth, and ${whyNoPrompt(outputFormat, noInteractive)}.`,\n {\n exitCode: EXIT_USAGE,\n hint: `Pass --hours and --budget. Analysis ${created.analysisId} is created and holds no data yet; `\n + `remove it with 'diafunc analyze delete ${created.analysisId}'.`,\n },\n );\n }\n detail(`depth: ${depthLabel(stored, await readDepths(api))}${created.depthPreselection ? \" (the account's starting depth)\" : ''}`);\n }\n\n // An import that outlasts the upload is followed to its end here, so everything below reads a\n // table that is complete.\n await sendData<DataAnswer>(importContext(api, created.analysisId, cmd, 'stream'), () => files.length > 1\n ? uploadSeveral(api, created.analysisId, files, stackChoices(options, files), outputFormat === 'human')\n : uploadOne(api, created.analysisId, file, asUploadedOf(options.asUploaded, files), outputFormat === 'human'));\n\n const columns = await readColumns(api, created.analysisId);\n const named = namedColumns(created.analysisId, columns, interactive,\n { typedTargets, presetTargets, segment: options.segment });\n\n let runHours: string | null | undefined = created.hours;\n if (interactive) {\n const configuredHours = await configureInteractively(api, prompter, created.analysisId, recipe, {\n targets: named.targets,\n segment: named.segment,\n questions: options.question === undefined ? undefined : questionsOf(options.question),\n intent: launch.notes === undefined ? undefined : launch.notes || null,\n hours: options.hours,\n budget: options.budget,\n }, columns, creation.licenceId, { launch, storedNotes: launch.notes || null });\n if (configuredHours === null) return;\n runHours = configuredHours;\n } else {\n const saved = await withStatus('Saving the analysis settings', () => api.analysis.update(created.analysisId, {\n ...recipe,\n targets: named.targets ?? null,\n segment: named.segment ?? null,\n }));\n await saveLaunchFields(api, created.analysisId, columns, launch);\n if (launch.notes) {\n await readNotesUnattended(api, { ...created, ...saved, analysisId: created.analysisId }, launch.notes, outputFormat);\n if (outputFormat === 'human') hint(`Confirmed proposals take part from the next run: 'diafunc analyze rerun ${created.analysisId}'.`);\n }\n }\n\n const run = await withStatus('Queuing analysis run', () => queueRun(api, created.analysisId));\n detail(`runId: ${run.runId}`);\n console.log();\n\n await monitorRun(api, created.analysisId, run.runId, budgetHoursOf(runHours), cmd);\n}\n\n/**\n * The targets and the segment the command line named, as columns of the uploaded file.\n *\n * A name that is not a column stops a run that cannot ask, saying what the columns are and how to\n * pick the analysis back up, since by now it exists and holds the data. In a terminal the name is\n * reported and left unanswered instead, so the wizard asks for it from the real columns.\n */\nfunction namedColumns(\n analysisId: string,\n columns: AnalysisColumn[],\n interactive: boolean,\n given: { typedTargets?: string[]; presetTargets?: string[]; segment?: string },\n): { targets?: string[]; segment?: string } {\n const names = columns.map((c) => c.name).filter((name) => name && name.length > 0);\n const read = <T>(resolve: () => T): T | undefined => {\n try {\n return resolve();\n } catch (error) {\n if (!(error instanceof CliError)) throw error;\n if (!interactive) {\n throw new CliError(error.message, {\n exitCode: error.exitCode,\n hint: [\n error.hint,\n `Analysis ${analysisId} is created and holds the data. Name the columns with 'diafunc analyze targets ${analysisId} <column...>'`\n + ` and start it with 'diafunc analyze rerun ${analysisId}'.`,\n ].filter(Boolean).join('\\n '),\n });\n }\n warn(error.message);\n return undefined;\n }\n };\n const targets = given.typedTargets && given.typedTargets.length > 0\n ? read(() => resolveColumnArguments(given.typedTargets!, names, analysisId))\n : given.presetTargets && given.presetTargets.length > 0\n ? read(() => resolveColumnNames(given.presetTargets!, names, analysisId))\n : undefined;\n const segment = given.segment === undefined || given.segment === ''\n ? undefined\n : read(() => resolveColumnArgument(given.segment!, names, analysisId));\n return { targets, segment };\n}\n\n/**\n * Asks what the run still needs and saves it onto the analysis.\n *\n * Shared by a fresh `analyze <file>` and by `rerun` on an analysis that was never fully configured.\n * `recipe` is the analysis as it stands; the answers are laid over it, and the result replaces it.\n *\n * Returns the time limit (hours) it saved, or null when the reader declined to start, having\n * already told them how to pick the analysis back up: it exists and is configured, so the answer is\n * a `rerun`, not a fresh upload.\n */\nasync function configureInteractively(\n api: ApiClient,\n prompter: Prompter,\n analysisId: string,\n recipe: CreateAnalysisRequest,\n supplied: RunPromptInput['supplied'],\n knownColumns?: AnalysisColumn[],\n licenceId?: string,\n fromCommandLine?: { launch: LaunchIntent; storedNotes: string | null },\n): Promise<string | null> {\n const columns = knownColumns ?? await readColumns(api, analysisId);\n const presets = await readPresets(api);\n const depthAsked = supplied.hours === undefined || supplied.budget === undefined;\n const depthDefault = depthAsked ? await readDepthDefault(api, recipe) : null;\n const depths = await readDepths(api);\n console.log();\n\n const answers = await promptRunFields(prompter, { columns, presets, supplied, depthDefault, depths });\n\n console.log();\n // Saved before the confirmation, not after it. Declining leaves a complete, runnable analysis,\n // so the `rerun` this offers below is a command that works rather than one that comes back\n // asking for the targets that were just chosen.\n const saved = await withStatus('Saving the analysis settings', () => api.analysis.update(analysisId, {\n ...recipe,\n targets: answers.targets,\n questions: answers.questions,\n segment: answers.segment,\n hours: answers.hours,\n budget: answers.budget,\n }));\n const recipeNow = await settleNotes(api, prompter, analysisId, saved, columns, answers.intent,\n fromCommandLine ?? { launch: null, storedNotes: supplied.intent ?? null },\n { targets: answers.targets, segment: answers.segment });\n\n console.log();\n heading('Ready to run');\n const identity = {\n name: recipe.name,\n description: recipe.description ?? null,\n visibility: recipe.visibility ?? ('PRIVATE' as Visibility),\n ...(licenceId ? { licenceId } : {}),\n };\n // The depth shown is the one the platform stored, which is what the run will use.\n const depth = depthOf(saved?.hours, saved?.budget) ?? { hours: answers.hours, budget: answers.budget };\n for (const line of summaryLines(identity, { ...answers, ...depth }, depths)) detail(line);\n for (const line of intentRecipeLines(recipeNow ?? {})) detail(line);\n console.log();\n\n if (!await prompter.confirm({ message: 'Start the analysis?', default: true })) {\n warn('Not started. The analysis and these settings are saved.');\n hint(`Start it later with 'diafunc analyze rerun ${analysisId}'.`);\n return null;\n }\n return depth.hours;\n}\n\n/**\n * The wizard's step for the notes, after the settings are saved: the expectations and charts the\n * command line gave are saved, the notes are stored when they are new, read into proposals, and each\n * proposal still open is asked about (`promptIntentDecisions`). Returns the analysis as it then\n * stands, for the summary, or what was saved when nothing about the notes changed.\n */\nasync function settleNotes(\n api: ApiClient,\n prompter: Prompter,\n analysisId: string,\n saved: AnalysisResponse,\n columns: AnalysisColumn[],\n notes: string | null,\n given: { launch: LaunchIntent | null; storedNotes: string | null },\n setup: { targets: string[]; segment: string | null },\n): Promise<AnalysisResponse> {\n let touched = false;\n if (given.launch && (given.launch.shapes || (given.launch.pairs?.length ?? 0) > 0)) {\n await saveLaunchFields(api, analysisId, columns, given.launch);\n touched = true;\n }\n if (notes && notes !== given.storedNotes) {\n await withStatus('Saving your notes', () => api.analysis.patchIntent(analysisId, { intent: notes }));\n }\n if (notes && !isDryRun()) {\n const base = { ...saved, analysisId, targets: saved?.targets ?? setup.targets, segment: saved?.segment ?? setup.segment };\n const interpretation = await withStatus('Reading your notes', () => readNotes(api, analysisId, interpretRequestOf(base, notes)));\n if (interpretation.status !== 'READY') {\n printInterpretation(interpretation, analysisId);\n } else {\n printUnavailable(interpretation);\n for (const note of [...interpretation.notUnderstood ?? [], ...interpretation.rejections ?? []]) {\n warn(`Not used: \"${note.quote}\"${note.reason ? `: ${note.reason}` : ''}`);\n }\n const decisions = await promptIntentDecisions(prompter, interpretation);\n if (decisions.length > 0) {\n await withStatus('Saving your decisions', () => api.analysis.decideIntentItems(analysisId, { decisions }));\n touched = true;\n }\n }\n }\n if (!touched || isDryRun()) return saved;\n try {\n return (await api.analysis.get(analysisId)).analysis ?? saved;\n } catch (error) {\n if (isAuthenticationFailure(error)) throw error;\n return saved;\n }\n}\n\n/** The depth ladder as the platform serves it; empty when it cannot be read, so nothing depends on it. */\nexport async function readDepths(api: Pick<ApiClient, 'analysis'>): Promise<DepthPreset[]> {\n try {\n return (await api.analysis.getDepths()) ?? [];\n } catch {\n return [];\n }\n}\n\n/**\n * Turns `--depth <name or credits>` into the hours and credits of its step. A depth and a pair of its own\n * cannot both be named; a name the ladder does not have is refused with the names it has.\n */\nexport function applyDepthOption(\n options: { depth?: string; hours?: string; budget?: string },\n depths: readonly DepthPreset[],\n): void {\n if (options.depth === undefined) return;\n if (options.hours !== undefined || options.budget !== undefined) {\n usageError('Name a depth with --depth, or a time limit and a credit budget with --hours and --budget, not both.');\n }\n if (depths.length === 0) {\n usageError('The depths could not be read from the platform.', 'Pass --hours and --budget instead.');\n }\n const step = findDepth(depths, options.depth);\n if (!step) {\n usageError(`There is no depth '${options.depth}'.`,\n `Name one of ${depths.map((d) => d.name).join(', ')}, or its credits (for example --depth 4000).`);\n }\n options.hours = step.hours;\n options.budget = step.budget;\n}\n\n/**\n * The depth the depth prompt preselects: the one the platform would give this account's next\n * analysis.\n *\n * When the platform does not answer (one that predates the rule, or a failed read), the depth the\n * analysis itself holds is used, since the platform decided that one too. When it holds none,\n * nothing is preselected: the CLI has no starting depth of its own to offer in its place.\n */\nexport async function readDepthDefault(\n api: Pick<ApiClient, 'analysis'>,\n stored: { hours?: string | null; budget?: string | null },\n): Promise<Depth | null> {\n try {\n const answer = await api.analysis.getDepthDefault();\n const depth = depthOf(answer?.hours, answer?.budget);\n if (depth) return depth;\n } catch { /* the read is a convenience; the prompt works without it */ }\n return depthOf(stored.hours, stored.budget);\n}\n\n/**\n * Columns of the freshly uploaded table.\n *\n * An empty list is a legitimate answer for a moment after the upload, so this retries briefly\n * before giving up; the wizard falls back to typed target names rather than failing on it.\n */\nasync function readColumns(api: ApiClient, analysisId: string): Promise<AnalysisColumn[]> {\n for (let attempt = 0; attempt < COLUMN_READ_ATTEMPTS; attempt++) {\n if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, COLUMN_READ_INTERVAL_MS));\n try {\n const columns = await api.analysis.getColumns(analysisId);\n if (columns.length > 0) return columns;\n } catch (error) {\n if (isAuthenticationFailure(error)) throw error;\n /* the table is still being written; try again */\n }\n }\n warn('Could not read the column names from the uploaded file.');\n return [];\n}\n\n/** Saved presets, or none. A preset list is a convenience, so a failure to read it is not fatal. */\nasync function readPresets(api: ApiClient): Promise<AnalysisPreset[]> {\n try {\n return await api.analysis.getPresets();\n } catch {\n return [];\n }\n}\n\n/**\n * Follows a run to its terminal state.\n *\n * The display is driven by the run row, not by the output feed: the platform publishes `phase`\n * and `overallFraction` precisely so every surface reports the same figure, and the feed's `event`\n * rows are JSON envelopes meant for programmatic consumers rather than for reading.\n */\nasync function monitorRun(\n api: ApiClient,\n analysisId: string,\n runId: string,\n budgetHours: number | null,\n cmd: Command,\n): Promise<void> {\n const config = loadConfig();\n const outputFormat = getOutputFormat(cmd);\n const human = outputFormat === 'human';\n const status = new Status();\n // `info` rows mutate in place under a stable outputId, so the value is part of the key;\n // deduplicating on the id alone froze the caption at whatever it said first.\n const seenOutputs = new Set<string>();\n let caption: string | null = null;\n let lastReported = '';\n let missingPolls = 0;\n\n if (human) status.start();\n\n try {\n for (;;) {\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n\n let run: AnalysisRun | null = null;\n let absent = false;\n try {\n run = (await api.analysis.getRun(runId)).run;\n absent = run === null;\n } catch (error) {\n // Credentials the platform does not accept stay unaccepted however often they are sent,\n // and each further poll would count against the sign-in service's limit for this address.\n if (isAuthenticationFailure(error)) throw error;\n // A transient read failure should not end the watch; a run the platform does not know is not transient.\n absent = error instanceof ApiError && error.status === 404;\n }\n if (!run) {\n missingPolls = absent ? missingPolls + 1 : 0;\n if (missingPolls >= MISSING_RUN_POLLS) {\n status.stop();\n failure(`Run ${runId} was not found.`);\n hint(`List the runs with 'diafunc analyze runs ${analysisId}'.`);\n process.exit(EXIT_FAILURE);\n }\n continue;\n }\n missingPolls = 0;\n\n try {\n for (const out of await api.analysis.getRunOutputs(analysisId, runId)) {\n const key = `${out.outputId}:${out.output}`;\n if (seenOutputs.has(key)) continue;\n seenOutputs.add(key);\n if (out.type === 'event') {\n // Machine envelopes. In JSON mode they are the payload a script wants; in human mode\n // they are noise, and the same information is already on the run row.\n if (!human) process.stdout.write(JSON.stringify({ type: 'event', ...safeParse(out.output) }) + '\\n');\n } else {\n caption = out.output;\n if (!human) {\n process.stdout.write(JSON.stringify({ type: 'info', message: out.output }) + '\\n');\n }\n }\n }\n } catch (error) {\n if (isAuthenticationFailure(error)) throw error;\n /* the feed lags the run row; the run row is enough to keep rendering */\n }\n\n if (isTerminalState(run.state)) {\n status.stop();\n await reportTerminalRun(api, config, run, analysisId, runId, outputFormat);\n return;\n }\n\n const startedAt = run.startedAt ?? run.submittedAt ?? Date.now();\n if (human) {\n status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption, budgetHours }));\n } else {\n // One line per actual change, so a CI log records the shape of the run without repeating\n // an unchanged state every poll.\n const snapshot = JSON.stringify({\n type: 'progress',\n state: run.state,\n phase: run.phase,\n overallFraction: run.overallFraction,\n progressDone: run.progressDone,\n progressTotal: run.progressTotal,\n });\n if (snapshot !== lastReported) {\n lastReported = snapshot;\n process.stdout.write(snapshot + '\\n');\n }\n }\n }\n } finally {\n status.stop();\n }\n}\n\nfunction safeParse(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text) as unknown;\n return parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : { output: text };\n } catch {\n return { output: text };\n }\n}\n\n/**\n * Final report for a run that reached a terminal state. A run that failed or was canceled exits\n * non-zero, so `diafunc analyze ... && deploy` cannot proceed past a failed analysis.\n */\nasync function reportTerminalRun(\n api: ApiClient,\n config: ReturnType<typeof loadConfig>,\n run: AnalysisRun,\n analysisId: string,\n runId: string,\n outputFormat: OutputFormat,\n): Promise<void> {\n const baseStart = run.startedAt ?? run.submittedAt ?? Date.now();\n const durationMs = (run.endedAt ?? Date.now()) - baseStart;\n const credits = runCredits(run);\n\n if (outputFormat !== 'human') {\n format({\n status: run.state.toLowerCase(),\n runId,\n analysisId,\n durationMs,\n credits,\n validity: run.validity ?? null,\n error: run.errorMessage,\n }, { format: outputFormat });\n if (run.state !== 'COMPLETED') process.exit(EXIT_FAILURE);\n return;\n }\n\n console.log();\n const sentence = terminalSentence(run.state, formatDurationPrecise(durationMs), credits);\n if (run.state === 'COMPLETED') {\n success(sentence);\n const verdict = verdictSentence(run.validity);\n if (verdict) warn(verdict);\n await printNotebookLink(api, config, analysisId);\n return;\n }\n if (run.state === 'CANCELLED') {\n warn(sentence);\n process.exit(EXIT_FAILURE);\n }\n failure(sentence);\n if (run.errorMessage) hint(run.errorMessage);\n hint(`Queue a fresh run with 'diafunc analyze rerun ${analysisId}'.`);\n process.exit(EXIT_FAILURE);\n}\n\nasync function printNotebookLink(\n api: ApiClient,\n config: ReturnType<typeof loadConfig>,\n analysisId: string,\n): Promise<void> {\n try {\n const nav = await api.analysis.getNavigation(analysisId);\n const endpoint = config.profiles[config.currentProfile]?.endpoint ?? 'https://diafunc.com';\n detail(`${endpoint}${nav.labUrl}`);\n } catch { /* the notebook link is a convenience; its absence is not a failure */ }\n}\n\n// ---------- list / get ----------\n\nasync function listAnalyses(limit: number, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const analyses = await api.analysis.getRecent(limit);\n // Nulls are passed through rather than pre-substituted with a dash: the renderer knows how to\n // show an absent value, and off a TTY it emits an empty field instead of a character to strip.\n format(analyses.map((a) => ({\n analysisId: a.analysisId,\n name: a.name,\n visibility: a.visibility,\n hours: a.hours,\n budget: a.budget,\n targets: a.targets,\n // A reader sees the import where the run state would be: no run can start before the data is\n // in place. JSON keeps the state as it is and carries the import beside it.\n latestRunState: outputFormat !== 'json' && isImporting(a.dataImport) ? importingLabel(a.dataImport) : a.latestRunState,\n createdAt: a.createdAt,\n ...(outputFormat === 'json' && a.dataImport !== undefined ? { dataImport: a.dataImport } : {}),\n })), {\n format: outputFormat,\n columns: [\n { key: 'analysisId', kind: 'id' },\n { key: 'name', maxWidth: 40 },\n { key: 'visibility' },\n { key: 'hours' },\n { key: 'budget' },\n { key: 'targets' },\n { key: 'latestRunState', header: 'last run', kind: 'state' },\n { key: 'createdAt', header: 'created', kind: 'date' },\n ],\n });\n}\n\nasync function getAnalysisDetails(\n analysisId: string | undefined,\n options: { full?: boolean },\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const result = analysisId\n ? await api.analysis.get(analysisId)\n : await api.analysis.getLast();\n\n if (!result.analysis) {\n empty('analysis found');\n return;\n }\n\n if (outputFormat !== 'human') {\n format(result.analysis, { format: outputFormat });\n return;\n }\n\n // The introduction is a whole markdown document; the Boston Housing one runs to thirty lines\n // of prose and a column table. Printing it in full buries the eight fields a reader came for.\n const analysis = options.full\n ? result.analysis\n : {\n ...result.analysis,\n introduction: abbreviate(result.analysis.introduction),\n intent: abbreviate(result.analysis.intent ?? null),\n };\n const config = loadConfig();\n const endpoint = config.profiles[config.currentProfile]?.endpoint ?? 'https://diafunc.com';\n const details = analysisDetails(analysis, endpoint, await resultVerdict(api, result.analysis));\n format(details.data, { format: outputFormat, columns: details.columns });\n if (!options.full && isLong(result.analysis.introduction)) {\n hint('Introduction abbreviated. Pass --full to print it whole.');\n }\n if (!options.full && isLong(result.analysis.intent ?? null)) {\n hint(\"Your notes abbreviated. Pass --full, or run 'diafunc analyze intent \" + result.analysis.analysisId + \"', to print them whole.\");\n }\n}\n\n/**\n * The verdict of the run behind the analysis's result, from its newest runs, or null when that run is\n * not among them or they cannot be read: the verdict is a line of the details, not a reason to fail them.\n */\nasync function resultVerdict(api: ApiClient, analysis: AnalysisResponse): Promise<AnalysisRun | null> {\n if (!analysis.resultRunId) return null;\n try {\n const runs = await api.analysis.getRunsForAnalysis(analysis.analysisId, RESULT_RUN_LOOKBACK);\n return runs.find((r) => r.runId === analysis.resultRunId) ?? null;\n } catch (error) {\n if (isAuthenticationFailure(error)) throw error;\n return null;\n }\n}\n\n/** How many of an analysis's newest runs are searched for the one behind its result. */\nconst RESULT_RUN_LOOKBACK = 20;\n\nconst INTRODUCTION_PREVIEW_LINES = 3;\n\nfunction isLong(text: string | null): boolean {\n return Boolean(text && text.split('\\n').length > INTRODUCTION_PREVIEW_LINES);\n}\n\nfunction abbreviate(text: string | null): string | null {\n if (!isLong(text)) return text;\n const lines = (text as string).split('\\n').filter((l) => l.trim().length > 0);\n return `${lines.slice(0, INTRODUCTION_PREVIEW_LINES).join('\\n')}\\n…`;\n}\n\n// ---------- watch ----------\n\nasync function watchAnalysis(analysisId: string | undefined, cmd: Command): Promise<void> {\n const api = createApiClient();\n const result = analysisId\n ? await api.analysis.get(analysisId)\n : await api.analysis.getLast();\n\n if (!result.analysis) {\n empty('analysis found');\n return;\n }\n const analysis = result.analysis;\n\n const runs = await api.analysis.getRunsForAnalysis(analysis.analysisId, 1);\n if (runs.length === 0) {\n empty('runs for this analysis');\n return;\n }\n const latest = runs[0];\n\n if (isTerminalState(latest.state)) {\n // A finished run is reported by its outcome, not announced as a success regardless of it.\n const sentence = latestRunSentence(latest.state);\n if (latest.state === 'COMPLETED') {\n success(sentence);\n const verdict = verdictSentence(latest.validity);\n if (verdict) warn(verdict);\n } else {\n warn(sentence);\n if (latest.errorMessage) hint(latest.errorMessage);\n }\n await printNotebookLink(api, loadConfig(), analysis.analysisId);\n return;\n }\n\n console.log(`Watching run ${latest.runId} for analysis ${analysis.analysisId} ...`);\n await monitorRun(api, analysis.analysisId, latest.runId, budgetHoursOf(analysis.hours), cmd);\n}\n\n// ---------- rerun ----------\n\n/**\n * Queues a fresh run.\n *\n * An analysis made by `analyze create`, or edited field by field, can lack something the platform\n * requires to run. In a terminal the gaps are asked for, from the analysis's own columns, and\n * saved; off one the command names the command that fills each gap. A complete analysis is queued\n * without a question either way.\n */\nasync function rerunAnalysis(analysisId: string, cmd: Command): Promise<void> {\n const api = createApiClient();\n const found = await api.analysis.get(analysisId);\n if (!found.analysis) {\n failure(`Analysis not found: ${analysisId}`);\n process.exit(EXIT_FAILURE);\n }\n const analysis = found.analysis;\n\n const missing = missingRunFields(analysis);\n if (missing.length > 0) {\n const outputFormat = getOutputFormat(cmd);\n const noInteractive = noInteractiveFlag(cmd);\n if (!canPrompt(outputFormat, noInteractive)) {\n const { message, suggestion } = explainMissingRunFields(\n analysisId, missing, whyNoPrompt(outputFormat, noInteractive));\n usageError(message, suggestion);\n }\n const recipe: CreateAnalysisRequest = {\n name: analysis.name,\n description: analysis.description,\n visibility: analysis.visibility,\n introduction: analysis.introduction,\n hours: analysis.hours,\n budget: analysis.budget,\n targets: analysis.targets,\n questions: analysis.questions,\n segment: analysis.segment,\n };\n const configuredHours = await configureInteractively(\n api, createInquirerPrompter(), analysisId, recipe, suppliedFromAnalysis(analysis));\n if (configuredHours === null) return;\n }\n\n const run = await queueRun(api, analysisId);\n if (isDryRun()) {\n hint('Dry run: no run was queued.');\n return;\n }\n success(`Queued run ${run.runId} for analysis ${analysisId}.`);\n hint(`Follow it with 'diafunc analyze watch ${analysisId}'.`);\n}\n\n// ---------- open ----------\n\nasync function openAnalysis(analysisId: string | undefined): Promise<void> {\n const api = createApiClient();\n const result = analysisId\n ? await api.analysis.get(analysisId)\n : await api.analysis.getLast();\n\n if (!result.analysis) {\n empty('analysis found');\n return;\n }\n const config = loadConfig();\n const endpoint = config.profiles[config.currentProfile]?.endpoint ?? 'https://diafunc.com';\n try {\n const nav = await api.analysis.getNavigation(result.analysis.analysisId);\n const url = `${endpoint}${nav.labUrl}`;\n console.log(`Opening ${url} ...`);\n openUrl(url);\n } catch {\n hint('The notebook is not available yet. Run the analysis first.');\n }\n}\n\n// ---------- create (no data, no run) ----------\n\ninterface CreateOptions {\n name?: string;\n description?: string;\n visibility: string;\n license?: string;\n /** `--depth`: a step of the ladder by name or credits; resolved into `hours` and `budget`. */\n depth?: string;\n hours?: string;\n budget?: string;\n targets?: string[];\n question?: string[];\n segment?: string;\n introduction?: string;\n intent?: string;\n intentFile?: string;\n shape?: string[];\n pair?: string[];\n focus?: string[];\n}\n\n/**\n * Expectations for `analyze create`, which has no data yet: the window of a direction or a\n * curvature cannot be bound to an observed range there, so one has to be given.\n */\nfunction windowedShapes(shapes: Record<string, string[]> | null): Record<string, string[]> | null {\n if (!shapes) return null;\n for (const statement of Object.values(shapes).flat()) {\n const args = /\\((.*)\\)\\s*$/.exec(statement)?.[1].split(',') ?? [];\n if (!/range\\s*\\(/i.test(statement) && args.length !== 3) {\n usageError(`'${statement}' has no window, and an analysis without data has no observed range to bind it to.`,\n 'Give the window, for example increasing(size_m2, 20, 200), or set the expectation after the upload with '\n + \"'diafunc analyze expectations <id> --target <target> <statement...>'.\");\n }\n }\n return shapes;\n}\n\n/**\n * Column names typed before there is any data to read them against: each occurrence of the flag is\n * a list, where a double-quoted entry keeps its commas and spaces.\n */\nfunction typedColumns(given: string | string[] | undefined): string[] | null {\n const entries = occurrences(given);\n return entries === undefined ? null : resolveColumnArguments(entries, []);\n}\n\nasync function createAnalysis(options: CreateOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const launch = launchIntentOf(options);\n const shapes = windowedShapes(launch.shapes);\n const api = createApiClient();\n applyDepthOption(options, options.depth === undefined ? [] : await readDepths(api));\n const visibility = parseVisibility(options.visibility);\n const request: CreateAnalysisRequest = {\n name: options.name ?? 'CLI Analysis',\n description: options.description ?? null,\n visibility,\n introduction: options.introduction ?? null,\n ...namedDepth(options),\n targets: typedColumns(options.targets),\n questions: questionsOf(options.question),\n segment: options.segment ?? null,\n };\n const created = await api.analysis.create({\n ...request,\n ...creationIntent(launch),\n ...(shapes ? { shapeExpectations: shapes } : {}),\n ...(launch.pairs && launch.pairs.length > 0 ? { requestedPairs: launch.pairs } : {}),\n ...(options.license ? { licenceId: options.license } : {}),\n });\n if (isDryRun()) {\n hint('Dry run: nothing was created.');\n return;\n }\n format(created, { format: outputFormat });\n if (launch.notes && outputFormat === 'human') {\n hint(`Your notes are stored. Read them into proposals once the data is uploaded: 'diafunc analyze intent read ${created.analysisId}'.`);\n }\n}\n\n// ---------- delete ----------\n\nasync function deleteAnalysis(analysisId: string): Promise<void> {\n const api = createApiClient();\n await api.analysis.delete(analysisId);\n if (isDryRun()) {\n hint('Dry run: nothing was deleted.');\n return;\n }\n success(`Deleted analysis ${analysisId}.`);\n}\n\n// ---------- typed PATCH subcommands ----------\n\ntype PatchHandler = (api: ApiClient, analysisId: string, value: string) => Promise<AnalysisResponse>;\n\nasync function patchAndPrint(\n analysisId: string,\n value: string,\n handler: PatchHandler,\n successLabel: string,\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const updated = await handler(api, analysisId, value);\n if (isDryRun()) {\n hint('Dry run: nothing was changed.');\n return;\n }\n if (outputFormat === 'human') {\n success(`${successLabel} updated for analysis ${analysisId}.`);\n } else {\n format(updated, { format: outputFormat });\n }\n}\n\n/** The analysis's column names, or none when it holds no data yet. */\nasync function columnNames(api: ApiClient, analysisId: string): Promise<string[]> {\n return (await api.analysis.getColumns(analysisId)).map((c) => c.name).filter((name) => name && name.length > 0);\n}\n\n/**\n * Sets a recipe field that holds column names. What was typed is read against the analysis's own\n * columns first, so a name that is not one of them is refused here, with the columns listed, and\n * nothing is sent.\n */\nasync function patchColumns(\n analysisId: string,\n given: string | string[],\n send: (api: ApiClient, columns: string[]) => Promise<AnalysisResponse>,\n successLabel: string,\n cmd: Command,\n): Promise<void> {\n const api = createApiClient();\n const columns = resolveColumnArguments(occurrences(given) ?? [], await columnNames(api, analysisId), analysisId);\n await patchAndPrint(analysisId, '', () => send(api, columns), successLabel, cmd);\n}\n\n// ---------- the owner's notes, expectations, charts and focus ----------\n\n/** The analysis, or the command stops: these commands work on one the caller owns. */\nasync function ownAnalysis(api: ApiClient, analysisId: string): Promise<AnalysisResponse> {\n const found = await api.analysis.get(analysisId);\n if (!found.analysis) {\n failure(`Analysis not found: ${analysisId}`);\n process.exit(EXIT_FAILURE);\n }\n return found.analysis;\n}\n\n/**\n * `analyze intent <id> [text]`: shows the notes, or stores new ones (`--file` reads them from a file;\n * an empty text or `--clear` clears them). Storing does not read them; `intent read` does.\n */\nasync function notesCommand(\n analysisId: string,\n text: string | undefined,\n options: { file?: string; clear?: boolean },\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const given = [text !== undefined, options.file !== undefined, options.clear === true].filter(Boolean).length;\n if (given > 1) usageError('Give the notes as text, with --file, or clear them with --clear: one of the three.');\n if (given === 0) {\n const analysis = await ownAnalysis(api, analysisId);\n if (outputFormat !== 'human') {\n format({ analysisId, intent: analysis.intent ?? null }, { format: outputFormat });\n return;\n }\n if (!analysis.intent) {\n empty('notes');\n hint(`Write them with 'diafunc analyze intent ${analysisId} \"<text>\"'. Only you can read them.`);\n return;\n }\n console.log(analysis.intent);\n hint(`Only you can read these notes. Read them into proposals with 'diafunc analyze intent read ${analysisId}'.`);\n return;\n }\n let notes: string | null;\n if (options.clear) {\n notes = null;\n } else if (options.file !== undefined) {\n notes = notesFromOptions({ intentFile: options.file }) || null;\n } else {\n checkNotesLength(text as string);\n notes = (text as string).trim() || null;\n }\n const updated = await api.analysis.patchIntent(analysisId, { intent: notes });\n if (isDryRun()) {\n hint('Dry run: nothing was changed.');\n return;\n }\n if (outputFormat !== 'human') {\n format(updated, { format: outputFormat });\n return;\n }\n if (notes === null) {\n success(`Notes cleared for analysis ${analysisId}.`);\n hint('Proposals you confirmed earlier stay in place until you decline them.');\n return;\n }\n success(`Notes saved for analysis ${analysisId}. Only you can read them.`);\n hint(`Read them into proposals with 'diafunc analyze intent read ${analysisId}'. Nothing changes until you confirm one.`);\n}\n\n/** `analyze intent read <id>`: reads the stored notes against the analysis's setup and prints the proposals. */\nasync function readNotesCommand(analysisId: string, options: { force?: boolean; refine?: boolean }, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const analysis = await ownAnalysis(api, analysisId);\n if (!analysis.intent) {\n if (outputFormat !== 'human') {\n format({ status: 'EMPTY', hash: null, derivedAt: null, items: [], notUnderstood: [], rejections: [], findings: [] },\n { format: outputFormat });\n return;\n }\n empty('notes');\n hint(`Write them first with 'diafunc analyze intent ${analysisId} \"<text>\"'.`);\n return;\n }\n const reading = () => readNotes(api, analysisId,\n interpretRequestOf(analysis, analysis.intent as string), { force: options.force, refine: options.refine });\n // The status line goes to stdout, which off the human format carries the payload alone.\n const interpretation = outputFormat === 'human' ? await withStatus('Reading your notes', reading) : await reading();\n if (isDryRun()) {\n hint('Dry run: the notes were not read.');\n return;\n }\n if (outputFormat !== 'human') {\n format(interpretation, { format: outputFormat });\n return;\n }\n printInterpretation(interpretation, analysisId);\n}\n\n/**\n * `analyze intent confirm|decline|reset <id> <proposalId...>`: decides proposals of the stored\n * reading. A confirmed proposal is applied, a declined one is taken back out, a reset one is open\n * again. `--steer` / `--no-steer` switch whether a confirmed expectation also steers the model.\n */\nasync function decideCommand(\n state: IntentItemState,\n analysisId: string,\n ids: string[],\n options: { steer?: boolean },\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const wanted = [...new Set(ids.flatMap((id) => id.split(',')).map((id) => id.trim()).filter((id) => id.length > 0))];\n if (wanted.length === 0) usageError('Name at least one proposal.', `The ids are in 'diafunc analyze intent read ${analysisId}'.`);\n if (options.steer !== undefined && state !== 'CONFIRMED') {\n usageError('--steer and --no-steer go with confirm only.');\n }\n const api = createApiClient();\n const stored = await api.analysis.getIntentInterpretation(analysisId);\n const known = new Map((stored.items ?? []).map((item) => [item.id, item]));\n const unknown = wanted.filter((id) => !known.has(id));\n if (unknown.length > 0) {\n usageError(`${unknown.map((id) => `'${id}'`).join(', ')} ${unknown.length === 1 ? 'is not a proposal' : 'are not proposals'} of analysis ${analysisId}.`,\n `List the proposals with 'diafunc analyze intent read ${analysisId}'.`);\n }\n if (options.steer !== undefined) {\n const notExpectations = wanted.filter((id) => known.get(id)?.effect !== 'checks');\n if (notExpectations.length > 0) {\n usageError(`Only an expectation can steer the model; ${notExpectations.map((id) => `'${id}'`).join(', ')} ${notExpectations.length === 1 ? 'is' : 'are'} not one.`);\n }\n }\n const decisions: IntentDecision[] = wanted.map((id) => ({ id, state, steer: options.steer ?? null }));\n const decided = await api.analysis.decideIntentItems(analysisId, { decisions });\n if (isDryRun()) {\n hint('Dry run: nothing was changed.');\n return;\n }\n if (outputFormat !== 'human') {\n format(decided, { format: outputFormat });\n return;\n }\n const verb = state === 'CONFIRMED' ? 'Using' : state === 'DECLINED' ? 'Not using' : 'Open again:';\n for (const item of (decided.items ?? []).filter((i) => wanted.includes(i.id))) {\n success(`${verb} ${item.id}: ${item.statement}`);\n }\n if (state === 'CONFIRMED') hint(`It takes part from the next run: 'diafunc analyze rerun ${analysisId}'.`);\n}\n\n/**\n * `analyze expectations <id> [statements...]`: shows the expectations, or sets those of one target.\n * With `--target` every statement is about that target; without it a statement is\n * `<target>=<statement>`, or a bare statement when the analysis has one target. The targets named\n * get the statements given; the expectations of the other targets are kept. `--clear` clears the\n * target named, or all of them.\n */\nasync function expectationsCommand(\n analysisId: string,\n given: string[],\n options: { target?: string; clear?: boolean },\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const analysis = await ownAnalysis(api, analysisId);\n const current = analysis.shapeExpectations ?? {};\n const statements = given.filter((g) => g.trim().length > 0);\n if (options.clear && statements.length > 0) usageError('Give statements or --clear, not both.');\n\n if (!options.clear && statements.length === 0) {\n const shown = options.target === undefined ? current\n : Object.fromEntries(Object.entries(current).filter(([target]) => target === options.target));\n if (outputFormat !== 'human') {\n format({ analysisId, shapeExpectations: shown }, { format: outputFormat });\n return;\n }\n const lines = expectationLines(shown);\n if (lines.length === 0) {\n empty('expectations');\n hint(`Set one with 'diafunc analyze expectations ${analysisId} --target <target> \"increasing(<input>)\"'.`);\n return;\n }\n for (const line of lines) console.log(line);\n hint('An expectation is checked and reported; one written with require: also steers the model.');\n return;\n }\n\n const columns = await columnNames(api, analysisId);\n const targetOf = (typed: string) => resolveColumnArgument(typed, columns, analysisId);\n const byTarget: Record<string, string[]> = Object.fromEntries(Object.entries(current).map(([t, s]) => [t, [...s]]));\n if (options.clear) {\n if (options.target === undefined) {\n for (const target of Object.keys(byTarget)) delete byTarget[target];\n } else {\n delete byTarget[targetOf(options.target)];\n }\n } else {\n const named: Record<string, string[]> = {};\n for (const entry of statements) {\n let target: string;\n let statement: string;\n if (options.target !== undefined) {\n target = targetOf(options.target);\n statement = checkedStatement(entry);\n } else if (entry.includes('=')) {\n const read = parseShapeFlag(entry);\n target = targetOf(read.target);\n statement = read.statement;\n } else if ((analysis.targets ?? []).length === 1) {\n target = (analysis.targets as string[])[0];\n statement = checkedStatement(entry);\n } else {\n usageError(`'${entry}' names no target, and the analysis has ${(analysis.targets ?? []).length === 0 ? 'none yet' : 'several'}.`,\n `Pass --target <target>, or write <target>=<statement>.`);\n }\n (named[target] ??= []);\n if (!named[target].includes(statement)) named[target].push(statement);\n }\n Object.assign(byTarget, named);\n }\n const updated = await api.analysis.patchShapeExpectations(analysisId, { byTarget });\n if (isDryRun()) {\n hint('Dry run: nothing was changed.');\n return;\n }\n if (outputFormat !== 'human') {\n format(updated, { format: outputFormat });\n return;\n }\n success(`Expectations updated for analysis ${analysisId}.`);\n for (const line of expectationLines(updated?.shapeExpectations)) detail(line);\n}\n\n/** `analyze charts <id> <pair...>`: the charts asked for at launch, each `<first>,<second>[,<kind>]`; a single empty argument clears them. */\nasync function chartsCommand(analysisId: string, given: string[], cmd: Command): Promise<void> {\n const api = createApiClient();\n const pairs = resolvePairs(pairsOf(given) ?? [], await columnNames(api, analysisId), analysisId);\n await patchAndPrint(analysisId, pairs.map(pairText).join('; '),\n () => api.analysis.patchRequestedPairs(analysisId, { pairs }),\n 'Charts', cmd);\n}\n\n/** `analyze focus <id> <family...>`: the question families that matter most, most important first; a single empty argument clears them. */\nasync function focusCommand(analysisId: string, given: string[], cmd: Command): Promise<void> {\n const families = focusOf(given) ?? [];\n await patchAndPrint(analysisId, families.map(focusText).join(', '),\n (api, aid) => api.analysis.patchFocusFamilies(aid, { families }),\n 'Focus', cmd);\n}\n\n// ---------- upload ----------\n\ninterface UploadOptions {\n url?: string;\n fileColumn?: boolean;\n keepDuplicates?: boolean;\n rowsOf?: string;\n planOnly?: boolean;\n asUploaded?: true | string[];\n}\n\n/** Collects the files `--as-uploaded <file>` names; the flag without a file stands for every file. */\nfunction collectAsUploaded(value: string, previous: true | string[] | undefined): string[] {\n return [...(Array.isArray(previous) ? previous : []), value];\n}\n\nconst AS_UPLOADED_HELP = 'Read a file exactly as it is, without the reshape its shape suggests (a column per year read as a row per year, a header over several rows, several numbers in one cell). Without a file name: every file; repeat the flag for several';\n\n/** The files `--as-uploaded` stands for among `files`. */\nfunction asUploadedOf(asUploaded: true | string[] | undefined, files: string[]): string[] {\n if (asUploaded === true) return files;\n return asUploaded ?? [];\n}\n\n/**\n * The choices about several files as the flags state them: the file column unless `--no-file-column`,\n * duplicates dropped unless `--keep-duplicates`, the file that carries the rows when `--rows-of` names\n * one, and no build with `--plan-only`.\n */\nfunction stackChoices(options: { fileColumn?: boolean; keepDuplicates?: boolean; rowsOf?: string; planOnly?: boolean;\n asUploaded?: true | string[] }, files: string[]): StackChoices {\n return {\n asUploaded: asUploadedOf(options.asUploaded, files),\n fileColumn: options.fileColumn !== false,\n keepDuplicates: options.keepDuplicates === true,\n rowsOf: options.rowsOf,\n planOnly: options.planOnly === true,\n };\n}\n\n/**\n * Uploads one file as the analysis's data. A file that is not one row per observation is then read\n * through the reshape the platform proposes, unless `asUploaded` names it; a file still being\n * imported when the upload answers is left as uploaded, since nothing can be built beside it.\n */\nasync function uploadOne(api: ReturnType<typeof createApiClient>, analysisId: string, file: string, asUploaded: string[],\n human: boolean): Promise<DataAnswer> {\n const uploaded = await withStatus(`Uploading ${path.basename(file)}`,\n () => api.analysis.uploadDataMultipart(analysisId, multipartFromFile(file)));\n if (isDryRun() || uploaded.dataImport) return uploaded;\n if (asUploaded.length > 0) {\n sourcesAsUploaded([{ fileName: path.basename(file) }], asUploaded);\n return uploaded;\n }\n return await reshapeSingle(api, analysisId, human) ?? uploaded;\n}\n\nasync function uploadData(analysisId: string, files: string[], options: UploadOptions, cmd: Command): Promise<void> {\n const api = createApiClient();\n const outputFormat = getOutputFormat(cmd);\n const ctx = importContext(api, analysisId, cmd, 'none');\n const file: string | undefined = files[0];\n if (files.length > 1) {\n if (options.url) {\n usageError('Provide either files or --url, not both.', 'Drop one of the two and run it again.');\n }\n const built = await sendData(ctx,\n () => uploadSeveral(api, analysisId, files, stackChoices(options, files), outputFormat === 'human'));\n if (outputFormat !== 'human') {\n format({\n ...built.answer,\n rowCount: built.rowCount,\n columnCount: built.columnCount,\n dataImport: built.dataImport,\n }, { format: outputFormat });\n }\n return;\n }\n const dataUrl = options.url;\n if (dataUrl && file) {\n usageError('Provide either a file or --url, not both.', 'Drop one of the two and run it again.');\n }\n if (!dataUrl) {\n if (!file) {\n usageError('Provide a file path or --url <URL>.',\n `For example: diafunc analyze upload ${analysisId} data.csv`);\n }\n if (!fs.existsSync(file)) {\n throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });\n }\n }\n const uploaded = await sendData(ctx, () => dataUrl\n ? withStatus(`Uploading from ${dataUrl}`, () => api.analysis.uploadDataUrl(analysisId, { dataUrl }))\n : uploadOne(api, analysisId, file as string, asUploadedOf(options.asUploaded, files), outputFormat === 'human'));\n if (isDryRun()) {\n hint('Dry run: nothing was uploaded.');\n return;\n }\n if (outputFormat !== 'human') {\n format({\n dataImport: uploaded.dataImport,\n rowCount: uploaded.rowCount,\n columnCount: uploaded.columnCount,\n }, { format: outputFormat });\n }\n}\n\n/**\n * Stops the import that is running for an analysis and reports the state it ended in. The data is\n * then incomplete until it is uploaded again, which the platform's sentence says.\n */\nasync function stopDataImport(analysisId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const stopped = await withStatus('Stopping the data import', () => stopImport(api, analysisId));\n if (isDryRun()) {\n hint('Dry run: nothing was stopped.');\n return;\n }\n if (outputFormat !== 'human') {\n format(stopped, { format: outputFormat });\n return;\n }\n if (!stopped.dataImport) {\n success(`No data import is running for analysis ${analysisId}.`);\n return;\n }\n if (stopped.dataImport.state === 'STOPPED') {\n success(`Stopped the data import of analysis ${analysisId}.`);\n hint(stopped.dataImport.message);\n return;\n }\n // The import ended on its own before the stop reached it.\n warn(stopped.dataImport.message);\n}\n\n// ---------- columns ----------\n\nasync function listColumns(analysisId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const columns = await api.analysis.getColumns(analysisId);\n if (columns.length === 0) {\n empty('columns', { format: outputFormat });\n if (outputFormat === 'human') hint(`Upload data first: diafunc analyze upload ${analysisId} data.csv`);\n return;\n }\n format(columns, { format: outputFormat, columns: ['name', 'valueType'] });\n}\n\n// ---------- runs / cancel ----------\n\nasync function listRuns(analysisId: string, count: number, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const runs = await api.analysis.getRunsForAnalysis(analysisId, count);\n // Absent values are passed through: the renderer shows them as absent, and off a TTY it\n // emits an empty field instead of a character to strip.\n format(runs.map((r) => ({\n runId: r.runId,\n state: r.state,\n phase: runPhaseCell(r),\n validity: verdictLabel(r),\n submittedAt: r.submittedAt,\n startedAt: r.startedAt,\n endedAt: r.endedAt,\n evaluationId: r.evaluationId,\n })), {\n format: outputFormat,\n columns: [\n { key: 'runId', kind: 'id' },\n { key: 'state', kind: 'state' },\n { key: 'phase' },\n { key: 'validity' },\n { key: 'submittedAt', header: 'submitted', kind: 'date' },\n { key: 'endedAt', header: 'ended', kind: 'date' },\n ],\n });\n}\n\nasync function cancelRun(runId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const run = await api.analysis.cancelRun(runId);\n if (outputFormat === 'human') {\n if (run.state === 'CANCELLED') {\n success(cancelSentence(run));\n } else {\n warn(cancelSentence(run));\n }\n } else {\n format(run, { format: outputFormat });\n }\n}\n\n// ---------- presets ----------\n\nasync function listPresets(cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const presets = await api.analysis.getPresets();\n format(presets.map((p) => ({\n presetId: p.presetId,\n name: p.name,\n targets: p.targets.join(', '),\n questions: p.questions.length,\n segment: p.segmentKey,\n hours: p.time,\n budget: p.budget,\n })), {\n format: outputFormat,\n columns: [\n { key: 'presetId', kind: 'id' },\n 'name', 'targets', 'questions', 'segment', 'hours', 'budget',\n ],\n });\n}\n\nasync function getPreset(presetId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const opt = await api.analysis.getPreset(presetId);\n if (!opt.preset) {\n empty('preset found', { format: outputFormat });\n return;\n }\n format(opt.preset, { format: outputFormat });\n}\n\ninterface SavePresetOptions {\n id?: string;\n name: string;\n /** One entry per `--targets`; a single string when a prompt answered it. */\n targets: string | string[];\n hours: string;\n budget: string;\n question?: string[];\n segment?: string;\n}\n\nasync function savePreset(options: SavePresetOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const preset: AnalysisPreset = {\n presetId: options.id ?? null,\n name: options.name,\n targets: typedColumns(options.targets) ?? [],\n questions: questionsOf(options.question) ?? [],\n segmentKey: options.segment ?? null,\n time: options.hours,\n budget: options.budget,\n };\n const saved = await api.analysis.savePreset(preset);\n if (isDryRun()) {\n hint('Dry run: nothing was saved.');\n return;\n }\n format(saved, { format: outputFormat });\n}\n\nasync function deletePreset(presetId: string): Promise<void> {\n const api = createApiClient();\n await api.analysis.deletePreset(presetId);\n success(`Deleted preset ${presetId}.`);\n}\n\n// ---------- triggers ----------\n\n/** A trigger as `triggers list` shows it: its schedule, whether it refreshes the data first, and what became of its last firing. */\nexport function triggerRow(t: AnalysisTrigger): Record<string, unknown> {\n return {\n triggerId: t.triggerId,\n kind: t.kind,\n schedule: t.scheduleSpec,\n active: t.active,\n refreshFirst: t.refreshFirst === true,\n nextFireAt: t.nextFireAt,\n lastOutcome: t.lastOutcome ?? '',\n };\n}\n\n/**\n * What `triggers update` sends. A field that was not given is not sent as a change: `active` and the schedule go\n * as null, which the platform reads as \"leave it\", and `refreshFirst` is left out.\n */\nexport function triggerChanges(options: { active?: string; schedule?: string; refreshFirst?: string }): UpdateAnalysisTriggerRequest {\n const flag = (name: string, value: string | undefined): boolean | undefined => {\n if (value === undefined) return undefined;\n const lc = value.toLowerCase();\n if (lc !== 'true' && lc !== 'false') {\n throw new CliError(`Invalid --${name} value \"${value}\". Use true or false.`);\n }\n return lc === 'true';\n };\n const active = flag('active', options.active);\n const refreshFirst = flag('refresh-first', options.refreshFirst);\n if (active === undefined && !options.schedule && refreshFirst === undefined) {\n throw new CliError('Pass at least one of --active, --schedule or --refresh-first.');\n }\n return {\n active: active ?? null,\n scheduleSpec: options.schedule ?? null,\n ...(refreshFirst === undefined ? {} : { refreshFirst }),\n };\n}\n\nasync function listTriggers(analysisId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const triggers = await api.analysis.listTriggers(analysisId);\n format(triggers.map(triggerRow), {\n format: outputFormat,\n columns: [\n { key: 'triggerId', kind: 'id' },\n 'kind', 'schedule',\n { key: 'active', kind: 'boolean' },\n { key: 'refreshFirst', header: 'refresh first', kind: 'boolean' },\n { key: 'nextFireAt', header: 'next fire', kind: 'date' },\n { key: 'lastOutcome', header: 'last outcome' },\n ],\n });\n}\n\nasync function createTrigger(\n analysisId: string,\n kind: string,\n schedule: string,\n cmd: Command,\n refreshFirst = false,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const upper = kind.toUpperCase();\n if (upper !== 'ONCE' && upper !== 'CRON') {\n failure(`Invalid kind \"${kind}\". Use ONCE or CRON.`);\n process.exit(EXIT_FAILURE);\n }\n const api = createApiClient();\n const trigger = await api.analysis.createTrigger(analysisId, {\n kind: upper as AnalysisTriggerKind,\n scheduleSpec: schedule,\n ...(refreshFirst ? { refreshFirst: true } : {}),\n });\n format(trigger, { format: outputFormat });\n}\n\nasync function deleteTrigger(triggerId: string): Promise<void> {\n const api = createApiClient();\n await api.analysis.deleteTrigger(triggerId);\n success(`Deleted trigger ${triggerId}.`);\n}\n\nasync function updateTriggerCmd(\n triggerId: string,\n options: { active?: string; schedule?: string; refreshFirst?: string },\n cmd: Command,\n): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const changes = triggerChanges(options);\n const api = createApiClient();\n const trigger = await api.analysis.updateTrigger(triggerId, changes);\n format(trigger, { format: outputFormat });\n}\n\n// ---------- registration ----------\n\n/** How a column list is typed, said the same way wherever one is taken. */\nconst COLUMN_LIST_HELP = 'one argument each or comma-separated; a name that contains a comma is an argument of its own, or goes in double quotes inside a list';\n\nconst LICENSE_HELP = \"With PUBLIC: the license the analysis's project is published under, an id of the license catalog (see 'diafunc license list')\";\n\nconst TARGETS_HELP = `Target column names: repeat the flag or separate them with commas; a name that contains a comma is one flag of its own, or goes in double quotes inside a list`;\n\nconst INTENT_HELP = 'What you know about the data and what matters to you, in your own words. Private to you. '\n + 'It is read into proposals; nothing changes until you confirm one';\n\nconst SHAPE_HELP = 'An expectation about a target\\'s shape, <target>=<statement>, for example price=increasing(size_m2); '\n + 'checked and reported, or with require: in front also steering the model; repeat the flag for several';\n\nconst PAIR_QUOTING_HELP = 'A column whose name holds a comma goes in double quotes: \\'\"a, b\",price\\'';\n\nconst PAIR_HELP = `A chart to add to the report: the second column against the first, with kind scatter, groups or counts, or none; at most ${MAX_PAIRS}; repeat the flag for several. ${PAIR_QUOTING_HELP}`;\n\nconst FOCUS_HELP = `A question family that matters most to you, for example extrapolation or input_importance; at most ${MAX_FOCUS}, most important first; repeat the flag for several`;\n\nconst FOCUS_FAMILY_LINES = FOCUS_FAMILIES.map((f) => ` ${f.id.padEnd(20)}${f.label}`).join('\\n');\n\nconst FOCUS_FAMILIES_HELP = `\nQuestion families:\n${FOCUS_FAMILY_LINES}\n`;\n\nexport function registerAnalyzeCommand(program: Command): void {\n const analyze = program\n .command('analyze')\n .description('Run and manage automatic analyses');\n\n // `analyze <file>` is the default subcommand rather than an action on `analyze` itself. Commander\n // lets a parent claim any flag it declares wherever it appears, so a parent that owned `--name`,\n // `--hours` or `--targets` took them from `create`, `presets save` and `rerun` too. A parent with\n // no options of its own leaves every flag to the subcommand it was typed for.\n analyze\n .command('run', { isDefault: true })\n .description('Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)')\n .argument('[files...]', 'Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns')\n .option('--name <name>', 'Analysis name (asked for, or derived from the filename)')\n .option('--description <text>', 'Analysis description')\n .option('--visibility <vis>', 'PRIVATE or PUBLIC (default: PRIVATE)')\n .option('--license <licenseId>', LICENSE_HELP)\n .addOption(hiddenOptionAlias('--licence <licenseId>', 'license'))\n .option('--depth <name or credits>', DEPTH_HELP)\n .option('--hours <hours>', `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`)\n .option('--budget <credits>', `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`)\n .option('--targets <columns>', `${TARGETS_HELP} (required when not interactive)`, collectColumns)\n .option('--question <text>', 'A question for the analysis to answer; repeat the flag for several', collectQuestion)\n .option('--segment <name>', 'Column to segment the analysis by')\n .option('--introduction <markdown>', 'Markdown introduction shown at the top of the notebook')\n .option('--preset <id>', 'Apply a saved preset as defaults (explicit flags override it)')\n .option('--no-file-column', 'With several files: do not add the column that records the file each row came from')\n .option('--keep-duplicates', 'With several files: keep rows that occur in more than one file')\n .option('--rows-of <file>', 'With several files that can be read two ways: the file in which one row is one observation')\n .option('--as-uploaded [file]', AS_UPLOADED_HELP, collectAsUploaded)\n .option('--intent <text>', INTENT_HELP)\n .option('--intent-file <path>', 'Read the notes from a file instead (for notes longer than a line)')\n .option('--shape <target=statement>', SHAPE_HELP, collectQuestion)\n .option('--pair <first,second[,kind]>', PAIR_HELP, collectQuestion)\n .option('--focus <family>', FOCUS_HELP, collectQuestion)\n .action(async (files: string[], options: RunOptions, cmd: Command) => {\n try {\n if (files.length === 0) {\n analyze.help();\n return;\n }\n await runAnalysis(files, options, cmd);\n } catch (error) {\n reportCommandError(error);\n }\n });\n\n analyze\n .command('list')\n .description('List recent analyses')\n .option('--limit <n>', 'Number of analyses to list', '20')\n .action(async (options: { limit: string }, cmd: Command) => {\n try {\n await listAnalyses(parseInt(options.limit, 10), cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('get')\n .description('Show details of an analysis')\n .argument('[id]', 'Analysis ID (defaults to the most recent)')\n .option('--full', 'Print the introduction and your notes in full instead of abbreviating them')\n .addHelpText('after', REPORT_TERMS_HELP)\n .action(async (id: string | undefined, options: { full?: boolean }, cmd: Command) => {\n try {\n await getAnalysisDetails(id, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('watch')\n .description('Follow the latest run of an analysis live')\n .argument('[id]', 'Analysis ID (defaults to the most recent)')\n .addHelpText('after', REPORT_TERMS_HELP)\n .action(async (id: string | undefined, _options, cmd: Command) => {\n try {\n await watchAnalysis(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('open')\n .description('Open an analysis notebook in your browser')\n .argument('[id]', 'Analysis ID (defaults to the most recent)')\n .action(async (id: string | undefined) => {\n try {\n await openAnalysis(id);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('report')\n .description('Print the report of an analysis as Markdown: the summary and the chapter titles, or one chapter')\n .argument('<id>', 'Analysis ID')\n .option('--chapter <title or path>', 'A chapter title, or a path of titles separated by \">\" (for example \"Age > Correlation\")')\n .option('--part <n>', 'With --chapter: the part to read of a chapter that comes in parts, from 1 (default: 1)')\n .option('--max-bytes <n>', 'Largest answer in bytes; the platform reads 4096 to 262144 (default: 32768)')\n .addHelpText('after', REPORT_HELP)\n .action(async (id: string, options: { chapter?: string; part?: string; maxBytes?: string }) => {\n try {\n await printReport(id, options);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('export-model')\n .description('Print the model of a target as a formula or as source code')\n .argument('<id>', 'Analysis ID')\n .requiredOption('--language <language>', `One of: ${EXPORT_LANGUAGES.join(', ')}`)\n .option('--target <name>', 'The target whose model to export (required when the analysis has several)')\n .addHelpText('after', EXPORT_MODEL_HELP)\n .action(async (id: string, options: { language: string; target?: string }) => {\n try {\n await printModelExport(id, options);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('rerun')\n .description('Queue a fresh run on an existing analysis (asks for anything a run still needs). A run cannot start while the data is still being imported')\n .argument('<id>', 'Analysis ID to rerun')\n .action(async (id: string, _options: unknown, cmd: Command) => {\n try {\n await rerunAnalysis(id, cmd);\n } catch (error) {\n reportCommandError(error);\n }\n });\n\n analyze\n .command('create')\n .description('Create an analysis without uploading data or running it')\n .option('--name <name>', 'Analysis name')\n .option('--description <text>', 'Analysis description')\n .option('--visibility <vis>', 'PRIVATE or PUBLIC', 'PRIVATE')\n .option('--license <licenseId>', LICENSE_HELP)\n .addOption(hiddenOptionAlias('--licence <licenseId>', 'license'))\n .option('--depth <name or credits>', DEPTH_HELP)\n .option('--hours <hours>', `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`)\n .option('--budget <credits>', `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`)\n .option('--targets <columns>', TARGETS_HELP, collectColumns)\n .option('--question <text>', 'A question for the analysis to answer; repeat the flag for several', collectQuestion)\n .option('--segment <name>', 'Column to segment the analysis by')\n .option('--introduction <markdown>', 'Markdown introduction shown at the top of the notebook')\n .option('--intent <text>', INTENT_HELP)\n .option('--intent-file <path>', 'Read the notes from a file instead (for notes longer than a line)')\n .option('--shape <target=statement>', SHAPE_HELP, collectQuestion)\n .option('--pair <first,second[,kind]>', PAIR_HELP, collectQuestion)\n .option('--focus <family>', FOCUS_HELP, collectQuestion)\n .action(async (options: CreateOptions, cmd: Command) => {\n try {\n await createAnalysis(options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('delete')\n .description('Delete an analysis, canceling any run still in flight')\n .argument('<id>', 'Analysis ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (id: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete analysis \"${id}\".`, { yes: options.yes, resourceId: id });\n await deleteAnalysis(id);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- typed PATCH subcommands ----------\n\n analyze\n .command('rename')\n .description('Set the analysis name')\n .argument('<id>', 'Analysis ID')\n .argument('<name>', 'New name')\n .action(async (id: string, name: string, _options, cmd: Command) => {\n try {\n await patchAndPrint(id, name,\n (api, aid, v) => api.analysis.patchName(aid, { name: v }),\n 'Name', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('description')\n .description('Set or clear the analysis description (empty string clears)')\n .argument('<id>', 'Analysis ID')\n .argument('<text>', 'New description (empty string to clear)')\n .action(async (id: string, text: string, _options, cmd: Command) => {\n try {\n await patchAndPrint(id, text,\n (api, aid, v) => api.analysis.patchDescription(aid, { description: v === '' ? null : v }),\n 'Description', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('visibility')\n .description('Set analysis visibility (PRIVATE or PUBLIC)')\n .argument('<id>', 'Analysis ID')\n .argument('<vis>', 'PRIVATE or PUBLIC')\n .option('--license <licenseId>', LICENSE_HELP)\n .addOption(hiddenOptionAlias('--licence <licenseId>', 'license'))\n .addHelpText('after', `\nExamples:\n $ diafunc analyze visibility <id> PUBLIC --license CC-BY-4.0 publish under a license\n $ diafunc analyze visibility <id> PRIVATE withdraw it; the license is kept for later\n`)\n .action(async (id: string, vis: string, options: { license?: string }, cmd: Command) => {\n try {\n const visibility = parseVisibility(vis);\n await patchAndPrint(id, visibility,\n (api, aid, v) => api.analysis.patchVisibility(aid, {\n visibility: v as Visibility,\n ...(options.license ? { licenceId: options.license } : {}),\n }),\n 'Visibility', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('introduction')\n .description('Set or clear the markdown introduction')\n .argument('<id>', 'Analysis ID')\n .argument('<markdown>', 'New introduction (empty string to clear)')\n .action(async (id: string, markdown: string, _options, cmd: Command) => {\n try {\n await patchAndPrint(id, markdown,\n (api, aid, v) => api.analysis.patchIntroduction(aid, { introduction: v === '' ? null : v }),\n 'Introduction', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('hours')\n .description('Set the time limit (hours) for the next run')\n .argument('<id>', 'Analysis ID')\n .argument('<hours>', 'Time limit (hours), e.g. 4')\n .action(async (id: string, hours: string, _options, cmd: Command) => {\n try {\n await patchAndPrint(id, hours,\n (api, aid, v) => api.analysis.patchHours(aid, { hours: v }),\n 'Hours', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('budget')\n .description('Set the credit budget for the next run')\n .argument('<id>', 'Analysis ID')\n .argument('<credits>', 'Credit budget, e.g. 10000')\n .action(async (id: string, credits: string, _options, cmd: Command) => {\n try {\n await patchAndPrint(id, credits,\n (api, aid, v) => api.analysis.patchBudget(aid, { budget: v }),\n 'Budget', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('targets')\n .description('Set the target columns, matched against the columns of the analysis data')\n .argument('<id>', 'Analysis ID')\n .argument('<column...>', `Target column names, ${COLUMN_LIST_HELP}`)\n .action(async (id: string, given: string | string[], _options, cmd: Command) => {\n try {\n await patchColumns(id, given,\n (api, targets) => api.analysis.patchTargets(id, { targets }),\n 'Targets', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('input-exclusions')\n .description('Set the columns the analysis leaves out as inputs (a single empty string leaves nothing out)')\n .argument('<id>', 'Analysis ID')\n .argument('<column...>', `Column names, ${COLUMN_LIST_HELP}`)\n .action(async (id: string, given: string | string[], _options, cmd: Command) => {\n try {\n await patchColumns(id, given,\n (api, columns) => api.analysis.patchInputExclusions(id, { columns }),\n 'Columns left out as inputs', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('confirmed-inputs')\n .description('Set the columns the owner confirms as known before the target (a single empty string confirms nothing). A confirmed column raises no leakage concern.')\n .argument('<id>', 'Analysis ID')\n .argument('<column...>', `Column names, ${COLUMN_LIST_HELP}`)\n .action(async (id: string, given: string | string[], _options, cmd: Command) => {\n try {\n await patchColumns(id, given,\n (api, columns) => api.analysis.patchConfirmedInputs(id, { columns }),\n 'Columns known before the target', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('questions')\n .description('Set the questions the analysis answers, one argument per question')\n .argument('<id>', 'Analysis ID')\n .argument('<question...>', 'The questions, each quoted as one argument (a single empty string clears them)')\n .action(async (id: string, given: string | string[], _options, cmd: Command) => {\n try {\n const questions = questionsOf(Array.isArray(given) ? given : [given]) ?? [];\n await patchAndPrint(id, questions.join(' | '),\n (api, aid) => api.analysis.patchQuestions(aid, { questions }),\n 'Questions', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('segment')\n .description('Set or clear the segmentation column (empty string clears)')\n .argument('<id>', 'Analysis ID')\n .argument('<name>', 'Column name, matched against the columns of the analysis data (empty string to clear)')\n .action(async (id: string, name: string, _options, cmd: Command) => {\n try {\n const api = createApiClient();\n const segment = name === '' ? null : resolveColumnArgument(name, await columnNames(api, id), id);\n await patchAndPrint(id, name,\n () => api.analysis.patchSegment(id, { segment }),\n 'Segment', cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- what you know and what matters ----------\n\n const intent = analyze\n .command('intent')\n .description('Your private notes (\"What you know and what matters\"), read into proposals that apply only when you confirm them');\n\n // The default subcommand, so `analyze intent <id> [text]` reads as one command while `read`,\n // `confirm`, `decline` and `reset` stay subcommands; `intent` itself declares no flag.\n intent\n .command('notes', { isDefault: true })\n .description('Show your notes, or set them (an empty text or --clear clears them). Only you can read them; storing them does not read them')\n .argument('<id>', 'Analysis ID')\n .argument('[text]', `The notes, in your own words (at most ${MAX_INTENT_LENGTH.toLocaleString('en-US')} characters)`)\n .option('--file <path>', 'Read the notes from a file')\n .option('--clear', 'Clear the notes')\n .action(async (id: string, text: string | undefined, options: { file?: string; clear?: boolean }, cmd: Command) => {\n try {\n await notesCommand(id, text, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n intent\n .command('read')\n .description('Read your notes into proposals and print them. Nothing changes until you confirm one')\n .argument('<id>', 'Analysis ID')\n .option('--force', 'Read them again even when nothing changed since the last reading')\n .option('--refine', 'Read them for a refinement of the analysis, where a row focus can be applied')\n .action(async (id: string, options: { force?: boolean; refine?: boolean }, cmd: Command) => {\n try {\n await readNotesCommand(id, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n const decisions: { name: string; state: IntentItemState; description: string }[] = [\n { name: 'confirm', state: 'CONFIRMED', description: 'Use proposals: each is applied to the analysis from the next run. An expectation is checked; --steer lets it steer the model too' },\n { name: 'decline', state: 'DECLINED', description: 'Do not use proposals; one that was applied is taken back out' },\n { name: 'reset', state: 'PROPOSED', description: 'Open proposals again, undoing the decision; one that was applied is taken back out' },\n ];\n for (const decision of decisions) {\n const command = intent\n .command(decision.name)\n .description(decision.description)\n .argument('<id>', 'Analysis ID')\n .argument('<proposalId...>', \"Proposal ids, as 'analyze intent read' prints them\");\n if (decision.state === 'CONFIRMED') {\n command\n .option('--steer', 'Also let the expectations steer which model is delivered')\n .option('--no-steer', 'Check and report the expectations only (the default for a new one)');\n }\n command.action(async (id: string, ids: string[], options: { steer?: boolean }, cmd: Command) => {\n try {\n await decideCommand(decision.state, id, ids, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n }\n\n analyze\n .command('expectations')\n .description('Show or set expectations about a target\\'s shape. Each is checked and reported; one written with require: also steers the model')\n .argument('<id>', 'Analysis ID')\n .argument('[statements...]', 'Statements such as increasing(size_m2), decreasing(price, 1, 20), convex(x), concave(x) or range(0, inf), '\n + \"each with check: (the default) or require: in front; without --target written <target>=<statement>. A window left open is the input's observed range\")\n .option('--target <target>', 'The target the statements are about; with --clear, the target to clear')\n .option('--clear', 'Clear the expectations of the target named, or all of them')\n .action(async (id: string, statements: string[], options: { target?: string; clear?: boolean }, cmd: Command) => {\n try {\n await expectationsCommand(id, statements, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('charts')\n .description(`Set the charts to add to the report, at most ${MAX_PAIRS} (a single empty string clears them)`)\n .argument('<id>', 'Analysis ID')\n .argument('<pair...>', `Each <first>,<second>[,<kind>]: the second column against the first; kind is scatter, groups or counts, or left out for the chart rules to choose. ${PAIR_QUOTING_HELP}`)\n .action(async (id: string, given: string[], _options, cmd: Command) => {\n try {\n await chartsCommand(id, given, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('focus')\n .description(`Set what matters most to you, as question families, most important first, at most ${MAX_FOCUS} (a single empty string clears them). The report answers these first`)\n .argument('<id>', 'Analysis ID')\n .argument('<family...>', 'Question families, for example extrapolation or input_importance')\n .addHelpText('after', FOCUS_FAMILIES_HELP)\n .action(async (id: string, given: string[], _options, cmd: Command) => {\n try {\n await focusCommand(id, given, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- data ----------\n\n analyze\n .command('upload')\n .description('Replace the analysis data with a new file (any supported format; see `table import-formats`). An import that takes long is followed until it has finished')\n .argument('<id>', 'Analysis ID')\n .argument('[files...]', 'Data file to upload (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns')\n .option('--url <url>', 'HTTPS URL to fetch the data file from, instead of a file path')\n .option('--no-file-column', 'With several files: do not add the column that records the file each row came from')\n .option('--keep-duplicates', 'With several files: keep rows that occur in more than one file')\n .option('--rows-of <file>', 'With several files that can be read two ways: the file in which one row is one observation')\n .option('--as-uploaded [file]', AS_UPLOADED_HELP, collectAsUploaded)\n .option('--plan-only', 'With several files: store them and print how they fit together, without building the table')\n .action(async (id: string, files: string[], options: UploadOptions, cmd: Command) => {\n try {\n await uploadData(id, files, options, cmd);\n } catch (error) {\n reportCommandError(error);\n }\n });\n\n analyze\n .command('stop-import')\n .description('Stop the data import that is running for an analysis, so the data can be uploaded again')\n .argument('<id>', 'Analysis ID')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await stopDataImport(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('columns')\n .description('List the columns of the analysis data')\n .argument('<id>', 'Analysis ID')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await listColumns(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- runs ----------\n\n analyze\n .command('runs')\n .description('List recent runs for an analysis (newest first)')\n .argument('<id>', 'Analysis ID')\n .option('--count <n>', 'Max number of runs to show', '20')\n .action(async (id: string, options: { count: string }, cmd: Command) => {\n try {\n await listRuns(id, parseInt(options.count, 10), cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n analyze\n .command('cancel')\n .description('Cancel a run that has not finished (a finished run is left as it is)')\n .argument('<runId>', 'Run ID to cancel')\n .action(async (runId: string, _options, cmd: Command) => {\n try {\n await cancelRun(runId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- presets ----------\n\n const presets = analyze\n .command('presets')\n .description('Manage saved analysis presets');\n\n presets\n .command('list')\n .description('List your analysis presets')\n .action(async (_options, cmd: Command) => {\n try {\n await listPresets(cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n presets\n .command('get')\n .description('Show details of a preset')\n .argument('<id>', 'Preset ID')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await getPreset(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n presets\n .command('save')\n .description('Create a new preset (omit --id) or update an existing one (with --id)')\n .requiredOption('--name <name>', 'Preset name')\n .requiredOption('--targets <columns>', TARGETS_HELP, collectColumns)\n .requiredOption('--hours <hours>', 'Time limit (hours)')\n .requiredOption('--budget <credits>', 'Credit budget')\n .option('--question <text>', 'A question for the analysis to answer; repeat the flag for several', collectQuestion)\n .option('--segment <name>', 'Column to segment the analysis by')\n .option('--id <id>', 'Existing preset ID (update mode)')\n .action(async (options: SavePresetOptions, cmd: Command) => {\n try {\n await savePreset(options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n presets\n .command('delete')\n .description('Delete a preset')\n .argument('<id>', 'Preset ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (id: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete preset \"${id}\".`, { yes: options.yes, resourceId: id });\n await deletePreset(id);\n } catch (error) {\n handleError(error);\n }\n });\n\n // ---------- triggers ----------\n\n const triggers = analyze\n .command('triggers')\n .description('Manage scheduled triggers on an analysis');\n\n triggers\n .command('list')\n .description('List triggers for an analysis')\n .argument('<analysisId>', 'Analysis ID')\n .action(async (analysisId: string, _options, cmd: Command) => {\n try {\n await listTriggers(analysisId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n triggers\n .command('create')\n .description('Create a trigger (ONCE: ISO-8601 timestamp; CRON: cron expression)')\n .argument('<analysisId>', 'Analysis ID')\n .requiredOption('--kind <kind>', 'ONCE or CRON')\n .requiredOption('--schedule <spec>', 'ISO-8601 timestamp (ONCE) or cron expression (CRON)')\n .option('--refresh-first', 'Fetch the data sources that feed the analysis and build its data again before every run this trigger starts. A fetch that fails, or data that no longer fits, starts no run; `triggers list` says why')\n .action(async (analysisId: string, options: { kind: string; schedule: string; refreshFirst?: boolean }, cmd: Command) => {\n try {\n await createTrigger(analysisId, options.kind, options.schedule, cmd, options.refreshFirst === true);\n } catch (error) {\n handleError(error);\n }\n });\n\n triggers\n .command('delete')\n .description('Delete a trigger')\n .argument('<triggerId>', 'Trigger ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (triggerId: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete trigger \"${triggerId}\".`, { yes: options.yes, resourceId: triggerId });\n await deleteTrigger(triggerId);\n } catch (error) {\n handleError(error);\n }\n });\n\n triggers\n .command('update')\n .description('Update a trigger: pause or resume it (--active), reschedule it (--schedule), switch refreshing the data first on or off (--refresh-first), or several at once')\n .argument('<triggerId>', 'Trigger ID')\n .option('--active <bool>', 'true to resume, false to pause')\n .option('--schedule <spec>', 'New schedule spec (ISO-8601 instant for ONCE, Quartz cron for CRON)')\n .option('--refresh-first <bool>', 'true to fetch the analysis\\'s data sources before each run, false to run on the data as it is')\n .action(async (triggerId: string, options: { active?: string; schedule?: string; refreshFirst?: string }, cmd: Command) => {\n try {\n await updateTriggerCmd(triggerId, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import chalk from 'chalk';\nimport { SPINNER, bar, percent, qualityPercent } from '../../output/progress.js';\nimport { formatDurationPrecise, formatNumber } from '../../output/values.js';\nimport type { AnalysisRun } from '../../client/types/analysis.js';\nimport { phaseLabel, stepCounter } from './copy.js';\n\nexport { phaseLabel } from './copy.js';\n\n/**\n * How far along the whole run is, 0..1.\n *\n * `overallFraction` is the platform's own weighted figure and is what every other surface shows.\n * The counters are a fallback for a platform build that predates phases, and only a fallback,\n * because they measure one phase: a run 49 of 64 tasks into PROFILING is 16% done, not 77%.\n */\nexport function overallProgress(run: AnalysisRun): number | null {\n if (run.overallFraction !== null && run.overallFraction !== undefined) return run.overallFraction;\n if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;\n return null;\n}\n\n/**\n * Upper bound on the time the search has left, in millis, or null when there is no honest bound.\n *\n * Deliberately a ceiling rather than an estimate, and the same one the web app shows. The search\n * stops when its time or credit budget runs out, and it can stop earlier by converging, which no\n * budget predicts. Extrapolating elapsed time against the fraction achieved so far produces a\n * figure that is wrong in the direction that annoys people: too low, then overrun. Only the\n * search phase has a budget to bound; the other phases take what they take.\n */\nexport function remainingCeiling(run: AnalysisRun, budgetHours: number | null): number | null {\n if (run.phase !== 'DISCOVERING') return null;\n if (budgetHours === null || !Number.isFinite(budgetHours) || budgetHours <= 0) return null;\n const fraction = run.phaseFraction;\n if (fraction === null || fraction === undefined) return null;\n return Math.max(0, budgetHours * 3_600_000 * (1 - Math.max(0, Math.min(fraction, 1))));\n}\n\n/**\n * Detail beneath the bar, chosen by what the phase can actually say.\n *\n * During DISCOVERING the task counters do not move for hours, so the search's own telemetry,\n * which generation it is on and the quality it has reached, is the only honest sign of life.\n * Quality is read as the web app reads it, floored with as many decimals as it takes to show\n * where it moves ({@link qualityPercent}), so the two surfaces never show one search at two figures.\n */\nfunction phaseDetail(run: AnalysisRun): string | null {\n const parts: string[] = [];\n\n if (run.phase === 'DISCOVERING') {\n if (run.fitGeneration !== null && run.fitGeneration !== undefined) {\n parts.push(`generation ${formatNumber(run.fitGeneration)}`);\n }\n if (run.fitQuality !== null && run.fitQuality !== undefined) {\n parts.push(`quality ${qualityPercent(run.fitQuality)}`);\n }\n if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== undefined) {\n parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);\n }\n }\n\n if (parts.length === 0 && run.progressTotal && run.progressTotal > 0) {\n parts.push(`${formatNumber(run.progressDone ?? 0)} of ${formatNumber(run.progressTotal)} tasks`);\n } else if (parts.length === 0 && run.phaseFraction !== null && run.phaseFraction !== undefined) {\n parts.push(`${Math.round(run.phaseFraction * 100)}% of this step`);\n }\n\n return parts.length > 0 ? parts.join(' · ') : null;\n}\n\nexport interface WatchViewInput {\n run: AnalysisRun;\n /** Elapsed wall time since the run started, in millis. */\n elapsedMs: number;\n /** The latest `info` caption from the output feed, if any. */\n caption: string | null;\n /** The analysis's time limit in hours, which bounds the search; null when unknown. */\n budgetHours: number | null;\n}\n\n/**\n * The transient block shown while a run is in flight.\n *\n * Three lines at most: what it is doing, how far along the whole run is, and the detail that\n * distinguishes a working run from a stuck one.\n */\nexport function renderWatchBlock(input: WatchViewInput): string[] {\n const { run, elapsedMs, caption, budgetHours } = input;\n const lines: string[] = [];\n\n const step = stepCounter(run);\n const headline = [\n chalk.cyan(SPINNER),\n chalk.bold(phaseLabel(run)),\n step ? chalk.dim(step) : null,\n ].filter(Boolean).join(' ');\n lines.push(` ${headline}`);\n\n const fraction = overallProgress(run);\n const elapsed = chalk.dim(formatDurationPrecise(elapsedMs));\n if (fraction === null) {\n lines.push(` ${chalk.dim('working')} ${elapsed}`);\n } else {\n const ceiling = remainingCeiling(run, budgetHours);\n lines.push(\n ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` +\n (ceiling !== null ? chalk.dim(` · at most ${formatDurationPrecise(ceiling)} remaining`) : ''),\n );\n }\n\n // The caption is the platform's own words for the current step; the derived detail is a\n // fallback for when it has not sent one yet.\n const detail = caption ?? phaseDetail(run);\n if (detail) lines.push(` ${chalk.dim(detail)}`);\n\n if (run.retryAttempts && run.retryAttempts > 0) {\n lines.push(` ${chalk.yellow('!')} ${chalk.dim(\n `restarted ${run.retryAttempts === 1 ? 'once' : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`,\n )}`);\n }\n\n return lines;\n}\n","import type { Visibility } from './admin.js';\n\n// ----- Clean analysis surface (after platform!141 cleanup) ---------------------------------\n//\n// No internal IDs (projectId / rawDataTableId / notebookId / analysisFunctionId /\n// analysisChapterId) appear in any DTO. Server owns provisioning. Wizard / UI state\n// (phase / step / evaluationId / year-month-day-hour / started) is no longer\n// persisted on the analysis; clients derive what they need from latestRunState +\n// the run rows.\n\nexport type AnalysisRunState =\n | 'QUEUED'\n | 'DISPATCHING'\n | 'RUNNING'\n | 'COMPLETED'\n | 'FAILED'\n | 'CANCELLED';\n\nexport interface AnalysisResponse {\n analysisId: string;\n name: string;\n description: string | null;\n visibility: Visibility;\n /** The license the analysis's project is published under, an id of the license catalog. */\n licenceId?: string | null;\n introduction: string | null;\n hours: string;\n budget: string;\n targets: string[] | null;\n questions: string[] | null;\n segment: string | null;\n createdAt: string | null;\n modifiedAt: string | null;\n latestRunId: string | null;\n latestRunState: AnalysisRunState | null;\n /** The latest result's quality, 0 to 1: the figure the notebook leads with. */\n heldOutQuality?: number | null;\n /** The held-out rows that quality was measured on; absent from a platform or a result without the count. */\n heldOutRows?: number | null;\n /** The rows the model behind that quality was found on; absent likewise. */\n searchRows?: number | null;\n /** The quality the result's own run recorded; the only figure when no rows could be held back. */\n resultRunQuality?: number | null;\n latestRunQuality?: number | null;\n targetResultCount?: number | null;\n targetResults?: AnalysisTargetResult[] | null;\n resultRunId?: string | null;\n labUrl?: string | null;\n parentAnalysisId?: string | null;\n projectId?: string | null;\n creditsUsed?: number | null;\n notifyByEmail?: boolean | null;\n minComplexity?: number | null;\n maxComplexity?: number | null;\n minMilliseconds?: number | null;\n stopAtQuality?: number | null;\n stopAtComplexity?: number | null;\n stopAtError?: number | null;\n rowCount?: number | null;\n columnCount?: number | null;\n inputExclusions?: string[] | null;\n /** Columns the owner confirmed as known before the target; the run raises no leakage concern for them. */\n confirmedInputs?: string[] | null;\n targetKinds?: Record<string, string> | null;\n /** The import of this analysis's data that is running or ended without success; null or absent when the data is as recorded. */\n dataImport?: DataImport | null;\n /**\n * Set on the answer to a creation that named no depth: which starting depth the platform gave the\n * analysis. Null on every other response, and when the creation named its depth.\n */\n depthPreselection?: DepthPreselection | null;\n /** What the owner wrote under \"What you know and what matters\". Owner-only: null for anyone else. */\n intent?: string | null;\n /** The confirmed expectations about each target's shape, by target, in the recipe form (`check:increasing(size_m2, 18.0, 240.0)`). */\n shapeExpectations?: Record<string, string[]> | null;\n /** The charts asked for at launch, in the order asked. */\n requestedPairs?: RequestedPair[] | null;\n /** The question families the owner cares about most, most important first. */\n focusFamilies?: string[] | null;\n}\n\n/** `IMPORTING` and `STOPPING` are in flight; the other three stand until the next upload. */\nexport type DataImportState = 'IMPORTING' | 'STOPPING' | 'FAILED' | 'STOPPED' | 'INTERRUPTED';\n\nexport interface DataImport {\n importId: string;\n state: DataImportState;\n /** 0 to 1, or null when the format does not know its row count. */\n progress: number | null;\n rowsWritten: number | null;\n totalRows: number | null;\n fileName: string;\n startedAt: string;\n /** The platform's sentence for this state, shown as delivered. */\n message: string;\n /** True while a run is refused because of this import. */\n blocksRun: boolean;\n}\n\n/** The answer of the import poll and of the stop: `dataImport` null means the data is in place and counted. */\nexport interface DataImportStatus {\n dataImport: DataImport | null;\n rowCount: number | null;\n columnCount: number | null;\n}\n\n/** `first-analysis` is Express, for an account without a finished analysis; `standard` is Standard. */\nexport type DepthPreselection = 'first-analysis' | 'standard';\n\n/** One step of the depth ladder, as `GET /analyses/depths` answers it. */\nexport interface AnalysisDepth {\n name: string;\n hours: string;\n budget: string;\n /** One of the five names known from before the ladder (Express, Quick, Standard, Thorough, Deep). */\n landmark: boolean;\n /** The step runs for days: it shares the server, and a restart of the platform starts its search over. */\n longRun: boolean;\n}\n\n/** The depth an analysis created without one would get: `GET /analyses/depth-default`. */\nexport interface AnalysisDepthDefault {\n hours: string;\n budget: string;\n depthPreselection: DepthPreselection;\n}\n\n/** One target of an analysis's latest result. */\nexport interface AnalysisTargetResult {\n target: string | null;\n title: string | null;\n expression: string | null;\n quality: number | null;\n /** The held-out rows this target's quality was measured on; absent from an older platform. */\n heldOutRows?: number | null;\n /** The rows this target's model was found on; absent likewise. */\n searchRows?: number | null;\n}\n\nexport interface OptAnalysisResponse {\n analysis: AnalysisResponse | null;\n}\n\n/** One entry of the anonymous listing of public analyses. */\nexport interface PublicAnalysis {\n analysisId: string;\n projectId: string;\n /** An instant as the platform serializes it: epoch milliseconds. An ISO-8601 text is read too. */\n publishedAt: number | string;\n /** The last time the analysis changed while public: an edit, or a new run finishing. */\n changedAt: number | string;\n /** The license the project is published under, an id of the license catalog; null when none was chosen. */\n licenceId?: string | null;\n}\n\nexport interface PublicAnalysesPage {\n analyses: PublicAnalysis[];\n /** Passed back as `cursor` to read the next page; null on the last one. */\n nextCursor: string | null;\n}\n\nexport interface CreateAnalysisRequest {\n name: string;\n description?: string | null;\n visibility?: Visibility | null;\n introduction?: string | null;\n hours?: string | null;\n budget?: string | null;\n targets?: string[] | null;\n questions?: string[] | null;\n segment?: string | null;\n}\n\n/**\n * The fields of a creation that come from the owner's notes. They are part of the creation only:\n * the replace (`PUT`) leaves them as they are, and each has its own PATCH.\n */\nexport interface IntentFields {\n intent?: string | null;\n shapeExpectations?: Record<string, string[]> | null;\n requestedPairs?: RequestedPair[] | null;\n focusFamilies?: string[] | null;\n}\n\n/** The creation's body: a public analysis names the license its project is published under. */\nexport interface NewAnalysisRequest extends CreateAnalysisRequest, IntentFields {\n licenceId?: string | null;\n}\n\nexport interface UpdateAnalysisRequest extends CreateAnalysisRequest {}\n\nexport interface PatchNameRequest { name: string; }\nexport interface PatchDescriptionRequest { description: string | null; }\nexport interface PatchVisibilityRequest { visibility: Visibility; licenceId?: string | null; }\nexport interface PatchIntroductionRequest { introduction: string | null; }\nexport interface PatchHoursRequest { hours: string; }\nexport interface PatchBudgetRequest { budget: string; }\nexport interface PatchTargetsRequest { targets: string[]; }\nexport interface PatchInputExclusionsRequest { columns: string[]; }\nexport interface PatchConfirmedInputsRequest { columns: string[]; }\nexport interface PatchQuestionsRequest { questions: string[]; }\nexport interface PatchSegmentRequest { segment: string | null; }\nexport interface PatchIntentRequest { intent: string | null; }\nexport interface PatchShapeExpectationsRequest { byTarget: Record<string, string[]>; }\nexport interface PatchRequestedPairsRequest { pairs: RequestedPair[]; }\nexport interface PatchFocusFamiliesRequest { families: string[]; }\n\n/** The chart kinds a requested chart may name; none lets the chart rules choose. */\nexport type RequestedChartKind = 'scatter' | 'groups' | 'counts';\n\n/** A chart asked for at launch: the second column against the first. */\nexport interface RequestedPair {\n first: string;\n second: string;\n kind: RequestedChartKind | null;\n}\n\n/** The owner's notes and the setup they are read against (`POST /analyses/{id}/intent/interpretation`). */\nexport interface IntentInterpretRequest {\n intent: string;\n targets: string[];\n segment: string | null;\n inputExclusions: string[];\n targetKinds: Record<string, string>;\n}\n\nexport type IntentItemState = 'PROPOSED' | 'CONFIRMED' | 'DECLINED';\n\n/**\n * What a proposal does: `checks` verifies the model (and steers it when `steer` is on), `changes`\n * changes what is analyzed, `presents` adds a chart, a focus or a question, `note` is an annotation\n * only, `unavailable` cannot be applied on this run (the statement says why).\n */\nexport type IntentEffect = 'checks' | 'changes' | 'presents' | 'note' | 'unavailable';\n\n/**\n * One proposal read from the owner's notes. `statement` is written by the platform, never by the\n * language model. Only the fields of the item's kind are set.\n */\nexport interface IntentItem {\n id: string;\n kind: string;\n quote: string;\n statement: string;\n effect: IntentEffect;\n state: IntentItemState;\n steer?: boolean | null;\n target?: string;\n input?: string;\n direction?: string;\n curvature?: string;\n from?: number;\n to?: number;\n lower?: number;\n upper?: number;\n column?: string;\n first?: string;\n second?: string;\n chart?: string;\n families?: string[];\n question?: string;\n value?: string;\n note?: string;\n}\n\n/** Words from the notes that were not turned into a proposal, or a proposal the checks refused, and why. */\nexport interface IntentNote {\n quote: string;\n kind: string | null;\n reason: string;\n}\n\n/** An entry for the \"Before you launch\" panel. */\nexport interface RunFinding {\n id: string;\n kind: string;\n severity: string;\n title: string;\n text: string;\n part?: string | null;\n group?: string | null;\n chapterId?: string | null;\n}\n\n/** `READY`, `EMPTY` (no notes) or `UNAVAILABLE` (the notes could not be read now; nothing was applied). */\nexport type IntentInterpretationStatus = 'READY' | 'EMPTY' | 'UNAVAILABLE';\n\nexport interface IntentInterpretation {\n status: IntentInterpretationStatus;\n hash: string | null;\n derivedAt: string | null;\n items: IntentItem[];\n notUnderstood: IntentNote[];\n rejections: IntentNote[];\n findings: RunFinding[];\n}\n\n/** The owner's decision on one proposal; `steer` null keeps an expectation's steering as it is. */\nexport interface IntentDecision {\n id: string;\n state: IntentItemState;\n steer: boolean | null;\n}\n\nexport interface IntentDecisionsRequest { decisions: IntentDecision[]; }\n\nexport interface UploadDataUrlRequest { dataUrl: string; }\nexport interface UploadDataInlineRequest { csvContent: string; fileName?: string | null; }\n\n/** One file an analysis's data is built from, kept in the analysis's project as it arrived. */\nexport interface AnalysisSource {\n sourceId: string;\n entityId: string;\n fileName: string;\n sizeBytes: number;\n checksum: string;\n tables: string[];\n options: Record<string, string>;\n origin: string;\n createdAt: string;\n /** The owner wants the file read as uploaded, so no reshape is proposed for it. */\n asUploaded?: boolean;\n /** What the last build made for the tables of this file that are read reshaped. */\n reshaping?: { table: string; reshapes: Reshape[]; uploadedTableId: string; reshapedTableId: string; functionId: string }[];\n /** The data source that refreshes this file; absent for a file that was uploaded. */\n dataSourceId?: string | null;\n}\n\n/**\n * One step that turns a table which is not one row per observation into one that is: `UNPIVOT`\n * (a column per year becomes a row per year), `PROMOTE_HEADER` (the first rows belong to the\n * header) or `SPLIT_COLUMN` (a cell holding several numbers becomes several columns).\n */\nexport interface Reshape {\n kind: 'UNPIVOT' | 'PROMOTE_HEADER' | 'SPLIT_COLUMN' | string;\n keep?: string[];\n namesColumn?: string | null;\n valuesColumn?: string | null;\n headerRows?: number | null;\n column?: string | null;\n separator?: string | null;\n names?: string[];\n keepOriginal?: boolean | null;\n}\n\n/**\n * How one table is built from several source tables: the parts are stacked in order, `originColumn`\n * names the column recording the part each row came from (null: none), and `dropDuplicates` leaves\n * out a row that already occurred in an earlier part.\n */\n/** A table of a stored file that does not look like one row per observation, and what was noticed about it. */\nexport interface TableShape {\n source: string;\n table: string;\n label: string;\n suggestedReshapes: Reshape[];\n noticed: string[];\n}\n\n/**\n * One table of one file in a recipe. `reshapes` are the reshapes the table is read through before it\n * takes part; absent or empty, the table is read as uploaded.\n */\nexport interface CombinedRecipePart {\n source: string;\n table: string;\n label: string;\n reshapes?: Reshape[];\n}\n\n/**\n * A table whose columns are added to the rows that match its key. With `reductions` it is first\n * reduced to one row per key; without them its key must be unique.\n */\nexport interface CombinedRecipeLookup {\n label: string;\n parts: CombinedRecipePart[];\n keys: { main: string; lookup: string }[];\n normalised: boolean;\n reductions: { column: string; how: string }[];\n orderBy: string | null;\n}\n\nexport interface CombinedRecipe {\n parts: CombinedRecipePart[];\n originColumn: string | null;\n dropDuplicates: boolean;\n /** The tables that add columns to the stacked rows, in order. Absent on older platforms. */\n lookups?: CombinedRecipeLookup[];\n}\n\n/** What a plan measured about one lookup. `alternative` is the recipe of the other reading of the same files. */\nexport interface CombinedLookupPlan {\n label: string;\n mainRows: number;\n matched: number;\n matchedNormalised: number;\n lookupRows: number;\n unusedKeys: number;\n rowsPerKeyAtMost: number;\n addedColumns: string[];\n reductionChoices: Record<string, string[]>;\n alternative: CombinedRecipe | null;\n}\n\nexport interface CombinedFinding {\n kind: string;\n message: string;\n tables: string[];\n columns: string[];\n count: number;\n}\n\n/** What building from a recipe yields, measured before anything is written. */\nexport interface CombinedPlan {\n recipe: CombinedRecipe;\n tables: {\n source: string; table: string; label: string; rows: number; columns: string[]; used: boolean;\n /** The reshapes the table's shape suggests; a suggestion, not applied. */\n suggestedReshapes?: Reshape[];\n /** The reshapes this plan reads the table through. */\n reshapes?: Reshape[];\n /** The table as its file holds it, when it is read through reshapes. */\n uploaded?: { rows: number; columns: (string | null)[]; sampleRows: string[][] } | null;\n }[];\n findings: CombinedFinding[];\n rows: number;\n columns: number;\n sampleRows: string[][];\n lookups?: CombinedLookupPlan[];\n}\n\nexport interface AnalysisDataBuild {\n plan: CombinedPlan;\n rowCount: number | null;\n columnCount: number | null;\n dataImport?: DataImport | null;\n}\n\nexport interface AnalysisColumn {\n name: string;\n valueType: string;\n}\n\nexport interface AnalysisNavigation {\n labUrl: string;\n}\n\n/**\n * Kind of run output.\n *\n * The feed carries both halves of the progress story and they are not interchangeable:\n * `event` rows are JSON envelopes for programmatic consumers, `info` rows are the single\n * human-readable caption. Rendering them identically is what put\n * `{\"name\":\"analysis.job.progress\",\"payload\":{...}}` in front of readers 52 times in one run.\n */\nexport type AnalysisRunOutputType = 'info' | 'event' | string;\n\nexport interface AnalysisRunOutput {\n outputId: string;\n type: AnalysisRunOutputType;\n /**\n * For `info` rows this is a caption that **mutates in place**: the same `outputId` comes back\n * with new text as the count advances. Anything deduplicating on `outputId` alone will show the\n * first version forever.\n */\n output: string;\n timestamp: string | null;\n}\n\n// ----- Runs -------------------------------------------------------------------------------\n\n/**\n * Span of the pipeline a run is in. The platform reports this alongside the counters because a\n * percentage cannot say what the run is doing, and on this pipeline the percentage sits still for\n * hours while the search runs. Mirrors `RunPhase` on the platform and in the web app.\n */\nexport type RunPhase =\n | 'QUEUED'\n | 'PREPARING'\n | 'PROFILING'\n | 'DISCOVERING'\n | 'EXPLAINING'\n | 'WRITING';\n\n/** Reader-facing label per phase. Mirrors `RunPhase.displayLabel()` on the platform. */\nexport const RUN_PHASE_LABELS: Record<RunPhase, string> = {\n QUEUED: 'Waiting for a slot',\n PREPARING: 'Preparing',\n PROFILING: 'Profiling your data',\n DISCOVERING: 'Discovering formulas',\n EXPLAINING: 'Building charts and diagnostics',\n WRITING: 'Writing the report',\n};\n\n/**\n * What holds a queued run back. `OWN_RUNS`: its owner already runs as many analyses as one user\n * may, and it starts when one of them ends. `PLATFORM_BUSY`: the platform has no free slot for it,\n * and it starts on its own. Mirrors `RunWaitReason` on the platform and in the web app.\n */\nexport type RunWaitReason = 'OWN_RUNS' | 'PLATFORM_BUSY';\n\n/**\n * Whether a completed run's result is one to rely on, as its report opens with it: `valid`, `needs_review`\n * (something looks too good and only the owner can say what it is) or `not_valid` (the target was among the\n * inputs in another form). Mirrors the platform's validity verdict.\n */\nexport type RunValidity = 'valid' | 'needs_review' | 'not_valid';\n\nexport interface AnalysisRun {\n runId: string;\n analysisId: string;\n userId: string | null;\n state: AnalysisRunState;\n evaluationId: string | null;\n submittedAt: number | null;\n startedAt: number | null;\n endedAt: number | null;\n\n /** Tasks finished and expected *within the current phase*, not across the run. */\n progressDone: number | null;\n progressTotal: number | null;\n\n /** Null on a run from a platform build that predates phases; callers fall back to the counters. */\n phase: RunPhase | null;\n\n /** Completion within {@link phase}, where the task count says nothing. Null outside such phases. */\n phaseFraction: number | null;\n\n /**\n * What the search last reported. Carried on the run so a caption can show it without polling the\n * fit's own output feed. Null outside DISCOVERING and before the first generation.\n */\n fitGeneration: number | null;\n fitQuality: number | null;\n fitBudgetFraction: number | null;\n\n /**\n * How many times this run has been re-dispatched after an interruption it did not cause, such as\n * a platform rollout terminating its evaluation. A retry restarts the analysis from the\n * beginning, so the phase and every progress figure legitimately go backwards when this is above\n * zero; a display that does not say so looks broken.\n */\n retryAttempts: number | null;\n\n /**\n * Fraction of the whole run completed, 0..1, computed by the platform from the phase weights so\n * every surface agrees. Null when the phase is unknown. This is the run's progress, not\n * `progressDone / progressTotal`, which covers a single phase.\n */\n overallFraction: number | null;\n\n /** What the run settled at, in credits. Null while the run is in flight or its ledger could not be read. */\n creditCommitted: number | null;\n\n /** What the run has cost so far, in credits; the figure to show until {@link creditCommitted} is set. */\n creditSpent: number | null;\n\n errorMessage: string | null;\n parentRunId: string | null;\n\n /**\n * Why the run has not started, while it is `QUEUED`. Null in every other state and for the first\n * seconds after a run is queued; absent on a platform build that predates it.\n */\n waitReason?: RunWaitReason | null;\n\n /**\n * The verdict on the run's result. Null for a run that has not completed, that fitted no model, or\n * whose verdict has not been reached yet; absent on a platform build that predates it.\n */\n validity?: RunValidity | null;\n\n /** True when a `valid` verdict rests on the owner's statement that the inputs were known before the target. */\n validityByStatement?: boolean | null;\n\n /** When a result that is valid by the owner's statement was reviewed by Diafunc; null until then. */\n validityReviewedAt?: number | null;\n\n /** The version of the platform's validity rules that reached the verdict; null for an older verdict. */\n validityRule?: number | null;\n}\n\nexport interface OptAnalysisRun {\n run: AnalysisRun | null;\n}\n\n// ----- Presets ----------------------------------------------------------------------------\n\nexport interface AnalysisPreset {\n userId?: string | null;\n presetId?: string | null;\n name: string;\n targets: string[];\n questions: string[];\n segmentKey: string | null;\n time: string;\n budget: string;\n created?: number | null;\n modified?: number | null;\n}\n\nexport interface OptAnalysisPreset {\n preset: AnalysisPreset | null;\n}\n\n// ----- Triggers ---------------------------------------------------------------------------\n\nexport type AnalysisTriggerKind = 'ONCE' | 'CRON';\n\nexport interface AnalysisTrigger {\n triggerId: string;\n analysisId: string;\n userId: string | null;\n kind: AnalysisTriggerKind;\n scheduleSpec: string;\n nextFireAt: number | null;\n active: boolean;\n createdAt: number | null;\n /** A firing fetches the analysis's data sources and builds its data again before the run is queued. */\n refreshFirst?: boolean | null;\n /** What became of the last firing, in a sentence; set for a trigger that refreshes first. */\n lastOutcome?: string | null;\n lastOutcomeAt?: number | string | null;\n}\n\n/** A data source to feed an analysis: what is fetched, and when it refreshes by itself. */\nexport interface AttachDataSourceRequest {\n name: string;\n type: string;\n config: Record<string, string>;\n scheduleCron: string | null;\n}\n\nexport interface CreateAnalysisTriggerRequest {\n kind: AnalysisTriggerKind;\n scheduleSpec: string;\n refreshFirst?: boolean | null;\n}\n\nexport interface UpdateAnalysisTriggerRequest {\n active?: boolean | null;\n scheduleSpec?: string | null;\n refreshFirst?: boolean | null;\n}\n","import {\n RUN_PHASE_LABELS,\n type AnalysisRun,\n type AnalysisRunState,\n type DataImport,\n type RunPhase,\n type RunValidity,\n} from '../../client/types/analysis.js';\n\n/**\n * The sentences the analysis commands say about a run's state.\n *\n * A state is an enum token on the wire (`FAILED`, `CANCELLED`) and a sentence to a reader\n * (\"The latest run failed.\"). These helpers own the translation so no command prints the token.\n */\n\n/** The five phases a run works through, in order. Waiting for a slot and starting are not steps. */\nexport const RUN_STEPS: readonly RunPhase[] = ['PREPARING', 'PROFILING', 'DISCOVERING', 'EXPLAINING', 'WRITING'];\n\n/** Label shown while a dispatcher has leased the run and is provisioning it. */\nconst STARTING = 'Starting';\n\n/** The fields a state reading needs; a cancel answer carries the state without the counters. */\nexport type RunReading = Pick<AnalysisRun, 'state'> & Partial<Pick<AnalysisRun, 'phase' | 'progressTotal' | 'waitReason'>>;\n\n/**\n * What a run is doing, in words: the phase label when the platform reported one, otherwise the\n * reading its state allows. Running with nothing counted yet is preparation, and saying so beats a\n * generic word over an empty bar.\n */\nexport function phaseLabel(run: RunReading): string {\n if (run.state === 'QUEUED') return waitLabel(run);\n if (run.state === 'DISPATCHING') return STARTING;\n if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];\n if (run.state === 'RUNNING' && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;\n // The wire keeps the platform's `CANCELLED`; a reader gets the US word.\n if (run.state === 'CANCELLED') return 'Canceled';\n return run.state.charAt(0) + run.state.slice(1).toLowerCase();\n}\n\n/**\n * What a queued run waits for, in the web app's words. The two waits call for different things:\n * the first ends when one of the owner's own analyses does, the second on its own. A run that\n * gives no reason (an older platform, or the first seconds after queueing) only says that it waits.\n */\nexport function waitLabel(run: RunReading): string {\n switch (run.waitReason) {\n case 'OWN_RUNS': return 'Waiting for one of your analyses to finish';\n case 'PLATFORM_BUSY': return 'Waiting for a free slot';\n default: return RUN_PHASE_LABELS.QUEUED;\n }\n}\n\n/** The same in the few words a table cell has room for. */\nfunction waitCell(run: RunReading): string {\n return run.waitReason === 'OWN_RUNS' ? 'Waiting for your runs' : RUN_PHASE_LABELS.QUEUED;\n}\n\n/** `step 3 of 5`, or nothing while the run is waiting, starting, or on a build without phases. */\nexport function stepCounter(run: AnalysisRun): string | null {\n if (!run.phase) return null;\n const index = RUN_STEPS.indexOf(run.phase);\n if (index < 0) return null;\n return `step ${index + 1} of ${RUN_STEPS.length}`;\n}\n\n/**\n * The phase cell of the runs table. A run in flight shows what it is doing; a run that failed or\n * was canceled shows where it stopped; a completed run went through every phase, so the cell\n * says nothing rather than repeating the last one.\n */\nexport function runPhaseCell(run: AnalysisRun): string | null {\n if (run.state === 'COMPLETED') return null;\n if (run.state === 'QUEUED') return waitCell(run);\n if (run.state === 'DISPATCHING') return phaseLabel(run);\n if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];\n return null;\n}\n\n/** \"The latest run failed.\" and its siblings, for a run the reader asked to watch. */\nexport function latestRunSentence(state: AnalysisRunState): string {\n switch (state) {\n case 'COMPLETED': return 'The latest run has already completed.';\n case 'FAILED': return 'The latest run failed.';\n case 'CANCELLED': return 'The latest run was canceled.';\n case 'QUEUED': return 'The latest run is waiting for a slot.';\n case 'DISPATCHING': return 'The latest run is starting.';\n default: return 'The latest run is in progress.';\n }\n}\n\n/** What a cancel request achieved, from the state the platform answered with. */\nexport function cancelSentence(run: RunReading & Pick<AnalysisRun, 'runId'>): string {\n switch (run.state) {\n case 'CANCELLED': return `Canceled run ${run.runId}.`;\n case 'COMPLETED': return `Run ${run.runId} had already completed.`;\n case 'FAILED': return `Run ${run.runId} had already failed.`;\n default: return `Run ${run.runId} is still ${phaseLabel(run).toLowerCase()}.`;\n }\n}\n\n/**\n * What a run cost, in credits: the settled figure once there is one, otherwise what it has spent so\n * far. Null when neither was measured, which is not the same as a run that cost nothing.\n */\nexport function runCredits(run: Pick<AnalysisRun, 'creditCommitted' | 'creditSpent'>): number | null {\n return run.creditCommitted ?? run.creditSpent ?? null;\n}\n\n/**\n * Sentence for the closing line of a watched run. A canceled or failed run is charged for the work\n * it did, so its cost is named as well; an unmeasured cost is left out rather than shown as zero.\n */\nexport function terminalSentence(state: AnalysisRunState, duration: string, credits: number | null = null): string {\n const cost = credits === null ? '' : ` · ${credits.toLocaleString('en-US', { maximumFractionDigits: 0 })} ${credits === 1 ? 'credit' : 'credits'}`;\n switch (state) {\n case 'COMPLETED': return `Analysis completed in ${duration}${cost}.`;\n case 'CANCELLED': return `Analysis canceled after ${duration}${cost}.`;\n default: return `Analysis failed after ${duration}${cost}.`;\n }\n}\n\n/** Whether the data is still arriving. The other states are an import that ended, and stand until the next upload. */\nexport function isImporting(dataImport: DataImport | null | undefined): dataImport is DataImport {\n return dataImport?.state === 'IMPORTING' || dataImport?.state === 'STOPPING';\n}\n\n/**\n * `Importing data, 42%`, or `Importing data` when the format does not know its row count. Shown\n * where a run state would be, since no run can start before the data is in place. Floored, so an\n * import that has not finished never reads 100%.\n */\nexport function importingLabel(dataImport: Pick<DataImport, 'progress'>): string {\n const progress = dataImport.progress;\n if (progress === null || progress === undefined || !Number.isFinite(progress)) return 'Importing data';\n return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)}%`;\n}\n\n/** The fields a verdict reading needs. */\nexport type VerdictReading = Partial<Pick<AnalysisRun, 'validity' | 'validityByStatement' | 'validityReviewedAt'>>;\n\n/**\n * The verdict on a run's result in the report's words, or null when the run carries none. A result that\n * is valid by the owner's statement says so, and whether Diafunc has reviewed the statement yet.\n */\nexport function verdictLabel(run: VerdictReading): string | null {\n switch (run.validity) {\n case 'valid':\n if (!run.validityByStatement) return 'Valid';\n return run.validityReviewedAt != null\n ? \"Valid by the owner's statement, reviewed\"\n : \"Valid by the owner's statement\";\n case 'needs_review': return 'Needs review';\n case 'not_valid': return 'Not valid';\n default: return null;\n }\n}\n\n/**\n * The line a watched run closes with when its result is not plainly valid, or null. Where the reasons\n * are is said, since the run row carries the verdict and the report carries why.\n */\nexport function verdictSentence(validity: RunValidity | null | undefined): string | null {\n switch (validity) {\n case 'needs_review': return \"The result needs review: the report's Validity chapter says why and what settles it.\";\n case 'not_valid': return \"The result is not valid: the report's Validity chapter says why.\";\n default: return null;\n }\n}\n","import chalk from 'chalk';\nimport type { License, Visibility } from '../../client/types/admin.js';\nimport type { AnalysisColumn, AnalysisDepth, AnalysisPreset, AnalysisResponse } from '../../client/types/analysis.js';\nimport type { Prompter } from '../../prompting/prompter.js';\nimport { parseColumnList } from './columns.js';\nimport { MAX_INTENT_LENGTH } from './intent.js';\n\n/**\n * The interactive half of `diafunc analyze <file>`.\n *\n * A run needs `hours`, `budget` and `targets`. The platform gives a new analysis its depth when\n * the creation names none, but it never guesses the targets, and the target column names cannot be\n * known before the file is uploaded, because they come out of its header. Without prompting, the\n * only way to name them was to type `--targets` from memory, and getting it wrong cost a created\n * analysis and an uploaded file for nothing: the recipe was saved, the data ingested, and only\n * then did the run request come back `Analysis is missing required fields: targets`.\n *\n * The prompts run through the shared {@link Prompter} (`src/prompting/prompter.ts`), so the flow\n * can be exercised end to end against a scripted answer list instead of a terminal.\n */\n\n/** A step of the depth ladder: a time limit with the credits the analysis may spend. */\nexport type DepthPreset = Pick<AnalysisDepth, 'name' | 'hours' | 'budget'> & Partial<Pick<AnalysisDepth, 'longRun'>>;\n\n/**\n * The rule the platform applies to an analysis created without a depth, in the words every surface\n * uses for it. The CLI holds no default of its own: it sends a depth only when one was named.\n */\nexport const STARTING_DEPTH_RULE = \"Defaults to the account's starting depth: Express (1 hour, 500 credits) \"\n + 'until the account has a finished analysis, Standard (4 hours, 4,000 credits) afterwards.';\n\n/** Credits in full, with grouped thousands: \"16,000 credits\". */\nexport function creditsLabel(budget: string): string {\n const n = Number(budget);\n return `${Number.isFinite(n) ? n.toLocaleString('en-US') : budget} credits`;\n}\n\n/**\n * The longest time a depth may take, the way the web app says it: hours up to a day, then days to one\n * decimal, then whole weeks from two weeks on.\n */\nexport function timeLabel(hours: string): string {\n const h = Number(hours);\n if (!Number.isFinite(h) || h <= 0) return `${hours} hours`;\n const trim = (v: number) => (Number.isInteger(v) ? v.toString() : (Math.round(v * 10) / 10).toString());\n if (h < 24) return h === 1 ? '1 hour' : `${trim(h)} hours`;\n const days = h / 24;\n if (days < 14) return days === 1 ? '1 day' : `${trim(Math.round(days * 10) / 10)} days`;\n return `${Math.round(days / 7)} weeks`;\n}\n\n/**\n * The step `--depth` names: its name in any case, or its credits (\"4000\", \"4,000\"). Undefined when no\n * step answers to it.\n */\nexport function findDepth(depths: readonly DepthPreset[], nameOrCredits: string): DepthPreset | undefined {\n const wanted = nameOrCredits.trim();\n const credits = wanted.replace(/[,_]/g, '');\n return depths.find((step) => step.name.toLowerCase() === wanted.toLowerCase() || step.budget === credits);\n}\n\n/** A time limit and a credit budget that belong together. */\nexport interface Depth {\n hours: string;\n budget: string;\n}\n\n/** `hours` and `budget` as a depth, or null unless both are there. */\nexport function depthOf(hours: string | null | undefined, budget: string | null | undefined): Depth | null {\n const h = hours?.trim();\n const b = budget?.trim();\n return h && b ? { hours: h, budget: b } : null;\n}\n\n// ---------- step 1: the analysis itself ----------\n\nexport interface CreationAnswers {\n name: string;\n description: string | null;\n visibility: Visibility;\n /** The license a public analysis's project is published under; absent for a private one unless a flag named it. */\n licenceId?: string;\n}\n\n/**\n * Asks for the fields that describe the analysis. A flag that was supplied is never asked about\n * again, so `--name x` in a terminal behaves like `--name x` in a script.\n *\n * A public analysis is asked for its license, from the catalog `licenses` reads; it is read only\n * then, so a private analysis costs no request.\n */\nexport async function promptCreationFields(\n prompter: Prompter,\n supplied: { name?: string; description?: string; visibility?: Visibility; licenceId?: string },\n fallbackName: string,\n licenses?: () => Promise<License[]>,\n): Promise<CreationAnswers> {\n const name = supplied.name ?? await prompter.input({\n message: 'Analysis name',\n default: fallbackName,\n validate: (value) => value.trim().length > 0 || 'A name is required.',\n });\n\n const description = supplied.description ?? await prompter.input({\n message: 'Description (optional)',\n });\n\n const visibility = supplied.visibility ?? await prompter.select<Visibility>({\n message: 'Visibility',\n default: 'PRIVATE',\n choices: [\n { name: 'Private', value: 'PRIVATE', description: 'Only you can open the analysis.' },\n { name: 'Public', value: 'PUBLIC', description: 'Anyone with the link can read the notebook.' },\n ],\n });\n\n const answers: CreationAnswers = { name: name.trim(), description: description.trim() || null, visibility };\n const licenseId = supplied.licenceId\n ?? (visibility === 'PUBLIC' && licenses ? await promptLicense(prompter, await licenses()) : undefined);\n if (licenseId) answers.licenceId = licenseId;\n return answers;\n}\n\n/** The choice under the recommended licenses that opens the whole catalog; no license id holds a colon. */\nconst ALL_LICENSES = ':all';\n\n/**\n * Asks which license a public analysis is published under: the recommended licenses first, and the\n * whole catalog one step further. Only an active license can be chosen, so a deprecated one is not\n * offered. Returns undefined when the catalog offers nothing to choose, and the platform decides.\n */\nexport async function promptLicense(prompter: Prompter, catalog: License[]): Promise<string | undefined> {\n const selectable = catalog.filter((l) => l.state === 'ACTIVE');\n if (selectable.length === 0) return undefined;\n const choice = (l: License) => ({ name: `${l.name} (${l.licenceId})`, value: l.licenceId, description: l.summary ?? undefined });\n const recommended = selectable.filter((l) => l.recommended);\n const others = selectable.filter((l) => !l.recommended);\n if (recommended.length === 0 || others.length === 0) {\n return prompter.select<string>({ message: 'License', default: selectable[0].licenceId, choices: selectable.map(choice) });\n }\n const picked = await prompter.select<string>({\n message: 'License',\n default: recommended[0].licenceId,\n choices: [\n ...recommended.map(choice),\n { name: 'Another license…', value: ALL_LICENSES, description: `${others.length} more in the catalog.` },\n ],\n });\n if (picked !== ALL_LICENSES) return picked;\n return prompter.select<string>({ message: 'License (all)', default: others[0].licenceId, choices: selectable.map(choice) });\n}\n\n// ---------- step 2: what to run ----------\n\nexport interface RunAnswers {\n targets: string[];\n segment: string | null;\n questions: string[] | null;\n /** The owner's notes (\"What you know and what matters\"), or null for none. */\n intent: string | null;\n hours: string;\n budget: string;\n}\n\nexport interface RunPromptInput {\n /** Columns of the uploaded table. Empty when the header could not be read; targets are typed then. */\n columns: AnalysisColumn[];\n /** The caller's saved presets, offered as a starting point. Empty when none exist or the read failed. */\n presets: AnalysisPreset[];\n /**\n * Values already fixed by a flag, by `--preset`, or by the analysis being rerun. `undefined`\n * means \"ask\"; a `null` segment or question list means \"decided: none\", and is not asked about.\n */\n supplied: {\n targets?: string[] | null;\n segment?: string | null;\n questions?: string[] | null;\n /** The notes; `null` means \"decided: none\". */\n intent?: string | null;\n hours?: string;\n budget?: string;\n };\n /**\n * The depth the platform would give this account's next analysis, preselected in the depth\n * prompt. Null or absent when the platform did not say: nothing is preselected then.\n */\n depthDefault?: Depth | null;\n /**\n * The depth ladder as the platform serves it (`GET /analyses/depths`). Empty when it could not be\n * read: the prompt then asks for the two figures.\n */\n depths?: readonly DepthPreset[];\n}\n\n/** The step whose figures match `hours`/`budget` exactly, or null for a custom pair. */\nexport function matchDepthPreset(\n depths: readonly DepthPreset[],\n hours: string | null | undefined,\n budget: string | null | undefined,\n): DepthPreset | null {\n if (!hours || !budget) return null;\n return depths.find((p) => p.hours === hours && p.budget === budget) ?? null;\n}\n\n/**\n * The column a target defaults to.\n *\n * The last column, matching the web wizard. Datasets are conventionally written with the target\n * last, and a wrong pre-selection costs one keystroke to undo where an empty one costs a decision.\n */\nexport function defaultTargets(columns: readonly AnalysisColumn[]): string[] {\n const named = columns.filter((c) => c.name && c.name.length > 0);\n return named.length > 0 ? [named[named.length - 1].name] : [];\n}\n\n/** Reject anything that is not a positive, finite number of hours or credits. */\nfunction positiveNumber(label: string): (value: string) => true | string {\n return (value: string) => {\n const parsed = Number(value.trim());\n if (!Number.isFinite(parsed) || parsed <= 0) return `${label} must be a positive number.`;\n return true;\n };\n}\n\nexport async function promptRunFields(prompter: Prompter, options: RunPromptInput): Promise<RunAnswers> {\n const { columns, depthDefault } = options;\n const depths = options.depths ?? [];\n const named = columns.filter((c) => c.name && c.name.length > 0);\n let supplied = { ...options.supplied };\n\n // A saved preset answers every question below at once, so it is offered before any of them are\n // asked. It only appears when nothing was fixed on the command line — a preset that silently\n // overrode an explicit flag would be the opposite of what the flag was typed for.\n const nothingSupplied = supplied.targets === undefined && supplied.segment === undefined\n && supplied.questions === undefined && supplied.hours === undefined && supplied.budget === undefined;\n if (options.presets.length > 0 && nothingSupplied) {\n const preset = await prompter.select<AnalysisPreset | null>({\n message: 'Start from a saved preset?',\n default: null,\n choices: [\n { name: 'No, set it up now', value: null },\n ...options.presets.map((p) => ({\n name: p.name,\n value: p,\n description: describePreset(p),\n })),\n ],\n });\n if (preset) {\n supplied = {\n targets: preset.targets.length > 0 ? preset.targets : undefined,\n questions: preset.questions.length > 0 ? preset.questions : undefined,\n segment: preset.segmentKey ?? undefined,\n intent: supplied.intent,\n hours: preset.time || undefined,\n budget: preset.budget || undefined,\n };\n }\n }\n\n // ----- targets (required) -----\n let targets = supplied.targets ?? null;\n if (targets === null || targets.length === 0) {\n if (named.length > 0) {\n const preselected = new Set(defaultTargets(named));\n targets = await prompter.checkbox({\n message: 'Target columns: what should the analysis predict?',\n choices: named.map((c) => ({\n name: c.valueType ? `${c.name} ${chalk.dim(`(${c.valueType})`)}` : c.name,\n value: c.name,\n checked: preselected.has(c.name),\n })),\n validate: (chosen) => chosen.length > 0 || 'Pick at least one target column.',\n });\n } else {\n // No header came back. Typing the names is still better than failing after the upload.\n const typed = await prompter.input({\n message: 'Target column names (comma-separated; a name that contains a comma goes in double quotes)',\n validate: (value) => {\n try {\n return parseColumnList(value).length > 0 || 'Name at least one target column.';\n } catch (error) {\n return error instanceof Error ? error.message : String(error);\n }\n },\n });\n targets = parseColumnList(typed);\n }\n }\n\n const remaining = named.filter((c) => !targets!.includes(c.name));\n\n // ----- segment (optional) -----\n let segment: string | null = supplied.segment ?? null;\n if (supplied.segment === undefined && remaining.length > 0) {\n segment = await prompter.select<string | null>({\n message: 'Segment the analysis by a column? (optional)',\n default: null,\n choices: [\n { name: 'No segmentation', value: null },\n ...remaining.map((c) => ({\n name: c.valueType ? `${c.name} ${chalk.dim(`(${c.valueType})`)}` : c.name,\n value: c.name as string | null,\n })),\n ],\n });\n }\n\n // ----- questions (optional) -----\n let questions: string[] | null = supplied.questions ?? null;\n if (supplied.questions === undefined) {\n const wanted = await prompter.confirm({\n message: 'Add questions for the analysis to answer? (optional)',\n default: false,\n });\n if (wanted) {\n const collected: string[] = [];\n for (;;) {\n const question = await prompter.input({\n message: collected.length === 0 ? 'Question' : 'Another question (blank to finish)',\n });\n const trimmed = question.trim();\n if (trimmed.length === 0) break;\n collected.push(trimmed);\n }\n questions = collected.length > 0 ? collected : null;\n }\n }\n\n // ----- the notes (optional, private to the owner) -----\n let intent: string | null = supplied.intent ?? null;\n if (supplied.intent === undefined) {\n const typed = await prompter.input({\n message: 'What you know and what matters (optional, private to you; blank to skip)',\n validate: (value) => value.length <= MAX_INTENT_LENGTH\n || `At most ${MAX_INTENT_LENGTH.toLocaleString('en-US')} characters; --intent-file takes longer notes.`,\n });\n intent = typed.trim() || null;\n }\n\n // ----- depth -----\n let hours = supplied.hours;\n let budget = supplied.budget;\n if (hours === undefined && budget === undefined && depths.length > 0) {\n const chosen = await prompter.select<DepthPreset | null>({\n message: 'Depth: what may the analysis spend, and how long may it take?',\n default: matchDepthPreset(depths, depthDefault?.hours, depthDefault?.budget) ?? undefined,\n choices: [\n ...depths.map((p) => ({\n name: `${p.name}: ${creditsLabel(p.budget)}, up to ${timeLabel(p.hours)}`,\n value: p as DepthPreset | null,\n description: p.longRun\n ? 'A long analysis: it runs for days and shares the server. If the platform restarts, its search starts '\n + 'again; the interrupted attempt is not charged.'\n : undefined,\n })),\n { name: 'Set your own time and credits', value: null },\n ],\n });\n if (chosen) {\n hours = chosen.hours;\n budget = chosen.budget;\n }\n }\n if (hours === undefined) {\n hours = await prompter.input({\n message: 'Time limit (hours)',\n default: depthDefault?.hours,\n validate: positiveNumber('Time limit'),\n });\n }\n if (budget === undefined) {\n budget = await prompter.input({\n message: 'Credit budget',\n default: depthDefault?.budget,\n validate: positiveNumber('Credit budget'),\n });\n }\n\n return {\n targets: targets ?? [],\n segment,\n questions,\n intent,\n hours: hours.trim(),\n budget: budget.trim(),\n };\n}\n\n/** One line summarising a saved preset, shown beside its name in the picker. */\nexport function describePreset(preset: AnalysisPreset): string {\n const parts: string[] = [];\n if (preset.time) parts.push(`${preset.time}h`);\n if (preset.budget) parts.push(`${preset.budget} credits`);\n if (preset.targets.length > 0) parts.push(`targets: ${preset.targets.join(', ')}`);\n if (preset.segmentKey) parts.push(`segmented by ${preset.segmentKey}`);\n return parts.join(' · ');\n}\n\n/** The lines of the pre-flight summary, in reading order. Returned rather than printed so it is testable. */\nexport function summaryLines(creation: CreationAnswers, run: Omit<RunAnswers, 'intent'> & { intent?: string | null }, depths: readonly DepthPreset[] = []): string[] {\n const lines = [\n `Name: ${creation.name}`,\n `Visibility: ${creation.visibility === 'PUBLIC' ? 'Public' : 'Private'}`,\n ];\n if (creation.licenceId) lines.push(`License: ${creation.licenceId}`);\n lines.push(`Targets: ${run.targets.join(', ')}`);\n if (run.segment) lines.push(`Segment: ${run.segment}`);\n if (run.questions && run.questions.length > 0) {\n lines.push(`Questions: ${run.questions.length}`);\n }\n if (run.intent) lines.push('Notes: written (private to you)');\n lines.push(`Depth: ${depthLabel(run, depths)}`);\n return lines;\n}\n\n/** A depth as a reader is shown it: the step's name when the figures are one, then the figures. */\nexport function depthLabel(depth: Depth, depths: readonly DepthPreset[] = []): string {\n const preset = matchDepthPreset(depths, depth.hours, depth.budget);\n const named = preset ? `${preset.name}, ` : '';\n return `${named}${creditsLabel(depth.budget)}, up to ${timeLabel(depth.hours)}`;\n}\n\n// ---------- rerun of an existing analysis ----------\n\n/** A run field the platform refuses to run without. */\nexport type RunField = 'hours' | 'budget' | 'targets';\n\n/**\n * Which required run fields a recipe lacks, in the order the platform names them.\n *\n * Mirrors the check the platform makes before it queues a run, so `rerun` can ask for the gaps\n * instead of sending a request that comes back `Analysis is missing required fields`.\n */\nexport function missingRunFields(recipe: {\n hours?: string | null;\n budget?: string | null;\n targets?: string[] | null;\n}): RunField[] {\n const missing: RunField[] = [];\n if (!recipe.hours || recipe.hours.trim().length === 0) missing.push('hours');\n if (!recipe.budget || recipe.budget.trim().length === 0) missing.push('budget');\n if (!recipe.targets || recipe.targets.length === 0) missing.push('targets');\n return missing;\n}\n\n/**\n * An existing analysis's settings as wizard input.\n *\n * Everything the analysis already has counts as answered, including an absent segment and an empty\n * question list: those were decisions, and a rerun asks only for what would stop the run.\n */\nexport function suppliedFromAnalysis(analysis: AnalysisResponse): RunPromptInput['supplied'] {\n return {\n targets: analysis.targets && analysis.targets.length > 0 ? analysis.targets : undefined,\n hours: analysis.hours?.trim() ? analysis.hours : undefined,\n budget: analysis.budget?.trim() ? analysis.budget : undefined,\n segment: analysis.segment ?? null,\n questions: analysis.questions ?? null,\n intent: analysis.intent ?? null,\n };\n}\n\nconst FIELD_COMMANDS: Record<RunField, string> = {\n hours: 'hours <id> <hours>',\n budget: 'budget <id> <credits>',\n targets: 'targets <id> <column...>',\n};\n\n/** The refusal for a rerun that cannot ask, naming the command that fills each gap. */\nexport function explainMissingRunFields(\n analysisId: string,\n missing: readonly RunField[],\n reason: string,\n): { message: string; suggestion: string } {\n const commands = missing.map((f) => `'diafunc analyze ${FIELD_COMMANDS[f].replace('<id>', analysisId)}'`);\n const columns = missing.includes('targets') ? ` Column names: 'diafunc analyze columns ${analysisId}'.` : '';\n return {\n message: `Analysis ${analysisId} cannot run yet: it has no ${joinList(missing)}, and ${reason}.`,\n suggestion: `Set ${missing.length === 1 ? 'it' : 'them'} with ${commands.join(', ')}, then rerun.${columns}`,\n };\n}\n\nfunction joinList(items: readonly string[]): string {\n if (items.length <= 1) return items.join('');\n return `${items.slice(0, -1).join(', ')} or ${items[items.length - 1]}`;\n}\n","import { isInteractive } from '../output/terminal.js';\nimport type { OutputFormat } from '../output/formatter.js';\n\n/**\n * Asking the reader, as one small interface.\n *\n * Every question the CLI asks goes through a {@link Prompter} rather than calling\n * `@inquirer/prompts` directly, so a flow can be exercised end to end against a scripted answer list\n * instead of a terminal. The analyze wizard and the missing-input machinery share it.\n */\n\n/** Raised when the reader interrupts a prompt. Carries no message the caller has to print. */\nexport class PromptCanceled extends Error {\n constructor() {\n super('Canceled.');\n this.name = 'PromptCanceled';\n }\n}\n\nexport interface Choice<T> {\n name: string;\n value: T;\n description?: string;\n}\n\nexport interface CheckboxChoice {\n name: string;\n value: string;\n checked?: boolean;\n}\n\n/** The prompt kinds the CLI uses, narrowed to what it actually needs from `@inquirer/prompts`. */\nexport interface Prompter {\n input(options: { message: string; default?: string; validate?: (value: string) => true | string }): Promise<string>;\n select<T>(options: { message: string; default?: T; choices: Choice<T>[] }): Promise<T>;\n checkbox(options: {\n message: string;\n choices: CheckboxChoice[];\n validate?: (chosen: readonly { value: string }[]) => true | string;\n }): Promise<string[]>;\n confirm(options: { message: string; default?: boolean }): Promise<boolean>;\n /**\n * Type-to-filter. `source` runs on every keystroke with what has been typed so far, so it can\n * filter a list it already holds or ask the server for matches.\n */\n search<T>(options: { message: string; source: (term: string) => Promise<Choice<T>[]> | Choice<T>[] }): Promise<T>;\n}\n\n/**\n * The real prompter. `@inquirer/prompts` is imported lazily because it installs signal handlers and\n * raw-mode listeners on load, and a piped run never prompts at all.\n */\nexport function createInquirerPrompter(): Prompter {\n const load = () => import('@inquirer/prompts');\n // A Ctrl-C inside a prompt arrives as ExitPromptError. Translating it here keeps every call site\n // free of the distinction between \"the reader stopped\" and \"the prompt broke\".\n const guard = async <T>(work: () => Promise<T>): Promise<T> => {\n try {\n return await work();\n } catch (error) {\n if (error instanceof Error && error.name === 'ExitPromptError') throw new PromptCanceled();\n throw error;\n }\n };\n return {\n async input(options) {\n const { input } = await load();\n return guard(() => input(options));\n },\n async select(options) {\n const { select } = await load();\n return guard(() => select(options as never)) as never;\n },\n async checkbox(options) {\n const { checkbox } = await load();\n return guard(() => checkbox(options as never)) as never;\n },\n async confirm(options) {\n const { confirm } = await load();\n return guard(() => confirm(options));\n },\n async search(options) {\n const { search } = await load();\n return guard(() => search({\n message: options.message,\n pageSize: 12,\n source: async (term) => options.source(term ?? '') as never,\n })) as never;\n },\n };\n}\n\n/**\n * Whether this invocation may ask questions.\n *\n * Both streams matter: a prompt reads stdin and repaints stdout, so a run with either end\n * redirected has to be answered from flags. `--output json` is a script's contract regardless of\n * what it is attached to, and `--no-interactive` is the explicit opt out.\n */\nexport function canPrompt(outputFormat: OutputFormat, noInteractive: boolean): boolean {\n if (noInteractive) return false;\n if (outputFormat !== 'human') return false;\n return Boolean(process.stdin.isTTY) && isInteractive();\n}\n\n/**\n * Why {@link canPrompt} said no, as the end of a sentence. A refusal that blamed the terminal when\n * the reader was sitting at one and had typed `--no-interactive` would send them looking for a\n * problem that is not there.\n */\nexport function whyNoPrompt(outputFormat: OutputFormat, noInteractive: boolean): string {\n if (noInteractive) return '--no-interactive is set';\n if (outputFormat !== 'human') return `--output ${outputFormat} does not prompt`;\n return 'there is no terminal to ask';\n}\n","import chalk from 'chalk';\nimport type { ApiClient } from '../../client/api.js';\nimport { ApiError } from '../../client/errors.js';\nimport type { AnalysisRun, DataImport, DataImportStatus } from '../../client/types/analysis.js';\nimport type { OutputFormat } from '../../output/formatter.js';\nimport { hint, success, warn } from '../../output/messages.js';\nimport { SPINNER, Status, bar, percent, withStatus } from '../../output/progress.js';\nimport { formatDurationPrecise } from '../../output/values.js';\nimport type { Prompter } from '../../prompting/prompter.js';\nimport { CliError, EXIT_CANCELLED } from '../../util/errors.js';\nimport { isImporting } from './copy.js';\nimport { dataShape } from './details.js';\n\n/**\n * An import that outlasts the upload request.\n *\n * The platform waits a while for an import and then answers the upload anyway, with the import\n * still writing. Uploading again at that point would clear the table under the import that is\n * filling it, so the commands follow the import instead, and a second upload is refused by the\n * platform until the first has ended or was stopped. Every sentence about the import's state is the\n * platform's own `message`, shown as delivered.\n */\n\n/** How often the import is re-read while waiting, the interval the platform recommends. */\nexport const IMPORT_POLL_INTERVAL_MS = 2000;\n\n/** What an upload, a build, the poll and the stop all answer about the data. */\nexport interface DataAnswer {\n dataImport?: DataImport | null;\n rowCount?: number | null;\n columnCount?: number | null;\n}\n\nexport interface ImportContext {\n api: ApiClient;\n analysisId: string;\n outputFormat: OutputFormat;\n /** A person is watching a terminal, so the wait may be a line that redraws. */\n live: boolean;\n /** Present when the reader may be asked what to do about an import that is already running. */\n prompter: Prompter | null;\n /**\n * How the end of a followed import is reported off the human format: `stream` writes one JSON\n * line, for a command that goes on streaming a run; `none` leaves it to the caller's own payload.\n */\n machineReport: 'stream' | 'none';\n}\n\n/** The data as it stands once nothing is in flight, and the answer of the upload that led there, if one did. */\nexport interface DataOutcome<T> extends DataImportStatus {\n answer: T | null;\n}\n\n/**\n * The transient lines shown while an import is followed: what is happening, then how far it is.\n * The bar needs the import's own `progress`; a format that cannot count its rows ahead has none, and\n * the platform's sentence, which counts the rows written, stands in for it.\n */\nexport function renderImportBlock(dataImport: DataImport, elapsedMs: number): string[] {\n const title = dataImport.state === 'STOPPING' ? 'Stopping the data import' : 'Importing data';\n const lines = [` ${chalk.cyan(SPINNER)} ${chalk.bold(title)}`];\n const elapsed = chalk.dim(formatDurationPrecise(elapsedMs));\n if (dataImport.state === 'IMPORTING' && dataImport.progress !== null && dataImport.progress !== undefined) {\n lines.push(` ${bar(dataImport.progress)} ${percent(dataImport.progress)} ${elapsed}`);\n } else {\n lines.push(` ${chalk.dim(dataImport.message)} ${elapsed}`);\n }\n return lines;\n}\n\nfunction sleep(ms: number): { done: Promise<'elapsed'>; cancel: () => void } {\n let timer: NodeJS.Timeout;\n const done = new Promise<'elapsed'>((resolve) => { timer = setTimeout(() => resolve('elapsed'), ms); });\n return { done, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Follows an import until it is no longer in flight and returns the poll's last answer: `dataImport`\n * null when the data is in place, otherwise the state it ended in.\n *\n * Ctrl-C ends the waiting, not the import: the platform keeps importing, and the reader is told how\n * to come back to it. A read that fails in passing does not end the wait; a refusal does.\n */\nexport async function followImport(ctx: ImportContext, first: DataImport): Promise<DataImportStatus> {\n const { api, analysisId } = ctx;\n const human = ctx.outputFormat === 'human';\n const startedAt = Date.parse(first.startedAt);\n const since = Number.isFinite(startedAt) ? startedAt : Date.now();\n const status = new Status();\n\n let interrupt: () => void = () => {};\n const interrupted = new Promise<'interrupted'>((resolve) => { interrupt = () => resolve('interrupted'); });\n process.once('SIGINT', interrupt);\n\n if (ctx.live) {\n status.start();\n } else {\n // stderr, so a payload on stdout stays whole.\n console.error('The import is still running on the platform. Waiting for it to finish.');\n }\n\n let current = first;\n try {\n for (;;) {\n if (ctx.live) status.set(renderImportBlock(current, Date.now() - since));\n\n const pause = sleep(IMPORT_POLL_INTERVAL_MS);\n const woke = await Promise.race([pause.done, interrupted]);\n if (woke === 'interrupted') {\n pause.cancel();\n status.stop();\n warn('Stopped waiting. The import keeps running on the platform.');\n hint(`See how far it is with 'diafunc analyze get ${analysisId}'.`);\n hint(`Start the run once it has finished with 'diafunc analyze rerun ${analysisId}'.`);\n process.exit(EXIT_CANCELLED);\n }\n\n let answer: DataImportStatus;\n try {\n answer = await api.analysis.getDataImport(analysisId);\n } catch (error) {\n if (error instanceof ApiError && error.status < 500) throw error;\n continue;\n }\n if (isImporting(answer.dataImport)) {\n current = answer.dataImport;\n continue;\n }\n\n status.stop();\n if (!answer.dataImport) {\n const shape = dataShape(answer.rowCount, answer.columnCount);\n if (human) {\n success(shape ? `Data imported: ${shape}.` : 'Data imported.');\n } else if (ctx.machineReport === 'stream') {\n process.stdout.write(JSON.stringify({\n type: 'import',\n state: 'IMPORTED',\n rowCount: answer.rowCount ?? null,\n columnCount: answer.columnCount ?? null,\n }) + '\\n');\n } else {\n console.error('The import has finished.');\n }\n }\n return { dataImport: answer.dataImport ?? null, rowCount: answer.rowCount ?? null, columnCount: answer.columnCount ?? null };\n }\n } finally {\n status.stop();\n process.off('SIGINT', interrupt);\n }\n}\n\n/**\n * Stops the running import and waits until it has ended. The platform's own wait can end while the\n * writer is still finishing its last batch (`STOPPING`); an upload sent in that window is refused,\n * so the caller gets the answer only when the table is free.\n */\nexport async function stopImport(api: ApiClient, analysisId: string): Promise<DataImportStatus> {\n let answer = await api.analysis.stopDataImport(analysisId);\n while (answer.dataImport?.state === 'STOPPING') {\n await sleep(IMPORT_POLL_INTERVAL_MS).done;\n answer = await api.analysis.getDataImport(analysisId);\n }\n return { dataImport: answer.dataImport ?? null, rowCount: answer.rowCount ?? null, columnCount: answer.columnCount ?? null };\n}\n\n/**\n * The import that is in flight for this analysis, or null. Asked after a refusal, to tell \"another\n * import is running\" apart from every other conflict. A platform that does not know the question\n * has no such import.\n */\nasync function importInFlight(api: ApiClient, analysisId: string): Promise<DataImport | null> {\n try {\n const { dataImport } = await api.analysis.getDataImport(analysisId);\n return isImporting(dataImport) ? dataImport : null;\n } catch {\n return null;\n }\n}\n\n/** The import that stands in the way of a run, in flight or ended, or null. */\nasync function importBlockingRun(api: ApiClient, analysisId: string): Promise<DataImport | null> {\n try {\n const { dataImport } = await api.analysis.getDataImport(analysisId);\n return dataImport?.blocksRun ? dataImport : null;\n } catch {\n return null;\n }\n}\n\nfunction uploadAgainHint(analysisId: string): string {\n return `Upload the data with 'diafunc analyze upload ${analysisId} <file>'.`;\n}\n\n/**\n * Brings the data to rest after an upload or a build answered, or after the wait for another\n * import: follows an import that is still in flight, then reads the state it ended in. An import\n * that ended without the data and blocks a run stops the command with the platform's sentence; one\n * that left the table as it was is a warning, and the command goes on.\n */\nasync function settle<T>(ctx: ImportContext, answer: T | null, data: DataAnswer): Promise<DataOutcome<T>> {\n let status: DataImportStatus = {\n dataImport: data.dataImport ?? null,\n rowCount: data.rowCount ?? null,\n columnCount: data.columnCount ?? null,\n };\n if (isImporting(status.dataImport)) {\n status = await followImport(ctx, status.dataImport);\n }\n const ended = status.dataImport;\n if (ended) {\n if (ended.blocksRun) {\n throw new CliError(ended.message, { hint: uploadAgainHint(ctx.analysisId) });\n }\n warn(ended.message);\n }\n return { ...status, answer };\n}\n\n/**\n * Sends data to the analysis through `send` (an upload or a build) and returns once the data is at\n * rest.\n *\n * When the platform refuses because another import is running, a reader at a terminal chooses\n * between waiting for that import and replacing it: stop it, wait until it has ended, send again.\n * Off a terminal the refusal stands, with the command that stops the import.\n */\nexport async function sendData<T extends DataAnswer>(\n ctx: ImportContext,\n send: () => Promise<T>,\n): Promise<DataOutcome<T>> {\n let answer: T;\n try {\n answer = await send();\n } catch (error) {\n if (!(error instanceof ApiError) || error.status !== 409) throw error;\n const running = await importInFlight(ctx.api, ctx.analysisId);\n if (!running) throw error;\n if (!ctx.prompter) {\n throw new CliError(error.message, {\n hint: `Stop the running import with 'diafunc analyze stop-import ${ctx.analysisId}' and upload again,`\n + ` or wait for it: 'diafunc analyze get ${ctx.analysisId}' shows how far it is.`,\n });\n }\n warn(error.message);\n const stopping = running.state === 'STOPPING';\n const choice = await ctx.prompter.select<'wait' | 'replace'>({\n message: 'What should happen?',\n choices: stopping\n ? [\n { name: 'Upload as soon as the stopped import has ended', value: 'replace' },\n { name: 'Wait for the stopped import to end and upload nothing', value: 'wait' },\n ]\n : [\n { name: 'Wait for the running import to finish and keep its data', value: 'wait' },\n { name: 'Stop the running import and upload again', value: 'replace' },\n ],\n });\n if (choice === 'wait') {\n return settle<T>(ctx, null, { dataImport: running });\n }\n await withStatus('Stopping the running import', () => stopImport(ctx.api, ctx.analysisId));\n answer = await send();\n }\n return settle(ctx, answer, answer);\n}\n\n/**\n * Queues a run. A run is refused while an import stands in its way; that refusal is shown as the\n * platform wrote it, with what the reader can do about it.\n */\nexport async function queueRun(api: ApiClient, analysisId: string): Promise<AnalysisRun> {\n try {\n return await api.analysis.runAnalysis(analysisId);\n } catch (error) {\n if (!(error instanceof ApiError) || error.status !== 409) throw error;\n const blocking = await importBlockingRun(api, analysisId);\n if (!blocking) throw error;\n throw new CliError(error.message, {\n hint: isImporting(blocking)\n ? `Wait for the import to finish: 'diafunc analyze get ${analysisId}' shows how far it is.`\n + ` Then start the run with 'diafunc analyze rerun ${analysisId}'.`\n : uploadAgainHint(analysisId),\n });\n }\n}\n","import type { AnalysisResponse } from '../../client/types/analysis.js';\nimport type { ColumnSpec } from '../../output/columns.js';\nimport { formatDurationPrecise, formatNumber } from '../../output/values.js';\nimport { qualityPercent } from '../../output/progress.js';\nimport { importingLabel, isImporting, verdictLabel, type VerdictReading } from './copy.js';\nimport { expectationLines, focusText, pairText } from './intent.js';\n\n/**\n * What `diafunc analyze get` shows a person: the analysis in the words the web app uses, not the\n * response's property names. `--output json` still prints the response as the platform sent it.\n *\n * Figures a reader cannot act on are folded together: the six optional search constraints become\n * one line, the row and column counts one \"Data\" line, and the three quality figures the response\n * carries become the one the notebook leads with.\n *\n * `verdict` is the validity verdict of the run behind the result ({@link AnalysisResponse.resultRunId}),\n * which the runs carry and the analysis does not. A result that is not valid shows no quality, and one\n * that needs review shows it marked, as the report's top does.\n */\nexport function analysisDetails(\n analysis: AnalysisResponse,\n endpoint: string,\n verdict: VerdictReading | null = null,\n): { data: Record<string, unknown>; columns: ColumnSpec[] } {\n const data: Record<string, unknown> = {\n analysisId: analysis.analysisId,\n name: analysis.name,\n description: analysis.description,\n visibility: sentenceCase(analysis.visibility),\n license: licenseText(analysis),\n introduction: analysis.introduction,\n data: dataShape(analysis.rowCount, analysis.columnCount),\n dataImport: analysis.dataImport?.message ?? null,\n targets: analysis.targets,\n targetKinds: analysis.targetKinds && Object.keys(analysis.targetKinds).length > 0\n ? analysis.targetKinds\n : 'detected from the data',\n inputExclusions: analysis.inputExclusions,\n confirmedInputs: analysis.confirmedInputs,\n questions: analysis.questions,\n segment: analysis.segment,\n // The platform sends the notes to their owner only; for anyone else they are null and the line is empty.\n intent: analysis.intent ?? null,\n expectations: joinedLines(expectationLines(analysis.shapeExpectations)),\n charts: joinedLines((analysis.requestedPairs ?? []).map(pairText)),\n focus: joinedLines((analysis.focusFamilies ?? []).map(focusText)),\n hours: hoursText(analysis.hours),\n budget: creditsText(analysis.budget),\n constraints: constraintsText(analysis),\n notifyByEmail: analysis.notifyByEmail == null ? 'account default' : analysis.notifyByEmail ? 'yes' : 'no',\n // While the data is still arriving no run can start, so the import is what the analysis is doing.\n latestRunState: isImporting(analysis.dataImport)\n ? importingLabel(analysis.dataImport)\n : analysis.latestRunState ? sentenceCase(analysis.latestRunState) : null,\n latestRunId: analysis.latestRunId,\n quality: qualityText(analysis, verdict),\n validity: verdict ? verdictLabel(verdict) : null,\n targetResults: targetResultsText(analysis),\n resultRunId: analysis.resultRunId,\n creditsUsed: creditsText(analysis.creditsUsed),\n notebook: analysis.labUrl ? `${endpoint}${analysis.labUrl}` : null,\n projectId: analysis.projectId,\n parentAnalysisId: analysis.parentAnalysisId,\n createdAt: analysis.createdAt,\n modifiedAt: analysis.modifiedAt,\n };\n const columns: ColumnSpec[] = [\n { key: 'analysisId', header: 'Analysis ID', kind: 'id' },\n { key: 'name', header: 'Name' },\n { key: 'description', header: 'Description' },\n { key: 'visibility', header: 'Visibility' },\n { key: 'license', header: 'License' },\n { key: 'introduction', header: 'Introduction' },\n { key: 'data', header: 'Data' },\n { key: 'dataImport', header: 'Data import' },\n { key: 'targets', header: 'Targets' },\n { key: 'targetKinds', header: 'Target kinds' },\n { key: 'inputExclusions', header: 'Columns left out as inputs' },\n { key: 'confirmedInputs', header: 'Known before the target' },\n { key: 'questions', header: 'Questions' },\n { key: 'segment', header: 'Segment' },\n { key: 'intent', header: 'Your notes' },\n { key: 'expectations', header: 'Expectations' },\n { key: 'charts', header: 'Charts you asked for' },\n { key: 'focus', header: 'Focus' },\n { key: 'hours', header: 'Time limit' },\n { key: 'budget', header: 'Credit budget' },\n { key: 'constraints', header: 'Constraints' },\n { key: 'notifyByEmail', header: 'Email when done' },\n { key: 'latestRunState', header: 'Latest run', kind: 'state' },\n { key: 'latestRunId', header: 'Latest run ID', kind: 'id' },\n { key: 'quality', header: 'Quality' },\n { key: 'validity', header: 'Validity' },\n { key: 'targetResults', header: 'Target results' },\n { key: 'resultRunId', header: 'Result from run', kind: 'id' },\n { key: 'creditsUsed', header: 'Credits used' },\n { key: 'notebook', header: 'Notebook' },\n { key: 'projectId', header: 'Project ID', kind: 'id' },\n { key: 'parentAnalysisId', header: 'Refined from', kind: 'id' },\n { key: 'createdAt', header: 'Created', kind: 'date' },\n { key: 'modifiedAt', header: 'Modified', kind: 'date' },\n ];\n return { data, columns };\n}\n\nfunction joinedLines(lines: string[]): string | null {\n return lines.length > 0 ? lines.join('\\n') : null;\n}\n\n/**\n * The license the project is published under. A public analysis without one says so, since what a\n * reader may do with it then rests on the owner alone; a private one shows a license only when it\n * keeps one for a later publication.\n */\nfunction licenseText(analysis: AnalysisResponse): string | null {\n if (analysis.licenceId) return analysis.licenceId;\n return analysis.visibility === 'PUBLIC' ? 'none chosen' : null;\n}\n\n/** `PUBLIC` -> `Public`: a state or a visibility is a word to a reader, not an enum token. */\nfunction sentenceCase(token: string): string {\n const words = token.toLowerCase().replace(/_/g, ' ');\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\nfunction hoursText(hours: string | null | undefined): string | null {\n if (hours == null || hours === '') return null;\n const n = Number(hours);\n if (!Number.isFinite(n)) return hours;\n return `${formatNumber(n)} ${n === 1 ? 'hour' : 'hours'}`;\n}\n\nfunction creditsText(credits: string | number | null | undefined): string | null {\n if (credits == null || credits === '') return null;\n const n = Number(credits);\n if (!Number.isFinite(n)) return String(credits);\n return `${formatNumber(n)} ${n === 1 ? 'credit' : 'credits'}`;\n}\n\nexport function dataShape(rows: number | null | undefined, columns: number | null | undefined): string | null {\n if (rows == null && columns == null) return null;\n const parts: string[] = [];\n if (rows != null) parts.push(`${formatNumber(rows)} ${rows === 1 ? 'row' : 'rows'}`);\n if (columns != null) parts.push(`${formatNumber(columns)} ${columns === 1 ? 'column' : 'columns'}`);\n return parts.join(' × ');\n}\n\n/**\n * The figure the notebook leads with. An analysis whose data was too small to hold rows back has\n * only the quality its search recorded on the rows it trained on, and says so.\n */\nfunction qualityText(analysis: AnalysisResponse, verdict: VerdictReading | null): string | null {\n if (verdict?.validity === 'not_valid') return 'not shown: the result is not valid';\n const figure = analysis.heldOutQuality != null\n ? qualityPercent(analysis.heldOutQuality) + rowsText(analysis.heldOutRows, analysis.searchRows)\n : analysis.resultRunQuality != null ? `${qualityPercent(analysis.resultRunQuality)} on the training rows`\n : null;\n if (figure == null) return null;\n return verdict?.validity === 'needs_review' ? `${figure}, needs review` : figure;\n}\n\nfunction targetResultsText(analysis: AnalysisResponse): string | null {\n const results = analysis.targetResults ?? [];\n if (results.length === 0) return null;\n const lines = results.map((r) => {\n const name = r.title ?? r.target ?? 'target';\n return r.quality != null ? `${name}: ${qualityPercent(r.quality)}${rowsText(r.heldOutRows, r.searchRows)}` : name;\n });\n const more = (analysis.targetResultCount ?? results.length) - results.length;\n if (more > 0) lines.push(`and ${formatNumber(more)} more`);\n return lines.join('\\n');\n}\n\n/**\n * \" on 10 held-out rows, found on 30 rows\": the rows a held-out quality was measured on and its model\n * found on, as far as the platform reports them; empty for a platform or a result without the counts.\n */\nexport function rowsText(heldOutRows: number | null | undefined, searchRows: number | null | undefined): string {\n if (heldOutRows == null || !(heldOutRows > 0)) return '';\n const measured = ` on ${formatNumber(heldOutRows)} held-out ${heldOutRows === 1 ? 'row' : 'rows'}`;\n return searchRows != null && searchRows > 0\n ? `${measured}, found on ${formatNumber(searchRows)} ${searchRows === 1 ? 'row' : 'rows'}`\n : measured;\n}\n\n/** An error bound as a percentage, the scale the quality next to it is printed on. */\nfunction errorPercent(error: number): string {\n return `${formatNumber(Math.round(error * 1000) / 10)}%`;\n}\n\n/** The optional search constraints, as one line: only the ones the analysis sets. */\nfunction constraintsText(analysis: AnalysisResponse): string {\n const parts: string[] = [];\n if (analysis.minComplexity != null) parts.push(`complexity at least ${formatNumber(analysis.minComplexity)}`);\n if (analysis.maxComplexity != null) parts.push(`complexity at most ${formatNumber(analysis.maxComplexity)}`);\n if (analysis.stopAtComplexity != null) parts.push(`aim for complexity ${formatNumber(analysis.stopAtComplexity)}`);\n if (analysis.stopAtQuality != null) parts.push(`stop at quality ${qualityPercent(analysis.stopAtQuality)}`);\n if (analysis.stopAtError != null) parts.push(`stop at error ${errorPercent(analysis.stopAtError)}`);\n if (analysis.minMilliseconds != null) parts.push(`search at least ${formatDurationPrecise(analysis.minMilliseconds)}`);\n return parts.length > 0 ? parts.join(', ') : 'none';\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { ApiClient } from '../../client/api.js';\nimport type { AnalysisDataBuild, CombinedPlan, CombinedRecipe } from '../../client/types/analysis.js';\nimport { ApiError } from '../../client/errors.js';\nimport { CliError, EXIT_USAGE } from '../../util/errors.js';\nimport { detail, hint, warn } from '../../output/messages.js';\nimport { withStatus } from '../../output/progress.js';\n\n/** What the caller chose about a table stacked from several files. */\nexport interface StackChoices {\n /** Add the column that records the file each row came from. */\n fileColumn: boolean;\n /** Keep rows that occur in more than one file, instead of importing them once. */\n keepDuplicates: boolean;\n /** The file that carries the rows, where the files can be read two ways; undefined takes the proposal. */\n rowsOf?: string;\n /** Store the files and print the plan, but build nothing. */\n planOnly?: boolean;\n /** Files to read exactly as they are, without the reshape their shape suggests. */\n asUploaded?: string[];\n}\n\n/** The findings a reader should stop at, as opposed to the ones that only say what was done. */\nconst CAUTIONS = new Set(['UNEVEN_COLUMNS', 'TYPE_CONFLICT', 'SOURCE_WARNING', 'LEFT_OUT', 'POSSIBLE_KEY',\n 'MANY_TO_MANY', 'NO_KEY', 'TOO_LARGE', 'HINT_REJECTED', 'RESHAPE_REFUSED']);\n\n/**\n * The platform's proposal with the caller's choices applied, or null when they already agree with\n * it. A single table has no file column and nothing to deduplicate against, so its proposal stands.\n */\nexport function recipeWithChoices(proposal: CombinedRecipe, choices: StackChoices): CombinedRecipe | null {\n if (proposal.parts.length < 2) return null;\n const originColumn = choices.fileColumn ? proposal.originColumn : null;\n const dropDuplicates = !choices.keepDuplicates;\n if (originColumn === proposal.originColumn && dropDuplicates === proposal.dropDuplicates) return null;\n return { parts: proposal.parts, originColumn, dropDuplicates, lookups: proposal.lookups ?? [] };\n}\n\n/** A file's name as a plan labels it: without directory and extension, case folded. */\nfunction labelOf(file: string): string {\n return path.basename(file, path.extname(file)).trim().toLowerCase();\n}\n\n/** The file that would carry the rows under the other reading of the proposal's files, or null when there is none. */\nexport function otherRowsLabel(proposal: CombinedPlan): string | null {\n const alternative = (proposal.lookups ?? []).find(lookup => lookup.alternative)?.alternative;\n return alternative && alternative.parts.length > 0 ? alternative.parts[0].label : null;\n}\n\n/**\n * The recipe in which `rowsOf` carries the rows: null when the proposal already reads the files that\n * way, the proposal's alternative when that is the reading asked for. A name that fits neither\n * reading is a usage error, because nothing the platform measured has that file as the rows.\n */\nexport function recipeWithRowsOf(proposal: CombinedPlan, rowsOf: string): CombinedRecipe | null {\n const wanted = labelOf(rowsOf);\n if (proposal.recipe.parts.some(part => part.label.trim().toLowerCase() === wanted)) return null;\n const alternative = (proposal.lookups ?? []).find(lookup => lookup.alternative)?.alternative;\n if (alternative && alternative.parts.some(part => part.label.trim().toLowerCase() === wanted)) return alternative;\n const rows = proposal.recipe.parts.map(part => part.label).join(', ');\n throw new CliError(`${rowsOf} cannot carry the rows of this table.`, {\n exitCode: EXIT_USAGE,\n hint: alternative\n ? `The rows can come from ${rows} or from ${alternative.parts.map(part => part.label).join(', ')}.`\n : `These files have one reading: the rows come from ${rows}.`,\n });\n}\n\n/**\n * The stored sources among `uploaded` that `asUploaded` names, by file name with or without its\n * directory and extension. A name that matches no file is a usage error: silently reshaping a file\n * the caller asked to keep as it is would be worse than stopping.\n */\nexport function sourcesAsUploaded<T extends { fileName: string }>(uploaded: T[], asUploaded: string[]): T[] {\n const chosen: T[] = [];\n for (const name of asUploaded) {\n const wanted = path.basename(name).trim().toLowerCase();\n const matches = uploaded.filter(source => {\n const fileName = source.fileName.trim().toLowerCase();\n return fileName === wanted || labelOf(fileName) === labelOf(wanted);\n });\n if (matches.length === 0) {\n throw new CliError(`--as-uploaded names ${name}, which is not among the files.`, {\n exitCode: EXIT_USAGE,\n hint: `The files are: ${uploaded.map(source => source.fileName).join(', ')}.`,\n });\n }\n for (const match of matches) {\n if (!chosen.includes(match)) chosen.push(match);\n }\n }\n return chosen;\n}\n\n/** Whether a recipe reads any of its tables through a reshape. */\nexport function readsReshaped(recipe: CombinedRecipe): boolean {\n const parts = [...recipe.parts, ...(recipe.lookups ?? []).flatMap(lookup => lookup.parts)];\n return parts.some(part => (part.reshapes ?? []).length > 0);\n}\n\n/**\n * After a single file was uploaded as it is: asks the platform whether anything was noticed about\n * the file's shape and, only then, whether the file should be read\n * differently (a column per year as a row per year, a header over several rows, several numbers in\n * one cell) and, when it proposes that, says so and builds the data that way. Returns null when\n * the file is one row per observation already, or when the platform cannot say.\n */\nexport async function reshapeSingle(api: ApiClient, analysisId: string, human: boolean): Promise<AnalysisDataBuild | null> {\n let plan: CombinedPlan;\n try {\n // The cheap question first: it reads the first rows only, where a plan reads the whole file.\n if ((await api.analysis.sourceShapes(analysisId)).length === 0) return null;\n plan = await withStatus('Reading how the file should be read', () => api.analysis.planSources(analysisId, null));\n } catch (error) {\n // A format that cannot be read as rows has no plan, and an older platform no such question; the upload itself stands.\n if (error instanceof ApiError && error.status >= 400 && error.status < 500 && error.status !== 401 && error.status !== 403) {\n return null;\n }\n throw error;\n }\n if (!readsReshaped(plan.recipe)) return null;\n if (human) {\n for (const finding of plan.findings) {\n if (finding.kind === 'RESHAPED') detail(finding.message);\n }\n hint('The reshape is a function in the analysis\\'s project and can be changed in the Lab. To read the file exactly as it is, add --as-uploaded.');\n }\n return withStatus('Building the data from the reshaped file', () => api.analysis.buildSources(analysisId, plan.recipe));\n}\n\n/** The plan as lines for the terminal: the result first, then each finding, cautions marked. */\nexport function planLines(plan: CombinedPlan): { text: string; caution: boolean }[] {\n const lines = [{\n text: `One table of ${plan.rows.toLocaleString('en-US')} rows and ${plan.columns.toLocaleString('en-US')} columns.`,\n caution: false,\n }];\n for (const finding of plan.findings) {\n lines.push({ text: finding.message, caution: CAUTIONS.has(finding.kind) });\n }\n return lines;\n}\n\nfunction multipart(file: string): FormData {\n const formData = new FormData();\n formData.append('content', new Blob([fs.readFileSync(file)]), path.basename(file));\n return formData;\n}\n\n/**\n * Makes `files` the analysis's data: stores each as a source (replacing the sources the analysis\n * held), asks the platform how they fit together, prints that plan, and builds the one table.\n *\n * Every file is checked to exist before anything is sent, so a typo does not leave half the files\n * uploaded. A file the platform cannot combine fails the plan with the platform's own message.\n */\nexport async function uploadSeveral(api: ApiClient, analysisId: string, files: string[], choices: StackChoices,\n human: boolean): Promise<AnalysisDataBuild> {\n for (const file of files) {\n if (!fs.existsSync(file)) {\n throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });\n }\n }\n for (const earlier of await api.analysis.listSources(analysisId)) {\n await api.analysis.removeSource(analysisId, earlier.sourceId);\n }\n const uploaded = [];\n for (const file of files) {\n uploaded.push(await withStatus(`Uploading ${path.basename(file)}`, () => api.analysis.addSource(analysisId, multipart(file))));\n }\n for (const source of sourcesAsUploaded(uploaded, choices.asUploaded ?? [])) {\n await api.analysis.updateSource(analysisId, source.sourceId, { asUploaded: true });\n }\n let other: string | null = null;\n const plan = await withStatus('Reading the files together', async () => {\n const proposal = await api.analysis.planSources(analysisId, null);\n const exchanged = choices.rowsOf ? recipeWithRowsOf(proposal, choices.rowsOf) : null;\n if (exchanged) {\n other = proposal.recipe.parts[0]?.label ?? null;\n return api.analysis.planSources(analysisId, exchanged);\n }\n other = otherRowsLabel(proposal);\n const chosen = recipeWithChoices(proposal.recipe, choices);\n return chosen ? api.analysis.planSources(analysisId, chosen) : proposal;\n });\n if (human) {\n for (const line of planLines(plan)) {\n if (line.caution) warn(line.text);\n else detail(line.text);\n }\n if (readsReshaped(plan.recipe)) {\n hint('A reshape is a function in the analysis\\'s project and can be changed in the Lab. To read a file exactly as it is, add --as-uploaded <file>.');\n }\n if (other) {\n hint(`These files can be read two ways. For one row per row of ${other}, add --rows-of ${other}.`);\n }\n }\n if (choices.planOnly) {\n if (human) hint('Plan only: the files are stored with the analysis and nothing was built.');\n return { plan, rowCount: null, columnCount: null };\n }\n const tables = plan.recipe.parts.length + (plan.recipe.lookups ?? []).reduce((sum, lookup) => sum + lookup.parts.length, 0);\n return withStatus(`Building one table from ${tables} file${tables === 1 ? '' : 's'}`,\n () => api.analysis.buildSources(analysisId, plan.recipe));\n}\n","import { Command } from 'commander';\nimport { loadConfig, resolveEndpoint } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport type { AnalysisService } from '../../client/services/analysis.js';\nimport type { AnalysisRun, PublicAnalysis } from '../../client/types/analysis.js';\nimport { CliError, EXIT_USAGE, handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, heading, hint } from '../../output/messages.js';\nimport { analysisDetails } from '../analyze/details.js';\nimport { runPhaseCell } from '../analyze/copy.js';\n\n/** The page sizes the platform accepts on the public listing. */\nexport const MIN_LIMIT = 1;\nexport const MAX_LIMIT = 500;\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function parseLimit(value: string): number {\n const limit = Number(value);\n if (!Number.isInteger(limit) || limit < MIN_LIMIT || limit > MAX_LIMIT) {\n throw new CliError(\n `Invalid limit \"${value}\". Expected a whole number from ${MIN_LIMIT} to ${MAX_LIMIT}.`,\n { exitCode: EXIT_USAGE },\n );\n }\n return limit;\n}\n\n/** A calendar date, or a date and time that names its zone: a bare local time would mean a different instant per machine. */\nconst ISO_INSTANT = /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2}))?$/;\n\n/** The instant `--changed-since` names, as epoch milliseconds. */\nexport function parseChangedSince(value: string): number {\n const text = value.trim();\n const instant = ISO_INSTANT.test(text) ? Date.parse(text) : Number.NaN;\n if (!Number.isFinite(instant)) {\n throw new CliError(\n `Invalid timestamp \"${value}\". Expected ISO-8601, such as 2026-10-01 or 2026-10-01T08:30:00Z.`,\n { exitCode: EXIT_USAGE },\n );\n }\n return instant;\n}\n\n/**\n * An instant of the listing as epoch milliseconds. The platform sends a number; a text is parsed as\n * ISO-8601. Anything else is NaN, which no `--changed-since` admits.\n */\nexport function instantMillis(value: unknown): number {\n if (typeof value === 'number') return value;\n return typeof value === 'string' ? Date.parse(value) : Number.NaN;\n}\n\nexport interface PublicListing {\n analyses: PublicAnalysis[];\n /** Where a later call continues; null when the listing was read to its end. */\n nextCursor: string | null;\n}\n\n/**\n * Reads one page of the public analyses, or with `all` every page from `cursor` on.\n *\n * `changedSince` is applied here, to each page as it arrives: the platform lists everything and a\n * client compares two listings itself, so the cursor still walks the whole listing.\n */\nexport async function readPublicAnalyses(\n analysis: Pick<AnalysisService, 'listPublic'>,\n options: { limit: number; cursor?: string; all?: boolean; changedSince?: number },\n): Promise<PublicListing> {\n const analyses: PublicAnalysis[] = [];\n const seen = new Set<string>();\n let cursor = options.cursor;\n for (;;) {\n const page = await analysis.listPublic({ cursor, limit: options.limit });\n for (const entry of page.analyses ?? []) {\n if (options.changedSince === undefined || instantMillis(entry.changedAt) >= options.changedSince) {\n analyses.push(entry);\n }\n }\n const next = page.nextCursor ?? null;\n if (!options.all || next === null) return { analyses, nextCursor: next };\n // A cursor that comes back a second time would be followed forever.\n if (seen.has(next)) {\n throw new CliError(`The platform returned the cursor \"${next}\" twice; stopped after ${analyses.length} analyses.`);\n }\n seen.add(next);\n cursor = next;\n }\n}\n\ninterface ListOptions {\n limit: string;\n cursor?: string;\n all?: boolean;\n changedSince?: string;\n}\n\nasync function listPublicAnalyses(options: ListOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const limit = parseLimit(options.limit);\n const changedSince = options.changedSince === undefined ? undefined : parseChangedSince(options.changedSince);\n const api = createApiClient();\n const listing = await readPublicAnalyses(api.analysis, {\n limit, cursor: options.cursor, all: options.all, changedSince,\n });\n\n if (outputFormat === 'json') {\n // The cursor travels with the rows, so a script can continue where this call stopped.\n format(listing, { format: outputFormat });\n return;\n }\n if (listing.analyses.length === 0 && outputFormat === 'human') {\n empty('public analyses');\n } else {\n format(listing.analyses, {\n format: outputFormat,\n columns: [\n { key: 'analysisId', kind: 'id' },\n { key: 'projectId', kind: 'id' },\n { key: 'publishedAt', header: 'published', kind: 'date' },\n { key: 'changedAt', header: 'changed', kind: 'date' },\n { key: 'licenceId', header: 'license' },\n ],\n });\n }\n if (listing.nextCursor !== null) {\n hint(`More public analyses follow. Continue with --cursor ${listing.nextCursor}, or pass --all.`);\n }\n}\n\nfunction newestRunRecord(run: AnalysisRun): Record<string, unknown> {\n return {\n runId: run.runId,\n state: run.state,\n phase: runPhaseCell(run),\n submittedAt: run.submittedAt,\n startedAt: run.startedAt,\n endedAt: run.endedAt,\n };\n}\n\nasync function showPublicAnalysis(analysisId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const result = await api.analysis.get(analysisId);\n if (!result?.analysis) {\n throw new CliError(`No public analysis \"${analysisId}\".`, {\n hint: `List the public analyses with 'diafunc public list'.`,\n });\n }\n // The runs come newest first, so one is the newest.\n const runs = await api.analysis.getRunsForAnalysis(analysisId, 1);\n const newestRun = runs?.[0] ?? null;\n\n if (outputFormat === 'json') {\n format({ analysis: result.analysis, newestRun }, { format: outputFormat });\n return;\n }\n if (outputFormat === 'table') {\n format({\n ...result.analysis,\n newestRunId: newestRun?.runId ?? null,\n newestRunState: newestRun?.state ?? null,\n newestRunSubmittedAt: newestRun?.submittedAt ?? null,\n newestRunStartedAt: newestRun?.startedAt ?? null,\n newestRunEndedAt: newestRun?.endedAt ?? null,\n }, { format: outputFormat });\n return;\n }\n\n const details = analysisDetails(result.analysis, resolveEndpoint(loadConfig()));\n format(details.data, { format: outputFormat, columns: details.columns });\n heading('Newest run');\n if (!newestRun) {\n empty('runs');\n return;\n }\n format(newestRunRecord(newestRun), {\n format: outputFormat,\n columns: [\n { key: 'runId', header: 'Run ID', kind: 'id' },\n { key: 'state', header: 'State', kind: 'state' },\n { key: 'phase', header: 'Phase' },\n { key: 'submittedAt', header: 'Submitted', kind: 'date' },\n { key: 'startedAt', header: 'Started', kind: 'date' },\n { key: 'endedAt', header: 'Ended', kind: 'date' },\n ],\n });\n}\n\nexport function registerPublicCommands(program: Command): void {\n const pub = program\n .command('public')\n .description('Read the analyses their owners made public (no sign-in needed)')\n .addHelpText('after', `\nExamples:\n $ diafunc public list the first 100 public analyses\n $ diafunc public list --all --output json every one of them, for a script\n $ diafunc public list --all --changed-since 2026-10-01 only those changed since that day\n $ diafunc public show <analysisId> one analysis and its newest run\n`);\n\n pub\n .command('list')\n .description('List public analyses')\n .option('--limit <n>', `Analyses per page (${MIN_LIMIT} to ${MAX_LIMIT})`, '100')\n .option('--cursor <c>', 'Continue from the cursor an earlier call ended with')\n .option('--all', 'Follow the pages to the end of the listing')\n .option('--changed-since <ISO-8601>', 'Only analyses changed at or after this date or instant')\n .action(async (options: ListOptions, cmd: Command) => {\n try {\n await listPublicAnalyses(options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n pub\n .command('show')\n .description('Show a public analysis and its newest run')\n .argument('<analysisId>', 'Analysis ID')\n .action(async (analysisId: string, _options, cmd: Command) => {\n try {\n await showPublicAnalysis(analysisId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { ApiError } from '../../client/errors.js';\nimport type { License, LicenseCatalogEntry } from '../../client/types/admin.js';\nimport { CliError, handleError } from '../../util/errors.js';\nimport { hiddenAlias } from '../../util/hidden-aliases.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, success } from '../../output/messages.js';\nimport { confirmDestructive } from '../../util/confirm.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/** What each permission of a license is marked with in `license list`, in reading order. */\nexport const LICENSE_MARKS: readonly { mark: string; flag: keyof License; meaning: string }[] = [\n { mark: 'C', flag: 'commercialUse', meaning: 'commercial use' },\n { mark: 'D', flag: 'derivatives', meaning: 'adaptations and forks' },\n { mark: 'R', flag: 'redistribution', meaning: 'redistribution' },\n { mark: 'BY', flag: 'attributionRequired', meaning: 'attribution required' },\n { mark: 'SA', flag: 'shareAlike', meaning: 'share-alike' },\n];\n\n/** The marks of the flags a license sets, `C D R BY`; null when it sets none, as a view-only license. */\nexport function licenseMarks(license: License): string | null {\n const marks = LICENSE_MARKS.filter(({ flag }) => license[flag] === true).map(({ mark }) => mark);\n return marks.length > 0 ? marks.join(' ') : null;\n}\n\n/** `ACTIVE` -> `active`: a state is a word to a reader. */\nfunction stateWord(state: string): string {\n return state.toLowerCase();\n}\n\n/**\n * The five permission flags from marks as `license list` prints them (`C D R BY`, any order, any case);\n * `none` for a license that allows nothing beyond viewing.\n */\nexport function flagsFromMarks(marks: string): Pick<License, 'commercialUse' | 'derivatives' | 'redistribution'\n | 'attributionRequired' | 'shareAlike'> {\n const given = marks.trim().toUpperCase().split(/[\\s,]+/).filter((m) => m.length > 0);\n const known = new Set(LICENSE_MARKS.map(({ mark }) => mark));\n const unknown = given.filter((m) => m !== 'NONE' && !known.has(m));\n if (unknown.length > 0 || (given.includes('NONE') && given.length > 1) || given.length === 0) {\n throw new CliError(`Unknown flags \"${marks}\".`, {\n hint: `Use any of ${LICENSE_MARKS.map(({ mark }) => mark).join(', ')} (for example \"C D R BY\"), or \"none\".`,\n });\n }\n return {\n commercialUse: given.includes('C'),\n derivatives: given.includes('D'),\n redistribution: given.includes('R'),\n attributionRequired: given.includes('BY'),\n shareAlike: given.includes('SA'),\n };\n}\n\nfunction parseSortOrder(value: string | undefined): number | null | undefined {\n if (value === undefined) return undefined;\n if (value === '') return null;\n const order = Number(value);\n if (!Number.isInteger(order)) {\n throw new CliError(`--sort-order must be a whole number, not \"${value}\".`);\n }\n return order;\n}\n\nfunction parseBool(name: string, value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n if (value === 'true' || value === 'false') return value === 'true';\n throw new CliError(`${name} must be true or false, not \"${value}\".`);\n}\n\nasync function catalogEntry(licenseId: string): Promise<LicenseCatalogEntry> {\n const entries = await createApiClient().admin.listLicenseCatalog();\n const entry = entries.find((e) => e.licence.licenceId === licenseId);\n if (!entry) {\n throw new CliError(`No license \"${licenseId}\" in the catalog.`, {\n hint: `List every entry, withdrawn ones included, with 'diafunc license catalog'.`,\n });\n }\n return entry;\n}\n\nfunction printLicense(license: License, cmd: Command, verb: string): void {\n const outputFormat = getOutputFormat(cmd);\n if (outputFormat !== 'human') {\n format(license, { format: outputFormat });\n return;\n }\n success(`License \"${license.licenceId}\" ${verb} (${stateWord(license.state)}, flags ${licenseMarks(license) ?? 'none'}).`);\n}\n\nasync function listCatalog(cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const entries = await createApiClient().admin.listLicenseCatalog();\n if (outputFormat === 'json') {\n format(entries, { format: outputFormat });\n return;\n }\n if (entries.length === 0 && outputFormat === 'human') {\n empty('licenses');\n return;\n }\n format(entries.map((e) => ({\n licenceId: e.licence.licenceId,\n name: e.licence.name,\n state: stateWord(e.licence.state),\n flags: licenseMarks(e.licence),\n recommended: e.licence.recommended,\n publicProjects: e.publicProjects,\n sortOrder: e.licence.sortOrder,\n })), {\n format: outputFormat,\n columns: [\n { key: 'licenceId', header: 'id' },\n { key: 'name' },\n { key: 'state', kind: 'state' },\n { key: 'flags' },\n { key: 'recommended', kind: 'boolean' },\n { key: 'publicProjects', header: 'public projects' },\n { key: 'sortOrder', header: 'order' },\n ],\n });\n}\n\nasync function listLicenses(cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const licenses = await api.admin.listLicenses();\n\n if (outputFormat === 'json') {\n format(licenses, { format: outputFormat });\n return;\n }\n if (licenses.length === 0 && outputFormat === 'human') {\n empty('licenses');\n return;\n }\n format(licenses.map((l) => ({\n licenceId: l.licenceId,\n name: l.name,\n state: stateWord(l.state),\n flags: licenseMarks(l),\n recommended: l.recommended,\n })), {\n format: outputFormat,\n columns: [\n { key: 'licenceId', header: 'id' },\n { key: 'name' },\n { key: 'state', kind: 'state' },\n { key: 'flags' },\n { key: 'recommended', kind: 'boolean' },\n ],\n });\n if (outputFormat === 'human') {\n // A note, not data: on stderr, so piped rows stay rows.\n console.error(chalk.dim(\n `\\nFlags: ${LICENSE_MARKS.map(({ mark, meaning }) => `${mark} ${meaning}`).join(', ')}. `\n + 'A deprecated license stays on the projects that carry it and cannot be chosen.',\n ));\n }\n}\n\nasync function showLicense(licenseId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n let license: License;\n try {\n license = await api.admin.getLicense(licenseId);\n } catch (error) {\n if (error instanceof ApiError && error.status === 404) {\n throw new CliError(`No license \"${licenseId}\" in the catalog.`, {\n hint: `List the licenses with 'diafunc license list'.`,\n });\n }\n throw error;\n }\n\n if (outputFormat !== 'human') {\n format(license, { format: outputFormat });\n return;\n }\n format({\n licenceId: license.licenceId,\n name: license.name,\n state: stateWord(license.state),\n summary: license.summary,\n url: license.url,\n commercialUse: license.commercialUse,\n derivatives: license.derivatives,\n redistribution: license.redistribution,\n attributionRequired: license.attributionRequired,\n shareAlike: license.shareAlike,\n recommended: license.recommended,\n }, {\n format: outputFormat,\n columns: [\n { key: 'licenceId', header: 'ID', kind: 'id' },\n { key: 'name', header: 'Name' },\n { key: 'state', header: 'State', kind: 'state' },\n { key: 'summary', header: 'Summary' },\n { key: 'url', header: 'License text' },\n { key: 'commercialUse', header: 'Commercial use', kind: 'boolean' },\n { key: 'derivatives', header: 'Adaptations and forks', kind: 'boolean' },\n { key: 'redistribution', header: 'Redistribution', kind: 'boolean' },\n { key: 'attributionRequired', header: 'Attribution required', kind: 'boolean' },\n { key: 'shareAlike', header: 'Share-alike', kind: 'boolean' },\n { key: 'recommended', header: 'Recommended', kind: 'boolean' },\n ],\n });\n}\n\nexport function registerLicenseCommands(program: Command): void {\n const license = hiddenAlias(program.command('license'), 'licence')\n .description('The licenses a public project can be published under (reading needs no sign-in; managing the catalog is for administrators)')\n .addHelpText('after', `\nExamples:\n $ diafunc license list the licenses that can be chosen\n $ diafunc license show CC-BY-4.0 one license and what it allows\n $ diafunc license catalog administrators: every entry, with its public projects\n $ diafunc license create CC-BY-3.0 --name \"Creative Commons Attribution 3.0\" --flags \"C D R BY\"\n $ diafunc license deprecate CC-BY-3.0 administrators: stop offering it\n $ diafunc project create --visibility PUBLIC --license CC-BY-4.0\n $ diafunc analyze visibility <id> PUBLIC --license CC0-1.0\n`);\n\n license\n .command('list')\n .description('List the license catalog: the active and the deprecated licenses, in catalog order')\n .action(async (_options, cmd: Command) => {\n try {\n await listLicenses(cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('show')\n .description('Show one license, in any state, and what it allows')\n .argument('<licenseId>', 'License ID (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)')\n .action(async (licenseId: string, _options, cmd: Command) => {\n try {\n await showLicense(licenseId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('catalog')\n .description('Administrators: every catalog entry, withdrawn ones included, with the number of public projects that carry it')\n .action(async (_options, cmd: Command) => {\n try {\n await listCatalog(cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('create')\n .description('Administrators: add a license to the catalog (active from the start)')\n .argument('<licenseId>', 'SPDX identifier where one exists (CC-BY-3.0), an own slug otherwise; never changes')\n .requiredOption('--name <name>', 'Full name')\n .requiredOption('--flags <marks>', 'What it allows: any of C D R BY SA (commercial use, adaptations, redistribution, attribution required, share-alike), or \"none\"')\n .option('--url <url>', 'Address of the license text')\n .option('--summary <text>', 'One or two sentences shown where a license is chosen')\n .option('--recommended', 'Show it in the short list where a license is chosen')\n .option('--sort-order <n>', 'Position in the list; without one it comes last')\n .action(async (licenseId: string, options, cmd: Command) => {\n try {\n const created = await createApiClient().admin.createLicense({\n licenceId: licenseId,\n name: options.name,\n summary: options.summary ?? null,\n url: options.url ?? null,\n state: 'ACTIVE',\n ...flagsFromMarks(options.flags),\n recommended: !!options.recommended,\n sortOrder: parseSortOrder(options.sortOrder) ?? null,\n });\n printLicense(created, cmd, 'created');\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('update')\n .description('Administrators: change a catalog entry; what is not given stays as it is')\n .argument('<licenseId>', 'License ID')\n .option('--name <name>', 'Full name')\n .option('--flags <marks>', 'What it allows: any of C D R BY SA, or \"none\"')\n .option('--url <url>', 'Address of the license text; an empty value clears it')\n .option('--summary <text>', 'Shown where a license is chosen; an empty value clears it')\n .option('--recommended <bool>', 'Show it in the short list (true/false)')\n .option('--sort-order <n>', 'Position in the list; an empty value clears it')\n .action(async (licenseId: string, options, cmd: Command) => {\n try {\n const current = (await catalogEntry(licenseId)).licence;\n const sortOrder = parseSortOrder(options.sortOrder);\n const recommended = parseBool('--recommended', options.recommended);\n const updated = await createApiClient().admin.updateLicense({\n ...current,\n ...(options.name !== undefined ? { name: options.name } : {}),\n ...(options.url !== undefined ? { url: options.url || null } : {}),\n ...(options.summary !== undefined ? { summary: options.summary || null } : {}),\n ...(options.flags !== undefined ? flagsFromMarks(options.flags) : {}),\n ...(recommended !== undefined ? { recommended } : {}),\n ...(sortOrder !== undefined ? { sortOrder } : {}),\n });\n printLicense(updated, cmd, 'updated');\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('deprecate')\n .description('Administrators: stop offering a license; the projects that carry it keep it')\n .argument('<licenseId>', 'License ID')\n .action(async (licenseId: string, _options, cmd: Command) => {\n try {\n printLicense(await createApiClient().admin.deprecateLicense(licenseId), cmd, 'deprecated');\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('reactivate')\n .description('Administrators: offer a deprecated or withdrawn license again')\n .argument('<licenseId>', 'License ID')\n .action(async (licenseId: string, _options, cmd: Command) => {\n try {\n printLicense(await createApiClient().admin.reactivateLicense(licenseId), cmd, 'reactivated');\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('withdraw')\n .description('Administrators: end publication under a license; every public project that carries it becomes private')\n .argument('<licenseId>', 'License ID')\n .option('--expected-affected <n>', 'The number of public projects that become private, as `license catalog` shows it; the platform refuses when it differs')\n .action(async (licenseId: string, options, cmd: Command) => {\n try {\n const affected = (await catalogEntry(licenseId)).publicProjects;\n if (options.expectedAffected === undefined) {\n throw new CliError(`Withdrawing \"${licenseId}\" makes ${affected} public project(s) private.`, {\n hint: `Confirm with 'diafunc license withdraw ${licenseId} --expected-affected ${affected}'.`,\n });\n }\n const expected = Number(options.expectedAffected);\n if (!Number.isInteger(expected) || expected < 0) {\n throw new CliError(`--expected-affected must be a whole number, not \"${options.expectedAffected}\".`);\n }\n printLicense(await createApiClient().admin.withdrawLicense(licenseId, expected), cmd, 'withdrawn');\n } catch (error) {\n handleError(error);\n }\n });\n\n license\n .command('delete')\n .description('Administrators: remove a license no project refers to (otherwise deprecate or withdraw it)')\n .argument('<licenseId>', 'License ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (licenseId: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete license \"${licenseId}\" from the catalog.`,\n { yes: options.yes, resourceId: licenseId });\n await createApiClient().admin.deleteLicense(licenseId);\n success(`License \"${licenseId}\" deleted.`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/*\n * (C) Copyright by Markus Pollak, diafunc.com - All Rights Reserved\n *\n * diafunc.com, Markus Pollak, 7083 Purbach, Austria\n *\n * All information contained herein is, and remains the property of Markus Pollak. The intellectual\n * and technical concepts contained herein are proprietary to Markus Pollak (diafunc.com) and are\n * protected by trade secret or copyright law. Dissemination of this information or reproduction of\n * this material is strictly forbidden unless prior written permission is obtained from Markus Pollak.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient, type ApiClient } from '../../client/api.js';\nimport { planLines } from '../analyze/sources.js';\nimport type { AnalysisDataBuild, AnalysisSource } from '../../client/types/analysis.js';\nimport { CliError, EXIT_USAGE, handleError, usageError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, success } from '../../output/messages.js';\nimport type {\n CreateDataSourceRequest,\n DataSource,\n DataSourceDashboardSummary,\n DataSourceRun,\n UpdateDataSourceRequest,\n} from '../../client/types/storage.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n// `--config k=v --config k=v` → { k: v, k: v }. The same flag can repeat.\nexport function parseConfigPairs(pairs: string[] | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n if (!pairs) return out;\n for (const pair of pairs) {\n const idx = pair.indexOf('=');\n if (idx <= 0) {\n throw new Error(`Invalid --config \"${pair}\". Expected key=value.`);\n }\n const key = pair.substring(0, idx).trim();\n const value = pair.substring(idx + 1);\n if (!key) {\n throw new Error(`Invalid --config \"${pair}\". The key is empty.`);\n }\n out[key] = value;\n }\n return out;\n}\n\nfunction dataSourceTableRow(ds: DataSource): Record<string, string> {\n return {\n id: ds.id,\n name: ds.name,\n type: ds.type,\n target: ds.analysisId ? `analysis ${ds.analysisId}` : `${ds.targetEntityId}@${ds.targetEntityBranch}`,\n schedule: ds.scheduleCron ?? 'manual',\n lastStatus: ds.lastRunStatus ?? '—',\n lastRefreshAt: ds.lastRefreshAt ?? '—',\n };\n}\n\nexport function formatBytes(bytes: number | null | undefined): string {\n if (bytes === null || bytes === undefined) return '—';\n if (bytes < 1000) return `${bytes} B`;\n if (bytes < 1_000_000) return `${(bytes / 1000).toFixed(1)} kB`;\n if (bytes < 1_000_000_000) return `${(bytes / 1_000_000).toFixed(2)} MB`;\n return `${(bytes / 1_000_000_000).toFixed(2)} GB`;\n}\n\nexport function formatCredits(credits: number | null | undefined): string {\n if (credits === null || credits === undefined) return '—';\n if (credits === 0) return '0';\n if (credits < 0.01) return credits.toFixed(4);\n return credits.toFixed(2);\n}\n\n/**\n * Best-effort prose for a Quartz cron expression (`sec min hour dom month dow [year]`).\n * Recognises a few common cadences; falls back to the raw expression otherwise. Null/blank\n * means the source is refreshed manually only. Mirrors the app's `humanizeCron`.\n */\nexport function humanizeCron(cron: string | null | undefined): string {\n if (!cron || !cron.trim()) return 'manual';\n const parts = cron.trim().split(/\\s+/);\n if (parts.length < 6) return cron.trim();\n const [sec, min, hour, dom, mon, dow] = parts;\n const pad2 = (n: string): string => (n.length < 2 ? `0${n}` : n);\n const everyDay = (dom === '*' || dom === '?') && mon === '*' && (dow === '*' || dow === '?');\n if (sec === '0' && min === '*' && hour === '*' && everyDay) return 'every minute';\n if (sec === '0' && /^\\d+$/.test(min) && hour === '*' && everyDay) {\n return min === '0' ? 'hourly' : `hourly at :${pad2(min)}`;\n }\n if (sec === '0' && /^\\d+$/.test(min) && /^\\d+$/.test(hour) && everyDay) {\n if (hour === '0' && min === '0') return 'daily at midnight UTC';\n return `daily at ${pad2(hour)}:${pad2(min)} UTC`;\n }\n return cron.trim();\n}\n\nexport function dashboardTableRow(s: DataSourceDashboardSummary): Record<string, string> {\n return {\n id: s.id,\n name: s.name,\n type: s.type,\n schedule: humanizeCron(s.scheduleCron),\n lastStatus: s.lastRunStatus ?? '—',\n lastRunAt: s.lastRunAt ?? '—',\n nextScheduledAt: s.nextScheduledAt ?? '—',\n recentFailures: `${s.recentFailureCount}/${s.recentRunCount}`,\n lastTransferred: formatBytes(s.lastBytesFetched),\n };\n}\n\nexport function runTableRow(run: DataSourceRun): Record<string, string> {\n return {\n runId: run.runId,\n status: run.status,\n startedAt: run.startedAt ?? '—',\n finishedAt: run.finishedAt ?? '—',\n rows: run.rowsImported !== null && run.rowsImported !== undefined ? String(run.rowsImported) : '—',\n transferred: formatBytes(run.bytesFetched),\n credits: formatCredits(run.creditsCharged),\n triggeredBy: run.triggeredBy ?? '—',\n };\n}\n\n/**\n * Resolves the project this command works on: the global `--project`, then the configured\n * default. Failing that it says which to supply rather than passing nothing on and letting the\n * server answer \"Missing required field: projectId\".\n */\nfunction resolveProjectId(cmd: Command): string {\n const globals = cmd.optsWithGlobals() as { project?: string };\n const resolved = globals.project ?? loadConfig().defaults.project;\n if (!resolved) {\n usageError(\n 'This command needs a project.',\n `Pass --project <id>, or set a default with 'diafunc config set defaults.project <id>'.`,\n );\n }\n return resolved;\n}\n\n// ---------- list / get / create / update / delete / refresh ----------\n\nasync function listDataSources(projectId: string | undefined, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const sources = await api.storage.listDataSources(projectId);\n if (outputFormat === 'human' && sources.length === 0) {\n empty('data sources');\n return;\n }\n format(sources.map(dataSourceTableRow), {\n format: outputFormat,\n columns: [\n { key: 'id', kind: 'id' },\n { key: 'name' },\n { key: 'type' },\n { key: 'target' },\n { key: 'schedule' },\n { key: 'lastStatus', header: 'last status', kind: 'state' },\n { key: 'lastRefreshAt', header: 'last refresh', kind: 'date' },\n ],\n });\n}\n\nasync function getDataSource(id: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const ds = await api.storage.getDataSource(id);\n format(ds, { format: outputFormat });\n}\n\nasync function showDashboard(projectId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const dashboard = await api.storage.getDataSourceDashboard(projectId);\n if (outputFormat !== 'human') {\n format(dashboard, { format: outputFormat });\n return;\n }\n const r = dashboard.rollup;\n let line = chalk.bold(`DataSources in ${projectId}: `)\n + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;\n if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;\n console.log(line);\n if (dashboard.sources.length === 0) {\n empty('data sources');\n return;\n }\n format(dashboard.sources.map(dashboardTableRow), {\n format: outputFormat,\n columns: [\n { key: 'id', kind: 'id' },\n { key: 'name' },\n { key: 'type' },\n { key: 'schedule' },\n { key: 'lastStatus', header: 'last status', kind: 'state' },\n { key: 'lastRunAt', header: 'last run', kind: 'date' },\n { key: 'nextScheduledAt', header: 'next run', kind: 'date' },\n { key: 'recentFailures', header: 'failures', kind: 'number' },\n { key: 'lastTransferred', header: 'transferred' },\n ],\n });\n}\n\nexport interface CreateOptions {\n analysis?: string;\n projectId?: string;\n projectBranch?: string;\n targetEntityId?: string;\n targetEntityBranch?: string;\n name: string;\n type: string;\n config?: string[];\n scheduleCron?: string;\n}\n\n/** The flags that name a table to overwrite; a data source has either all of them or `--analysis`. */\nconst TABLE_TARGET_FLAGS: [keyof CreateOptions, string][] = [\n ['projectId', '--project-id'],\n ['projectBranch', '--project-branch'],\n ['targetEntityId', '--target-entity-id'],\n ['targetEntityBranch', '--target-entity-branch'],\n];\n\n/**\n * What a new data source refreshes: one of the files an analysis is built from, or a table. Mixing the two\n * and naming neither are usage errors said before anything is sent.\n */\nexport function createTarget(options: CreateOptions): 'analysis' | 'table' {\n const given = TABLE_TARGET_FLAGS.filter(([key]) => options[key] !== undefined).map(([, flag]) => flag);\n if (options.analysis !== undefined) {\n if (given.length > 0) {\n throw new CliError(`--analysis cannot be combined with ${given.join(', ')}.`,\n { exitCode: EXIT_USAGE, hint: 'A data source feeds an analysis or overwrites a table, not both.' });\n }\n return 'analysis';\n }\n const missing = TABLE_TARGET_FLAGS.filter(([key]) => options[key] === undefined).map(([, flag]) => flag);\n if (missing.length > 0) {\n throw new CliError(`Say what the data source refreshes: --analysis <analysisId>, or a table with ${missing.join(', ')}.`,\n { exitCode: EXIT_USAGE });\n }\n return 'table';\n}\n\n/**\n * Makes a data source one of the files of an analysis: the platform fetches once, the file is stored like an\n * uploaded one, and the analysis's data is built from all its files the way the platform proposes.\n */\nexport async function createForAnalysis(api: ApiClient, options: CreateOptions, human: boolean): Promise<{ source: AnalysisSource; build: AnalysisDataBuild }> {\n const analysisId = options.analysis as string;\n const source = await api.analysis.attachDataSource(analysisId, {\n name: options.name,\n type: options.type,\n config: parseConfigPairs(options.config),\n scheduleCron: options.scheduleCron ?? null,\n });\n const plan = await api.analysis.planSources(analysisId, null);\n const build = await api.analysis.buildSources(analysisId, plan.recipe);\n if (human) {\n success(`Added ${source.fileName} to analysis ${analysisId} from data source ${source.dataSourceId ?? ''}`.trimEnd());\n for (const line of planLines(build.plan)) {\n console.log(line.caution ? chalk.yellow(` ${line.text}`) : chalk.dim(` ${line.text}`));\n }\n console.log(chalk.dim(options.scheduleCron\n ? ` Refreshes ${humanizeCron(options.scheduleCron)}; each refresh replaces the file and builds the data again.`\n : ' No schedule of its own: refresh it with `data-sources refresh`, or let a trigger fetch it before a run (`analyze triggers create --refresh-first`).'));\n }\n return { source, build };\n}\n\nasync function createDataSource(options: CreateOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const target = createTarget(options);\n const api = createApiClient();\n if (target === 'analysis') {\n const created = await createForAnalysis(api, options, outputFormat === 'human');\n if (outputFormat !== 'human') {\n format(created, { format: outputFormat });\n }\n return;\n }\n const request: CreateDataSourceRequest = {\n projectId: options.projectId as string,\n projectBranch: options.projectBranch as string,\n targetEntityId: options.targetEntityId as string,\n targetEntityBranch: options.targetEntityBranch as string,\n name: options.name,\n type: options.type,\n config: parseConfigPairs(options.config),\n scheduleCron: options.scheduleCron ?? null,\n };\n const ds = await api.storage.createDataSource(request);\n if (outputFormat === 'human') {\n success(`Created data source ${ds.id}`);\n console.log(chalk.dim(` Last run: ${ds.lastRunStatus ?? '—'}`));\n if (ds.lastRunError) console.log(chalk.dim(` Error: ${ds.lastRunError}`));\n } else {\n format(ds, { format: outputFormat });\n }\n}\n\ninterface UpdateOptions {\n name?: string;\n type?: string;\n config?: string[];\n scheduleCron?: string;\n clearSchedule?: boolean;\n}\n\nasync function updateDataSource(id: string, options: UpdateOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n if (\n options.name === undefined &&\n options.type === undefined &&\n (!options.config || options.config.length === 0) &&\n options.scheduleCron === undefined &&\n !options.clearSchedule\n ) {\n throw new Error('Provide at least one of --name, --type, --config, --schedule-cron, or --clear-schedule.');\n }\n if (options.scheduleCron !== undefined && options.clearSchedule) {\n throw new Error('--schedule-cron and --clear-schedule are mutually exclusive.');\n }\n\n // Backend semantics: scheduleCron === '' means \"clear\" (manual-only), null means \"no change\".\n let scheduleCron: string | null;\n if (options.clearSchedule) {\n scheduleCron = '';\n } else if (options.scheduleCron !== undefined) {\n scheduleCron = options.scheduleCron;\n } else {\n scheduleCron = null;\n }\n\n const request: UpdateDataSourceRequest = {\n name: options.name ?? null,\n type: options.type ?? null,\n config: options.config && options.config.length > 0 ? parseConfigPairs(options.config) : null,\n scheduleCron,\n };\n\n const api = createApiClient();\n const ds = await api.storage.updateDataSource(id, request);\n if (outputFormat === 'human') {\n success(`Updated data source ${ds.id}`);\n } else {\n format(ds, { format: outputFormat });\n }\n}\n\nasync function deleteDataSource(id: string): Promise<void> {\n const api = createApiClient();\n await api.storage.deleteDataSource(id);\n success(`Deleted data source ${id}`);\n}\n\nasync function refreshDataSource(id: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const run = await api.storage.refreshDataSource(id);\n if (outputFormat === 'human') {\n success(`Refresh queued: run ${run.runId}, status ${run.status}.`);\n if (run.errorMessage) console.log(chalk.red(` Error: ${run.errorMessage}`));\n } else {\n format(run, { format: outputFormat });\n }\n}\n\n// ---------- runs ----------\n\nasync function listRuns(id: string, limit: number, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const runs = await api.storage.listDataSourceRuns(id, limit);\n if (outputFormat === 'human' && runs.length === 0) {\n empty('runs yet');\n return;\n }\n format(runs.map(runTableRow), {\n format: outputFormat,\n columns: [\n { key: 'runId', kind: 'id' },\n { key: 'status', kind: 'state' },\n { key: 'startedAt', header: 'started', kind: 'date' },\n { key: 'finishedAt', header: 'finished', kind: 'date' },\n { key: 'rows', kind: 'number' },\n { key: 'transferred' },\n { key: 'credits' },\n { key: 'triggeredBy', header: 'triggered by' },\n ],\n });\n}\n\nasync function getRun(id: string, runId: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const run = await api.storage.getDataSourceRun(id, runId);\n format(run, { format: outputFormat });\n}\n\n// ---------- types ----------\n\nasync function listConnectorTypes(cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const types = await api.storage.listDataSourceConnectorTypes();\n if (outputFormat === 'human') {\n if (types.length === 0) {\n empty('connector types registered');\n return;\n }\n for (const t of types) console.log(t);\n } else {\n format(types, { format: outputFormat });\n }\n}\n\n// ---------- registration ----------\n\nexport function registerDataSourcesCommands(program: Command): void {\n const dataSources = program\n .command('data-sources')\n .description('Manage scheduled DataSource imports (Google Sheets, S3 URL, JDBC)');\n\n dataSources\n .command('list')\n // The platform partitions data sources by project and rejects an unscoped query, so this is\n // scoped, not \"optionally scoped\" as the description used to claim.\n .description('List the data sources of one project')\n .addHelpText('after', `\nExamples:\n $ diafunc data-sources list --project <id>\n $ diafunc config set defaults.project <id> then --project can be omitted\n`)\n .action(async (_options, cmd: Command) => {\n try {\n await listDataSources(resolveProjectId(cmd), cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('dashboard')\n .description('Project-level rollup: per-source last-run status, next-scheduled, recent failures')\n .requiredOption('--project-id <id>', 'Project ID')\n .action(async (options: { projectId: string }, cmd: Command) => {\n try {\n await showDashboard(options.projectId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('get')\n .description('Show one data source')\n .argument('<id>', 'Data source ID (UUID)')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await getDataSource(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('create')\n .description('Create a data source (runs the initial fetch synchronously). With --analysis the fetched file becomes one of the files that analysis is built from, and every refresh builds its data again; otherwise the data source overwrites a table')\n .option('--analysis <analysisId>', 'The analysis to feed: the file is stacked, matched by a key or reshaped like an uploaded one. Replaces the four table flags')\n .option('--project-id <id>', 'Project ID (for a table)')\n .option('--project-branch <branch>', 'Project branch, usually \"main\" (for a table)')\n .option('--target-entity-id <id>', 'Target table entity ID (for a table)')\n .option('--target-entity-branch <branch>', 'Target table entity branch (for a table)')\n .requiredOption('--name <name>', 'Display name')\n .requiredOption('--type <type>', 'Connector type (google_sheets, s3_url, jdbc)')\n .option('--config <key=value>', 'Connector config field; repeat for multiple', (value: string, prev: string[] = []) => prev.concat([value]), [] as string[])\n .option('--schedule-cron <expr>', 'Quartz cron expression (e.g. \"0 0 2 * * ?\" for daily 02:00 UTC); omit for manual-only')\n .action(async (options: CreateOptions, cmd: Command) => {\n try {\n await createDataSource(options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('update')\n .description('Update a data source (omit a flag to leave that field unchanged)')\n .argument('<id>', 'Data source ID')\n .option('--name <name>', 'New display name')\n .option('--type <type>', 'New connector type')\n .option('--config <key=value>', 'Replace the entire config map; repeat for multiple. Send \"[redacted]\" as a value to keep the existing encrypted credential.', (value: string, prev: string[] = []) => prev.concat([value]), [] as string[])\n .option('--schedule-cron <expr>', 'New Quartz cron expression')\n .option('--clear-schedule', 'Switch this data source to manual-only')\n .action(async (id: string, options: UpdateOptions, cmd: Command) => {\n try {\n await updateDataSource(id, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('delete')\n .description('Delete a data source (existing imported rows are kept)')\n .argument('<id>', 'Data source ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (id: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete data source \"${id}\".`, { yes: options.yes, resourceId: id });\n await deleteDataSource(id);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('refresh')\n .description('Trigger an out-of-schedule refresh now')\n .argument('<id>', 'Data source ID')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await refreshDataSource(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('runs')\n .description('List recent runs for a data source (newest first)')\n .argument('<id>', 'Data source ID')\n .option('--limit <n>', 'Max number of runs to show', '20')\n .action(async (id: string, options: { limit: string }, cmd: Command) => {\n try {\n await listRuns(id, parseInt(options.limit, 10), cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('run')\n .description('Show one run')\n .argument('<id>', 'Data source ID')\n .argument('<runId>', 'Run ID')\n .action(async (id: string, runId: string, _options, cmd: Command) => {\n try {\n await getRun(id, runId, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n dataSources\n .command('types')\n .description('List registered connector types')\n .action(async (_options, cmd: Command) => {\n try {\n await listConnectorTypes(cmd);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/*\n * (C) Copyright by Markus Pollak, diafunc.com - All Rights Reserved\n *\n * diafunc.com, Markus Pollak, 7083 Purbach, Austria\n *\n * All information contained herein is, and remains the property of Markus Pollak. The intellectual\n * and technical concepts contained herein are proprietary to Markus Pollak (diafunc.com) and are\n * protected by trade secret or copyright law. Dissemination of this information or reproduction of\n * this material is strictly forbidden unless prior written permission is obtained from Markus Pollak.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport type { UserDefinedExporter } from '../../client/types/storage.js';\nimport { failure, success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function registerTableExportersCommands(program: Command): void {\n const exporters = program\n .command('table-exporters')\n .description('Manage user-defined exporters (UDE); admin only');\n\n exporters\n .command('list')\n .description('List all registered user-defined exporters')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const list = await api.storage.listUserDefinedExporters();\n if (outputFormat === 'json') {\n format(list, { format: outputFormat });\n return;\n }\n const rows = list.map(e => ({\n id: e.id ?? '',\n name: e.name,\n format: e.format,\n extension: e.extension ?? '',\n mimeType: e.mimeType ?? '',\n priority: e.priority ?? 50,\n function: `${e.functionProjectId}/${e.functionEntityId}`,\n createdBy: e.createdBy ?? '',\n }));\n format(rows, {\n format: outputFormat,\n columns: ['id', 'name', 'format', 'extension', 'mimeType', 'priority', 'function', 'createdBy'],\n });\n console.log(chalk.dim(`${list.length} exporter(s)`));\n } catch (error) {\n handleError(error);\n }\n });\n\n exporters\n .command('get')\n .description('Show a single user-defined exporter by id')\n .argument('<id>', 'Exporter id')\n .action(async (id: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const list = await api.storage.listUserDefinedExporters();\n const exporter = list.find(e => e.id === id);\n if (!exporter) {\n failure(`No exporter with id=\"${id}\".`);\n process.exit(1);\n }\n format(exporter, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n exporters\n .command('create')\n .description('Register a new user-defined exporter')\n .requiredOption('--name <name>', 'Display name (e.g. \"Acme machine instrument export\")')\n .requiredOption('--format <token>', 'Format token used in the dispatch URL (e.g. \"acme\")')\n .requiredOption('--function-project <id>', 'Function entity\\'s project id')\n .requiredOption('--function-entity <id>', 'Function entity id')\n .option('--description <text>', 'Free-form description')\n .option('--extension <ext>', 'Filename extension (must start with \".\")')\n .option('--mime-type <mime>', 'MIME type the function produces')\n .option('--function-project-branch <branch>', 'Function project branch', 'main')\n .option('--function-entity-branch <branch>', 'Function entity branch', 'main')\n .option('--priority <n>', 'Dispatch priority (default 50; > 200 overrides built-ins)', '50')\n .action(async (options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const payload: UserDefinedExporter = {\n name: options.name,\n description: options.description,\n format: options.format,\n extension: options.extension,\n mimeType: options.mimeType,\n functionProjectId: options.functionProject,\n functionProjectBranch: options.functionProjectBranch,\n functionEntityId: options.functionEntity,\n functionEntityBranch: options.functionEntityBranch,\n priority: Number(options.priority),\n };\n const created = await api.storage.registerUserDefinedExporter(payload);\n if (outputFormat === 'json') {\n format(created, { format: outputFormat });\n return;\n }\n success(`Registered exporter \"${created.name}\" (id=${created.id}, format=${created.format})`);\n } catch (error) {\n handleError(error);\n }\n });\n\n exporters\n .command('delete')\n .description('Delete a user-defined exporter')\n .argument('<id>', 'Exporter id')\n .action(async (id: string) => {\n try {\n const api = createApiClient();\n await api.storage.deleteUserDefinedExporter(id);\n success(`Deleted exporter id=${id}`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/*\n * (C) Copyright by Markus Pollak, diafunc.com - All Rights Reserved\n *\n * diafunc.com, Markus Pollak, 7083 Purbach, Austria\n *\n * All information contained herein is, and remains the property of Markus Pollak. The intellectual\n * and technical concepts contained herein are proprietary to Markus Pollak (diafunc.com) and are\n * protected by trade secret or copyright law. Dissemination of this information or reproduction of\n * this material is strictly forbidden unless prior written permission is obtained from Markus Pollak.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { confirmDestructive } from '../../util/confirm.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { empty, success } from '../../output/messages.js';\nimport type {\n CreateSkeletonRequest,\n Skeleton,\n UpdateSkeletonRequest,\n} from '../../client/types/storage.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/**\n * Resolve the project ID for a skeleton command. Order of precedence:\n * 1. the global --project, in any position (`diafunc skeleton list --project p`)\n * 2. `defaults.project` from the active profile\n * Throws if none resolves. All `skeleton` subcommands are project-scoped — without an\n * id the server can't enforce the per-project cap or authorise the caller.\n */\nexport function resolveProjectId(cmd: Command): string {\n const globalOpts = cmd.optsWithGlobals() as { project?: string };\n if (globalOpts.project) return globalOpts.project;\n const config = loadConfig();\n if (config.defaults.project) return config.defaults.project;\n throw new Error(\n 'No project specified. Pass --project <id>, set the global --project flag, or run `diafunc config set defaults.project <id>`.',\n );\n}\n\n/**\n * `--template @file.txt` reads the template body from a file. The literal sentinel is\n * a single leading `@`; users who genuinely need a template starting with `@` can\n * escape it (`@@…` → keeps the second `@`). Returns the raw template string.\n *\n * The escape rule (not a path-only rule) is deliberate: an absolute-path heuristic\n * would still mis-handle a template that happens to begin with `/`, and the more\n * common case is \"tiny inline expression\" where ambiguity comes from a literal `@`,\n * not from an absolute path that looks like a file.\n */\nexport function resolveTemplate(raw: string): string {\n if (raw.startsWith('@@')) {\n // Escape: literal '@' content, no file read.\n return raw.substring(1);\n }\n if (raw.startsWith('@')) {\n const file = raw.substring(1);\n if (!file) {\n throw new Error('--template @ requires a filename after the @, e.g. --template @template.txt');\n }\n if (!fs.existsSync(file)) {\n throw new Error(`Template file not found: ${file}`);\n }\n return fs.readFileSync(file, 'utf-8').trim();\n }\n return raw;\n}\n\nfunction parseWeight(raw: string | undefined): number | null {\n if (raw === undefined) return null;\n const value = Number(raw);\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`Invalid --weight \"${raw}\". Use a positive number.`);\n }\n return value;\n}\n\nexport function skeletonTableRow(s: Skeleton): Record<string, string> {\n return {\n id: s.id,\n name: s.name,\n template: s.template,\n paramCount: String(s.paramCount),\n weight: s.weight.toFixed(2),\n createdAt: s.createdAt ?? '—',\n };\n}\n\n// ---------- create / list / get / update / delete ----------\n\ninterface CreateOptions {\n name: string;\n template: string;\n weight?: string;\n}\n\nasync function createSkeleton(options: CreateOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const projectId = resolveProjectId(cmd);\n const template = resolveTemplate(options.template);\n const weight = parseWeight(options.weight);\n // The branch pairs with the project: the global flag, then the profile default, then main.\n const globals = cmd.optsWithGlobals() as { branch?: string };\n\n const request: CreateSkeletonRequest = {\n projectId,\n projectBranch: globals.branch ?? loadConfig().defaults.branch ?? 'main',\n name: options.name,\n template,\n weight,\n };\n\n const api = createApiClient();\n const skeleton = await api.storage.createSkeleton(request);\n if (outputFormat === 'human') {\n success(`Created skeleton ${skeleton.id}`);\n console.log(chalk.dim(` name: ${skeleton.name}`));\n console.log(chalk.dim(` template: ${skeleton.template}`));\n console.log(chalk.dim(` paramCount: ${skeleton.paramCount}`));\n console.log(chalk.dim(` weight: ${skeleton.weight}`));\n } else {\n format(skeleton, { format: outputFormat });\n }\n}\n\nasync function listSkeletons(cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const projectId = resolveProjectId(cmd);\n const api = createApiClient();\n const skeletons = await api.storage.listSkeletons(projectId);\n if (outputFormat === 'human' && skeletons.length === 0) {\n empty(`skeletons in project ${projectId}`);\n return;\n }\n format(skeletons.map(skeletonTableRow), {\n format: outputFormat,\n columns: ['id', 'name', 'template', 'paramCount', 'weight', 'createdAt'],\n });\n}\n\nasync function getSkeleton(id: string, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const skeleton = await api.storage.getSkeleton(id);\n format(skeleton, { format: outputFormat });\n}\n\ninterface UpdateOptions {\n name?: string;\n template?: string;\n weight?: string;\n}\n\nasync function updateSkeleton(id: string, options: UpdateOptions, cmd: Command): Promise<void> {\n const outputFormat = getOutputFormat(cmd);\n if (\n options.name === undefined &&\n options.template === undefined &&\n options.weight === undefined\n ) {\n throw new Error('Provide at least one of --name, --template, --weight.');\n }\n\n const request: UpdateSkeletonRequest = {\n name: options.name ?? null,\n template: options.template !== undefined ? resolveTemplate(options.template) : null,\n weight: parseWeight(options.weight),\n };\n\n const api = createApiClient();\n const skeleton = await api.storage.updateSkeleton(id, request);\n if (outputFormat === 'human') {\n success(`Updated skeleton ${skeleton.id}`);\n console.log(chalk.dim(` name: ${skeleton.name}`));\n console.log(chalk.dim(` template: ${skeleton.template}`));\n console.log(chalk.dim(` paramCount: ${skeleton.paramCount}`));\n console.log(chalk.dim(` weight: ${skeleton.weight}`));\n } else {\n format(skeleton, { format: outputFormat });\n }\n}\n\nasync function deleteSkeleton(id: string): Promise<void> {\n const api = createApiClient();\n await api.storage.deleteSkeleton(id);\n success(`Deleted skeleton ${id}`);\n}\n\n// ---------- registration ----------\n\nexport function registerSkeletonCommands(program: Command): void {\n const skeleton = program\n .command('skeleton')\n .description('Manage user-provided skeleton templates (project-scoped, capped at 100/project)')\n .addHelpText('after', `\nExamples:\n $ diafunc skeleton list --project <id>\n $ diafunc skeleton create --project <id> --name linear --template 'a*x+b'\n`);;\n\n skeleton\n .command('create')\n .description('Create a skeleton. A template the platform cannot parse is reported on stderr.')\n .requiredOption('--name <name>', 'Display name')\n .requiredOption(\n '--template <expr>',\n 'Skeleton template expression (e.g. \"?*x+?\"). Use \"@file.txt\" to read from a file; \"@@…\" escapes a literal leading @.',\n )\n .option('--weight <number>', 'Sampling weight (positive; server default applies if omitted)')\n .action(async (options: CreateOptions, cmd: Command) => {\n try {\n await createSkeleton(options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n skeleton\n .command('list')\n .description('List skeletons in a project')\n .action(async (_options, cmd: Command) => {\n try {\n await listSkeletons(cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n skeleton\n .command('get')\n .description('Show one skeleton')\n .argument('<id>', 'Skeleton ID (UUID)')\n .action(async (id: string, _options, cmd: Command) => {\n try {\n await getSkeleton(id, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n skeleton\n .command('update')\n .description('Update a skeleton (omit a flag to leave that field unchanged)')\n .argument('<id>', 'Skeleton ID')\n .option('--name <name>', 'New display name')\n .option('--template <expr>', 'New template expression (supports the same \"@file.txt\" sugar as create)')\n .option('--weight <number>', 'New sampling weight (positive)')\n .action(async (id: string, options: UpdateOptions, cmd: Command) => {\n try {\n await updateSkeleton(id, options, cmd);\n } catch (error) {\n handleError(error);\n }\n });\n\n skeleton\n .command('delete')\n .description('Delete a skeleton')\n .argument('<id>', 'Skeleton ID')\n .option('-y, --yes', 'Skip confirmation prompt (for CI / scripted use)')\n .action(async (id: string, options: { yes?: boolean }) => {\n try {\n await confirmDestructive(`This will permanently delete skeleton \"${id}\".`, { yes: options.yes, resourceId: id });\n await deleteSkeleton(id);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\n\nconst BASH_COMPLETION = `#!/bin/bash\n_diafunc_completions() {\n local cur prev commands subcommands\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n\n commands=\"auth config project team entity link event branch table function trigger schedule chat search admin analyze help\"\n\n case \"\\${COMP_WORDS[1]}\" in\n auth)\n subcommands=\"login logout status token\"\n if [[ \"\\${COMP_WORDS[2]}\" == \"token\" ]]; then\n COMPREPLY=($(compgen -W \"create list revoke\" -- \"\\${cur}\"))\n else\n COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\"))\n fi\n ;;\n config)\n subcommands=\"set get list profile\"\n if [[ \"\\${COMP_WORDS[2]}\" == \"profile\" ]]; then\n COMPREPLY=($(compgen -W \"add use list remove\" -- \"\\${cur}\"))\n else\n COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\"))\n fi\n ;;\n project)\n subcommands=\"list get create delete lock unlock members tags\"\n if [[ \"\\${COMP_WORDS[2]}\" == \"members\" ]]; then\n COMPREPLY=($(compgen -W \"list invite join remove\" -- \"\\${cur}\"))\n elif [[ \"\\${COMP_WORDS[2]}\" == \"tags\" ]]; then\n COMPREPLY=($(compgen -W \"get add remove set\" -- \"\\${cur}\"))\n else\n COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\"))\n fi\n ;;\n entity)\n subcommands=\"list get delete history revert rename content tags\"\n if [[ \"\\${COMP_WORDS[2]}\" == \"content\" ]]; then\n COMPREPLY=($(compgen -W \"get set delete\" -- \"\\${cur}\"))\n elif [[ \"\\${COMP_WORDS[2]}\" == \"tags\" ]]; then\n COMPREPLY=($(compgen -W \"get add remove set\" -- \"\\${cur}\"))\n else\n COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\"))\n fi\n ;;\n link)\n COMPREPLY=($(compgen -W \"list create delete\" -- \"\\${cur}\"))\n ;;\n event)\n COMPREPLY=($(compgen -W \"list get delete\" -- \"\\${cur}\"))\n ;;\n branch)\n COMPREPLY=($(compgen -W \"list create delete merge fork\" -- \"\\${cur}\"))\n ;;\n table)\n subcommands=\"view import export row column cell clear\"\n case \"\\${COMP_WORDS[2]}\" in\n row) COMPREPLY=($(compgen -W \"add remove\" -- \"\\${cur}\")) ;;\n column) COMPREPLY=($(compgen -W \"add remove\" -- \"\\${cur}\")) ;;\n cell) COMPREPLY=($(compgen -W \"set delete\" -- \"\\${cur}\")) ;;\n *) COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\")) ;;\n esac\n ;;\n function)\n COMPREPLY=($(compgen -W \"call evaluations outputs logs stop engines\" -- \"\\${cur}\"))\n ;;\n trigger)\n COMPREPLY=($(compgen -W \"list get delete\" -- \"\\${cur}\"))\n ;;\n schedule)\n COMPREPLY=($(compgen -W \"call\" -- \"\\${cur}\"))\n ;;\n chat)\n subcommands=\"repl send stream upload session usage\"\n if [[ \"\\${COMP_WORDS[2]}\" == \"session\" ]]; then\n COMPREPLY=($(compgen -W \"list delete\" -- \"\\${cur}\"))\n else\n COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\"))\n fi\n ;;\n team)\n subcommands=\"list get use usage create portal cancel leave members invitations seats packs transfer\"\n case \"\\${COMP_WORDS[2]}\" in\n members) COMPREPLY=($(compgen -W \"list invite remove\" -- \"\\${cur}\")) ;;\n invitations) COMPREPLY=($(compgen -W \"list revoke resend accept\" -- \"\\${cur}\")) ;;\n seats|packs) COMPREPLY=($(compgen -W \"preview set\" -- \"\\${cur}\")) ;;\n transfer) COMPREPLY=($(compgen -W \"start status accept cancel\" -- \"\\${cur}\")) ;;\n *) COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\")) ;;\n esac\n ;;\n admin)\n subcommands=\"users subscription settings backup curated-tags\"\n case \"\\${COMP_WORDS[2]}\" in\n users) COMPREPLY=($(compgen -W \"list get\" -- \"\\${cur}\")) ;;\n settings) COMPREPLY=($(compgen -W \"get set\" -- \"\\${cur}\")) ;;\n backup) COMPREPLY=($(compgen -W \"create-full project\" -- \"\\${cur}\")) ;;\n curated-tags) COMPREPLY=($(compgen -W \"list create update delete\" -- \"\\${cur}\")) ;;\n *) COMPREPLY=($(compgen -W \"\\${subcommands}\" -- \"\\${cur}\")) ;;\n esac\n ;;\n analyze)\n COMPREPLY=($(compgen -f -- \"\\${cur}\"))\n ;;\n *)\n COMPREPLY=($(compgen -W \"\\${commands}\" -- \"\\${cur}\"))\n ;;\n esac\n}\ncomplete -F _diafunc_completions diafunc`;\n\nconst ZSH_COMPLETION = `#compdef diafunc\n\n_diafunc() {\n local -a commands\n commands=(\n 'auth:Authentication and credential management'\n 'config:Manage CLI configuration'\n 'project:Manage projects'\n 'team:Manage teams'\n 'entity:Manage entities'\n 'link:Manage links between entities'\n 'event:Manage events'\n 'branch:Manage branches'\n 'table:Manage tables'\n 'function:Execute and manage functions'\n 'trigger:Manage function triggers'\n 'schedule:Schedule function execution'\n 'chat:AI chat'\n 'search:Search entities across projects'\n 'admin:Administration commands'\n 'analyze:Run an automatic analysis on a data file'\n )\n\n _arguments -C \\\\\n '(-V --version)'{-V,--version}'[output the version number]' \\\\\n '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\\\\n '(-o --output)'{-o,--output}'[Output format]:format:(human json table)' \\\\\n '--project[Default project ID override]:project:' \\\\\n '--branch[Default branch override]:branch:' \\\\\n '(-h --help)'{-h,--help}'[display help]' \\\\\n '1: :->command' \\\\\n '*::arg:->args'\n\n case $state in\n command)\n _describe 'command' commands\n ;;\n args)\n case \\${words[1]} in\n auth) _diafunc_auth ;;\n config) _diafunc_config ;;\n project) _diafunc_project ;;\n team) _diafunc_team ;;\n entity) _diafunc_entity ;;\n link) _values 'subcommand' list create delete ;;\n event) _values 'subcommand' list get delete ;;\n branch) _values 'subcommand' list create delete merge fork ;;\n table) _diafunc_table ;;\n function) _values 'subcommand' call evaluations outputs logs stop engines ;;\n trigger) _values 'subcommand' list get delete ;;\n schedule) _values 'subcommand' call ;;\n chat) _diafunc_chat ;;\n admin) _diafunc_admin ;;\n analyze) _files ;;\n esac\n ;;\n esac\n}\n\n_diafunc_auth() { _values 'subcommand' login logout status token; }\n_diafunc_config() { _values 'subcommand' set get list profile; }\n_diafunc_project() { _values 'subcommand' list get create delete lock unlock members tags; }\n_diafunc_team() { _values 'subcommand' list get use usage create portal cancel leave members invitations seats packs transfer; }\n_diafunc_entity() { _values 'subcommand' list get delete history revert rename content tags; }\n_diafunc_table() { _values 'subcommand' view import export row column cell clear; }\n_diafunc_chat() { _values 'subcommand' repl send stream upload session usage; }\n_diafunc_admin() { _values 'subcommand' users subscription settings backup curated-tags; }\n\n_diafunc \"$@\"`;\n\nconst FISH_COMPLETION = `# Fish completions for diafunc\nset -l commands auth config project team entity link event branch table function trigger schedule chat search admin analyze\n\n# Disable file completions by default\ncomplete -c diafunc -f\n\n# Top-level commands\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a auth -d \"Authentication and credential management\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a config -d \"Manage CLI configuration\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a project -d \"Manage projects\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a team -d \"Manage teams\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a entity -d \"Manage entities\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a link -d \"Manage links between entities\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a event -d \"Manage events\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a branch -d \"Manage branches\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a table -d \"Manage tables\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a function -d \"Execute and manage functions\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a trigger -d \"Manage function triggers\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a schedule -d \"Schedule function execution\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a chat -d \"AI chat\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a search -d \"Search entities\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a admin -d \"Administration commands\"\ncomplete -c diafunc -n \"not __fish_seen_subcommand_from $commands\" -a analyze -d \"Run automatic analysis\"\n\n# Global flags\ncomplete -c diafunc -s p -l profile -d \"Profile to use\"\ncomplete -c diafunc -s o -l output -d \"Output format\" -a \"human json table\"\ncomplete -c diafunc -l project -d \"Default project ID override\"\ncomplete -c diafunc -l branch -d \"Default branch override\"\ncomplete -c diafunc -l dry-run -d \"Preview without executing\"\n\n# auth\ncomplete -c diafunc -n \"__fish_seen_subcommand_from auth; and not __fish_seen_subcommand_from login logout status token\" -a \"login logout status token\"\ncomplete -c diafunc -n \"__fish_seen_subcommand_from token; and not __fish_seen_subcommand_from create list revoke\" -a \"create list revoke\"\n\n# config\ncomplete -c diafunc -n \"__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from set get list profile\" -a \"set get list profile\"\ncomplete -c diafunc -n \"__fish_seen_subcommand_from profile; and not __fish_seen_subcommand_from add use list remove\" -a \"add use list remove\"\n\n# project\ncomplete -c diafunc -n \"__fish_seen_subcommand_from project; and not __fish_seen_subcommand_from list get create delete lock unlock members tags\" -a \"list get create delete lock unlock members tags\"\n\n# entity\ncomplete -c diafunc -n \"__fish_seen_subcommand_from entity; and not __fish_seen_subcommand_from list get delete history revert rename content tags\" -a \"list get delete history revert rename content tags\"\n\n# branch\ncomplete -c diafunc -n \"__fish_seen_subcommand_from branch; and not __fish_seen_subcommand_from list create delete merge fork\" -a \"list create delete merge fork\"\n\n# table\ncomplete -c diafunc -n \"__fish_seen_subcommand_from table; and not __fish_seen_subcommand_from view import export row column cell clear\" -a \"view import export row column cell clear\"\n\n# function\ncomplete -c diafunc -n \"__fish_seen_subcommand_from function; and not __fish_seen_subcommand_from call evaluations outputs logs stop engines\" -a \"call evaluations outputs logs stop engines\"\n\n# chat\ncomplete -c diafunc -n \"__fish_seen_subcommand_from chat; and not __fish_seen_subcommand_from repl send stream upload session usage\" -a \"repl send stream upload session usage\"\n\n# team\ncomplete -c diafunc -n \"__fish_seen_subcommand_from team; and not __fish_seen_subcommand_from list get use usage create portal cancel leave members invitations seats packs transfer\" -a \"list get use usage create portal cancel leave members invitations seats packs transfer\"\ncomplete -c diafunc -n \"__fish_seen_subcommand_from invitations; and not __fish_seen_subcommand_from list revoke resend accept\" -a \"list revoke resend accept\"\ncomplete -c diafunc -n \"__fish_seen_subcommand_from seats packs; and not __fish_seen_subcommand_from preview set\" -a \"preview set\"\ncomplete -c diafunc -n \"__fish_seen_subcommand_from transfer; and not __fish_seen_subcommand_from start status accept cancel\" -a \"start status accept cancel\"\n\n# admin\ncomplete -c diafunc -n \"__fish_seen_subcommand_from admin; and not __fish_seen_subcommand_from users subscription settings backup curated-tags\" -a \"users subscription settings backup curated-tags\"\n\n# analyze accepts files\ncomplete -c diafunc -n \"__fish_seen_subcommand_from analyze\" -F`;\n\nexport function registerCompletionCommand(program: Command): void {\n program\n .command('completion')\n .description('Generate shell completion scripts')\n .argument('<shell>', 'Shell type: bash, zsh, or fish')\n .action((shell: string) => {\n switch (shell.toLowerCase()) {\n case 'bash':\n console.log(BASH_COMPLETION);\n break;\n case 'zsh':\n console.log(ZSH_COMPLETION);\n break;\n case 'fish':\n console.log(FISH_COMPLETION);\n break;\n default:\n console.error(`Unknown shell: \"${shell}\". Supported: bash, zsh, fish`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show the currently authenticated user')\n .action(async (_options, cmd) => {\n try {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n const outputFormat = globalOpts.output ?? config.defaults.output ?? 'human';\n\n const api = createApiClient();\n const user = await api.admin.getMyUser();\n\n if (outputFormat === 'human') {\n console.log(chalk.bold(user.name) + chalk.dim(` <${user.email}>`));\n console.log(chalk.dim(` Role: ${user.role} · Remaining credits: ${user.remainingCredits} · Profile: ${config.currentProfile}`));\n } else {\n format(user, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { formatNumber } from '../../output/values.js';\nimport type { Utilization } from '../../client/types/admin.js';\nimport { empty } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\n/**\n * Describes the window a utilization record covers.\n *\n * Credit consumption is accounted per billing cycle, and that cycle starts on the subscription\n * anniversary. Printing `2026-08` implied a calendar month and was wrong for every subscriber\n * whose renewal day is not the 1st, so the dates are named when the platform sends them.\n */\nfunction windowLabel(u: Utilization): string {\n if (u.cycleStart) {\n return u.cycleEnd\n ? `billing cycle ${u.cycleStart} to ${u.cycleEnd}`\n : `billing cycle from ${u.cycleStart}`;\n }\n if (u.day !== null && u.day !== undefined) {\n return `${u.year}-${String(u.month).padStart(2, '0')}-${String(u.day).padStart(2, '0')}`;\n }\n return `billing cycle ${u.year}-${String(u.month).padStart(2, '0')}`;\n}\n\nfunction printUtilizationHuman(u: Utilization, label?: string): void {\n const when = windowLabel(u);\n console.log(label ? chalk.bold(label) + ' ' + chalk.dim(when) : chalk.bold(when));\n\n if (u.types.length === 0) {\n console.log(chalk.dim(' (no usage)'));\n return;\n }\n\n // Ordered by what it cost. The wire order is whatever the accounting produced, which buried the\n // one or two lines that account for nearly all of the total among a dozen zeroes.\n const types = [...u.types].sort((a, b) => b.credits - a.credits);\n const width = Math.max(...types.map((t) => t.type.length));\n for (const t of types) {\n const line =\n ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)}` +\n ` ${chalk.dim('credits')} ${t.credits.toFixed(2).padStart(10)}`;\n console.log(t.credits === 0 ? chalk.dim(line) : line);\n }\n\n const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);\n console.log(chalk.bold(` ${'Total'.padEnd(width)} ${' '.repeat(12)} ${chalk.dim('credits')} ${total.toFixed(2).padStart(10)}`));\n}\n\n/**\n * The cycle day by day: what each day cost, beneath it the types that cost anything that day, most\n * expensive first, and the total over the days shown.\n *\n * A history day's `credits` and `quantity` are the calendar-month values of that day's usage\n * snapshot, not its spend, so printing them showed one running total climbing day after day. What a\n * day cost is `dailyCredits`. A day runs from the platform's 04:00 UTC snapshot to the next one, and\n * today's figure grows until tomorrow's snapshot.\n */\nexport function formatDailyHistory(history: Utilization[]): string[] {\n const spentOn = (u: Utilization) =>\n u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);\n const costly = (u: Utilization) =>\n u.types\n .filter((t) => (t.dailyCredits ?? 0) > 0)\n .sort((a, b) => (b.dailyCredits ?? 0) - (a.dailyCredits ?? 0));\n const totalLabel = `Total, ${history.length} ${history.length === 1 ? 'day' : 'days'}`;\n const width = Math.max(\n totalLabel.length,\n ...history.map((u) => windowLabel(u).length),\n ...history.flatMap((u) => costly(u).map((t) => t.type.length + 2)),\n );\n const amount = (credits: number) => credits.toFixed(2).padStart(10);\n\n const lines: string[] = [];\n let total = 0;\n for (const u of history) {\n const spent = spentOn(u);\n total += spent;\n const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk.dim('credits')}`;\n lines.push(spent > 0 ? chalk.bold(line) : chalk.dim(line));\n for (const t of costly(u)) {\n lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);\n }\n }\n lines.push('');\n lines.push(chalk.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk.dim('credits')}`));\n return lines;\n}\n\nexport function registerUtilizationCommand(program: Command): void {\n const util = program\n .command('utilization')\n .description('Show credit utilization for the current billing cycle')\n .addHelpText('after', `\nThe billing cycle starts on your subscription anniversary, not on the first of the month.\n\nExamples:\n $ diafunc utilization this cycle, by consumption type\n $ diafunc utilization history day by day across the cycle\n`);\n\n util\n .command('actual', { isDefault: true })\n .description('Show current utilization (default subcommand)')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const utilization = await api.admin.getActualUtilization();\n if (outputFormat === 'human') {\n printUtilizationHuman(utilization, 'Current utilization');\n } else {\n format(utilization, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n util\n .command('history')\n .description('Show what each day of the billing cycle cost')\n .action(async (_options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const api = createApiClient();\n const history = await api.admin.getUtilizationHistory();\n if (outputFormat === 'human') {\n if (history.length === 0) {\n empty('usage recorded');\n return;\n }\n for (const line of formatDailyHistory(history)) {\n console.log(line);\n }\n } else {\n format(history, { format: outputFormat });\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { parseEntityReference } from '../../util/references.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nfunction getOverrides(cmd: Command): { project?: string; branch?: string } {\n const opts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n return { project: opts.project, branch: opts.branch };\n}\n\nexport function registerEntityBranchCommands(program: Command): void {\n const eb = program\n .command('entity-branch')\n .description('Manage entity branches (parallel versions of a single entity)');\n\n eb\n .command('list')\n .description('List branches of an entity')\n .argument('<ref>', 'Entity reference (projectId/branch/entityId)')\n .action(async (ref: string, _options, cmd) => {\n try {\n const outputFormat = getOutputFormat(cmd);\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n const branches = await api.storage.getEntityBranches(\n resolved.projectId, resolved.projectBranch, resolved.entityId,\n );\n if (outputFormat === 'json') {\n format(branches, { format: outputFormat });\n } else {\n for (const b of branches) console.log(b);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n eb\n .command('create')\n .description('Create a new branch of an entity from an existing branch')\n .argument('<ref>', 'Source entity reference (projectId/branch/entityId/sourceBranch)')\n .argument('<targetBranch>', 'New branch name')\n .action(async (ref: string, targetBranch: string, _options, cmd) => {\n try {\n const overrides = getOverrides(cmd);\n const resolved = parseEntityReference(ref, overrides);\n const api = createApiClient();\n await api.storage.createEntityBranch({\n projectId: resolved.projectId,\n projectBranch: resolved.projectBranch,\n entityId: resolved.entityId,\n sourceEntityBranch: resolved.entityBranch,\n targetEntityBranch: targetBranch,\n });\n success(`Entity branch \"${targetBranch}\" created from \"${resolved.entityBranch}\".`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\n\n/**\n * Fields of the subscription DTO that belong to the billing integration rather than to the\n * subscriber: the Stripe object ids and the dunning state machine. A person asking what plan they\n * are on has no use for `stripePriceId` or `nextRetryAt`, so human output omits them. `--output\n * json` still carries the whole payload for anything that needs it.\n */\nconst BILLING_INTERNALS = new Set([\n 'stripeSubscriptionId', 'stripePriceId', 'stripeCustomerId',\n 'dunningStage', 'dunningStartedAt', 'nextRetryAt',\n]);\n\nfunction forReader(subscription: unknown): unknown {\n if (!subscription || typeof subscription !== 'object') return subscription;\n return Object.fromEntries(\n Object.entries(subscription as Record<string, unknown>)\n .filter(([key]) => !BILLING_INTERNALS.has(key)),\n );\n}\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function registerSubscriptionCommand(program: Command): void {\n const sub = program\n .command('subscription')\n .description('View subscription info')\n .addHelpText('after', `\nExamples:\n $ diafunc subscription current plan, term and billing interval\n $ diafunc subscription current -o json including the billing-integration fields\n`);\n\n sub\n .command('current', { isDefault: true })\n .description('Show the current subscription')\n .action(async (_options, cmd) => {\n try {\n const api = createApiClient();\n const outputFormat = getOutputFormat(cmd);\n const s = await api.admin.getCurrentSubscription();\n format(outputFormat === 'human' ? forReader(s) : s, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n sub\n .command('next')\n .description('Show the next (upcoming) subscription')\n .action(async (_options, cmd) => {\n try {\n const api = createApiClient();\n const outputFormat = getOutputFormat(cmd);\n const s = await api.admin.getNextSubscription();\n format(outputFormat === 'human' ? forReader(s) : s, { format: outputFormat });\n } catch (error) {\n handleError(error);\n }\n });\n\n sub\n .command('plans')\n .description('Show subscription plans')\n .argument('<subscriptionToken>', 'Subscription token')\n .action(async (subscriptionToken: string, _options, cmd) => {\n try {\n const api = createApiClient();\n const plans = await api.admin.getSubscriptionPlans(subscriptionToken);\n format(plans, { format: getOutputFormat(cmd) });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { format, type OutputFormat } from '../../output/formatter.js';\nimport { success } from '../../output/messages.js';\n\nfunction getOutputFormat(cmd: Command): OutputFormat {\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { output?: OutputFormat };\n return globalOpts.output ?? config.defaults.output ?? 'human';\n}\n\nexport function registerInvoiceCommand(program: Command): void {\n const invoice = program\n .command('invoice')\n .description('View and download invoices')\n .addHelpText('after', `\nExamples:\n $ diafunc invoice list\n $ diafunc invoice download 120 invoice-120.pdf\n`);;\n\n invoice\n .command('list')\n .description('List your invoices')\n .action(async (_options, cmd) => {\n try {\n const api = createApiClient();\n const invoices = await api.admin.getInvoices();\n format(invoices, {\n format: getOutputFormat(cmd),\n columns: [\n { key: 'invoiceNumber', header: 'number' },\n { key: 'issued', kind: 'date' },\n { key: 'periodFrom', header: 'from' },\n { key: 'periodTo', header: 'to' },\n { key: 'total', kind: 'number' },\n { key: 'status', kind: 'state' },\n ],\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n invoice\n .command('download')\n .description('Download an invoice document')\n .argument('<invoiceNumber>', 'Invoice number')\n .argument('<fileName>', 'File name of the document')\n .option('--out <path>', 'Output file path (defaults to <fileName>)')\n .action(async (invoiceNumber: string, fileName: string, options: { out?: string }) => {\n try {\n const api = createApiClient();\n const response = await api.admin.downloadInvoice(invoiceNumber, fileName);\n const buffer = Buffer.from(await response.arrayBuffer());\n const outPath = options.out ?? fileName;\n fs.writeFileSync(outPath, buffer);\n success(`Invoice saved to ${outPath}`);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport { timeUuid } from '../../util/time-uuid.js';\nimport { loadConfig } from '../../config/store.js';\nimport { createApiClient, type ApiClient } from '../../client/api.js';\nimport { handleError } from '../../util/errors.js';\nimport { parseEntityReference, type ResolvedReference } from '../../util/references.js';\nimport { buildFunctionEntity, resultText } from '../../util/function-content.js';\nimport { resolveLanguage } from '../../util/function-language.js';\nimport { failure, hint, success } from '../../output/messages.js';\n\n// Mirrors the lab shell widget (app/src/app/lab/widgets/shell/shell.component.ts):\n// save a function entity with the typed source, call it with removeFunction=true,\n// display outputs and the final result, then loop. Each iteration fully replaces\n// the function content — there is no persistent state between evaluations.\n\ninterface ShellOptions {\n function?: string;\n language?: string;\n}\n\nfunction extensionFor(language: string): string {\n const l = language.toLowerCase();\n if (l === 'java') return 'java';\n if (l === 'javascript' || l === 'js') return 'js';\n if (l === 'kotlin') return 'kt';\n if (l === 'python') return 'py';\n if (l === 'scala') return 'scala';\n return 'txt';\n}\n\nasync function openInEditor(initial: string, ext: string): Promise<string> {\n const tmpFile = path.join(os.tmpdir(), `diafunc-shell-${randomUUID()}.${ext}`);\n fs.writeFileSync(tmpFile, initial);\n const editor = process.env.VISUAL ?? process.env.EDITOR ?? 'vi';\n await new Promise<void>((resolve, reject) => {\n const child = spawn(editor, [tmpFile], { stdio: 'inherit' });\n child.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`Editor exited with ${code}`))));\n child.on('error', reject);\n });\n const content = fs.readFileSync(tmpFile, 'utf-8');\n fs.unlinkSync(tmpFile);\n return content;\n}\n\nfunction utcNowParts(): { year: number; month: number; day: number; hour: number } {\n const d = new Date();\n return {\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour: d.getUTCHours(),\n };\n}\n\nasync function evaluate(\n api: ApiClient,\n fnRef: ResolvedReference,\n language: string,\n sourceCode: string,\n): Promise<void> {\n // Save the function entity fresh with the typed code.\n const entity = buildFunctionEntity({\n projectId: fnRef.projectId,\n projectBranch: fnRef.projectBranch,\n entityId: fnRef.entityId,\n entityBranch: fnRef.entityBranch,\n name: fnRef.entityId,\n language,\n sourceCode,\n });\n await api.storage.saveEntities([entity]);\n\n // Call it with removeFunction: true — the entity is deleted after eval, so\n // the next turn has to re-save it. The call is synchronous: the response\n // contains outputs and the final result (or error).\n const evaluationId = timeUuid();\n const nowParts = utcNowParts();\n const result = await api.evaluation.call({\n evaluationId,\n projectId: fnRef.projectId,\n projectBranch: fnRef.projectBranch,\n functionId: fnRef.entityId,\n functionBranch: fnRef.entityBranch,\n targetEntityId: null,\n targetEntityBranch: null,\n arguments: null,\n types: null,\n requested: Date.now(),\n provideOutputs: true,\n removeFunction: true,\n }, false);\n\n if (result.outputs?.length) {\n for (const out of result.outputs) {\n console.log(chalk.dim(` [${out.type}]`) + ' ' + out.output);\n }\n }\n if (result.successful) {\n if (result.result) {\n console.log(chalk.green('=>') + ' ' + resultText(result.result, result.resultEncoding));\n } else {\n console.log(chalk.dim('=> (no value)'));\n }\n const duration = result.completed - result.started;\n console.log(chalk.dim(` [${duration}ms · ${evaluationId}]`));\n } else {\n console.log(chalk.red('error: ') + result.error);\n if (result.lineNumber > 0) {\n console.log(chalk.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));\n }\n }\n}\n\nexport function registerShellCommand(program: Command): void {\n program\n .command('shell')\n .description('Interactive REPL for function code evaluation')\n .option('--function <ref>', 'Function entity reference to use as scratch (required)')\n .option('--language <lang>', \"Source language; defaults to the project's language\")\n .action(async (options: ShellOptions, cmd: Command) => {\n try {\n if (!options.function) {\n failure('Missing --function <ref>.');\n hint('Pass an existing or new function entity reference to use as the shell target.');\n hint('Example: diafunc shell --function my-project/main/scratch/main --language Kotlin');\n process.exit(1);\n }\n const config = loadConfig();\n const globalOpts = cmd.optsWithGlobals() as { project?: string; branch?: string };\n const fnRef = parseEntityReference(options.function, {\n project: globalOpts.project,\n branch: globalOpts.branch,\n });\n\n const api = createApiClient();\n const { input: promptInput } = await import('@inquirer/prompts');\n const { getUpdateNotice } = await import('../../util/update-check.js');\n\n // The shell has to pin a language on every snippet it saves, so resolve one up front:\n // an explicit --language, else the project's default, else Java.\n const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);\n\n console.log(chalk.bold('Diafunc shell') + chalk.dim(` · function ${fnRef.entityId} · ${resolvedLanguage}`));\n console.log(chalk.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));\n console.log(chalk.dim(\"Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit\"));\n const notice = await getUpdateNotice();\n if (notice) console.log(chalk.dim(notice));\n console.log();\n\n let language = resolvedLanguage;\n\n for (;;) {\n let line: string;\n try {\n line = await promptInput({ message: chalk.cyan.bold(`${language} >`) });\n } catch {\n console.log();\n return;\n }\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n if (trimmed.startsWith('/')) {\n const [cmd, ...rest] = trimmed.slice(1).split(/\\s+/);\n const arg = rest.join(' ');\n switch (cmd) {\n case 'quit':\n case 'exit':\n case 'q':\n return;\n case 'help':\n case 'h':\n case '?':\n console.log(chalk.dim(' /edit open $EDITOR for multi-line code'));\n console.log(chalk.dim(' /file <path> evaluate the contents of a file'));\n console.log(chalk.dim(' /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)'));\n console.log(chalk.dim(' /quit exit the shell'));\n continue;\n case 'lang':\n if (arg) language = arg;\n console.log(chalk.dim(`Language: ${language}`));\n continue;\n case 'edit': {\n const sourceCode = await openInEditor('', extensionFor(language));\n if (!sourceCode.trim()) {\n console.log(chalk.dim('(empty; not evaluated)'));\n continue;\n }\n try { await evaluate(api, fnRef, language, sourceCode); }\n catch (e) { console.error(chalk.red((e as Error).message)); }\n continue;\n }\n case 'file': {\n if (!arg) { console.log(chalk.dim('usage: /file <path>')); continue; }\n if (!fs.existsSync(arg)) { console.log(chalk.red(`file not found: ${arg}`)); continue; }\n const sourceCode = fs.readFileSync(arg, 'utf-8');\n try { await evaluate(api, fnRef, language, sourceCode); }\n catch (e) { console.error(chalk.red((e as Error).message)); }\n continue;\n }\n default:\n console.log(chalk.dim(`Unknown command: /${cmd}. Try /help.`));\n continue;\n }\n }\n\n try {\n await evaluate(api, fnRef, language, trimmed);\n } catch (e) {\n console.error(chalk.red((e as Error).message));\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport pkg from '../../../package.json' with { type: 'json' };\nimport { detectInstall } from '../../util/install-method.js';\nimport { handleError } from '../../util/errors.js';\n\nconst MANIFEST_URL = 'https://diafunc.com/cli/latest.json';\nconst POSIX_INSTALLER_URL = 'https://diafunc.com/cli/install.sh';\nconst WINDOWS_INSTALLER_URL = 'https://diafunc.com/cli/install.ps1';\n\nasync function fetchLatestVersion(): Promise<string> {\n const res = await fetch(MANIFEST_URL);\n if (!res.ok) throw new Error(`Failed to fetch ${MANIFEST_URL}: HTTP ${res.status}`);\n const manifest = await res.json() as { version?: string };\n if (!manifest.version) throw new Error('Manifest missing version field.');\n return manifest.version;\n}\n\nfunction runInstaller(installDir: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const isWindows = process.platform === 'win32';\n const cmd = isWindows ? 'powershell.exe' : 'sh';\n // On Windows the script does the move-then-replace dance internally so the\n // running diafunc.exe is renamed aside before the new exe is dropped in.\n const args = isWindows\n ? ['-NoProfile', '-Command', `& { iwr -useb ${WINDOWS_INSTALLER_URL} | iex }`]\n : ['-c', `curl -fsSL ${POSIX_INSTALLER_URL} | sh`];\n const child = spawn(cmd, args, {\n stdio: 'inherit',\n env: { ...process.env, DIAFUNC_CLI_INSTALL_DIR: installDir },\n });\n child.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`Installer exited with code ${code}`))));\n child.on('error', reject);\n });\n}\n\nexport function registerUpdateCommand(program: Command): void {\n program\n .command('update')\n .description('Update the CLI to the latest released version')\n .action(async () => {\n try {\n const install = detectInstall();\n const latest = await fetchLatestVersion();\n\n if (latest === pkg.version) {\n console.log(chalk.dim(`diafunc is already at the latest version (${pkg.version}).`));\n return;\n }\n\n console.log(chalk.dim(`Current: ${pkg.version} → Available: ${latest}`));\n\n if (install.method === 'npm') {\n console.log();\n console.log('Installed via npm. Upgrade with:');\n console.log(chalk.bold(` npm install -g @diafunc/cli@${latest}`));\n return;\n }\n\n const installDir = path.dirname(install.binaryPath);\n console.log(`Installing diafunc ${latest} to ${installDir}...`);\n console.log();\n await runInstaller(installDir);\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import * as fs from 'node:fs';\n\nexport type InstallMethod = 'npm' | 'binary';\n\nexport interface InstallInfo {\n method: InstallMethod;\n binaryPath: string;\n}\n\n// Bun-compiled binary: process.execPath is the binary itself (\"/.../diafunc\").\n// npm: process.execPath is the node interpreter (\"/.../node[.exe]\").\nexport function detectInstall(): InstallInfo {\n const exec = process.execPath;\n const exe = exec.replace(/\\\\/g, '/').toLowerCase();\n const isNode = exe.endsWith('/node') || exe.endsWith('/node.exe');\n return {\n method: isNode ? 'npm' : 'binary',\n binaryPath: isNode ? exec : fs.realpathSync(exec),\n };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { detectInstall } from '../../util/install-method.js';\nimport { handleError } from '../../util/errors.js';\n\nexport function registerUninstallCommand(program: Command): void {\n program\n .command('uninstall')\n .description('Remove the CLI binary and (optionally) its config from this machine')\n .option('-y, --yes', 'Skip confirmation prompts')\n .option('--purge', 'Also remove ~/.diafunc/ (config + credentials) without prompting')\n .action(async (options: { yes?: boolean; purge?: boolean }) => {\n try {\n const install = detectInstall();\n const configDir = path.join(os.homedir(), '.diafunc');\n\n if (install.method === 'npm') {\n console.log('Installed via npm. Remove with:');\n console.log(chalk.bold(' npm uninstall -g @diafunc/cli'));\n if (fs.existsSync(configDir)) {\n console.log();\n console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);\n console.log(chalk.bold(` rm -rf ${configDir}`));\n }\n return;\n }\n\n const { confirm } = await import('@inquirer/prompts');\n\n const removeBinary = options.yes\n ? true\n : await confirm({\n message: `Remove binary at ${install.binaryPath}?`,\n default: false,\n });\n if (!removeBinary) {\n console.log(chalk.dim('Aborted.'));\n return;\n }\n\n let removeConfig = options.purge ?? false;\n if (!options.purge && !options.yes && fs.existsSync(configDir)) {\n removeConfig = await confirm({\n message: `Also remove ${configDir} (config + credentials)?`,\n default: false,\n });\n }\n\n if (removeConfig && fs.existsSync(configDir)) {\n fs.rmSync(configDir, { recursive: true, force: true });\n console.log(chalk.dim(`Removed ${configDir}`));\n }\n\n if (process.platform === 'win32') {\n // The running .exe is locked on Windows, so we can't delete it\n // ourselves. Spawn a detached cmd.exe that waits for our process to\n // exit, then deletes the binary, then deletes itself.\n const cmd = `timeout /t 2 /nobreak >nul & del /f /q \"${install.binaryPath}\"`;\n const child = spawn('cmd.exe', ['/c', cmd], {\n detached: true,\n stdio: 'ignore',\n windowsHide: true,\n });\n child.unref();\n console.log(chalk.dim(`Removing ${install.binaryPath} on exit...`));\n console.log();\n console.log('diafunc uninstalled.');\n return;\n }\n\n fs.rmSync(install.binaryPath, { force: true });\n console.log(chalk.dim(`Removed ${install.binaryPath}`));\n console.log();\n console.log('diafunc uninstalled.');\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command, type Option } from 'commander';\nimport { loadConfig } from '../config/store.js';\nimport type { ApiClient } from '../client/api.js';\nimport type { OutputFormat } from '../output/formatter.js';\nimport { canPrompt, type Prompter } from './prompter.js';\n\n/**\n * Commander, taught to ask for a missing required input instead of refusing it.\n *\n * Commander checks for missing required arguments and mandatory flags while it parses, and reports\n * each through `missingArgument()` / `missingMandatoryOptionValue()`. Those two methods are the only\n * seam: override them to *record* the gap and let parsing continue, and the argument simply arrives\n * as `undefined`. The program's `preAction` hook then asks for everything recorded (see `fill.ts`)\n * before the action runs, because the action reads `processedArgs` and `opts()` only when it is\n * called.\n *\n * Off a terminal the overrides defer to commander, so a script sees the same message and exit code\n * it always has. `--help` is untouched: nothing un-marks an input as required.\n */\n\n/** A required input the reader did not supply, recorded while commander parsed. */\nexport interface PendingInput {\n kind: 'argument' | 'option';\n /** The argument's name, or the option's attribute name (`--target-entity-id` → `targetEntityId`). */\n name: string;\n /** The option's long flag as typed, e.g. `--name`. Arguments have none. */\n flag?: string;\n /** The argument's position. Options have none. */\n index?: number;\n description: string;\n /** A `<ids...>` argument takes several values. */\n variadic: boolean;\n}\n\n/** What the prompting machinery needs from outside, all replaceable so tests touch neither a TTY nor the network. */\nexport interface PromptEnvironment {\n /** Answers questions. Defaults to the terminal. */\n prompter?: Prompter;\n /** Forces the interactive decision. Unset, `canPrompt()` decides from the terminal and the flags. */\n interactive?: boolean;\n /** Builds the API client pickers read from. */\n api?: () => ApiClient;\n /** Where the \"Equivalent:\" line is written. Defaults to stdout. */\n log?: (line: string) => void;\n}\n\ninterface CommanderInternals {\n missingArgument(this: Command, name: string): void;\n missingMandatoryOptionValue(this: Command, option: Option): void;\n}\n\nconst commanderOriginal = Command.prototype as unknown as CommanderInternals;\n\nexport class DiafuncCommand extends Command {\n /** Gaps recorded during the current parse, in the order commander found them. */\n readonly pendingInputs: PendingInput[] = [];\n\n /** Set on the program only; every command reads it from there. */\n promptEnvironment: PromptEnvironment = {};\n\n override createCommand(name?: string): DiafuncCommand {\n return new DiafuncCommand(name);\n }\n\n missingArgument(name: string): void {\n if (!this.mayPrompt()) {\n commanderOriginal.missingArgument.call(this, name);\n return;\n }\n const index = this.registeredArguments.findIndex((a) => a.name() === name);\n const argument = this.registeredArguments[index];\n this.pendingInputs.push({\n kind: 'argument',\n name,\n index,\n description: argument?.description ?? '',\n variadic: Boolean(argument?.variadic),\n });\n }\n\n missingMandatoryOptionValue(option: Option): void {\n if (!this.mayPrompt()) {\n commanderOriginal.missingMandatoryOptionValue.call(this, option);\n return;\n }\n this.pendingInputs.push({\n kind: 'option',\n name: option.attributeName(),\n flag: option.long ?? option.flags,\n description: option.description ?? '',\n variadic: Boolean(option.variadic),\n });\n }\n\n /** The environment set on the program. */\n environment(): PromptEnvironment {\n let root: Command = this;\n while (root.parent) root = root.parent;\n return root instanceof DiafuncCommand ? root.promptEnvironment : {};\n }\n\n private mayPrompt(): boolean {\n const forced = this.environment().interactive;\n if (forced !== undefined) return forced;\n const globals = this.optsWithGlobals() as { output?: OutputFormat; interactive?: boolean };\n const output = globals.output ?? loadConfig().defaults.output ?? 'human';\n return canPrompt(output, globals.interactive === false);\n }\n}\n","import chalk from 'chalk';\nimport type { Command } from 'commander';\nimport { createApiClient, type ApiClient } from '../client/api.js';\nimport { DiafuncCommand, type PendingInput } from './command.js';\nimport { createInquirerPrompter } from './prompter.js';\nimport { dependencies, specFor, type InputSpec } from './resolvers.js';\nimport { askFor, type AskContext } from './pickers.js';\n\n/**\n * Asks for every required input the reader left out, then lets the action run.\n *\n * Runs as the program's `preAction` hook, which commander calls after parsing and before the\n * action. The answers are written where the action reads them: arguments into `processedArgs`,\n * flags through `setOptionValueWithSource`. Questions are asked in dependency order, so a\n * member picker sees the team chosen a moment earlier.\n */\nexport async function fillPendingInputs(actionCommand: Command): Promise<void> {\n const chain = commandChain(actionCommand);\n const owners = chain.filter((c): c is DiafuncCommand => c instanceof DiafuncCommand && c.pendingInputs.length > 0);\n if (owners.length === 0) return;\n\n const env = (actionCommand as DiafuncCommand).environment();\n const pending: Pending[] = owners.flatMap((owner) => owner.pendingInputs.splice(0).map((input) => ({\n owner,\n input,\n spec: specFor(pathOf(owner), input) ?? { kind: 'text' },\n })));\n\n const ctx: AskContext = {\n prompter: env.prompter ?? createInquirerPrompter(),\n api: memoize(env.api ?? (() => createApiClient())),\n known: knownValues(actionCommand),\n globals: actionCommand.optsWithGlobals() as { project?: string; branch?: string },\n prefill: new Map(),\n note: (line) => process.stderr.write(chalk.dim(` ${line}\\n`)),\n };\n\n for (const item of orderByDependencies(pending)) {\n const value = await askFor(item.spec, item.input, ctx);\n write(item.owner, item.input, value);\n ctx.known.set(item.input.name, value);\n }\n\n const log = env.log ?? ((line: string) => console.log(line));\n log(chalk.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));\n}\n\ninterface Pending {\n owner: DiafuncCommand;\n input: PendingInput;\n spec: InputSpec;\n}\n\n/** The command and everything above it, program first. */\nfunction commandChain(cmd: Command): Command[] {\n const chain: Command[] = [];\n for (let c: Command | null = cmd; c; c = c.parent) chain.unshift(c);\n return chain;\n}\n\n/** `table view` for `diafunc table view`: the path below the program. */\nexport function pathOf(cmd: Command): string {\n return commandChain(cmd).slice(1).map((c) => c.name()).join(' ');\n}\n\n/** Everything already on the command line, by input name, for questions that need context. */\nfunction knownValues(cmd: Command): Map<string, unknown> {\n const known = new Map<string, unknown>();\n for (const [key, value] of Object.entries(cmd.optsWithGlobals())) {\n if (value !== undefined) known.set(key, value);\n }\n cmd.registeredArguments.forEach((argument, i) => {\n const value = cmd.processedArgs[i];\n if (value !== undefined) known.set(argument.name(), value);\n });\n return known;\n}\n\n/**\n * Pending inputs, reordered so each comes after the pending inputs it depends on. Declaration order\n * is kept otherwise; a dependency cycle, which no rule produces, falls back to it.\n */\nfunction orderByDependencies(pending: Pending[]): Pending[] {\n const remaining = [...pending];\n const ordered: Pending[] = [];\n while (remaining.length > 0) {\n const waiting = new Set(remaining.map((p) => p.input.name));\n const index = remaining.findIndex((p) => dependencies(p.spec).every((name) => !waiting.has(name) || name === p.input.name));\n ordered.push(...remaining.splice(index === -1 ? 0 : index, 1));\n }\n return ordered;\n}\n\nfunction write(owner: DiafuncCommand, input: PendingInput, value: string | string[]): void {\n if (input.kind === 'argument' && input.index !== undefined && input.index >= 0) {\n owner.processedArgs[input.index] = value;\n } else {\n owner.setOptionValueWithSource(input.name, value, 'cli');\n }\n}\n\nfunction memoize<T>(make: () => T): () => T {\n let made: T | undefined;\n return () => (made ??= make());\n}\n\n/**\n * The command with every answer written out, so the reader learns the form a script would use.\n * Only what was typed or answered appears: defaults and config values are left out.\n */\nexport function equivalentCommand(cmd: Command): string {\n const chain = commandChain(cmd);\n const tokens: string[] = [chain[0].name(), ...chain.slice(1).map((c) => c.name())];\n\n for (const value of cmd.processedArgs) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) tokens.push(quote(String(v)));\n }\n\n for (const c of chain) {\n for (const option of c.options) {\n const key = option.attributeName();\n if (c.getOptionValueSource(key) !== 'cli' || !option.long) continue;\n const value = c.getOptionValue(key);\n if (typeof value === 'boolean') {\n // A negatable flag (`--no-color`) is stored as false; a plain flag as true.\n if (value === !option.negate) tokens.push(option.long);\n } else if (Array.isArray(value)) {\n for (const v of value) tokens.push(option.long, quote(String(v)));\n } else if (value !== undefined) {\n tokens.push(option.long, quote(String(value)));\n }\n }\n }\n return tokens.join(' ');\n}\n\n/** Leaves a token bare when a shell would read it unchanged, and single-quotes it otherwise. */\nexport function quote(value: string): string {\n if (/^[\\w@%+=:,./-]+$/.test(value)) return value;\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport type { ApiClient };\n","import * as fs from 'node:fs';\nimport chalk from 'chalk';\nimport type { ApiClient } from '../client/api.js';\nimport type { SearchItem } from '../client/types/index-search.js';\nimport { createStatusService } from '../client/services/status.js';\nimport { loadConfig } from '../config/store.js';\nimport { parseEntityReference } from '../util/references.js';\nimport type { PendingInput } from './command.js';\nimport type { Choice, Prompter } from './prompter.js';\nimport type { EntityContentType, InputSpec } from './resolvers.js';\n\n/**\n * The questions themselves.\n *\n * A picker lists what the reader can choose, by name with the id dimmed beside it, and always\n * offers \"Type it instead\". It falls back to a plain text prompt when the list cannot be read or\n * comes back empty. A picker may make typing unnecessary, but it must never make typing impossible:\n * the reader may know an id the listing does not show.\n */\n\nexport interface AskContext {\n prompter: Prompter;\n /** The API client, built on first use so a question that needs no listing never signs in. */\n api: () => ApiClient;\n /** Everything answered so far and everything typed on the command line, by input name. */\n known: Map<string, unknown>;\n globals: { project?: string; branch?: string };\n /** Answers a picker settled on the way to its own, keyed by the input they answer. */\n prefill: Map<string, string>;\n /** A line of explanation the reader should see, such as why a list is not offered. */\n note: (line: string) => void;\n}\n\n/** Above this many choices a list is filtered by typing rather than scrolled. */\nexport const SEARCH_THRESHOLD = 10;\n\n/** The value a \"Type it instead\" choice carries. No real id can contain a NUL. */\nexport const TYPE_IT = '\\u0000type-it';\n\ninterface Item {\n label: string;\n value: string;\n hint?: string;\n}\n\nexport async function askFor(spec: InputSpec, input: PendingInput, ctx: AskContext): Promise<string | string[]> {\n const prefilled = ctx.prefill.get(input.name);\n if (prefilled !== undefined) return prefilled;\n\n switch (spec.kind) {\n case 'project':\n return askProject(ctx, spec.withBranch, messageFor(input, 'Project'));\n case 'entity':\n return askEntity(ctx, spec, input);\n case 'team':\n return listed(ctx, 'teams', messageFor(input, 'Team'), async () =>\n (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id })));\n case 'teamMember': {\n const teamId = text(ctx, 'teamId');\n return listed(ctx, 'team members', messageFor(input, 'Team member'), async () =>\n teamId ? (await ctx.api().admin.listTeamMembers(teamId))\n .filter((m) => !m.removedAt)\n .map((m) => ({ label: m.name ?? m.email ?? m.userId, value: m.userId, hint: `${m.role} · ${m.userId}` })) : []);\n }\n case 'projectMember': {\n const projectId = text(ctx, 'projectId')?.split('/')[0];\n return listed(ctx, 'project members', messageFor(input, 'Project member'), async () =>\n projectId ? (await ctx.api().admin.getProjectMembers(projectId))\n .map((m) => ({ label: m.userId, value: m.userId, hint: m.role })) : []);\n }\n case 'teamInvitation': {\n const teamId = text(ctx, 'teamId');\n return listed(ctx, 'invitations', messageFor(input, 'Invitation'), async () =>\n teamId ? (await ctx.api().admin.listTeamInvitations(teamId))\n .map((i) => ({ label: i.email, value: i.invitationId, hint: `${i.role} · ${i.invitationId}` })) : []);\n }\n case 'analysis':\n return askAnalysis(ctx, messageFor(input, 'Analysis'));\n case 'analysisRun': {\n const analysisId = text(ctx, 'id') ?? await askAnalysis(ctx, 'Analysis');\n return listed(ctx, 'runs', messageFor(input, 'Run'), async () => {\n const runs = await ctx.api().analysis.getRunsForAnalysis(analysisId, 20);\n const unfinished = (s: string) => !['COMPLETED', 'FAILED', 'CANCELLED'].includes(s);\n return [...runs]\n .sort((a, b) => Number(unfinished(b.state)) - Number(unfinished(a.state)))\n .map((r) => ({ label: r.state, value: r.runId, hint: `${when(r.submittedAt)} · ${r.runId}` }));\n });\n }\n case 'preset':\n return listed(ctx, 'presets', messageFor(input, 'Preset'), async () =>\n (await ctx.api().analysis.getPresets())\n .filter((p) => p.presetId)\n .map((p) => ({ label: p.name, value: p.presetId!, hint: p.presetId! })));\n case 'analysisTrigger': {\n const analysisId = text(ctx, 'analysisId') ?? await askAnalysis(ctx, 'Analysis');\n return listed(ctx, 'triggers', messageFor(input, 'Trigger'), async () =>\n (await ctx.api().analysis.listTriggers(analysisId)).map((t) => ({\n label: `${t.kind} ${t.scheduleSpec}`,\n value: t.triggerId,\n hint: `${t.active ? 'active' : 'paused'} · ${t.triggerId}`,\n })));\n }\n case 'analysisColumns':\n return askColumns(ctx, spec, input);\n case 'evaluation':\n return askEvaluation(ctx, input);\n case 'functionTrigger': {\n const ref = entityRef(ctx, 'ref');\n return listed(ctx, 'triggers', messageFor(input, 'Trigger'), async () =>\n ref ? (await ctx.api().evaluation.getTriggers(ref.projectId, ref.projectBranch, ref.entityId, ref.entityBranch))\n .filter((t) => t.triggerId)\n .map((t) => ({ label: `${t.type}${t.expression ? ` ${t.expression}` : ''}`, value: t.triggerId!, hint: t.triggerId! })) : []);\n }\n case 'chatSession':\n return listed(ctx, 'chat sessions', messageFor(input, 'Chat session'), async () =>\n (await ctx.api().language.getSessions())\n .map((s) => ({ label: s.title || '(untitled)', value: s.sessionId, hint: `${s.modified} · ${s.sessionId}` })));\n case 'apiToken':\n return listed(ctx, 'API tokens', messageFor(input, 'API token'), async () =>\n (await ctx.api().admin.getApiTokens()).map((t) => ({\n label: t.name,\n value: t.tokenId,\n hint: `${t.resourceType} ${t.resourceId} · ${t.scopes.join(',')}`,\n })));\n case 'tokenResource':\n return text(ctx, 'resourceType')?.toLowerCase() === 'team'\n ? listed(ctx, 'teams', 'Team', async () =>\n (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id })))\n : askProject(ctx, false, 'Project');\n case 'dataSource':\n return listed(ctx, 'data sources', messageFor(input, 'Data source'), async () =>\n (await ctx.api().storage.listDataSources(defaultProject(ctx)))\n .map((d) => ({ label: d.name, value: d.id, hint: `${d.type} · ${d.id}` })));\n case 'dataSourceRun': {\n const id = text(ctx, 'id');\n return listed(ctx, 'runs', messageFor(input, 'Run'), async () =>\n id ? (await ctx.api().storage.listDataSourceRuns(id, 20))\n .map((r) => ({ label: r.status, value: r.runId, hint: `${r.startedAt ?? ''} · ${r.runId}` })) : []);\n }\n case 'skeleton': {\n const projectId = defaultProject(ctx) ?? await askProject(ctx, false, 'Project');\n return listed(ctx, 'skeletons', messageFor(input, 'Skeleton'), async () =>\n (await ctx.api().storage.listSkeletons(projectId))\n .map((s) => ({ label: s.name, value: s.id, hint: `${s.template} · ${s.id}` })));\n }\n case 'tableExporter':\n return listed(ctx, 'exporters', messageFor(input, 'Exporter'), async () =>\n (await ctx.api().storage.listUserDefinedExporters())\n .filter((e) => e.id)\n .map((e) => ({ label: e.name, value: e.id!, hint: `${e.format} · ${e.id}` })));\n case 'tableExport': {\n const ref = entityRef(ctx, 'ref');\n return listed(ctx, 'exports', messageFor(input, 'Export'), async () =>\n ref ? (await ctx.api().storage.listExports(ref)).map((e) => ({\n label: e.filename,\n value: e.exportId,\n hint: `${e.finished ? (e.succeeded ? 'done' : 'failed') : `${Math.round(e.progress * 100)}%`} · ${e.exportId}`,\n })) : []);\n }\n case 'invoice':\n return listed(ctx, 'invoices', messageFor(input, 'Invoice'), async () => {\n const invoices = (await ctx.api().admin.getInvoices()) as Array<{\n invoiceNumber: number | string; kind?: string; periodFrom?: string; periodTo?: string;\n total?: number; currency?: string | null; status?: string;\n }>;\n for (const i of invoices) ctx.prefill.set(`invoiceKind:${i.invoiceNumber}`, i.kind ?? 'INVOICE');\n return invoices.map((i) => ({\n label: `#${i.invoiceNumber} ${i.periodFrom ?? ''} to ${i.periodTo ?? ''}`,\n value: String(i.invoiceNumber),\n hint: `${i.status ?? ''} · ${i.total ?? ''} ${i.currency ?? ''}`.trim(),\n }));\n });\n case 'invoiceDocument': {\n const number = text(ctx, 'invoiceNumber');\n const kind = number ? ctx.prefill.get(`invoiceKind:${number}`) : undefined;\n const slug = kind && /credit/i.test(kind) ? 'credit-note' : 'invoice';\n return typed(ctx, messageFor(input, 'Document file name'), { defaultValue: number ? `diafunc-${slug}-${number}.pdf` : undefined });\n }\n case 'projectBranch': {\n const projectId = text(ctx, spec.projectFrom)?.split('/')[0];\n return listed(ctx, 'branches', messageFor(input, 'Branch'), async () =>\n projectId ? (await ctx.api().storage.getProjectBranches(projectId)).map((b) => ({ label: b, value: b })) : []);\n }\n case 'event':\n return askEvent(ctx, input);\n case 'occurrence': {\n const ref = entityRef(ctx, 'ref');\n const eventId = text(ctx, 'eventId');\n return listed(ctx, 'occurrences', messageFor(input, 'Occurrence'), async () =>\n ref ? (await ctx.api().storage.getEvents(ref))\n .filter((e) => !eventId || e.eventId === eventId)\n .map((e) => ({ label: e.occurrenceId, value: e.occurrenceId, hint: e.type })) : []);\n }\n case 'link': {\n const ref = entityRef(ctx, 'sourceRef');\n return listed(ctx, 'links', messageFor(input, 'Link'), async () =>\n ref ? (await ctx.api().storage.getLinkIds('FORWARD', ref)).map((id) => ({ label: id, value: id })) : []);\n }\n case 'exportFormat':\n return listed(ctx, 'export formats', messageFor(input, 'Export format'), async () =>\n (await ctx.api().storage.getSupportedExportFormats()).formats\n .map((f) => ({ label: f.displayName, value: f.id, hint: `${f.id} · ${f.category}` })));\n case 'connectorType':\n return listed(ctx, 'connector types', messageFor(input, 'Connector type'), async () =>\n (await ctx.api().storage.listDataSourceConnectorTypes()).map((t) => ({ label: t, value: t })));\n case 'profile':\n return listed(ctx, 'profiles', messageFor(input, 'Profile'), async () =>\n Object.keys(loadConfig().profiles).map((p) => ({ label: p, value: p })));\n case 'statusComponent':\n return listed(ctx, 'components', messageFor(input, 'Component'), async () =>\n (await createStatusService().getComponents())\n .map((c) => ({ label: c.id, value: c.id, hint: `${c.state} · ${c.domainId}` })));\n case 'license':\n return listed(ctx, 'licenses', messageFor(input, 'License'), async () =>\n (await ctx.api().admin.listLicenses())\n .map((l) => ({ label: l.name, value: l.licenceId, hint: `${l.state.toLowerCase()} · ${l.licenceId}` })));\n case 'choice':\n return choose(ctx, question(input), spec.choices.map((c) => ({ label: c, value: c })));\n case 'choices': {\n const chosen = await ctx.prompter.checkbox({\n message: question(input),\n choices: spec.choices.map((c) => ({ name: c, value: c })),\n validate: (picked) => picked.length > 0 || 'Pick at least one.',\n });\n return chosen.join(',');\n }\n case 'file':\n return typed(ctx, question(input), {\n validate: (value) => fs.existsSync(value.trim()) || `No file at ${value.trim()}.`,\n });\n case 'number':\n return typed(ctx, question(input), { validate: numberRule(spec) });\n case 'date':\n return typed(ctx, question(input), {\n defaultValue: currentUtcHour(),\n validate: (value) => /^\\d{4}-\\d{2}-\\d{2}-\\d{2}$/.test(value.trim()) || 'Use YYYY-MM-DD-HH, in UTC.',\n });\n case 'text':\n return typed(ctx, question(input), {\n allowEmpty: spec.allowEmpty,\n defaultValue: spec.defaultValue,\n validate: spec.email\n ? (value) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value.trim()) || 'That is not an email address.'\n : undefined,\n });\n }\n}\n\n// ---------- projects and entities: live index search ----------\n\nasync function askProject(ctx: AskContext, withBranch: boolean, message: string): Promise<string> {\n const projectId = await fromIndex(ctx, message, { contentType: 'project' }, (item) => item.projectId);\n if (!withBranch) return projectId;\n let branches: string[] = [];\n try {\n branches = await ctx.api().storage.getProjectBranches(projectId);\n } catch { /* one branch is the common case; the answer still works without the listing */ }\n if (branches.length <= 1) return projectId;\n const branch = await choose(ctx, 'Branch', branches.map((b) => ({ label: b, value: b })), 'main');\n return branch === 'main' ? projectId : `${projectId}/${branch}`;\n}\n\nasync function askEntity(\n ctx: AskContext,\n spec: Extract<InputSpec, { kind: 'entity' }>,\n input: PendingInput,\n): Promise<string | string[]> {\n const { projectId, projectBranch } = await projectContext(ctx, spec.projectFrom);\n const noun = spec.contentType ? capitalize(spec.contentType) : 'Entity';\n const query = { contentType: spec.contentType, projectId, projectBranch };\n const answer = (item: SearchItem) => spec.form === 'id'\n ? item.entityId!\n : [item.projectId, item.projectBranch, item.entityId, ...(item.entityBranch && item.entityBranch !== 'main' ? [item.entityBranch] : [])].join('/');\n\n if (spec.multiple) {\n let items: SearchItem[] = [];\n try {\n items = await indexItems(ctx, '*', query, 200);\n } catch (error) {\n ctx.note(`Could not list them (${reason(error)}).`);\n }\n if (items.length === 0) {\n const typed = await typedValue(ctx, `${question(input)} (space-separated)`);\n return typed.split(/[\\s,]+/).filter(Boolean);\n }\n return ctx.prompter.checkbox({\n message: messageFor(input, `${noun}s`),\n choices: items.map((item) => ({ name: labelled(item.name || item.entityId!, item.entityId!), value: answer(item) })),\n validate: (picked) => picked.length > 0 || 'Pick at least one.',\n });\n }\n return fromIndex(ctx, messageFor(input, noun), query, answer);\n}\n\n/** Where an entity question looks: the input it names, else the global flags, else the profile, else asks. */\nasync function projectContext(ctx: AskContext, projectFrom?: string): Promise<{ projectId: string; projectBranch: string }> {\n const config = loadConfig();\n const raw = (projectFrom ? text(ctx, projectFrom) : undefined)\n ?? ctx.globals.project\n ?? config.defaults.project\n ?? await askProject(ctx, true, 'Project');\n const [projectId, branch] = raw.split('/');\n return { projectId, projectBranch: branch || ctx.globals.branch || config.defaults.branch || 'main' };\n}\n\n/** How many of the newest items a type-to-filter picker reads before it asks the index by word. */\nconst FIRST_PAGE = 100;\n\n/**\n * Type-to-filter over the search index, which is where names live: a project's name is on its main\n * entity, not on the project row, and tables and functions sit inside notebooks rather than at the\n * project's top level.\n *\n * The index matches whole words only, so \"prom\" finds nothing and \"prompt\" does not find\n * \"prompt-qa\". Asking it on every keystroke would show nothing until a word was complete. Instead\n * the newest items are read once and filtered locally by any part of the name or id; a term that\n * matches none of them is then sent to the index, which still reaches older items by whole word.\n */\nasync function fromIndex(\n ctx: AskContext,\n message: string,\n query: { contentType?: EntityContentType | 'project'; projectId?: string; projectBranch?: string },\n answer: (item: SearchItem) => string,\n): Promise<string> {\n let firstPage: SearchItem[] | null = null;\n let warned = false;\n const toChoice = (item: SearchItem): Choice<string> => ({\n name: labelled(item.name || item.entityId || item.projectId, item.entityId ?? item.projectId),\n value: answer(item),\n });\n const picked = await ctx.prompter.search<string>({\n message,\n source: async (term) => {\n try {\n firstPage ??= await indexItems(ctx, '*', query, FIRST_PAGE);\n const needle = term.trim().toLowerCase();\n let items = needle\n ? firstPage.filter((item) => `${item.name ?? ''} ${item.entityId ?? item.projectId}`.toLowerCase().includes(needle))\n : firstPage;\n if (needle && items.length === 0) items = await indexItems(ctx, term.trim(), query, 30);\n return [...items.map(toChoice), typeItChoice()];\n } catch (error) {\n if (!warned) ctx.note(`Could not search (${reason(error)}).`);\n warned = true;\n return [typeItChoice()];\n }\n },\n });\n return picked === TYPE_IT ? typedValue(ctx, message) : picked;\n}\n\nasync function indexItems(\n ctx: AskContext,\n term: string,\n query: { contentType?: EntityContentType | 'project'; projectId?: string; projectBranch?: string },\n limit: number,\n): Promise<SearchItem[]> {\n const page = await ctx.api().index.searchPage({\n query: term,\n limit,\n contentType: query.contentType ?? null,\n projectId: query.projectId ?? null,\n projectBranch: query.projectId ? (query.projectBranch ?? 'main') : null,\n });\n const seen = new Set<string>();\n return page.items.filter((item) => {\n // A project row is not an entity; an entity question must not offer one.\n if (query.contentType !== 'project' && !item.entityId) return false;\n const key = [item.contentType, item.projectId, item.projectBranch, item.entityId, item.entityBranch].join('|');\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n// ---------- analyses, evaluations, events ----------\n\nasync function askAnalysis(ctx: AskContext, message: string): Promise<string> {\n return listed(ctx, 'analyses', message, async () =>\n (await ctx.api().analysis.getRecent(50)).map((a) => ({\n label: a.name,\n value: a.analysisId,\n hint: `${a.latestRunState ?? 'never run'} · ${a.analysisId}`,\n })));\n}\n\nasync function askColumns(\n ctx: AskContext,\n spec: Extract<InputSpec, { kind: 'analysisColumns' }>,\n input: PendingInput,\n): Promise<string | string[]> {\n const analysisId = text(ctx, 'id');\n let columns: string[] = [];\n try {\n if (analysisId) columns = (await ctx.api().analysis.getColumns(analysisId)).map((c) => c.name).filter(Boolean);\n } catch (error) {\n ctx.note(`Could not read the columns (${reason(error)}).`);\n }\n if (columns.length === 0) return typed(ctx, question(input), { allowEmpty: spec.allowEmpty });\n if (spec.multiple) {\n const chosen = await ctx.prompter.checkbox({\n message: messageFor(input, 'Columns'),\n choices: columns.map((c) => ({ name: c, value: c })),\n validate: (picked) => picked.length > 0 || 'Pick at least one column.',\n });\n // One argument per column, never joined: a column name may itself hold a comma.\n return chosen;\n }\n const items: Item[] = columns.map((c) => ({ label: c, value: c }));\n if (spec.allowEmpty) items.unshift({ label: 'None (clear it)', value: '' });\n return choose(ctx, messageFor(input, 'Column'), items);\n}\n\nasync function askEvaluation(ctx: AskContext, input: PendingInput): Promise<string> {\n const ref = entityRef(ctx, 'ref');\n const hour = parseHour(text(ctx, 'date') ?? currentUtcHour());\n return listed(ctx, 'evaluations in that hour', messageFor(input, 'Evaluation'), async () =>\n ref && hour ? (await ctx.api().evaluation.getEvaluations(\n ref.projectId, ref.projectBranch, ref.entityId, ref.entityBranch, hour.year, hour.month, hour.day, hour.hour,\n )).map((e) => ({ label: e.evaluationId, value: e.evaluationId, hint: e.active ? 'running' : 'finished' })) : []);\n}\n\nasync function askEvent(ctx: AskContext, input: PendingInput): Promise<string> {\n const ref = entityRef(ctx, 'ref');\n let events: Awaited<ReturnType<ApiClient['storage']['getEvents']>> = [];\n try {\n if (ref) events = await ctx.api().storage.getEvents(ref);\n } catch (error) {\n ctx.note(`Could not list the events (${reason(error)}).`);\n }\n if (events.length === 0) return typedValue(ctx, question(input));\n const key = await choose(ctx, messageFor(input, 'Event'), events.map((e) => ({\n label: `${e.type} ${e.eventId}`,\n value: `${e.eventId}\\u0000${e.occurrenceId}`,\n hint: e.occurrenceId,\n })));\n if (key === TYPE_IT || !key.includes('\\u0000')) return key === TYPE_IT ? typedValue(ctx, question(input)) : key;\n const [eventId, occurrenceId] = key.split('\\u0000');\n // One pick names both halves of the key; the occurrence question, if pending, is already answered.\n ctx.prefill.set('occurrenceId', occurrenceId);\n return eventId;\n}\n\n// ---------- generic list / choose / type ----------\n\n/** A picker over a list read from the API, with the text fallbacks every picker owes the reader. */\nasync function listed(ctx: AskContext, noun: string, message: string, load: () => Promise<Item[]>): Promise<string> {\n let items: Item[];\n try {\n items = await load();\n } catch (error) {\n ctx.note(`Could not list ${noun} (${reason(error)}); type it instead.`);\n return typedValue(ctx, message);\n }\n if (items.length === 0) {\n ctx.note(`No ${noun} to choose from; type it instead.`);\n return typedValue(ctx, message);\n }\n const picked = await choose(ctx, message, items);\n return picked === TYPE_IT ? typedValue(ctx, message) : picked;\n}\n\n/** One of `items`, scrolled when short and filtered by typing when long, with \"Type it instead\" last. */\nasync function choose(ctx: AskContext, message: string, items: Item[], defaultValue?: string): Promise<string> {\n const choices: Choice<string>[] = [\n ...items.map((i) => ({ name: labelled(i.label, i.hint), value: i.value })),\n typeItChoice(),\n ];\n if (items.length > SEARCH_THRESHOLD) {\n return ctx.prompter.search<string>({\n message,\n source: (term) => {\n const needle = term.trim().toLowerCase();\n if (!needle) return choices;\n return [\n ...choices.filter((c) => c.value !== TYPE_IT && `${c.name} ${c.value}`.toLowerCase().includes(needle)),\n typeItChoice(),\n ];\n },\n });\n }\n return ctx.prompter.select<string>({ message, choices, default: defaultValue });\n}\n\nasync function typed(\n ctx: AskContext,\n message: string,\n options: { allowEmpty?: boolean; defaultValue?: string; validate?: (value: string) => true | string } = {},\n): Promise<string> {\n const value = await ctx.prompter.input({\n message,\n default: options.defaultValue,\n validate: (raw) => {\n if (!options.allowEmpty && raw.trim().length === 0) return 'A value is required.';\n if (options.allowEmpty && raw.trim().length === 0) return true;\n return options.validate ? options.validate(raw) : true;\n },\n });\n return value.trim();\n}\n\nfunction typedValue(ctx: AskContext, message: string): Promise<string> {\n return typed(ctx, message);\n}\n\nfunction typeItChoice(): Choice<string> {\n return { name: chalk.dim('Type it instead'), value: TYPE_IT };\n}\n\n// ---------- small helpers ----------\n\n/** A known value as a string, if there is one. */\nfunction text(ctx: AskContext, name: string): string | undefined {\n const value = ctx.known.get(name);\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction entityRef(ctx: AskContext, name: string) {\n const ref = text(ctx, name);\n if (!ref) return undefined;\n try {\n return parseEntityReference(ref, ctx.globals);\n } catch {\n return undefined;\n }\n}\n\nfunction defaultProject(ctx: AskContext): string | undefined {\n return (ctx.globals.project ?? loadConfig().defaults.project)?.split('/')[0];\n}\n\n/**\n * The question for a picker: its noun, keeping a leading \"Source\" or \"Target\" from the command's own\n * description so `link create` asks for a source entity and then a target one.\n */\nfunction messageFor(input: PendingInput, noun: string): string {\n const lead = /^(Source|Target)\\b/.exec(input.description)?.[1];\n return lead ? `${lead} ${noun.toLowerCase()}` : noun;\n}\n\n/** The question for a typed value: the command's own description of the input. */\nfunction question(input: PendingInput): string {\n const text = input.description.trim() || input.name;\n return capitalize(text);\n}\n\nfunction capitalize(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction labelled(label: string, hint?: string): string {\n return hint && hint !== label ? `${label} ${chalk.dim(hint)}` : label;\n}\n\nfunction numberRule(spec: Extract<InputSpec, { kind: 'number' }>): (value: string) => true | string {\n return (raw) => {\n const value = Number(raw.trim());\n if (raw.trim() === '' || !Number.isFinite(value)) return 'Enter a number.';\n if (spec.integer && !Number.isInteger(value)) return 'Enter a whole number.';\n if (spec.exclusive ? value <= spec.min : value < spec.min) {\n return spec.exclusive ? `Enter a number above ${spec.min}.` : `Enter ${spec.min} or more.`;\n }\n return true;\n };\n}\n\n/** The current hour in UTC as `YYYY-MM-DD-HH`, the form the evaluation commands take. */\nexport function currentUtcHour(now: Date = new Date()): string {\n const iso = now.toISOString();\n return `${iso.slice(0, 10)}-${iso.slice(11, 13)}`;\n}\n\nfunction parseHour(value: string): { year: number; month: number; day: number; hour: number } | null {\n const match = /^(\\d{4})-(\\d{2})-(\\d{2})-(\\d{2})$/.exec(value.trim());\n if (!match) return null;\n return { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]), hour: Number(match[4]) };\n}\n\nfunction when(epochMs: number | null): string {\n return epochMs ? new Date(epochMs).toISOString().slice(0, 16).replace('T', ' ') : '';\n}\n\nfunction reason(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;AAAA,OAAOA,aAAW;;;ACClB,OAAOC,YAAW;;;ACDlB,YAAYC,SAAQ;AACpB,YAAYC,WAAU;AACtB,YAAYC,SAAQ;AACpB,YAAYC,aAAY;;;ACHxB,YAAY,YAAY;AACxB,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;AA4Bf,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EAET,YAAY,UAAkB,UAAkB;AAC9C,UAAM,mBAAmB,KAAK,MAAM,WAAW,GAAI,CAAC,iBAAiB,QAAQ,GAAG;AAChF,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAEO,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAC/B,IAAM,kBAAkB;AAUxB,IAAM,OAAO,oBAAI,IAAoB;AACrC,IAAI,o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OAAO;AAC5B,wBAAsB,OAAO;AAC7B,2BAAyB,OAAO;AAChC,0BAAwB,OAAO;AAE/B,SAAO;AACT;","names":["chalk","chalk","fs","path","os","crypto","resolve","change","detail","text","crypto","fs","sleep","resolve","reason","path","text","url","resolve","reason","chalk","chalk","chalk","text","chalk","deriveAuthUrl","chalk","text","resolve","deriveAuthUrl","chalk","chalk","text","chalk","text","pad","chalk","text","chalk","chalk","SERVICE","SERVICE","change","path","format","SERVICE","enc","SERVICE","enc","SERVICE","enc","SERVICE","enc","chalk","chalk","chalk","profile","path","chalk","defaultProject","chalk","fs","path","chalk","chalk","chalk","sleep","resolve","take","chalk","typed","typed","chalk","chalk","hint","resolve","getOutputFormat","getOutputFormat","chalk","project","chalk","getOutputFormat","chalk","change","fs","getOutputFormat","getOverrides","text","getOutputFormat","getOverrides","getOutputFormat","getOverrides","event","fs","resolve","getOutputFormat","getOverrides","chalk","fs","path","text","cell","randomUUID","getOutputFormat","getOverrides","chalk","cell","row","randomUUID","resolve","format","chalk","fs","path","getOutputFormat","getOverrides","chalk","chalk","fs","os","path","randomUUID","randomBytes","text","getOutputFormat","getOverrides","chalk","resolve","randomUUID","fs","chalk","text","listed","text","refuse","typed","pause","resolve","chalk","text","path","getOutputFormat","getOverrides","getOutputFormat","getOverrides","chalk","fs","path","chalk","chalk","heading","text","quote","getOutputFormat","chalk","detail","chalk","getOutputFormat","chalk","text","readFile","chalk","getOutputFormat","typed","chalk","text","resolve","getOutputFormat","reason","getOutputFormat","readFile","chalk","path","chalk","chalk","stateSymbol","chalk","chalk","chalk","fs","path","spawn","chalk","chalk","detail","chalk","chalk","typed","question","reason","chalk","chalk","sleep","resolve","pause","fs","path","spawn","getOutputFormat","question","resolve","text","typed","getOutputFormat","text","chalk","getOutputFormat","parseSortOrder","chalk","chalk","getOutputFormat","chalk","listRuns","chalk","getOutputFormat","chalk","chalk","fs","getOutputFormat","resolveProjectId","chalk","chalk","chalk","chalk","getOutputFormat","when","chalk","getOutputFormat","getOverrides","getOutputFormat","fs","getOutputFormat","chalk","fs","os","path","spawn","randomUUID","extensionFor","randomUUID","resolve","spawn","chalk","cmd","chalk","path","spawn","fs","resolve","spawn","chalk","chalk","spawn","fs","os","path","chalk","spawn","Command","Command","chalk","fs","chalk","typed","FIRST_PAGE","chalk","text","hint","chalk","chalk"]}