
# TypeScript API

Use Sovrium as a library in your TypeScript project. Import `start`, `build`, and the `AppConfig` type for full programmatic control with typed configuration.

```typescript
import { start, build, generateAppJsonSchema, validateConfig } from 'sovrium'
import type { AppConfig, SimpleServer, ValidateConfigResult } from 'sovrium'

// All config types are available:
// PageConfig, TableConfig, ThemeConfig, AuthConfig,
// ComponentConfig, LanguageConfig, AnalyticsConfig, ...
```

## Why TypeScript?

Using Sovrium programmatically gives you advantages beyond the CLI.

### Type safety

The `AppConfig` type provides autocomplete for every property and field type. Catch errors at compile time, not runtime.

### Programmatic control

Generate configuration dynamically, compose schemas, and integrate Sovrium into existing applications.

### IDE integration

Full IntelliSense in VS Code and JetBrains — hover docs, go-to-definition, and type errors.

## `start(app, options?)`

Start a development server from a typed configuration object. Returns a server instance with a `stop()` method.

```typescript
import { start } from 'sovrium'

const server = await start({
  name: 'my-app',
})

console.log(`Server running at ${server.url}`)
```

### `StartOptions`

Optional second argument to configure the server.

| Property    | Description                                                        |
| ----------- | ------------------------------------------------------------------ |
| `port`      | Port number (0–65535). 0 selects an available port. Default: 3000. |
| `hostname`  | Server hostname. Default: `localhost`.                             |
| `publicDir` | Static file directory. Files are served at their relative path.    |

```typescript
import { start } from 'sovrium'

const server = await start(
  {
    name: 'my-app',
    tables: [
      {
        id: 1,
        name: 'tasks',
        fields: [
          { id: 1, name: 'title', type: 'single-line-text', required: true },
          { id: 2, name: 'done', type: 'checkbox' },
        ],
      },
    ],
  },
  {
    port: 8080,
    hostname: '0.0.0.0',
    publicDir: './public',
  }
)
```

## `build(app, options?)`

Generate a static site from a typed configuration object.

### `GenerateStaticOptions`

Optional second argument to control static output.

| Property             | Description                                         |
| -------------------- | --------------------------------------------------- |
| `outputDir`          | Output directory. Default: `./static`.              |
| `baseUrl`            | Base URL for sitemap and canonical links.           |
| `basePath`           | Path prefix for subdirectory deployments.           |
| `deployment`         | Target platform: `github-pages` or `generic`.       |
| `languages`          | Array of language codes for generation.             |
| `defaultLanguage`    | Default language code.                              |
| `generateSitemap`    | Generate `sitemap.xml`. Default: `false`.           |
| `generateRobotsTxt`  | Generate `robots.txt`. Default: `false`.            |
| `hydration`          | Enable client-side hydration. Default: `false`.     |
| `generateManifest`   | Generate `manifest.json` for PWA. Default: `false`. |
| `bundleOptimization` | Splitting strategy: `split` or `none`.              |
| `publicDir`          | Static asset directory to copy into output.         |

```typescript
import { build } from 'sovrium'

await build(
  {
    name: 'my-site',
    pages: [
      {
        name: 'home',
        path: '/',
        sections: [
          { type: 'heading', content: 'Welcome' },
          { type: 'paragraph', content: 'Built with Sovrium.' },
        ],
      },
    ],
  },
  {
    outputDir: './dist',
    baseUrl: 'https://example.com',
    deployment: 'github-pages',
    generateSitemap: true,
    generateRobotsTxt: true,
  }
)
```

## `generateAppJsonSchema()`

Generate the JSON Schema (Draft-07) for the Sovrium app configuration. Returns a plain object suitable for serialization or programmatic use.

```typescript
import { generateAppJsonSchema } from 'sovrium'

const schema = generateAppJsonSchema()
Bun.write('app.schema.json', JSON.stringify(schema, null, 2))
```

## `validateConfig(config)`

Validate an unknown value against the Sovrium AppSchema. Returns a result object indicating whether the config is valid, with parsed config or error details.

```typescript
import { validateConfig } from 'sovrium'

const result = validateConfig({ name: 'My App' })
if (result.valid) {
  console.log(result.config.name)
} else {
  console.error(result.errors)
}
```

