@rebasepro/client 0.25.1 → 0.27.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/README.md CHANGED
@@ -34,7 +34,7 @@ of it resolves too: Node has supported `require(esm)` since 22.12.
34
34
  |---|---|
35
35
  | `createRebaseClient<DB>(options)` | Create a client instance. Generic `DB` parameter enables type-safe `client.data.*` access. |
36
36
  | `CreateRebaseClientResult<DB>` | The client type it returns (`RebaseClient<DB>` from `@rebasepro/types`, narrowed) — includes `auth`, `admin`, `cron`, `functions`, `storage`, `ws`, `data`, `call`, and token management methods. |
37
- | `CreateRebaseClientOptions` | Extends `RebaseClientConfig` with the `auth`, `admin`, `cron`, `apiKeys` and `personalKeys` sub-configs, plus `storageSources`, `collections` and `offline`. |
37
+ | `CreateRebaseClientOptions` | Extends `RebaseClientConfig` with the `auth`, `admin`, `cron`, `apiKeys` and `personalKeys` sub-configs, plus `storageSources`, `collections`, `offline` and `debug`. |
38
38
 
39
39
  ### Config
40
40
 
@@ -49,6 +49,7 @@ of it resolves too: Node has supported `require(esm)` since 22.12.
49
49
  | `realtime` | `boolean` | `true` | Open the WebSocket — `false` lets a one-shot script exit |
50
50
  | `collections` | `Record<string, string>` | — | Maps accessor names to collection slugs |
51
51
  | `offline` | `boolean \| OfflineConfig` | `false` | Local-first sync — see [the docs](https://rebase.pro/docs/sdk/offline) |
52
+ | `debug` | `boolean` | `false` | Log the realtime connection's progress with `console.debug`. One browser can turn it on with `localStorage.setItem("rebase_debug", "1")` — see [Connection logging](https://rebase.pro/docs/sdk#connection-logging) |
52
53
 
53
54
  ### Tokens
54
55
 
package/dist/admin.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Transport } from "./transport.js";
2
- import type { AdminUser, RoleSummary } from "@rebasepro/types";
2
+ import type { AdminGuest, AdminUser, DeleteGuestsResult, RoleSummary } from "@rebasepro/types";
3
3
  export type { AdminUser };
