@veroxm/sdk 0.1.1 → 0.3.0

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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - `app.functions` (call functions with an HTTP trigger), `app.tasks` (process tasks for end users and server keys)
6
+ and `app.processes` (start runs and read them, server keys).
7
+ - Types generated from the API's OpenAPI document (`/public/v2/openapi.json`): `MediaItem`, `Account`,
8
+ `AuthUser` and the rest are the API's own schemas, exported as `Schemas`, with `ApiPaths` and `ApiOperations`.
9
+ `MediaItem` gains the WebP addresses, tags, focal point and hotspots the API already sent.
10
+ - `ExperienceDecision.reason` includes `'holdout'` (a visitor in the impact holdout): show your default.
11
+ - Fixed: for the API framework's own errors (a malformed id, a body that fails validation),
12
+ `VeroXMApiError.message` is the reason, such as "Validation failed (numeric string is expected)", not "Bad Request".
13
+
14
+ ## 0.2.0
15
+
16
+ - End-user accounts on `app.auth`: `signUp`, `verifyEmail`, `resendVerification`, `signInWithEmail`,
17
+ `requestPasswordReset`, `resetPassword`, `acceptInvite`, `currentUser`, `onAuthStateChange`,
18
+ `getAccount`, `updateAccount`, `changePassword`, `deleteAccount`.
19
+ - Social sign-in with PKCE: `socialProviders`, `signInWithRedirect` and `completeSignInWithRedirect`
20
+ in a browser, `startSocialSignIn` and `exchangeSocialCode` for apps.
21
+ - `signOut()` also revokes the refresh token on the server.
22
+ - `VeroXMApiError.code`: the API's reason, such as `email_not_verified`.
23
+
3
24
  ## 0.1.1
4
25
 
5
26
  - First release published from CI with npm trusted publishing. No code changes.
package/README.md CHANGED
@@ -106,7 +106,8 @@ between there.
106
106
  for server-to-server use where there's no per-user identity; never
107
107
  expires, nothing to refresh.
108
108
  - **`signInWithCredentials(username, password)`** -- the login flow from a