## `AppConfig`

The primary type for typing your JSON or YAML configuration objects. Import it from `sovrium` to get full autocomplete and type checking.

| Property       | Description                                                                            |
| -------------- | -------------------------------------------------------------------------------------- |
| `name`         | Application name. Lowercase, npm-compatible (e.g. `my-app`, `@org/app`).               |
| `version?`     | SemVer version string (e.g. `1.0.0`).                                                  |
| `description?` | Single-line application description.                                                   |
| `tables?`      | Array of data table definitions with fields, indexes, and constraints.                 |
| `theme?`       | Design tokens: colors, fonts, spacing, animations, breakpoints, shadows, borderRadius. |
| `pages?`       | Array of page configurations with metadata, sections, and scripts.                     |
| `forms?`       | Standalone form definitions that capture submissions or trigger automations.           |
| `auth?`        | Authentication config: strategies, roles, plugins (admin, organization).               |
| `languages?`   | Multi-language config: supported languages, default language, translations.            |
| `components?`  | Array of reusable component templates with variable substitution.                      |
| `automations?` | Event-driven workflows: triggers plus sequential actions.                              |
| `actions?`     | Reusable action templates referenced from automations via `$ref`.                      |
| `connections?` | External-service credentials (OAuth2, API key, basic, bearer).                         |
| `agents?`      | AI agents acting under an auth role with constrained tools.                            |
| `buckets?`     | Named file-storage containers with per-bucket limits and permissions.                  |
| `env?`         | Declared automation environment variables, referenced as `$env.NAME`.                  |
| `analytics?`   | Built-in privacy-friendly analytics. Set to `true` for defaults or pass an object.     |

```typescript
import type { AppConfig } from 'sovrium'

const config: AppConfig = {
  name: 'my-app',
  version: '1.0.0',
  description: 'My application',
  tables: [/* ... */],
  theme: {/* ... */},
  pages: [/* ... */],
  auth: {/* ... */},
  languages: {/* ... */},
  components: [/* ... */],
  analytics: true,
}
```

:::callout
**Incremental complexity.** Only `name` is required. Add `tables`, `theme`, `pages`, `auth`, `languages`, `components`, and `analytics` as you need them.
:::

## Type Reference

Additional TypeScript types exported from the `sovrium` package. Import them with `import type { ... } from "sovrium"`.

### `SimpleServer`

Returned by `start()`. A lightweight interface to the running server.

| Property | Description                                                                            |
| -------- | -------------------------------------------------------------------------------------- |
| `url`    | Server URL including protocol and port (e.g. `"http://localhost:3000"`).               |
| `stop()` | Gracefully stop the server. Returns a Promise that resolves when shutdown is complete. |

```typescript
import { start } from 'sovrium'
import type { SimpleServer } from 'sovrium'

const server: SimpleServer = await start({ name: 'my-app' })
console.log(server.url) // "http://localhost:3000"
await server.stop() // graceful shutdown
```

### `PageConfig`

Configuration for a single page. Element of `AppConfig['pages']`.

```typescript
const page: PageConfig = {
  name: 'home',
  path: '/',
  sections: [{ type: 'heading', content: 'Welcome' }],
}
```

### `TableConfig`

Configuration for a single data table. Element of `AppConfig['tables']`.

```typescript
const table: TableConfig = {
  id: 1,
  name: 'tasks',
  fields: [{ id: 1, name: 'title', type: 'single-line-text' }],
}
```

### `ComponentConfig`

Reusable component template with variable placeholders. Element of `AppConfig['components']`.

```typescript
const hero: ComponentConfig = {
  name: 'hero',
  type: 'section',
  children: [{ type: 'heading', content: '$title' }],
}
```

### `ThemeConfig`

Design tokens for colors, typography, spacing, shadows, and more.

```typescript
const theme: ThemeConfig = {
  colors: { primary: '#3b82f6' },
  fonts: { sans: 'Inter, sans-serif' },
}
```

### `AuthConfig`

Authentication strategies, roles, and plugin configuration.

```typescript
const auth: AuthConfig = {
  strategies: [{ type: 'emailAndPassword' }],
  roles: [{ name: 'admin' }, { name: 'member' }],
}
```

### `LanguageConfig`

