Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

`spree api`: Improve output, add autocompletion, add help

Damian Legawiec377db59e9257
diff --git a/docs/api-reference/admin-api/introduction.mdx b/docs/api-reference/admin-api/introduction.mdx
index d0813aea76..e878ce200f 100644
--- a/docs/api-reference/admin-api/introduction.mdx
+++ b/docs/api-reference/admin-api/introduction.mdx
@@ -54,8 +54,19 @@ const { data: orders } = await client.orders.list({
})
```
+## From the command line
+
+Every endpoint can also be called with the [Spree CLI](/developer/cli/admin-api) — a `gh api`-style client built into `@spree/cli`. It's the fastest way to explore the API from a terminal or drive it from scripts and AI agents, with zero-config credentials in local development:
+
+```bash
+spree api get /orders -q status_eq=complete --limit 25
+```
+
+Each endpoint page below shows the matching **Spree CLI** command alongside the SDK example. To browse the whole surface offline, use `spree api endpoints` and `spree api schema "<METHOD> <path>"`.
+
Before integrating, read:
- [Authentication](/api-reference/admin-api/authentication) — secret API keys, scopes, and JWT tokens
- [Errors](/api-reference/admin-api/errors) — error format and admin-specific codes
- [Querying](/api-reference/admin-api/querying) — filtering, sorting, pagination, and `expand`
+- [Spree CLI](/developer/cli/admin-api) — call the Admin API from your terminal
diff --git a/docs/developer/cli/admin-api.mdx b/docs/developer/cli/admin-api.mdx
index 3271d0aa93..db4c129af1 100644
--- a/docs/developer/cli/admin-api.mdx
+++ b/docs/developer/cli/admin-api.mdx
@@ -23,10 +23,16 @@ Credentials resolve through four layers — first match wins:
| Layer | How |
|---|---|
| Flags | `--base-url` / `--api-key` (and `--profile`, which selects a saved profile explicitly) |
-| Environment | `SPREE_BASE_URL` + `SPREE_API_KEY` — the path for CI and agents |
+| Environment | `SPREE_API_KEY` (+ `SPREE_BASE_URL`) — the path for CI and agents. `SPREE_BASE_URL` is optional: a bare key defaults to `http://localhost:3000`, so local dev needs only the key. Set it for a remote store. |
| Project | Inside a Spree project with the dev stack running, the CLI mints a **read-only** key on first use and stores it in `.spree/credentials.json` (gitignored) |
| Profile | `~/.config/spree/config.json`, written by `spree auth login` |
+Host and key resolve **together** per source — a saved or minted key is never silently re-pointed at a host from a different layer. Only `--base-url` (or `SPREE_BASE_URL` paired with `SPREE_API_KEY`) re-points a key deliberately. So against local dev:
+
+```bash
+SPREE_API_KEY=sk_xxx spree api get /products # → http://localhost:3000
+```
+
Zero configuration is needed for local development — the first `spree api get` inside your project just works:
```bash
@@ -62,7 +68,25 @@ spree api get /products/prod_86Rf07xd --expand variants,variants.prices
spree api get /customers --fields id,email --format table
```
-Output is pretty-printed JSON on stdout — pipe it straight into `jq`. `--format table` renders collections for humans.
+`--fields` trims the response to the attributes you name (comma-separated). The resource `id` is **always returned** even if you don't list it, so you only need to name the extra fields. `--expand` is the companion axis — `--fields` selects top-level attributes, `--expand` pulls in related resources:
+
+```bash
+spree api get /products --fields name,price # → id + name + price
+spree api get /products --fields name --expand variants
+```
+
+### Output format
+
+Output is JSON on stdout, and it adapts to where it goes (like `gh` and `stripe`):
+
+- **In a terminal** — indented and syntax-colored, for reading.
+- **Piped or redirected** — compact, single-line, uncolored, so it stays fast and feeds cleanly into `jq` (color codes would corrupt it).
+
+```bash
+spree api get /products --limit 5 | jq '.data[].name'
+```
+
+`--format table` renders collections as a table for humans (nested objects collapse to `{…}`, arrays to `[N]`).
## Writing data
@@ -90,6 +114,21 @@ spree api status # resolved credentials + server r
`spree api endpoints` shows the `read_*` / `write_*` scope each endpoint requires (see [Authentication](/api-reference/admin-api/authentication)) — useful for deciding what to grant a new key.
+### Shell completion
+
+Tab-completion suggests resource paths, Ransack predicate stems (`name_cont=`, `status_eq=`, …), and scope names — all offline from the bundled spec. Add the generated script to your shell:
+
+```bash
+# zsh — add to ~/.zshrc
+eval "$(spree completion zsh)"
+# bash — add to ~/.bashrc
+eval "$(spree completion bash)"
+# fish — add to ~/.config/fish/config.fish
+spree completion fish | source
+```
+
+Then `spree api get /pro⇥` completes to `/products`, and `spree api get /products -q name_⇥` offers the Ransack predicates.
+
## Errors and exit codes
API errors print the error envelope to stderr and exit `1`; usage and configuration problems exit `2`. A scope denial includes the exact remediation:
diff --git a/packages/cli/.changeset/admin-api-commands.md b/packages/cli/.changeset/admin-api-commands.md
index ee53e110c9..0aececbdeb 100644
--- a/packages/cli/.changeset/admin-api-commands.md
+++ b/packages/cli/.changeset/admin-api-commands.md
@@ -8,6 +8,9 @@ New `spree api` and `spree auth` command groups — a gh api-style Admin API cli
- `spree api endpoints` / `spree api schema` — offline schema introspection over a bundled OpenAPI snapshot, including each endpoint's required scope
- `spree api status` — resolved credentials + server reachability
- `spree auth login|status|logout|list` — named profiles in `~/.config/spree/config.json`
-- Zero-config credentials inside a project: a read-only key is minted via the dev stack on first use and stored in `.spree/credentials.json`; remote stores use profiles or `SPREE_BASE_URL`/`SPREE_API_KEY`
+- `spree completion bash|zsh|fish` — shell completion for resource paths, Ransack predicate stems, and scope names, resolved offline from the bundled spec
+- Zero-config credentials inside a project: a read-only key is minted via the dev stack on first use and stored in `.spree/credentials.json`. For other servers, `SPREE_API_KEY` is enough — the host defaults to `http://localhost:3000`; set `SPREE_BASE_URL` or save a profile for a remote store.
+
+Output is JSON: indented and colored in a terminal, compact and uncolored when piped (clean for `jq`).
Works against any Spree 5.5+ instance.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 0f9e2f6913..fd0eb84ba8 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -137,7 +137,7 @@ spree api-key revoke pk_abc123def456...
### `spree api`
-Call the Admin API directly with `gh api`-style generic verbs. Works against any Spree 5.5+ instance — inside a project it self-provisions a **read-only** key via the dev stack on first use (saved to `.spree/credentials.json`, gitignored); remote stores use `SPREE_BASE_URL`/`SPREE_API_KEY` env vars or saved profiles.
+Call the Admin API directly with `gh api`-style generic verbs. Works against any Spree 5.5+ instance — inside a project it self-provisions a **read-only** key via the dev stack on first use (saved to `.spree/credentials.json`, gitignored). For other servers set `SPREE_API_KEY` (the host defaults to `http://localhost:3000`; add `SPREE_BASE_URL` for a remote store) or save a profile with `spree auth login`.
```bash
spree api get /products -q status_eq=active --sort -created_at --limit 10
@@ -151,7 +151,15 @@ spree api schema "POST /orders" # request/response schema (offline)
spree api status # resolved credentials + server check
```
-Output is JSON on stdout (pipes into `jq`); `--format table` renders collections for humans. API errors exit `1` with the error envelope on stderr — scope denials include the exact `--scopes` remediation.
+Output is JSON on stdout — indented and colored in a terminal, compact and uncolored when piped (so it feeds cleanly into `jq`). `--format table` renders collections for humans. `--fields name,price` trims the response (the `id` is always included). API errors exit `1` with the error envelope on stderr — scope denials include the exact `--scopes` remediation.
+
+### `spree completion`
+
+Output a shell completion script (`bash`, `zsh`, or `fish`). Tab-completion suggests resource paths, Ransack predicate stems, and scope names — offline from the bundled spec.
+
+```bash
+eval "$(spree completion zsh)" # add to ~/.zshrc (bash/fish also supported)
+```
### `spree auth`
diff --git a/packages/cli/src/api/output.ts b/packages/cli/src/api/output.ts
index 4f933aba3d..a95fe07fcf 100644
--- a/packages/cli/src/api/output.ts
+++ b/packages/cli/src/api/output.ts
@@ -6,8 +6,12 @@ import { CredentialError } from '../config.js'
export type OutputFormat = 'json' | 'table'
/**
- * Prints an API result. JSON (pretty, stdout) is the default so output pipes
- * cleanly into `jq`; `--format table` renders collections for humans.
+ * Prints an API result. JSON is the default; `--format table` renders
+ * collections for humans.
+ *
+ * JSON adapts to the destination, like `gh`/`stripe`: a terminal gets
+ * indented, syntax-colored output; a pipe or file gets compact, uncolored
+ * JSON so it stays fast and `jq`-clean (color codes would corrupt it).
*/
export function printResult(result: unknown, format: OutputFormat = 'json'): void {
if (result === undefined || result === null) return
@@ -23,7 +27,30 @@ export function printResult(result: unknown, format: OutputFormat = 'json'): voi
return
}
- process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
+ if (process.stdout.isTTY) {
+ process.stdout.write(`${colorizeJson(JSON.stringify(result, null, 2))}\n`)
+ } else {
+ process.stdout.write(`${JSON.stringify(result)}\n`)
+ }
+}
+
+// Token regex for already-formatted JSON: strings (object keys and values),
+// literals, and numbers. Keys are strings immediately followed by a colon.
+const JSON_TOKEN =
+ /("(?:\\.|[^"\\])*"(\s*:)?)|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g
+
+/** Syntax-highlights pretty-printed JSON for the terminal (TTY only). Exported for tests. */
+export function colorizeJson(json: string): string {
+ return json.replace(JSON_TOKEN, (match, str, colon, literal, num) => {
+ if (str !== undefined) {
+ // A trailing colon marks an object key; color the key but leave the
+ // colon uncolored.
+ return colon ? pc.cyan(str.slice(0, -colon.length)) + colon : pc.green(str)
+ }
+ if (literal !== undefined) return pc.yellow(literal)
+ if (num !== undefined) return pc.yellow(num)
+ return match
+ })
}
function collectionRows(result: unknown): Record<string, unknown>[] | null {
diff --git a/packages/cli/src/api/ping.ts b/packages/cli/src/api/ping.ts
index b9995a2f48..1ecc1e2db3 100644
--- a/packages/cli/src/api/ping.ts
+++ b/packages/cli/src/api/ping.ts
@@ -1,4 +1,5 @@
import { createAdminClient, SpreeError } from '@spree/admin-sdk'
+import pc from 'picocolors'
export type PingStatus = 'connected' | 'forbidden' | 'unauthorized' | 'unreachable'
@@ -38,3 +39,14 @@ export async function pingCredentials(baseUrl: string, apiKey: string): Promise<
return { status: 'unreachable', message }
}
}
+
+/** Human-readable, colorized one-liner for a ping result — shared by `spree api status` and `spree auth status`. */
+export function formatPingStatus(ping: PingResult): string {
+ return {
+ connected: pc.green(`connected${ping.storeName ? ` (${ping.storeName})` : ''}`),
+ forbidden:
+ pc.green('connected') + pc.dim(' (key valid; lacks read_settings for store details)'),
+ unauthorized: pc.red('key rejected (401)'),
+ unreachable: pc.red(`unreachable — ${ping.message}`),
+ }[ping.status]
+}
diff --git a/packages/cli/src/api/spec.ts b/packages/cli/src/api/spec.ts
index 3ca4273280..69d4af3744 100644
--- a/packages/cli/src/api/spec.ts
+++ b/packages/cli/src/api/spec.ts
@@ -4,7 +4,12 @@
* scripts/bundle-spec.mjs). Powers `spree api endpoints` / `spree api schema`.
*/
+// Bundled at build time by tsup (the package ships a single inlined file, so
+// the snapshot becomes a module literal — there is no separate JSON file to
+// read at runtime). `spree api get`/`post`/… reference loadBundledSpec() only
+// indirectly, and a JS object literal costs nothing until used.
import adminSpecJson from '../generated/admin-spec.json' with { type: 'json' }
+import { normalizePath } from './params.js'
export interface OpenApiOperation {
summary?: string
@@ -34,10 +39,31 @@ export function loadBundledSpec(): AdminSpec {
return adminSpecJson as unknown as AdminSpec
}
+/**
+ * Top-level resource paths (`/products`, `/orders`, …) from the bundled spec —
+ * the completion candidates for `spree api <verb> <TAB>`. Deduped, sorted, and
+ * limited to first-segment paths (nested paths carry `{id}` placeholders a
+ * shell can't usefully complete).
+ */
+export function resourcePaths(spec: AdminSpec): string[] {
+ const segments = new Set<string>()
+ for (const specPath of Object.keys(spec.paths)) {
+ const shortPath = specPath.replace('/api/v3/admin', '') || '/'
+ const segment = shortPath.split('/')[1]
+ if (segment && !segment.startsWith('{')) segments.add(`/${segment}`)
+ }
+ return [...segments].sort()
+}
+
/**
* Extracts the `**Required scope:** ...` line rswag writes into operation
* descriptions. Free-form notes (e.g. exports — gated by the exported
* resource) come through verbatim.
+ *
+ * The same annotation is parsed at build time by
+ * `scripts/generate-endpoints-doc.mjs` (a separate `.mjs` runtime, so the
+ * logic can't be shared as an import); keep the two in sync if the rswag
+ * `admin_scope` format changes.
*/
export function requiredScope(operation: OpenApiOperation): string {
const match = operation.description?.match(
@@ -103,10 +129,7 @@ export function getSchema(spec: AdminSpec, target: string): SchemaResult[] {
const method = parts.length > 1 ? parts[0].toLowerCase() : undefined
const rawPath = parts.length > 1 ? parts[1] : parts[0]
- let lookupPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`
- if (lookupPath.startsWith('/api/v3/admin')) {
- lookupPath = lookupPath.slice('/api/v3/admin'.length) || '/'
- }
+ const lookupPath = normalizePath(rawPath)
// Router precedence: an exact literal path wins over a `{id}` template, so
// `/payment_methods/types` resolves to itself and not to `/payment_methods/{id}`.
diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts
index 238b783b30..1ba88cc6a7 100644
--- a/packages/cli/src/commands/api.ts
+++ b/packages/cli/src/commands/api.ts
@@ -5,7 +5,7 @@ import pc from 'picocolors'
import { NO_BODY, readBody } from '../api/body.js'
import { handleApiError, type OutputFormat, printResult } from '../api/output.js'
import { buildParams, normalizePath } from '../api/params.js'
-import { pingCredentials } from '../api/ping.js'
+import { formatPingStatus, pingCredentials } from '../api/ping.js'
import { getSchema, listEndpoints, loadBundledSpec } from '../api/spec.js'
import { type ResolvedCredentials, resolveCredentials } from '../config.js'
@@ -71,6 +71,24 @@ export function registerApiCommand(program: Command): void {
.command('api')
.description('Call the Admin API directly (gh api-style generic verbs)')
+ // Discovery pointers — shown on `spree api --help` and after an unknown
+ // subcommand (the global showHelpAfterError prints help on usage errors).
+ api.addHelpText(
+ 'after',
+ [
+ '',
+ 'Examples:',
+ ' spree api get /products -q status_eq=active --limit 10',
+ ' spree api post /products -d \'{"name":"Classic Tee"}\'',
+ ' spree api get /orders/ord_x8k2J9aQ --expand items,payments',
+ '',
+ 'Discover the surface (offline, no server needed):',
+ ' spree api endpoints --search <term> # find endpoints + required scopes',
+ ' spree api schema "POST /orders" # request/response schema for one operation',
+ ' spree completion zsh # tab-completion for paths, filters, scopes',
+ ].join('\n'),
+ )
+
// --- Read verb -----------------------------------------------------------
withSharedFlags(
@@ -193,14 +211,7 @@ export function registerApiCommand(program: Command): void {
)
const ping = await pingCredentials(credentials.baseUrl, credentials.apiKey)
const spec = loadBundledSpec()
-
- const serverLine = {
- connected: pc.green(`connected${ping.storeName ? ` (${ping.storeName})` : ''}`),
- forbidden:
- pc.green('connected') + pc.dim(' (key valid; lacks read_settings for store details)'),
- unauthorized: pc.red('key rejected (401)'),
- unreachable: pc.red(`unreachable — ${ping.message}`),
- }[ping.status]
+ const serverLine = formatPingStatus(ping)
const lines = [
`${pc.bold('Base URL:')} ${credentials.baseUrl}`,
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
index c1ebadf76d..d861193236 100644
--- a/packages/cli/src/commands/auth.ts
+++ b/packages/cli/src/commands/auth.ts
@@ -3,7 +3,7 @@ import type { Command } from 'commander'
import { printTable } from 'console-table-printer'
import pc from 'picocolors'
import { handleApiError } from '../api/output.js'
-import { pingCredentials } from '../api/ping.js'
+import { formatPingStatus, pingCredentials } from '../api/ping.js'
import {
configPath,
projectCredentialsPath,
@@ -126,13 +126,7 @@ export function registerAuthCommand(program: Command): void {
const ping = await pingCredentials(credentials.baseUrl, credentials.apiKey)
s.stop('')
- const statusLine = {
- connected: pc.green(`connected${ping.storeName ? ` (${ping.storeName})` : ''}`),
- forbidden:
- pc.green('connected') + pc.dim(' (key valid; lacks read_settings for store details)'),
- unauthorized: pc.red('key rejected (401)'),
- unreachable: pc.red(`unreachable — ${ping.message}`),
- }[ping.status]
+ const statusLine = formatPingStatus(ping)
p.note(
[
diff --git a/packages/cli/src/commands/completion.ts b/packages/cli/src/commands/completion.ts
new file mode 100644
index 0000000000..e38c44567f
--- /dev/null
+++ b/packages/cli/src/commands/completion.ts
@@ -0,0 +1,175 @@
+import type { Command } from 'commander'
+import { loadBundledSpec, resourcePaths } from '../api/spec.js'
+
+/**
+ * Shell completion, following the `gh`/`kubectl` architecture: `spree
+ * completion <shell>` prints a static script that, on Tab, calls a hidden
+ * `spree __complete <words...>` subcommand. The resolver reads the bundled
+ * OpenAPI snapshot (offline — no server, no network), so it can suggest live
+ * resource paths, verbs, Ransack predicates, and scopes.
+ */
+
+const SHELLS = ['bash', 'zsh', 'fish'] as const
+type Shell = (typeof SHELLS)[number]
+
+// Ransack predicate suffixes for `-q <attr>_<predicate>=…`. A fixed, well-known
+// set (the matchers are not enumerated per-attribute in the spec), so we offer
+// the common ones rather than every Ransack matcher.
+const RANSACK_PREDICATES = [
+ 'eq',
+ 'not_eq',
+ 'cont',
+ 'not_cont',
+ 'start',
+ 'end',
+ 'in',
+ 'not_in',
+ 'gt',
+ 'gteq',
+ 'lt',
+ 'lteq',
+ 'null',
+ 'not_null',
+ 'present',
+ 'blank',
+]
+
+const API_VERBS = ['get', 'post', 'patch', 'delete', 'endpoints', 'schema', 'status']
+const SCOPES = [
+ 'read_all',
+ 'write_all',
+ 'read_orders',
+ 'write_orders',
+ 'read_products',
+ 'write_products',
+ 'read_promotions',
+ 'write_promotions',
+ 'read_customers',
+ 'write_customers',
+ 'read_payments',
+ 'write_payments',
+ 'read_fulfillments',
+ 'write_fulfillments',
+ 'read_refunds',
+ 'write_refunds',
+ 'read_gift_cards',
+ 'write_gift_cards',
+ 'read_store_credits',
+ 'write_store_credits',
+ 'read_stock',
+ 'write_stock',
+ 'read_categories',
+ 'write_categories',
+ 'read_settings',
+ 'write_settings',
+ 'read_webhooks',
+ 'write_webhooks',
+ 'read_api_keys',
+ 'write_api_keys',
+ 'read_dashboard',
+]
+
+/**
+ * Resolves completion candidates for a partial command line. `words` is the
+ * argv after `spree` (the last entry is the word being typed, possibly empty).
+ */
+export function completionCandidates(words: string[]): string[] {
+ const [top, sub, ...rest] = words
+ const current = words[words.length - 1] ?? ''
+
+ // `spree <TAB>` — top-level command names (plus the api verbs surfaced flat).
+ if (words.length <= 1) {
+ return filterByPrefix(['api', 'auth', ...TOP_LEVEL_HINT], current)
+ }
+
+ if (top === 'api') {
+ // `spree api <TAB>` — verbs.
+ if (words.length === 2) return filterByPrefix(API_VERBS, current)
+
+ // `spree api get /pro<TAB>` — resource paths (only for path-taking verbs).
+ if (['get', 'post', 'patch', 'delete', 'schema'].includes(sub) && rest.length <= 1) {
+ return filterByPrefix(resourcePaths(loadBundledSpec()), current)
+ }
+
+ // `spree api get /products -q <attr>_<TAB>` — append Ransack predicates to
+ // a typed attribute stem.
+ if (sub === 'get' && current.includes('_') && !current.includes('=')) {
+ const stem = current.slice(0, current.lastIndexOf('_') + 1)
+ return RANSACK_PREDICATES.map((p) => `${stem}${p}=`)
+ }
+ }
+
+ // `spree api-key create --scopes <TAB>` / `spree auth ...` scope values.
+ if (current && SCOPES.some((s) => s.startsWith(current))) {
+ return filterByPrefix(SCOPES, current)
+ }
+
+ return []
+}
+
+// A few high-traffic top-level commands so `spree <TAB>` isn't empty; the full
+// list comes from Commander's own help. Kept short on purpose.
+const TOP_LEVEL_HINT = ['api-key', 'dev', 'console', 'migrate']
+
+function filterByPrefix(candidates: string[], prefix: string): string[] {
+ if (!prefix) return candidates
+ return candidates.filter((c) => c.startsWith(prefix))
+}
+
+function completionScript(shell: Shell): string {
+ if (shell === 'fish') {
+ return `# spree fish completion — eval "$(spree completion fish)"
+function __spree_complete
+ set -l tokens (commandline -opc) (commandline -ct)
+ spree __complete $tokens[2..-1]
+end
+complete -c spree -f -a '(__spree_complete)'
+`
+ }
+
+ if (shell === 'zsh') {
+ return `# spree zsh completion — eval "$(spree completion zsh)"
+_spree() {
+ local -a completions
+ completions=(\${(f)"$(spree __complete \${words[2,$CURRENT]})"})
+ compadd -- $completions
+}
+compdef _spree spree
+`
+ }
+
+ // bash
+ return `# spree bash completion — eval "$(spree completion bash)"
+_spree() {
+ local words=("\${COMP_WORDS[@]:1:$COMP_CWORD}")
+ COMPREPLY=( $(spree __complete "\${words[@]}") )
+}
+complete -F _spree spree
+`
+}
+
+export function registerCompletionCommand(program: Command): void {
+ program
+ .command('completion <shell>')
+ .description('Output a shell completion script (bash, zsh, or fish)')
+ .action((shell: string) => {
+ if (!SHELLS.includes(shell as Shell)) {
+ process.stderr.write(`Unsupported shell "${shell}". Choose one of: ${SHELLS.join(', ')}.\n`)
+ process.exitCode = 2
+ return
+ }
+ process.stdout.write(completionScript(shell as Shell))
+ })
+
+ // Hidden resolver the generated scripts call on Tab. Prints one candidate
+ // per line; offline (reads the bundled spec only).
+ program
+ .command('__complete', { hidden: true })
+ .allowUnknownOption()
+ .argument('[words...]')
+ .action((words: string[]) => {
+ for (const candidate of completionCandidates(words ?? [])) {
+ process.stdout.write(`${candidate}\n`)
+ }
+ })
+}
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 3eceba548d..45022900f4 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -2,9 +2,13 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import pc from 'picocolors'
+import { DEFAULT_SPREE_PORT } from './constants.js'
import { detectProject } from './context.js'
import { rakeTask } from './docker.js'
+/** Host a flag/env key defaults to when none is given — the local dev server. */
+const LOCAL_DEV_URL = `http://localhost:${DEFAULT_SPREE_PORT}`
+
/**
* Credential resolution for `spree api` / `spree auth`.
*
@@ -15,8 +19,9 @@ import { rakeTask } from './docker.js'
*
* 1. flags --base-url / --api-key (and --profile, which selects a
* saved profile explicitly and then outranks env)
- * 2. env SPREE_API_KEY (+ SPREE_BASE_URL); SPREE_BASE_URL alone
- * never pairs with a lower-layer key
+ * 2. env SPREE_API_KEY (+ SPREE_BASE_URL, defaulting to the
+ * local dev server); SPREE_BASE_URL alone never pairs
+ * with a lower-layer key
* 3. project .spree/credentials.json next to docker-compose.yml,
* auto-minted (read_all) on first use via the dev stack
* 4. profile ~/.config/spree/config.json, default profile
@@ -303,15 +308,27 @@ export async function resolveCredentials(
// An explicit --base-url always wins (re-point a key at staging, etc.); a
// flag pairing is the user's deliberate cross-layer mix.
- const baseUrl = flagBaseUrl ?? resolved?.baseUrl
+ let baseUrl = flagBaseUrl ?? resolved?.baseUrl
const apiKey = resolved?.apiKey
+ // Local-dev convenience: a key supplied via flag or env with no host at all
+ // defaults to the local dev server, so `SPREE_API_KEY=sk_… spree api get …`
+ // just works. Profile/project sources always carry their own host, so this
+ // never silently re-points a saved remote key.
+ if (apiKey && !baseUrl && (resolved?.source === 'flags' || resolved?.source === 'env')) {
+ baseUrl = LOCAL_DEV_URL
+ }
+
if (!baseUrl || !apiKey) {
throw new CredentialError(
[
'No Admin API credentials found. Provide them via one of (host and key resolve together per source):',
- ' - flags: --base-url <url> --api-key <sk_...>',
- ' - env: SPREE_BASE_URL + SPREE_API_KEY',
+ ' - flags: --api-key <sk_...> (host defaults to ' +
+ LOCAL_DEV_URL +
+ '; pass --base-url for a remote store)',
+ ' - env: SPREE_API_KEY (host defaults to ' +
+ LOCAL_DEV_URL +
+ '; set SPREE_BASE_URL for a remote store)',
' - project: run inside a Spree project with the dev stack up (auto-mints a read-only key)',
' - profile: spree auth login --profile <name>',
].join('\n'),
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index c83ada9f81..21c91638b2 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -5,6 +5,7 @@ import { registerApiKeyCommand } from './commands/api-key.js'
import { registerAuthCommand } from './commands/auth.js'
import { registerBuildCommand } from './commands/build.js'
import { registerBundleCommand } from './commands/bundle.js'
+import { registerCompletionCommand } from './commands/completion.js'
import { registerConsoleCommand } from './commands/console.js'
import { registerDbCommand } from './commands/db.js'
import { registerDevCommand } from './commands/dev.js'
@@ -35,6 +36,10 @@ const program = new Command()
// so flags like `ls -la` or `bin/rails routes -g foo` reach the inner command
// instead of being parsed as options of the spree subcommand.
.enablePositionalOptions()
+ // "did you mean …" on an unknown command/option (on by default; explicit so
+ // it isn't lost in a future refactor) + a nudge toward help on error.
+ .showSuggestionAfterError(true)
+ .showHelpAfterError('(run `spree --help` for usage)')
// Must be set BEFORE registering subcommands — commander copies the exit
// callback to each subcommand at `.command()` creation time, so a later call
// would leave subcommands (e.g. `api endpoints --format`) on the default
@@ -86,6 +91,7 @@ registerSampleDataCommand(program)
// Admin API access (works against any Spree 5.5+ instance, not just local projects)
registerApiCommand(program)
registerAuthCommand(program)
+registerCompletionCommand(program)
async function main() {
try {
diff --git a/packages/cli/tests/api-output.test.ts b/packages/cli/tests/api-output.test.ts
new file mode 100644
index 0000000000..3e7331a4e8
--- /dev/null
+++ b/packages/cli/tests/api-output.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { colorizeJson, printResult } from '../src/api/output'
+
+// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ANSI SGR escapes
+const ANSI = /\x1b\[[0-9;]*m/g
+const stripAnsi = (s: string) => s.replace(ANSI, '')
+
+describe('printResult JSON output', () => {
+ let stdout: string
+ let spy: ReturnType<typeof vi.spyOn>
+ const originalIsTTY = process.stdout.isTTY
+
+ beforeEach(() => {
+ stdout = ''
+ spy = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
+ stdout += String(chunk)
+ return true
+ })
+ })
+
+ afterEach(() => {
+ spy.mockRestore()
+ Object.defineProperty(process.stdout, 'isTTY', { value: originalIsTTY, configurable: true })
+ })
+
+ function setTTY(value: boolean) {
+ Object.defineProperty(process.stdout, 'isTTY', { value, configurable: true })
+ }
+
+ it('emits compact, uncolored JSON when piped (non-TTY)', () => {
+ setTTY(false)
+ printResult({ name: 'Tee', price: 10 })
+ // Compact (no indentation) and no ANSI escapes that would break `jq`.
+ expect(stdout).toBe('{"name":"Tee","price":10}\n')
+ expect(stdout).not.toMatch(ANSI)
+ })
+
+ it('emits indented, colored JSON in a terminal (TTY)', () => {
+ setTTY(true)
+ printResult({ name: 'Tee' })
+ expect(stripAnsi(stdout)).toBe('{\n "name": "Tee"\n}\n')
+ })
+
+ it('round-trips back to the same value regardless of destination', () => {
+ const value = { data: [{ id: 'prod_1', qty: 3, active: true, tag: null }], meta: { count: 1 } }
+
+ setTTY(false)
+ printResult(value)
+ expect(JSON.parse(stdout)).toEqual(value)
+
+ stdout = ''
+ setTTY(true)
+ printResult(value)
+ expect(JSON.parse(stripAnsi(stdout))).toEqual(value)
+ })
+
+ it('prints nothing for null/undefined', () => {
+ setTTY(true)
+ printResult(null)
+ printResult(undefined)
+ expect(stdout).toBe('')
+ })
+})
+
+describe('colorizeJson', () => {
+ it('does not mistake a colon inside a string value for a key', () => {
+ const colored = colorizeJson(JSON.stringify({ note: 'a: b' }, null, 2))
+ expect(JSON.parse(stripAnsi(colored))).toEqual({ note: 'a: b' })
+ })
+
+ it('leaves structure untouched after stripping color', () => {
+ const input = JSON.stringify({ n: 1, arr: [true, null] }, null, 2)
+ expect(stripAnsi(colorizeJson(input))).toBe(input)
+ })
+})
diff --git a/packages/cli/tests/completion.test.ts b/packages/cli/tests/completion.test.ts
new file mode 100644
index 0000000000..24a875b34e
--- /dev/null
+++ b/packages/cli/tests/completion.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest'
+import { completionCandidates } from '../src/commands/completion'
+
+describe('completionCandidates', () => {
+ it('suggests api verbs after `api`', () => {
+ const out = completionCandidates(['api', ''])
+ expect(out).toContain('get')
+ expect(out).toContain('endpoints')
+ expect(out).toContain('schema')
+ })
+
+ it('suggests resource paths from the bundled spec after a path-taking verb', () => {
+ const out = completionCandidates(['api', 'get', ''])
+ expect(out).toContain('/products')
+ expect(out).toContain('/orders')
+ // Nested/placeholder paths are excluded.
+ expect(out.every((p) => !p.includes('{'))).toBe(true)
+ })
+
+ it('filters resource paths by the typed prefix', () => {
+ const out = completionCandidates(['api', 'get', '/prod'])
+ expect(out).toContain('/products')
+ expect(out.every((p) => p.startsWith('/prod'))).toBe(true)
+ })
+
+ it('appends Ransack predicates to a -q attribute stem', () => {
+ const out = completionCandidates(['api', 'get', '/products', '-q', 'name_'])
+ expect(out).toContain('name_eq=')
+ expect(out).toContain('name_cont=')
+ expect(out.every((c) => c.startsWith('name_') && c.endsWith('='))).toBe(true)
+ })
+
+ it('suggests scope names by prefix', () => {
+ const out = completionCandidates(['api-key', 'create', '--scopes', 'write_pr'])
+ expect(out).toContain('write_products')
+ expect(out).toContain('write_promotions')
+ })
+
+ it('returns nothing for an unknown context', () => {
+ expect(completionCandidates(['api', 'status', 'xyz'])).toEqual([])
+ })
+})
diff --git a/packages/cli/tests/config.test.ts b/packages/cli/tests/config.test.ts
index 7a18e0107b..0d4c262721 100644
--- a/packages/cli/tests/config.test.ts
+++ b/packages/cli/tests/config.test.ts
@@ -55,6 +55,33 @@ describe('resolveCredentials', () => {
expect(creds.tokenPrefix).toBe('sk_env_token')
})
+ it('defaults the host to the local dev server when only SPREE_API_KEY is set', async () => {
+ isolateConfigHome()
+ process.env.SPREE_API_KEY = 'sk_env_token_123'
+ // SPREE_BASE_URL intentionally unset.
+
+ const creds = await resolveCredentials({}, { cwd: makeTempDir(), allowMint: false })
+
+ expect(creds).toMatchObject({
+ baseUrl: 'http://localhost:3000',
+ apiKey: 'sk_env_token_123',
+ source: 'env',
+ })
+ })
+
+ it('defaults the host to local dev for a bare --api-key flag', async () => {
+ isolateConfigHome()
+ const creds = await resolveCredentials(
+ { apiKey: 'sk_flag_only' },
+ { cwd: makeTempDir(), allowMint: false },
+ )
+ expect(creds).toMatchObject({
+ baseUrl: 'http://localhost:3000',
+ apiKey: 'sk_flag_only',
+ source: 'flags',
+ })
+ })
+
it('lets flags override env', async () => {
isolateConfigHome()
process.env.SPREE_BASE_URL = 'https://env.example.com'