@vibase/sdk 0.0.0-stage → 0.3.1
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/LICENSE +18 -0
- package/README.md +269 -2
- package/dist/client.d.ts +10 -0
- package/dist/client.js +171 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +14 -0
- package/dist/filters.d.ts +34 -0
- package/dist/filters.js +53 -0
- package/dist/generated/operations.d.ts +3 -0
- package/dist/generated/operations.js +5385 -0
- package/dist/generated/types.d.ts +10451 -0
- package/dist/generated/types.js +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/session.d.ts +12 -0
- package/dist/session.js +42 -0
- package/dist/sign-in.d.ts +57 -0
- package/dist/sign-in.js +386 -0
- package/dist/types.d.ts +94 -0
- package/dist/types.js +1 -0
- package/dist/typing.d.ts +119 -0
- package/dist/typing.js +1 -0
- package/package.json +28 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vibase contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
6
|
+
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
|
7
|
+
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
12
|
+
portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
15
|
+
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
16
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
18
|
+
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,270 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vibase/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The typed TypeScript client of a Vibase deployment, for building custom front ends, dashboards and scripts on its REST API. One
|
|
4
|
+
fetch-only runtime for Node 22+, Workers and browsers, with no dependencies.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @vibase/sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The package is ESM only and ships its own type declarations. It needs `fetch`, which Node 22, Workers and every current browser
|
|
13
|
+
provide.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createClient, isVibaseError } from '@vibase/sdk'
|
|
17
|
+
|
|
18
|
+
const vibase = createClient({ url: 'https://crm.acme.example', auth: () => getToken() })
|
|
19
|
+
|
|
20
|
+
const page = await vibase.contacts.list({ limit: 50 })
|
|
21
|
+
await vibase.deals.moveStage({ id, stage_id })
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## createClient
|
|
25
|
+
|
|
26
|
+
`createClient({ url, auth, fetch?, operations? })`
|
|
27
|
+
|
|
28
|
+
- **`url`** (required): the deployment's origin. One deployment per organisation.
|
|
29
|
+
- **`auth`**: a bearer token (a string), or a function returning `string | null` (or a promise of one), called before every
|
|
30
|
+
request. `null` throws `401 no_credential` and sends nothing. The SDK calls the REST API, which accepts only bearer credentials, so it never sends or
|
|
31
|
+
stores a session cookie: an API key, an OAuth access token or a Better Auth session JWT (a Clerk session token on a Clerk instance). Requests go out with `credentials: 'omit'` and
|
|
32
|
+
`redirect: 'error'` (on workerd, which rejects that value, the client retries once with `manual` and refuses a redirect response as `unexpected_redirect`); a table path that would leave the configured origin is refused (`origin_mismatch`) before the
|
|
33
|
+
credential is read. There is no automatic retry: a function that returns a fresh token on its own owns refresh.
|
|
34
|
+
- **`fetch`**: defaults to the global; inject one for tests.
|
|
35
|
+
- **`operations`**: the operation table, defaulting to the built-ins. A generated table infers its map.
|
|
36
|
+
|
|
37
|
+
## Calls
|
|
38
|
+
|
|
39
|
+
A client has one namespace per resource prefix and one method per operation, named from the operation id, camelCased:
|
|
40
|
+
`action_requests.approve` is `vibase.actionRequests.approve`, `deals.move_stage` is `vibase.deals.moveStage`. Data stays
|
|
41
|
+
snake_case, exactly as the API sends it.
|
|
42
|
+
|
|
43
|
+
A method takes the operation's flat arguments (path, query and body fields in one object) and an optional
|
|
44
|
+
`{ signal }`. It resolves to the success body; a `204` resolves `undefined`; `files.content` resolves the checked `Response`
|
|
45
|
+
for the caller to stream.
|
|
46
|
+
|
|
47
|
+
## Filters
|
|
48
|
+
|
|
49
|
+
A list operation's column filters (`x-vibase-filter` parameters) take a bare operand (sent as `eq.<value>`, so a value such as
|
|
50
|
+
`is.gd` is a literal) or an object of the field's operators, one repeated condition per key; `not` carries a second object.
|
|
51
|
+
Operands are typed by the field's kind (a `timestamp` also takes a `Date`), and an operator the field lacks is a type error.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
await vibase.tasks.list({
|
|
55
|
+
created_at: { gte: new Date('2026-01-01'), lt: '2026-02-01T00:00:00Z' },
|
|
56
|
+
status: { not: { in: ['done', 'cancelled'] } },
|
|
57
|
+
assignee_id: { is: null },
|
|
58
|
+
title: { ilike: 'renew*' },
|
|
59
|
+
})
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`in` items holding `,`, `(`, `)`, `"` or a backslash are quoted for you. Each parameter takes at most the conditions its
|
|
63
|
+
OpenAPI schema allows (`maxItems`, 4 today), counting `not` keys; more is a `400 validation_error` thrown before anything is
|
|
64
|
+
sent. Other parameters (`limit`, `sort`, `after`) are sent as given.
|
|
65
|
+
|
|
66
|
+
## Pagination
|
|
67
|
+
|
|
68
|
+
A method returns one page. A paginated operation also has `.all(args?, { signal? })`, an async iterable of items that
|
|
69
|
+
follows `next_cursor` until it is `null` or empty. Every page keeps the other arguments (`limit` included) and the signal and
|
|
70
|
+
calls `auth` once; an `after` in `args` is ignored; a repeated cursor rejects with `invalid_response`. Breaking out sends
|
|
71
|
+
no further request.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
for await (const task of vibase.tasks.list.all({ limit: 100, status: 'open' })) console.log(task.title)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Aggregates
|
|
78
|
+
|
|
79
|
+
`vibase.<list>.aggregate(args?)` exists on contacts, companies, deals, tasks and every custom object. It is one method, typed
|
|
80
|
+
from the `x-vibase-aggregate` extension the API publishes on each aggregate operation, so the call site names only the fields
|
|
81
|
+
a function takes. `sum`, `avg`, `min` and `max` take one field or an array of them (a function with no field on the list has no
|
|
82
|
+
parameter); `group_by` takes one groupable field or a tuple of one or two. Filters are typed as for `list`. A comma-joined
|
|
83
|
+
string no longer type-checks; the client joins an array itself and refuses an empty one with
|
|
84
|
+
`VibaseError(400, 'validation_error', '<param>: give at least one field; nothing was sent')`. It checks no names, group cap or
|
|
85
|
+
duplicates: the server's own 400 comes back.
|
|
86
|
+
|
|
87
|
+
The answer is typed by what was asked: ungrouped it is `{ count }` plus the functions given and `currency` for a money field;
|
|
88
|
+
grouped it is `{ count, groups }` with `groups[].key` by field kind (always `| null`, the null group) and the same function keys
|
|
89
|
+
in each group. An optional `group_by` gives the union of both. Typing for a workspace's custom objects and `__c` fields needs
|
|
90
|
+
the generated workspace types (`vibase gen types`, see [Workspace types](#workspace-types)).
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const total = await vibase.deals.aggregate({ status: 'open', sum: 'amount_minor' })
|
|
94
|
+
total.sum.amount_minor // number | null
|
|
95
|
+
total.currency.amount_minor // string | null
|
|
96
|
+
|
|
97
|
+
const perStage = await vibase.deals.aggregate({ group_by: ['stage_id', 'currency'], sum: 'amount_minor' })
|
|
98
|
+
for (const g of perStage.groups) console.log(g.key.stage_id, g.key.currency, g.count, g.sum.amount_minor)
|
|
99
|
+
|
|
100
|
+
await vibase.deals.aggregate({ sum: 'name' }) // compile error: sum takes amount_minor
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Proposals
|
|
104
|
+
|
|
105
|
+
A proposable operation also has `.propose(args, proposal, { signal? })`, which calls `action_requests.create` with the
|
|
106
|
+
operation id and the same flat `args` (path fields and `null`s kept), and resolves to the action request with `operation`
|
|
107
|
+
narrowed and `arguments` typed. `proposal` is the request's other fields; `reason` is required.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const request = await vibase.tasks.update.propose({ id, title: 'Renamed' }, { reason: 'Matches the new naming' })
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Browser sessions
|
|
114
|
+
|
|
115
|
+
The SDK itself only sends bearer tokens. `sessionToken({ url, fetch?, cookie? })` is a credential function for a Better Auth browser session: it exchanges the
|
|
116
|
+
session cookie (the only place a cookie is used) for a short-lived bearer JWT at `GET <origin>/auth/token` on every call (never cached) and resolves `null` when signed out (a `401`, or a
|
|
117
|
+
success without a `token`), which `createClient` turns into `401 no_credential` without sending the API request. In a
|
|
118
|
+
browser it sends `credentials: 'include'`; server-side, pass `cookie` (a string, or a function called once per request) to
|
|
119
|
+
send that cookie header with `credentials: 'omit'`. Other failures reject with `VibaseError` as above.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const vibase = createClient({ url, auth: sessionToken({ url }) })
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Browser sign-in
|
|
126
|
+
|
|
127
|
+
`browserSignIn(options)` signs a person in to a browser app that lives on its own origin (a dashboard, a deals board), with the OAuth
|
|
128
|
+
authorization-code flow and PKCE (`S256`), and hands `createClient` an access token. It serves Better Auth deployments only
|
|
129
|
+
(`unsupported_provider` otherwise), uses only `fetch`, Web Crypto and the page's own storage, and reads no browser global until a
|
|
130
|
+
verb runs. It sends no cookie: every request is `credentials: 'omit'`.
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
import { browserSignIn, createClient } from '@vibase/sdk'
|
|
134
|
+
|
|
135
|
+
const signIn = browserSignIn({
|
|
136
|
+
url: 'https://crm.acme.example',
|
|
137
|
+
clientId: 'the-client-id',
|
|
138
|
+
redirectUri: `${location.origin}/callback`,
|
|
139
|
+
scopes: ['contacts.read'], // optional
|
|
140
|
+
})
|
|
141
|
+
const vibase = createClient({ url: 'https://crm.acme.example', auth: signIn.token })
|
|
142
|
+
|
|
143
|
+
// On the callback page, once on load:
|
|
144
|
+
const done = await signIn.handleRedirect() // { returnTo } after a sign-in, else null
|
|
145
|
+
if (done) history.replaceState(null, '', done.returnTo)
|
|
146
|
+
else if (!signIn.isSignedIn()) await signIn.signIn() // the browser leaves for the sign-in page
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### The verbs
|
|
150
|
+
|
|
151
|
+
- **`signIn({ returnTo? })`** stores one pending record (state, PKCE verifier, redirect URI and a same-origin `returnTo`, which defaults to the current page) in `sessionStorage` and navigates to the authorize endpoint. Its promise never resolves: the page is leaving. A `returnTo` on another origin rejects `invalid_return_to`.
|
|
152
|
+
- **`handleRedirect()`** answers `null` when the current URL is not the callback. On the callback it deletes the pending record first, checks `state` and `iss`, exchanges the code (no cookie, no client secret), stores the token record, removes the callback parameters from the address bar and resolves `{ returnTo }`. It does not navigate.
|
|
153
|
+
- **`token()`** is the `auth` function `createClient` takes. It returns the stored access token, refreshes it when less than 60 seconds remain (see Refresh), and resolves `null` when signed out.
|
|
154
|
+
- **`isSignedIn()`** is synchronous: true while a token record exists. It does not check expiry or the server.
|
|
155
|
+
- **`signOut()`** forgets the token and pending records on this device and sends nothing (see Sign-out).
|
|
156
|
+
|
|
157
|
+
### Options
|
|
158
|
+
|
|
159
|
+
| Option | Meaning |
|
|
160
|
+
|---|---|
|
|
161
|
+
| `url` | The deployment; only its origin is used. |
|
|
162
|
+
| `clientId` | The first-party client's id. |
|
|
163
|
+
| `redirectUri` | A redirect URI registered on that client, on the page's origin. |
|
|
164
|
+
| `scopes` | Omitted: no `scope` is sent and the instance grants its default set. Given: `openid offline_access` followed by these. |
|
|
165
|
+
| `storage` | Where the token record lives: `'session'` (default), `'local'`, `'memory'`, or an object with `getItem`, `setItem` and `removeItem`. The pending record is always in `sessionStorage`. |
|
|
166
|
+
| `fetch`, `location`, `navigate`, `replaceUrl`, `sessionStorage` | Injection points for tests and unusual hosts. |
|
|
167
|
+
|
|
168
|
+
Records are keyed by the deployment's origin and the client id, so two clients on one page do not see each other. If the chosen
|
|
169
|
+
storage throws or is absent (a private window, blocked site data), the SDK falls back to memory for the life of the page.
|
|
170
|
+
|
|
171
|
+
### What the app needs
|
|
172
|
+
|
|
173
|
+
- **A first-party client**, created by an owner with `oauth_clients.create`, whose `redirect_uris` include the exact `redirectUri`. A client of this kind signs people in without a consent screen.
|
|
174
|
+
- **The app's origin in `CORS_ALLOWED_ORIGINS`** on the deployment (not `AUTH_TRUSTED_ORIGINS`): the token endpoint and `/api` answer the browser's cross-origin requests only for listed origins.
|
|
175
|
+
- **On a Better Auth deployment** the signed-in person acts as themselves: within their own role and the app's scopes. An app whose scopes are left to the default gains new scopes as they are declared. The SDK decodes no token and assumes no principal.
|
|
176
|
+
|
|
177
|
+
### Storage and tabs
|
|
178
|
+
|
|
179
|
+
`sessionStorage` (the default) keeps the sign-in to one tab: a new tab signs in again. `'local'` shares it across tabs, and then two tabs
|
|
180
|
+
can refresh at the same time. Single-flight (below) is per sign-in object, so it does not coordinate tabs; when a refresh token is
|
|
181
|
+
rotated, the tab that loses the race can find its token refused and be signed out. Use `'session'` unless you need the shared sign-in.
|
|
182
|
+
`'memory'` survives only the page.
|
|
183
|
+
|
|
184
|
+
### Refresh
|
|
185
|
+
|
|
186
|
+
When less than 60 seconds remain, `token()` refreshes once at the token endpoint (`grant_type=refresh_token`, with `client_id` and
|
|
187
|
+
`resource`) and stores the answer. A new `refresh_token` replaces the old one; an answer without one keeps it. Concurrent calls share one
|
|
188
|
+
request and one answer, and a refresh that finishes after `signOut()` (or after another sign-in stored a different record) stores
|
|
189
|
+
nothing and resolves `null`. An expired token with no refresh token resolves `null` and clears the record.
|
|
190
|
+
|
|
191
|
+
A failed refresh is one of two kinds, and they need different handling:
|
|
192
|
+
|
|
193
|
+
- **The grant is gone** (the server answered `400` or `401`): the record is cleared and `token()` resolves `null`. The app is signed out; show the sign-in button.
|
|
194
|
+
- **The refresh could not be completed** (`fetch` threw: `network_error`; a `5xx` or another status: rejects with that status; an unusable `200`: `invalid_response`): `token()` rejects and the record is kept, so the next call tries again. The app can retry or tell the person to try later.
|
|
195
|
+
|
|
196
|
+
### Sign-out and revocation
|
|
197
|
+
|
|
198
|
+
`signOut()` is local. It calls no revoke or end-session endpoint (neither answers a browser app's cross-origin request), so a token that was
|
|
199
|
+
already issued stays valid until it expires. The owner's revocation is deleting the client (`oauth_clients.delete`): the next refresh is refused and the app is signed out.
|
|
200
|
+
|
|
201
|
+
### A 401 from the API
|
|
202
|
+
|
|
203
|
+
The SDK never retries. A `401` from `/api` for a token `token()` returned rejects as `VibaseError 401` and leaves the record alone. It means the token is no longer accepted, chiefly because the owner deleted the app (refused within about a minute). Call `signOut()` and show the sign-in button. A removed person gets `403 organization_forbidden` and a narrowed app gets `403 insufficient_scope` for operations outside its list; refresh cures neither.
|
|
204
|
+
|
|
205
|
+
### Errors
|
|
206
|
+
|
|
207
|
+
Every failure is a `VibaseError { status, code, message }`.
|
|
208
|
+
|
|
209
|
+
| Code | status | When |
|
|
210
|
+
|---|---|---|
|
|
211
|
+
| `unsupported_provider` | 0 | The deployment is not Better Auth. |
|
|
212
|
+
| `discovery_failed` | 0 | A discovery document is missing, not `200`, or lacks what is needed (including S256). |
|
|
213
|
+
| `issuer_mismatch` | 0 | The metadata, or the callback's `iss`, names another issuer. |
|
|
214
|
+
| `endpoint_origin` | 0 | An endpoint is not a URL or is not on the issuer's origin. |
|
|
215
|
+
| `insecure_issuer` | 0 | The issuer is not `https` (`http` is allowed on `localhost` and `127.0.0.1`). |
|
|
216
|
+
| `invalid_return_to` | 0 | `returnTo` is not a URL on the page's origin. |
|
|
217
|
+
| `state_mismatch` | 0 | The callback matches no sign-in this page started (or it was already used). |
|
|
218
|
+
| `authorization_failed` | 0 | The callback carries an `error`; the message holds it and its description. |
|
|
219
|
+
| `invalid_response` | the response's | A `200` from the token endpoint without an access token and a numeric `expires_in`. |
|
|
220
|
+
| `network_error` | 0 | `fetch` rejected. |
|
|
221
|
+
| the OAuth `error` (`invalid_grant`, `invalid_client`, ...) | the response's | The token endpoint refused the code exchange, or a refresh failed with a status other than `400`/`401` and a body naming one. |
|
|
222
|
+
| `http_<status>` | the response's | The token endpoint answered a failed refresh with no OAuth `error`. |
|
|
223
|
+
|
|
224
|
+
## Errors
|
|
225
|
+
|
|
226
|
+
Every failure rejects with a `VibaseError { status, code, message }`; `isVibaseError(e)` is the guard.
|
|
227
|
+
|
|
228
|
+
| Failure | status | code |
|
|
229
|
+
|---|---|---|
|
|
230
|
+
| The API's `{ error: { code, message } }` | the response's | the API's |
|
|
231
|
+
| Another non-2xx | the response's | `http_<status>` (message holds an excerpt) |
|
|
232
|
+
| `fetch` rejected | `0` | `network_error` |
|
|
233
|
+
| 2xx whose JSON does not parse | the response's | `invalid_response` |
|
|
234
|
+
| `auth` returned `null` | `401` | `no_credential` |
|
|
235
|
+
| A path that leaves the origin | `0` | `origin_mismatch` |
|
|
236
|
+
| A 3xx answer (never followed) | the 3xx status | `unexpected_redirect` |
|
|
237
|
+
| A path argument is missing | `0` | `invalid_argument` |
|
|
238
|
+
|
|
239
|
+
An abort rethrows the `AbortError` untouched.
|
|
240
|
+
|
|
241
|
+
## Workspace types
|
|
242
|
+
|
|
243
|
+
The built-in client types the built-ins only. A workspace's custom objects (`projects__c`) and `__c` fields on contacts,
|
|
244
|
+
companies, deals and tasks are declared in its schema file; a generated map of every operation (built-ins included) gives them
|
|
245
|
+
types, and `createClient` takes it through `operations`:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
import { createClient } from '@vibase/sdk'
|
|
249
|
+
import { workspaceOperations } from './vibase/operations.js'
|
|
250
|
+
|
|
251
|
+
const vibase = createClient({ url: 'https://crm.acme.example', auth: () => getToken(), operations: workspaceOperations })
|
|
252
|
+
await vibase.projects__c.list({ budget: { gte: 5000 } }) // a one-word custom object keeps its key
|
|
253
|
+
await vibase.sessionRecordings__c.list({ length_seconds: { gte: 30 } }) // `session_recordings__c`: the stem is camelCased, the `__c` suffix kept; argument keys stay snake_case
|
|
254
|
+
await vibase.contacts.update({ id, tier__c: 'gold' }) // 'platinum' is a type error
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
A custom object's namespace is its key with the stem camelCased and the `__c` suffix kept (`session_recordings__c` is
|
|
258
|
+
`vibase.sessionRecordings__c`); the arguments and the results keep the snake_case names of the API.
|
|
259
|
+
|
|
260
|
+
Generate the map with the Vibase CLI, which reads your instance's own documents (no login is needed for them):
|
|
261
|
+
|
|
262
|
+
```bash
|
|
263
|
+
npm i -D @vibase/sdk openapi-typescript@7
|
|
264
|
+
npx @vibase/cli gen types --out src/vibase --server https://crm.acme.example
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
It writes `src/vibase/operations.ts` and `src/vibase/types.ts`. `openapi-typescript` 7 is the project's own dependency and needs
|
|
268
|
+
`typescript` 5 where it resolves (a project on TypeScript 7 adds `typescript@5` for it). Commit the two files and run the command
|
|
269
|
+
again when the schema file or the release changes; nothing checks at run time that the map matches the deployment. Without the
|
|
270
|
+
map the client still works against any deployment; the custom objects are simply untyped by the built-in table.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { VibaseError } from './errors.js';
|
|
2
|
+
import type { BuiltInOperations } from './generated/types.js';
|
|
3
|
+
import type { Client, ClientOptions, OperationMap } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The typed client of one deployment (DX603). One namespace per resource prefix, one method per operation:
|
|
6
|
+
* `vibase.deals.moveStage({ id, stage_id })`. Methods take the flat arguments, resolve to the success body and
|
|
7
|
+
* reject with a `VibaseError`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createClient<Ops extends OperationMap = BuiltInOperations>(options: ClientOptions<Ops>): Client<Ops>;
|
|
10
|
+
export declare function failure(response: Response): Promise<VibaseError>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { VibaseError } from './errors.js';
|
|
2
|
+
import { serialiseFilter } from './filters.js';
|
|
3
|
+
import { builtInOperations } from './generated/operations.js';
|
|
4
|
+
/** How much of a non-JSON error body an `http_<status>` message keeps. */
|
|
5
|
+
const EXCERPT_LENGTH = 200;
|
|
6
|
+
/**
|
|
7
|
+
* The typed client of one deployment (DX603). One namespace per resource prefix, one method per operation:
|
|
8
|
+
* `vibase.deals.moveStage({ id, stage_id })`. Methods take the flat arguments, resolve to the success body and
|
|
9
|
+
* reject with a `VibaseError`.
|
|
10
|
+
*/
|
|
11
|
+
export function createClient(options) {
|
|
12
|
+
const origin = new URL(options.url).origin;
|
|
13
|
+
const table = (options.operations ?? builtInOperations);
|
|
14
|
+
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
15
|
+
const redirect = { value: 'error' };
|
|
16
|
+
const client = {};
|
|
17
|
+
for (const [id, entry] of Object.entries(table)) {
|
|
18
|
+
const namespace = (client[entry.namespace] ??= {});
|
|
19
|
+
const send = (target, args, callOptions) => call(origin, options.auth, doFetch, redirect, target, args, callOptions);
|
|
20
|
+
const method = (args, callOptions) => send(entry, args ?? {}, callOptions);
|
|
21
|
+
if (entry.paginated)
|
|
22
|
+
Object.assign(method, {
|
|
23
|
+
all: (args, o) => pages(send.bind(null, entry), args ?? {}, o),
|
|
24
|
+
});
|
|
25
|
+
if (entry.proposable)
|
|
26
|
+
Object.assign(method, {
|
|
27
|
+
propose: (args, proposal, o) => {
|
|
28
|
+
const create = table['action_requests.create'];
|
|
29
|
+
if (!create)
|
|
30
|
+
throw new VibaseError(0, 'invalid_argument', 'This operation table has no action_requests.create');
|
|
31
|
+
return send(create, { ...proposal, operation: id, arguments: args }, o);
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
namespace[entry.method] = method;
|
|
35
|
+
}
|
|
36
|
+
return client;
|
|
37
|
+
}
|
|
38
|
+
/** `.all()`: one request per page, `after` from `next_cursor`, until it is null or empty; a repeated cursor is an invalid response (DX608 D10). */
|
|
39
|
+
async function* pages(send, args, callOptions) {
|
|
40
|
+
const seen = new Set();
|
|
41
|
+
let after;
|
|
42
|
+
for (;;) {
|
|
43
|
+
const page = (await send({ ...args, after }, callOptions));
|
|
44
|
+
if (!page || !Array.isArray(page.data))
|
|
45
|
+
throw new VibaseError(200, 'invalid_response', 'A page has no data list');
|
|
46
|
+
yield* page.data;
|
|
47
|
+
const next = page.next_cursor;
|
|
48
|
+
if (next === null || next === undefined || next === '')
|
|
49
|
+
return;
|
|
50
|
+
if (typeof next !== 'string' || seen.has(next))
|
|
51
|
+
throw new VibaseError(200, 'invalid_response', 'The next_cursor repeats or is not a string');
|
|
52
|
+
seen.add(next);
|
|
53
|
+
after = next;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function call(origin, auth, doFetch, redirect, entry, args, callOptions) {
|
|
57
|
+
// The origin guard comes first: a path that would leave the configured origin is refused before the credential is read.
|
|
58
|
+
if (!/^\/(?![/\\])/.test(entry.path))
|
|
59
|
+
throw new VibaseError(0, 'origin_mismatch', `Refusing ${entry.http} ${entry.path}: it would leave ${origin}`);
|
|
60
|
+
const { path, query, body } = place(entry, args);
|
|
61
|
+
const url = new URL(path, origin);
|
|
62
|
+
if (url.origin !== origin)
|
|
63
|
+
throw new VibaseError(0, 'origin_mismatch', `Refusing ${entry.http} ${entry.path}: it would leave ${origin}`);
|
|
64
|
+
for (const [name, value] of query)
|
|
65
|
+
url.searchParams.append(name, value);
|
|
66
|
+
const token = typeof auth === 'function' ? await auth() : auth;
|
|
67
|
+
if (token === null || token === undefined)
|
|
68
|
+
throw new VibaseError(401, 'no_credential', 'No credential: the auth function returned null');
|
|
69
|
+
const headers = { authorization: `Bearer ${token}`, accept: 'application/json' };
|
|
70
|
+
if (body !== undefined)
|
|
71
|
+
headers['content-type'] = 'application/json';
|
|
72
|
+
const send = () => doFetch(url.toString(), {
|
|
73
|
+
method: entry.http,
|
|
74
|
+
headers,
|
|
75
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
76
|
+
signal: callOptions?.signal,
|
|
77
|
+
credentials: 'omit',
|
|
78
|
+
redirect: redirect.value,
|
|
79
|
+
});
|
|
80
|
+
let response;
|
|
81
|
+
try {
|
|
82
|
+
try {
|
|
83
|
+
response = await send();
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// workerd rejects `redirect: 'error'` before sending anything: fall back to `manual` for this client and refuse a redirect below.
|
|
87
|
+
if (redirect.value !== 'error' || !(error instanceof TypeError) || !/redirect/i.test(error.message))
|
|
88
|
+
throw error;
|
|
89
|
+
redirect.value = 'manual';
|
|
90
|
+
response = await send();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (isAbort(error))
|
|
95
|
+
throw error;
|
|
96
|
+
throw new VibaseError(0, 'network_error', error instanceof Error ? error.message : String(error));
|
|
97
|
+
}
|
|
98
|
+
if (response.type === 'opaqueredirect' ||
|
|
99
|
+
(redirect.value === 'manual' && response.status >= 300 && response.status < 400))
|
|
100
|
+
throw new VibaseError(response.status, 'unexpected_redirect', `The server answered with a redirect (HTTP ${response.status}), which is never followed`);
|
|
101
|
+
if (!response.ok)
|
|
102
|
+
throw await failure(response);
|
|
103
|
+
if (entry.output === 'empty' || response.status === 204)
|
|
104
|
+
return undefined;
|
|
105
|
+
if (entry.output === 'binary')
|
|
106
|
+
return response;
|
|
107
|
+
try {
|
|
108
|
+
return await response.json();
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (isAbort(error))
|
|
112
|
+
throw error;
|
|
113
|
+
throw new VibaseError(response.status, 'invalid_response', `The response body is not valid JSON (HTTP ${response.status})`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const isAbort = (error) => error instanceof Error && error.name === 'AbortError';
|
|
117
|
+
/** Splits the flat arguments by the table: the path with its fields substituted, the query pairs, the JSON body (or none). */
|
|
118
|
+
function place(entry, args) {
|
|
119
|
+
const path = entry.path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
120
|
+
const value = args[name];
|
|
121
|
+
if (value === undefined || value === null)
|
|
122
|
+
throw new VibaseError(0, 'invalid_argument', `Missing the path argument "${name}"`);
|
|
123
|
+
return encodeURIComponent(String(value));
|
|
124
|
+
});
|
|
125
|
+
const query = [];
|
|
126
|
+
const body = {};
|
|
127
|
+
for (const [name, value] of Object.entries(args)) {
|
|
128
|
+
if (value === undefined)
|
|
129
|
+
continue;
|
|
130
|
+
const place = entry.fields[name];
|
|
131
|
+
if (place === 'path')
|
|
132
|
+
continue;
|
|
133
|
+
if (place === 'query') {
|
|
134
|
+
const filter = entry.filters[name];
|
|
135
|
+
if (filter) {
|
|
136
|
+
if (value === null)
|
|
137
|
+
continue;
|
|
138
|
+
for (const condition of serialiseFilter(name, value, filter))
|
|
139
|
+
query.push([name, condition]);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (entry.aggregateParams?.includes(name) && Array.isArray(value)) {
|
|
143
|
+
// DX616 D5: an array is one comma-joined value; an empty one would change the answer's shape, so it is refused before anything is sent.
|
|
144
|
+
if (value.length === 0)
|
|
145
|
+
throw new VibaseError(400, 'validation_error', `${name}: give at least one field; nothing was sent`);
|
|
146
|
+
query.push([name, value.join(',')]);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
150
|
+
if (item !== undefined && item !== null)
|
|
151
|
+
query.push([name, String(item)]);
|
|
152
|
+
}
|
|
153
|
+
else if (entry.body)
|
|
154
|
+
body[name] = value;
|
|
155
|
+
}
|
|
156
|
+
return { path, query, body: entry.body ? body : undefined };
|
|
157
|
+
}
|
|
158
|
+
export async function failure(response) {
|
|
159
|
+
const text = await response.text().catch(() => '');
|
|
160
|
+
try {
|
|
161
|
+
const parsed = JSON.parse(text);
|
|
162
|
+
const error = parsed?.error;
|
|
163
|
+
if (typeof error?.code === 'string' && typeof error.message === 'string')
|
|
164
|
+
return new VibaseError(response.status, error.code, error.message);
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
// not JSON: fall through to the generic code
|
|
168
|
+
}
|
|
169
|
+
const excerpt = text.replace(/\s+/g, ' ').trim().slice(0, EXCERPT_LENGTH);
|
|
170
|
+
return new VibaseError(response.status, `http_${response.status}`, excerpt ? `HTTP ${response.status}: ${excerpt}` : `HTTP ${response.status}`);
|
|
171
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Every failure of a call rejects with this (DX603 D8): the API's own `{ error: { code, message } }`, or a code the client chose. */
|
|
2
|
+
export declare class VibaseError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly code: string;
|
|
5
|
+
constructor(status: number, code: string, message: string);
|
|
6
|
+
}
|
|
7
|
+
export declare function isVibaseError(value: unknown): value is VibaseError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Every failure of a call rejects with this (DX603 D8): the API's own `{ error: { code, message } }`, or a code the client chose. */
|
|
2
|
+
export class VibaseError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
constructor(status, code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'VibaseError';
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function isVibaseError(value) {
|
|
13
|
+
return value instanceof VibaseError;
|
|
14
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Column filters (DX608 D9): the typed operand/condition forms and the serialiser to the API's `[not.]<operator>.<operand>` grammar. */
|
|
2
|
+
export type FilterKind = 'uuid' | 'text' | 'integer' | 'timestamp' | 'boolean';
|
|
3
|
+
type OperandOf<K extends string> = K extends 'integer' ? number : K extends 'boolean' ? boolean : K extends 'timestamp' ? string | Date : string;
|
|
4
|
+
type Conditions<K extends string, Ops extends string> = {
|
|
5
|
+
[Op in Exclude<Ops, 'in' | 'is' | 'like' | 'ilike'>]?: OperandOf<K>;
|
|
6
|
+
} & ('in' extends Ops ? {
|
|
7
|
+
in?: readonly OperandOf<K>[];
|
|
8
|
+
} : unknown) & ('is' extends Ops ? {
|
|
9
|
+
is?: K extends 'boolean' ? boolean | null : null;
|
|
10
|
+
} : unknown) & ('like' extends Ops ? {
|
|
11
|
+
like?: string;
|
|
12
|
+
} : unknown) & ('ilike' extends Ops ? {
|
|
13
|
+
ilike?: string;
|
|
14
|
+
} : unknown);
|
|
15
|
+
/** What a filter parameter takes: a bare operand (equals), or an object of the field's operators, with `not` carrying the same again. */
|
|
16
|
+
export type Filter<K extends string, Ops extends string> = OperandOf<K> | (Conditions<K, Ops> & {
|
|
17
|
+
not?: Conditions<K, Ops>;
|
|
18
|
+
});
|
|
19
|
+
/** The filter parameters of an operation in the map: name to `[kind, operators]`. */
|
|
20
|
+
export type FilterSpecs = {
|
|
21
|
+
[name: string]: readonly [kind: string, operators: string];
|
|
22
|
+
};
|
|
23
|
+
export type FilterArgs<Args, F extends FilterSpecs> = Omit<Args, keyof F> & {
|
|
24
|
+
[N in keyof F]?: Filter<F[N][0], F[N][1]>;
|
|
25
|
+
};
|
|
26
|
+
export interface FilterEntry {
|
|
27
|
+
readonly kind: string;
|
|
28
|
+
readonly operators: readonly string[];
|
|
29
|
+
/** The most conditions the parameter takes (its array schema's `maxItems`). */
|
|
30
|
+
readonly max: number;
|
|
31
|
+
}
|
|
32
|
+
/** The repeated parameter values of one filter: a bare operand is `eq.<v>`, an object one condition per key (`not` keys counted too). */
|
|
33
|
+
export declare function serialiseFilter(name: string, value: unknown, entry: FilterEntry): string[];
|
|
34
|
+
export {};
|
package/dist/filters.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { VibaseError } from './errors.js';
|
|
2
|
+
const refuse = (name, message) => new VibaseError(400, 'validation_error', `filter ${name}: ${message}`);
|
|
3
|
+
function operand(name, value) {
|
|
4
|
+
if (value instanceof Date) {
|
|
5
|
+
if (Number.isNaN(value.getTime()))
|
|
6
|
+
throw refuse(name, 'the Date is invalid');
|
|
7
|
+
return value.toISOString();
|
|
8
|
+
}
|
|
9
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
10
|
+
return String(value);
|
|
11
|
+
throw refuse(name, `an operand is a string, number, boolean or Date, not ${value === null ? 'null' : typeof value}`);
|
|
12
|
+
}
|
|
13
|
+
/** An item of `in.(...)`: quoted when the grammar needs it (`,` `(` `)` `"`, a backslash, edge whitespace, empty). */
|
|
14
|
+
function listItem(name, value) {
|
|
15
|
+
const text = operand(name, value);
|
|
16
|
+
return /[,()"\\]|^\s|\s$|^$/.test(text) ? `"${text.replace(/[\\"]/g, '\\$&')}"` : text;
|
|
17
|
+
}
|
|
18
|
+
function conditions(name, spec, prefix, out) {
|
|
19
|
+
if (typeof spec !== 'object' || spec === null || Array.isArray(spec) || spec instanceof Date)
|
|
20
|
+
throw refuse(name, 'takes an operand or an object of operators');
|
|
21
|
+
for (const [op, value] of Object.entries(spec)) {
|
|
22
|
+
if (value === undefined)
|
|
23
|
+
continue;
|
|
24
|
+
if (op === 'not') {
|
|
25
|
+
if (prefix !== '')
|
|
26
|
+
throw refuse(name, 'not cannot be nested');
|
|
27
|
+
conditions(name, value, 'not.', out);
|
|
28
|
+
}
|
|
29
|
+
else if (op === 'in') {
|
|
30
|
+
if (!Array.isArray(value))
|
|
31
|
+
throw refuse(name, 'in takes a list');
|
|
32
|
+
out.push(`${prefix}in.(${value.map((item) => listItem(name, item)).join(',')})`);
|
|
33
|
+
}
|
|
34
|
+
else if (op === 'is') {
|
|
35
|
+
if (value !== null && typeof value !== 'boolean')
|
|
36
|
+
throw refuse(name, 'is takes null, true or false');
|
|
37
|
+
out.push(`${prefix}is.${value}`);
|
|
38
|
+
}
|
|
39
|
+
else
|
|
40
|
+
out.push(`${prefix}${op}.${operand(name, value)}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The repeated parameter values of one filter: a bare operand is `eq.<v>`, an object one condition per key (`not` keys counted too). */
|
|
44
|
+
export function serialiseFilter(name, value, entry) {
|
|
45
|
+
const out = [];
|
|
46
|
+
if (typeof value === 'object' && value !== null && !(value instanceof Date))
|
|
47
|
+
conditions(name, value, '', out);
|
|
48
|
+
else
|
|
49
|
+
out.push(`eq.${operand(name, value)}`);
|
|
50
|
+
if (out.length > entry.max)
|
|
51
|
+
throw refuse(name, `at most ${entry.max} conditions (got ${out.length}); nothing was sent`);
|
|
52
|
+
return out;
|
|
53
|
+
}
|