@koolbase/core 12.25.0 → 12.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.
@@ -1,5 +1,5 @@
1
1
  import { AuthStateListener, KoolbaseConfig, KoolbaseSession, KoolbaseUser, LinkPhoneParams, LoginParams, OtpSendResult, PhoneVerifyResult, RegisterParams, RestoreResult, KoolbaseAuditPage, KoolbaseSessionInfo, ResendVerificationResult, SendOtpParams, SignUpResult, SignInWithAppleParams, VerifyOtpParams } from './types.js';
2
- import type { SignInWithGoogleParams, SignOutReason } from './types.js';
2
+ import type { KoolbaseAvatarFile, SignInWithGoogleParams, SignOutReason } from './types.js';
3
3
  export declare class KoolbaseAuth {
4
4
  private config;
5
5
  private storage;
@@ -248,10 +248,16 @@ export declare class KoolbaseAuth {
248
248
  * Only the fields given are sent, so passing one leaves the other
249
249
  * untouched. The updated user is persisted, so `currentUser` reflects it
250
250
  * without a refetch.
251
+ *
252
+ * The photo is one of: `avatar`, one of the user's own files -- the bucket
253
+ * and path an upload returned; read it in a preset's size, and signed when
254
+ * the bucket is private -- `avatarUrl`, an address; or `avatar: null`,
255
+ * removed. A file someone else uploaded is refused.
251
256
  */
252
257
  updateProfile(params: {
253
258
  fullName?: string;
254
259
  avatarUrl?: string;
260
+ avatar?: KoolbaseAvatarFile | null;
255
261
  }): Promise<KoolbaseUser>;
256
262
  /**
257
263
  * Change the signed-in user's password.
package/dist/cjs/auth.js CHANGED
@@ -6,6 +6,15 @@ const types_js_1 = require("./types.js");
6
6
  const auth_errors_js_1 = require("./auth-errors.js");
7
7
  const platform_js_1 = require("./platform.js");
8
8
  const device_metadata_js_1 = require("./device-metadata.js");
9
+ /** The server's `{ bucket, path }`; undefined when it is not one. */
10
+ function avatarFileOf(raw) {
11
+ if (!raw || typeof raw !== 'object')
12
+ return undefined;
13
+ const { bucket, path } = raw;
14
+ if (typeof bucket !== 'string' || typeof path !== 'string' || !bucket || !path)
15
+ return undefined;
16
+ return { bucket, path };
17
+ }
9
18
  class KoolbaseAuth {
10
19
  constructor(config) {
11
20
  this.session = null;
@@ -760,13 +769,24 @@ class KoolbaseAuth {
760
769
  * Only the fields given are sent, so passing one leaves the other
761
770
  * untouched. The updated user is persisted, so `currentUser` reflects it
762
771
  * without a refetch.
772
+ *
773
+ * The photo is one of: `avatar`, one of the user's own files -- the bucket
774
+ * and path an upload returned; read it in a preset's size, and signed when
775
+ * the bucket is private -- `avatarUrl`, an address; or `avatar: null`,
776
+ * removed. A file someone else uploaded is refused.
763
777
  */
764
778
  async updateProfile(params) {
779
+ if (params.avatarUrl !== undefined && params.avatar !== undefined) {
780
+ throw new TypeError('updateProfile: give avatar or avatarUrl, not both');
781
+ }
765
782
  const body = {};
766
783
  if (params.fullName !== undefined)
767
784
  body.full_name = params.fullName;
768
785
  if (params.avatarUrl !== undefined)
769
786
  body.avatar_url = params.avatarUrl;
787
+ if (params.avatar !== undefined) {
788
+ body.avatar = params.avatar === null ? {} : { bucket: params.avatar.bucket, path: params.avatar.path };
789
+ }
770
790
  const res = await this.authRequest('/v1/sdk/auth/me', {
771
791
  method: 'PATCH',
772
792
  body,
@@ -1212,6 +1232,7 @@ class KoolbaseAuth {
1212
1232
  phoneVerified: raw.phone_verified ?? false,
1213
1233
  fullName: raw.full_name,
1214
1234
  avatarUrl: raw.avatar_url,
1235
+ ...(avatarFileOf(raw.avatar) ? { avatar: avatarFileOf(raw.avatar) } : {}),
1215
1236
  verified: raw.verified ?? false,
1216
1237
  createdAt: raw.created_at,
1217
1238
  // Only the claims readable by the user reach here (#155b).
@@ -1,5 +1,5 @@
1
1
  import type { KoolbaseDatabase } from './database.js';
2
- import type { KoolbaseRecord } from './types.js';
2
+ import type { FieldSearch, KoolbaseRecord } from './types.js';
3
3
  export type CollectionStatus = 'loading' | 'loaded' | 'error';
4
4
  /** What to read. Equality only: each `where` entry is field = literal value. */
5
5
  export interface CollectionQuery {
@@ -16,6 +16,14 @@ export interface CollectionQuery {
16
16
  * in, and goes live then.
17
17
  */
18
18
  live?: boolean;
19
+ /**
20
+ * A search over the fields it names, on the server (#160): the first load
21
+ * is of its matches. Not part of the query's identity -- change it with
22
+ * setSearch(), which keeps the controller and what it shows.
23
+ */
24
+ search?: FieldSearch | null;
25
+ /** How long setSearch() waits for the typing to pause. 250 ms. */
26
+ searchDelayMs?: number;
19
27
  }
20
28
  export interface CollectionState {
21
29
  readonly status: CollectionStatus;
@@ -30,6 +38,14 @@ export interface CollectionState {
30
38
  readonly loadingMore: boolean;
31
39
  /** Whether the server has rows past the last page loaded. True before the first load. */
32
40
  readonly hasMore: boolean;
41
+ /**
42
+ * True from setSearch() until the server answers it (#160). The records
43
+ * shown meanwhile are from before the search: what an app filters from
44
+ * them is a preview, not the answer.
45
+ */
46
+ readonly searching: boolean;
47
+ /** Why the server could not answer the latest search, or null. The records are not its answer. */
48
+ readonly searchError: unknown;
33
49
  }
34
50
  export declare const initialCollectionState: CollectionState;
35
51
  /** One string per distinct query, whatever the order of its `where` keys. */
@@ -49,7 +65,19 @@ export declare class KoolbaseCollectionController {
49
65
  private unregister;
50
66
  private unlive;
51
67
  private liveTimer;
68
+ private search;
69
+ private searchTimer;
52
70
  constructor(db: QueryReader, collection: string, query?: CollectionQuery);
71
+ /**
72
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
73
+ * one of the matches replaces what is shown, never merged with it, and
74
+ * paging continues inside the search. A newer search, or a refresh, drops
75
+ * an older one's answer. Null or empty text: the list unsearched again.
76
+ * Until the server answers, `searching` is true; if it cannot,
77
+ * `searchError` says why and the records shown are not its answer.
78
+ */
79
+ setSearch(search?: FieldSearch | null): void;
80
+ private runSearch;
53
81
  getState(): CollectionState;
54
82
  /** Called on every change. Returns the unsubscribe. */
55
83
  subscribe(listener: () => void): () => void;
@@ -35,7 +35,19 @@ exports.initialCollectionState = Object.freeze({
35
35
  refreshing: false,
36
36
  loadingMore: false,
37
37
  hasMore: true,
38
+ searching: false,
39
+ searchError: null,
38
40
  });
41
+ /** A search with text to search, or null: none. */
42
+ function normalizedSearch(search) {
43
+ if (!search || search.text.trim() === '')
44
+ return null;
45
+ return {
46
+ text: search.text.trim(),
47
+ fields: [...(search.fields ?? [])],
48
+ choices: (search.choices ?? []).map((c) => ({ field: c.field, values: [...c.values], listed: [...c.listed] })),
49
+ };
50
+ }
39
51
  function sortedWhere(where) {
40
52
  const out = {};
41
53
  for (const key of Object.keys(where ?? {}).sort())
@@ -82,9 +94,59 @@ class KoolbaseCollectionController {
82
94
  // A live list's realtime subscription, and its pending debounced re-read.
83
95
  this.unlive = null;
84
96
  this.liveTimer = null;
97
+ this.searchTimer = null;
85
98
  this.db = db;
86
99
  this.collection = collection;
87
100
  this.spec = query;
101
+ this.search = normalizedSearch(query.search);
102
+ }
103
+ /**
104
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
105
+ * one of the matches replaces what is shown, never merged with it, and
106
+ * paging continues inside the search. A newer search, or a refresh, drops
107
+ * an older one's answer. Null or empty text: the list unsearched again.
108
+ * Until the server answers, `searching` is true; if it cannot,
109
+ * `searchError` says why and the records shown are not its answer.
110
+ */
111
+ setSearch(search) {
112
+ if (this.disposed)
113
+ return;
114
+ const next = normalizedSearch(search);
115
+ if (JSON.stringify(next) === JSON.stringify(this.search))
116
+ return;
117
+ this.search = next;
118
+ // Whatever is in flight was for the old search.
119
+ this.generation++;
120
+ if (this.searchTimer)
121
+ clearTimeout(this.searchTimer);
122
+ this.set({ searching: true, searchError: null, loadingMore: false });
123
+ this.searchTimer = setTimeout(() => {
124
+ this.searchTimer = null;
125
+ void this.runSearch();
126
+ }, this.spec.searchDelayMs ?? 250);
127
+ this.searchTimer.unref?.();
128
+ }
129
+ async runSearch() {
130
+ if (this.disposed)
131
+ return;
132
+ const gen = ++this.generation;
133
+ if (this.state.loadingMore)
134
+ this.set({ loadingMore: false });
135
+ try {
136
+ const result = await this.db.query(this.collection, this.options(0, 'network-only'));
137
+ if (this.isStale(gen))
138
+ return;
139
+ this.showPageOne(result, false, false);
140
+ this.set({ searching: false, searchError: null });
141
+ }
142
+ catch (error) {
143
+ if (this.isStale(gen))
144
+ return;
145
+ // Nothing loaded yet to show under it: the list's own error.
146
+ this.set(this.state.status === 'loaded'
147
+ ? { searching: false, searchError: error }
148
+ : { searching: false, searchError: error, status: 'error', error });
149
+ }
88
150
  }
89
151
  getState() {
90
152
  return this.state;
@@ -148,13 +210,15 @@ class KoolbaseCollectionController {
148
210
  */
149
211
  async loadMore() {
150
212
  const s = this.state;
151
- if (this.disposed || s.loadingMore || !s.hasMore || s.status !== 'loaded')
213
+ // Not while a search waits for its answer (#160): the next page of the
214
+ // records shown is not the next page of the search.
215
+ if (this.disposed || s.loadingMore || s.searching || !s.hasMore || s.status !== 'loaded')
152
216
  return;
153
217
  const gen = this.generation;
154
218
  const offset = this.nextOffset;
155
219
  this.set({ loadingMore: true });
156
220
  try {
157
- const result = await this.db.query(this.collection, this.options(offset, 'default'));
221
+ const result = await this.db.query(this.collection, this.options(offset, this.search ? 'network-only' : 'default'));
158
222
  if (this.isStale(gen))
159
223
  return;
160
224
  this.laterPages = [...this.laterPages, ...result.records];
@@ -182,6 +246,10 @@ class KoolbaseCollectionController {
182
246
  clearTimeout(this.liveTimer);
183
247
  this.liveTimer = null;
184
248
  }
249
+ if (this.searchTimer) {
250
+ clearTimeout(this.searchTimer);
251
+ this.searchTimer = null;
252
+ }
185
253
  this.listeners.clear();
186
254
  }
187
255
  async firstPage(cache) {
@@ -191,14 +259,25 @@ class KoolbaseCollectionController {
191
259
  if (this.state.loadingMore)
192
260
  this.set({ loadingMore: false });
193
261
  try {
194
- const result = await this.db.query(this.collection, this.options(0, cache, (fresh) => {
262
+ const result = await this.db.query(this.collection,
263
+ // A search's answer is the server's, never a cached one (#160).
264
+ this.options(0, this.search ? 'network-only' : cache, (fresh) => {
195
265
  if (!this.isStale(gen))
196
266
  this.showPageOne(fresh, false, true);
197
267
  }));
198
- if (!this.isStale(gen))
268
+ if (!this.isStale(gen)) {
199
269
  this.showPageOne(result, result.isFromCache === true, false);
270
+ // A search this fetch superseded is answered by it -- unless a newer
271
+ // one is still waiting for the typing to pause.
272
+ if (!this.searchTimer && (this.state.searching || this.state.searchError !== null)) {
273
+ this.set({ searching: false, searchError: null });
274
+ }
275
+ }
200
276
  }
201
277
  catch (error) {
278
+ if (!this.isStale(gen) && this.state.searching && !this.searchTimer) {
279
+ this.set({ searching: false, searchError: error });
280
+ }
202
281
  if (!this.isStale(gen) && this.state.records.length === 0) {
203
282
  this.set({ status: 'error', error });
204
283
  }
@@ -231,6 +310,7 @@ class KoolbaseCollectionController {
231
310
  offset,
232
311
  orderBy: this.spec.orderBy,
233
312
  orderDesc: this.spec.orderDesc,
313
+ ...(this.search ? { fieldSearch: this.search } : {}),
234
314
  cache,
235
315
  onRefresh,
236
316
  };
@@ -170,6 +170,16 @@ class KoolbaseDatabase {
170
170
  order_by: options.orderBy,
171
171
  order_desc: options.orderDesc ?? false,
172
172
  populate: options.populate ?? [],
173
+ // #160: only with text to search; the server checks the rest.
174
+ ...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
175
+ ? {
176
+ field_search: {
177
+ text: options.fieldSearch.text,
178
+ fields: options.fieldSearch.fields ?? [],
179
+ choices: options.fieldSearch.choices ?? [],
180
+ },
181
+ }
182
+ : {}),
173
183
  });
174
184
  const records = raw.records.map(record_js_1.recordFromWire);
175
185
  // Individually, as well as under the query key. The query cache answers
@@ -211,6 +221,12 @@ class KoolbaseDatabase {
211
221
  // who to tell, not what to read, so it stays out the same way.
212
222
  const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
213
223
  const queryHash = (0, cache_store_js_3.hashQuery)(collection, queryOptions);
224
+ // A search's answer is the server's (#160): never served from the cache,
225
+ // and not kept there -- one entry per search typed would pile up.
226
+ if (queryOptions.fieldSearch && queryOptions.fieldSearch.text.trim() !== '') {
227
+ const result = await this.runQuery(collection, queryOptions);
228
+ return { ...result, isFromCache: false };
229
+ }
214
230
  const cached = cachePolicy === 'network-only' ? null : await (0, cache_store_js_3.getCached)(userId, collection, queryHash);
215
231
  if (cached) {
216
232
  this.runQuery(collection, queryOptions)
@@ -32,6 +32,13 @@ function createUseCollection(getDb) {
32
32
  const subscribe = (0, react_1.useCallback)((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
33
33
  const getSnapshot = (0, react_1.useCallback)(() => (controller ? controller.getState() : index_js_1.initialCollectionState), [controller]);
34
34
  const state = (0, react_1.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
35
+ // The search (#160) is not the query's identity: changing it keeps the
36
+ // controller, and what it shows, and searches after a pause.
37
+ const searchKey = JSON.stringify(query.search ?? null);
38
+ (0, react_1.useEffect)(() => {
39
+ controller?.setSearch(query.search ?? null);
40
+ // Depends on the search as a value, not the object.
41
+ }, [controller, searchKey]);
35
42
  const refresh = (0, react_1.useCallback)(() => (controller ? controller.refresh() : done()), [controller]);
36
43
  const loadMore = (0, react_1.useCallback)(() => (controller ? controller.loadMore() : done()), [controller]);
37
44
  return { ...state, refresh, loadMore };
@@ -28,13 +28,29 @@ export interface KoolbaseConfig {
28
28
  */
29
29
  fetch?: FetchLike;
30
30
  }
31
+ /**
32
+ * Where a user's profile photo is stored, when it is one of their files: a
33
+ * path in one of the project's buckets. Read it like any stored file -- in
34
+ * one of the project's image presets, and signed when the bucket is private:
35
+ * `storage.getDownloadUrl({ bucket, path, preset: 'thumb' })`.
36
+ */
37
+ export interface KoolbaseAvatarFile {
38
+ bucket: string;
39
+ path: string;
40
+ }
31
41
  export interface KoolbaseUser {
32
42
  id: string;
33
43
  email: string;
34
44
  phoneNumber?: string;
35
45
  phoneVerified?: boolean;
36
46
  fullName?: string;
47
+ /**
48
+ * The photo's address: set by updateProfile's avatarUrl, or following
49
+ * `avatar` -- a public bucket's permanent link, absent for a private one.
50
+ */
37
51
  avatarUrl?: string;
52
+ /** Where the photo is stored, when it is one of the user's files. */
53
+ avatar?: KoolbaseAvatarFile;
38
54
  verified: boolean;
39
55
  createdAt: string;
40
56
  /**
@@ -246,6 +262,30 @@ export interface KoolbaseRecord {
246
262
  */
247
263
  revision?: number;
248
264
  }
265
+ /**
266
+ * A search over the fields it names, on the server (#160): records whose
267
+ * text fields contain `text`, ignoring case, inside the read rule and the
268
+ * filters and before the page -- so `total` and every page are of the
269
+ * matches. A Choice field is searched by its labels: `values` are the stored
270
+ * values whose label contains the text, `listed` every value the field
271
+ * declares (the server checks both against the declaration); a stored value
272
+ * not declared matches as itself. Empty `text` is no search.
273
+ */
274
+ export interface FieldSearch {
275
+ text: string;
276
+ /** Declared Text or Long text fields (any field, on a collection that declares none). */
277
+ fields?: string[];
278
+ /** Declared Choice fields, by their labels. */
279
+ choices?: ChoiceSearch[];
280
+ }
281
+ /** One Choice field in a [FieldSearch]. */
282
+ export interface ChoiceSearch {
283
+ field: string;
284
+ /** The stored values whose label contains the search text. */
285
+ values: string[];
286
+ /** Every value the field declares. */
287
+ listed: string[];
288
+ }
249
289
  export interface QueryOptions {
250
290
  filters?: Record<string, unknown>;
251
291
  limit?: number;
@@ -253,6 +293,8 @@ export interface QueryOptions {
253
293
  orderBy?: string;
254
294
  orderDesc?: boolean;
255
295
  populate?: string[];
296
+ /** A search over the fields it names, on the server (#160). Empty text: none. */
297
+ fieldSearch?: FieldSearch;
256
298
  /**
257
299
  * How to read: 'default' is cache-first, refreshed in the background;
258
300
  * 'network-only' skips the cache and waits for the server (the result still
@@ -1,5 +1,5 @@
1
1
  import { AuthStateListener, KoolbaseConfig, KoolbaseSession, KoolbaseUser, LinkPhoneParams, LoginParams, OtpSendResult, PhoneVerifyResult, RegisterParams, RestoreResult, KoolbaseAuditPage, KoolbaseSessionInfo, ResendVerificationResult, SendOtpParams, SignUpResult, SignInWithAppleParams, VerifyOtpParams } from './types.js';
2
- import type { SignInWithGoogleParams, SignOutReason } from './types.js';
2
+ import type { KoolbaseAvatarFile, SignInWithGoogleParams, SignOutReason } from './types.js';
3
3
  export declare class KoolbaseAuth {
4
4
  private config;
5
5
  private storage;
@@ -248,10 +248,16 @@ export declare class KoolbaseAuth {
248
248
  * Only the fields given are sent, so passing one leaves the other
249
249
  * untouched. The updated user is persisted, so `currentUser` reflects it
250
250
  * without a refetch.
251
+ *
252
+ * The photo is one of: `avatar`, one of the user's own files -- the bucket
253
+ * and path an upload returned; read it in a preset's size, and signed when
254
+ * the bucket is private -- `avatarUrl`, an address; or `avatar: null`,
255
+ * removed. A file someone else uploaded is refused.
251
256
  */
252
257
  updateProfile(params: {
253
258
  fullName?: string;
254
259
  avatarUrl?: string;
260
+ avatar?: KoolbaseAvatarFile | null;
255
261
  }): Promise<KoolbaseUser>;
256
262
  /**
257
263
  * Change the signed-in user's password.
package/dist/esm/auth.js CHANGED
@@ -3,6 +3,15 @@ import { RestoreResult, } from './types.js';
3
3
  import { AccountLockedError, EmailAlreadyInUseError, InvalidCredentialsError, InvalidPhoneNumberError, KoolbaseAuthError, OtpExpiredError, OtpInvalidError, OtpMaxAttemptsError, OtpRateLimitError, PhoneAlreadyLinkedError, IdentityNotFoundError, InsufficientScopeError, MalformedSessionResponseError, ProviderIdentityAlreadyLinkedError, AccountExistsError, ContactNotVerifiedError, CurrentPasswordIncorrectError, HideRequiresVerificationError, InsufficientAuthorityError, LastCredentialError, OAuthOnlyAccountError, SessionRequiredError, SignupsDisabledError, TokenAlreadyUsedError, TokenExpiredError, UnsupportedOAuthProviderError, RateLimitError, VerificationResendCooldownError, VerificationResendDailyCapError, SessionExpiredError, SmsConfigMissingError, TokenRevokedError, UnlockTokenInvalidError, UserDisabledError, WeakPasswordError, AppleEmailRequiredError, AppleSignInNotConfiguredError, InvalidAppleTokenError, OAuthEmailConflictError, GoogleEmailRequiredError, GoogleSignInNotConfiguredError, InvalidGoogleTokenError, EmailCodeDisabledError, MfaRequiredError, RecentAuthRequiredError, RecentMfaRequiredError, MfaAlreadyEnabledError, MfaEnrollmentNotFoundError, MfaNotEnabledError, } from './auth-errors.js';
4
4
  import { getPlatform } from './platform.js';
5
5
  import { DeviceMetadata } from './device-metadata.js';
6
+ /** The server's `{ bucket, path }`; undefined when it is not one. */
7
+ function avatarFileOf(raw) {
8
+ if (!raw || typeof raw !== 'object')
9
+ return undefined;
10
+ const { bucket, path } = raw;
11
+ if (typeof bucket !== 'string' || typeof path !== 'string' || !bucket || !path)
12
+ return undefined;
13
+ return { bucket, path };
14
+ }
6
15
  export class KoolbaseAuth {
7
16
  constructor(config) {
8
17
  this.session = null;
@@ -757,13 +766,24 @@ export class KoolbaseAuth {
757
766
  * Only the fields given are sent, so passing one leaves the other
758
767
  * untouched. The updated user is persisted, so `currentUser` reflects it
759
768
  * without a refetch.
769
+ *
770
+ * The photo is one of: `avatar`, one of the user's own files -- the bucket
771
+ * and path an upload returned; read it in a preset's size, and signed when
772
+ * the bucket is private -- `avatarUrl`, an address; or `avatar: null`,
773
+ * removed. A file someone else uploaded is refused.
760
774
  */
761
775
  async updateProfile(params) {
776
+ if (params.avatarUrl !== undefined && params.avatar !== undefined) {
777
+ throw new TypeError('updateProfile: give avatar or avatarUrl, not both');
778
+ }
762
779
  const body = {};
763
780
  if (params.fullName !== undefined)
764
781
  body.full_name = params.fullName;
765
782
  if (params.avatarUrl !== undefined)
766
783
  body.avatar_url = params.avatarUrl;
784
+ if (params.avatar !== undefined) {
785
+ body.avatar = params.avatar === null ? {} : { bucket: params.avatar.bucket, path: params.avatar.path };
786
+ }
767
787
  const res = await this.authRequest('/v1/sdk/auth/me', {
768
788
  method: 'PATCH',
769
789
  body,
@@ -1209,6 +1229,7 @@ export class KoolbaseAuth {
1209
1229
  phoneVerified: raw.phone_verified ?? false,
1210
1230
  fullName: raw.full_name,
1211
1231
  avatarUrl: raw.avatar_url,
1232
+ ...(avatarFileOf(raw.avatar) ? { avatar: avatarFileOf(raw.avatar) } : {}),
1212
1233
  verified: raw.verified ?? false,
1213
1234
  createdAt: raw.created_at,
1214
1235
  // Only the claims readable by the user reach here (#155b).
@@ -1,5 +1,5 @@
1
1
  import type { KoolbaseDatabase } from './database.js';
2
- import type { KoolbaseRecord } from './types.js';
2
+ import type { FieldSearch, KoolbaseRecord } from './types.js';
3
3
  export type CollectionStatus = 'loading' | 'loaded' | 'error';
4
4
  /** What to read. Equality only: each `where` entry is field = literal value. */
5
5
  export interface CollectionQuery {
@@ -16,6 +16,14 @@ export interface CollectionQuery {
16
16
  * in, and goes live then.
17
17
  */
18
18
  live?: boolean;
19
+ /**
20
+ * A search over the fields it names, on the server (#160): the first load
21
+ * is of its matches. Not part of the query's identity -- change it with
22
+ * setSearch(), which keeps the controller and what it shows.
23
+ */
24
+ search?: FieldSearch | null;
25
+ /** How long setSearch() waits for the typing to pause. 250 ms. */
26
+ searchDelayMs?: number;
19
27
  }
20
28
  export interface CollectionState {
21
29
  readonly status: CollectionStatus;
@@ -30,6 +38,14 @@ export interface CollectionState {
30
38
  readonly loadingMore: boolean;
31
39
  /** Whether the server has rows past the last page loaded. True before the first load. */
32
40
  readonly hasMore: boolean;
41
+ /**
42
+ * True from setSearch() until the server answers it (#160). The records
43
+ * shown meanwhile are from before the search: what an app filters from
44
+ * them is a preview, not the answer.
45
+ */
46
+ readonly searching: boolean;
47
+ /** Why the server could not answer the latest search, or null. The records are not its answer. */
48
+ readonly searchError: unknown;
33
49
  }
34
50
  export declare const initialCollectionState: CollectionState;
35
51
  /** One string per distinct query, whatever the order of its `where` keys. */
@@ -49,7 +65,19 @@ export declare class KoolbaseCollectionController {
49
65
  private unregister;
50
66
  private unlive;
51
67
  private liveTimer;
68
+ private search;
69
+ private searchTimer;
52
70
  constructor(db: QueryReader, collection: string, query?: CollectionQuery);
71
+ /**
72
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
73
+ * one of the matches replaces what is shown, never merged with it, and
74
+ * paging continues inside the search. A newer search, or a refresh, drops
75
+ * an older one's answer. Null or empty text: the list unsearched again.
76
+ * Until the server answers, `searching` is true; if it cannot,
77
+ * `searchError` says why and the records shown are not its answer.
78
+ */
79
+ setSearch(search?: FieldSearch | null): void;
80
+ private runSearch;
53
81
  getState(): CollectionState;
54
82
  /** Called on every change. Returns the unsubscribe. */
55
83
  subscribe(listener: () => void): () => void;
@@ -31,7 +31,19 @@ export const initialCollectionState = Object.freeze({
31
31
  refreshing: false,
32
32
  loadingMore: false,
33
33
  hasMore: true,
34
+ searching: false,
35
+ searchError: null,
34
36
  });
37
+ /** A search with text to search, or null: none. */
38
+ function normalizedSearch(search) {
39
+ if (!search || search.text.trim() === '')
40
+ return null;
41
+ return {
42
+ text: search.text.trim(),
43
+ fields: [...(search.fields ?? [])],
44
+ choices: (search.choices ?? []).map((c) => ({ field: c.field, values: [...c.values], listed: [...c.listed] })),
45
+ };
46
+ }
35
47
  function sortedWhere(where) {
36
48
  const out = {};
37
49
  for (const key of Object.keys(where ?? {}).sort())
@@ -78,9 +90,59 @@ export class KoolbaseCollectionController {
78
90
  // A live list's realtime subscription, and its pending debounced re-read.
79
91
  this.unlive = null;
80
92
  this.liveTimer = null;
93
+ this.searchTimer = null;
81
94
  this.db = db;
82
95
  this.collection = collection;
83
96
  this.spec = query;
97
+ this.search = normalizedSearch(query.search);
98
+ }
99
+ /**
100
+ * Search on the server (#160), once the typing pauses (searchDelayMs): page
101
+ * one of the matches replaces what is shown, never merged with it, and
102
+ * paging continues inside the search. A newer search, or a refresh, drops
103
+ * an older one's answer. Null or empty text: the list unsearched again.
104
+ * Until the server answers, `searching` is true; if it cannot,
105
+ * `searchError` says why and the records shown are not its answer.
106
+ */
107
+ setSearch(search) {
108
+ if (this.disposed)
109
+ return;
110
+ const next = normalizedSearch(search);
111
+ if (JSON.stringify(next) === JSON.stringify(this.search))
112
+ return;
113
+ this.search = next;
114
+ // Whatever is in flight was for the old search.
115
+ this.generation++;
116
+ if (this.searchTimer)
117
+ clearTimeout(this.searchTimer);
118
+ this.set({ searching: true, searchError: null, loadingMore: false });
119
+ this.searchTimer = setTimeout(() => {
120
+ this.searchTimer = null;
121
+ void this.runSearch();
122
+ }, this.spec.searchDelayMs ?? 250);
123
+ this.searchTimer.unref?.();
124
+ }
125
+ async runSearch() {
126
+ if (this.disposed)
127
+ return;
128
+ const gen = ++this.generation;
129
+ if (this.state.loadingMore)
130
+ this.set({ loadingMore: false });
131
+ try {
132
+ const result = await this.db.query(this.collection, this.options(0, 'network-only'));
133
+ if (this.isStale(gen))
134
+ return;
135
+ this.showPageOne(result, false, false);
136
+ this.set({ searching: false, searchError: null });
137
+ }
138
+ catch (error) {
139
+ if (this.isStale(gen))
140
+ return;
141
+ // Nothing loaded yet to show under it: the list's own error.
142
+ this.set(this.state.status === 'loaded'
143
+ ? { searching: false, searchError: error }
144
+ : { searching: false, searchError: error, status: 'error', error });
145
+ }
84
146
  }
85
147
  getState() {
86
148
  return this.state;
@@ -144,13 +206,15 @@ export class KoolbaseCollectionController {
144
206
  */
145
207
  async loadMore() {
146
208
  const s = this.state;
147
- if (this.disposed || s.loadingMore || !s.hasMore || s.status !== 'loaded')
209
+ // Not while a search waits for its answer (#160): the next page of the
210
+ // records shown is not the next page of the search.
211
+ if (this.disposed || s.loadingMore || s.searching || !s.hasMore || s.status !== 'loaded')
148
212
  return;
149
213
  const gen = this.generation;
150
214
  const offset = this.nextOffset;
151
215
  this.set({ loadingMore: true });
152
216
  try {
153
- const result = await this.db.query(this.collection, this.options(offset, 'default'));
217
+ const result = await this.db.query(this.collection, this.options(offset, this.search ? 'network-only' : 'default'));
154
218
  if (this.isStale(gen))
155
219
  return;
156
220
  this.laterPages = [...this.laterPages, ...result.records];
@@ -178,6 +242,10 @@ export class KoolbaseCollectionController {
178
242
  clearTimeout(this.liveTimer);
179
243
  this.liveTimer = null;
180
244
  }
245
+ if (this.searchTimer) {
246
+ clearTimeout(this.searchTimer);
247
+ this.searchTimer = null;
248
+ }
181
249
  this.listeners.clear();
182
250
  }
183
251
  async firstPage(cache) {
@@ -187,14 +255,25 @@ export class KoolbaseCollectionController {
187
255
  if (this.state.loadingMore)
188
256
  this.set({ loadingMore: false });
189
257
  try {
190
- const result = await this.db.query(this.collection, this.options(0, cache, (fresh) => {
258
+ const result = await this.db.query(this.collection,
259
+ // A search's answer is the server's, never a cached one (#160).
260
+ this.options(0, this.search ? 'network-only' : cache, (fresh) => {
191
261
  if (!this.isStale(gen))
192
262
  this.showPageOne(fresh, false, true);
193
263
  }));
194
- if (!this.isStale(gen))
264
+ if (!this.isStale(gen)) {
195
265
  this.showPageOne(result, result.isFromCache === true, false);
266
+ // A search this fetch superseded is answered by it -- unless a newer
267
+ // one is still waiting for the typing to pause.
268
+ if (!this.searchTimer && (this.state.searching || this.state.searchError !== null)) {
269
+ this.set({ searching: false, searchError: null });
270
+ }
271
+ }
196
272
  }
197
273
  catch (error) {
274
+ if (!this.isStale(gen) && this.state.searching && !this.searchTimer) {
275
+ this.set({ searching: false, searchError: error });
276
+ }
198
277
  if (!this.isStale(gen) && this.state.records.length === 0) {
199
278
  this.set({ status: 'error', error });
200
279
  }
@@ -227,6 +306,7 @@ export class KoolbaseCollectionController {
227
306
  offset,
228
307
  orderBy: this.spec.orderBy,
229
308
  orderDesc: this.spec.orderDesc,
309
+ ...(this.search ? { fieldSearch: this.search } : {}),
230
310
  cache,
231
311
  onRefresh,
232
312
  };
@@ -167,6 +167,16 @@ export class KoolbaseDatabase {
167
167
  order_by: options.orderBy,
168
168
  order_desc: options.orderDesc ?? false,
169
169
  populate: options.populate ?? [],
170
+ // #160: only with text to search; the server checks the rest.
171
+ ...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
172
+ ? {
173
+ field_search: {
174
+ text: options.fieldSearch.text,
175
+ fields: options.fieldSearch.fields ?? [],
176
+ choices: options.fieldSearch.choices ?? [],
177
+ },
178
+ }
179
+ : {}),
170
180
  });
171
181
  const records = raw.records.map(recordFromWire);
172
182
  // Individually, as well as under the query key. The query cache answers
@@ -208,6 +218,12 @@ export class KoolbaseDatabase {
208
218
  // who to tell, not what to read, so it stays out the same way.
209
219
  const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
210
220
  const queryHash = hashQuery(collection, queryOptions);
221
+ // A search's answer is the server's (#160): never served from the cache,
222
+ // and not kept there -- one entry per search typed would pile up.
223
+ if (queryOptions.fieldSearch && queryOptions.fieldSearch.text.trim() !== '') {
224
+ const result = await this.runQuery(collection, queryOptions);
225
+ return { ...result, isFromCache: false };
226
+ }
211
227
  const cached = cachePolicy === 'network-only' ? null : await getCached(userId, collection, queryHash);
212
228
  if (cached) {
213
229
  this.runQuery(collection, queryOptions)
@@ -29,6 +29,13 @@ export function createUseCollection(getDb) {
29
29
  const subscribe = useCallback((onChange) => (controller ? controller.subscribe(onChange) : noop), [controller]);
30
30
  const getSnapshot = useCallback(() => (controller ? controller.getState() : initialCollectionState), [controller]);
31
31
  const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
32
+ // The search (#160) is not the query's identity: changing it keeps the
33
+ // controller, and what it shows, and searches after a pause.
34
+ const searchKey = JSON.stringify(query.search ?? null);
35
+ useEffect(() => {
36
+ controller?.setSearch(query.search ?? null);
37
+ // Depends on the search as a value, not the object.
38
+ }, [controller, searchKey]);
32
39
  const refresh = useCallback(() => (controller ? controller.refresh() : done()), [controller]);
33
40
  const loadMore = useCallback(() => (controller ? controller.loadMore() : done()), [controller]);
34
41
  return { ...state, refresh, loadMore };
@@ -28,13 +28,29 @@ export interface KoolbaseConfig {
28
28
  */
29
29
  fetch?: FetchLike;
30
30
  }
31
+ /**
32
+ * Where a user's profile photo is stored, when it is one of their files: a
33
+ * path in one of the project's buckets. Read it like any stored file -- in
34
+ * one of the project's image presets, and signed when the bucket is private:
35
+ * `storage.getDownloadUrl({ bucket, path, preset: 'thumb' })`.
36
+ */
37
+ export interface KoolbaseAvatarFile {
38
+ bucket: string;
39
+ path: string;
40
+ }
31
41
  export interface KoolbaseUser {
32
42
  id: string;
33
43
  email: string;
34
44
  phoneNumber?: string;
35
45
  phoneVerified?: boolean;
36
46
  fullName?: string;
47
+ /**
48
+ * The photo's address: set by updateProfile's avatarUrl, or following
49
+ * `avatar` -- a public bucket's permanent link, absent for a private one.
50
+ */
37
51
  avatarUrl?: string;
52
+ /** Where the photo is stored, when it is one of the user's files. */
53
+ avatar?: KoolbaseAvatarFile;
38
54
  verified: boolean;
39
55
  createdAt: string;
40
56
  /**
@@ -246,6 +262,30 @@ export interface KoolbaseRecord {
246
262
  */
247
263
  revision?: number;
248
264
  }
265
+ /**
266
+ * A search over the fields it names, on the server (#160): records whose
267
+ * text fields contain `text`, ignoring case, inside the read rule and the
268
+ * filters and before the page -- so `total` and every page are of the
269
+ * matches. A Choice field is searched by its labels: `values` are the stored
270
+ * values whose label contains the text, `listed` every value the field
271
+ * declares (the server checks both against the declaration); a stored value
272
+ * not declared matches as itself. Empty `text` is no search.
273
+ */
274
+ export interface FieldSearch {
275
+ text: string;
276
+ /** Declared Text or Long text fields (any field, on a collection that declares none). */
277
+ fields?: string[];
278
+ /** Declared Choice fields, by their labels. */
279
+ choices?: ChoiceSearch[];
280
+ }
281
+ /** One Choice field in a [FieldSearch]. */
282
+ export interface ChoiceSearch {
283
+ field: string;
284
+ /** The stored values whose label contains the search text. */
285
+ values: string[];
286
+ /** Every value the field declares. */
287
+ listed: string[];
288
+ }
249
289
  export interface QueryOptions {
250
290
  filters?: Record<string, unknown>;
251
291
  limit?: number;
@@ -253,6 +293,8 @@ export interface QueryOptions {
253
293
  orderBy?: string;
254
294
  orderDesc?: boolean;
255
295
  populate?: string[];
296
+ /** A search over the fields it names, on the server (#160). Empty text: none. */
297
+ fieldSearch?: FieldSearch;
256
298
  /**
257
299
  * How to read: 'default' is cache-first, refreshed in the background;
258
300
  * 'network-only' skips the cache and waits for the server (the result still
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koolbase/core",
3
- "version": "12.25.0",
3
+ "version": "12.27.0",
4
4
  "description": "Koolbase SDK core \u2014 shared behaviour behind @koolbase/react-native and @koolbase/js. Install one of those, not this.",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "types": "./dist/esm/index.d.ts",