# @sypnia/data, the package

> One package for browsers, phones and servers: /client for auth and data, /server for secret keys, machines and direct Postgres, and the CLI.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://data.docs.sypnia.com/data/sdk/

For agents: @sypnia/data (MIT, Node 20+), subpaths /client and /server, and the CLI npx @sypnia/data (login, logout, whoami, init, pull, migrate, version; map only runs npx @sypnia/cases map). Sypnorm, the use-case ORM, and the use-case map are not part of it: they come with Sypnia Cases as @sypnia/cases (a dependency of @sypnia/data since 0.3.0; npx @sypnia/cases map). @sypnia/data/sypnorm and createServer from @sypnia/data/server are deprecated re-exports of @sypnia/cases/sypnorm (DeprecationWarning, SYPNIA_NO_DEPRECATION=1 silences it): import from @sypnia/cases/sypnorm. Client: createClient(url, publishableKey, {auth: {storage, crossSubdomain, autoRefresh, persistSession, detectSessionInUrl, storageKey, httpOnlyRefresh}, db: {schema}, fetch}). auth: signUp, signInWithPassword, signInWithOtp, verifyOtp, signInWithOAuth, exchangeCodeForSession, linkIdentity, unlinkIdentity, getSession, getUser, refreshSession, setSession, updateUser, resetPasswordForEmail, reauthenticate, signOut({scope}), onAuthStateChange, getSettings, sessions.list/revoke, tokens.list/create/revoke, devices.lookup/approve. Data: from(table) select/insert/upsert/update/delete with eq neq gt gte lt lte like ilike is in contains containedBy overlaps textSearch not or match order limit range single maybeSingle; rpc(fn, args); schema(name); transaction(operations). Server (@sypnia/data/server): createClient(url, {secretKey} | {client: {id, privateKey|secret, dpop, scope, resource}} | {accessToken} | {source}) adds sql`…`, query, sqlTransaction, schema, migrations.list/apply, admin (users, invite, generateLink, settings, clients, apiKeys); fromCredentials() uses the session saved by login. Refresh 60 s before expiry, one refresh at a time across tabs. CLI env: SYPNIA_SECRET_KEY, SYPNIA_CONFIG_DIR, SYPNIA_CLOUD_API.

```bash
npm install @sypnia/data
```

| Import                | For                                                                    |
| --------------------- | ---------------------------------------------------------------------- |
| `@sypnia/data/client` | browsers, phones, any app: auth and the query builder                  |
| `@sypnia/data/server` | servers: a secret key or a machine client, SQL, admin, direct Postgres |