4
4
  export interface CreateAdminOptions {
5
5
  adminPath?: string;
@@ -11,6 +11,21 @@ export interface ListUsersOptions {
11
11
  offset?: number;
12
12
  orderBy?: string;
13
13
  orderDir?: "asc" | "desc";
14
+ /** Only the users holding this role id (`?role=`). */
15
+ role?: string;
16
+ /**
17
+ * Resolve exactly these users in one round trip (`?ids=`), for turning
18
+ * stored ids into names. The window, search and role are ignored when it
19
+ * is given, and ids that name no user are left out of the answer.
20
+ */
21
+ ids?: readonly string[];
22
+ }
23
+ /** The window and filter `GET /admin/guests` takes. */
24
+ export interface ListGuestsOptions {
25
+ limit?: number;
26
+ offset?: number;
27
+ /** Only the guests last seen before this date. */
28
+ lastSeenBefore?: Date | string;
14
29
  }
15
30
  export declare function createAdmin(transport: Transport, options?: CreateAdminOptions): {
16
31
  listUsers: (options?: ListUsersOptions) => Promise<{
@@ -56,6 +71,19 @@ export declare function createAdmin(transport: Transport, options?: CreateAdminO
56
71
  success: boolean;
57
72
  removedFactors: number;
58
73
  }>;
74
+ listGuests: (options?: ListGuestsOptions) => Promise<{
75
+ guests: AdminGuest[];
76
+ total: number;
77
+ limit: number;
78
+ offset: number;
79
+ }>;
80
+ deleteGuest: (userId: string) => Promise<{
81
+ success: boolean;
82
+ }>;
83
+ deleteGuests: (options: {
84
+ lastSeenBefore: Date | string;
85
+ offset?: number;
86
+ }) => Promise<DeleteGuestsResult>;
59
87
  resetPassword: (userId: string, options?: {
60
88
  password?: string;
61
89
  }) => Promise<{
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The browser half of Sign in with Apple.
3
+ *
4
+ * Apple is the one provider a single-page app cannot take through the usual
5
+ * redirect: asking for the `name` or `email` scope obliges
6
+ * `response_mode=form_post`, so Apple answers with a cross-site POST to the
7
+ * redirect URI — a request a static page never sees. Apple's own JS SDK has a
8
+ * popup mode that hands the answer back to the opening page with
9
+ * `postMessage` instead, and that is what this uses. The redirect URI still
10
+ * has to be listed under the Services ID's Return URLs (HTTPS, no
11
+ * `localhost`), because Apple matches it and the token exchange repeats it.
12
+ *
13
+ * `state` is generated and checked here, which is what binds the code that
14
+ * comes back to the click that started it.
15
+ */
16
+ /** Apple's JS SDK, the only way into its popup mode. */
17
+ export declare const APPLE_JS_SDK_URL = "https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleauth.js";
18
+ /** What `POST /auth/apple` needs from a web sign-in. */
19
+ export interface AppleAuthorization {
20
+ code: string;
21
+ redirectUri: string;
22
+ /**
23
+ * Present on the first authorization only — Apple never sends the name
24
+ * again, so it has to reach the backend on this request or not at all.
25
+ */
26
+ user?: {
27
+ name?: {
28
+ firstName?: string;
29
+ lastName?: string;
30
+ };
31
+ };
32
+ }
33
+ export interface AppleAuthorizationRequest {
34
+ /** The Services ID. */
35
+ clientId: string;
36
+ /**
37
+ * A Return URL registered on the Services ID. Defaults to this page's
38
+ * origin with a trailing slash (`https://app.example.com/`).
39
+ */
40
+ redirectUri?: string;
41
+ }
42
+ /**
43
+ * Start loading Apple's SDK ahead of the click. Worth calling when the sign-in
44
+ * button mounts: with the SDK already on the page, the popup opens in the same
45
+ * task as the click, and Safari blocks a popup that opens later than that.
46
+ */
47
+ export declare function preloadAppleSignIn(): Promise<void>;
48
+ /**
49
+ * Open Apple's sign-in popup and return the authorization code, without
50
+ * spending it. Call it from a click handler: browsers block a popup that no
51
+ * gesture opened. Call {@link preloadAppleSignIn} first (on mount) so the
52
+ * popup does not wait on a script download.
53
+ *
54
+ * Throws a `RebaseClientError` whose `code` is `APPLE_SIGN_IN_CANCELLED` when
55
+ * the visitor closes the popup or declines, `APPLE_SIGN_IN_UNAVAILABLE` when
56
+ * Apple's script cannot load or this is not a browser, and
57
+ * `APPLE_SIGN_IN_FAILED` otherwise.
58
+ */
59
+ export declare function requestAppleAuthorization(request: AppleAuthorizationRequest): Promise<AppleAuthorization>;
package/dist/auth.d.ts CHANGED
@@ -17,6 +17,26 @@ export interface PublicUserProfile {
17
17
  * every backend does send.
18
18
  */
19
19
  export type AuthConfig = AuthConfigDocument;
20
+ /** The body of an Apple sign-in. See `signInWithApple`. */
21
+ export interface AppleSignInPayload {
22
+ /** The authorization code Apple returned. */
23
+ code: string;
24
+ /** Web: the redirect URI the browser authorization used. */
25
+ redirectUri?: string;
26
+ /** Native: the bundle id of the app that obtained the code. */
27
+ bundleId?: string;
28
+ /**
29
+ * The name Apple reports on the first authorization only. An `email`
30
+ * here is ignored — the backend reads the address from Apple's id_token.
31
+ */
32
+ user?: {
33
+ name?: {
34
+ firstName?: string;
35
+ lastName?: string;
36
+ };
37
+ email?: string;
38
+ };
39
+ }
20
40
  export interface AuthStorage {
21
41
  getItem: (key: string) => string | null;
22
42
  setItem: (key: string, value: string) => void;
@@ -29,12 +49,32 @@ export interface CreateAuthOptions {
29
49
  autoRefresh?: boolean;
30
50
  persistSession?: boolean;
31
51
  /**
32
- * Authentication flow mode.
33
- * - 'json' (default): Tokens are sent/received in JSON bodies. Refresh token is stored in local storage.
34
- * - 'cookie': Refresh token is sent/received via httpOnly cookies. Access token remains in memory.
52
+ * Where the refresh token lives.
53
+ * - `"cookie"`: in an HttpOnly cookie the server sets (its `auth.cookieAuth`),
54
+ * out of reach of script on the page. The access token stays in memory.
55
+ * - `"json"`: in the response body, kept in `storage`. For a client with no
56
+ * cookie jar, against a server that does not use `cookieAuth`.
57
+ *
58
+ * Defaults to `"cookie"` in a browser and `"json"` anywhere else, or when
59
+ * `storage` is passed: see {@link resolveAuthFlowMode}.
35
60
  */
36
61
  authFlowMode?: "json" | "cookie";
37
62
  }
63
+ /**
64
+ * The flow mode a client uses when `authFlowMode` is not set.
65
+ *
66
+ * Cookie in a browser. A backend run by the Rebase runtime always keeps the
67
+ * refresh token in a cookie and answers the body's with `""`, so a browser
68
+ * client defaulting to json held nothing to renew with, and was signed out
69
+ * without a word once its access token expired, about an hour after sign-in.
70
+ *
71
+ * Json off the browser (Node, a worker, React Native), where there is no
72
+ * cookie jar to keep it in — and in a browser that passes its own `storage`,
73
+ * which says where the session is to be kept: a second client on the page
74
+ * that keeps its own sign-in apart from the page's cookie. In cookie mode
75
+ * nothing would be kept there, and every reload would lose that sign-in.
76
+ */
77
+ export declare function resolveAuthFlowMode(options?: CreateAuthOptions): "json" | "cookie";
38
78
  /**
39
79
  * Finishing a sign-in that the server refused with `MFA_REQUIRED`.
40
80
  *
@@ -95,12 +135,14 @@ export declare function createAuth(transport: Transport, options?: CreateAuthOpt
95
135
  accessToken: string;
96
136
  refreshToken: string;
97
137
  }>;
98
- signInWithApple: (code: string, redirectUri: string, user?: {
99
- name?: {
100
- firstName?: string;
101
- lastName?: string;
102
- };
103
- email?: string;
138
+ signInWithApple: (payloadOrCode: AppleSignInPayload | string, redirectUri?: string, user?: AppleSignInPayload["user"]) => Promise<{
139
+ user: User;
140
+ accessToken: string;
141
+ refreshToken: string;
142
+ }>;
143
+ signInWithApplePopup: (options?: {
144
+ clientId?: string;
145
+ redirectUri?: string;
104
146
  }) => Promise<{
105
147
  user: User;
106
148
  accessToken: string;
@@ -324,6 +366,7 @@ export declare function createAuth(transport: Transport, options?: CreateAuthOpt
324
366
  }>;
325
367
  getAuthConfig: () => Promise<AuthConfigDocument>;
326
368
  getSession: () => RebaseSession | null;
369
+ getAccessToken: () => Promise<string | null>;
327
370
  onAuthStateChange: (callback: (event: AuthChangeEvent, session: RebaseSession | null) => void) => () => boolean;
328
371
  canRestoreSession: () => boolean;
329
372
  isInitialized: () => Promise<void>;
@@ -8,7 +8,7 @@
8
8
  * package only, so an argument type missing from the barrel is one it has to
9
9
  * spell out by hand or reach into a package it never installed.
10
10
  */
11
- import type { AggregateMeta, AggregateParams, AggregateResult, AggregateRow, AggregateSelect, FieldPath, FilterCondition, FilterConditionFor, FilterValues, IncludeOptions, IncludeSpec, InsertOf, LogicalCondition, LogicalConditionFor, OrderBySpec, QueryComputedFields, RestoreOptions, RowOf, StorageSource, TrashClient, UpdateOf, WhereConditionFor, WhereFilterOp, WhereFor, WhereValueFor, WriteOptions } from "./index.js";
11
+ import type { AggregateMeta, AggregateParams, AggregateResult, AggregateRow, AggregateSelect, FieldPath, FilterCondition, FilterConditionFor, FilterValues, IncludeOptions, IncludeSpec, InsertOf, LogicalCondition, LogicalConditionFor, OrderBySpec, QueryComputedFields, RestoreOptions, RowOf, StorageSource, ClientStorageSource, ClientUploadFileProps, UploadFileResult, TrashClient, UpdateOf, WhereConditionFor, WhereFilterOp, WhereFor, WhereValueFor, WriteOptions } from "./index.js";
12
12
  export type ConsumerCanName = [
13
13
  AggregateMeta,
14
14
  AggregateParams,
@@ -28,6 +28,9 @@ export type ConsumerCanName = [
28
28
  QueryComputedFields,
29
29
  RowOf<Record<string, unknown>>,
30
30
  StorageSource,
31
+ ClientStorageSource,
32
+ ClientUploadFileProps,
33
+ UploadFileResult,
31
34
  UpdateOf<Record<string, unknown>>,
32
35
  WhereConditionFor<string>,
33
36
  WhereFilterOp,
package/dist/index.d.ts CHANGED
@@ -9,11 +9,11 @@ import { createFunctionsClient } from "./functions.js";
9
9
  import { RebaseWebSocketClient } from "./websocket.js";
10
10
  import { RebaseRealtimeChannel, type ChannelOptions } from "./realtime-channel.js";
11
11
  import type { OfflineApi, OfflineConfig } from "./offline.js";
12
- import { type BatchOperation, type BatchResult, type IncludeOf, InsertOf, RebaseClient, RebaseSdkData, RowOf, StorageSource, StorageSourceDefinition, StorageSourceRegistry, UpdateOf, type WriteOptions } from "@rebasepro/types";
12
+ import { type AccessSimulation, type BatchOperation, type BatchResult, type IncludeOf, InsertOf, RebaseClient, RebaseSdkData, RowOf, ClientStorageSource, StorageSource, StorageSourceDefinition, StorageSourceRegistry, UpdateOf, type WriteOptions } from "@rebasepro/types";
13
13
  export { RebaseApiError } from "./transport.js";
14
14
  export { RebaseClientError } from "./errors.js";
15
15
  export type { RebaseErrorCode } from "@rebasepro/types";
16
- export type { RebaseClientConfig, FindParams, FindResponse } from "./transport.js";
16
+ export type { RebaseClientConfig, RealtimeClientOptions, FindParams, FindResponse } from "./transport.js";
17
17
  export type { CollectionClient, RestoreOptions, TrashClient } from "./collection.js";
18
18
  export type { FindResult, SDKCollectionClient, SDKQueryBuilderInterface, PaginationMeta } from "@rebasepro/types";
19
19
  export type { IterateParams, FindAllParams, PageWalkOptions, CursorSpec } from "@rebasepro/types";
@@ -23,9 +23,11 @@ export { or, and, not, cond } from "@rebasepro/common";
23
23
  export { resolveStorageReferences, storageReference, parseStorageReference, isStorageReference, STORAGE_REFERENCE_SCHEME, storageTargetOfDownloadUrl, storageReferencesForDownloadUrls, storageTargetsInText } from "@rebasepro/types";
24
24
  export type { StorageReferenceTarget, StorageReferenceResolver } from "@rebasepro/types";
25
25
  export { createCookieStorage, createMemoryStorage } from "./auth.js";
26
- export type { AuthConfig, AuthStorage, CookieStorageOptions, CreateAuthOptions, SessionRestoreOutcome } from "./auth.js";
26
+ export type { AppleSignInPayload, AuthConfig, AuthStorage, CookieStorageOptions, CreateAuthOptions, SessionRestoreOutcome } from "./auth.js";
27
+ export { requestAppleAuthorization, preloadAppleSignIn, APPLE_JS_SDK_URL } from "./apple-sign-in.js";
28
+ export type { AppleAuthorization, AppleAuthorizationRequest } from "./apple-sign-in.js";
27
29
  export type { User, RebaseSession, AuthTokens, AuthChangeEvent, DeviceSession } from "@rebasepro/types";
28
- export type { CreateAdminOptions, ListUsersOptions } from "./admin.js";
30
+ export type { CreateAdminOptions, ListGuestsOptions, ListUsersOptions } from "./admin.js";
29
31
  export type { AdminUser } from "./admin.js";
30
32
  export type { CreateCronOptions } from "./cron.js";
31
33
  export type { BackupStream } from "./backups.js";
@@ -39,7 +41,7 @@ export { isOfflineError } from "./offline-errors.js";
39
41
  export type { LiveResult, ObserveByIdOptions, ObserveOptions, RowSnapshotMeta } from "./collection.js";
40
42
  export { etagOf } from "./collection.js";
41
43
  export type { BatchOperation, BatchRef, BatchResult, FieldOperation, UpdateValues, UpsertOptions } from "@rebasepro/types";
42
- export type { WriteOptions, WhereFilterOp, WhereFor, WhereConditionFor, WhereValueFor, FilterValues, FieldPath, OrderBySpec, LogicalCondition, LogicalConditionFor, FilterCondition, FilterConditionFor, AggregateParams, AggregateSelect, AggregateRow, AggregateResult, AggregateMeta, IncludeSpec, IncludeOptions, QueryComputedFields, RowOf, InsertOf, UpdateOf, StorageSource } from "@rebasepro/types";
44
+ export type { WriteOptions, WhereFilterOp, WhereFor, WhereConditionFor, WhereValueFor, FilterValues, FieldPath, OrderBySpec, LogicalCondition, LogicalConditionFor, FilterCondition, FilterConditionFor, AggregateParams, AggregateSelect, AggregateRow, AggregateResult, AggregateMeta, IncludeSpec, IncludeOptions, QueryComputedFields, RowOf, InsertOf, UpdateOf, StorageSource, ClientStorageSource, ClientUploadFileProps, UploadFileResult } from "@rebasepro/types";
43
45
  export type { OfflineStore, OfflineCacheEntry, OfflineCacheRecord, PendingMutation, MutationRollback } from "./offline-store.js";
44
46
  export { MemoryOfflineStore } from "./offline-store.js";
45
47
  export interface CreateRebaseClientOptions extends RebaseClientConfig {
@@ -57,10 +59,17 @@ export interface CreateRebaseClientOptions extends RebaseClientConfig {
57
59
  */
58
60
  storageSources?: StorageSourceDefinition[];
59
61
  /**
60
- * Maps camelCase property names / safe identifiers to the actual
61
- * collection slugs on the server (e.g. `{ companyMembers: "company-members" }`).
62
- * If provided, the data layer proxy will resolve property accessors to their
63
- * correct slugs via this map before falling back to automatic snake_casing.
62
+ * Maps each `client.data` accessor to the collection slug the server
63
+ * serves (e.g. `{ companyMembers: "company-members" }`): the generated
64
+ * `collectionsDictionary`.
65
+ *
66
+ * **Required for a typed client** (`createRebaseClient<Database>`). The
67
+ * types offer every accessor, but without the map the proxy sends
68
+ * `client.data.companyMembers` to `/data/company_members`, so a kebab-case
69
+ * slug or a renamed accessor (`collectionCollection`) answers 404; a
70
+ * one-time warning names the accessor. With the map, an unknown accessor
71
+ * throws `UNKNOWN_COLLECTION` with a suggestion. A later version will make
72
+ * it required in the types when `Database` is supplied.
64
73
  */
65
74
  collections?: Record<string, string>;
66
75
  /**
@@ -78,6 +87,17 @@ export interface CreateRebaseClientOptions extends RebaseClientConfig {
78
87
  * shared across tabs. Off by default.
79
88
  */
80
89
  offline?: boolean | OfflineConfig;
90
+ /**
91
+ * Log the realtime connection's progress — opened, signed in, closed,
92
+ * redialling — with `console.debug`. Off by default, so a public page says
93
+ * nothing about its backend in a visitor's console; warnings and errors
94
+ * are written either way.
95
+ *
96
+ * Without a code change, one browser can turn it on from its console with
97
+ * `localStorage.setItem("rebase_debug", "1")` (remove the key to stop), and
98
+ * any runtime with `globalThis.__REBASE_DEBUG__ = true`.
99
+ */
100
+ debug?: boolean;
81
101
  }
82
102
  type KebabToCamelCase<S extends string> = S extends `${infer T}-${infer U}` ? `${T}${Capitalize<KebabToCamelCase<U>>}` : S;
83
103
  /** The accessor whose generated entry declares `Slug: S`, or `never`. */
@@ -101,7 +121,19 @@ type TypedDataLayer<DB> = {
101
121
  * capabilities populated and the `data` layer narrowed to provide
102
122
  * typed collection accessors when a `DB` schema generic is supplied.
103
123
  */
104
- export type CreateRebaseClientResult<DB = Record<string, unknown>> = Omit<RebaseClient<DB>, "data" | "email"> & {
124
+ export type CreateRebaseClientResult<DB = Record<string, unknown>> = Omit<RebaseClient<DB>, "data" | "email" | "simulate"> & {
125
+ /**
126
+ * A client whose data requests run with simulated access — as a role, a
127
+ * uid holding a role, or a service key — for an administrator checking
128
+ * what row-level security lets that identity read. See
129
+ * {@link RebaseClient.simulate} for what the server honours and refuses.
130
+ *
131
+ * Always present here, typed by the same `Database` (it is built with the
132
+ * same `collections` dictionary), and closable: it is a client of its own,
133
+ * so release it with `close()` when done. On `RebaseClient` it is optional,
134
+ * because a server-side client has none.
135
+ */
136
+ simulate: (simulation: AccessSimulation) => CreateRebaseClientResult<DB>;
105
137
  /**
106
138
  * Send this token from now on, over HTTP and on the realtime socket. An
107
139
  * open socket is rebuilt to authenticate with it. A token getter, when one
@@ -157,6 +189,14 @@ export type CreateRebaseClientResult<DB = Record<string, unknown>> = Omit<Rebase
157
189
  * join and on every reconnect, for channels the server retains.
158
190
  */
159
191
  channel: (name: string, options?: ChannelOptions) => RebaseRealtimeChannel;
192
+ /**
193
+ * Name the group this client's socket belongs to, or clear it with
194
+ * `null` — {@link RealtimeClientOptions.affinity}, for a key that is
195
+ * only known after the client is created. Call it before the first
196
+ * `join()` or `listen()`: a socket already open stays where it is
197
+ * until it next connects. Does nothing with `realtime: false`.
198
+ */
199
+ setAffinity: (key: string | null) => void;
160
200
  };
161
201
  /**
162
202
  * Release everything this client holds that can keep a process alive: the
@@ -172,7 +212,8 @@ export type CreateRebaseClientResult<DB = Record<string, unknown>> = Omit<Rebase
172
212
  * persisted session survives for the next client to restore.
173
213
  */
174
214
  close: () => void;
175
- storage: StorageSource;
215
+ /** The default storage source. Its upload takes any `Blob`, and a key only when you want to name the object. */
216
+ storage: ClientStorageSource;
176
217
  storageRegistry: StorageSourceRegistry;
177
218
  createStorageSource: (storageId: string) => StorageSource;
178
219
  fetchStorageSources: () => Promise<StorageSourceDefinition[]>;