@veroxm/sdk 0.0.0-stage → 0.1.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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +255 -2
- package/dist/auth.d.ts +40 -0
- package/dist/auth.js +123 -0
- package/dist/client.d.ts +36 -0
- package/dist/client.js +59 -0
- package/dist/content.d.ts +75 -0
- package/dist/content.js +78 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +38 -0
- package/dist/http.d.ts +19 -0
- package/dist/http.js +42 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +8 -0
- package/dist/media.d.ts +40 -0
- package/dist/media.js +40 -0
- package/dist/token-storage.d.ts +43 -0
- package/dist/token-storage.js +43 -0
- package/dist/tracker.d.ts +149 -0
- package/dist/tracker.js +461 -0
- package/package.json +48 -4
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VeroXM
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,256 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @veroxm/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small client for VeroXM's public API -- authenticate, read/write content, and
|
|
4
|
+
manage media from any JavaScript/TypeScript project (a web app, a Node
|
|
5
|
+
backend, or React Native). No runtime dependencies: it's built entirely on
|
|
6
|
+
the platform's own `fetch`/`FormData`, which every target environment
|
|
7
|
+
already has (Node 18+, every modern browser, React Native 0.71+).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @veroxm/sdk
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Works in Node 18+, every modern browser and React Native 0.71+. No runtime dependencies.
|
|
16
|
+
|
|
17
|
+
## Quickstart
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { VeroXMApp } from '@veroxm/sdk';
|
|
21
|
+
|
|
22
|
+
const app = VeroXMApp.initializeApp({
|
|
23
|
+
baseUrl: 'https://your-veroxm-host',
|
|
24
|
+
projectId: 'YOUR-PROJECT-UUID', // Developer tab > Connection, in the dashboard
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Option A -- username/password (the Developer > Authentication tab).
|
|
28
|
+
// Refreshes silently in the background; you never call /auth/refresh yourself.
|
|
29
|
+
await app.auth.signInWithCredentials('a-username', 'a-password');
|
|
30
|
+
|
|
31
|
+
// Option B -- a static API key (the Developer > API Keys tab). No login
|
|
32
|
+
// step, no expiry, no refresh.
|
|
33
|
+
app.auth.signInWithApiKey('40|abcdef...');
|
|
34
|
+
|
|
35
|
+
// Typed access to one content collection (the slug from your Content
|
|
36
|
+
// Model screen). `T` is whatever shape you expect back -- the API's
|
|
37
|
+
// response shape follows that collection's own field list.
|
|
38
|
+
interface Post {
|
|
39
|
+
id: number;
|
|
40
|
+
title: string;
|
|
41
|
+
body: string;
|
|
42
|
+
}
|
|
43
|
+
const posts = app.content<Post>('posts');
|
|
44
|
+
|
|
45
|
+
const latest = await posts.list({ limit: 10, sort: 'created_at:desc' });
|
|
46
|
+
const one = await posts.get(42);
|
|
47
|
+
const created = await posts.create({ title: 'Hello', body: '...' });
|
|
48
|
+
await posts.update(created.id, { title: 'Hello, updated' });
|
|
49
|
+
await posts.delete(created.id);
|
|
50
|
+
|
|
51
|
+
// The where[]/whereRelation filter DSL -- see your project's SDK Docs tab
|
|
52
|
+
// for the full operator list (like/in/between/gte/...).
|
|
53
|
+
const drafts = await posts.search({
|
|
54
|
+
where: [{ title: { like: 'Hello' } }],
|
|
55
|
+
state: 'only_draft',
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Media
|
|
59
|
+
const media = app.media();
|
|
60
|
+
const page = await media.list({ page: 1 });
|
|
61
|
+
const uploaded = await media.upload(fileFromAnInput, 'a caption'); // browser: a File/Blob
|
|
62
|
+
await media.updateCaption(uploaded.id, 'a new caption');
|
|
63
|
+
await media.delete(uploaded.id);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Drafts & publishing
|
|
67
|
+
|
|
68
|
+
Two real API behaviors worth knowing before you rely on them:
|
|
69
|
+
|
|
70
|
+
- `content(...).get(id)` only ever returns a **published** record -- there's
|
|
71
|
+
no way to fetch a draft by id (it 404s), even right after
|
|
72
|
+
`create({..., draft: true})`. To find or inspect drafts, use
|
|
73
|
+
`list({state: 'only_draft'})` / `search({..., state: 'only_draft'})` instead.
|
|
74
|
+
- `update(id, data)` follows the same rule as `create()`: omitting `draft`
|
|
75
|
+
(or passing `draft: false`) **publishes the record immediately**, even if
|
|
76
|
+
the update itself doesn't touch any content fields and the record was
|
|
77
|
+
previously a draft. Pass `draft: true` explicitly if you want the update
|
|
78
|
+
to leave it (or put it back) unpublished.
|
|
79
|
+
|
|
80
|
+
## Locales
|
|
81
|
+
|
|
82
|
+
An entry can have per-locale variants (separate rows sharing whatever field
|
|
83
|
+
you use to identify "the same logical entry", e.g. `slug` -- there's no
|
|
84
|
+
built-in cross-locale id). `list()`/`search()`/`count()` all take a
|
|
85
|
+
`locale` option:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
// Only the Arabic entries.
|
|
89
|
+
const arPosts = await posts.list({ locale: 'ar' });
|
|
90
|
+
|
|
91
|
+
// One specific entry's translation, falling back to the project's
|
|
92
|
+
// default locale if that exact translation doesn't exist yet -- never a
|
|
93
|
+
// silent 404 just because a translation is missing.
|
|
94
|
+
const post = await posts.search({ where: [{ slug: { equals: 'hello' } }], first: true, locale: 'ar' });
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Omitting `locale` matches the project's default locale *and* any entry
|
|
98
|
+
created before locales existed (which has no locale tag at all) -- not
|
|
99
|
+
"every locale mixed together." `get(id)` has no `locale` option: an id
|
|
100
|
+
already identifies one exact row/locale, so there's nothing to select
|
|
101
|
+
between there.
|
|
102
|
+
|
|
103
|
+
## Auth modes
|
|
104
|
+
|
|
105
|
+
- **`signInWithApiKey(key)`** -- a static project API key. Simplest option
|
|
106
|
+
for server-to-server use where there's no per-user identity; never
|
|
107
|
+
expires, nothing to refresh.
|
|
108
|
+
- **`signInWithCredentials(username, password)`** -- the login flow from a
|
|
109
|
+
project's Authentication tab. Returns a 1-hour access token plus a
|
|
110
|
+
30-day refresh token; `VeroXMAuth` refreshes automatically, a little
|
|
111
|
+
before actual expiry, and again on demand if a request still comes back
|
|
112
|
+
`401` (clock skew, or a token revoked server-side). You never need to
|
|
113
|
+
call the refresh endpoint yourself.
|
|
114
|
+
|
|
115
|
+
Either way, `app.content(...)`/`app.media()` calls just work -- the SDK
|
|
116
|
+
attaches whichever credential is active.
|
|
117
|
+
|
|
118
|
+
### Persisting sign-in across page reloads / app restarts
|
|
119
|
+
|
|
120
|
+
`initializeApp` picks `BrowserLocalStorageTokenStorage` automatically when
|
|
121
|
+
`window.localStorage` exists, and falls back to an in-memory store
|
|
122
|
+
(`MemoryTokenStorage`, cleared whenever the VeroXMApp instance is garbage
|
|
123
|
+
collected) everywhere else -- Node, React Native, SSR. To persist a
|
|
124
|
+
session across a Node process restart or in React Native, implement the
|
|
125
|
+
three-method `TokenStorage` interface against whatever that environment
|
|
126
|
+
offers (a file, `AsyncStorage`, etc.) and pass it as `tokenStorage` when
|
|
127
|
+
calling `initializeApp`.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
app.auth.onTokenChange((accessToken) => {
|
|
131
|
+
// accessToken is null right after signOut(), and after a successful
|
|
132
|
+
// sign-in/refresh otherwise -- mirror it into your own app state if useful.
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Visitor tracking (Experience OS)
|
|
137
|
+
|
|
138
|
+
Record page views and actions, the visitor's consent, and who they are, so
|
|
139
|
+
VeroXM can build visitor profiles (and, from Phase 2, personalise content).
|
|
140
|
+
Create a key with **only** the "Send events" permission in the dashboard --
|
|
141
|
+
it can't read or change content, so it's safe in browser code.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
import { createTracker } from '@veroxm/sdk';
|
|
145
|
+
|
|
146
|
+
const tracker = createTracker({
|
|
147
|
+
baseUrl: 'https://your-veroxm-host',
|
|
148
|
+
projectId: 'YOUR-PROJECT-UUID',
|
|
149
|
+
eventsKey: '12|events-only-key',
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// From your consent banner. Until analytics is granted nothing is stored
|
|
153
|
+
// on the device or sent; events wait in memory and go out once it is.
|
|
154
|
+
if (tracker.getConsent().analytics === 'unknown') showBanner();
|
|
155
|
+
tracker.consent({ analytics: true, personalization: true });
|
|
156
|
+
// Separately, only if they opted in to marketing emails (journey emails):
|
|
157
|
+
tracker.consent({ marketing: true });
|
|
158
|
+
|
|
159
|
+
tracker.page(); // path, url, title, referrer added in browsers
|
|
160
|
+
tracker.track('demo_requested', { plan: 'enterprise' });
|
|
161
|
+
await tracker.identify(user.id, { plan: 'pro' }); // after sign-in
|
|
162
|
+
tracker.reset(); // after sign-out
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
- **Delivery:** batched (every 5 s or 20 events, and when the tab is
|
|
166
|
+
hidden), retried with backoff using the same event ids, and -- with
|
|
167
|
+
consent -- kept in `localStorage` until sent, so a reload doesn't lose
|
|
168
|
+
events. A batch the API rejects (4xx) is dropped and reported via
|
|
169
|
+
`onError`.
|
|
170
|
+
- **Consent:** `requireConsent` defaults to `true`. Set it to `false` only
|
|
171
|
+
where you may count visitors without consent; events are then sent
|
|
172
|
+
anonymously until the visitor consents. Three purposes: `analytics`
|
|
173
|
+
(store and attach events), `personalization` (targeting, journeys,
|
|
174
|
+
personal recommendations) and `marketing` (journey emails). Each email
|
|
175
|
+
carries an unsubscribe link that sets `marketing` to denied.
|
|
176
|
+
- **Outside a browser** (React Native, Node), pass `storage` with
|
|
177
|
+
`get/set/remove` backed by that platform's storage; otherwise the visitor
|
|
178
|
+
id lasts for the process only.
|
|
179
|
+
|
|
180
|
+
### Experiences and feature flags
|
|
181
|
+
|
|
182
|
+
Ask which variant of a placement this visitor sees. Experiences are set up
|
|
183
|
+
in the dashboard (project > **Experiences**); a variant is a CMS entry
|
|
184
|
+
and/or a JSON config.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
const d = await tracker.getExperience<HeroEntry, { cta?: string }>('home.hero');
|
|
188
|
+
if (d.reason === 'none') renderDefaultHero();
|
|
189
|
+
else renderHero(d.content ?? defaultHero, d.config?.cta);
|
|
190
|
+
|
|
191
|
+
// A config-only experience doubles as a feature flag:
|
|
192
|
+
const newCheckout = await tracker.getFlag('checkout.flags', 'newCheckout', false);
|
|
193
|
+
|
|
194
|
+
// Consent, identify() or reset() can change the answer -- ask again:
|
|
195
|
+
const stop = tracker.subscribe(() => rerenderExperiences());
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
- **Never throws.** Errors and timeouts (`timeoutMs`, default 1500) resolve
|
|
199
|
+
to `reason: 'none'` with `error` set -- show your default.
|
|
200
|
+
- **Consent:** before analytics consent it resolves to `'none'` with
|
|
201
|
+
`waitingForConsent: true` and makes no request (a sticky assignment needs
|
|
202
|
+
a stored visitor id, and the server records an exposure). Segment
|
|
203
|
+
targeting additionally needs personalization consent.
|
|
204
|
+
- **Journey messages:** a journey's in-app step can leave a message for
|
|
205
|
+
this person on a placement. Then `d.reason === 'journey'` and the
|
|
206
|
+
message fields are in `d.config` (e.g. `title`, `text`, `ctaLabel`,
|
|
207
|
+
`ctaUrl`); `content` and the experiment ids are `null`.
|
|
208
|
+
- **Sticky and cached:** the same visitor always gets the same variant;
|
|
209
|
+
answers are cached per placement until consent, identity or the visitor
|
|
210
|
+
changes.
|
|
211
|
+
- **Server-side rendering:** use the GraphQL `experience(placement,
|
|
212
|
+
visitorId, country)` query with the visitor's id from your own cookie.
|
|
213
|
+
|
|
214
|
+
### Recommendations
|
|
215
|
+
|
|
216
|
+
Record which entries a visitor reads, then ask for a collection's entries
|
|
217
|
+
ranked for them -- "people who read this also read":
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
tracker.viewContent(article.id); // on an article page
|
|
221
|
+
const recs = await tracker.getRecommendations<Article>('articles', { limit: 3, exclude: [article.id] });
|
|
222
|
+
// recs.strategy: 'personal' (from their reading and similar readers) or 'popular' (most read)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Personal ranking needs personalization consent and at least two entries
|
|
226
|
+
read; otherwise (and to fill a short list) you get the most-read entries.
|
|
227
|
+
What the visitor already read is left out of personal results. Never
|
|
228
|
+
throws: an error returns an empty list with `error` set.
|
|
229
|
+
|
|
230
|
+
## Errors
|
|
231
|
+
|
|
232
|
+
Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, and a
|
|
233
|
+
`.message` extracted from whichever error shape the API used). A request
|
|
234
|
+
made before any sign-in call throws `VeroXMNotAuthenticatedError`.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { VeroXMApiError } from '@veroxm/sdk';
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
await posts.delete(1);
|
|
241
|
+
} catch (e) {
|
|
242
|
+
if (e instanceof VeroXMApiError && e.status === 403) {
|
|
243
|
+
// this credential's abilities don't include 'delete'
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## Documentation and support
|
|
249
|
+
|
|
250
|
+
- Guide: https://docs.veroxm.com/sdks#veroxm-sdk
|
|
251
|
+
- All VeroXM SDKs: https://docs.veroxm.com/sdks
|
|
252
|
+
- Changelog: https://docs.veroxm.com/changelog
|
|
253
|
+
|
|
254
|
+
## License
|
|
255
|
+
|
|
256
|
+
MIT
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { TokenStorage } from './token-storage.js';
|
|
2
|
+
/**
|
|
3
|
+
* Handles both auth modes this SDK supports:
|
|
4
|
+
* - `signInWithApiKey` -- a static project API key (Sanctum-style,
|
|
5
|
+
* never expires, no refresh needed). Matches pasting a key into the
|
|
6
|
+
* dashboard's API Keys tab.
|
|
7
|
+
* - `signInWithCredentials` -- the username/password login flow (a
|
|
8
|
+
* project's Authentication tab), which returns a short-lived access
|
|
9
|
+
* token plus a refresh token; this class refreshes silently and
|
|
10
|
+
* transparently as needed, the same "just works" feel as Firebase
|
|
11
|
+
* Auth's token refresh.
|
|
12
|
+
*/
|
|
13
|
+
export declare class VeroXMAuth {
|
|
14
|
+
private readonly apiBase;
|
|
15
|
+
private readonly storage;
|
|
16
|
+
private apiKey;
|
|
17
|
+
private session;
|
|
18
|
+
private loadedFromStorage;
|
|
19
|
+
private refreshInFlight;
|
|
20
|
+
private readonly listeners;
|
|
21
|
+
constructor(apiBase: string, storage: TokenStorage);
|
|
22
|
+
/** Static-key mode: no login round-trip, no expiry, no refresh token. */
|
|
23
|
+
signInWithApiKey(apiKey: string): void;
|
|
24
|
+
/** Username/password mode -- exchanges credentials for an access+refresh token pair and persists it via the configured TokenStorage. */
|
|
25
|
+
signInWithCredentials(username: string, password: string): Promise<void>;
|
|
26
|
+
signOut(): Promise<void>;
|
|
27
|
+
/** Returns the abilities (read/create/update/delete, or ['*']) the current credential carries, or null if signed out or in static-key mode (a key's abilities aren't known client-side -- only the API enforces them). */
|
|
28
|
+
currentAbilities(): string[] | null;
|
|
29
|
+
/** Notified with the current access token whenever it changes (sign-in, refresh, sign-out) -- e.g. to mirror it into your own app state. Returns an unsubscribe function. */
|
|
30
|
+
onTokenChange(listener: (accessToken: string | null) => void): () => void;
|
|
31
|
+
/** True while a refresh-token session (not static-key mode) is available to retry a request with. */
|
|
32
|
+
canRefresh(): boolean;
|
|
33
|
+
/** Forces a refresh regardless of expiry and returns the new access token -- used by VeroXMApp to retry a request that came back 401 despite the proactive expiry check below. */
|
|
34
|
+
forceRefreshAndGetToken(): Promise<string>;
|
|
35
|
+
/** Resolves the bearer token for the next request, transparently refreshing a near-expired session first. Throws VeroXMNotAuthenticatedError if nothing has signed in yet. */
|
|
36
|
+
getAccessToken(): Promise<string>;
|
|
37
|
+
private refresh;
|
|
38
|
+
private persistSession;
|
|
39
|
+
private notify;
|
|
40
|
+
}
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { rawRequest } from './http.js';
|
|
2
|
+
import { VeroXMNotAuthenticatedError } from './errors.js';
|
|
3
|
+
// Refresh a little before the token actually expires, not exactly at the
|
|
4
|
+
// deadline -- covers clock skew and the time an in-flight request spends
|
|
5
|
+
// on the wire between "token looked valid" and "server received it".
|
|
6
|
+
const REFRESH_SKEW_MS = 30000;
|
|
7
|
+
/**
|
|
8
|
+
* Handles both auth modes this SDK supports:
|
|
9
|
+
* - `signInWithApiKey` -- a static project API key (Sanctum-style,
|
|
10
|
+
* never expires, no refresh needed). Matches pasting a key into the
|
|
11
|
+
* dashboard's API Keys tab.
|
|
12
|
+
* - `signInWithCredentials` -- the username/password login flow (a
|
|
13
|
+
* project's Authentication tab), which returns a short-lived access
|
|
14
|
+
* token plus a refresh token; this class refreshes silently and
|
|
15
|
+
* transparently as needed, the same "just works" feel as Firebase
|
|
16
|
+
* Auth's token refresh.
|
|
17
|
+
*/
|
|
18
|
+
export class VeroXMAuth {
|
|
19
|
+
constructor(apiBase, storage) {
|
|
20
|
+
this.apiBase = apiBase;
|
|
21
|
+
this.storage = storage;
|
|
22
|
+
this.apiKey = null;
|
|
23
|
+
this.session = null;
|
|
24
|
+
this.loadedFromStorage = false;
|
|
25
|
+
this.refreshInFlight = null;
|
|
26
|
+
this.listeners = new Set();
|
|
27
|
+
}
|
|
28
|
+
/** Static-key mode: no login round-trip, no expiry, no refresh token. */
|
|
29
|
+
signInWithApiKey(apiKey) {
|
|
30
|
+
this.apiKey = apiKey;
|
|
31
|
+
this.session = null;
|
|
32
|
+
this.loadedFromStorage = true; // nothing left to load -- api-key mode short-circuits getAccessToken()
|
|
33
|
+
this.notify(apiKey);
|
|
34
|
+
}
|
|
35
|
+
/** Username/password mode -- exchanges credentials for an access+refresh token pair and persists it via the configured TokenStorage. */
|
|
36
|
+
async signInWithCredentials(username, password) {
|
|
37
|
+
const data = (await rawRequest(this.apiBase, {
|
|
38
|
+
method: 'POST',
|
|
39
|
+
path: '/auth/token',
|
|
40
|
+
json: { username, password },
|
|
41
|
+
}));
|
|
42
|
+
this.apiKey = null;
|
|
43
|
+
await this.persistSession(data);
|
|
44
|
+
}
|
|
45
|
+
async signOut() {
|
|
46
|
+
this.apiKey = null;
|
|
47
|
+
this.session = null;
|
|
48
|
+
this.loadedFromStorage = true;
|
|
49
|
+
await this.storage.clear();
|
|
50
|
+
this.notify(null);
|
|
51
|
+
}
|
|
52
|
+
/** Returns the abilities (read/create/update/delete, or ['*']) the current credential carries, or null if signed out or in static-key mode (a key's abilities aren't known client-side -- only the API enforces them). */
|
|
53
|
+
currentAbilities() {
|
|
54
|
+
return this.session?.abilities ?? null;
|
|
55
|
+
}
|
|
56
|
+
/** Notified with the current access token whenever it changes (sign-in, refresh, sign-out) -- e.g. to mirror it into your own app state. Returns an unsubscribe function. */
|
|
57
|
+
onTokenChange(listener) {
|
|
58
|
+
this.listeners.add(listener);
|
|
59
|
+
return () => this.listeners.delete(listener);
|
|
60
|
+
}
|
|
61
|
+
/** True while a refresh-token session (not static-key mode) is available to retry a request with. */
|
|
62
|
+
canRefresh() {
|
|
63
|
+
return !this.apiKey && !!this.session?.refreshToken;
|
|
64
|
+
}
|
|
65
|
+
/** Forces a refresh regardless of expiry and returns the new access token -- used by VeroXMApp to retry a request that came back 401 despite the proactive expiry check below. */
|
|
66
|
+
async forceRefreshAndGetToken() {
|
|
67
|
+
await this.refresh();
|
|
68
|
+
return this.session.accessToken;
|
|
69
|
+
}
|
|
70
|
+
/** Resolves the bearer token for the next request, transparently refreshing a near-expired session first. Throws VeroXMNotAuthenticatedError if nothing has signed in yet. */
|
|
71
|
+
async getAccessToken() {
|
|
72
|
+
if (this.apiKey)
|
|
73
|
+
return this.apiKey;
|
|
74
|
+
if (!this.loadedFromStorage) {
|
|
75
|
+
this.session = await this.storage.get();
|
|
76
|
+
this.loadedFromStorage = true;
|
|
77
|
+
}
|
|
78
|
+
if (!this.session)
|
|
79
|
+
throw new VeroXMNotAuthenticatedError();
|
|
80
|
+
if (Date.now() >= this.session.expiresAt - REFRESH_SKEW_MS) {
|
|
81
|
+
await this.refresh();
|
|
82
|
+
}
|
|
83
|
+
return this.session.accessToken;
|
|
84
|
+
}
|
|
85
|
+
async refresh() {
|
|
86
|
+
if (!this.session?.refreshToken)
|
|
87
|
+
throw new VeroXMNotAuthenticatedError();
|
|
88
|
+
// Coalesce concurrent refreshes: several in-flight requests hitting a
|
|
89
|
+
// near-expired token at the same moment should trigger exactly one
|
|
90
|
+
// refresh call, not one each -- the API's refresh tokens are single-use
|
|
91
|
+
// (rotated on every call), so a second concurrent call would just fail.
|
|
92
|
+
if (!this.refreshInFlight) {
|
|
93
|
+
const refreshToken = this.session.refreshToken;
|
|
94
|
+
this.refreshInFlight = (async () => {
|
|
95
|
+
const data = (await rawRequest(this.apiBase, {
|
|
96
|
+
method: 'POST',
|
|
97
|
+
path: '/auth/refresh',
|
|
98
|
+
json: { refreshToken },
|
|
99
|
+
}));
|
|
100
|
+
await this.persistSession(data);
|
|
101
|
+
})().finally(() => {
|
|
102
|
+
this.refreshInFlight = null;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
await this.refreshInFlight;
|
|
106
|
+
}
|
|
107
|
+
async persistSession(data) {
|
|
108
|
+
const session = {
|
|
109
|
+
accessToken: data.accessToken,
|
|
110
|
+
refreshToken: data.refreshToken,
|
|
111
|
+
expiresAt: Date.now() + data.expiresIn * 1000,
|
|
112
|
+
abilities: data.abilities,
|
|
113
|
+
};
|
|
114
|
+
this.session = session;
|
|
115
|
+
this.loadedFromStorage = true;
|
|
116
|
+
await this.storage.set(session);
|
|
117
|
+
this.notify(session.accessToken);
|
|
118
|
+
}
|
|
119
|
+
notify(accessToken) {
|
|
120
|
+
for (const listener of this.listeners)
|
|
121
|
+
listener(accessToken);
|
|
122
|
+
}
|
|
123
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type RawRequestOptions } from './http.js';
|
|
2
|
+
import { VeroXMAuth } from './auth.js';
|
|
3
|
+
import { ContentResource } from './content.js';
|
|
4
|
+
import { MediaResource } from './media.js';
|
|
5
|
+
import { type TokenStorage } from './token-storage.js';
|
|
6
|
+
export interface VeroXMAppOptions {
|
|
7
|
+
/** Your VeroXM deployment's origin, e.g. "https://cms.example.com" -- no trailing /public/... needed, VeroXMApp builds that itself. */
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
/** The project's UUID (Developer tab > Connection > Project UUID in the dashboard). */
|
|
10
|
+
projectId: string;
|
|
11
|
+
/** Defaults to browser localStorage when available, otherwise an in-memory store that only lasts for this VeroXMApp instance's lifetime. Pass your own TokenStorage implementation for disk persistence in Node/React Native. */
|
|
12
|
+
tokenStorage?: TokenStorage;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The SDK's entry point -- one `initializeApp()` call, Firebase-style,
|
|
16
|
+
* then `app.auth`, `app.content(slug)`, and `app.media()` for everything
|
|
17
|
+
* else. See this package's README for a full quickstart.
|
|
18
|
+
*/
|
|
19
|
+
export declare class VeroXMApp {
|
|
20
|
+
readonly auth: VeroXMAuth;
|
|
21
|
+
private readonly apiBase;
|
|
22
|
+
private constructor();
|
|
23
|
+
static initializeApp(options: VeroXMAppOptions): VeroXMApp;
|
|
24
|
+
/** Typed access to one content collection's entries (list/get/create/update/delete/search). */
|
|
25
|
+
content<T = Record<string, unknown>>(collectionSlug: string): ContentResource<T>;
|
|
26
|
+
/** This project's media library (list/upload/updateCaption/delete). */
|
|
27
|
+
media(): MediaResource;
|
|
28
|
+
/**
|
|
29
|
+
* Used internally by ContentResource/MediaResource -- attaches the
|
|
30
|
+
* current bearer token and, if the very first attempt still comes back
|
|
31
|
+
* 401 (clock skew, or a token revoked server-side since the last
|
|
32
|
+
* proactive refresh), forces one refresh and retries exactly once
|
|
33
|
+
* before giving up.
|
|
34
|
+
*/
|
|
35
|
+
request(opts: RawRequestOptions): Promise<unknown>;
|
|
36
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { rawRequest } from './http.js';
|
|
2
|
+
import { VeroXMApiError } from './errors.js';
|
|
3
|
+
import { VeroXMAuth } from './auth.js';
|
|
4
|
+
import { ContentResource } from './content.js';
|
|
5
|
+
import { MediaResource } from './media.js';
|
|
6
|
+
import { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
|
|
7
|
+
function defaultTokenStorage(projectId) {
|
|
8
|
+
if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {
|
|
9
|
+
return new BrowserLocalStorageTokenStorage(projectId);
|
|
10
|
+
}
|
|
11
|
+
return new MemoryTokenStorage();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The SDK's entry point -- one `initializeApp()` call, Firebase-style,
|
|
15
|
+
* then `app.auth`, `app.content(slug)`, and `app.media()` for everything
|
|
16
|
+
* else. See this package's README for a full quickstart.
|
|
17
|
+
*/
|
|
18
|
+
export class VeroXMApp {
|
|
19
|
+
constructor(apiBase, tokenStorage) {
|
|
20
|
+
this.apiBase = apiBase;
|
|
21
|
+
this.auth = new VeroXMAuth(apiBase, tokenStorage);
|
|
22
|
+
}
|
|
23
|
+
static initializeApp(options) {
|
|
24
|
+
const base = options.baseUrl.replace(/\/$/, '');
|
|
25
|
+
const apiBase = `${base}/public/v2/projects/${options.projectId}`;
|
|
26
|
+
return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId));
|
|
27
|
+
}
|
|
28
|
+
/** Typed access to one content collection's entries (list/get/create/update/delete/search). */
|
|
29
|
+
content(collectionSlug) {
|
|
30
|
+
return new ContentResource(this, collectionSlug);
|
|
31
|
+
}
|
|
32
|
+
/** This project's media library (list/upload/updateCaption/delete). */
|
|
33
|
+
media() {
|
|
34
|
+
return new MediaResource(this);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Used internally by ContentResource/MediaResource -- attaches the
|
|
38
|
+
* current bearer token and, if the very first attempt still comes back
|
|
39
|
+
* 401 (clock skew, or a token revoked server-side since the last
|
|
40
|
+
* proactive refresh), forces one refresh and retries exactly once
|
|
41
|
+
* before giving up.
|
|
42
|
+
*/
|
|
43
|
+
async request(opts) {
|
|
44
|
+
const token = await this.auth.getAccessToken();
|
|
45
|
+
try {
|
|
46
|
+
return await rawRequest(this.apiBase, withAuth(opts, token));
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
if (e instanceof VeroXMApiError && e.status === 401 && this.auth.canRefresh()) {
|
|
50
|
+
const retryToken = await this.auth.forceRefreshAndGetToken();
|
|
51
|
+
return rawRequest(this.apiBase, withAuth(opts, retryToken));
|
|
52
|
+
}
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function withAuth(opts, token) {
|
|
58
|
+
return { ...opts, headers: { ...opts.headers, Authorization: `Bearer ${token}` } };
|
|
59
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { VeroXMApp } from './client.js';
|
|
2
|
+
export interface ListOptions {
|
|
3
|
+
/** Field-value filter -- an array of `{field: value}` clauses (AND'ed together), each value either a scalar or an operator object like `{like: '...'}`, `{gte: '...'}`, `{in: 'a,b,c'}`, etc. See the project's SDK Docs tab for the full operator list. */
|
|
4
|
+
where?: unknown;
|
|
5
|
+
whereRelation?: Record<string, Record<string, string>>;
|
|
6
|
+
/** e.g. "created_at:desc" or "title:asc,created_at:desc". */
|
|
7
|
+
sort?: string;
|
|
8
|
+
/** Pass "only_draft" to include unpublished entries; anything else (including omitted) returns published-only. */
|
|
9
|
+
state?: 'only_draft' | string;
|
|
10
|
+
offset?: number;
|
|
11
|
+
limit?: number;
|
|
12
|
+
/** When true, the API returns a single number (the match count) instead of a list -- see count() below for a typed shortcut. */
|
|
13
|
+
count?: boolean;
|
|
14
|
+
/** search() only -- returns the first match directly instead of an array (404s if there are none). */
|
|
15
|
+
first?: boolean;
|
|
16
|
+
/** Include created_at/updated_at in each returned entry. */
|
|
17
|
+
timestamps?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* docs/ADVANCED-USE-CASES-IMPLEMENTATION-PLAN.md §4.2 -- filter to one
|
|
20
|
+
* locale's entries. Omitted matches the project's default locale (and
|
|
21
|
+
* any entry created before multi-locale existed, which has no locale
|
|
22
|
+
* tag at all) -- not "every locale mixed together". Combine with
|
|
23
|
+
* `first` (via search()) to fetch one specific logical entry's
|
|
24
|
+
* translation, e.g. `search({where: {slug: 'my-post'}, first: true,
|
|
25
|
+
* locale: 'ar'})` -- if no `ar` row exists for that filter, the API
|
|
26
|
+
* falls back to the default locale once before 404ing, so this never
|
|
27
|
+
* silently returns a translation you didn't ask for EXCEPT as an
|
|
28
|
+
* explicit last resort.
|
|
29
|
+
*/
|
|
30
|
+
locale?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Typed access to one content collection's entries. `T` is whatever
|
|
34
|
+
* shape you expect back (the API's actual response is a plain object per
|
|
35
|
+
* the collection's own fields, so this is a cast you opt into, not
|
|
36
|
+
* something the SDK can verify -- see your project's SDK Docs tab for
|
|
37
|
+
* that collection's real field list).
|
|
38
|
+
*/
|
|
39
|
+
export declare class ContentResource<T = Record<string, unknown>> {
|
|
40
|
+
private readonly app;
|
|
41
|
+
private readonly slug;
|
|
42
|
+
constructor(app: VeroXMApp, slug: string);
|
|
43
|
+
private root;
|
|
44
|
+
list(options?: ListOptions): Promise<T[]>;
|
|
45
|
+
/** Same filters as list(), sent as a JSON body -- use this for `where`/`whereRelation`, which are awkward to express as query-string params. */
|
|
46
|
+
search(options: ListOptions): Promise<T[]>;
|
|
47
|
+
/** A typed shortcut for search({...options, count: true}) -- the API returns a bare number for a counting query, not a list. */
|
|
48
|
+
count(options?: Omit<ListOptions, 'count' | 'first'>): Promise<number>;
|
|
49
|
+
/**
|
|
50
|
+
* Only ever returns a PUBLISHED record -- the API's single-item lookup
|
|
51
|
+
* has no `state` override, so a draft id 404s here even right after
|
|
52
|
+
* create({draft: true}); use list({state: 'only_draft'}) to find/inspect
|
|
53
|
+
* drafts instead.
|
|
54
|
+
*
|
|
55
|
+
* No `locale` option here (unlike list()/search()/count()) -- `id`
|
|
56
|
+
* already identifies one exact row, which has exactly one locale;
|
|
57
|
+
* there's no "translation of this same id" to select between. To fetch
|
|
58
|
+
* a specific locale's entry, filter list()/search() by whatever field
|
|
59
|
+
* identifies the logical entry (e.g. `slug`) plus `locale`, not by id.
|
|
60
|
+
*/
|
|
61
|
+
get(id: number, options?: {
|
|
62
|
+
timestamps?: boolean;
|
|
63
|
+
}): Promise<T>;
|
|
64
|
+
/** Fields are sent flat (no wrapper). Pass `draft: true` to create without publishing; omit it (or pass false) to publish immediately. */
|
|
65
|
+
create(data: Record<string, unknown>): Promise<T>;
|
|
66
|
+
/**
|
|
67
|
+
* A partial update -- only the fields present in `data` are changed.
|
|
68
|
+
* Publish state follows the same rule as create(): omitting `draft` (or
|
|
69
|
+
* passing `draft: false`) PUBLISHES the record immediately, even if it
|
|
70
|
+
* was previously a draft and this update doesn't touch content fields.
|
|
71
|
+
* Pass `draft: true` explicitly to keep (or return) it unpublished.
|
|
72
|
+
*/
|
|
73
|
+
update(id: number, data: Record<string, unknown>): Promise<T>;
|
|
74
|
+
delete(id: number): Promise<void>;
|
|
75
|
+
}
|