109
- project's Authentication tab. Returns a 1-hour access token plus a
109
+ project's Authentication tab (for built-in accounts, `signInWithEmail`
110
+ and the rest of [End-user accounts](#end-user-accounts)). Returns a 1-hour access token plus a
110
111
  30-day refresh token; `VeroXMAuth` refreshes automatically, a little
111
112
  before actual expiry, and again on demand if a request still comes back
112
113
  `401` (clock skew, or a token revoked server-side). You never need to
@@ -133,6 +134,59 @@ app.auth.onTokenChange((accessToken) => {
133
134
  });
134
135
  ```
135
136
 
137
+ ## End-user accounts
138
+
139
+ When the project has built-in accounts turned on (Developer > Authentication
140
+ > Accounts), your app can sign people up and in without a server of its own.
141
+ Every way of signing in ends in the same session, refreshed automatically.
142
+
143
+ ```ts
144
+ // Sign up. When the project wants emails confirmed, the person gets a 6-digit code.
145
+ const result = await app.auth.signUp({ email, password, name });
146
+ if ('verificationSent' in result) {
147
+ await app.auth.verifyEmail({ email, code }); // or { token } from the email's link
148
+ }
149
+
150
+ await app.auth.signInWithEmail(email, password);
151
+ app.auth.currentUser(); // { id, email, name, roles, emailVerified }
152
+
153
+ // Forgotten password
154
+ await app.auth.requestPasswordReset(email);
155
+ await app.auth.resetPassword({ email, code, password: newPassword });
156
+
157
+ // An admin's invitation
158
+ await app.auth.acceptInvite({ email, code, password, name });
159
+
160
+ // The signed-in person's own account
161
+ await app.auth.getAccount(); // also abilities, hasPassword, signInMethods
162
+ await app.auth.updateAccount({ name: 'Amira K' });
163
+ await app.auth.changePassword({ currentPassword, newPassword });
164
+ await app.auth.deleteAccount({ password });
165
+
166
+ app.auth.onAuthStateChange((user) => render(user));
167
+ await app.auth.signOut();
168
+ ```
169
+
170
+ ### Google, Microsoft, Apple
171
+
172
+ In a browser, one call leaves for the provider, and one call on your
173
+ redirect page finishes. `redirectUri` must be one of the project's redirect
174
+ addresses. The PKCE verifier waits in `sessionStorage` meanwhile.
175
+
176
+ ```ts
177
+ const providers = await app.auth.socialProviders(); // [{ key: 'google', name: 'Google', ... }]
178
+ await app.auth.signInWithRedirect('google', { redirectUri: 'https://app.example.com/auth/done' });
179
+
180
+ // on https://app.example.com/auth/done
181
+ const user = await app.auth.completeSignInWithRedirect();
182
+ ```
183
+
184
+ In a mobile app, open the URL from `startSocialSignIn` in the system browser,
185
+ keep its `codeVerifier` and `state`, and when your app is opened with the
186
+ redirect address, check the `state` and call
187
+ `exchangeSocialCode(code, codeVerifier)`. React Native needs a Web Crypto
188
+ polyfill (such as `react-native-quick-crypto`) for the PKCE challenge.
189
+
136
190
  ## Visitor tracking (Experience OS)
137
191
 
138
192
  Record page views and actions, the visitor's consent, and who they are, so
@@ -185,7 +239,7 @@ and/or a JSON config.
185
239
 
186
240
  ```ts
187
241
  const d = await tracker.getExperience<HeroEntry, { cta?: string }>('home.hero');
188
- if (d.reason === 'none') renderDefaultHero();
242
+ if (d.reason === 'none' || d.reason === 'holdout') renderDefaultHero();
189
243
  else renderHero(d.content ?? defaultHero, d.config?.cta);
190
244
 
191
245
  // A config-only experience doubles as a feature flag:
@@ -197,6 +251,8 @@ const stop = tracker.subscribe(() => rerenderExperiences());
197
251
 
198
252
  - **Never throws.** Errors and timeouts (`timeoutMs`, default 1500) resolve
199
253
  to `reason: 'none'` with `error` set -- show your default.
254
+ - **Holdout:** a visitor in the project's impact holdout gets
255
+ `reason: 'holdout'` -- show your default for that too.
200
256
  - **Consent:** before analytics consent it resolves to `'none'` with
201
257
  `waitingForConsent: true` and makes no request (a sticky assignment needs
202
258
  a stored visitor id, and the server records an exposure). Segment
@@ -227,10 +283,52 @@ read; otherwise (and to fill a short list) you get the most-read entries.
227
283
  What the visitor already read is left out of personal results. Never
228
284
  throws: an error returns an empty list with `error` set.
229
285
 
286
+ ## Functions, tasks and processes
287
+
288
+ ```ts
289
+ // A function with an HTTP trigger (Developer > Functions). JSON comes back parsed,
290
+ // text as a string, and null when the function returned nothing.
291
+ const quote = await app.functions.call<{ total: number }>('price-quote', { items: [1, 2] });
292
+ const hello = await app.functions.get<string>('greet', { name: 'Amira' });
293
+
294
+ // Process tasks: a signed-in person's own, or any of the project's with a server key.
295
+ const tasks = await app.tasks.list(); // open ones; { status, entryId } to filter
296
+ const task = await app.tasks.get(tasks[0].id); // task.record: the entry's current values
297
+ await app.tasks.complete(task.id, 'approve', { note: 'Looks good' });
298
+
299
+ // Processes, from your server (a key with every ability).
300
+ const { runId } = await app.processes.start('onboarding', entryId, { plan: 'gold' });
301
+ const run = await app.processes.run(runId); // run.activity: what each step did
302
+ ```
303
+
304
+ A function that fails rejects with `VeroXMApiError` whose `code` is
305
+ `function_error` (the error is in the call log), `function_timeout`,
306
+ `function_limit` (the month's limit is used up) or `functions_disabled`.
307
+ A process that can't start rejects with a 409 and `code` `already_running`,
308
+ `already_ran`, `not_live` or `no_entry`.
309
+
310
+ ## Types from the API
311
+
312
+ The SDK's types are generated from the public API's OpenAPI document, which
313
+ the API serves at `/public/v2/openapi.json`, so they can't drift from what it
314
+ sends. They're exported too:
315
+
316
+ ```ts
317
+ import type { Schemas, ApiPaths, ApiOperations } from '@veroxm/sdk';
318
+
319
+ type Task = Schemas['Task'];
320
+ type Decision = Schemas['Decision'];
321
+ ```
322
+
323
+ `ApiPaths` works with typed fetch helpers such as `openapi-fetch` if you
324
+ call a route the SDK doesn't wrap.
325
+
230
326
  ## Errors
231
327
 
232
- Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, and a
233
- `.message` extracted from whichever error shape the API used). A request
328
+ Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, a
329
+ `.message` extracted from whichever error shape the API used, and `.code`
330
+ when the API gave a reason, such as `email_not_verified`, `invalid_code`,
331
+ `sign_up_closed` or `too_many_attempts`). A request
234
332
  made before any sign-in call throws `VeroXMNotAuthenticatedError`.