Multi-language support with translations and language detection.

```typescript
const languages: LanguageConfig = {
  supported: ['en', 'fr'],
  default: 'en',
}
```

### `AnalyticsConfig`

Built-in privacy-friendly analytics. Use `true` for defaults or an object for custom settings.

```typescript
// Simple: just enable defaults
const analytics: AnalyticsConfig = true

// Custom settings
const custom: AnalyticsConfig = { retentionDays: 90, excludedPaths: ['/admin'] }
```

### `GenerateStaticResult`

Returned by `build()`. Contains the output directory path and the list of generated files.

| Property    | Description                                                         |
| ----------- | ------------------------------------------------------------------- |
| `outputDir` | Absolute path to the output directory (e.g. `"./static"`).          |
| `files`     | Array of file paths generated during the build (HTML, CSS, assets). |

```typescript
import { build } from 'sovrium'
import type { GenerateStaticResult } from 'sovrium'

const result: GenerateStaticResult = await build({
  name: 'my-site',
  pages: [/* ... */],
})
console.log(result.outputDir) // "./static"
console.log(result.files.length) // number of generated files
```

### `ValidateConfigResult`

Returned by `validateConfig()`. Indicates whether the config is valid and provides parsed config or error details.

| Property | Description                                                          |
| -------- | -------------------------------------------------------------------- |
| `valid`  | Boolean. `true` if the configuration is valid against the AppSchema. |
| `errors` | Array of validation error objects. Empty when `valid` is `true`.     |
| `config` | The parsed `AppConfig` object. Only present when `valid` is `true`.  |

```typescript
import { validateConfig } from 'sovrium'
import type { ValidateConfigResult } from 'sovrium'

const result: ValidateConfigResult = validateConfig({ name: 'my-app' })
console.log(result.valid) // true or false
console.log(result.errors) // validation error array (empty if valid)
console.log(result.config) // parsed AppConfig (if valid)
```

## Watch Mode

In development, use Bun's built-in watch mode to automatically restart your script when files change.

```bash
bun --watch index.ts
```

:::callout
**Reload vs watch.** `bun --watch` restarts the entire process when any imported file changes. For config-only changes, the CLI's `--watch` flag is more efficient.
:::

## Examples

Common usage patterns with Sovrium in TypeScript.

### Minimal server

```typescript
import { start } from 'sovrium'

const server = await start({
  name: 'my-app',
})

console.log(`Server running at ${server.url}`)
```

### With data tables

```typescript
import { start } from 'sovrium'

const server = await start(
  {
    name: 'my-app',
    tables: [
      {
        id: 1,
        name: 'tasks',
        fields: [
          { id: 1, name: 'title', type: 'single-line-text', required: true },
          { id: 2, name: 'done', type: 'checkbox' },
        ],
      },
    ],
  },
  {
    port: 8080,
    hostname: '0.0.0.0',
    publicDir: './public',
  }
)
```

### Static site generation

```typescript
import { build } from 'sovrium'

await build(
  {
    name: 'my-site',
    pages: [
      {
        name: 'home',
        path: '/',
        sections: [
          { type: 'heading', content: 'Welcome' },
          { type: 'paragraph', content: 'Built with Sovrium.' },
        ],
      },
    ],
  },
  {
    outputDir: './dist',
    baseUrl: 'https://example.com',
    deployment: 'github-pages',
    generateSitemap: true,
    generateRobotsTxt: true,
  }
)
```

### Dynamic configuration

```typescript
import { start } from 'sovrium'
import type { AppConfig, PageConfig, TableConfig, ThemeConfig } from 'sovrium'

// Compose config from typed sub-configs
const theme: ThemeConfig = {
  colors: { primary: process.env.BRAND_COLOR ?? '#3b82f6' },
}

const tables: TableConfig[] = ['users', 'posts'].map((name, i) => ({
  id: i + 1,
  name,
  fields: [
    { id: 1, name: 'title', type: 'single-line-text' as const, required: true },
    { id: 2, name: 'created_at', type: 'date' as const, includeTime: true },
  ],
}))

const pages: PageConfig[] = [{ name: 'home', path: '/', sections: [] }]

const app: AppConfig = {
  name: 'dynamic-app',
  tables,
  pages,
  theme,
}

await start(app)
```
