bonbox 0.2.0 → 0.3.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.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/commands/account.ts","../src/auth.ts","../src/config.ts","../src/i18n/en.json","../src/i18n/de.json","../src/i18n/fr.json","../src/i18n/it.json","../src/i18n/index.ts","../src/errors.ts","../src/api.ts","../src/lib/context.ts","../src/commands/customers.ts","../src/format.ts","../src/commands/invoices.ts","../src/lib/args.ts","../src/lib/customers.ts","../src/lib/items.ts","../src/commands/login.ts","../src/commands/receipts.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from 'citty';\n\nimport { logoutCommand, whoamiCommand } from './commands/account.js';\nimport { customersCommand } from './commands/customers.js';\nimport { invoicesCommand } from './commands/invoices.js';\nimport { loginCommand } from './commands/login.js';\nimport { receiptsCommand } from './commands/receipts.js';\nimport { CliError, EXIT_ERROR, EXIT_USAGE } from './errors.js';\nimport { resolveLocale, setLocale, t } from './i18n/index.js';\nimport { langFromArgv } from './lib/context.js';\n\nconst VERSION = '0.2.0';\n\nconst argv = process.argv.slice(2);\nsetLocale(resolveLocale(langFromArgv(argv)));\n\n/** citty would read the value of `--lang de` as a sub-command name; the locale is\n * applied globally before parsing, so the flag can be dropped from the arg list. */\nfunction withoutLangFlag(rawArgs: string[]): string[] {\n const kept: string[] = [];\n for (let index = 0; index < rawArgs.length; index += 1) {\n const entry = rawArgs[index] ?? '';\n if (entry === '--lang') {\n index += 1;\n continue;\n }\n if (entry.startsWith('--lang=')) continue;\n kept.push(entry);\n }\n return kept;\n}\n\nconst cliArgs = withoutLangFlag(argv);\n\nconst main = defineCommand({\n meta: { name: 'bonbox', version: VERSION, description: t('cli_app_description') },\n subCommands: {\n login: loginCommand(),\n logout: logoutCommand(),\n whoami: whoamiCommand(),\n customers: customersCommand(),\n invoices: invoicesCommand(),\n receipts: receiptsCommand(),\n },\n});\n\n/** Walk into the deepest sub-command named on the command line, for --help. */\nasync function resolveSubCommand(\n command: CommandDef,\n rawArgs: string[],\n parent?: CommandDef,\n): Promise<[CommandDef, CommandDef | undefined]> {\n const subCommands = command.subCommands as Record<string, CommandDef> | undefined;\n if (subCommands && Object.keys(subCommands).length > 0) {\n const index = rawArgs.findIndex((arg) => !arg.startsWith('-'));\n const name = rawArgs[index];\n const sub = name ? subCommands[name] : undefined;\n if (sub) return resolveSubCommand(sub, rawArgs.slice(index + 1), command);\n }\n return [command, parent];\n}\n\n/** citty signals unknown/missing commands with a CLIError; those are usage errors. */\nfunction isUsageError(error: unknown): boolean {\n const code = (error as { code?: string })?.code;\n return code === 'E_UNKNOWN_COMMAND' || code === 'E_NO_COMMAND';\n}\n\nasync function run(): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h') || cliArgs.length === 0) {\n await showUsage(...(await resolveSubCommand(main, cliArgs)));\n return 0;\n }\n if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-v')) {\n process.stdout.write(`${VERSION}\\n`);\n return 0;\n }\n\n try {\n await runCommand(main, { rawArgs: cliArgs });\n return 0;\n } catch (error) {\n if (isUsageError(error)) {\n process.stderr.write(`${(error as Error).message}\\n`);\n await showUsage(...(await resolveSubCommand(main, cliArgs)));\n return EXIT_USAGE;\n }\n if (error instanceof CliError) {\n process.stderr.write(`${error.message}\\n`);\n return error.exitCode;\n }\n process.stderr.write(`${(error as Error)?.message ?? String(error)}\\n`);\n return EXIT_ERROR;\n }\n}\n\nprocess.exit(await run());\n","import { defineCommand } from 'citty';\n\nimport { clearSessionFile, getSupabase } from '../auth.js';\nimport { t } from '../i18n/index.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport type { Me } from '../types.js';\n\nexport function logoutCommand() {\n return defineCommand({\n meta: { name: 'logout', description: t('cli_cmd_logout') },\n args: commonArgs(),\n async run({ args }) {\n await getSupabase().auth.signOut({ scope: 'local' }).catch(() => undefined);\n const removed = clearSessionFile();\n if (args.json) printJson({ signedOut: removed });\n else out(removed ? t('cli_logout_done') : t('cli_logout_none'));\n },\n });\n}\n\nexport function whoamiCommand() {\n return defineCommand({\n meta: { name: 'whoami', description: t('cli_cmd_whoami') },\n args: commonArgs(),\n async run({ args }) {\n const me = await client().get<Me>('/me');\n if (args.json) {\n printJson(me);\n return;\n }\n const rows: [string, string][] = [\n [t('cli_label_email'), me.email ?? me.id],\n [t('cli_label_plan'), me.isPro ? t('cli_plan_pro') : t('cli_plan_free')],\n ];\n if (me.companyName) rows.push([t('cli_label_company'), me.companyName]);\n if (me.defaultCurrency) rows.push([t('cli_label_currency'), me.defaultCurrency]);\n\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) out(`${label.padEnd(width)} ${value}`);\n },\n });\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js';\nimport { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nimport { SUPABASE_ANON_KEY, SUPABASE_URL } from './config.js';\nimport { CliError } from './errors.js';\nimport { t } from './i18n/index.js';\n\n/** ~/.config/bonbox/session.json, honouring XDG_CONFIG_HOME. */\nexport function sessionPath(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), '.config');\n return join(base, 'bonbox', 'session.json');\n}\n\n/**\n * supabase-js storage backed by a single 0600 JSON file. It holds the session\n * plus the transient PKCE verifier, keyed exactly as supabase-js expects.\n */\nclass FileStorage {\n constructor(private readonly file: string) {}\n\n private read(): Record<string, string> {\n if (!existsSync(this.file)) return {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(this.file, 'utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, string>) : {};\n } catch {\n return {};\n }\n }\n\n private write(entries: Record<string, string>): void {\n mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });\n writeFileSync(this.file, `${JSON.stringify(entries, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(this.file, 0o600);\n }\n\n getItem(key: string): string | null {\n return this.read()[key] ?? null;\n }\n\n setItem(key: string, value: string): void {\n this.write({ ...this.read(), [key]: value });\n }\n\n removeItem(key: string): void {\n const entries = this.read();\n delete entries[key];\n this.write(entries);\n }\n}\n\nlet cached: SupabaseClient | null = null;\n\nexport function getSupabase(): SupabaseClient {\n if (!cached) {\n cached = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {\n auth: {\n storage: new FileStorage(sessionPath()),\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl: false,\n flowType: 'pkce',\n },\n });\n }\n return cached;\n}\n\n/** Drop the stored session file entirely. */\nexport function clearSessionFile(): boolean {\n const file = sessionPath();\n if (!existsSync(file)) return false;\n rmSync(file);\n return true;\n}\n\n/** A valid access token, refreshed by supabase-js when needed. */\nexport async function getAccessToken(): Promise<string> {\n const { data } = await getSupabase().auth.getSession();\n const token = data.session?.access_token;\n if (!token) throw new CliError(t('cli_error_unauthorized'));\n return token;\n}\n","/** Supabase project the CLI authenticates against. */\nexport const SUPABASE_URL = 'https://gaxsaareqnpthuyjfwrz.supabase.co';\n\n/** Public anon key — safe to ship, it only allows what RLS allows. */\nexport const SUPABASE_ANON_KEY =\n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdheHNhYXJlcW5wdGh1eWpmd3J6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzU3NDkxMjcsImV4cCI6MjA1MTMyNTEyN30.iUiUnilZnLlLLoGam4hC5qcmhC4oDtB2sZDGz0xHU8k';\n\n/** Where users manage their subscription. */\nexport const APP_URL = 'https://app.bonbox.io';\n\nconst DEFAULT_API_BASE = 'https://app.bonbox.io/api/v1';\n\n// Bypasses the app.bonbox.io Vercel proxy for large multipart uploads — it caps request bodies.\nconst SCAN_BASE = `${SUPABASE_URL}/functions/v1/api-v1`;\n\nfunction resolveBase(env: NodeJS.ProcessEnv, fallback: string): string {\n const raw = env.BONBOX_API_URL?.trim();\n return (raw && raw.length > 0 ? raw : fallback).replace(/\\/+$/, '');\n}\n\n/** API base URL, overridable with BONBOX_API_URL (e.g. the Supabase functions URL). */\nexport function apiBase(env: NodeJS.ProcessEnv = process.env): string {\n return resolveBase(env, DEFAULT_API_BASE);\n}\n\n/** Base URL for large multipart uploads (receipt scans), bypassing the Vercel proxy. */\nexport function scanBase(env: NodeJS.ProcessEnv = process.env): string {\n return resolveBase(env, SCAN_BASE);\n}\n\n/** Ports tried in order for the local OAuth callback listener. */\nexport const CALLBACK_PORTS = [51823, 51824, 51825] as const;\n","{\n \"cli_app_description\": \"Manage your bonbox receipts, invoices and customers from the terminal.\",\n \"cli_cmd_login\": \"Sign in to your bonbox account\",\n \"cli_cmd_logout\": \"Sign out on this machine\",\n \"cli_cmd_whoami\": \"Show the account you are signed in with\",\n \"cli_cmd_customers\": \"Work with your customers\",\n \"cli_cmd_customers_ls\": \"List your customers\",\n \"cli_cmd_invoices\": \"Work with your invoices and quotes\",\n \"cli_cmd_invoices_ls\": \"List invoices and quotes\",\n \"cli_cmd_invoices_create\": \"Create an invoice or a quote\",\n \"cli_cmd_invoices_pdf\": \"Download the PDF of an invoice or quote\",\n \"cli_cmd_invoices_paid\": \"Mark an invoice as paid\",\n \"cli_cmd_invoices_unpaid\": \"Mark an invoice as unpaid again\",\n \"cli_cmd_receipts\": \"Work with your receipts\",\n \"cli_cmd_receipts_ls\": \"List your receipts\",\n \"cli_cmd_receipts_add\": \"Add a receipt by hand\",\n \"cli_cmd_receipts_scan\": \"Upload a receipt and let bonbox read it\",\n \"cli_flag_json\": \"Print the raw API response as JSON\",\n \"cli_flag_lang\": \"Output language (en, de, fr, it)\",\n \"cli_flag_archived\": \"Include archived customers\",\n \"cli_flag_status\": \"Filter by status: created or paid\",\n \"cli_flag_quotes\": \"Show quotes instead of invoices\",\n \"cli_flag_customer_ref\": \"Customer name or ID\",\n \"cli_flag_item\": \"Line item as description:quantity:unitPrice[:discount%], can be repeated\",\n \"cli_flag_quote\": \"Create a quote instead of an invoice\",\n \"cli_flag_invoice_date\": \"Invoice date (YYYY-MM-DD), today by default\",\n \"cli_flag_payment_days\": \"Payment term in days\",\n \"cli_flag_currency\": \"Currency code, for example CHF\",\n \"cli_flag_language\": \"Document language: de, en, fr or it\",\n \"cli_flag_subtitle\": \"Subtitle shown on the document\",\n \"cli_flag_reference\": \"Your reference for this document\",\n \"cli_flag_pdf\": \"Also save the PDF to this file\",\n \"cli_flag_output\": \"Save the PDF to this file\",\n \"cli_flag_paid_date\": \"Payment date (YYYY-MM-DD), today by default\",\n \"cli_flag_no_receipt\": \"Do not book the payment as income\",\n \"cli_flag_month\": \"Limit to one month (YYYY-MM)\",\n \"cli_flag_from\": \"Start date (YYYY-MM-DD)\",\n \"cli_flag_to\": \"End date (YYYY-MM-DD)\",\n \"cli_flag_project\": \"Project ID\",\n \"cli_flag_seller\": \"Seller, or the customer for income\",\n \"cli_flag_price\": \"Amount, for example 23.50\",\n \"cli_flag_receipt_date\": \"Receipt date (YYYY-MM-DD), today by default\",\n \"cli_flag_category\": \"Category\",\n \"cli_flag_tax_category\": \"Tax category\",\n \"cli_flag_booking_text\": \"Booking text\",\n \"cli_arg_invoice_ref\": \"Invoice number or ID\",\n \"cli_arg_scan_files\": \"Image or PDF files, all pages of one receipt\",\n \"cli_error_unauthorized\": \"You are not signed in. Run: bonbox login\",\n \"cli_error_pro_required\": \"This needs bonbox Pro. You can upgrade at %1$s\",\n \"cli_error_quota\": \"You have reached the limit of your plan. You can upgrade at %1$s\",\n \"cli_error_network\": \"Could not reach bonbox: %1$s\",\n \"cli_error_unexpected_response\": \"Unexpected answer from bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Invalid item \\\"%1$s\\\". Expected description:quantity:unitPrice[:discount%]\",\n \"cli_error_item_number\": \"Invalid number in item \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Add at least one line item with --item\",\n \"cli_error_customer_required\": \"Name a customer with --customer\",\n \"cli_error_price_required\": \"Give an amount with --price\",\n \"cli_error_seller_required\": \"Give a seller with --seller\",\n \"cli_error_price_invalid\": \"Invalid amount: %1$s\",\n \"cli_error_date_invalid\": \"Invalid date: %1$s. Expected YYYY-MM-DD\",\n \"cli_error_month_invalid\": \"Invalid month: %1$s. Expected YYYY-MM\",\n \"cli_error_customer_not_found\": \"No customer matches \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" matches several customers:\",\n \"cli_error_files_required\": \"Name at least one file to scan\",\n \"cli_error_file_missing\": \"File not found: %1$s\",\n \"cli_login_opening\": \"Opening the bonbox sign-in page in your browser ...\",\n \"cli_login_manual\": \"If your browser does not open, visit:\\n%1$s\",\n \"cli_login_waiting\": \"Waiting for you to finish signing in ...\",\n \"cli_login_success\": \"Signed in as %1$s\",\n \"cli_login_failed\": \"Sign-in failed: %1$s\",\n \"cli_login_timeout\": \"Sign-in timed out. Please try again.\",\n \"cli_login_no_port\": \"No free port for the sign-in callback (tried %1$s).\",\n \"cli_callback_title\": \"Signed in to bonbox\",\n \"cli_callback_heading\": \"You are signed in\",\n \"cli_callback_body\": \"You can close this tab and go back to the terminal.\",\n \"cli_callback_error_heading\": \"Sign-in failed\",\n \"cli_callback_error_body\": \"Go back to the terminal and try again.\",\n \"cli_logout_done\": \"Signed out.\",\n \"cli_logout_none\": \"You were not signed in.\",\n \"cli_label_email\": \"Email\",\n \"cli_label_plan\": \"Plan\",\n \"cli_label_company\": \"Company\",\n \"cli_label_currency\": \"Currency\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Free\",\n \"cli_col_number\": \"Number\",\n \"cli_col_date\": \"Date\",\n \"cli_col_status\": \"Status\",\n \"cli_col_customer\": \"Customer\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Name\",\n \"cli_col_city\": \"City\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Seller\",\n \"cli_col_amount\": \"Amount\",\n \"cli_col_category\": \"Category\",\n \"cli_col_archived\": \"Archived\",\n \"cli_status_created\": \"Open\",\n \"cli_status_paid\": \"Paid\",\n \"cli_yes\": \"yes\",\n \"cli_no\": \"no\",\n \"cli_empty_customers\": \"No customers yet.\",\n \"cli_empty_invoices\": \"No invoices yet.\",\n \"cli_empty_quotes\": \"No quotes yet.\",\n \"cli_empty_receipts\": \"No receipts found.\",\n \"cli_invoice_created\": \"Invoice %1$s created, %2$s\",\n \"cli_quote_created\": \"Quote %1$s created, %2$s\",\n \"cli_pdf_saved\": \"Saved to %1$s\",\n \"cli_invoice_paid\": \"%1$s marked as paid.\",\n \"cli_invoice_unpaid\": \"%1$s marked as unpaid.\",\n \"cli_receipt_added\": \"Receipt saved: %1$s, %2$s\",\n \"cli_scan_uploading\": \"Uploading %1$s file(s) ...\",\n \"cli_receipt_scanned\": \"Receipt saved: %1$s, %2$s (extracted automatically)\"\n}\n","{\n \"cli_app_description\": \"Belege, Rechnungen und Kunden von bonbox direkt im Terminal verwalten.\",\n \"cli_cmd_login\": \"Beim bonbox-Konto anmelden\",\n \"cli_cmd_logout\": \"Auf diesem Gerät abmelden\",\n \"cli_cmd_whoami\": \"Zeigt das angemeldete Konto\",\n \"cli_cmd_customers\": \"Kunden verwalten\",\n \"cli_cmd_customers_ls\": \"Kunden auflisten\",\n \"cli_cmd_invoices\": \"Rechnungen und Offerten verwalten\",\n \"cli_cmd_invoices_ls\": \"Rechnungen und Offerten auflisten\",\n \"cli_cmd_invoices_create\": \"Rechnung oder Offerte erstellen\",\n \"cli_cmd_invoices_pdf\": \"PDF einer Rechnung oder Offerte herunterladen\",\n \"cli_cmd_invoices_paid\": \"Rechnung als bezahlt markieren\",\n \"cli_cmd_invoices_unpaid\": \"Rechnung wieder als offen markieren\",\n \"cli_cmd_receipts\": \"Belege verwalten\",\n \"cli_cmd_receipts_ls\": \"Belege auflisten\",\n \"cli_cmd_receipts_add\": \"Beleg von Hand erfassen\",\n \"cli_cmd_receipts_scan\": \"Beleg hochladen und von bonbox auslesen lassen\",\n \"cli_flag_json\": \"Antwort der API als reines JSON ausgeben\",\n \"cli_flag_lang\": \"Sprache der Ausgabe (en, de, fr, it)\",\n \"cli_flag_archived\": \"Archivierte Kunden einschliessen\",\n \"cli_flag_status\": \"Nach Status filtern: created oder paid\",\n \"cli_flag_quotes\": \"Offerten statt Rechnungen anzeigen\",\n \"cli_flag_customer_ref\": \"Kundenname oder Kunden-ID\",\n \"cli_flag_item\": \"Position als Beschreibung:Menge:Einzelpreis[:Rabatt%], mehrfach möglich\",\n \"cli_flag_quote\": \"Offerte statt Rechnung erstellen\",\n \"cli_flag_invoice_date\": \"Rechnungsdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_payment_days\": \"Zahlungsfrist in Tagen\",\n \"cli_flag_currency\": \"Währung, zum Beispiel CHF\",\n \"cli_flag_language\": \"Sprache des Dokuments: de, en, fr oder it\",\n \"cli_flag_subtitle\": \"Untertitel auf dem Dokument\",\n \"cli_flag_reference\": \"Ihre Referenz für dieses Dokument\",\n \"cli_flag_pdf\": \"PDF zusätzlich in diese Datei speichern\",\n \"cli_flag_output\": \"PDF in diese Datei speichern\",\n \"cli_flag_paid_date\": \"Zahlungsdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_no_receipt\": \"Zahlung nicht als Einnahme verbuchen\",\n \"cli_flag_month\": \"Auf einen Monat einschränken (JJJJ-MM)\",\n \"cli_flag_from\": \"Startdatum (JJJJ-MM-TT)\",\n \"cli_flag_to\": \"Enddatum (JJJJ-MM-TT)\",\n \"cli_flag_project\": \"Projekt-ID\",\n \"cli_flag_seller\": \"Anbieter, bei Einnahmen der Kunde\",\n \"cli_flag_price\": \"Betrag, zum Beispiel 23.50\",\n \"cli_flag_receipt_date\": \"Belegdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_category\": \"Kategorie\",\n \"cli_flag_tax_category\": \"Steuerkategorie\",\n \"cli_flag_booking_text\": \"Buchungstext\",\n \"cli_arg_invoice_ref\": \"Rechnungsnummer oder ID\",\n \"cli_arg_scan_files\": \"Bild- oder PDF-Dateien, alle Seiten eines Belegs\",\n \"cli_error_unauthorized\": \"Sie sind nicht angemeldet. Führen Sie aus: bonbox login\",\n \"cli_error_pro_required\": \"Dafür wird bonbox Pro benötigt. Upgrade unter %1$s\",\n \"cli_error_quota\": \"Das Limit Ihres Abos ist erreicht. Upgrade unter %1$s\",\n \"cli_error_network\": \"bonbox ist nicht erreichbar: %1$s\",\n \"cli_error_unexpected_response\": \"Unerwartete Antwort von bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Ungültige Position \\\"%1$s\\\". Erwartet: Beschreibung:Menge:Einzelpreis[:Rabatt%]\",\n \"cli_error_item_number\": \"Ungültige Zahl in Position \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Erfassen Sie mindestens eine Position mit --item\",\n \"cli_error_customer_required\": \"Geben Sie einen Kunden mit --customer an\",\n \"cli_error_price_required\": \"Geben Sie einen Betrag mit --price an\",\n \"cli_error_seller_required\": \"Geben Sie einen Anbieter mit --seller an\",\n \"cli_error_price_invalid\": \"Ungültiger Betrag: %1$s\",\n \"cli_error_date_invalid\": \"Ungültiges Datum: %1$s. Erwartet: JJJJ-MM-TT\",\n \"cli_error_month_invalid\": \"Ungültiger Monat: %1$s. Erwartet: JJJJ-MM\",\n \"cli_error_customer_not_found\": \"Kein Kunde passt zu \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" passt auf mehrere Kunden:\",\n \"cli_error_files_required\": \"Geben Sie mindestens eine Datei zum Scannen an\",\n \"cli_error_file_missing\": \"Datei nicht gefunden: %1$s\",\n \"cli_login_opening\": \"Die bonbox-Anmeldeseite wird im Browser geöffnet ...\",\n \"cli_login_manual\": \"Falls sich der Browser nicht öffnet, rufen Sie auf:\\n%1$s\",\n \"cli_login_waiting\": \"Warten auf den Abschluss der Anmeldung ...\",\n \"cli_login_success\": \"Angemeldet als %1$s\",\n \"cli_login_failed\": \"Anmeldung fehlgeschlagen: %1$s\",\n \"cli_login_timeout\": \"Zeitüberschreitung bei der Anmeldung. Bitte erneut versuchen.\",\n \"cli_login_no_port\": \"Kein freier Port für die Anmeldung (versucht: %1$s).\",\n \"cli_callback_title\": \"Bei bonbox angemeldet\",\n \"cli_callback_heading\": \"Sie sind angemeldet\",\n \"cli_callback_body\": \"Sie können diesen Tab schliessen und zum Terminal zurückkehren.\",\n \"cli_callback_error_heading\": \"Anmeldung fehlgeschlagen\",\n \"cli_callback_error_body\": \"Kehren Sie zum Terminal zurück und versuchen Sie es erneut.\",\n \"cli_logout_done\": \"Abgemeldet.\",\n \"cli_logout_none\": \"Sie waren nicht angemeldet.\",\n \"cli_label_email\": \"E-Mail\",\n \"cli_label_plan\": \"Abo\",\n \"cli_label_company\": \"Firma\",\n \"cli_label_currency\": \"Währung\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratis\",\n \"cli_col_number\": \"Nummer\",\n \"cli_col_date\": \"Datum\",\n \"cli_col_status\": \"Status\",\n \"cli_col_customer\": \"Kunde\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Name\",\n \"cli_col_city\": \"Ort\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Anbieter\",\n \"cli_col_amount\": \"Betrag\",\n \"cli_col_category\": \"Kategorie\",\n \"cli_col_archived\": \"Archiviert\",\n \"cli_status_created\": \"Offen\",\n \"cli_status_paid\": \"Bezahlt\",\n \"cli_yes\": \"ja\",\n \"cli_no\": \"nein\",\n \"cli_empty_customers\": \"Noch keine Kunden.\",\n \"cli_empty_invoices\": \"Noch keine Rechnungen.\",\n \"cli_empty_quotes\": \"Noch keine Offerten.\",\n \"cli_empty_receipts\": \"Keine Belege gefunden.\",\n \"cli_invoice_created\": \"Rechnung %1$s erstellt, %2$s\",\n \"cli_quote_created\": \"Offerte %1$s erstellt, %2$s\",\n \"cli_pdf_saved\": \"Gespeichert unter %1$s\",\n \"cli_invoice_paid\": \"%1$s als bezahlt markiert.\",\n \"cli_invoice_unpaid\": \"%1$s als offen markiert.\",\n \"cli_receipt_added\": \"Beleg gespeichert: %1$s, %2$s\",\n \"cli_scan_uploading\": \"%1$s Datei(en) werden hochgeladen ...\",\n \"cli_receipt_scanned\": \"Beleg gespeichert: %1$s, %2$s (automatisch erkannt)\"\n}\n","{\n \"cli_app_description\": \"Gérez vos justificatifs, factures et clients bonbox depuis le terminal.\",\n \"cli_cmd_login\": \"Se connecter à votre compte bonbox\",\n \"cli_cmd_logout\": \"Se déconnecter sur cet appareil\",\n \"cli_cmd_whoami\": \"Afficher le compte connecté\",\n \"cli_cmd_customers\": \"Gérer vos clients\",\n \"cli_cmd_customers_ls\": \"Lister vos clients\",\n \"cli_cmd_invoices\": \"Gérer vos factures et devis\",\n \"cli_cmd_invoices_ls\": \"Lister les factures et devis\",\n \"cli_cmd_invoices_create\": \"Créer une facture ou un devis\",\n \"cli_cmd_invoices_pdf\": \"Télécharger le PDF d'une facture ou d'un devis\",\n \"cli_cmd_invoices_paid\": \"Marquer une facture comme payée\",\n \"cli_cmd_invoices_unpaid\": \"Remettre une facture en attente de paiement\",\n \"cli_cmd_receipts\": \"Gérer vos justificatifs\",\n \"cli_cmd_receipts_ls\": \"Lister vos justificatifs\",\n \"cli_cmd_receipts_add\": \"Saisir un justificatif manuellement\",\n \"cli_cmd_receipts_scan\": \"Envoyer un justificatif et le faire lire par bonbox\",\n \"cli_flag_json\": \"Afficher la réponse brute de l'API en JSON\",\n \"cli_flag_lang\": \"Langue de l'affichage (en, de, fr, it)\",\n \"cli_flag_archived\": \"Inclure les clients archivés\",\n \"cli_flag_status\": \"Filtrer par statut : created ou paid\",\n \"cli_flag_quotes\": \"Afficher les devis au lieu des factures\",\n \"cli_flag_customer_ref\": \"Nom ou identifiant du client\",\n \"cli_flag_item\": \"Poste au format description:quantité:prix unitaire[:remise%], répétable\",\n \"cli_flag_quote\": \"Créer un devis au lieu d'une facture\",\n \"cli_flag_invoice_date\": \"Date de la facture (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_payment_days\": \"Délai de paiement en jours\",\n \"cli_flag_currency\": \"Monnaie, par exemple CHF\",\n \"cli_flag_language\": \"Langue du document : de, en, fr ou it\",\n \"cli_flag_subtitle\": \"Sous-titre affiché sur le document\",\n \"cli_flag_reference\": \"Votre référence pour ce document\",\n \"cli_flag_pdf\": \"Enregistrer aussi le PDF dans ce fichier\",\n \"cli_flag_output\": \"Enregistrer le PDF dans ce fichier\",\n \"cli_flag_paid_date\": \"Date du paiement (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_no_receipt\": \"Ne pas comptabiliser le paiement comme recette\",\n \"cli_flag_month\": \"Limiter à un mois (AAAA-MM)\",\n \"cli_flag_from\": \"Date de début (AAAA-MM-JJ)\",\n \"cli_flag_to\": \"Date de fin (AAAA-MM-JJ)\",\n \"cli_flag_project\": \"Identifiant du projet\",\n \"cli_flag_seller\": \"Fournisseur, ou le client pour une recette\",\n \"cli_flag_price\": \"Montant, par exemple 23.50\",\n \"cli_flag_receipt_date\": \"Date du justificatif (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_category\": \"Catégorie\",\n \"cli_flag_tax_category\": \"Catégorie fiscale\",\n \"cli_flag_booking_text\": \"Libellé comptable\",\n \"cli_arg_invoice_ref\": \"Numéro de facture ou identifiant\",\n \"cli_arg_scan_files\": \"Fichiers image ou PDF, toutes les pages d'un justificatif\",\n \"cli_error_unauthorized\": \"Vous n'êtes pas connecté. Exécutez : bonbox login\",\n \"cli_error_pro_required\": \"Cette action nécessite bonbox Pro. Passez à Pro sur %1$s\",\n \"cli_error_quota\": \"Vous avez atteint la limite de votre abonnement. Passez à Pro sur %1$s\",\n \"cli_error_network\": \"bonbox est injoignable : %1$s\",\n \"cli_error_unexpected_response\": \"Réponse inattendue de bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Poste invalide \\\"%1$s\\\". Attendu : description:quantité:prix unitaire[:remise%]\",\n \"cli_error_item_number\": \"Nombre invalide dans le poste \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Ajoutez au moins un poste avec --item\",\n \"cli_error_customer_required\": \"Indiquez un client avec --customer\",\n \"cli_error_price_required\": \"Indiquez un montant avec --price\",\n \"cli_error_seller_required\": \"Indiquez un fournisseur avec --seller\",\n \"cli_error_price_invalid\": \"Montant invalide : %1$s\",\n \"cli_error_date_invalid\": \"Date invalide : %1$s. Attendu : AAAA-MM-JJ\",\n \"cli_error_month_invalid\": \"Mois invalide : %1$s. Attendu : AAAA-MM\",\n \"cli_error_customer_not_found\": \"Aucun client ne correspond à \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" correspond à plusieurs clients :\",\n \"cli_error_files_required\": \"Indiquez au moins un fichier à traiter\",\n \"cli_error_file_missing\": \"Fichier introuvable : %1$s\",\n \"cli_login_opening\": \"Ouverture de la page de connexion bonbox dans votre navigateur ...\",\n \"cli_login_manual\": \"Si le navigateur ne s'ouvre pas, rendez-vous sur :\\n%1$s\",\n \"cli_login_waiting\": \"En attente de la fin de la connexion ...\",\n \"cli_login_success\": \"Connecté en tant que %1$s\",\n \"cli_login_failed\": \"Échec de la connexion : %1$s\",\n \"cli_login_timeout\": \"Délai de connexion dépassé. Veuillez réessayer.\",\n \"cli_login_no_port\": \"Aucun port libre pour la connexion (essayés : %1$s).\",\n \"cli_callback_title\": \"Connecté à bonbox\",\n \"cli_callback_heading\": \"Vous êtes connecté\",\n \"cli_callback_body\": \"Vous pouvez fermer cet onglet et revenir au terminal.\",\n \"cli_callback_error_heading\": \"Échec de la connexion\",\n \"cli_callback_error_body\": \"Revenez au terminal et réessayez.\",\n \"cli_logout_done\": \"Déconnecté.\",\n \"cli_logout_none\": \"Vous n'étiez pas connecté.\",\n \"cli_label_email\": \"E-mail\",\n \"cli_label_plan\": \"Abonnement\",\n \"cli_label_company\": \"Entreprise\",\n \"cli_label_currency\": \"Monnaie\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratuit\",\n \"cli_col_number\": \"Numéro\",\n \"cli_col_date\": \"Date\",\n \"cli_col_status\": \"Statut\",\n \"cli_col_customer\": \"Client\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Nom\",\n \"cli_col_city\": \"Localité\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Fournisseur\",\n \"cli_col_amount\": \"Montant\",\n \"cli_col_category\": \"Catégorie\",\n \"cli_col_archived\": \"Archivé\",\n \"cli_status_created\": \"Ouverte\",\n \"cli_status_paid\": \"Payée\",\n \"cli_yes\": \"oui\",\n \"cli_no\": \"non\",\n \"cli_empty_customers\": \"Aucun client pour l'instant.\",\n \"cli_empty_invoices\": \"Aucune facture pour l'instant.\",\n \"cli_empty_quotes\": \"Aucun devis pour l'instant.\",\n \"cli_empty_receipts\": \"Aucun justificatif trouvé.\",\n \"cli_invoice_created\": \"Facture %1$s créée, %2$s\",\n \"cli_quote_created\": \"Devis %1$s créé, %2$s\",\n \"cli_pdf_saved\": \"Enregistré sous %1$s\",\n \"cli_invoice_paid\": \"%1$s marquée comme payée.\",\n \"cli_invoice_unpaid\": \"%1$s remise en attente de paiement.\",\n \"cli_receipt_added\": \"Justificatif enregistré : %1$s, %2$s\",\n \"cli_scan_uploading\": \"Envoi de %1$s fichier(s) ...\",\n \"cli_receipt_scanned\": \"Justificatif enregistré : %1$s, %2$s (reconnu automatiquement)\"\n}\n","{\n \"cli_app_description\": \"Gestisci giustificativi, fatture e clienti di bonbox dal terminale.\",\n \"cli_cmd_login\": \"Accedi al tuo account bonbox\",\n \"cli_cmd_logout\": \"Esci su questo dispositivo\",\n \"cli_cmd_whoami\": \"Mostra l'account con cui hai effettuato l'accesso\",\n \"cli_cmd_customers\": \"Gestisci i tuoi clienti\",\n \"cli_cmd_customers_ls\": \"Elenca i tuoi clienti\",\n \"cli_cmd_invoices\": \"Gestisci fatture e preventivi\",\n \"cli_cmd_invoices_ls\": \"Elenca fatture e preventivi\",\n \"cli_cmd_invoices_create\": \"Crea una fattura o un preventivo\",\n \"cli_cmd_invoices_pdf\": \"Scarica il PDF di una fattura o di un preventivo\",\n \"cli_cmd_invoices_paid\": \"Segna una fattura come pagata\",\n \"cli_cmd_invoices_unpaid\": \"Riporta una fattura fra quelle aperte\",\n \"cli_cmd_receipts\": \"Gestisci i tuoi giustificativi\",\n \"cli_cmd_receipts_ls\": \"Elenca i tuoi giustificativi\",\n \"cli_cmd_receipts_add\": \"Inserisci un giustificativo manualmente\",\n \"cli_cmd_receipts_scan\": \"Carica un giustificativo e lascia che bonbox lo legga\",\n \"cli_flag_json\": \"Stampa la risposta dell'API come JSON grezzo\",\n \"cli_flag_lang\": \"Lingua dell'output (en, de, fr, it)\",\n \"cli_flag_archived\": \"Includi i clienti archiviati\",\n \"cli_flag_status\": \"Filtra per stato: created o paid\",\n \"cli_flag_quotes\": \"Mostra i preventivi invece delle fatture\",\n \"cli_flag_customer_ref\": \"Nome o ID del cliente\",\n \"cli_flag_item\": \"Voce nel formato descrizione:quantità:prezzo unitario[:sconto%], ripetibile\",\n \"cli_flag_quote\": \"Crea un preventivo invece di una fattura\",\n \"cli_flag_invoice_date\": \"Data della fattura (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_payment_days\": \"Termine di pagamento in giorni\",\n \"cli_flag_currency\": \"Valuta, ad esempio CHF\",\n \"cli_flag_language\": \"Lingua del documento: de, en, fr o it\",\n \"cli_flag_subtitle\": \"Sottotitolo mostrato sul documento\",\n \"cli_flag_reference\": \"Il tuo riferimento per questo documento\",\n \"cli_flag_pdf\": \"Salva anche il PDF in questo file\",\n \"cli_flag_output\": \"Salva il PDF in questo file\",\n \"cli_flag_paid_date\": \"Data del pagamento (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_no_receipt\": \"Non registrare il pagamento come entrata\",\n \"cli_flag_month\": \"Limita a un mese (AAAA-MM)\",\n \"cli_flag_from\": \"Data di inizio (AAAA-MM-GG)\",\n \"cli_flag_to\": \"Data di fine (AAAA-MM-GG)\",\n \"cli_flag_project\": \"ID del progetto\",\n \"cli_flag_seller\": \"Fornitore, oppure il cliente per le entrate\",\n \"cli_flag_price\": \"Importo, ad esempio 23.50\",\n \"cli_flag_receipt_date\": \"Data del giustificativo (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_category\": \"Categoria\",\n \"cli_flag_tax_category\": \"Categoria fiscale\",\n \"cli_flag_booking_text\": \"Testo di registrazione\",\n \"cli_arg_invoice_ref\": \"Numero della fattura o ID\",\n \"cli_arg_scan_files\": \"File immagine o PDF, tutte le pagine di un giustificativo\",\n \"cli_error_unauthorized\": \"Non hai effettuato l'accesso. Esegui: bonbox login\",\n \"cli_error_pro_required\": \"Serve bonbox Pro. Puoi passare a Pro qui: %1$s\",\n \"cli_error_quota\": \"Hai raggiunto il limite del tuo abbonamento. Puoi passare a Pro qui: %1$s\",\n \"cli_error_network\": \"bonbox non è raggiungibile: %1$s\",\n \"cli_error_unexpected_response\": \"Risposta inattesa da bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Voce non valida \\\"%1$s\\\". Formato atteso: descrizione:quantità:prezzo unitario[:sconto%]\",\n \"cli_error_item_number\": \"Numero non valido nella voce \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Aggiungi almeno una voce con --item\",\n \"cli_error_customer_required\": \"Indica un cliente con --customer\",\n \"cli_error_price_required\": \"Indica un importo con --price\",\n \"cli_error_seller_required\": \"Indica un fornitore con --seller\",\n \"cli_error_price_invalid\": \"Importo non valido: %1$s\",\n \"cli_error_date_invalid\": \"Data non valida: %1$s. Formato atteso: AAAA-MM-GG\",\n \"cli_error_month_invalid\": \"Mese non valido: %1$s. Formato atteso: AAAA-MM\",\n \"cli_error_customer_not_found\": \"Nessun cliente corrisponde a \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" corrisponde a più clienti:\",\n \"cli_error_files_required\": \"Indica almeno un file da elaborare\",\n \"cli_error_file_missing\": \"File non trovato: %1$s\",\n \"cli_login_opening\": \"Apertura della pagina di accesso bonbox nel browser ...\",\n \"cli_login_manual\": \"Se il browser non si apre, visita:\\n%1$s\",\n \"cli_login_waiting\": \"In attesa del completamento dell'accesso ...\",\n \"cli_login_success\": \"Accesso effettuato come %1$s\",\n \"cli_login_failed\": \"Accesso non riuscito: %1$s\",\n \"cli_login_timeout\": \"Tempo scaduto per l'accesso. Riprova.\",\n \"cli_login_no_port\": \"Nessuna porta libera per l'accesso (provate: %1$s).\",\n \"cli_callback_title\": \"Accesso a bonbox effettuato\",\n \"cli_callback_heading\": \"Hai effettuato l'accesso\",\n \"cli_callback_body\": \"Puoi chiudere questa scheda e tornare al terminale.\",\n \"cli_callback_error_heading\": \"Accesso non riuscito\",\n \"cli_callback_error_body\": \"Torna al terminale e riprova.\",\n \"cli_logout_done\": \"Disconnesso.\",\n \"cli_logout_none\": \"Non avevi effettuato l'accesso.\",\n \"cli_label_email\": \"E-mail\",\n \"cli_label_plan\": \"Abbonamento\",\n \"cli_label_company\": \"Azienda\",\n \"cli_label_currency\": \"Valuta\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratuito\",\n \"cli_col_number\": \"Numero\",\n \"cli_col_date\": \"Data\",\n \"cli_col_status\": \"Stato\",\n \"cli_col_customer\": \"Cliente\",\n \"cli_col_total\": \"Totale\",\n \"cli_col_name\": \"Nome\",\n \"cli_col_city\": \"Località\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Fornitore\",\n \"cli_col_amount\": \"Importo\",\n \"cli_col_category\": \"Categoria\",\n \"cli_col_archived\": \"Archiviato\",\n \"cli_status_created\": \"Aperta\",\n \"cli_status_paid\": \"Pagata\",\n \"cli_yes\": \"sì\",\n \"cli_no\": \"no\",\n \"cli_empty_customers\": \"Ancora nessun cliente.\",\n \"cli_empty_invoices\": \"Ancora nessuna fattura.\",\n \"cli_empty_quotes\": \"Ancora nessun preventivo.\",\n \"cli_empty_receipts\": \"Nessun giustificativo trovato.\",\n \"cli_invoice_created\": \"Fattura %1$s creata, %2$s\",\n \"cli_quote_created\": \"Preventivo %1$s creato, %2$s\",\n \"cli_pdf_saved\": \"Salvato in %1$s\",\n \"cli_invoice_paid\": \"%1$s segnata come pagata.\",\n \"cli_invoice_unpaid\": \"%1$s riportata fra quelle aperte.\",\n \"cli_receipt_added\": \"Giustificativo salvato: %1$s, %2$s\",\n \"cli_scan_uploading\": \"Caricamento di %1$s file ...\",\n \"cli_receipt_scanned\": \"Giustificativo salvato: %1$s, %2$s (riconosciuto automaticamente)\"\n}\n","import en from './en.json';\nimport de from './de.json';\nimport fr from './fr.json';\nimport it from './it.json';\n\nexport const LOCALES = ['en', 'de', 'fr', 'it'] as const;\nexport type Locale = (typeof LOCALES)[number];\nexport type StringKey = keyof typeof en;\n\nconst BUNDLES: Record<Locale, Record<string, string>> = { en, de, fr, it };\n\nexport function isLocale(value: string): value is Locale {\n return (LOCALES as readonly string[]).includes(value);\n}\n\n/**\n * --lang wins, then BONBOX_LANG, then LANG/LC_ALL from the environment, then en.\n * Accepts full tags such as `de_CH.UTF-8` and `fr-FR`.\n */\nexport function resolveLocale(\n explicit?: string,\n env: NodeJS.ProcessEnv = process.env,\n): Locale {\n const candidates = [explicit, env.BONBOX_LANG, env.LC_ALL, env.LANG];\n for (const candidate of candidates) {\n const tag = candidate?.trim().toLowerCase().split(/[._-]/)[0];\n if (tag && isLocale(tag)) return tag;\n }\n return 'en';\n}\n\n/** Pure lookup with `%1$s`-style placeholders; falls back to English, then to the key. */\nexport function translate(locale: Locale, key: string, ...args: unknown[]): string {\n const template = BUNDLES[locale]?.[key] ?? BUNDLES.en[key];\n if (template === undefined) return key;\n return template.replace(/%(\\d+)\\$s/g, (match, index: string) => {\n const value = args[Number(index) - 1];\n return value === undefined ? match : String(value);\n });\n}\n\nlet current: Locale = 'en';\n\nexport function setLocale(locale: Locale): void {\n current = locale;\n}\n\nexport function getLocale(): Locale {\n return current;\n}\n\n/** Translate with the locale selected for this run. */\nexport function t(key: string, ...args: unknown[]): string {\n return translate(current, key, ...args);\n}\n","import { APP_URL } from './config.js';\nimport { t } from './i18n/index.js';\n\nexport const EXIT_OK = 0;\nexport const EXIT_ERROR = 1;\nexport const EXIT_USAGE = 2;\n\n/** An error already phrased for the user; the CLI prints the message and exits with `exitCode`. */\nexport class CliError extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode: number = EXIT_ERROR) {\n super(message);\n this.name = 'CliError';\n this.exitCode = exitCode;\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string) {\n super(message, EXIT_USAGE);\n this.name = 'UsageError';\n }\n}\n\ntype ErrorEnvelope = { error?: { code?: string; message?: string } };\n\nfunction envelopeMessage(body: unknown): string | undefined {\n const message = (body as ErrorEnvelope | null)?.error?.message;\n return typeof message === 'string' && message.length > 0 ? message : undefined;\n}\n\n/** Map an API error response onto a localized CliError. */\nexport function mapApiError(status: number, body: unknown): CliError {\n switch (status) {\n case 401:\n return new CliError(t('cli_error_unauthorized'));\n case 402:\n return new CliError(t('cli_error_pro_required', APP_URL));\n case 429:\n return new CliError(t('cli_error_quota', APP_URL));\n default:\n return new CliError(\n envelopeMessage(body) ?? t('cli_error_unexpected_response', status),\n );\n }\n}\n","import { apiBase } from './config.js';\nimport { CliError, mapApiError } from './errors.js';\nimport { t } from './i18n/index.js';\nimport type { ListResponse } from './types.js';\n\nexport interface ApiClientOptions {\n /** Resolves a Supabase access token; throws a CliError when not signed in. */\n getToken: () => Promise<string>;\n baseUrl?: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface BinaryResponse {\n data: Uint8Array;\n filename: string | null;\n}\n\ntype Query = Record<string, string | number | boolean | undefined | null>;\n\nfunction buildUrl(baseUrl: string, path: string, query?: Query): string {\n const url = new URL(baseUrl + path);\n for (const [key, value] of Object.entries(query ?? {})) {\n if (value !== undefined && value !== null && value !== '') {\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n}\n\nfunction filenameFromDisposition(header: string | null): string | null {\n if (!header) return null;\n const match = /filename\\*?=(?:UTF-8'')?\"?([^\";]+)\"?/i.exec(header);\n return match?.[1] ? decodeURIComponent(match[1]) : null;\n}\n\nexport class ApiClient {\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: ApiClientOptions) {\n this.baseUrl = options.baseUrl ?? apiBase();\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n private async send(path: string, init: RequestInit, query?: Query): Promise<Response> {\n const token = await this.options.getToken();\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${token}`);\n headers.set('Accept', headers.get('Accept') ?? 'application/json');\n\n let response: Response;\n try {\n response = await this.fetchImpl(buildUrl(this.baseUrl, path, query), {\n ...init,\n headers,\n });\n } catch (error) {\n throw new CliError(t('cli_error_network', (error as Error).message));\n }\n\n if (!response.ok) {\n const body = await response.json().catch(() => null);\n throw mapApiError(response.status, body);\n }\n return response;\n }\n\n private async parseJson<T>(response: Response): Promise<T> {\n try {\n return (await response.json()) as T;\n } catch {\n // e.g. HTML from a proxy or SPA fallback instead of the API\n throw new CliError(t('cli_error_unexpected_response', String(response.status)));\n }\n }\n\n async get<T>(path: string, query?: Query): Promise<T> {\n const response = await this.send(path, { method: 'GET' }, query);\n return await this.parseJson<T>(response);\n }\n\n async post<T>(path: string, body?: unknown): Promise<T> {\n const response = await this.send(path, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n });\n return await this.parseJson<T>(response);\n }\n\n async postMultipart<T>(path: string, form: FormData): Promise<T> {\n const response = await this.send(path, { method: 'POST', body: form });\n return await this.parseJson<T>(response);\n }\n\n /**\n * Fetches every page of a list endpoint and returns the concatenated items.\n * Stops once a page comes back short of `limit`, and also honors `total`\n * when the API reports it — but works fine without it.\n */\n async getAllPages<T>(path: string, query?: Query): Promise<T[]> {\n const limit = 200;\n let offset = 0;\n const items: T[] = [];\n for (;;) {\n const page = await this.get<ListResponse<T>>(path, { ...query, limit, offset });\n items.push(...page.items);\n offset += limit;\n if (page.items.length < limit) break;\n if (typeof page.total === 'number' && items.length >= page.total) break;\n }\n return items;\n }\n\n async getBinary(path: string): Promise<BinaryResponse> {\n const response = await this.send(path, { method: 'GET', headers: { Accept: '*/*' } });\n const buffer = await response.arrayBuffer();\n return {\n data: new Uint8Array(buffer),\n filename: filenameFromDisposition(response.headers.get('content-disposition')),\n };\n }\n}\n","import { ApiClient } from '../api.js';\nimport { getAccessToken } from '../auth.js';\nimport { scanBase } from '../config.js';\nimport { t } from '../i18n/index.js';\n\n/** Flags every command accepts. Built lazily so the locale is already set. */\nexport function commonArgs() {\n return {\n json: { type: 'boolean' as const, description: t('cli_flag_json'), default: false },\n lang: { type: 'string' as const, description: t('cli_flag_lang') },\n };\n}\n\n/** Read --lang straight from argv: the locale must be known before help is built. */\nexport function langFromArgv(argv: string[]): string | undefined {\n for (let index = 0; index < argv.length; index += 1) {\n const entry = argv[index] ?? '';\n if (entry === '--lang') return argv[index + 1];\n if (entry.startsWith('--lang=')) return entry.slice('--lang='.length);\n }\n return undefined;\n}\n\nexport function client(): ApiClient {\n return new ApiClient({ getToken: getAccessToken });\n}\n\n/** Client pointed at the Supabase functions URL directly (bypasses the Vercel proxy). */\nexport function scanClient(): ApiClient {\n return new ApiClient({ getToken: getAccessToken, baseUrl: scanBase() });\n}\n\nexport function out(line: string): void {\n process.stdout.write(`${line}\\n`);\n}\n\nexport function printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n","import { defineCommand } from 'citty';\n\nimport { table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport type { Customer } from '../types.js';\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_customers_ls') },\n args: {\n ...commonArgs(),\n archived: { type: 'boolean', description: t('cli_flag_archived'), default: false },\n },\n async run({ args }) {\n const items = await client().getAllPages<Customer>('/customers', {\n includeArchived: args.archived ? 'true' : undefined,\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(t('cli_empty_customers'));\n return;\n }\n\n const columns = [\n { header: t('cli_col_name') },\n { header: t('cli_col_city') },\n ...(args.archived ? [{ header: t('cli_col_archived') }] : []),\n { header: t('cli_col_id') },\n ];\n const rows = items.map((customer) => [\n customer.name,\n [customer.postalCode, customer.city].filter(Boolean).join(' '),\n ...(args.archived ? [customer.archived ? t('cli_yes') : t('cli_no')] : []),\n customer.id,\n ]);\n out(table(columns, rows));\n },\n });\n}\n\nexport function customersCommand() {\n return defineCommand({\n meta: { name: 'customers', description: t('cli_cmd_customers') },\n subCommands: { ls: listCommand() },\n });\n}\n","export type Align = 'left' | 'right';\n\nexport interface Column {\n header: string;\n align?: Align;\n}\n\n/** `2026-08-30T00:00:00+00:00` and `2026-08-30` both render as `2026-08-30`. */\nexport function formatDate(value: string | null | undefined): string {\n if (!value) return '';\n const match = /^(\\d{4}-\\d{2}-\\d{2})/.exec(value);\n return match?.[1] ?? value;\n}\n\n/** Swiss grouping: `CHF 1'234.50`. Currency first, two decimals, never localized separators. */\nexport function formatMoney(\n amount: number | null | undefined,\n currency: string | null | undefined,\n): string {\n if (amount === null || amount === undefined || Number.isNaN(amount)) return '';\n const negative = amount < 0;\n const [whole = '0', fraction = '00'] = Math.abs(amount).toFixed(2).split('.');\n const grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \"'\");\n const number = `${negative ? '-' : ''}${grouped}.${fraction}`;\n return currency ? `${currency} ${number}` : number;\n}\n\n/** Today in Europe/Zurich as YYYY-MM-DD — the timezone bonbox books in. */\nexport function todayInZurich(now: Date = new Date()): string {\n return new Intl.DateTimeFormat('en-CA', {\n timeZone: 'Europe/Zurich',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(now);\n}\n\nfunction pad(value: string, width: number, align: Align): string {\n const padding = ' '.repeat(Math.max(0, width - value.length));\n return align === 'right' ? padding + value : value + padding;\n}\n\n/**\n * Render an aligned table. Columns are separated by two spaces and the last\n * column is never padded, so lines have no trailing whitespace.\n */\nexport function table(columns: Column[], rows: string[][]): string {\n const widths = columns.map((column, index) =>\n Math.max(column.header.length, ...rows.map((row) => (row[index] ?? '').length)),\n );\n\n const render = (cells: string[]): string =>\n cells\n .map((cell, index) => {\n const align = columns[index]?.align ?? 'left';\n const isLast = index === columns.length - 1;\n return isLast && align === 'left' ? cell : pad(cell, widths[index] ?? 0, align);\n })\n .join(' ')\n .replace(/\\s+$/, '');\n\n return [render(columns.map((column) => column.header)), ...rows.map(render)].join('\\n');\n}\n","import { defineCommand } from 'citty';\nimport { writeFile } from 'node:fs/promises';\n\nimport type { ApiClient } from '../api.js';\nimport { formatDate, formatMoney, table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { optional, requireDate, requireNumber, toArray } from '../lib/args.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport { resolveCustomer } from '../lib/customers.js';\nimport { parseItems } from '../lib/items.js';\nimport { UsageError } from '../errors.js';\nimport type { Customer, Invoice } from '../types.js';\n\nasync function customerNames(api: ApiClient): Promise<Map<string, string>> {\n const customers = await api.getAllPages<Customer>('/customers', {\n includeArchived: 'true',\n });\n return new Map(customers.map((customer) => [customer.id, customer.name]));\n}\n\nexport function invoiceTable(invoices: Invoice[], names: Map<string, string>): string {\n const columns = [\n { header: t('cli_col_number') },\n { header: t('cli_col_date') },\n { header: t('cli_col_status') },\n { header: t('cli_col_total'), align: 'right' as const },\n { header: t('cli_col_customer') },\n ];\n const rows = invoices.map((invoice) => [\n invoice.invoiceNumber,\n formatDate(invoice.invoiceDate),\n invoice.status === 'paid' ? t('cli_status_paid') : t('cli_status_created'),\n formatMoney(invoice.total, invoice.currency),\n (invoice.customerId && names.get(invoice.customerId)) || '',\n ]);\n return table(columns, rows);\n}\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_invoices_ls') },\n args: {\n ...commonArgs(),\n status: { type: 'string', description: t('cli_flag_status') },\n quotes: { type: 'boolean', description: t('cli_flag_quotes'), default: false },\n },\n async run({ args }) {\n const status = optional(args.status);\n if (status && status !== 'created' && status !== 'paid') {\n throw new UsageError(t('cli_flag_status'));\n }\n\n const api = client();\n const items = await api.getAllPages<Invoice>('/invoices', {\n status,\n quotes: args.quotes ? 'only' : 'exclude',\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(args.quotes ? t('cli_empty_quotes') : t('cli_empty_invoices'));\n return;\n }\n out(invoiceTable(items, await customerNames(api)));\n },\n });\n}\n\nasync function savePdf(api: ApiClient, reference: string, target?: string): Promise<string> {\n const pdf = await api.getBinary(`/invoices/${encodeURIComponent(reference)}/pdf`);\n const filename = target ?? pdf.filename ?? `Invoice-${reference}.pdf`;\n await writeFile(filename, pdf.data);\n return filename;\n}\n\nfunction createCommand() {\n return defineCommand({\n meta: { name: 'create', description: t('cli_cmd_invoices_create') },\n args: {\n ...commonArgs(),\n customer: { type: 'string', description: t('cli_flag_customer_ref') },\n item: { type: 'string', description: t('cli_flag_item') },\n quote: { type: 'boolean', description: t('cli_flag_quote'), default: false },\n date: { type: 'string', description: t('cli_flag_invoice_date') },\n 'payment-days': { type: 'string', description: t('cli_flag_payment_days') },\n currency: { type: 'string', description: t('cli_flag_currency') },\n language: { type: 'string', description: t('cli_flag_language') },\n subtitle: { type: 'string', description: t('cli_flag_subtitle') },\n reference: { type: 'string', description: t('cli_flag_reference') },\n pdf: { type: 'string', description: t('cli_flag_pdf') },\n },\n async run({ args }) {\n const customerRef = optional(args.customer);\n if (!customerRef) throw new UsageError(t('cli_error_customer_required'));\n const items = parseItems(toArray(args.item));\n\n const api = client();\n const customers = await api.getAllPages<Customer>('/customers');\n const customer = resolveCustomer(customerRef, customers);\n\n const invoice = await api.post<Invoice>('/invoices', {\n customerId: customer.id,\n items,\n quote: Boolean(args.quote),\n date: requireDate(optional(args.date)),\n paymentDays: requireNumber(optional(args['payment-days']), 'cli_error_price_invalid'),\n currency: optional(args.currency),\n language: optional(args.language),\n subtitle: optional(args.subtitle),\n reference: optional(args.reference),\n });\n\n const pdfTarget = optional(args.pdf);\n const savedTo = pdfTarget ? await savePdf(api, invoice.id, pdfTarget) : null;\n\n if (args.json) {\n printJson(invoice);\n return;\n }\n const total = formatMoney(invoice.total, invoice.currency);\n out(\n invoice.isQuote\n ? t('cli_quote_created', invoice.invoiceNumber, total)\n : t('cli_invoice_created', invoice.invoiceNumber, total),\n );\n if (savedTo) out(t('cli_pdf_saved', savedTo));\n },\n });\n}\n\nfunction pdfCommand() {\n return defineCommand({\n meta: { name: 'pdf', description: t('cli_cmd_invoices_pdf') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n output: { type: 'string', alias: 'o', description: t('cli_flag_output') },\n },\n async run({ args }) {\n const filename = await savePdf(client(), String(args.invoice), optional(args.output));\n if (args.json) printJson({ file: filename });\n else out(t('cli_pdf_saved', filename));\n },\n });\n}\n\nfunction paidCommand() {\n return defineCommand({\n meta: { name: 'paid', description: t('cli_cmd_invoices_paid') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n date: { type: 'string', description: t('cli_flag_paid_date') },\n receipt: { type: 'boolean', description: t('cli_flag_no_receipt'), default: true },\n },\n async run({ args }) {\n const invoice = await client().post<Invoice>(\n `/invoices/${encodeURIComponent(String(args.invoice))}/paid`,\n {\n paidDate: requireDate(optional(args.date)),\n createReceipt: args.receipt !== false,\n },\n );\n if (args.json) printJson(invoice);\n else out(t('cli_invoice_paid', invoice.invoiceNumber));\n },\n });\n}\n\nfunction unpaidCommand() {\n return defineCommand({\n meta: { name: 'unpaid', description: t('cli_cmd_invoices_unpaid') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n },\n async run({ args }) {\n const invoice = await client().post<Invoice>(\n `/invoices/${encodeURIComponent(String(args.invoice))}/unpaid`,\n );\n if (args.json) printJson(invoice);\n else out(t('cli_invoice_unpaid', invoice.invoiceNumber));\n },\n });\n}\n\nexport function invoicesCommand() {\n return defineCommand({\n meta: { name: 'invoices', description: t('cli_cmd_invoices') },\n subCommands: {\n ls: listCommand(),\n create: createCommand(),\n pdf: pdfCommand(),\n paid: paidCommand(),\n unpaid: unpaidCommand(),\n },\n });\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\n\n/** citty gives a string for a single flag and an array when it is repeated. */\nexport function toArray(value: unknown): string[] {\n if (value === undefined || value === null || value === false) return [];\n if (Array.isArray(value)) return value.map(String).filter((entry) => entry.length > 0);\n const single = String(value);\n return single.length > 0 ? [single] : [];\n}\n\nexport function optional(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n const text = String(value).trim();\n return text.length > 0 ? text : undefined;\n}\n\nexport function requireDate(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) {\n throw new UsageError(t('cli_error_date_invalid', value));\n }\n return value;\n}\n\nexport function requireNumber(value: string | undefined, messageKey: string): number | undefined {\n if (value === undefined) return undefined;\n const parsed = Number(value.replace(',', '.'));\n if (!Number.isFinite(parsed)) throw new UsageError(t(messageKey, value));\n return parsed;\n}\n\n/** `2026-08` → the first and last day of that month. */\nexport function monthRange(month: string): { from: string; to: string } {\n const match = /^(\\d{4})-(\\d{2})$/.exec(month);\n const year = Number(match?.[1]);\n const monthIndex = Number(match?.[2]);\n if (!match || monthIndex < 1 || monthIndex > 12) {\n throw new UsageError(t('cli_error_month_invalid', month));\n }\n const lastDay = new Date(Date.UTC(year, monthIndex, 0)).getUTCDate();\n const padded = String(monthIndex).padStart(2, '0');\n return { from: `${year}-${padded}-01`, to: `${year}-${padded}-${String(lastDay).padStart(2, '0')}` };\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport type { Customer } from '../types.js';\n\nexport type CustomerMatch =\n | { kind: 'match'; customer: Customer }\n | { kind: 'ambiguous'; candidates: Customer[] }\n | { kind: 'none' };\n\n/**\n * Resolve a customer reference: exact ID, then exact name (case-insensitive),\n * then a unique name prefix. Anything else is ambiguous or unknown.\n */\nexport function matchCustomer(reference: string, customers: Customer[]): CustomerMatch {\n const needle = reference.trim().toLowerCase();\n if (!needle) return { kind: 'none' };\n\n const byId = customers.find((customer) => customer.id.toLowerCase() === needle);\n if (byId) return { kind: 'match', customer: byId };\n\n const exact = customers.filter((customer) => customer.name.trim().toLowerCase() === needle);\n if (exact.length === 1) return { kind: 'match', customer: exact[0] as Customer };\n if (exact.length > 1) return { kind: 'ambiguous', candidates: exact };\n\n const prefix = customers.filter((customer) =>\n customer.name.trim().toLowerCase().startsWith(needle),\n );\n if (prefix.length === 1) return { kind: 'match', customer: prefix[0] as Customer };\n if (prefix.length > 1) return { kind: 'ambiguous', candidates: prefix };\n\n return { kind: 'none' };\n}\n\n/** Same as {@link matchCustomer}, but throws a message the user can act on. */\nexport function resolveCustomer(reference: string, customers: Customer[]): Customer {\n const result = matchCustomer(reference, customers);\n if (result.kind === 'match') return result.customer;\n if (result.kind === 'ambiguous') {\n const list = result.candidates\n .map((customer) => ` ${customer.name} ${customer.id}`)\n .join('\\n');\n throw new UsageError(`${t('cli_error_customer_ambiguous', reference)}\\n${list}`);\n }\n throw new UsageError(t('cli_error_customer_not_found', reference));\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport type { NewLineItem } from '../types.js';\n\nconst NUMBER = /^-?\\d+(?:[.,]\\d+)?$/;\n\nfunction toNumber(raw: string): number | null {\n const trimmed = raw.trim();\n if (!NUMBER.test(trimmed)) return null;\n return Number(trimmed.replace(',', '.'));\n}\n\n/**\n * Parse `description:quantity:unitPrice[:discount%]`.\n * The description may itself contain colons — quantity, price and the optional\n * discount are read from the end. The trailing part is only a discount when it\n * ends with `%`; a bare number there is just part of the qty/price split.\n */\nexport function parseItem(raw: string): NewLineItem {\n const parts = raw.split(':');\n if (parts.length < 3) throw new UsageError(t('cli_error_item_format', raw));\n\n let discountPercent: number | undefined;\n const last = parts[parts.length - 1] ?? '';\n if (parts.length >= 4 && last.trim().endsWith('%')) {\n const value = toNumber(last.replace('%', ''));\n if (value === null) throw new UsageError(t('cli_error_item_number', raw));\n discountPercent = value;\n parts.pop();\n }\n\n const unitPrice = toNumber(parts.pop() ?? '');\n const quantity = toNumber(parts.pop() ?? '');\n if (unitPrice === null || quantity === null) {\n throw new UsageError(t('cli_error_item_number', raw));\n }\n\n const description = parts.join(':').trim();\n if (!description) throw new UsageError(t('cli_error_item_format', raw));\n\n return discountPercent === undefined\n ? { description, quantity, unitPrice }\n : { description, quantity, unitPrice, discountPercent };\n}\n\nexport function parseItems(raw: string[]): NewLineItem[] {\n if (raw.length === 0) throw new UsageError(t('cli_error_items_required'));\n return raw.map(parseItem);\n}\n","import { defineCommand } from 'citty';\nimport { randomBytes } from 'node:crypto';\nimport { createServer, type Server } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport open from 'open';\n\nimport { getSupabase } from '../auth.js';\nimport { APP_URL, CALLBACK_PORTS } from '../config.js';\nimport { CliError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport { commonArgs, out, printJson } from '../lib/context.js';\n\nconst TIMEOUT_MS = 5 * 60 * 1000;\n\nfunction page(heading: string, body: string): string {\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\n<title>${t('cli_callback_title')}</title></head>\n<body style=\"margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center;\nfont:16px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#111;background:#faf9f7\">\n<main style=\"text-align:center;max-width:28rem;padding:2rem\">\n<h1 style=\"font-size:1.25rem;font-weight:600;margin:0 0 .5rem\">${heading}</h1>\n<p style=\"margin:0;color:#555\">${body}</p>\n</main></body></html>`;\n}\n\nexport type CallbackResult =\n | { kind: 'success'; tokens: { accessToken: string; refreshToken: string } }\n | { kind: 'error'; message: string }\n | { kind: 'invalid' };\n\n/**\n * Pure request handler for the `/callback` redirect, split out so it's unit-testable.\n *\n * A state mismatch, or a request missing both tokens and an error, is `invalid` — the caller\n * responds 400 and keeps listening rather than aborting the whole login attempt (a stray or\n * malformed request shouldn't kill a valid in-flight login). An `error`/`error_description` param\n * with a *matching* state is a genuine failure report from the web page and does end the attempt.\n */\nexport function handleCallbackRequest(requestUrl: string, expectedState: string): CallbackResult {\n const url = new URL(requestUrl, 'http://localhost');\n const state = url.searchParams.get('state');\n if (state !== expectedState) return { kind: 'invalid' };\n\n const accessToken = url.searchParams.get('access_token');\n const refreshToken = url.searchParams.get('refresh_token');\n if (accessToken && refreshToken) {\n return { kind: 'success', tokens: { accessToken, refreshToken } };\n }\n\n const errorMessage = url.searchParams.get('error_description') ?? url.searchParams.get('error');\n if (errorMessage) return { kind: 'error', message: errorMessage };\n\n return { kind: 'invalid' };\n}\n\nfunction listen(port: number): Promise<Server | null> {\n return new Promise((resolve) => {\n const server = createServer();\n server.once('error', () => resolve(null));\n server.listen(port, '127.0.0.1', () => resolve(server));\n });\n}\n\nasync function openListener(): Promise<{ server: Server; port: number }> {\n for (const port of CALLBACK_PORTS) {\n const server = await listen(port);\n if (server) return { server, port: (server.address() as AddressInfo).port };\n }\n throw new CliError(t('cli_login_no_port', CALLBACK_PORTS.join(', ')));\n}\n\n/**\n * Resolve with the tokens the browser redirect carries back.\n *\n * The `/callback` request itself never renders the tokens: it 302s to `/done` (or `/error`) so\n * the access/refresh tokens don't linger in the browser's address bar or history.\n */\nexport function awaitTokens(\n server: Server,\n state: string,\n): Promise<{ accessToken: string; refreshToken: string }> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new CliError(t('cli_login_timeout')));\n }, TIMEOUT_MS);\n\n server.on('request', (request, response) => {\n const url = new URL(request.url ?? '/', 'http://localhost');\n\n if (url.pathname === '/done') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_heading'), t('cli_callback_body')));\n return;\n }\n if (url.pathname === '/error') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_error_heading'), t('cli_callback_error_body')));\n return;\n }\n if (!url.pathname.startsWith('/callback')) {\n response.writeHead(404).end();\n return;\n }\n\n const result = handleCallbackRequest(request.url ?? '/', state);\n if (result.kind === 'invalid') {\n response.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_error_heading'), t('cli_callback_error_body')));\n return;\n }\n\n if (result.kind === 'error') {\n response.writeHead(302, { Location: '/error' });\n response.end();\n clearTimeout(timer);\n reject(new CliError(t('cli_login_failed', result.message)));\n return;\n }\n\n response.writeHead(302, { Location: '/done' });\n response.end();\n clearTimeout(timer);\n resolve(result.tokens);\n });\n });\n}\n\nexport function loginCommand() {\n return defineCommand({\n meta: { name: 'login', description: t('cli_cmd_login') },\n args: commonArgs(),\n async run({ args }) {\n const { server, port } = await openListener();\n try {\n const state = randomBytes(16).toString('hex');\n const loginUrl = `${APP_URL}/login?cli_port=${port}&state=${state}`;\n\n if (!args.json) {\n out(t('cli_login_opening'));\n out(t('cli_login_manual', loginUrl));\n out(t('cli_login_waiting'));\n }\n await open(loginUrl).catch(() => undefined);\n\n const { accessToken, refreshToken } = await awaitTokens(server, state);\n\n const supabase = getSupabase();\n const { data, error } = await supabase.auth.setSession({\n access_token: accessToken,\n refresh_token: refreshToken,\n });\n if (error) throw new CliError(t('cli_login_failed', error.message));\n\n const email = data.user?.email ?? data.user?.id ?? '';\n if (args.json) printJson({ user: { id: data.user?.id, email } });\n else out(t('cli_login_success', email));\n } finally {\n server.close();\n }\n },\n });\n}\n","import { defineCommand } from 'citty';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, extname } from 'node:path';\n\nimport { UsageError } from '../errors.js';\nimport { formatDate, formatMoney, table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { monthRange, optional, requireDate, requireNumber, toArray } from '../lib/args.js';\nimport { client, commonArgs, out, printJson, scanClient } from '../lib/context.js';\nimport { resolveCustomer } from '../lib/customers.js';\nimport type { Customer, Receipt } from '../types.js';\n\nconst MIME_TYPES: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.webp': 'image/webp',\n '.pdf': 'application/pdf',\n};\n\nfunction receiptTable(receipts: Receipt[]): string {\n const columns = [\n { header: t('cli_col_date') },\n { header: t('cli_col_seller') },\n { header: t('cli_col_amount'), align: 'right' as const },\n { header: t('cli_col_category') },\n { header: t('cli_col_id') },\n ];\n const rows = receipts.map((receipt) => [\n formatDate(receipt.date),\n receipt.seller ?? '',\n formatMoney(receipt.price, receipt.currency),\n receipt.taxCategory ?? receipt.category ?? '',\n receipt.id,\n ]);\n return table(columns, rows);\n}\n\nfunction summarize(receipt: Receipt): string {\n return `${receipt.seller ?? ''}, ${formatMoney(receipt.price, receipt.currency)}`.replace(\n /^, /,\n '',\n );\n}\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_receipts_ls') },\n args: {\n ...commonArgs(),\n month: { type: 'string', description: t('cli_flag_month') },\n from: { type: 'string', description: t('cli_flag_from') },\n to: { type: 'string', description: t('cli_flag_to') },\n project: { type: 'string', description: t('cli_flag_project') },\n },\n async run({ args }) {\n const month = optional(args.month);\n const range = month ? monthRange(month) : undefined;\n\n const items = await client().getAllPages<Receipt>('/receipts', {\n from: range?.from ?? requireDate(optional(args.from)),\n to: range?.to ?? requireDate(optional(args.to)),\n projectId: optional(args.project),\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(t('cli_empty_receipts'));\n return;\n }\n out(receiptTable(items));\n },\n });\n}\n\nfunction addCommand() {\n return defineCommand({\n meta: { name: 'add', description: t('cli_cmd_receipts_add') },\n args: {\n ...commonArgs(),\n seller: { type: 'string', description: t('cli_flag_seller') },\n price: { type: 'string', description: t('cli_flag_price') },\n date: { type: 'string', description: t('cli_flag_receipt_date') },\n currency: { type: 'string', description: t('cli_flag_currency') },\n category: { type: 'string', description: t('cli_flag_category') },\n 'tax-category': { type: 'string', description: t('cli_flag_tax_category') },\n 'booking-text': { type: 'string', description: t('cli_flag_booking_text') },\n project: { type: 'string', description: t('cli_flag_project') },\n customer: { type: 'string', description: t('cli_flag_customer_ref') },\n },\n async run({ args }) {\n const seller = optional(args.seller);\n const rawPrice = optional(args.price);\n if (!seller) throw new UsageError(t('cli_error_seller_required'));\n if (!rawPrice) throw new UsageError(t('cli_error_price_required'));\n const price = requireNumber(rawPrice, 'cli_error_price_invalid');\n\n const api = client();\n const customerRef = optional(args.customer);\n let customerId: string | undefined;\n if (customerRef) {\n const customers = await api.getAllPages<Customer>('/customers');\n customerId = resolveCustomer(customerRef, customers).id;\n }\n\n const receipt = await api.post<Receipt>('/receipts', {\n seller,\n price,\n date: requireDate(optional(args.date)),\n currency: optional(args.currency),\n category: optional(args.category),\n taxCategory: optional(args['tax-category']),\n bookingText: optional(args['booking-text']),\n projectId: optional(args.project),\n customerId,\n });\n\n if (args.json) printJson(receipt);\n else out(t('cli_receipt_added', formatDate(receipt.date), summarize(receipt)));\n },\n });\n}\n\nfunction scanCommand() {\n return defineCommand({\n meta: { name: 'scan', description: t('cli_cmd_receipts_scan') },\n args: {\n files: { type: 'positional', description: t('cli_arg_scan_files'), required: false },\n ...commonArgs(),\n project: { type: 'string', description: t('cli_flag_project') },\n },\n async run({ args }) {\n const files = toArray((args as { _?: string[] })._ ?? args.files);\n if (files.length === 0) throw new UsageError(t('cli_error_files_required'));\n\n const form = new FormData();\n for (const path of files) {\n if (!existsSync(path)) throw new UsageError(t('cli_error_file_missing', path));\n const content = await readFile(path);\n const type = MIME_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream';\n form.append('file', new Blob([new Uint8Array(content)], { type }), basename(path));\n }\n const projectId = optional(args.project);\n if (projectId) form.append('projectId', projectId);\n\n if (!args.json) out(t('cli_scan_uploading', files.length));\n // Scans go straight to the Supabase functions URL — the Vercel proxy caps request bodies,\n // which large multi-page receipt scans can exceed.\n const receipt = await scanClient().postMultipart<Receipt>('/receipts/scan', form);\n\n if (args.json) printJson(receipt);\n else out(t('cli_receipt_scanned', formatDate(receipt.date), summarize(receipt)));\n },\n });\n}\n\nexport function receiptsCommand() {\n return defineCommand({\n meta: { name: 'receipts', description: t('cli_cmd_receipts') },\n subCommands: {\n ls: listCommand(),\n add: addCommand(),\n scan: scanCommand(),\n },\n });\n}\n"],"mappings":";;;AAAA,SAAS,iBAAAA,gBAAe,YAAY,iBAAkC;;;ACAtE,SAAS,qBAAqB;;;ACA9B,SAAS,oBAAyC;AAClD,SAAS,WAAW,YAAY,WAAW,cAAc,QAAQ,qBAAqB;AACtF,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;;;ACFvB,IAAM,eAAe;AAGrB,IAAM,oBACX;AAGK,IAAM,UAAU;AAEvB,IAAM,mBAAmB;AAGzB,IAAM,YAAY,GAAG,YAAY;AAEjC,SAAS,YAAY,KAAwB,UAA0B;AACrE,QAAM,MAAM,IAAI,gBAAgB,KAAK;AACrC,UAAQ,OAAO,IAAI,SAAS,IAAI,MAAM,UAAU,QAAQ,QAAQ,EAAE;AACpE;AAGO,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,SAAO,YAAY,KAAK,gBAAgB;AAC1C;AAGO,SAAS,SAAS,MAAyB,QAAQ,KAAa;AACrE,SAAO,YAAY,KAAK,SAAS;AACnC;AAGO,IAAM,iBAAiB,CAAC,OAAO,OAAO,KAAK;;;AC/BlD;AAAA,EACE,qBAAuB;AAAA,EACvB,eAAiB;AAAA,EACjB,gBAAkB;AAAA,EAClB,gBAAkB;AAAA,EAClB,mBAAqB;AAA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SAAS;AAClD;AAEA,eAAe,MAAuB;AACpC,MAAI,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,KAAK,QAAQ,WAAW,GAAG;AAC1E,UAAM,UAAU,GAAI,MAAM,kBAAkB,MAAM,OAAO,CAAE;AAC3D,WAAO;AAAA,EACT;AACA,MAAI,KAAK,WAAW,MAAM,KAAK,CAAC,MAAM,eAAe,KAAK,CAAC,MAAM,OAAO;AACtE,YAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAM,WAAW,MAAM,EAAE,SAAS,QAAQ,CAAC;AAC3C,WAAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,aAAa,KAAK,GAAG;AACvB,cAAQ,OAAO,MAAM,GAAI,MAAgB,OAAO;AAAA,CAAI;AACpD,YAAM,UAAU,GAAI,MAAM,kBAAkB,MAAM,OAAO,CAAE;AAC3D,aAAO;AAAA,IACT;AACA,QAAI,iBAAiB,UAAU;AAC7B,cAAQ,OAAO,MAAM,GAAG,MAAM,OAAO;AAAA,CAAI;AACzC,aAAO,MAAM;AAAA,IACf;AACA,YAAQ,OAAO,MAAM,GAAI,OAAiB,WAAW,OAAO,KAAK,CAAC;AAAA,CAAI;AACtE,WAAO;AAAA,EACT;AACF;AAEA,QAAQ,KAAK,MAAM,IAAI,CAAC;","names":["defineCommand","page","argv","defineCommand","defineCommand","defineCommand","listCommand","defineCommand","defineCommand","defineCommand","defineCommand","existsSync","listCommand","defineCommand","existsSync","defineCommand"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/commands/account.ts","../src/auth.ts","../src/config.ts","../src/i18n/en.json","../src/i18n/de.json","../src/i18n/fr.json","../src/i18n/it.json","../src/i18n/index.ts","../src/errors.ts","../src/api.ts","../src/lib/context.ts","../src/commands/customers.ts","../src/format.ts","../src/lib/args.ts","../src/lib/customers.ts","../src/commands/invoices.ts","../src/lib/items.ts","../src/commands/login.ts","../src/commands/receipts.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from 'citty';\n\nimport { logoutCommand, whoamiCommand } from './commands/account.js';\nimport { customersCommand } from './commands/customers.js';\nimport { invoicesCommand } from './commands/invoices.js';\nimport { loginCommand } from './commands/login.js';\nimport { receiptsCommand } from './commands/receipts.js';\nimport { CliError, EXIT_ERROR, EXIT_USAGE } from './errors.js';\nimport { resolveLocale, setLocale, t } from './i18n/index.js';\nimport { langFromArgv } from './lib/context.js';\n\nconst VERSION = '0.3.0';\n\nconst argv = process.argv.slice(2);\nsetLocale(resolveLocale(langFromArgv(argv)));\n\n/** citty would read the value of `--lang de` as a sub-command name; the locale is\n * applied globally before parsing, so the flag can be dropped from the arg list. */\nfunction withoutLangFlag(rawArgs: string[]): string[] {\n const kept: string[] = [];\n for (let index = 0; index < rawArgs.length; index += 1) {\n const entry = rawArgs[index] ?? '';\n if (entry === '--lang') {\n index += 1;\n continue;\n }\n if (entry.startsWith('--lang=')) continue;\n kept.push(entry);\n }\n return kept;\n}\n\nconst cliArgs = withoutLangFlag(argv);\n\nconst main = defineCommand({\n meta: { name: 'bonbox', version: VERSION, description: t('cli_app_description') },\n subCommands: {\n login: loginCommand(),\n logout: logoutCommand(),\n whoami: whoamiCommand(),\n customers: customersCommand(),\n invoices: invoicesCommand(),\n receipts: receiptsCommand(),\n },\n});\n\n/** Walk into the deepest sub-command named on the command line, for --help. */\nasync function resolveSubCommand(\n command: CommandDef,\n rawArgs: string[],\n parent?: CommandDef,\n): Promise<[CommandDef, CommandDef | undefined]> {\n const subCommands = command.subCommands as Record<string, CommandDef> | undefined;\n if (subCommands && Object.keys(subCommands).length > 0) {\n const index = rawArgs.findIndex((arg) => !arg.startsWith('-'));\n const name = rawArgs[index];\n const sub = name ? subCommands[name] : undefined;\n if (sub) return resolveSubCommand(sub, rawArgs.slice(index + 1), command);\n }\n return [command, parent];\n}\n\n/** citty signals unknown/missing commands with a CLIError; those are usage errors. */\nfunction isUsageError(error: unknown): boolean {\n const code = (error as { code?: string })?.code;\n return code === 'E_UNKNOWN_COMMAND' || code === 'E_NO_COMMAND';\n}\n\nasync function run(): Promise<number> {\n if (argv.includes('--help') || argv.includes('-h') || cliArgs.length === 0) {\n await showUsage(...(await resolveSubCommand(main, cliArgs)));\n return 0;\n }\n if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-v')) {\n process.stdout.write(`${VERSION}\\n`);\n return 0;\n }\n\n try {\n await runCommand(main, { rawArgs: cliArgs });\n return 0;\n } catch (error) {\n if (isUsageError(error)) {\n process.stderr.write(`${(error as Error).message}\\n`);\n await showUsage(...(await resolveSubCommand(main, cliArgs)));\n return EXIT_USAGE;\n }\n if (error instanceof CliError) {\n process.stderr.write(`${error.message}\\n`);\n return error.exitCode;\n }\n process.stderr.write(`${(error as Error)?.message ?? String(error)}\\n`);\n return EXIT_ERROR;\n }\n}\n\nprocess.exit(await run());\n","import { defineCommand } from 'citty';\n\nimport { clearSessionFile, getSupabase } from '../auth.js';\nimport { t } from '../i18n/index.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport type { Me } from '../types.js';\n\nexport function logoutCommand() {\n return defineCommand({\n meta: { name: 'logout', description: t('cli_cmd_logout') },\n args: commonArgs(),\n async run({ args }) {\n await getSupabase().auth.signOut({ scope: 'local' }).catch(() => undefined);\n const removed = clearSessionFile();\n if (args.json) printJson({ signedOut: removed });\n else out(removed ? t('cli_logout_done') : t('cli_logout_none'));\n },\n });\n}\n\nexport function whoamiCommand() {\n return defineCommand({\n meta: { name: 'whoami', description: t('cli_cmd_whoami') },\n args: commonArgs(),\n async run({ args }) {\n const me = await client().get<Me>('/me');\n if (args.json) {\n printJson(me);\n return;\n }\n const rows: [string, string][] = [\n [t('cli_label_email'), me.email ?? me.id],\n [t('cli_label_plan'), me.isPro ? t('cli_plan_pro') : t('cli_plan_free')],\n ];\n if (me.companyName) rows.push([t('cli_label_company'), me.companyName]);\n if (me.defaultCurrency) rows.push([t('cli_label_currency'), me.defaultCurrency]);\n\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) out(`${label.padEnd(width)} ${value}`);\n },\n });\n}\n","import { createClient, type SupabaseClient } from '@supabase/supabase-js';\nimport { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nimport { SUPABASE_ANON_KEY, SUPABASE_URL } from './config.js';\nimport { CliError } from './errors.js';\nimport { t } from './i18n/index.js';\n\n/** ~/.config/bonbox/session.json, honouring XDG_CONFIG_HOME. */\nexport function sessionPath(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), '.config');\n return join(base, 'bonbox', 'session.json');\n}\n\n/**\n * supabase-js storage backed by a single 0600 JSON file. It holds the session\n * plus the transient PKCE verifier, keyed exactly as supabase-js expects.\n */\nclass FileStorage {\n constructor(private readonly file: string) {}\n\n private read(): Record<string, string> {\n if (!existsSync(this.file)) return {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(this.file, 'utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, string>) : {};\n } catch {\n return {};\n }\n }\n\n private write(entries: Record<string, string>): void {\n mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });\n writeFileSync(this.file, `${JSON.stringify(entries, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(this.file, 0o600);\n }\n\n getItem(key: string): string | null {\n return this.read()[key] ?? null;\n }\n\n setItem(key: string, value: string): void {\n this.write({ ...this.read(), [key]: value });\n }\n\n removeItem(key: string): void {\n const entries = this.read();\n delete entries[key];\n this.write(entries);\n }\n}\n\nlet cached: SupabaseClient | null = null;\n\nexport function getSupabase(): SupabaseClient {\n if (!cached) {\n cached = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {\n auth: {\n storage: new FileStorage(sessionPath()),\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl: false,\n flowType: 'pkce',\n },\n });\n }\n return cached;\n}\n\n/** Drop the stored session file entirely. */\nexport function clearSessionFile(): boolean {\n const file = sessionPath();\n if (!existsSync(file)) return false;\n rmSync(file);\n return true;\n}\n\n/** A valid access token, refreshed by supabase-js when needed. */\nexport async function getAccessToken(): Promise<string> {\n const { data } = await getSupabase().auth.getSession();\n const token = data.session?.access_token;\n if (!token) throw new CliError(t('cli_error_unauthorized'));\n return token;\n}\n","/** Supabase project the CLI authenticates against. */\nexport const SUPABASE_URL = 'https://gaxsaareqnpthuyjfwrz.supabase.co';\n\n/** Public anon key — safe to ship, it only allows what RLS allows. */\nexport const SUPABASE_ANON_KEY =\n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImdheHNhYXJlcW5wdGh1eWpmd3J6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzU3NDkxMjcsImV4cCI6MjA1MTMyNTEyN30.iUiUnilZnLlLLoGam4hC5qcmhC4oDtB2sZDGz0xHU8k';\n\n/** Where users manage their subscription. */\nexport const APP_URL = 'https://app.bonbox.io';\n\nconst DEFAULT_API_BASE = 'https://app.bonbox.io/api/v1';\n\n// Bypasses the app.bonbox.io Vercel proxy for large multipart uploads — it caps request bodies.\nconst SCAN_BASE = `${SUPABASE_URL}/functions/v1/api-v1`;\n\nfunction resolveBase(env: NodeJS.ProcessEnv, fallback: string): string {\n const raw = env.BONBOX_API_URL?.trim();\n return (raw && raw.length > 0 ? raw : fallback).replace(/\\/+$/, '');\n}\n\n/** API base URL, overridable with BONBOX_API_URL (e.g. the Supabase functions URL). */\nexport function apiBase(env: NodeJS.ProcessEnv = process.env): string {\n return resolveBase(env, DEFAULT_API_BASE);\n}\n\n/** Base URL for large multipart uploads (receipt scans), bypassing the Vercel proxy. */\nexport function scanBase(env: NodeJS.ProcessEnv = process.env): string {\n return resolveBase(env, SCAN_BASE);\n}\n\n/** Ports tried in order for the local OAuth callback listener. */\nexport const CALLBACK_PORTS = [51823, 51824, 51825] as const;\n","{\n \"cli_app_description\": \"Manage your bonbox receipts, invoices and customers from the terminal.\",\n \"cli_cmd_login\": \"Sign in to your bonbox account\",\n \"cli_cmd_logout\": \"Sign out on this machine\",\n \"cli_cmd_whoami\": \"Show the account you are signed in with\",\n \"cli_cmd_customers\": \"Work with your customers\",\n \"cli_cmd_customers_ls\": \"List your customers\",\n \"cli_cmd_customers_create\": \"Create a customer\",\n \"cli_cmd_customers_update\": \"Update a customer\",\n \"cli_cmd_invoices\": \"Work with your invoices and quotes\",\n \"cli_cmd_invoices_ls\": \"List invoices and quotes\",\n \"cli_cmd_invoices_create\": \"Create an invoice or a quote\",\n \"cli_cmd_invoices_update\": \"Update an invoice or quote\",\n \"cli_cmd_invoices_pdf\": \"Download the PDF of an invoice or quote\",\n \"cli_cmd_invoices_paid\": \"Mark an invoice as paid\",\n \"cli_cmd_invoices_unpaid\": \"Mark an invoice as unpaid again\",\n \"cli_cmd_receipts\": \"Work with your receipts\",\n \"cli_cmd_receipts_ls\": \"List your receipts\",\n \"cli_cmd_receipts_add\": \"Add a receipt by hand\",\n \"cli_cmd_receipts_scan\": \"Upload a receipt and let bonbox read it\",\n \"cli_flag_json\": \"Print the raw API response as JSON\",\n \"cli_flag_lang\": \"Output language (en, de, fr, it)\",\n \"cli_flag_archived\": \"Include archived customers\",\n \"cli_flag_status\": \"Filter by status: created or paid\",\n \"cli_flag_quotes\": \"Show quotes instead of invoices\",\n \"cli_flag_customer_ref\": \"Customer name or ID\",\n \"cli_flag_name\": \"Customer name\",\n \"cli_flag_department\": \"Department\",\n \"cli_flag_address\": \"Street address\",\n \"cli_flag_postal_code\": \"Postal code\",\n \"cli_flag_city\": \"City\",\n \"cli_flag_country\": \"Country code, for example CH\",\n \"cli_flag_item\": \"Line item as description:quantity:unitPrice[:discount%], can be repeated\",\n \"cli_flag_quote\": \"Create a quote instead of an invoice\",\n \"cli_flag_invoice_date\": \"Invoice date (YYYY-MM-DD), today by default\",\n \"cli_flag_invoice_date_update\": \"Invoice date (YYYY-MM-DD)\",\n \"cli_flag_payment_days\": \"Payment term in days\",\n \"cli_flag_currency\": \"Currency code, for example CHF\",\n \"cli_flag_language\": \"Document language: de, en, fr or it\",\n \"cli_flag_subtitle\": \"Subtitle shown on the document\",\n \"cli_flag_reference\": \"Your reference for this document\",\n \"cli_flag_vat_rate\": \"VAT rate in percent, for example 8.1\",\n \"cli_flag_custom_notes\": \"Custom notes shown on the document\",\n \"cli_flag_pdf\": \"Also save the PDF to this file\",\n \"cli_flag_output\": \"Save the PDF to this file\",\n \"cli_flag_paid_date\": \"Payment date (YYYY-MM-DD), today by default\",\n \"cli_flag_no_receipt\": \"Do not book the payment as income\",\n \"cli_flag_month\": \"Limit to one month (YYYY-MM)\",\n \"cli_flag_from\": \"Start date (YYYY-MM-DD)\",\n \"cli_flag_to\": \"End date (YYYY-MM-DD)\",\n \"cli_flag_project\": \"Project ID\",\n \"cli_flag_seller\": \"Seller, or the customer for income\",\n \"cli_flag_price\": \"Amount, for example 23.50\",\n \"cli_flag_receipt_date\": \"Receipt date (YYYY-MM-DD), today by default\",\n \"cli_flag_category\": \"Category\",\n \"cli_flag_tax_category\": \"Tax category\",\n \"cli_flag_booking_text\": \"Booking text\",\n \"cli_arg_invoice_ref\": \"Invoice number or ID\",\n \"cli_arg_customer_ref\": \"Customer name or ID\",\n \"cli_arg_scan_files\": \"Image or PDF files, all pages of one receipt\",\n \"cli_error_unauthorized\": \"You are not signed in. Run: bonbox login\",\n \"cli_error_pro_required\": \"This needs bonbox Pro. You can upgrade at %1$s\",\n \"cli_error_quota\": \"You have reached the limit of your plan. You can upgrade at %1$s\",\n \"cli_error_network\": \"Could not reach bonbox: %1$s\",\n \"cli_error_unexpected_response\": \"Unexpected answer from bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Invalid item \\\"%1$s\\\". Expected description:quantity:unitPrice[:discount%]\",\n \"cli_error_item_number\": \"Invalid number in item \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Add at least one line item with --item\",\n \"cli_error_customer_required\": \"Name a customer with --customer\",\n \"cli_error_name_required\": \"Give a name with --name\",\n \"cli_error_address_required\": \"Give an address with --address\",\n \"cli_error_postal_code_required\": \"Give a postal code with --postal-code\",\n \"cli_error_city_required\": \"Give a city with --city\",\n \"cli_error_update_fields_required\": \"Give at least one field to update\",\n \"cli_error_price_required\": \"Give an amount with --price\",\n \"cli_error_seller_required\": \"Give a seller with --seller\",\n \"cli_error_price_invalid\": \"Invalid amount: %1$s\",\n \"cli_error_date_invalid\": \"Invalid date: %1$s. Expected YYYY-MM-DD\",\n \"cli_error_month_invalid\": \"Invalid month: %1$s. Expected YYYY-MM\",\n \"cli_error_customer_not_found\": \"No customer matches \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" matches several customers:\",\n \"cli_error_files_required\": \"Name at least one file to scan\",\n \"cli_error_file_missing\": \"File not found: %1$s\",\n \"cli_login_opening\": \"Opening the bonbox sign-in page in your browser ...\",\n \"cli_login_manual\": \"If your browser does not open, visit:\\n%1$s\",\n \"cli_login_waiting\": \"Waiting for you to finish signing in ...\",\n \"cli_login_success\": \"Signed in as %1$s\",\n \"cli_login_failed\": \"Sign-in failed: %1$s\",\n \"cli_login_timeout\": \"Sign-in timed out. Please try again.\",\n \"cli_login_no_port\": \"No free port for the sign-in callback (tried %1$s).\",\n \"cli_callback_title\": \"Signed in to bonbox\",\n \"cli_callback_heading\": \"You are signed in\",\n \"cli_callback_body\": \"You can close this tab and go back to the terminal.\",\n \"cli_callback_error_heading\": \"Sign-in failed\",\n \"cli_callback_error_body\": \"Go back to the terminal and try again.\",\n \"cli_logout_done\": \"Signed out.\",\n \"cli_logout_none\": \"You were not signed in.\",\n \"cli_label_email\": \"Email\",\n \"cli_label_plan\": \"Plan\",\n \"cli_label_company\": \"Company\",\n \"cli_label_currency\": \"Currency\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Free\",\n \"cli_col_number\": \"Number\",\n \"cli_col_date\": \"Date\",\n \"cli_col_status\": \"Status\",\n \"cli_col_customer\": \"Customer\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Name\",\n \"cli_col_city\": \"City\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Seller\",\n \"cli_col_amount\": \"Amount\",\n \"cli_col_category\": \"Category\",\n \"cli_col_archived\": \"Archived\",\n \"cli_status_created\": \"Open\",\n \"cli_status_paid\": \"Paid\",\n \"cli_yes\": \"yes\",\n \"cli_no\": \"no\",\n \"cli_empty_customers\": \"No customers yet.\",\n \"cli_empty_invoices\": \"No invoices yet.\",\n \"cli_empty_quotes\": \"No quotes yet.\",\n \"cli_empty_receipts\": \"No receipts found.\",\n \"cli_customer_created\": \"Customer %1$s created.\",\n \"cli_customer_updated\": \"Customer %1$s updated.\",\n \"cli_invoice_created\": \"Invoice %1$s created, %2$s\",\n \"cli_quote_created\": \"Quote %1$s created, %2$s\",\n \"cli_pdf_saved\": \"Saved to %1$s\",\n \"cli_invoice_updated\": \"Invoice %1$s updated.\",\n \"cli_quote_updated\": \"Quote %1$s updated.\",\n \"cli_invoice_paid\": \"%1$s marked as paid.\",\n \"cli_invoice_unpaid\": \"%1$s marked as unpaid.\",\n \"cli_receipt_added\": \"Receipt saved: %1$s, %2$s\",\n \"cli_scan_uploading\": \"Uploading %1$s file(s) ...\",\n \"cli_receipt_scanned\": \"Receipt saved: %1$s, %2$s (extracted automatically)\"\n}\n","{\n \"cli_app_description\": \"Belege, Rechnungen und Kunden von bonbox direkt im Terminal verwalten.\",\n \"cli_cmd_login\": \"Beim bonbox-Konto anmelden\",\n \"cli_cmd_logout\": \"Auf diesem Gerät abmelden\",\n \"cli_cmd_whoami\": \"Zeigt das angemeldete Konto\",\n \"cli_cmd_customers\": \"Kunden verwalten\",\n \"cli_cmd_customers_ls\": \"Kunden auflisten\",\n \"cli_cmd_customers_create\": \"Kunde erstellen\",\n \"cli_cmd_customers_update\": \"Kunde aktualisieren\",\n \"cli_cmd_invoices\": \"Rechnungen und Offerten verwalten\",\n \"cli_cmd_invoices_ls\": \"Rechnungen und Offerten auflisten\",\n \"cli_cmd_invoices_create\": \"Rechnung oder Offerte erstellen\",\n \"cli_cmd_invoices_update\": \"Rechnung oder Offerte aktualisieren\",\n \"cli_cmd_invoices_pdf\": \"PDF einer Rechnung oder Offerte herunterladen\",\n \"cli_cmd_invoices_paid\": \"Rechnung als bezahlt markieren\",\n \"cli_cmd_invoices_unpaid\": \"Rechnung wieder als offen markieren\",\n \"cli_cmd_receipts\": \"Belege verwalten\",\n \"cli_cmd_receipts_ls\": \"Belege auflisten\",\n \"cli_cmd_receipts_add\": \"Beleg von Hand erfassen\",\n \"cli_cmd_receipts_scan\": \"Beleg hochladen und von bonbox auslesen lassen\",\n \"cli_flag_json\": \"Antwort der API als reines JSON ausgeben\",\n \"cli_flag_lang\": \"Sprache der Ausgabe (en, de, fr, it)\",\n \"cli_flag_archived\": \"Archivierte Kunden einschliessen\",\n \"cli_flag_status\": \"Nach Status filtern: created oder paid\",\n \"cli_flag_quotes\": \"Offerten statt Rechnungen anzeigen\",\n \"cli_flag_customer_ref\": \"Kundenname oder Kunden-ID\",\n \"cli_flag_name\": \"Kundenname\",\n \"cli_flag_department\": \"Abteilung\",\n \"cli_flag_address\": \"Strasse und Hausnummer\",\n \"cli_flag_postal_code\": \"Postleitzahl\",\n \"cli_flag_city\": \"Ort\",\n \"cli_flag_country\": \"Ländercode, zum Beispiel CH\",\n \"cli_flag_item\": \"Position als Beschreibung:Menge:Einzelpreis[:Rabatt%], mehrfach möglich\",\n \"cli_flag_quote\": \"Offerte statt Rechnung erstellen\",\n \"cli_flag_invoice_date\": \"Rechnungsdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_invoice_date_update\": \"Rechnungsdatum (JJJJ-MM-TT)\",\n \"cli_flag_payment_days\": \"Zahlungsfrist in Tagen\",\n \"cli_flag_currency\": \"Währung, zum Beispiel CHF\",\n \"cli_flag_language\": \"Sprache des Dokuments: de, en, fr oder it\",\n \"cli_flag_subtitle\": \"Untertitel auf dem Dokument\",\n \"cli_flag_reference\": \"Ihre Referenz für dieses Dokument\",\n \"cli_flag_vat_rate\": \"Mehrwertsteuersatz in Prozent, zum Beispiel 8.1\",\n \"cli_flag_custom_notes\": \"Eigene Notizen auf dem Dokument\",\n \"cli_flag_pdf\": \"PDF zusätzlich in diese Datei speichern\",\n \"cli_flag_output\": \"PDF in diese Datei speichern\",\n \"cli_flag_paid_date\": \"Zahlungsdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_no_receipt\": \"Zahlung nicht als Einnahme verbuchen\",\n \"cli_flag_month\": \"Auf einen Monat einschränken (JJJJ-MM)\",\n \"cli_flag_from\": \"Startdatum (JJJJ-MM-TT)\",\n \"cli_flag_to\": \"Enddatum (JJJJ-MM-TT)\",\n \"cli_flag_project\": \"Projekt-ID\",\n \"cli_flag_seller\": \"Anbieter, bei Einnahmen der Kunde\",\n \"cli_flag_price\": \"Betrag, zum Beispiel 23.50\",\n \"cli_flag_receipt_date\": \"Belegdatum (JJJJ-MM-TT), standardmässig heute\",\n \"cli_flag_category\": \"Kategorie\",\n \"cli_flag_tax_category\": \"Steuerkategorie\",\n \"cli_flag_booking_text\": \"Buchungstext\",\n \"cli_arg_invoice_ref\": \"Rechnungsnummer oder ID\",\n \"cli_arg_customer_ref\": \"Kundenname oder ID\",\n \"cli_arg_scan_files\": \"Bild- oder PDF-Dateien, alle Seiten eines Belegs\",\n \"cli_error_unauthorized\": \"Sie sind nicht angemeldet. Führen Sie aus: bonbox login\",\n \"cli_error_pro_required\": \"Dafür wird bonbox Pro benötigt. Upgrade unter %1$s\",\n \"cli_error_quota\": \"Das Limit Ihres Abos ist erreicht. Upgrade unter %1$s\",\n \"cli_error_network\": \"bonbox ist nicht erreichbar: %1$s\",\n \"cli_error_unexpected_response\": \"Unerwartete Antwort von bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Ungültige Position \\\"%1$s\\\". Erwartet: Beschreibung:Menge:Einzelpreis[:Rabatt%]\",\n \"cli_error_item_number\": \"Ungültige Zahl in Position \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Erfassen Sie mindestens eine Position mit --item\",\n \"cli_error_customer_required\": \"Geben Sie einen Kunden mit --customer an\",\n \"cli_error_name_required\": \"Geben Sie einen Namen mit --name an\",\n \"cli_error_address_required\": \"Geben Sie eine Adresse mit --address an\",\n \"cli_error_postal_code_required\": \"Geben Sie eine Postleitzahl mit --postal-code an\",\n \"cli_error_city_required\": \"Geben Sie einen Ort mit --city an\",\n \"cli_error_update_fields_required\": \"Geben Sie mindestens ein zu änderndes Feld an\",\n \"cli_error_price_required\": \"Geben Sie einen Betrag mit --price an\",\n \"cli_error_seller_required\": \"Geben Sie einen Anbieter mit --seller an\",\n \"cli_error_price_invalid\": \"Ungültiger Betrag: %1$s\",\n \"cli_error_date_invalid\": \"Ungültiges Datum: %1$s. Erwartet: JJJJ-MM-TT\",\n \"cli_error_month_invalid\": \"Ungültiger Monat: %1$s. Erwartet: JJJJ-MM\",\n \"cli_error_customer_not_found\": \"Kein Kunde passt zu \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" passt auf mehrere Kunden:\",\n \"cli_error_files_required\": \"Geben Sie mindestens eine Datei zum Scannen an\",\n \"cli_error_file_missing\": \"Datei nicht gefunden: %1$s\",\n \"cli_login_opening\": \"Die bonbox-Anmeldeseite wird im Browser geöffnet ...\",\n \"cli_login_manual\": \"Falls sich der Browser nicht öffnet, rufen Sie auf:\\n%1$s\",\n \"cli_login_waiting\": \"Warten auf den Abschluss der Anmeldung ...\",\n \"cli_login_success\": \"Angemeldet als %1$s\",\n \"cli_login_failed\": \"Anmeldung fehlgeschlagen: %1$s\",\n \"cli_login_timeout\": \"Zeitüberschreitung bei der Anmeldung. Bitte erneut versuchen.\",\n \"cli_login_no_port\": \"Kein freier Port für die Anmeldung (versucht: %1$s).\",\n \"cli_callback_title\": \"Bei bonbox angemeldet\",\n \"cli_callback_heading\": \"Sie sind angemeldet\",\n \"cli_callback_body\": \"Sie können diesen Tab schliessen und zum Terminal zurückkehren.\",\n \"cli_callback_error_heading\": \"Anmeldung fehlgeschlagen\",\n \"cli_callback_error_body\": \"Kehren Sie zum Terminal zurück und versuchen Sie es erneut.\",\n \"cli_logout_done\": \"Abgemeldet.\",\n \"cli_logout_none\": \"Sie waren nicht angemeldet.\",\n \"cli_label_email\": \"E-Mail\",\n \"cli_label_plan\": \"Abo\",\n \"cli_label_company\": \"Firma\",\n \"cli_label_currency\": \"Währung\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratis\",\n \"cli_col_number\": \"Nummer\",\n \"cli_col_date\": \"Datum\",\n \"cli_col_status\": \"Status\",\n \"cli_col_customer\": \"Kunde\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Name\",\n \"cli_col_city\": \"Ort\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Anbieter\",\n \"cli_col_amount\": \"Betrag\",\n \"cli_col_category\": \"Kategorie\",\n \"cli_col_archived\": \"Archiviert\",\n \"cli_status_created\": \"Offen\",\n \"cli_status_paid\": \"Bezahlt\",\n \"cli_yes\": \"ja\",\n \"cli_no\": \"nein\",\n \"cli_empty_customers\": \"Noch keine Kunden.\",\n \"cli_empty_invoices\": \"Noch keine Rechnungen.\",\n \"cli_empty_quotes\": \"Noch keine Offerten.\",\n \"cli_empty_receipts\": \"Keine Belege gefunden.\",\n \"cli_customer_created\": \"Kunde %1$s erstellt.\",\n \"cli_customer_updated\": \"Kunde %1$s aktualisiert.\",\n \"cli_invoice_created\": \"Rechnung %1$s erstellt, %2$s\",\n \"cli_quote_created\": \"Offerte %1$s erstellt, %2$s\",\n \"cli_pdf_saved\": \"Gespeichert unter %1$s\",\n \"cli_invoice_updated\": \"Rechnung %1$s aktualisiert.\",\n \"cli_quote_updated\": \"Offerte %1$s aktualisiert.\",\n \"cli_invoice_paid\": \"%1$s als bezahlt markiert.\",\n \"cli_invoice_unpaid\": \"%1$s als offen markiert.\",\n \"cli_receipt_added\": \"Beleg gespeichert: %1$s, %2$s\",\n \"cli_scan_uploading\": \"%1$s Datei(en) werden hochgeladen ...\",\n \"cli_receipt_scanned\": \"Beleg gespeichert: %1$s, %2$s (automatisch erkannt)\"\n}\n","{\n \"cli_app_description\": \"Gérez vos justificatifs, factures et clients bonbox depuis le terminal.\",\n \"cli_cmd_login\": \"Se connecter à votre compte bonbox\",\n \"cli_cmd_logout\": \"Se déconnecter sur cet appareil\",\n \"cli_cmd_whoami\": \"Afficher le compte connecté\",\n \"cli_cmd_customers\": \"Gérer vos clients\",\n \"cli_cmd_customers_ls\": \"Lister vos clients\",\n \"cli_cmd_customers_create\": \"Créer un client\",\n \"cli_cmd_customers_update\": \"Mettre à jour un client\",\n \"cli_cmd_invoices\": \"Gérer vos factures et devis\",\n \"cli_cmd_invoices_ls\": \"Lister les factures et devis\",\n \"cli_cmd_invoices_create\": \"Créer une facture ou un devis\",\n \"cli_cmd_invoices_update\": \"Mettre à jour une facture ou un devis\",\n \"cli_cmd_invoices_pdf\": \"Télécharger le PDF d'une facture ou d'un devis\",\n \"cli_cmd_invoices_paid\": \"Marquer une facture comme payée\",\n \"cli_cmd_invoices_unpaid\": \"Remettre une facture en attente de paiement\",\n \"cli_cmd_receipts\": \"Gérer vos justificatifs\",\n \"cli_cmd_receipts_ls\": \"Lister vos justificatifs\",\n \"cli_cmd_receipts_add\": \"Saisir un justificatif manuellement\",\n \"cli_cmd_receipts_scan\": \"Envoyer un justificatif et le faire lire par bonbox\",\n \"cli_flag_json\": \"Afficher la réponse brute de l'API en JSON\",\n \"cli_flag_lang\": \"Langue de l'affichage (en, de, fr, it)\",\n \"cli_flag_archived\": \"Inclure les clients archivés\",\n \"cli_flag_status\": \"Filtrer par statut : created ou paid\",\n \"cli_flag_quotes\": \"Afficher les devis au lieu des factures\",\n \"cli_flag_customer_ref\": \"Nom ou identifiant du client\",\n \"cli_flag_name\": \"Nom du client\",\n \"cli_flag_department\": \"Service\",\n \"cli_flag_address\": \"Adresse\",\n \"cli_flag_postal_code\": \"Code postal\",\n \"cli_flag_city\": \"Ville\",\n \"cli_flag_country\": \"Code pays, par exemple CH\",\n \"cli_flag_item\": \"Poste au format description:quantité:prix unitaire[:remise%], répétable\",\n \"cli_flag_quote\": \"Créer un devis au lieu d'une facture\",\n \"cli_flag_invoice_date\": \"Date de la facture (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_invoice_date_update\": \"Date de la facture (AAAA-MM-JJ)\",\n \"cli_flag_payment_days\": \"Délai de paiement en jours\",\n \"cli_flag_currency\": \"Monnaie, par exemple CHF\",\n \"cli_flag_language\": \"Langue du document : de, en, fr ou it\",\n \"cli_flag_subtitle\": \"Sous-titre affiché sur le document\",\n \"cli_flag_reference\": \"Votre référence pour ce document\",\n \"cli_flag_vat_rate\": \"Taux de TVA en pourcent, par exemple 8.1\",\n \"cli_flag_custom_notes\": \"Notes personnalisées affichées sur le document\",\n \"cli_flag_pdf\": \"Enregistrer aussi le PDF dans ce fichier\",\n \"cli_flag_output\": \"Enregistrer le PDF dans ce fichier\",\n \"cli_flag_paid_date\": \"Date du paiement (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_no_receipt\": \"Ne pas comptabiliser le paiement comme recette\",\n \"cli_flag_month\": \"Limiter à un mois (AAAA-MM)\",\n \"cli_flag_from\": \"Date de début (AAAA-MM-JJ)\",\n \"cli_flag_to\": \"Date de fin (AAAA-MM-JJ)\",\n \"cli_flag_project\": \"Identifiant du projet\",\n \"cli_flag_seller\": \"Fournisseur, ou le client pour une recette\",\n \"cli_flag_price\": \"Montant, par exemple 23.50\",\n \"cli_flag_receipt_date\": \"Date du justificatif (AAAA-MM-JJ), aujourd'hui par défaut\",\n \"cli_flag_category\": \"Catégorie\",\n \"cli_flag_tax_category\": \"Catégorie fiscale\",\n \"cli_flag_booking_text\": \"Libellé comptable\",\n \"cli_arg_invoice_ref\": \"Numéro de facture ou identifiant\",\n \"cli_arg_customer_ref\": \"Nom ou identifiant du client\",\n \"cli_arg_scan_files\": \"Fichiers image ou PDF, toutes les pages d'un justificatif\",\n \"cli_error_unauthorized\": \"Vous n'êtes pas connecté. Exécutez : bonbox login\",\n \"cli_error_pro_required\": \"Cette action nécessite bonbox Pro. Passez à Pro sur %1$s\",\n \"cli_error_quota\": \"Vous avez atteint la limite de votre abonnement. Passez à Pro sur %1$s\",\n \"cli_error_network\": \"bonbox est injoignable : %1$s\",\n \"cli_error_unexpected_response\": \"Réponse inattendue de bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Poste invalide \\\"%1$s\\\". Attendu : description:quantité:prix unitaire[:remise%]\",\n \"cli_error_item_number\": \"Nombre invalide dans le poste \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Ajoutez au moins un poste avec --item\",\n \"cli_error_customer_required\": \"Indiquez un client avec --customer\",\n \"cli_error_name_required\": \"Indiquez un nom avec --name\",\n \"cli_error_address_required\": \"Indiquez une adresse avec --address\",\n \"cli_error_postal_code_required\": \"Indiquez un code postal avec --postal-code\",\n \"cli_error_city_required\": \"Indiquez une ville avec --city\",\n \"cli_error_update_fields_required\": \"Indiquez au moins un champ à mettre à jour\",\n \"cli_error_price_required\": \"Indiquez un montant avec --price\",\n \"cli_error_seller_required\": \"Indiquez un fournisseur avec --seller\",\n \"cli_error_price_invalid\": \"Montant invalide : %1$s\",\n \"cli_error_date_invalid\": \"Date invalide : %1$s. Attendu : AAAA-MM-JJ\",\n \"cli_error_month_invalid\": \"Mois invalide : %1$s. Attendu : AAAA-MM\",\n \"cli_error_customer_not_found\": \"Aucun client ne correspond à \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" correspond à plusieurs clients :\",\n \"cli_error_files_required\": \"Indiquez au moins un fichier à traiter\",\n \"cli_error_file_missing\": \"Fichier introuvable : %1$s\",\n \"cli_login_opening\": \"Ouverture de la page de connexion bonbox dans votre navigateur ...\",\n \"cli_login_manual\": \"Si le navigateur ne s'ouvre pas, rendez-vous sur :\\n%1$s\",\n \"cli_login_waiting\": \"En attente de la fin de la connexion ...\",\n \"cli_login_success\": \"Connecté en tant que %1$s\",\n \"cli_login_failed\": \"Échec de la connexion : %1$s\",\n \"cli_login_timeout\": \"Délai de connexion dépassé. Veuillez réessayer.\",\n \"cli_login_no_port\": \"Aucun port libre pour la connexion (essayés : %1$s).\",\n \"cli_callback_title\": \"Connecté à bonbox\",\n \"cli_callback_heading\": \"Vous êtes connecté\",\n \"cli_callback_body\": \"Vous pouvez fermer cet onglet et revenir au terminal.\",\n \"cli_callback_error_heading\": \"Échec de la connexion\",\n \"cli_callback_error_body\": \"Revenez au terminal et réessayez.\",\n \"cli_logout_done\": \"Déconnecté.\",\n \"cli_logout_none\": \"Vous n'étiez pas connecté.\",\n \"cli_label_email\": \"E-mail\",\n \"cli_label_plan\": \"Abonnement\",\n \"cli_label_company\": \"Entreprise\",\n \"cli_label_currency\": \"Monnaie\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratuit\",\n \"cli_col_number\": \"Numéro\",\n \"cli_col_date\": \"Date\",\n \"cli_col_status\": \"Statut\",\n \"cli_col_customer\": \"Client\",\n \"cli_col_total\": \"Total\",\n \"cli_col_name\": \"Nom\",\n \"cli_col_city\": \"Localité\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Fournisseur\",\n \"cli_col_amount\": \"Montant\",\n \"cli_col_category\": \"Catégorie\",\n \"cli_col_archived\": \"Archivé\",\n \"cli_status_created\": \"Ouverte\",\n \"cli_status_paid\": \"Payée\",\n \"cli_yes\": \"oui\",\n \"cli_no\": \"non\",\n \"cli_empty_customers\": \"Aucun client pour l'instant.\",\n \"cli_empty_invoices\": \"Aucune facture pour l'instant.\",\n \"cli_empty_quotes\": \"Aucun devis pour l'instant.\",\n \"cli_empty_receipts\": \"Aucun justificatif trouvé.\",\n \"cli_customer_created\": \"Client %1$s créé.\",\n \"cli_customer_updated\": \"Client %1$s mis à jour.\",\n \"cli_invoice_created\": \"Facture %1$s créée, %2$s\",\n \"cli_quote_created\": \"Devis %1$s créé, %2$s\",\n \"cli_pdf_saved\": \"Enregistré sous %1$s\",\n \"cli_invoice_updated\": \"Facture %1$s mise à jour.\",\n \"cli_quote_updated\": \"Devis %1$s mis à jour.\",\n \"cli_invoice_paid\": \"%1$s marquée comme payée.\",\n \"cli_invoice_unpaid\": \"%1$s remise en attente de paiement.\",\n \"cli_receipt_added\": \"Justificatif enregistré : %1$s, %2$s\",\n \"cli_scan_uploading\": \"Envoi de %1$s fichier(s) ...\",\n \"cli_receipt_scanned\": \"Justificatif enregistré : %1$s, %2$s (reconnu automatiquement)\"\n}\n","{\n \"cli_app_description\": \"Gestisci giustificativi, fatture e clienti di bonbox dal terminale.\",\n \"cli_cmd_login\": \"Accedi al tuo account bonbox\",\n \"cli_cmd_logout\": \"Esci su questo dispositivo\",\n \"cli_cmd_whoami\": \"Mostra l'account con cui hai effettuato l'accesso\",\n \"cli_cmd_customers\": \"Gestisci i tuoi clienti\",\n \"cli_cmd_customers_ls\": \"Elenca i tuoi clienti\",\n \"cli_cmd_customers_create\": \"Crea un cliente\",\n \"cli_cmd_customers_update\": \"Aggiorna un cliente\",\n \"cli_cmd_invoices\": \"Gestisci fatture e preventivi\",\n \"cli_cmd_invoices_ls\": \"Elenca fatture e preventivi\",\n \"cli_cmd_invoices_create\": \"Crea una fattura o un preventivo\",\n \"cli_cmd_invoices_update\": \"Aggiorna una fattura o un preventivo\",\n \"cli_cmd_invoices_pdf\": \"Scarica il PDF di una fattura o di un preventivo\",\n \"cli_cmd_invoices_paid\": \"Segna una fattura come pagata\",\n \"cli_cmd_invoices_unpaid\": \"Riporta una fattura fra quelle aperte\",\n \"cli_cmd_receipts\": \"Gestisci i tuoi giustificativi\",\n \"cli_cmd_receipts_ls\": \"Elenca i tuoi giustificativi\",\n \"cli_cmd_receipts_add\": \"Inserisci un giustificativo manualmente\",\n \"cli_cmd_receipts_scan\": \"Carica un giustificativo e lascia che bonbox lo legga\",\n \"cli_flag_json\": \"Stampa la risposta dell'API come JSON grezzo\",\n \"cli_flag_lang\": \"Lingua dell'output (en, de, fr, it)\",\n \"cli_flag_archived\": \"Includi i clienti archiviati\",\n \"cli_flag_status\": \"Filtra per stato: created o paid\",\n \"cli_flag_quotes\": \"Mostra i preventivi invece delle fatture\",\n \"cli_flag_customer_ref\": \"Nome o ID del cliente\",\n \"cli_flag_name\": \"Nome del cliente\",\n \"cli_flag_department\": \"Reparto\",\n \"cli_flag_address\": \"Indirizzo\",\n \"cli_flag_postal_code\": \"Codice postale\",\n \"cli_flag_city\": \"Città\",\n \"cli_flag_country\": \"Codice paese, ad esempio CH\",\n \"cli_flag_item\": \"Voce nel formato descrizione:quantità:prezzo unitario[:sconto%], ripetibile\",\n \"cli_flag_quote\": \"Crea un preventivo invece di una fattura\",\n \"cli_flag_invoice_date\": \"Data della fattura (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_invoice_date_update\": \"Data della fattura (AAAA-MM-GG)\",\n \"cli_flag_payment_days\": \"Termine di pagamento in giorni\",\n \"cli_flag_currency\": \"Valuta, ad esempio CHF\",\n \"cli_flag_language\": \"Lingua del documento: de, en, fr o it\",\n \"cli_flag_subtitle\": \"Sottotitolo mostrato sul documento\",\n \"cli_flag_reference\": \"Il tuo riferimento per questo documento\",\n \"cli_flag_vat_rate\": \"Aliquota IVA in percento, ad esempio 8.1\",\n \"cli_flag_custom_notes\": \"Note personalizzate mostrate sul documento\",\n \"cli_flag_pdf\": \"Salva anche il PDF in questo file\",\n \"cli_flag_output\": \"Salva il PDF in questo file\",\n \"cli_flag_paid_date\": \"Data del pagamento (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_no_receipt\": \"Non registrare il pagamento come entrata\",\n \"cli_flag_month\": \"Limita a un mese (AAAA-MM)\",\n \"cli_flag_from\": \"Data di inizio (AAAA-MM-GG)\",\n \"cli_flag_to\": \"Data di fine (AAAA-MM-GG)\",\n \"cli_flag_project\": \"ID del progetto\",\n \"cli_flag_seller\": \"Fornitore, oppure il cliente per le entrate\",\n \"cli_flag_price\": \"Importo, ad esempio 23.50\",\n \"cli_flag_receipt_date\": \"Data del giustificativo (AAAA-MM-GG), per impostazione predefinita oggi\",\n \"cli_flag_category\": \"Categoria\",\n \"cli_flag_tax_category\": \"Categoria fiscale\",\n \"cli_flag_booking_text\": \"Testo di registrazione\",\n \"cli_arg_invoice_ref\": \"Numero della fattura o ID\",\n \"cli_arg_customer_ref\": \"Nome o ID del cliente\",\n \"cli_arg_scan_files\": \"File immagine o PDF, tutte le pagine di un giustificativo\",\n \"cli_error_unauthorized\": \"Non hai effettuato l'accesso. Esegui: bonbox login\",\n \"cli_error_pro_required\": \"Serve bonbox Pro. Puoi passare a Pro qui: %1$s\",\n \"cli_error_quota\": \"Hai raggiunto il limite del tuo abbonamento. Puoi passare a Pro qui: %1$s\",\n \"cli_error_network\": \"bonbox non è raggiungibile: %1$s\",\n \"cli_error_unexpected_response\": \"Risposta inattesa da bonbox (HTTP %1$s)\",\n \"cli_error_item_format\": \"Voce non valida \\\"%1$s\\\". Formato atteso: descrizione:quantità:prezzo unitario[:sconto%]\",\n \"cli_error_item_number\": \"Numero non valido nella voce \\\"%1$s\\\"\",\n \"cli_error_items_required\": \"Aggiungi almeno una voce con --item\",\n \"cli_error_customer_required\": \"Indica un cliente con --customer\",\n \"cli_error_name_required\": \"Indica un nome con --name\",\n \"cli_error_address_required\": \"Indica un indirizzo con --address\",\n \"cli_error_postal_code_required\": \"Indica un codice postale con --postal-code\",\n \"cli_error_city_required\": \"Indica una città con --city\",\n \"cli_error_update_fields_required\": \"Indica almeno un campo da aggiornare\",\n \"cli_error_price_required\": \"Indica un importo con --price\",\n \"cli_error_seller_required\": \"Indica un fornitore con --seller\",\n \"cli_error_price_invalid\": \"Importo non valido: %1$s\",\n \"cli_error_date_invalid\": \"Data non valida: %1$s. Formato atteso: AAAA-MM-GG\",\n \"cli_error_month_invalid\": \"Mese non valido: %1$s. Formato atteso: AAAA-MM\",\n \"cli_error_customer_not_found\": \"Nessun cliente corrisponde a \\\"%1$s\\\"\",\n \"cli_error_customer_ambiguous\": \"\\\"%1$s\\\" corrisponde a più clienti:\",\n \"cli_error_files_required\": \"Indica almeno un file da elaborare\",\n \"cli_error_file_missing\": \"File non trovato: %1$s\",\n \"cli_login_opening\": \"Apertura della pagina di accesso bonbox nel browser ...\",\n \"cli_login_manual\": \"Se il browser non si apre, visita:\\n%1$s\",\n \"cli_login_waiting\": \"In attesa del completamento dell'accesso ...\",\n \"cli_login_success\": \"Accesso effettuato come %1$s\",\n \"cli_login_failed\": \"Accesso non riuscito: %1$s\",\n \"cli_login_timeout\": \"Tempo scaduto per l'accesso. Riprova.\",\n \"cli_login_no_port\": \"Nessuna porta libera per l'accesso (provate: %1$s).\",\n \"cli_callback_title\": \"Accesso a bonbox effettuato\",\n \"cli_callback_heading\": \"Hai effettuato l'accesso\",\n \"cli_callback_body\": \"Puoi chiudere questa scheda e tornare al terminale.\",\n \"cli_callback_error_heading\": \"Accesso non riuscito\",\n \"cli_callback_error_body\": \"Torna al terminale e riprova.\",\n \"cli_logout_done\": \"Disconnesso.\",\n \"cli_logout_none\": \"Non avevi effettuato l'accesso.\",\n \"cli_label_email\": \"E-mail\",\n \"cli_label_plan\": \"Abbonamento\",\n \"cli_label_company\": \"Azienda\",\n \"cli_label_currency\": \"Valuta\",\n \"cli_plan_pro\": \"Pro\",\n \"cli_plan_free\": \"Gratuito\",\n \"cli_col_number\": \"Numero\",\n \"cli_col_date\": \"Data\",\n \"cli_col_status\": \"Stato\",\n \"cli_col_customer\": \"Cliente\",\n \"cli_col_total\": \"Totale\",\n \"cli_col_name\": \"Nome\",\n \"cli_col_city\": \"Località\",\n \"cli_col_id\": \"ID\",\n \"cli_col_seller\": \"Fornitore\",\n \"cli_col_amount\": \"Importo\",\n \"cli_col_category\": \"Categoria\",\n \"cli_col_archived\": \"Archiviato\",\n \"cli_status_created\": \"Aperta\",\n \"cli_status_paid\": \"Pagata\",\n \"cli_yes\": \"sì\",\n \"cli_no\": \"no\",\n \"cli_empty_customers\": \"Ancora nessun cliente.\",\n \"cli_empty_invoices\": \"Ancora nessuna fattura.\",\n \"cli_empty_quotes\": \"Ancora nessun preventivo.\",\n \"cli_empty_receipts\": \"Nessun giustificativo trovato.\",\n \"cli_customer_created\": \"Cliente %1$s creato.\",\n \"cli_customer_updated\": \"Cliente %1$s aggiornato.\",\n \"cli_invoice_created\": \"Fattura %1$s creata, %2$s\",\n \"cli_quote_created\": \"Preventivo %1$s creato, %2$s\",\n \"cli_pdf_saved\": \"Salvato in %1$s\",\n \"cli_invoice_updated\": \"Fattura %1$s aggiornata.\",\n \"cli_quote_updated\": \"Preventivo %1$s aggiornato.\",\n \"cli_invoice_paid\": \"%1$s segnata come pagata.\",\n \"cli_invoice_unpaid\": \"%1$s riportata fra quelle aperte.\",\n \"cli_receipt_added\": \"Giustificativo salvato: %1$s, %2$s\",\n \"cli_scan_uploading\": \"Caricamento di %1$s file ...\",\n \"cli_receipt_scanned\": \"Giustificativo salvato: %1$s, %2$s (riconosciuto automaticamente)\"\n}\n","import en from './en.json';\nimport de from './de.json';\nimport fr from './fr.json';\nimport it from './it.json';\n\nexport const LOCALES = ['en', 'de', 'fr', 'it'] as const;\nexport type Locale = (typeof LOCALES)[number];\nexport type StringKey = keyof typeof en;\n\nconst BUNDLES: Record<Locale, Record<string, string>> = { en, de, fr, it };\n\nexport function isLocale(value: string): value is Locale {\n return (LOCALES as readonly string[]).includes(value);\n}\n\n/**\n * --lang wins, then BONBOX_LANG, then LANG/LC_ALL from the environment, then en.\n * Accepts full tags such as `de_CH.UTF-8` and `fr-FR`.\n */\nexport function resolveLocale(\n explicit?: string,\n env: NodeJS.ProcessEnv = process.env,\n): Locale {\n const candidates = [explicit, env.BONBOX_LANG, env.LC_ALL, env.LANG];\n for (const candidate of candidates) {\n const tag = candidate?.trim().toLowerCase().split(/[._-]/)[0];\n if (tag && isLocale(tag)) return tag;\n }\n return 'en';\n}\n\n/** Pure lookup with `%1$s`-style placeholders; falls back to English, then to the key. */\nexport function translate(locale: Locale, key: string, ...args: unknown[]): string {\n const template = BUNDLES[locale]?.[key] ?? BUNDLES.en[key];\n if (template === undefined) return key;\n return template.replace(/%(\\d+)\\$s/g, (match, index: string) => {\n const value = args[Number(index) - 1];\n return value === undefined ? match : String(value);\n });\n}\n\nlet current: Locale = 'en';\n\nexport function setLocale(locale: Locale): void {\n current = locale;\n}\n\nexport function getLocale(): Locale {\n return current;\n}\n\n/** Translate with the locale selected for this run. */\nexport function t(key: string, ...args: unknown[]): string {\n return translate(current, key, ...args);\n}\n","import { APP_URL } from './config.js';\nimport { t } from './i18n/index.js';\n\nexport const EXIT_OK = 0;\nexport const EXIT_ERROR = 1;\nexport const EXIT_USAGE = 2;\n\n/** An error already phrased for the user; the CLI prints the message and exits with `exitCode`. */\nexport class CliError extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode: number = EXIT_ERROR) {\n super(message);\n this.name = 'CliError';\n this.exitCode = exitCode;\n }\n}\n\nexport class UsageError extends CliError {\n constructor(message: string) {\n super(message, EXIT_USAGE);\n this.name = 'UsageError';\n }\n}\n\ntype ErrorEnvelope = { error?: { code?: string; message?: string } };\n\nfunction envelopeMessage(body: unknown): string | undefined {\n const message = (body as ErrorEnvelope | null)?.error?.message;\n return typeof message === 'string' && message.length > 0 ? message : undefined;\n}\n\n/** Map an API error response onto a localized CliError. */\nexport function mapApiError(status: number, body: unknown): CliError {\n switch (status) {\n case 401:\n return new CliError(t('cli_error_unauthorized'));\n case 402:\n return new CliError(t('cli_error_pro_required', APP_URL));\n case 429:\n return new CliError(t('cli_error_quota', APP_URL));\n default:\n return new CliError(\n envelopeMessage(body) ?? t('cli_error_unexpected_response', status),\n );\n }\n}\n","import { apiBase } from './config.js';\nimport { CliError, mapApiError } from './errors.js';\nimport { t } from './i18n/index.js';\nimport type { ListResponse } from './types.js';\n\nexport interface ApiClientOptions {\n /** Resolves a Supabase access token; throws a CliError when not signed in. */\n getToken: () => Promise<string>;\n baseUrl?: string;\n fetchImpl?: typeof fetch;\n}\n\nexport interface BinaryResponse {\n data: Uint8Array;\n filename: string | null;\n}\n\ntype Query = Record<string, string | number | boolean | undefined | null>;\n\nfunction buildUrl(baseUrl: string, path: string, query?: Query): string {\n const url = new URL(baseUrl + path);\n for (const [key, value] of Object.entries(query ?? {})) {\n if (value !== undefined && value !== null && value !== '') {\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n}\n\nfunction filenameFromDisposition(header: string | null): string | null {\n if (!header) return null;\n const match = /filename\\*?=(?:UTF-8'')?\"?([^\";]+)\"?/i.exec(header);\n return match?.[1] ? decodeURIComponent(match[1]) : null;\n}\n\nexport class ApiClient {\n private readonly baseUrl: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: ApiClientOptions) {\n this.baseUrl = options.baseUrl ?? apiBase();\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n private async send(path: string, init: RequestInit, query?: Query): Promise<Response> {\n const token = await this.options.getToken();\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${token}`);\n headers.set('Accept', headers.get('Accept') ?? 'application/json');\n\n let response: Response;\n try {\n response = await this.fetchImpl(buildUrl(this.baseUrl, path, query), {\n ...init,\n headers,\n });\n } catch (error) {\n throw new CliError(t('cli_error_network', (error as Error).message));\n }\n\n if (!response.ok) {\n const body = await response.json().catch(() => null);\n throw mapApiError(response.status, body);\n }\n return response;\n }\n\n private async parseJson<T>(response: Response): Promise<T> {\n try {\n return (await response.json()) as T;\n } catch {\n // e.g. HTML from a proxy or SPA fallback instead of the API\n throw new CliError(t('cli_error_unexpected_response', String(response.status)));\n }\n }\n\n async get<T>(path: string, query?: Query): Promise<T> {\n const response = await this.send(path, { method: 'GET' }, query);\n return await this.parseJson<T>(response);\n }\n\n async post<T>(path: string, body?: unknown): Promise<T> {\n const response = await this.send(path, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n });\n return await this.parseJson<T>(response);\n }\n\n async patch<T>(path: string, body?: unknown): Promise<T> {\n const response = await this.send(path, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body ?? {}),\n });\n return await this.parseJson<T>(response);\n }\n\n async postMultipart<T>(path: string, form: FormData): Promise<T> {\n const response = await this.send(path, { method: 'POST', body: form });\n return await this.parseJson<T>(response);\n }\n\n /**\n * Fetches every page of a list endpoint and returns the concatenated items.\n * Stops once a page comes back short of `limit`, and also honors `total`\n * when the API reports it — but works fine without it.\n */\n async getAllPages<T>(path: string, query?: Query): Promise<T[]> {\n const limit = 200;\n let offset = 0;\n const items: T[] = [];\n for (;;) {\n const page = await this.get<ListResponse<T>>(path, { ...query, limit, offset });\n items.push(...page.items);\n offset += limit;\n if (page.items.length < limit) break;\n if (typeof page.total === 'number' && items.length >= page.total) break;\n }\n return items;\n }\n\n async getBinary(path: string): Promise<BinaryResponse> {\n const response = await this.send(path, { method: 'GET', headers: { Accept: '*/*' } });\n const buffer = await response.arrayBuffer();\n return {\n data: new Uint8Array(buffer),\n filename: filenameFromDisposition(response.headers.get('content-disposition')),\n };\n }\n}\n","import { ApiClient } from '../api.js';\nimport { getAccessToken } from '../auth.js';\nimport { scanBase } from '../config.js';\nimport { t } from '../i18n/index.js';\n\n/** Flags every command accepts. Built lazily so the locale is already set. */\nexport function commonArgs() {\n return {\n json: { type: 'boolean' as const, description: t('cli_flag_json'), default: false },\n lang: { type: 'string' as const, description: t('cli_flag_lang') },\n };\n}\n\n/** Read --lang straight from argv: the locale must be known before help is built. */\nexport function langFromArgv(argv: string[]): string | undefined {\n for (let index = 0; index < argv.length; index += 1) {\n const entry = argv[index] ?? '';\n if (entry === '--lang') return argv[index + 1];\n if (entry.startsWith('--lang=')) return entry.slice('--lang='.length);\n }\n return undefined;\n}\n\nexport function client(): ApiClient {\n return new ApiClient({ getToken: getAccessToken });\n}\n\n/** Client pointed at the Supabase functions URL directly (bypasses the Vercel proxy). */\nexport function scanClient(): ApiClient {\n return new ApiClient({ getToken: getAccessToken, baseUrl: scanBase() });\n}\n\nexport function out(line: string): void {\n process.stdout.write(`${line}\\n`);\n}\n\nexport function printJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n","import { defineCommand } from 'citty';\n\nimport { UsageError } from '../errors.js';\nimport { table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { optional, providedValue } from '../lib/args.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport { isUuid, resolveCustomer } from '../lib/customers.js';\nimport type { Customer } from '../types.js';\n\n/** Flags shared by `create` and `update`. */\nfunction customerFieldArgs() {\n return {\n name: { type: 'string' as const, description: t('cli_flag_name') },\n department: { type: 'string' as const, description: t('cli_flag_department') },\n address: { type: 'string' as const, description: t('cli_flag_address') },\n 'postal-code': { type: 'string' as const, description: t('cli_flag_postal_code') },\n city: { type: 'string' as const, description: t('cli_flag_city') },\n country: { type: 'string' as const, description: t('cli_flag_country') },\n };\n}\n\ntype CustomerFieldArgs = {\n name?: unknown;\n department?: unknown;\n address?: unknown;\n 'postal-code'?: unknown;\n city?: unknown;\n country?: unknown;\n};\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_customers_ls') },\n args: {\n ...commonArgs(),\n archived: { type: 'boolean', description: t('cli_flag_archived'), default: false },\n },\n async run({ args }) {\n const items = await client().getAllPages<Customer>('/customers', {\n includeArchived: args.archived ? 'true' : undefined,\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(t('cli_empty_customers'));\n return;\n }\n\n const columns = [\n { header: t('cli_col_name') },\n { header: t('cli_col_city') },\n ...(args.archived ? [{ header: t('cli_col_archived') }] : []),\n { header: t('cli_col_id') },\n ];\n const rows = items.map((customer) => [\n customer.name,\n [customer.postalCode, customer.city].filter(Boolean).join(' '),\n ...(args.archived ? [customer.archived ? t('cli_yes') : t('cli_no')] : []),\n customer.id,\n ]);\n out(table(columns, rows));\n },\n });\n}\n\n/** Validates the required fields and builds the POST /customers body. */\nexport function buildCreateBody(fields: CustomerFieldArgs) {\n const name = optional(fields.name);\n const address = optional(fields.address);\n const postalCode = optional(fields['postal-code']);\n const city = optional(fields.city);\n if (!name) throw new UsageError(t('cli_error_name_required'));\n if (!address) throw new UsageError(t('cli_error_address_required'));\n if (!postalCode) throw new UsageError(t('cli_error_postal_code_required'));\n if (!city) throw new UsageError(t('cli_error_city_required'));\n\n return {\n name,\n address,\n postalCode,\n city,\n country: optional(fields.country),\n department: optional(fields.department),\n };\n}\n\nfunction createCommand() {\n return defineCommand({\n meta: { name: 'create', description: t('cli_cmd_customers_create') },\n args: {\n ...commonArgs(),\n ...customerFieldArgs(),\n },\n async run({ args }) {\n const customer = await client().post<Customer>('/customers', buildCreateBody(args));\n\n if (args.json) printJson(customer);\n else out(t('cli_customer_created', customer.name));\n },\n });\n}\n\n/**\n * Builds a partial-update body from whichever flags were actually given. A\n * flag given as an empty string is kept as an empty string — it is a\n * deliberate \"clear this field\" request, not a missing flag — and the server\n * decides what an empty value means per field (rejected for the required\n * ones, cleared to null for country/department).\n */\nexport function updatePayload(fields: CustomerFieldArgs): Record<string, string> {\n const payload: Record<string, string> = {};\n const name = providedValue(fields.name);\n const address = providedValue(fields.address);\n const postalCode = providedValue(fields['postal-code']);\n const city = providedValue(fields.city);\n const country = providedValue(fields.country);\n const department = providedValue(fields.department);\n if (name !== undefined) payload.name = name;\n if (address !== undefined) payload.address = address;\n if (postalCode !== undefined) payload.postalCode = postalCode;\n if (city !== undefined) payload.city = city;\n if (country !== undefined) payload.country = country;\n if (department !== undefined) payload.department = department;\n return payload;\n}\n\n/** Same as {@link updatePayload}, but throws when no field was actually given. */\nexport function ensureUpdatePayload(fields: CustomerFieldArgs): Record<string, string> {\n const payload = updatePayload(fields);\n if (Object.keys(payload).length === 0) {\n throw new UsageError(t('cli_error_update_fields_required'));\n }\n return payload;\n}\n\nfunction updateCommand() {\n return defineCommand({\n meta: { name: 'update', description: t('cli_cmd_customers_update') },\n args: {\n customer: { type: 'positional', description: t('cli_arg_customer_ref'), required: true },\n ...commonArgs(),\n ...customerFieldArgs(),\n },\n async run({ args }) {\n const payload = ensureUpdatePayload(args);\n const ref = String(args.customer);\n const api = client();\n\n // A UUID needs no lookup — skip paging through every customer just to\n // resolve a reference we already have.\n const customerId = isUuid(ref)\n ? ref\n : resolveCustomer(ref, await api.getAllPages<Customer>('/customers')).id;\n\n const customer = await api.patch<Customer>(`/customers/${customerId}`, payload);\n\n if (args.json) printJson(customer);\n else out(t('cli_customer_updated', customer.name));\n },\n });\n}\n\nexport function customersCommand() {\n return defineCommand({\n meta: { name: 'customers', description: t('cli_cmd_customers') },\n subCommands: { ls: listCommand(), create: createCommand(), update: updateCommand() },\n });\n}\n","export type Align = 'left' | 'right';\n\nexport interface Column {\n header: string;\n align?: Align;\n}\n\n/** `2026-08-30T00:00:00+00:00` and `2026-08-30` both render as `2026-08-30`. */\nexport function formatDate(value: string | null | undefined): string {\n if (!value) return '';\n const match = /^(\\d{4}-\\d{2}-\\d{2})/.exec(value);\n return match?.[1] ?? value;\n}\n\n/** Swiss grouping: `CHF 1'234.50`. Currency first, two decimals, never localized separators. */\nexport function formatMoney(\n amount: number | null | undefined,\n currency: string | null | undefined,\n): string {\n if (amount === null || amount === undefined || Number.isNaN(amount)) return '';\n const negative = amount < 0;\n const [whole = '0', fraction = '00'] = Math.abs(amount).toFixed(2).split('.');\n const grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \"'\");\n const number = `${negative ? '-' : ''}${grouped}.${fraction}`;\n return currency ? `${currency} ${number}` : number;\n}\n\n/** Today in Europe/Zurich as YYYY-MM-DD — the timezone bonbox books in. */\nexport function todayInZurich(now: Date = new Date()): string {\n return new Intl.DateTimeFormat('en-CA', {\n timeZone: 'Europe/Zurich',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(now);\n}\n\nfunction pad(value: string, width: number, align: Align): string {\n const padding = ' '.repeat(Math.max(0, width - value.length));\n return align === 'right' ? padding + value : value + padding;\n}\n\n/**\n * Render an aligned table. Columns are separated by two spaces and the last\n * column is never padded, so lines have no trailing whitespace.\n */\nexport function table(columns: Column[], rows: string[][]): string {\n const widths = columns.map((column, index) =>\n Math.max(column.header.length, ...rows.map((row) => (row[index] ?? '').length)),\n );\n\n const render = (cells: string[]): string =>\n cells\n .map((cell, index) => {\n const align = columns[index]?.align ?? 'left';\n const isLast = index === columns.length - 1;\n return isLast && align === 'left' ? cell : pad(cell, widths[index] ?? 0, align);\n })\n .join(' ')\n .replace(/\\s+$/, '');\n\n return [render(columns.map((column) => column.header)), ...rows.map(render)].join('\\n');\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\n\n/** citty gives a string for a single flag and an array when it is repeated. */\nexport function toArray(value: unknown): string[] {\n if (value === undefined || value === null || value === false) return [];\n if (Array.isArray(value)) return value.map(String).filter((entry) => entry.length > 0);\n const single = String(value);\n return single.length > 0 ? [single] : [];\n}\n\nexport function optional(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n const text = String(value).trim();\n return text.length > 0 ? text : undefined;\n}\n\n/**\n * Like {@link optional}, but a flag explicitly given as an empty string stays\n * empty instead of becoming `undefined` — for partial updates where \"given but\n * empty\" is itself meaningful (e.g. clearing an optional field).\n */\nexport function providedValue(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n return String(value).trim();\n}\n\nexport function requireDate(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) {\n throw new UsageError(t('cli_error_date_invalid', value));\n }\n return value;\n}\n\nexport function requireNumber(value: string | undefined, messageKey: string): number | undefined {\n if (value === undefined) return undefined;\n const parsed = Number(value.replace(',', '.'));\n if (!Number.isFinite(parsed)) throw new UsageError(t(messageKey, value));\n return parsed;\n}\n\n/** `2026-08` → the first and last day of that month. */\nexport function monthRange(month: string): { from: string; to: string } {\n const match = /^(\\d{4})-(\\d{2})$/.exec(month);\n const year = Number(match?.[1]);\n const monthIndex = Number(match?.[2]);\n if (!match || monthIndex < 1 || monthIndex > 12) {\n throw new UsageError(t('cli_error_month_invalid', month));\n }\n const lastDay = new Date(Date.UTC(year, monthIndex, 0)).getUTCDate();\n const padded = String(monthIndex).padStart(2, '0');\n return { from: `${year}-${padded}-01`, to: `${year}-${padded}-${String(lastDay).padStart(2, '0')}` };\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport type { Customer } from '../types.js';\n\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\nexport function isUuid(value: string): boolean {\n return UUID_RE.test(value);\n}\n\nexport type CustomerMatch =\n | { kind: 'match'; customer: Customer }\n | { kind: 'ambiguous'; candidates: Customer[] }\n | { kind: 'none' };\n\n/**\n * Resolve a customer reference: exact ID, then exact name (case-insensitive),\n * then a unique name prefix. Anything else is ambiguous or unknown.\n */\nexport function matchCustomer(reference: string, customers: Customer[]): CustomerMatch {\n const needle = reference.trim().toLowerCase();\n if (!needle) return { kind: 'none' };\n\n const byId = customers.find((customer) => customer.id.toLowerCase() === needle);\n if (byId) return { kind: 'match', customer: byId };\n\n const exact = customers.filter((customer) => customer.name.trim().toLowerCase() === needle);\n if (exact.length === 1) return { kind: 'match', customer: exact[0] as Customer };\n if (exact.length > 1) return { kind: 'ambiguous', candidates: exact };\n\n const prefix = customers.filter((customer) =>\n customer.name.trim().toLowerCase().startsWith(needle),\n );\n if (prefix.length === 1) return { kind: 'match', customer: prefix[0] as Customer };\n if (prefix.length > 1) return { kind: 'ambiguous', candidates: prefix };\n\n return { kind: 'none' };\n}\n\n/** Same as {@link matchCustomer}, but throws a message the user can act on. */\nexport function resolveCustomer(reference: string, customers: Customer[]): Customer {\n const result = matchCustomer(reference, customers);\n if (result.kind === 'match') return result.customer;\n if (result.kind === 'ambiguous') {\n const list = result.candidates\n .map((customer) => ` ${customer.name} ${customer.id}`)\n .join('\\n');\n throw new UsageError(`${t('cli_error_customer_ambiguous', reference)}\\n${list}`);\n }\n throw new UsageError(t('cli_error_customer_not_found', reference));\n}\n","import { defineCommand } from 'citty';\nimport { writeFile } from 'node:fs/promises';\n\nimport type { ApiClient } from '../api.js';\nimport { formatDate, formatMoney, table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { optional, providedValue, requireDate, requireNumber, toArray } from '../lib/args.js';\nimport { client, commonArgs, out, printJson } from '../lib/context.js';\nimport { resolveCustomer } from '../lib/customers.js';\nimport { parseItems } from '../lib/items.js';\nimport { UsageError } from '../errors.js';\nimport type { Customer, Invoice } from '../types.js';\n\nasync function customerNames(api: ApiClient): Promise<Map<string, string>> {\n const customers = await api.getAllPages<Customer>('/customers', {\n includeArchived: 'true',\n });\n return new Map(customers.map((customer) => [customer.id, customer.name]));\n}\n\nexport function invoiceTable(invoices: Invoice[], names: Map<string, string>): string {\n const columns = [\n { header: t('cli_col_number') },\n { header: t('cli_col_date') },\n { header: t('cli_col_status') },\n { header: t('cli_col_total'), align: 'right' as const },\n { header: t('cli_col_customer') },\n ];\n const rows = invoices.map((invoice) => [\n invoice.invoiceNumber,\n formatDate(invoice.invoiceDate),\n invoice.status === 'paid' ? t('cli_status_paid') : t('cli_status_created'),\n formatMoney(invoice.total, invoice.currency),\n (invoice.customerId && names.get(invoice.customerId)) || '',\n ]);\n return table(columns, rows);\n}\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_invoices_ls') },\n args: {\n ...commonArgs(),\n status: { type: 'string', description: t('cli_flag_status') },\n quotes: { type: 'boolean', description: t('cli_flag_quotes'), default: false },\n },\n async run({ args }) {\n const status = optional(args.status);\n if (status && status !== 'created' && status !== 'paid') {\n throw new UsageError(t('cli_flag_status'));\n }\n\n const api = client();\n const items = await api.getAllPages<Invoice>('/invoices', {\n status,\n quotes: args.quotes ? 'only' : 'exclude',\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(args.quotes ? t('cli_empty_quotes') : t('cli_empty_invoices'));\n return;\n }\n out(invoiceTable(items, await customerNames(api)));\n },\n });\n}\n\nasync function savePdf(api: ApiClient, reference: string, target?: string): Promise<string> {\n const pdf = await api.getBinary(`/invoices/${encodeURIComponent(reference)}/pdf`);\n const filename = target ?? pdf.filename ?? `Invoice-${reference}.pdf`;\n await writeFile(filename, pdf.data);\n return filename;\n}\n\nfunction createCommand() {\n return defineCommand({\n meta: { name: 'create', description: t('cli_cmd_invoices_create') },\n args: {\n ...commonArgs(),\n customer: { type: 'string', description: t('cli_flag_customer_ref') },\n item: { type: 'string', description: t('cli_flag_item') },\n quote: { type: 'boolean', description: t('cli_flag_quote'), default: false },\n date: { type: 'string', description: t('cli_flag_invoice_date') },\n 'payment-days': { type: 'string', description: t('cli_flag_payment_days') },\n currency: { type: 'string', description: t('cli_flag_currency') },\n language: { type: 'string', description: t('cli_flag_language') },\n subtitle: { type: 'string', description: t('cli_flag_subtitle') },\n reference: { type: 'string', description: t('cli_flag_reference') },\n pdf: { type: 'string', description: t('cli_flag_pdf') },\n },\n async run({ args }) {\n const customerRef = optional(args.customer);\n if (!customerRef) throw new UsageError(t('cli_error_customer_required'));\n const items = parseItems(toArray(args.item));\n\n const api = client();\n const customers = await api.getAllPages<Customer>('/customers');\n const customer = resolveCustomer(customerRef, customers);\n\n const invoice = await api.post<Invoice>('/invoices', {\n customerId: customer.id,\n items,\n quote: Boolean(args.quote),\n date: requireDate(optional(args.date)),\n paymentDays: requireNumber(optional(args['payment-days']), 'cli_error_price_invalid'),\n currency: optional(args.currency),\n language: optional(args.language),\n subtitle: optional(args.subtitle),\n reference: optional(args.reference),\n });\n\n const pdfTarget = optional(args.pdf);\n const savedTo = pdfTarget ? await savePdf(api, invoice.id, pdfTarget) : null;\n\n if (args.json) {\n printJson(invoice);\n return;\n }\n const total = formatMoney(invoice.total, invoice.currency);\n out(\n invoice.isQuote\n ? t('cli_quote_created', invoice.invoiceNumber, total)\n : t('cli_invoice_created', invoice.invoiceNumber, total),\n );\n if (savedTo) out(t('cli_pdf_saved', savedTo));\n },\n });\n}\n\nfunction updateCommand() {\n return defineCommand({\n meta: { name: 'update', description: t('cli_cmd_invoices_update') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n customer: { type: 'string', description: t('cli_flag_customer_ref') },\n item: { type: 'string', description: t('cli_flag_item') },\n date: { type: 'string', description: t('cli_flag_invoice_date_update') },\n 'payment-days': { type: 'string', description: t('cli_flag_payment_days') },\n currency: { type: 'string', description: t('cli_flag_currency') },\n language: { type: 'string', description: t('cli_flag_language') },\n subtitle: { type: 'string', description: t('cli_flag_subtitle') },\n reference: { type: 'string', description: t('cli_flag_reference') },\n 'vat-rate': { type: 'string', description: t('cli_flag_vat_rate') },\n 'custom-notes': { type: 'string', description: t('cli_flag_custom_notes') },\n },\n async run({ args }) {\n const customerRef = optional(args.customer);\n const rawItems = toArray(args.item);\n const items = rawItems.length > 0 ? parseItems(rawItems) : undefined;\n\n const api = client();\n const customerId = customerRef\n ? resolveCustomer(customerRef, await api.getAllPages<Customer>('/customers')).id\n : undefined;\n\n // Only the flags actually given end up in the body — this is a partial\n // update. subtitle/reference/customNotes/vatRate pass an explicitly\n // empty flag through as a deliberate \"clear this field\".\n const payload: Record<string, unknown> = {};\n if (customerId !== undefined) payload.customerId = customerId;\n if (items !== undefined) payload.items = items;\n\n const date = requireDate(optional(args.date));\n if (date !== undefined) payload.date = date;\n\n const paymentDays = requireNumber(optional(args['payment-days']), 'cli_error_price_invalid');\n if (paymentDays !== undefined) payload.paymentDays = paymentDays;\n\n const currency = optional(args.currency);\n if (currency !== undefined) payload.currency = currency;\n\n const language = optional(args.language);\n if (language !== undefined) payload.language = language;\n\n const subtitle = providedValue(args.subtitle);\n if (subtitle !== undefined) payload.subtitle = subtitle;\n\n const reference = providedValue(args.reference);\n if (reference !== undefined) payload.reference = reference;\n\n const customNotes = providedValue(args['custom-notes']);\n if (customNotes !== undefined) payload.customNotes = customNotes;\n\n const vatRateRaw = providedValue(args['vat-rate']);\n if (vatRateRaw === '') payload.vatRate = '';\n else if (vatRateRaw !== undefined) {\n payload.vatRate = requireNumber(vatRateRaw, 'cli_error_price_invalid');\n }\n\n if (Object.keys(payload).length === 0) {\n throw new UsageError(t('cli_error_update_fields_required'));\n }\n\n const invoice = await api.patch<Invoice>(\n `/invoices/${encodeURIComponent(String(args.invoice))}`,\n payload,\n );\n\n if (args.json) printJson(invoice);\n else out(invoice.isQuote ? t('cli_quote_updated', invoice.invoiceNumber) : t('cli_invoice_updated', invoice.invoiceNumber));\n },\n });\n}\n\nfunction pdfCommand() {\n return defineCommand({\n meta: { name: 'pdf', description: t('cli_cmd_invoices_pdf') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n output: { type: 'string', alias: 'o', description: t('cli_flag_output') },\n },\n async run({ args }) {\n const filename = await savePdf(client(), String(args.invoice), optional(args.output));\n if (args.json) printJson({ file: filename });\n else out(t('cli_pdf_saved', filename));\n },\n });\n}\n\nfunction paidCommand() {\n return defineCommand({\n meta: { name: 'paid', description: t('cli_cmd_invoices_paid') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n date: { type: 'string', description: t('cli_flag_paid_date') },\n receipt: { type: 'boolean', description: t('cli_flag_no_receipt'), default: true },\n },\n async run({ args }) {\n const invoice = await client().post<Invoice>(\n `/invoices/${encodeURIComponent(String(args.invoice))}/paid`,\n {\n paidDate: requireDate(optional(args.date)),\n createReceipt: args.receipt !== false,\n },\n );\n if (args.json) printJson(invoice);\n else out(t('cli_invoice_paid', invoice.invoiceNumber));\n },\n });\n}\n\nfunction unpaidCommand() {\n return defineCommand({\n meta: { name: 'unpaid', description: t('cli_cmd_invoices_unpaid') },\n args: {\n invoice: { type: 'positional', description: t('cli_arg_invoice_ref'), required: true },\n ...commonArgs(),\n },\n async run({ args }) {\n const invoice = await client().post<Invoice>(\n `/invoices/${encodeURIComponent(String(args.invoice))}/unpaid`,\n );\n if (args.json) printJson(invoice);\n else out(t('cli_invoice_unpaid', invoice.invoiceNumber));\n },\n });\n}\n\nexport function invoicesCommand() {\n return defineCommand({\n meta: { name: 'invoices', description: t('cli_cmd_invoices') },\n subCommands: {\n ls: listCommand(),\n create: createCommand(),\n update: updateCommand(),\n pdf: pdfCommand(),\n paid: paidCommand(),\n unpaid: unpaidCommand(),\n },\n });\n}\n","import { UsageError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport type { NewLineItem } from '../types.js';\n\nconst NUMBER = /^-?\\d+(?:[.,]\\d+)?$/;\n\nfunction toNumber(raw: string): number | null {\n const trimmed = raw.trim();\n if (!NUMBER.test(trimmed)) return null;\n return Number(trimmed.replace(',', '.'));\n}\n\n/**\n * Parse `description:quantity:unitPrice[:discount%]`.\n * The description may itself contain colons — quantity, price and the optional\n * discount are read from the end. The trailing part is only a discount when it\n * ends with `%`; a bare number there is just part of the qty/price split.\n */\nexport function parseItem(raw: string): NewLineItem {\n const parts = raw.split(':');\n if (parts.length < 3) throw new UsageError(t('cli_error_item_format', raw));\n\n let discountPercent: number | undefined;\n const last = parts[parts.length - 1] ?? '';\n if (parts.length >= 4 && last.trim().endsWith('%')) {\n const value = toNumber(last.replace('%', ''));\n if (value === null) throw new UsageError(t('cli_error_item_number', raw));\n discountPercent = value;\n parts.pop();\n }\n\n const unitPrice = toNumber(parts.pop() ?? '');\n const quantity = toNumber(parts.pop() ?? '');\n if (unitPrice === null || quantity === null) {\n throw new UsageError(t('cli_error_item_number', raw));\n }\n\n const description = parts.join(':').trim();\n if (!description) throw new UsageError(t('cli_error_item_format', raw));\n\n return discountPercent === undefined\n ? { description, quantity, unitPrice }\n : { description, quantity, unitPrice, discountPercent };\n}\n\nexport function parseItems(raw: string[]): NewLineItem[] {\n if (raw.length === 0) throw new UsageError(t('cli_error_items_required'));\n return raw.map(parseItem);\n}\n","import { defineCommand } from 'citty';\nimport { randomBytes } from 'node:crypto';\nimport { createServer, type Server } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport open from 'open';\n\nimport { getSupabase } from '../auth.js';\nimport { APP_URL, CALLBACK_PORTS } from '../config.js';\nimport { CliError } from '../errors.js';\nimport { t } from '../i18n/index.js';\nimport { commonArgs, out, printJson } from '../lib/context.js';\n\nconst TIMEOUT_MS = 5 * 60 * 1000;\n\nfunction page(heading: string, body: string): string {\n return `<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\n<title>${t('cli_callback_title')}</title></head>\n<body style=\"margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center;\nfont:16px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#111;background:#faf9f7\">\n<main style=\"text-align:center;max-width:28rem;padding:2rem\">\n<h1 style=\"font-size:1.25rem;font-weight:600;margin:0 0 .5rem\">${heading}</h1>\n<p style=\"margin:0;color:#555\">${body}</p>\n</main></body></html>`;\n}\n\nexport type CallbackResult =\n | { kind: 'success'; tokens: { accessToken: string; refreshToken: string } }\n | { kind: 'error'; message: string }\n | { kind: 'invalid' };\n\n/**\n * Pure request handler for the `/callback` redirect, split out so it's unit-testable.\n *\n * A state mismatch, or a request missing both tokens and an error, is `invalid` — the caller\n * responds 400 and keeps listening rather than aborting the whole login attempt (a stray or\n * malformed request shouldn't kill a valid in-flight login). An `error`/`error_description` param\n * with a *matching* state is a genuine failure report from the web page and does end the attempt.\n */\nexport function handleCallbackRequest(requestUrl: string, expectedState: string): CallbackResult {\n const url = new URL(requestUrl, 'http://localhost');\n const state = url.searchParams.get('state');\n if (state !== expectedState) return { kind: 'invalid' };\n\n const accessToken = url.searchParams.get('access_token');\n const refreshToken = url.searchParams.get('refresh_token');\n if (accessToken && refreshToken) {\n return { kind: 'success', tokens: { accessToken, refreshToken } };\n }\n\n const errorMessage = url.searchParams.get('error_description') ?? url.searchParams.get('error');\n if (errorMessage) return { kind: 'error', message: errorMessage };\n\n return { kind: 'invalid' };\n}\n\nfunction listen(port: number): Promise<Server | null> {\n return new Promise((resolve) => {\n const server = createServer();\n server.once('error', () => resolve(null));\n server.listen(port, '127.0.0.1', () => resolve(server));\n });\n}\n\nasync function openListener(): Promise<{ server: Server; port: number }> {\n for (const port of CALLBACK_PORTS) {\n const server = await listen(port);\n if (server) return { server, port: (server.address() as AddressInfo).port };\n }\n throw new CliError(t('cli_login_no_port', CALLBACK_PORTS.join(', ')));\n}\n\n/**\n * Resolve with the tokens the browser redirect carries back.\n *\n * The `/callback` request itself never renders the tokens: it 302s to `/done` (or `/error`) so\n * the access/refresh tokens don't linger in the browser's address bar or history.\n */\nexport function awaitTokens(\n server: Server,\n state: string,\n): Promise<{ accessToken: string; refreshToken: string }> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new CliError(t('cli_login_timeout')));\n }, TIMEOUT_MS);\n\n server.on('request', (request, response) => {\n const url = new URL(request.url ?? '/', 'http://localhost');\n\n if (url.pathname === '/done') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_heading'), t('cli_callback_body')));\n return;\n }\n if (url.pathname === '/error') {\n response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_error_heading'), t('cli_callback_error_body')));\n return;\n }\n if (!url.pathname.startsWith('/callback')) {\n response.writeHead(404).end();\n return;\n }\n\n const result = handleCallbackRequest(request.url ?? '/', state);\n if (result.kind === 'invalid') {\n response.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });\n response.end(page(t('cli_callback_error_heading'), t('cli_callback_error_body')));\n return;\n }\n\n if (result.kind === 'error') {\n response.writeHead(302, { Location: '/error' });\n response.end();\n clearTimeout(timer);\n reject(new CliError(t('cli_login_failed', result.message)));\n return;\n }\n\n response.writeHead(302, { Location: '/done' });\n response.end();\n clearTimeout(timer);\n resolve(result.tokens);\n });\n });\n}\n\nexport function loginCommand() {\n return defineCommand({\n meta: { name: 'login', description: t('cli_cmd_login') },\n args: commonArgs(),\n async run({ args }) {\n const { server, port } = await openListener();\n try {\n const state = randomBytes(16).toString('hex');\n const loginUrl = `${APP_URL}/login?cli_port=${port}&state=${state}`;\n\n if (!args.json) {\n out(t('cli_login_opening'));\n out(t('cli_login_manual', loginUrl));\n out(t('cli_login_waiting'));\n }\n await open(loginUrl).catch(() => undefined);\n\n const { accessToken, refreshToken } = await awaitTokens(server, state);\n\n const supabase = getSupabase();\n const { data, error } = await supabase.auth.setSession({\n access_token: accessToken,\n refresh_token: refreshToken,\n });\n if (error) throw new CliError(t('cli_login_failed', error.message));\n\n const email = data.user?.email ?? data.user?.id ?? '';\n if (args.json) printJson({ user: { id: data.user?.id, email } });\n else out(t('cli_login_success', email));\n } finally {\n server.close();\n }\n },\n });\n}\n","import { defineCommand } from 'citty';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, extname } from 'node:path';\n\nimport { UsageError } from '../errors.js';\nimport { formatDate, formatMoney, table } from '../format.js';\nimport { t } from '../i18n/index.js';\nimport { monthRange, optional, requireDate, requireNumber, toArray } from '../lib/args.js';\nimport { client, commonArgs, out, printJson, scanClient } from '../lib/context.js';\nimport { resolveCustomer } from '../lib/customers.js';\nimport type { Customer, Receipt } from '../types.js';\n\nconst MIME_TYPES: Record<string, string> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.webp': 'image/webp',\n '.pdf': 'application/pdf',\n};\n\nfunction receiptTable(receipts: Receipt[]): string {\n const columns = [\n { header: t('cli_col_date') },\n { header: t('cli_col_seller') },\n { header: t('cli_col_amount'), align: 'right' as const },\n { header: t('cli_col_category') },\n { header: t('cli_col_id') },\n ];\n const rows = receipts.map((receipt) => [\n formatDate(receipt.date),\n receipt.seller ?? '',\n formatMoney(receipt.price, receipt.currency),\n receipt.taxCategory ?? receipt.category ?? '',\n receipt.id,\n ]);\n return table(columns, rows);\n}\n\nfunction summarize(receipt: Receipt): string {\n return `${receipt.seller ?? ''}, ${formatMoney(receipt.price, receipt.currency)}`.replace(\n /^, /,\n '',\n );\n}\n\nfunction listCommand() {\n return defineCommand({\n meta: { name: 'ls', description: t('cli_cmd_receipts_ls') },\n args: {\n ...commonArgs(),\n month: { type: 'string', description: t('cli_flag_month') },\n from: { type: 'string', description: t('cli_flag_from') },\n to: { type: 'string', description: t('cli_flag_to') },\n project: { type: 'string', description: t('cli_flag_project') },\n },\n async run({ args }) {\n const month = optional(args.month);\n const range = month ? monthRange(month) : undefined;\n\n const items = await client().getAllPages<Receipt>('/receipts', {\n from: range?.from ?? requireDate(optional(args.from)),\n to: range?.to ?? requireDate(optional(args.to)),\n projectId: optional(args.project),\n });\n\n if (args.json) {\n printJson({ items });\n return;\n }\n if (items.length === 0) {\n out(t('cli_empty_receipts'));\n return;\n }\n out(receiptTable(items));\n },\n });\n}\n\nfunction addCommand() {\n return defineCommand({\n meta: { name: 'add', description: t('cli_cmd_receipts_add') },\n args: {\n ...commonArgs(),\n seller: { type: 'string', description: t('cli_flag_seller') },\n price: { type: 'string', description: t('cli_flag_price') },\n date: { type: 'string', description: t('cli_flag_receipt_date') },\n currency: { type: 'string', description: t('cli_flag_currency') },\n category: { type: 'string', description: t('cli_flag_category') },\n 'tax-category': { type: 'string', description: t('cli_flag_tax_category') },\n 'booking-text': { type: 'string', description: t('cli_flag_booking_text') },\n project: { type: 'string', description: t('cli_flag_project') },\n customer: { type: 'string', description: t('cli_flag_customer_ref') },\n },\n async run({ args }) {\n const seller = optional(args.seller);\n const rawPrice = optional(args.price);\n if (!seller) throw new UsageError(t('cli_error_seller_required'));\n if (!rawPrice) throw new UsageError(t('cli_error_price_required'));\n const price = requireNumber(rawPrice, 'cli_error_price_invalid');\n\n const api = client();\n const customerRef = optional(args.customer);\n let customerId: string | undefined;\n if (customerRef) {\n const customers = await api.getAllPages<Customer>('/customers');\n customerId = resolveCustomer(customerRef, customers).id;\n }\n\n const receipt = await api.post<Receipt>('/receipts', {\n seller,\n price,\n date: requireDate(optional(args.date)),\n currency: optional(args.currency),\n category: optional(args.category),\n taxCategory: optional(args['tax-category']),\n bookingText: optional(args['booking-text']),\n projectId: optional(args.project),\n customerId,\n });\n\n if (args.json) printJson(receipt);\n else out(t('cli_receipt_added', formatDate(receipt.date), summarize(receipt)));\n },\n });\n}\n\nfunction scanCommand() {\n return defineCommand({\n meta: { name: 'scan', description: t('cli_cmd_receipts_scan') },\n args: {\n files: { type: 'positional', description: t('cli_arg_scan_files'), required: false },\n ...commonArgs(),\n project: { type: 'string', description: t('cli_flag_project') },\n },\n async run({ args }) {\n const files = toArray((args as { _?: string[] })._ ?? args.files);\n if (files.length === 0) throw new UsageError(t('cli_error_files_required'));\n\n const form = new FormData();\n for (const path of files) {\n if (!existsSync(path)) throw new UsageError(t('cli_error_file_missing', path));\n const content = await readFile(path);\n const type = MIME_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream';\n form.append('file', new Blob([new Uint8Array(content)], { type }), basename(path));\n }\n const projectId = optional(args.project);\n if (projectId) form.append('projectId', projectId);\n\n if (!args.json) out(t('cli_scan_uploading', files.length));\n // Scans go straight to the Supabase functions URL — the Vercel proxy caps request bodies,\n // which large multi-page receipt scans can exceed.\n const receipt = await scanClient().postMultipart<Receipt>('/receipts/scan', form);\n\n if (args.json) printJson(receipt);\n else out(t('cli_receipt_scanned', formatDate(receipt.date), summarize(receipt)));\n },\n });\n}\n\nexport function receiptsCommand() {\n return defineCommand({\n meta: { name: 'receipts', description: t('cli_cmd_receipts') },\n subCommands: {\n ls: listCommand(),\n add: addCommand(),\n scan: scanCommand(),\n },\n });\n}\n"],"mappings":";;;AAAA,SAAS,iBAAAA,g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AAO;AAAA,EACT,SAAS,OAAO;AACd,QAAI,aAAa,KAAK,GAAG;AACvB,cAAQ,OAAO,MAAM,GAAI,MAAgB,OAAO;AAAA,CAAI;AACpD,YAAM,UAAU,GAAI,MAAM,kBAAkB,MAAM,OAAO,CAAE;AAC3D,aAAO;AAAA,IACT;AACA,QAAI,iBAAiB,UAAU;AAC7B,cAAQ,OAAO,MAAM,GAAG,MAAM,OAAO;AAAA,CAAI;AACzC,aAAO,MAAM;AAAA,IACf;AACA,YAAQ,OAAO,MAAM,GAAI,OAAiB,WAAW,OAAO,KAAK,CAAC;AAAA,CAAI;AACtE,WAAO;AAAA,EACT;AACF;AAEA,QAAQ,KAAK,MAAM,IAAI,CAAC;","names":["defineCommand","page","argv","defineCommand","defineCommand","defineCommand","listCommand","defineCommand","createCommand","updateCommand","defineCommand","defineCommand","defineCommand","existsSync","listCommand","defineCommand","existsSync","defineCommand"]}