> ## Documentation Index
> Fetch the complete documentation index at: https://docs.salesive.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Development

> Salesive development tooling, CLI, and Vite plugin

## Overview

`salesive-dev-tools` is a powerful CLI tool and Vite plugin for building and managing Salesive templates.

* **CLI commands** for project initialization, authentication, validation, and deployment to Salesive Themes API.
* **Vite plugin** that injects configuration from `salesive.config.json` as CSS variables and a global object.
* **React hooks** for accessing and dynamically updating configuration at runtime.
* **Template deployment** with the `salesive cook` command for one-command packaging and upload.

Pair with [`salesive-api-axios`](https://www.npmjs.com/package/salesive-api-axios) for complete Store API integration.

## Install the tooling

Add the package inside your project workspace:

```bash theme={null}
npm install salesive-dev-tools
# alternative package managers
yarn add salesive-dev-tools
pnpm add salesive-dev-tools
bun add salesive-dev-tools
```

For CLI access everywhere, install it globally:

```bash theme={null}
npm install -g salesive-dev-tools
# or
yarn global add salesive-dev-tools
# or
pnpm add -g salesive-dev-tools
# or
bun add -g salesive-dev-tools
```

## Configure Vite

Register the plugin alongside your existing React configuration:

```js theme={null}
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { salesiveConfigPlugin } from "salesive-dev-tools";

export default defineConfig({
  plugins: [react(), salesiveConfigPlugin()]
});
```

## Define your Salesive config

Create a `salesive.config.json` file in the project root to describe brand assets, CSS tokens, and metadata the plugin should inject.

```json theme={null}
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "My Project Description",
  "author": "Your Name",
  "license": "MIT",
  "shopTypes": ["ecommerce"],
  "routeOverrides": [],
  "variables": {
    "color-brand-primary": "#0d65d9",
    "color-brand-primary-x": "#e6f6ff",
    "font-brand-space": "Space Grotesk",
    "app-name": "My App",
    "app-description": "My awesome application",
    "app-logo": "https://example.com/logo.png",
    "app-favicon": "https://example.com/favicon.ico"
  }
}
```

<Note>
  **Configuration format:** Variables use a flat structure with kebab-case keys. You need to manually inject CSS variables in your stylesheets as needed.
</Note>

### Declare supported store types

The optional **`shopTypes`** array tells Salesive which [store types](/index#store-types) your theme is built for. A merchant can only install a theme on a store whose type is listed here.

```json theme={null}
"shopTypes": ["ecommerce"]
```

| Value          | Catalog the theme must render                                       |
| -------------- | ------------------------------------------------------------------- |
| `"ecommerce"`  | **Products** (with variants) — `catalogType: "product"`             |
| `"restaurant"` | **Foods/menu** (with add-ons) — `catalogType: "food"`               |
| `"business"`   | **Services** (with add-ons, no shipping) — `catalogType: "service"` |

<Note>
  The catalog endpoints (`/products`, `/products/{id}`, `/cart`, `/orders`) return a `catalogType` and per-item `itemType` that match the active store type, so a multi-type theme can branch on those fields. If `shopTypes` is omitted it defaults to `["ecommerce"]`. List every type your theme supports, e.g. `["ecommerce", "restaurant", "business"]`.
</Note>

### Override an automatic route

By default, [automatic routes](/routing#automatic-routes) such as `/cart`, `/checkout`, and `/blog` render with Salesive's built-in theme. The optional **`routeOverrides`** array lets your theme take over specific automatic routes and render them itself:

```json theme={null}
"routeOverrides": ["/blog", "/about-us"]
```

Each value must be one of the [automatic routes](/routing#automatic-routes), otherwise the theme upload is rejected. Declaring a base path overrides its whole subtree (`/blog` also covers `/blog/my-post`), and you become responsible for implementing that route in your app with React Router. Leave the array empty (or omit it) to keep every automatic route on the platform default. See [Overriding an automatic route](/routing#overriding-an-automatic-route) for the full behavior.

## Consume configuration in React

Use `useSalesiveConfig()` to read values anywhere in your component tree:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function StoreHeading() {
  // Get specific variable values
  const storeName = useSalesiveConfig("app-name");
  const brandColor = useSalesiveConfig("color-brand-primary");

  // Or get all variables
  const allVariables = useSalesiveConfig();

  return (
    <h1 style={{ color: brandColor }}>
      {storeName}
    </h1>
  );
}
```

## Apply updates at runtime

The toolkit ships with stateful helpers for mutating configuration without reloading the page.

```jsx theme={null}
import { updateSalesiveConfig, setSalesiveConfig } from "salesive-dev-tools";

// Update a single variable
setSalesiveConfig("app-name", "Salesive Demo Store");

// Update multiple variables (merges with existing)
updateSalesiveConfig({
  variables: {
    "color-brand-primary": "#ff5a1f",
    "app-description": "Updated on the fly"
  }
});

// Use a function to update based on previous state
updateSalesiveConfig((prevConfig) => ({
  ...prevConfig,
  variables: {
    ...prevConfig.variables,
    "app-name": `${prevConfig.variables["app-name"]} - Updated`
  }
}));

// Replace entire config (no merging)
updateSalesiveConfig(newConfig, { merge: false });
```

## Router-aware branding

Pair the helpers with React Router to switch themes per route.

```jsx theme={null}
import { useEffect } from "react";
import { Outlet, useLocation } from "react-router-dom";
import { setSalesiveConfig } from "salesive-dev-tools";

function ThemeSync() {
  const location = useLocation();

  useEffect(() => {
    const path = location.pathname;
    const color = path.startsWith("/admin")
      ? "#2d3748"
      : path.startsWith("/marketing")
      ? "#e53e3e"
      : "#0d65d9";

    setSalesiveConfig("color-brand-primary", color);
  }, [location.pathname]);

  return <Outlet />;
}
```

## Helper access outside React

When you need configuration data in non-component code, use `getSalesiveConfig()`.

```js theme={null}
import { getSalesiveConfig } from "salesive-dev-tools";

// Get all variables
const allVariables = getSalesiveConfig();

// Get a specific variable
const appName = getSalesiveConfig("app-name");
const favicon = getSalesiveConfig("app-favicon");
```

## Injected assets

The plugin automatically handles:

* **Document title** – sourced from `variables.app-name`.
* **Meta description** – written from `variables.app-description`.
* **Favicon** – linked using `variables.app-favicon`.
* **Global runtime object** – exposed as `window.SALESIVE_CONFIG` for direct inspection.

<Tip>
  Development mode only: The plugin runs during `vite dev` and is automatically disabled for production builds.
</Tip>

## Using CSS variables

To use configuration values as CSS custom properties, manually inject them in your stylesheets:

```css theme={null}
:root {
  --color-brand-primary: #0d65d9;
  --color-brand-primary-x: #e6f6ff;
  --font-brand-space: "Space Grotesk";
}
```

Or apply them dynamically using the React hook:

```jsx theme={null}
import { useSalesiveConfig } from "salesive-dev-tools";

function ThemedButton() {
  const brandColor = useSalesiveConfig("color-brand-primary");
  
  return (
    <button style={{ backgroundColor: brandColor }}>
      Click me
    </button>
  );
}
```

## Command-line workflows

Install globally to unlock the `salesive` CLI for daily workflows.

### Authenticate with Themes API

```bash theme={null}
salesive auth set-token     # Set your API token
salesive auth status         # Check authentication status
salesive auth verify         # Verify token with server
salesive auth clear-token    # Clear stored token
```

<Warning>
  **The API key must have the "Read & Write Themes" permission (`WRITE_THEMES`).**
  This is the permission `salesive cook` uses to publish and update your theme —
  without it, deploys are rejected with a permissions error. When you generate
  the API key in your Salesive dashboard, enable **Read & Write Themes** before
  setting the token with `salesive auth set-token`.
</Warning>

### Create projects

```bash theme={null}
salesive init                                      # Interactive prompts
salesive init --name my-project --template react-vite
salesive init --name existing-dir --force          # Overwrite existing
```

### Develop locally

```bash theme={null}
salesive dev                            # Start dev server
salesive dev --path ./my-project        # Custom project path
salesive dev --config ./my-config.json  # Custom config file
```

### Validate configuration

```bash theme={null}
salesive validate                       # Validate current project
salesive validate --path ./my-project   # Validate specific project
salesive validate --verbose             # Show detailed output
```

<Note>
  Validation checks: required fields (name, version, description), name format (lowercase, hyphens only), semantic versioning, and variables structure.
</Note>

### Deploy templates

The `cook` command packages and deploys your template to the Salesive Themes API.

<Note>
  `cook` uploads through the Themes API, so the authenticated API key must have
  the **Read & Write Themes** (`WRITE_THEMES`) permission. See
  [Authenticate with Themes API](#authenticate-with-themes-api).
</Note>

```bash theme={null}
salesive cook                           # Deploy from current directory
salesive cook --path ./my-template      # Deploy from specific path
salesive cook --config ./custom.json    # Use custom config
salesive cook --keep-temp               # Keep temp files for debugging
salesive cook --verbose                 # Show detailed output
```

**What gets deployed:**

* All template files (HTML, CSS, JS, images, etc.)
* `salesive.config.json` (required)
* `salesive.form.json` (optional)

**Automatic exclusions:**

* `node_modules/`, `.git/`, `.salesive-temp/`, `*.log`, `.DS_Store`

## CLI reference tables

### Cook (Deploy) options

| Option                | Description                                             |
| --------------------- | ------------------------------------------------------- |
| `-p, --path <path>`   | Path to template directory (default: current directory) |
| `-c, --config <path>` | Path to salesive.config.json file                       |
| `-k, --keep-temp`     | Keep temporary files after deployment                   |
| `-v, --verbose`       | Show verbose output and detailed errors                 |

### Auth options

| Option          | Description                                      |
| --------------- | ------------------------------------------------ |
| `-v, --verbose` | Show detailed error information (verify command) |

### Init options

| Option                      | Description                                         |
| --------------------------- | --------------------------------------------------- |
| `-n, --name <name>`         | Project directory name                              |
| `-t, --template <template>` | Template to scaffold (`react-vite`, `react-router`) |
| `-f, --force`               | Overwrite an existing directory                     |
| `-v, --verbose`             | Show additional progress output                     |

### Validate options

| Option                | Description                       |
| --------------------- | --------------------------------- |
| `-p, --path <path>`   | Path to project directory         |
| `-c, --config <path>` | Path to salesive.config.json file |
| `-v, --verbose`       | Show verbose output               |

## Integrate with Store API

Combine `salesive-dev-tools` with [`salesive-api-axios`](https://www.npmjs.com/package/salesive-api-axios) for complete Store API integration:

```jsx theme={null}
import { useEffect, useState } from "react";
import { products, cart } from "salesive-api-axios";
import { useSalesiveConfig } from "salesive-dev-tools";

function ProductList() {
  const [items, setItems] = useState([]);
  const appName = useSalesiveConfig("app-name");

  useEffect(() => {
    // Fetch products from Salesive Store API
    const loadProducts = async () => {
      const { data } = await products.list({ limit: 10 });
      setItems(data.products);
    };
    loadProducts();
  }, []);

  const addToCart = async (productId) => {
    await cart.addItem({ productId, quantity: 1 });
  };

  return (
    <div>
      <h1>{appName} - Products</h1>
      {items.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <button onClick={() => addToCart(product.id)}>Add to Cart</button>
        </div>
      ))}
    </div>
  );
}
```

## Auto-update notifications

The CLI automatically checks for updates once every 24 hours and notifies you when a new version is available:

```
┌──────────────────────────────────────────────────────────┐
│  Update available!  0.0.1 → 1.0.0                        │
│  Run npm install -g salesive-dev-tools to update         │
└──────────────────────────────────────────────────────────┘
```

## License

Released under the MIT license.