The [CLI](#the-cli) comes with it: `npx @sypnia/data`. It needs Node 20 or later, and ships ES modules with types.

`@sypnia/data` has no ORM of its own: use the one you want, or none ([Use any ORM](https://data.docs.sypnia.com/data/any-orm)). Sypnorm, the use-case ORM, and the map of your use cases come with [Sypnia Cases](https://cases.docs.sypnia.com/sypnorm/), in the package `@sypnia/cases`, which `@sypnia/data` installs with it. Import Sypnorm from `@sypnia/cases/sypnorm`: `@sypnia/data/sypnorm` (and `createServer` from `@sypnia/data/server`) is a deprecated re-export of it, kept so older code runs unchanged; it prints a `DeprecationWarning`, which `SYPNIA_NO_DEPRECATION=1` silences.

## In a browser or a phone

```ts
import { createClient } from '@sypnia/data/client';
export const sypnia = createClient('https://<ref>.data.sypnia.com', 'syp_pk_<ref>_…');
```

`createClient` refuses a secret key in a browser.

| Option                    | Default                                      | What                                                                                                                                                                                       |
| ------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `auth.storage`            | `localStorage` in browsers, memory elsewhere | where the session lives; any store with `getItem`, `setItem`, `removeItem` (React Native, a custom store)                                                                                  |
| `auth.crossSubdomain`     | —                                            | `'.example.com'`: keep the session in a cookie of that domain, shared by your apps ([Users and your data](https://data.docs.sypnia.com/auth/users-and-your-data#several-apps-one-sign-in)) |
| `auth.httpOnlyRefresh`    | `false`                                      | the refresh token lives in the engine's `HttpOnly` cookie, with the CSRF header (`csrfCookie`, `csrfHeader`)                                                                               |
| `auth.autoRefresh`        | `true`                                       | renew the access token 60 s before it expires                                                                                                                                              |
| `auth.persistSession`     | `true`                                       | keep the session in the storage                                                                                                                                                            |
| `auth.detectSessionInUrl` | `true` in browsers                           | read the session from an e-mail link or a provider return when the page loads                                                                                                              |
| `auth.storageKey`         | `sypnia-auth-<ref>`                          | the storage key                                                                                                                                                                            |
| `db.schema`               | `public`                                     | the default schema for `from()`                                                                                                                                                            |
| `fetch`                   | the global `fetch`                           | your own `fetch`                                                                                                                                                                           |

`cookieStorage({ domain, path?, maxAgeDays?, sameSite? })` and `memoryStorage()` are exported too.

### Auth

| Call                                                                                                                    | Does                                                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `auth.signUp({ email, password?, options: { data, emailRedirectTo, captchaToken } })`                                   | creates the user; without password, «e-mail first»                                                                   |
| `auth.signInWithPassword({ email, password, options: { captchaToken } })`                                               | signs in                                                                                                             |
| `auth.signInWithOtp({ email, options: { shouldCreateUser, emailRedirectTo, captchaToken } })`                           | e-mails a link and a code                                                                                            |
| `auth.verifyOtp({ email, token, type })` or `({ token_hash, type })`                                                    | checks a link or code and signs in                                                                                   |
| `auth.signInWithOAuth({ provider, options: { redirectTo, skipBrowserRedirect } })`, `auth.exchangeCodeForSession(code)` | Google, GitHub, with PKCE                                                                                            |
| `auth.linkIdentity({ provider, options })`, `auth.unlinkIdentity(provider)`                                             | another way to sign in for the same person                                                                           |
| `auth.getSession()`, `auth.getUser()`                                                                                   | the current session; the user, fresh from the engine                                                                 |
| `auth.refreshSession()`, `auth.setSession({ access_token, refresh_token })`                                             | renew now; adopt tokens you got elsewhere                                                                            |
| `auth.updateUser({ password, email, data, nonce })`                                                                     | changes                                                                                                              |
| `auth.resetPasswordForEmail(email, { redirectTo, captchaToken })`                                                       | recovery e-mail                                                                                                      |
| `auth.reauthenticate()`                                                                                                 | a code by e-mail for a sensitive change                                                                              |
| `auth.signOut({ scope })`                                                                                               | `local`, `others` or `global`                                                                                        |
| `auth.onAuthStateChange(fn)`                                                                                            | `SIGNED_IN`, `TOKEN_REFRESHED`, `SIGNED_OUT`, `PASSWORD_RECOVERY`                                                    |
| `auth.getSettings()`                                                                                                    | the project's public auth settings, `email_ready` included                                                           |
| `auth.sessions.list()`, `auth.sessions.revoke(id)`                                                                      | the person's devices                                                                                                 |
| `auth.tokens.list()`, `auth.tokens.create({ name, scopes, resource?, expiresAt? })`, `auth.tokens.revoke(id)`           | [personal access tokens](https://data.docs.sypnia.com/machines/tokens-and-api-keys); `create` returns the token once |
| `auth.devices.lookup(userCode)`, `auth.devices.approve(userCode, 'approve' \| 'deny')`                                  | the [device flow](https://data.docs.sypnia.com/machines/device-flow-and-agents), from the approving person's side    |

The SDK renews the access token 60 seconds before it expires, with **one refresh at a time** across all tabs of the app (a lock over `BroadcastChannel`), so rotating refresh tokens never trip reuse detection.

### Data

```ts
const { data, error, count } = await sypnia
  .from('orders')
  .select('id, total, customer:customers(name)', { count: 'exact' })
  .eq('status', 'paid').gte('total', 50000)
  .order('created_at', { ascending: false })
  .range(0, 19);

await sypnia.from('orders').insert({ total: 19000 }).select();
await sypnia.from('profiles').upsert({ user_id, name }, { onConflict: 'user_id' });
await sypnia.rpc('close_month', { month: '2026-11' });
```

Filters: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `is`, `in`, `contains`, `containedBy`, `overlaps`, `textSearch`, `not`, `or`, `match`, `filter`. Then `order`, `limit`, `range`, `single()`, `maybeSingle()`, `abortSignal`. `select(columns, { count, head })` counts without rows. `schema('billing').from(…)` reads another exposed schema. Every call answers `{ data, error, count, status }` and never throws for an API error.

Several operations in one database transaction ([Transactions](https://data.docs.sypnia.com/data/rest-api#transactions)):

```ts
await sypnia.transaction([
  { name: 'stock', method: 'PATCH', table: 'products', query: { id: 'eq.1', left_today: 'gte.2' }, increment: { left_today: -2 }, expect: { rows: 1 } },
  { name: 'order', method: 'POST', table: 'orders', body: { note: 'counter' } },
  { method: 'POST', table: 'order_items', body: { order_id: { $ref: 'order.id' }, product_id: 1, qty: 2 } },
]);
```

With the types from `npx @sypnia/data pull`, rows and filters are typed.

## On a server

```ts
import { createClient } from '@sypnia/data/server';

const admin = createClient('https://<ref>.data.sypnia.com', { secretKey: process.env.SYPNIA_SECRET_KEY! });
await admin.sql`select count(*) from orders where status = ${'paid'}`;
await admin.auth.admin.createUser({ email, emailConfirm: true });

const worker = createClient(url, { client: { id: 'cli_…', privateKey: process.env.SYPNIA_CLIENT_KEY!, dpop: true } });
```

| Credential                                                           | What                                                                                                                                  |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `{ secretKey }`                                                      | a secret key: `service_role`                                                                                                          |
| `{ client: { id, privateKey \| secret, dpop?, scope?, resource? } }` | a [machine client](https://data.docs.sypnia.com/machines/client-credentials); it gets and renews its own tokens, with DPoP and nonces |
| `{ accessToken, apiKey? }`                                           | a token you already have, such as a person's                                                                                          |
| `{ source }`                                                         | your own credential source                                                                                                            |

`fromCredentials({ project? })` builds a client from the session `npx @sypnia/data login` saved on this machine.

| Call                                                                                                                                    | Does                                                                                                                |
| --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `from`, `rpc`, `schemaFrom(schema).from`, `transaction`                                                                                 | the Data API, as above, with the server's credential                                                                |
| `` sql`…` ``                                                                                                                            | a tagged template: values become parameters; answers the rows of the last statement                                 |
| `query(text, params, { readOnly, rowLimit, timeoutMs })`                                                                                | [`/sql/v1/query`](https://data.docs.sypnia.com/data/sql-and-migrations), every result                               |
| `sqlTransaction(statements, { readOnly })`                                                                                              | `/sql/v1/transaction`                                                                                               |
| `schema(schemas)`                                                                                                                       | the schema as JSON                                                                                                  |
| `migrations.list()`, `migrations.apply(name, sql)`                                                                                      | migrations                                                                                                          |
| `auth.admin.listUsers`, `createUser`, `getUserById`, `updateUserById`, `deleteUser`, `signOutUser`, `inviteUserByEmail`, `generateLink` | users, with the same names as `supabase-js`                                                                         |
| `auth.admin.settings.get`, `.update`                                                                                                    | the project's settings                                                                                              |
| `auth.admin.clients.list`, `.create`, `.update`, `.delete`                                                                              | OAuth clients                                                                                                       |
| `auth.admin.apiKeys.list`, `.create`, `.revoke`                                                                                         | API keys                                                                                                            |
| `request(method, path, body?)`, `headers(method, url)`                                                                                  | any engine path with the same credential; the headers it would send, to call other Sypnia APIs as the same identity |

`@sypnia/data/server` refuses to load in a browser, so a secret key never ends up in your app's code.

## The CLI

```bash
npx @sypnia/data <command>
```

### `npx @sypnia/data login`\[Engine, Cloud]Signs this machine in with the [device flow](https://data.docs.sypnia.com/machines/device-flow-and-agents): DPoP-bound, saved with mode 600, revocable. Without `--project`, it signs in to your Sypnia account at `auth.sypnia.com`, which reaches your Cloud projects.

**Flags:**

None.

### `npx @sypnia/data logout`\[Engine, Cloud]Revokes the saved session and deletes its files. `--project` picks which one.

### `npx @sypnia/data whoami`\[Engine, Cloud]The saved sessions: project, scopes, device and since when; `*` marks the current one.

### `npx @sypnia/data init`\[Engine, Cloud]Connects the app in this folder and its coding agent to a project: keys, MCP, skills, a machine client and types. [Install with your coding agent](https://data.docs.sypnia.com/start/install-with-your-agent) has every step.

**Flags:**

None.

### `npx @sypnia/data pull`\[Engine, Cloud]Writes typed tables and enums from the project's schema, by default to `src/db/schema.gen.ts`.

**Flags:**

None.

### `npx @sypnia/data migrate`\[Engine, Cloud]Applies `migrations/*.sql` in name order, each once and with its checksum; a file changed after it was applied stops it (`migration_checksum_mismatch`).

**Flags:**

None.

### `npx @sypnia/data version`\[Engine, Cloud]Prints the version (also `--version`).

`npx @sypnia/data map` says that the command moved and runs [`npx @sypnia/cases map`](https://cases.docs.sypnia.com/sypnorm/the-map/) with the same arguments.

**Credentials**, in this order: `SYPNIA_SECRET_KEY`, a direct connection (`--database-url`), the session `login` saved for that project, then your Sypnia account session, which reaches a Cloud project through the Cloud API with your organization role. Secrets are never printed.

| Variable            | What                                                  |
| ------------------- | ----------------------------------------------------- |
| `SYPNIA_SECRET_KEY` | a secret key to use instead of a saved session        |
| `SYPNIA_CONFIG_DIR` | where sessions are saved (default `~/.config/sypnia`) |
| `SYPNIA_CLOUD_API`  | the Cloud API (default `https://data.api.sypnia.com`) |

`pull` and `migrate` read their defaults from `sypnia.toml` at the root of the repository, the project's one configuration file, which `init` writes: `project` at the top, and `out`, `migrations` and `schemas` in the `[data]` table. A database address carries a password, so it never goes in the file: pass it with `--database-url`.

`sypnia.toml`

```toml
format = 1
project = "la-espiga"        # the Sypnia project, shared by every product

[data]
address = "https://la-espiga.data.sypnia.com"
orm = "none"                 # none, sql, prisma or drizzle
mcp = true
cases = true
out = "src/db/schema.gen.ts"
schemas = ["public"]
migrations = "migrations"
```

Each Sypnia product reads only its own table and leaves the others as they are. The map of your use cases is made with `npx @sypnia/cases map` ([The map from your code](https://cases.docs.sypnia.com/sypnorm/the-map/)).