235
333
 
236
334
  ```ts
package/dist/auth.d.ts CHANGED
@@ -1,4 +1,31 @@
1
- import type { TokenStorage } from './token-storage.js';
1
+ import type { AuthUser, TokenStorage } from './token-storage.js';
2
+ import type { Schemas } from './schemas.js';
3
+ /** A code from an email, with the address; or the token from the email's link. */
4
+ export type EmailCode = {
5
+ email: string;
6
+ code: string;
7
+ } | {
8
+ token: string;
9
+ };
10
+ /**
11
+ * The signed-in person's account, from `getAccount()`. `signInMethods`: `password`, a social provider's key such as
12
+ * `google`, or `identity_provider`.
13
+ */
14
+ export type Account = Schemas['Account'];
15
+ /** A social sign-in option to show a button for. */
16
+ export type SocialProvider = Schemas['SocialProvider'];
17
+ /** What `startSocialSignIn` returns: send the person to `url`, keep the rest until they come back. */
18
+ export interface SocialSignInStart {
19
+ url: string;
20
+ codeVerifier: string;
21
+ state: string;
22
+ }
23
+ /** Where a sign-in in progress keeps its verifier across the redirect (sessionStorage in a browser). */
24
+ export interface PendingStore {
25
+ get(key: string): string | null;
26
+ set(key: string, value: string): void;
27
+ remove(key: string): void;
28
+ }
2
29
  /**
3
30
  * Handles both auth modes this SDK supports:
4
31
  * - `signInWithApiKey` -- a static project API key (Sanctum-style,
@@ -9,21 +36,108 @@ import type { TokenStorage } from './token-storage.js';
9
36
  * token plus a refresh token; this class refreshes silently and
10
37
  * transparently as needed, the same "just works" feel as Firebase
11
38
  * Auth's token refresh.
39
+ *
40
+ * And the project's built-in accounts on top of the second: sign-up, email
41
+ * codes, password reset, invitations, the signed-in person's own account,
42
+ * and social sign-in (Google, Microsoft, Apple...) with PKCE. Every way of
43
+ * signing in ends in the same session, refreshed the same way.
12
44
  */
13
45
  export declare class VeroXMAuth {
14
46
  private readonly apiBase;
15
47
  private readonly storage;
48
+ private readonly pending;
16
49
  private apiKey;
17
50
  private session;
18
51
  private loadedFromStorage;
19
52
  private refreshInFlight;
20
53
  private readonly listeners;
21
- constructor(apiBase: string, storage: TokenStorage);
54
+ private readonly userListeners;
55
+ constructor(apiBase: string, storage: TokenStorage, pending?: PendingStore);
22
56
  /** Static-key mode: no login round-trip, no expiry, no refresh token. */
23
57
  signInWithApiKey(apiKey: string): void;
24
58
  /** Username/password mode -- exchanges credentials for an access+refresh token pair and persists it via the configured TokenStorage. */
25
59
  signInWithCredentials(username: string, password: string): Promise<void>;
60
+ /** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
61
+ signInWithEmail(email: string, password: string): Promise<AuthUser | null>;
62
+ /** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
26
63
  signOut(): Promise<void>;
64
+ /**
65
+ * Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
66
+ * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
67
+ */
68
+ signUp(input: {
69
+ email: string;
70
+ password: string;
71
+ name?: string;
72
+ }): Promise<{
73
+ verificationSent: true;
74
+ } | {
75
+ user: AuthUser | null;
76
+ }>;
77
+ /** Confirms the email with its code (or the link's token) and signs the person in. */
78
+ verifyEmail(input: EmailCode): Promise<AuthUser | null>;
79
+ /** Sends a new confirmation code. Resolves the same whether or not the address has an account. */
80
+ resendVerification(email: string): Promise<void>;
81
+ /** Emails a password reset code. Resolves the same whether or not the address has an account. */
82
+ requestPasswordReset(email: string): Promise<void>;
83
+ /** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
84
+ resetPassword(input: EmailCode & {
85
+ password: string;
86
+ }): Promise<AuthUser | null>;
87
+ /** Accepts an invitation: chooses a password (and a name) with the invitation's code or link token, and signs in. */
88
+ acceptInvite(input: EmailCode & {
89
+ password: string;
90
+ name?: string;
91
+ }): Promise<AuthUser | null>;
92
+ /** Who is signed in, as of the last sign-in or refresh; null when signed out or using an API key. */
93
+ currentUser(): AuthUser | null;
94
+ /** Called with the person whenever they sign in, change, or sign out (and once now). Returns an unsubscribe function. */
95
+ onAuthStateChange(listener: (user: AuthUser | null) => void): () => void;
96
+ /** Loads a stored session (from a previous visit), so currentUser() knows who's signed in. */
97
+ ready(): Promise<void>;
98
+ /** The signed-in person's account, fresh from the API. */
99
+ getAccount(): Promise<Account>;
100
+ /** Changes the signed-in person's name. */
101
+ updateAccount(input: {
102
+ name: string | null;
103
+ }): Promise<Account>;
104
+ /** Changes the password (the current one is needed when there is one). Other devices are signed out; this one stays in. */
105
+ changePassword(input: {
106
+ currentPassword?: string;
107
+ newPassword: string;
108
+ }): Promise<void>;
109
+ /** Deletes the signed-in person's account (their password is needed when they have one), then signs out here. */
110
+ deleteAccount(input?: {
111
+ password?: string;
112
+ }): Promise<void>;
113
+ /** The social sign-in options the project has turned on, for your buttons. */
114
+ socialProviders(): Promise<SocialProvider[]>;
115
+ /**
116
+ * Starts a social sign-in and returns where to send the person. `redirectUri` must be one of the project's redirect
117
+ * addresses (Developer > Authentication > Accounts). Keep `codeVerifier` and `state` until they come back; in a
118
+ * browser, `signInWithRedirect` does all of this for you.
119
+ */
120
+ startSocialSignIn(provider: string, options: {
121
+ redirectUri: string;
122
+ state?: string;
123
+ }): Promise<SocialSignInStart>;
124
+ /** Trades the code the person came back with, and the verifier from `startSocialSignIn`, for a session. */
125
+ exchangeSocialCode(code: string, codeVerifier: string): Promise<AuthUser | null>;
126
+ /** Browser: starts a social sign-in and leaves the page for the provider. Finish on the redirect page with `completeSignInWithRedirect()`. */
127
+ signInWithRedirect(provider: string, options: {
128
+ redirectUri: string;
129
+ }): Promise<void>;
130
+ /**
131
+ * On the redirect page (or with the address an app was opened with): checks the `state`, trades the code, and signs the
132
+ * person in. Resolves null when the address has no sign-in result; throws when the provider or VeroXM refused it
133
+ * (the error's `code` is the `error` the page came back with, e.g. `access_denied` or `sign_up_closed`).
134
+ */
135
+ completeSignInWithRedirect(url?: string): Promise<AuthUser | null>;
136
+ private signInWith;
137
+ private post;
138
+ /** A call as the signed-in person (not with an API key). */
139
+ private authed;
140
+ private updateStoredUser;
27
141
  /** 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
142
  currentAbilities(): string[] | null;
29
143
  /** 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. */
@@ -37,4 +151,5 @@ export declare class VeroXMAuth {
37
151
  private refresh;
38
152
  private persistSession;
39
153
  private notify;
154
+ private notifyUser;
40
155
  }
package/dist/auth.js CHANGED
@@ -1,5 +1,20 @@
1
1
  import { rawRequest } from './http.js';
2
2
  import { VeroXMNotAuthenticatedError } from './errors.js';
3
+ import { createPkce, randomString } from './pkce.js';
4
+ function defaultPendingStore() {
5
+ try {
6
+ if (typeof window !== 'undefined' && window.sessionStorage) {
7
+ const ss = window.sessionStorage;
8
+ return { get: (k) => ss.getItem(k), set: (k, v) => ss.setItem(k, v), remove: (k) => ss.removeItem(k) };
9
+ }
10
+ }
11
+ catch {
12
+ // storage blocked: fall through to memory
13
+ }
14
+ const m = new Map();
15
+ return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v), remove: (k) => void m.delete(k) };
16
+ }
17
+ const PENDING_KEY = 'veroxm:social-sign-in';
3
18
  // Refresh a little before the token actually expires, not exactly at the
4
19
  // deadline -- covers clock skew and the time an in-flight request spends
5
20
  // on the wire between "token looked valid" and "server received it".
@@ -14,16 +29,23 @@ const REFRESH_SKEW_MS = 30000;
14
29
  * token plus a refresh token; this class refreshes silently and
15
30
  * transparently as needed, the same "just works" feel as Firebase
16
31
  * Auth's token refresh.
32
+ *
33
+ * And the project's built-in accounts on top of the second: sign-up, email
34
+ * codes, password reset, invitations, the signed-in person's own account,
35
+ * and social sign-in (Google, Microsoft, Apple...) with PKCE. Every way of
36
+ * signing in ends in the same session, refreshed the same way.
17
37
  */
18
38
  export class VeroXMAuth {
19
- constructor(apiBase, storage) {
39
+ constructor(apiBase, storage, pending = defaultPendingStore()) {
20
40
  this.apiBase = apiBase;
21
41
  this.storage = storage;
42
+ this.pending = pending;
22
43
  this.apiKey = null;
23
44
  this.session = null;
24
45
  this.loadedFromStorage = false;
25
46
  this.refreshInFlight = null;
26
47
  this.listeners = new Set();
48
+ this.userListeners = new Set();
27
49
  }
28
50
  /** Static-key mode: no login round-trip, no expiry, no refresh token. */
29
51
  signInWithApiKey(apiKey) {
@@ -42,12 +64,172 @@ export class VeroXMAuth {
42
64
  this.apiKey = null;
43
65
  await this.persistSession(data);
44
66
  }
67
+ /** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
68
+ async signInWithEmail(email, password) {
69
+ await this.signInWithCredentials(email, password);
70
+ return this.currentUser();
71
+ }
72
+ /** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
45
73
  async signOut() {
74
+ if (!this.loadedFromStorage)
75
+ this.session = await this.storage.get();
76
+ const refreshToken = this.session?.refreshToken;
46
77
  this.apiKey = null;
47
78
  this.session = null;
48
79
  this.loadedFromStorage = true;
49
80
  await this.storage.clear();
50
81
  this.notify(null);
82
+ if (refreshToken)
83
+ await rawRequest(this.apiBase, { method: 'POST', path: '/auth/logout', json: { refreshToken } }).catch(() => undefined);
84
+ }
85
+ // ------------------------------------------------------------------ built-in accounts
86
+ /**
87
+ * Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
88
+ * gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
89
+ */
90
+ async signUp(input) {
91
+ const data = (await this.post('/auth/signup', input));
92
+ if ('accessToken' in data) {
93
+ await this.persistSession(data);
94
+ return { user: this.currentUser() };
95
+ }
96
+ return { verificationSent: true };
97
+ }
98
+ /** Confirms the email with its code (or the link's token) and signs the person in. */
99
+ async verifyEmail(input) {
100
+ return this.signInWith('/auth/verify', input);
101
+ }
102
+ /** Sends a new confirmation code. Resolves the same whether or not the address has an account. */
103
+ async resendVerification(email) {
104
+ await this.post('/auth/verify/resend', { email });
105
+ }
106
+ /** Emails a password reset code. Resolves the same whether or not the address has an account. */
107
+ async requestPasswordReset(email) {
108
+ await this.post('/auth/password/forgot', { email });
109
+ }
110
+ /** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
111
+ async resetPassword(input) {
112
+ return this.signInWith('/auth/password/reset', input);
113
+ }
114
+ /** Accepts an invitation: chooses a password (and a name) with the invitation's code or link token, and signs in. */
115
+ async acceptInvite(input) {
116
+ return this.signInWith('/auth/invite/accept', input);
117
+ }
118
+ /** Who is signed in, as of the last sign-in or refresh; null when signed out or using an API key. */
119
+ currentUser() {
120
+ return this.session?.user ?? null;
121
+ }
122
+ /** Called with the person whenever they sign in, change, or sign out (and once now). Returns an unsubscribe function. */
123
+ onAuthStateChange(listener) {
124
+ this.userListeners.add(listener);
125
+ void this.ready().then(() => this.userListeners.has(listener) && listener(this.currentUser()));
126
+ return () => this.userListeners.delete(listener);
127
+ }
128
+ /** Loads a stored session (from a previous visit), so currentUser() knows who's signed in. */
129
+ async ready() {
130
+ if (!this.loadedFromStorage) {
131
+ this.session = await this.storage.get();
132
+ this.loadedFromStorage = true;
133
+ }
134
+ }
135
+ /** The signed-in person's account, fresh from the API. */
136
+ async getAccount() {
137
+ const account = (await this.authed('GET', '/auth/me'));
138
+ await this.updateStoredUser(account);
139
+ return account;
140
+ }
141
+ /** Changes the signed-in person's name. */
142
+ async updateAccount(input) {
143
+ const account = (await this.authed('PATCH', '/auth/me', input));
144
+ await this.updateStoredUser(account);
145
+ return account;
146
+ }
147
+ /** Changes the password (the current one is needed when there is one). Other devices are signed out; this one stays in. */
148
+ async changePassword(input) {
149
+ const data = (await this.authed('POST', '/auth/me/password', input));
150
+ await this.persistSession(data);
151
+ }
152
+ /** Deletes the signed-in person's account (their password is needed when they have one), then signs out here. */
153
+ async deleteAccount(input = {}) {
154
+ await this.authed('DELETE', '/auth/me', input);
155
+ this.session = null;
156
+ await this.storage.clear();
157
+ this.notify(null);
158
+ }
159
+ // ------------------------------------------------------------------ social sign-in
160
+ /** The social sign-in options the project has turned on, for your buttons. */
161
+ async socialProviders() {
162
+ return (await rawRequest(this.apiBase, { path: '/auth/social' }));
163
+ }
164
+ /**
165
+ * Starts a social sign-in and returns where to send the person. `redirectUri` must be one of the project's redirect
166
+ * addresses (Developer > Authentication > Accounts). Keep `codeVerifier` and `state` until they come back; in a
167
+ * browser, `signInWithRedirect` does all of this for you.
168
+ */
169
+ async startSocialSignIn(provider, options) {
170
+ const { codeVerifier, codeChallenge } = await createPkce();
171
+ const state = options.state ?? (await randomString(16));
172
+ const base = this.apiBase.endsWith('/') ? this.apiBase : `${this.apiBase}/`;
173
+ const url = new URL(`auth/social/${encodeURIComponent(provider)}/start`, base);
174
+ url.searchParams.set('redirect_uri', options.redirectUri);
175
+ url.searchParams.set('state', state);
176
+ url.searchParams.set('code_challenge', codeChallenge);
177
+ url.searchParams.set('code_challenge_method', 'S256');
178
+ return { url: url.toString(), codeVerifier, state };
179
+ }
180
+ /** Trades the code the person came back with, and the verifier from `startSocialSignIn`, for a session. */
181
+ async exchangeSocialCode(code, codeVerifier) {
182
+ return this.signInWith('/auth/social/token', { code, codeVerifier });
183
+ }
184
+ /** Browser: starts a social sign-in and leaves the page for the provider. Finish on the redirect page with `completeSignInWithRedirect()`. */
185
+ async signInWithRedirect(provider, options) {
186
+ const start = await this.startSocialSignIn(provider, options);
187
+ this.pending.set(PENDING_KEY, JSON.stringify({ codeVerifier: start.codeVerifier, state: start.state }));
188
+ window.location.assign(start.url);
189
+ }
190
+ /**
191
+ * On the redirect page (or with the address an app was opened with): checks the `state`, trades the code, and signs the
192
+ * person in. Resolves null when the address has no sign-in result; throws when the provider or VeroXM refused it
193
+ * (the error's `code` is the `error` the page came back with, e.g. `access_denied` or `sign_up_closed`).
194
+ */
195
+ async completeSignInWithRedirect(url = typeof window !== 'undefined' ? window.location.href : '') {
196
+ const params = new URL(url).searchParams;
197
+ const raw = this.pending.get(PENDING_KEY);
198
+ if (!params.has('code') && !params.has('error'))
199
+ return null;
200
+ this.pending.remove(PENDING_KEY);
201
+ const pending = raw ? JSON.parse(raw) : null;
202
+ if (!pending || params.get('state') !== pending.state) {
203
+ throw Object.assign(new Error("This sign-in wasn't started here, or it was already finished. Start it again."), { code: 'state_mismatch' });
204
+ }
205
+ const error = params.get('error');
206
+ if (error)
207
+ throw Object.assign(new Error(params.get('error_description') ?? 'The sign-in was refused.'), { code: error });
208
+ return this.exchangeSocialCode(params.get('code'), pending.codeVerifier);
209
+ }
210
+ async signInWith(path, body) {
211
+ const data = (await this.post(path, body));
212
+ this.apiKey = null;
213
+ await this.persistSession(data);
214
+ return this.currentUser();
215
+ }
216
+ post(path, json) {
217
+ return rawRequest(this.apiBase, { method: 'POST', path, json });
218
+ }
219
+ /** A call as the signed-in person (not with an API key). */
220
+ async authed(method, path, json) {
221
+ if (this.apiKey)
222
+ throw new VeroXMNotAuthenticatedError();
223
+ const token = await this.getAccessToken();
224
+ return rawRequest(this.apiBase, { method, path, ...(json !== undefined ? { json } : {}), headers: { Authorization: `Bearer ${token}` } });
225
+ }
226
+ async updateStoredUser(account) {
227
+ if (!this.session)
228
+ return;
229
+ const user = { id: account.id, email: account.email, name: account.name, roles: account.roles, emailVerified: account.emailVerified };
230
+ this.session = { ...this.session, user, abilities: account.abilities };
231
+ await this.storage.set(this.session);
232
+ this.notifyUser();
51
233
  }
52
234
  /** 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
235
  currentAbilities() {
@@ -110,6 +292,7 @@ export class VeroXMAuth {
110
292
  refreshToken: data.refreshToken,
111
293
  expiresAt: Date.now() + data.expiresIn * 1000,
112
294
  abilities: data.abilities,
295
+ user: data.user ?? this.session?.user ?? null,
113
296
  };
114
297
  this.session = session;
115
298
  this.loadedFromStorage = true;
@@ -119,5 +302,11 @@ export class VeroXMAuth {
119
302
  notify(accessToken) {
120
303
  for (const listener of this.listeners)
121
304
  listener(accessToken);
305
+ this.notifyUser();
306
+ }
307
+ notifyUser() {
308
+ const user = this.currentUser();
309
+ for (const listener of this.userListeners)
310
+ listener(user);
122
311
  }
123
312
  }
package/dist/client.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import { type RawRequestOptions } from './http.js';
2
- import { VeroXMAuth } from './auth.js';
2
+ import { VeroXMAuth, type PendingStore } from './auth.js';
3
3
  import { ContentResource } from './content.js';
4
4
  import { MediaResource } from './media.js';
5
+ import { FunctionsResource } from './functions.js';
6
+ import { TasksResource } from './tasks.js';
7
+ import { ProcessesResource } from './processes.js';
5
8
  import { type TokenStorage } from './token-storage.js';
6
9
  export interface VeroXMAppOptions {
7
10
  /** Your VeroXM deployment's origin, e.g. "https://cms.example.com" -- no trailing /public/... needed, VeroXMApp builds that itself. */
@@ -10,14 +13,22 @@ export interface VeroXMAppOptions {
10
13
  projectId: string;
11
14
  /** 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
15
  tokenStorage?: TokenStorage;
16
+ /** Where a social sign-in keeps its verifier while the person is at the provider. Defaults to sessionStorage in a browser. */
17
+ pendingStore?: PendingStore;
13
18
  }
14
19
  /**
15
20
  * 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.
21
+ * then `app.auth`, `app.content(slug)`, `app.media()`, `app.functions`,
22
+ * `app.tasks` and `app.processes` for everything else. See this package's README for a full quickstart.
18
23
  */
19
24
  export declare class VeroXMApp {
20
25
  readonly auth: VeroXMAuth;
26
+ /** Project functions with an HTTP trigger: `app.functions.call('quote', {items})`. */
27
+ readonly functions: FunctionsResource;
28
+ /** Process tasks: an end user's own, or any of the project's with a server key. */
29
+ readonly tasks: TasksResource;
30
+ /** Start processes and read their runs (server keys). */
31
+ readonly processes: ProcessesResource;
21
32
  private readonly apiBase;
22
33
  private constructor();
23
34
  static initializeApp(options: VeroXMAppOptions): VeroXMApp;
package/dist/client.js CHANGED
@@ -3,6 +3,9 @@ import { VeroXMApiError } from './errors.js';
3
3
  import { VeroXMAuth } from './auth.js';
4
4
  import { ContentResource } from './content.js';
5
5
  import { MediaResource } from './media.js';
6
+ import { FunctionsResource } from './functions.js';
7
+ import { TasksResource } from './tasks.js';
8
+ import { ProcessesResource } from './processes.js';
6
9
  import { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
7
10
  function defaultTokenStorage(projectId) {
8
11
  if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {
@@ -12,18 +15,21 @@ function defaultTokenStorage(projectId) {
12
15
  }
13
16
  /**
14
17
  * 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.
18
+ * then `app.auth`, `app.content(slug)`, `app.media()`, `app.functions`,
19
+ * `app.tasks` and `app.processes` for everything else. See this package's README for a full quickstart.
17
20
  */
18
21
  export class VeroXMApp {
19
- constructor(apiBase, tokenStorage) {
22
+ constructor(apiBase, tokenStorage, pendingStore) {
20
23
  this.apiBase = apiBase;
21
- this.auth = new VeroXMAuth(apiBase, tokenStorage);
24
+ this.auth = new VeroXMAuth(apiBase, tokenStorage, pendingStore);
25
+ this.functions = new FunctionsResource(this);
26
+ this.tasks = new TasksResource(this);
27
+ this.processes = new ProcessesResource(this);
22
28
  }
23
29
  static initializeApp(options) {
24
30
  const base = options.baseUrl.replace(/\/$/, '');
25
31
  const apiBase = `${base}/public/v2/projects/${options.projectId}`;
26
- return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId));
32
+ return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId), options.pendingStore);
27
33
  }
28
34
  /** Typed access to one content collection's entries (list/get/create/update/delete/search). */
29
35
  content(collectionSlug) {
package/dist/errors.d.ts CHANGED
@@ -10,6 +10,11 @@
10
10
  export declare class VeroXMApiError extends Error {
11
11
  readonly status: number;
12
12
  readonly body: unknown;
13
+ /**
14
+ * The API's machine-readable reason, when it gave one: e.g. `email_not_verified`, `invalid_code`,
15
+ * `sign_up_closed`, `too_many_attempts`, `access_denied`, `function_limit`.
16
+ */
17
+ readonly code: string | undefined;
13
18
  constructor(status: number, body: unknown);
14
19
  private static messageFrom;
15
20
  }
package/dist/errors.js CHANGED
@@ -13,10 +13,18 @@ export class VeroXMApiError extends Error {
13
13
  this.name = 'VeroXMApiError';
14
14
  this.status = status;
15
15
  this.body = body;
16
+ const c = body && typeof body === 'object' ? body.code : undefined;
17
+ this.code = typeof c === 'string' ? c : undefined;
16
18
  }
17
19
  static messageFrom(status, body) {
18
20
  if (body && typeof body === 'object') {
19
21
  const b = body;
22
+ // The framework's own shape names the status in `error` ("Bad Request") and says what's wrong in `message`.
23
+ const framework = typeof b.statusCode === 'number';
24
+ if (framework && typeof b.message === 'string')
25
+ return b.message;
26
+ if (framework && Array.isArray(b.message))
27
+ return b.message.join(', ');
20
28
  if (typeof b.error === 'string')
21
29
  return b.error;
22
30
  if (typeof b.message === 'string')