@koolbase/core 12.30.0 → 12.32.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.
Files changed (41) hide show
  1. package/dist/cjs/auth.js +13 -1
  2. package/dist/cjs/collection-controller.d.ts +8 -0
  3. package/dist/cjs/collection-controller.js +6 -0
  4. package/dist/cjs/database-errors.js +15 -0
  5. package/dist/cjs/database.js +19 -3
  6. package/dist/cjs/errors.d.ts +14 -0
  7. package/dist/cjs/errors.js +32 -1
  8. package/dist/cjs/fiscal.js +7 -1
  9. package/dist/cjs/function-errors.d.ts +1 -1
  10. package/dist/cjs/function-errors.js +6 -1
  11. package/dist/cjs/functions.js +2 -2
  12. package/dist/cjs/index.d.ts +1 -0
  13. package/dist/cjs/index.js +1 -0
  14. package/dist/cjs/network.d.ts +2 -1
  15. package/dist/cjs/network.js +60 -7
  16. package/dist/cjs/query-builder.d.ts +119 -0
  17. package/dist/cjs/query-builder.js +136 -0
  18. package/dist/cjs/storage-errors.js +4 -0
  19. package/dist/cjs/sync-engine.js +5 -2
  20. package/dist/cjs/types.d.ts +10 -0
  21. package/dist/esm/auth.js +13 -1
  22. package/dist/esm/collection-controller.d.ts +8 -0
  23. package/dist/esm/collection-controller.js +6 -0
  24. package/dist/esm/database-errors.js +15 -0
  25. package/dist/esm/database.js +19 -3
  26. package/dist/esm/errors.d.ts +14 -0
  27. package/dist/esm/errors.js +29 -0
  28. package/dist/esm/fiscal.js +7 -1
  29. package/dist/esm/function-errors.d.ts +1 -1
  30. package/dist/esm/function-errors.js +6 -1
  31. package/dist/esm/functions.js +2 -2
  32. package/dist/esm/index.d.ts +1 -0
  33. package/dist/esm/index.js +1 -0
  34. package/dist/esm/network.d.ts +2 -1
  35. package/dist/esm/network.js +60 -7
  36. package/dist/esm/query-builder.d.ts +119 -0
  37. package/dist/esm/query-builder.js +130 -0
  38. package/dist/esm/storage-errors.js +4 -0
  39. package/dist/esm/sync-engine.js +5 -2
  40. package/dist/esm/types.d.ts +10 -0
  41. package/package.json +1 -1
package/dist/cjs/auth.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KoolbaseAuth = void 0;
4
+ const errors_1 = require("./errors");
4
5
  const network_js_1 = require("./network.js");
5
6
  const types_js_1 = require("./types.js");
6
7
  const auth_errors_js_1 = require("./auth-errors.js");
@@ -493,6 +494,8 @@ class KoolbaseAuth {
493
494
  }
494
495
  throw new auth_errors_js_1.KoolbaseAuthError(`google sign-in failed: ${errorMessage}`, 'google_signin_failed');
495
496
  }
497
+ if (code === 'invalid_public_key')
498
+ throw new errors_1.KoolbaseInvalidPublicKeyError(errorMessage || undefined);
496
499
  if (res.status === 401)
497
500
  throw new auth_errors_js_1.InvalidGoogleTokenError();
498
501
  if (res.status === 403)
@@ -549,6 +552,8 @@ class KoolbaseAuth {
549
552
  }
550
553
  throw new auth_errors_js_1.KoolbaseAuthError(`apple sign-in failed: ${errorMessage}`, 'apple_signin_failed');
551
554
  }
555
+ if (code === 'invalid_public_key')
556
+ throw new errors_1.KoolbaseInvalidPublicKeyError(errorMessage || undefined);
552
557
  if (res.status === 401)
553
558
  throw new auth_errors_js_1.InvalidAppleTokenError();
554
559
  if (res.status === 403)
@@ -1312,6 +1317,8 @@ class KoolbaseAuth {
1312
1317
  throw new auth_errors_js_1.MfaEnrollmentNotFoundError();
1313
1318
  case 'mfa_not_enabled':
1314
1319
  throw new auth_errors_js_1.MfaNotEnabledError();
1320
+ case 'invalid_public_key':
1321
+ throw new errors_1.KoolbaseInvalidPublicKeyError(msg || undefined);
1315
1322
  case 'invalid_credentials':
1316
1323
  throw new auth_errors_js_1.InvalidCredentialsError();
1317
1324
  case 'email_in_use':
@@ -1397,7 +1404,12 @@ class KoolbaseAuth {
1397
1404
  if (res.status === 409)
1398
1405
  throw new auth_errors_js_1.EmailAlreadyInUseError();
1399
1406
  if (res.status === 401) {
1400
- throw isRefresh ? new auth_errors_js_1.SessionExpiredError() : new auth_errors_js_1.InvalidCredentialsError();
1407
+ // Never a wrong password by guesswork (#168): the server says
1408
+ // invalid_credentials when it means it, and an unrecognised 401 -- a
1409
+ // missing key, a request the app may not make -- is not one.
1410
+ if (isRefresh)
1411
+ throw new auth_errors_js_1.SessionExpiredError();
1412
+ throw new auth_errors_js_1.KoolbaseAuthError(msg || 'The request was not authorised.', code || 'unauthenticated');
1401
1413
  }
1402
1414
  if (res.status === 403)
1403
1415
  throw new auth_errors_js_1.UserDisabledError();
@@ -1,10 +1,18 @@
1
1
  import type { KoolbaseDatabase } from './database.js';
2
2
  import type { FieldSearch, KoolbaseRecord } from './types.js';
3
+ import type { KbSortField, KbWhereNode } from './query-builder.js';
3
4
  export type CollectionStatus = 'loading' | 'loaded' | 'error';
4
5
  /** What to read. Equality only: each `where` entry is field = literal value. */
5
6
  export interface CollectionQuery {
6
7
  where?: Record<string, unknown>;
7
8
  orderBy?: string;
9
+ /**
10
+ * The typed query (#165): a where tree, a sort and a zone (the device's
11
+ * unless named). Not combined with `where`, `orderBy` or `orderDesc`.
12
+ */
13
+ filter?: KbWhereNode;
14
+ sort?: KbSortField[];
15
+ timezone?: string;
8
16
  orderDesc?: boolean;
9
17
  /** Page size; the server's default (20) when absent. */
10
18
  limit?: number;
@@ -75,6 +75,9 @@ function collectionQueryKey(collection, query = {}) {
75
75
  query.orderBy ?? null,
76
76
  query.orderDesc === true,
77
77
  query.limit ?? null,
78
+ query.filter ?? null,
79
+ query.sort ?? null,
80
+ query.timezone ?? null,
78
81
  // Only when live: every other query keeps the key it always had.
79
82
  ...(query.live === true ? ['live'] : []),
80
83
  ]);
@@ -378,6 +381,9 @@ class KoolbaseCollectionController {
378
381
  offset,
379
382
  orderBy: this.spec.orderBy,
380
383
  orderDesc: this.spec.orderDesc,
384
+ ...(this.spec.filter ? { where: this.spec.filter } : {}),
385
+ ...(this.spec.sort && this.spec.sort.length > 0 ? { sort: this.spec.sort } : {}),
386
+ ...(this.spec.timezone ? { timezone: this.spec.timezone } : {}),
381
387
  ...(this.serverSearch() ? { fieldSearch: this.serverSearch() } : {}),
382
388
  cache,
383
389
  onRefresh,
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KoolbaseVectorDimensionMismatchError = exports.KoolbaseRateLimitError = exports.KoolbasePermissionError = exports.KoolbaseInsufficientAuthorityError = exports.KoolbaseValidationError = exports.KoolbaseNotFoundError = exports.KoolbaseCollectionReferencedError = exports.KoolbaseDanglingReferencesError = exports.KoolbaseReferenceInUseError = exports.KoolbaseReferenceInvalidError = exports.KoolbaseConflictError = exports.KoolbaseConstraintNotFoundError = exports.KoolbaseConstraintExistsError = exports.KoolbaseAmbiguousMatchError = exports.KoolbaseDuplicateValuesError = exports.KoolbaseBatchFailedError = exports.KoolbaseIdempotencyKeyReusedError = exports.KoolbaseRevisionMismatchError = exports.KoolbaseProviderInvalidError = exports.KoolbaseProviderNotConfiguredError = exports.KoolbaseEmbeddingModelUnsupportedError = exports.KoolbaseReembedConfirmationRequiredError = exports.KoolbaseAutoEmbeddingManagedError = exports.KoolbaseInvalidEmbeddingConfigError = exports.KoolbaseFieldNotAutoEmbedError = exports.KoolbaseVectorFieldExistsError = exports.KoolbaseStateConflictError = exports.KoolbaseNoChangesError = exports.KoolbaseInvalidBodyError = exports.KoolbaseProjectInvalidError = exports.KoolbaseInvitationInvalidError = exports.KoolbaseSlugTakenError = exports.KoolbaseSeedError = exports.KoolbaseDataError = void 0;
4
4
  exports.koolbaseDataError = koolbaseDataError;
5
+ const errors_1 = require("./errors");
5
6
  const errors_js_1 = require("./errors.js");
6
7
  /**
7
8
  * Base class for errors surfaced by the Koolbase data layer (database reads
@@ -522,6 +523,11 @@ function koolbaseDataError(status, body, fallbackMessage = 'Request failed') {
522
523
  // Status-first for auth: a 401 means the credentials were not accepted,
523
524
  // whatever code the body claims. Trusting a mislabelled body here bypasses
524
525
  // session-clearing and strands the app signed-in with dead credentials.
526
+ // A refused app key is setup, not a session (#169): never signs anyone
527
+ // out. Ahead of status-first because the code is the server's own refusal
528
+ // of the key, not a body's claim about a session.
529
+ if (code === 'invalid_public_key')
530
+ return attach(new errors_1.KoolbaseInvalidPublicKeyError(message));
525
531
  if (status === 401) {
526
532
  return new errors_js_1.KoolbaseUnauthenticatedError(message);
527
533
  }
@@ -617,6 +623,15 @@ function koolbaseDataError(status, body, fallbackMessage = 'Request failed') {
617
623
  return attach(new KoolbasePermissionError(message));
618
624
  case 'rate_limit':
619
625
  return attach(new KoolbaseRateLimitError(message));
626
+ // A refused typed query (#165): the field, operator or value it names.
627
+ case 'query_invalid':
628
+ case 'query_too_complex':
629
+ case 'query_operator_invalid':
630
+ case 'query_field_untyped':
631
+ case 'query_timezone_invalid':
632
+ case 'query_caller_path_invalid':
633
+ case 'query_sort_invalid':
634
+ case 'query_sort_untyped':
620
635
  case 'validation_error':
621
636
  case 'vector_collection_mismatch':
622
637
  case 'unsupported_dimension':
@@ -14,6 +14,7 @@ const cache_store_js_3 = require("./cache-store.js");
14
14
  const sync_engine_js_1 = require("./sync-engine.js");
15
15
  const record_js_1 = require("./record.js");
16
16
  const database_errors_js_2 = require("./database-errors.js");
17
+ const query_builder_js_1 = require("./query-builder.js");
17
18
  function generateWriteId() {
18
19
  return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
19
20
  }
@@ -162,13 +163,21 @@ class KoolbaseDatabase {
162
163
  }
163
164
  // ─── Query (cache-first) ───────────────────────────────────────────────────
164
165
  async runQuery(collection, options) {
166
+ // One language per request (#165): the server refuses both.
167
+ const typed = (0, query_builder_js_1.isTypedQuery)(options);
168
+ if (typed && (Object.keys(options.filters ?? {}).length > 0 || options.orderBy || options.orderDesc)) {
169
+ throw new TypeError('where, sort and timezone are not combined with filters, orderBy or orderDesc: use one or the other');
170
+ }
165
171
  const raw = await this.request('POST', '/v1/sdk/db/query', {
166
172
  collection,
167
- filters: options.filters ?? {},
173
+ ...(typed
174
+ ? {}
175
+ : { filters: options.filters ?? {}, order_by: options.orderBy, order_desc: options.orderDesc ?? false }),
168
176
  limit: options.limit ?? 20,
169
177
  offset: options.offset ?? 0,
170
- order_by: options.orderBy,
171
- order_desc: options.orderDesc ?? false,
178
+ ...(options.where ? { where: options.where } : {}),
179
+ ...(options.sort && options.sort.length > 0 ? { sort: options.sort } : {}),
180
+ ...(options.timezone ? { timezone: options.timezone } : {}),
172
181
  populate: options.populate ?? [],
173
182
  // #160: only with text to search; the server checks the rest.
174
183
  ...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
@@ -220,6 +229,13 @@ class KoolbaseDatabase {
220
229
  // query's identity, so both policies share one cache entry. onRefresh is
221
230
  // who to tell, not what to read, so it stays out the same way.
222
231
  const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
232
+ // #165: a typed query carries the device's zone unless it names one --
233
+ // resolved before the hash, so the zone is part of its identity.
234
+ if ((0, query_builder_js_1.isTypedQuery)(queryOptions) && !queryOptions.timezone) {
235
+ const zone = (0, query_builder_js_1.deviceZone)();
236
+ if (zone)
237
+ queryOptions.timezone = zone;
238
+ }
223
239
  const queryHash = (0, cache_store_js_3.hashQuery)(collection, queryOptions);
224
240
  // A search's answer is the server's (#160): never served from the cache,
225
241
  // and not kept there -- one entry per search typed would pile up.
@@ -89,3 +89,17 @@ export declare class KoolbaseServiceUnavailableError extends KoolbaseError {
89
89
  export declare class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
90
90
  constructor(message: string);
91
91
  }
92
+ /** What the server says for a refused app key, word for word. */
93
+ export declare const INVALID_PUBLIC_KEY_MESSAGE = "This app's Koolbase key isn't valid for this project.";
94
+ /**
95
+ * The app's Koolbase key was refused (`invalid_public_key`, #169): unknown or
96
+ * revoked, or its project deleted or not ready. The developer's setup, not the
97
+ * user's session: deliberately NOT a KoolbaseUnauthenticatedError, so it never
98
+ * signs anyone out. Raised by any surface, since every request carries the key.
99
+ */
100
+ export declare class KoolbaseInvalidPublicKeyError extends KoolbaseError {
101
+ constructor(message?: string);
102
+ }
103
+ /** The refusal in a failed response's body, when it is a refused app key
104
+ * (#169); null otherwise. For paths that read a status before a code. */
105
+ export declare function invalidPublicKeyIn(body: string): KoolbaseInvalidPublicKeyError | null;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KoolbaseOfflineBaselineUnavailableError = exports.KoolbaseServiceUnavailableError = exports.KoolbasePlanLimitError = exports.KoolbaseUnauthenticatedError = exports.KoolbaseError = void 0;
3
+ exports.KoolbaseInvalidPublicKeyError = exports.INVALID_PUBLIC_KEY_MESSAGE = exports.KoolbaseOfflineBaselineUnavailableError = exports.KoolbaseServiceUnavailableError = exports.KoolbasePlanLimitError = exports.KoolbaseUnauthenticatedError = exports.KoolbaseError = void 0;
4
+ exports.invalidPublicKeyIn = invalidPublicKeyIn;
4
5
  /**
5
6
  * The root of every error the SDK raises.
6
7
  *
@@ -120,3 +121,33 @@ class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
120
121
  }
121
122
  }
122
123
  exports.KoolbaseOfflineBaselineUnavailableError = KoolbaseOfflineBaselineUnavailableError;
124
+ /** What the server says for a refused app key, word for word. */
125
+ exports.INVALID_PUBLIC_KEY_MESSAGE = "This app's Koolbase key isn't valid for this project.";
126
+ /**
127
+ * The app's Koolbase key was refused (`invalid_public_key`, #169): unknown or
128
+ * revoked, or its project deleted or not ready. The developer's setup, not the
129
+ * user's session: deliberately NOT a KoolbaseUnauthenticatedError, so it never
130
+ * signs anyone out. Raised by any surface, since every request carries the key.
131
+ */
132
+ class KoolbaseInvalidPublicKeyError extends KoolbaseError {
133
+ constructor(message = exports.INVALID_PUBLIC_KEY_MESSAGE) {
134
+ super(message, 'invalid_public_key');
135
+ this.name = 'KoolbaseInvalidPublicKeyError';
136
+ Object.setPrototypeOf(this, new.target.prototype);
137
+ }
138
+ }
139
+ exports.KoolbaseInvalidPublicKeyError = KoolbaseInvalidPublicKeyError;
140
+ /** The refusal in a failed response's body, when it is a refused app key
141
+ * (#169); null otherwise. For paths that read a status before a code. */
142
+ function invalidPublicKeyIn(body) {
143
+ try {
144
+ const j = JSON.parse(body);
145
+ if (j && typeof j === 'object' && j.code === 'invalid_public_key') {
146
+ return new KoolbaseInvalidPublicKeyError(typeof j.error === 'string' && j.error ? j.error : undefined);
147
+ }
148
+ }
149
+ catch {
150
+ // not JSON: not this refusal
151
+ }
152
+ return null;
153
+ }
@@ -4,6 +4,7 @@ exports.KoolbaseFiscal = exports.KoolbaseFiscalError = void 0;
4
4
  exports.isFiscalized = isFiscalized;
5
5
  exports.isPending = isPending;
6
6
  exports.decodeFiscalResponse = decodeFiscalResponse;
7
+ const errors_1 = require("./errors");
7
8
  const network_js_1 = require("./network.js");
8
9
  const errors_js_1 = require("./errors.js");
9
10
  const KNOWN_STATUSES = [
@@ -88,11 +89,16 @@ class KoolbaseFiscal {
88
89
  };
89
90
  }
90
91
  async decode(res) {
92
+ const text = await res.text();
93
+ // A refused app key is setup, not a session (#169): never signs out.
94
+ const badKey = (0, errors_1.invalidPublicKeyIn)(text);
95
+ if (badKey)
96
+ throw badKey;
91
97
  if (res.status === 401 || res.status === 403) {
92
98
  await this.onSessionExpired?.();
93
99
  throw new errors_js_1.KoolbaseUnauthenticatedError(`fiscal: unauthenticated (${res.status})`);
94
100
  }
95
- return decodeFiscalResponse(res.status, await res.text());
101
+ return decodeFiscalResponse(res.status, text);
96
102
  }
97
103
  /**
98
104
  * Submit a sale for fiscalization.
@@ -67,4 +67,4 @@ export declare class FunctionRateLimitError extends FunctionInvokeError {
67
67
  constructor(message: string);
68
68
  }
69
69
  /** Builds the right error for a failed invocation. */
70
- export declare function functionInvokeError(status: number, message: string): KoolbaseError;
70
+ export declare function functionInvokeError(status: number, message: string, code?: string): KoolbaseError;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FunctionRateLimitError = exports.FunctionTimeoutError = exports.FunctionExecutionError = exports.FunctionQuotaExceededError = exports.FunctionValidationError = exports.FunctionPermissionError = exports.FunctionNotFoundError = exports.FunctionInvokeError = void 0;
4
4
  exports.functionInvokeError = functionInvokeError;
5
+ const errors_1 = require("./errors");
5
6
  const errors_js_1 = require("./errors.js");
6
7
  /**
7
8
  * A Function call did not succeed.
@@ -111,9 +112,13 @@ class FunctionRateLimitError extends FunctionInvokeError {
111
112
  }
112
113
  exports.FunctionRateLimitError = FunctionRateLimitError;
113
114
  /** Builds the right error for a failed invocation. */
114
- function functionInvokeError(status, message) {
115
+ function functionInvokeError(status, message, code) {
115
116
  switch (status) {
116
117
  case 401:
118
+ // A refused app key is setup, not a session (#169): never signs out.
119
+ if (code === 'invalid_public_key' || message === errors_1.INVALID_PUBLIC_KEY_MESSAGE) {
120
+ return new errors_1.KoolbaseInvalidPublicKeyError(message);
121
+ }
117
122
  // Not a Function failure. A rejected credential stops the whole SDK
118
123
  // working, so it raises the shared type.
119
124
  return new errors_js_1.KoolbaseUnauthenticatedError(message);
@@ -31,7 +31,7 @@ class KoolbaseFunctions {
31
31
  if (!res.ok) {
32
32
  const message = data?.error ??
33
33
  'Function deploy failed';
34
- const err = (0, function_errors_js_1.functionInvokeError)(res.status, message);
34
+ const err = (0, function_errors_js_1.functionInvokeError)(res.status, message, data?.code);
35
35
  if (err instanceof errors_js_1.KoolbaseUnauthenticatedError) {
36
36
  await this.onSessionExpired?.();
37
37
  }
@@ -68,7 +68,7 @@ class KoolbaseFunctions {
68
68
  if (!success) {
69
69
  const message = data?.error ??
70
70
  'Function invocation failed';
71
- const err = (0, function_errors_js_1.functionInvokeError)(res.status, message);
71
+ const err = (0, function_errors_js_1.functionInvokeError)(res.status, message, data?.code);
72
72
  if (err instanceof errors_js_1.KoolbaseUnauthenticatedError) {
73
73
  await this.onSessionExpired?.();
74
74
  }
@@ -39,3 +39,4 @@ export { koolbaseSdkVersion } from './device-metadata.js';
39
39
  export { RestoreResult } from './types.js';
40
40
  export type { AuthStateListener, FetchLike, KoolbaseAuthStorage, ResendVerificationResult } from './types.js';
41
41
  export { setPlatform, getPlatform, memoryPlatform, type PlatformAdapter, type PlatformBroadcast, type PlatformStorage, type PlatformNetwork, type PlatformLifecycle, type PlatformLocks, type PlatformInfo, } from './platform.js';
42
+ export * from './query-builder.js';
package/dist/cjs/index.js CHANGED
@@ -87,3 +87,4 @@ var platform_js_1 = require("./platform.js");
87
87
  Object.defineProperty(exports, "setPlatform", { enumerable: true, get: function () { return platform_js_1.setPlatform; } });
88
88
  Object.defineProperty(exports, "getPlatform", { enumerable: true, get: function () { return platform_js_1.getPlatform; } });
89
89
  Object.defineProperty(exports, "memoryPlatform", { enumerable: true, get: function () { return platform_js_1.memoryPlatform; } });
90
+ __exportStar(require("./query-builder.js"), exports);
@@ -17,7 +17,8 @@ export declare class KoolbaseNetworkError extends TypeError {
17
17
  readonly origin?: string;
18
18
  constructor(url: string, cause: unknown);
19
19
  }
20
- /** fetch, with network failures turned into a KoolbaseNetworkError. */
20
+ /** fetch, with network failures turned into a KoolbaseNetworkError, and a
21
+ * failed answer traced in a development build (#169). */
21
22
  export declare function koolbaseFetch(input: string, init?: RequestInit): Promise<Response>;
22
23
  type Renewal = (refusedToken: string) => Promise<string | null>;
23
24
  /** Installed by Koolbase.initialize: renews the session a request was refused with. */
@@ -42,8 +42,9 @@ class KoolbaseNetworkError extends TypeError {
42
42
  }
43
43
  }
44
44
  exports.KoolbaseNetworkError = KoolbaseNetworkError;
45
- /** fetch, with network failures turned into a KoolbaseNetworkError. */
46
- async function koolbaseFetch(input, init) {
45
+ /** fetch, with network failures turned into a KoolbaseNetworkError. Not
46
+ * logged: sessionFetch's first attempt may yet be answered by renewal. */
47
+ async function sendOnce(input, init) {
47
48
  try {
48
49
  return await fetch(input, init);
49
50
  }
@@ -54,6 +55,56 @@ async function koolbaseFetch(input, init) {
54
55
  throw new KoolbaseNetworkError(input, e);
55
56
  }
56
57
  }
58
+ /** fetch, with network failures turned into a KoolbaseNetworkError, and a
59
+ * failed answer traced in a development build (#169). */
60
+ async function koolbaseFetch(input, init) {
61
+ return logFailure(input, init, await sendOnce(input, init));
62
+ }
63
+ // ─── Tracing a failed request (#169) ──────────────────────────────────
64
+ /** A development build: React Native's and Expo's __DEV__, else the
65
+ * bundler's NODE_ENV (written literally, so a bundler replaces it). An
66
+ * unbundled release with neither prints nothing. */
67
+ function devBuild() {
68
+ const dev = globalThis.__DEV__;
69
+ if (typeof dev === 'boolean')
70
+ return dev;
71
+ try {
72
+ // @ts-ignore -- `process` is the bundler's, not a type this package declares
73
+ return process.env.NODE_ENV !== 'production';
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ /**
80
+ * One line for a failure the caller receives:
81
+ * `[Koolbase] POST /v1/sdk/auth/email/code -> 401 invalid_public_key: ...`.
82
+ * The method, the path, the status and the server's reason; never the host,
83
+ * the query, a header, the key, a token or the request body. The body is
84
+ * read from a clone, so the caller still reads all of it.
85
+ */
86
+ async function logFailure(input, init, res) {
87
+ if (res.status < 400 || !devBuild())
88
+ return res;
89
+ let path = input.split('?')[0];
90
+ try {
91
+ path = new URL(input).pathname;
92
+ }
93
+ catch {
94
+ // a relative url: its path is what is left before the query
95
+ }
96
+ let reason = '';
97
+ try {
98
+ const j = JSON.parse(await res.clone().text());
99
+ reason = [j?.code, j?.error].filter((x) => typeof x === 'string' && x !== '').join(': ');
100
+ }
101
+ catch {
102
+ // not JSON: method, path and status are still worth the line
103
+ }
104
+ const method = (init?.method ?? 'GET').toUpperCase();
105
+ console.warn(`[Koolbase] ${method} ${path} -> ${res.status}${reason ? ` ${reason}` : ''}`);
106
+ return res;
107
+ }
57
108
  let renewal = null;
58
109
  /** Installed by Koolbase.initialize: renews the session a request was refused with. */
59
110
  function setSessionRenewal(fn) {
@@ -98,17 +149,19 @@ function withHeader(headers, name, value) {
98
149
  * client's onSessionExpired, which ends the session.
99
150
  */
100
151
  async function sessionFetch(input, init) {
101
- const res = await koolbaseFetch(input, init);
152
+ // The first answer is traced only if the caller receives it (#169): a 401
153
+ // renewal answers is not a failure anyone sees.
154
+ const res = await sendOnce(input, init);
102
155
  if (res.status !== 401 || !renewal)
103
- return res;
156
+ return logFailure(input, init, res);
104
157
  const auth = headerOf(init?.headers, 'Authorization');
105
158
  if (!auth || !auth.startsWith('Bearer '))
106
- return res;
159
+ return logFailure(input, init, res);
107
160
  // Only a body that can be sent twice. Data requests send JSON text.
108
161
  if (init?.body !== undefined && init.body !== null && typeof init.body !== 'string')
109
- return res;
162
+ return logFailure(input, init, res);
110
163
  const fresh = await renewal(auth.slice('Bearer '.length));
111
164
  if (!fresh)
112
- return res;
165
+ return logFailure(input, init, res);
113
166
  return koolbaseFetch(input, { ...init, headers: withHeader(init?.headers, 'Authorization', `Bearer ${fresh}`) });
114
167
  }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The typed query (#165): which records to read, written as a tree the
3
+ * server validates against the collection's declared fields and runs after
4
+ * its read rule, so a filter can only narrow what the caller may read.
5
+ * Same names and the same JSON as the Flutter SDK's KbWhere.
6
+ *
7
+ * ```ts
8
+ * await Koolbase.db.query('events', {
9
+ * where: KbWhere.and([
10
+ * KbField('starts_at').after(KbValue.now()),
11
+ * KbWhere.or([KbField('category').isIn(['music', 'food']), KbField('price').eq(0)]),
12
+ * ]),
13
+ * sort: [KbSort.desc('featured'), KbSort.asc('starts_at')],
14
+ * });
15
+ * ```
16
+ *
17
+ * Operators follow the field's declared type; the server refuses one the
18
+ * type does not take (`query_operator_invalid`), or a range or date operator
19
+ * on an undeclared field (`query_field_untyped`). Limits, the server's:
20
+ * groups 3 deep (the outer group is 1), 20 conditions, 100 values in a list.
21
+ */
22
+ export type KbValueJson = {
23
+ kind: 'literal';
24
+ value: unknown;
25
+ } | {
26
+ kind: 'relative_time';
27
+ preset: string;
28
+ offset?: {
29
+ amount: number;
30
+ unit: 'minutes' | 'hours' | 'days';
31
+ };
32
+ } | {
33
+ kind: 'caller';
34
+ path: string;
35
+ } | {
36
+ kind: 'range';
37
+ from: KbValueJson;
38
+ to: KbValueJson;
39
+ };
40
+ export type KbWhereNode = {
41
+ op: 'and' | 'or';
42
+ conditions: KbWhereNode[];
43
+ } | {
44
+ field: string;
45
+ operator: string;
46
+ value?: KbValueJson;
47
+ };
48
+ export interface KbSortField {
49
+ field: string;
50
+ dir: 'asc' | 'desc';
51
+ }
52
+ export declare const KbWhere: {
53
+ /** Every condition must hold. */
54
+ and: (all: KbWhereNode[]) => KbWhereNode;
55
+ /** At least one condition must hold. */
56
+ or: (any: KbWhereNode[]) => KbWhereNode;
57
+ };
58
+ export declare const KbValue: {
59
+ /** v as an operand: a KbValueJson as is; a Date as an instant (UTC, ISO 8601); a list item by item. */
60
+ of(v: unknown): KbValueJson;
61
+ /** The server's clock now, optionally moved. */
62
+ now(offset?: {
63
+ minutes?: number;
64
+ hours?: number;
65
+ }): KbValueJson;
66
+ /** The start of today in the query's zone, optionally `days` later (calendar days). */
67
+ startOfToday(opts?: {
68
+ days?: number;
69
+ }): KbValueJson;
70
+ startOfTomorrow: () => KbValueJson;
71
+ /** Weeks start on Monday. */
72
+ startOfWeek: () => KbValueJson;
73
+ startOfNextWeek: () => KbValueJson;
74
+ startOfMonth: () => KbValueJson;
75
+ /** The signed-in user's id, from the session. Refused (caller_required) signed out. */
76
+ callerUserId: () => KbValueJson;
77
+ /** One of the signed-in user's claims, as the server set it. Refused (caller_claim_missing) without it. */
78
+ callerClaim: (name: string) => KbValueJson;
79
+ };
80
+ /** A record field to filter on: a declared field, or id, created_at, updated_at, created_by. */
81
+ export declare function KbField(name: string): {
82
+ eq: (v: unknown) => KbWhereNode;
83
+ neq: (v: unknown) => KbWhereNode;
84
+ gt: (v: unknown) => KbWhereNode;
85
+ gte: (v: unknown) => KbWhereNode;
86
+ lt: (v: unknown) => KbWhereNode;
87
+ lte: (v: unknown) => KbWhereNode;
88
+ contains: (text: string) => KbWhereNode;
89
+ startsWith: (text: string) => KbWhereNode;
90
+ /** One of the values: a list, or the caller's claim that holds one. */
91
+ isIn: (values: unknown) => KbWhereNode;
92
+ notIn: (values: unknown) => KbWhereNode;
93
+ /** Inclusive at both ends. */
94
+ between: (from: unknown, to: unknown) => KbWhereNode;
95
+ before: (when: unknown) => KbWhereNode;
96
+ after: (when: unknown) => KbWhereNode;
97
+ onOrBefore: (when: unknown) => KbWhereNode;
98
+ onOrAfter: (when: unknown) => KbWhereNode;
99
+ /** The calendar day of `when` in the query's zone. */
100
+ on: (when: unknown) => KbWhereNode;
101
+ /** No value: missing, null or an empty list. 0, false and an empty text are values. */
102
+ isEmpty: () => KbWhereNode;
103
+ isNotEmpty: () => KbWhereNode;
104
+ isTrue: () => KbWhereNode;
105
+ isFalse: () => KbWhereNode;
106
+ };
107
+ /** One sort field. Typed by the declaration; empty values last both ways; the id breaks ties. */
108
+ export declare const KbSort: {
109
+ asc: (field: string) => KbSortField;
110
+ desc: (field: string) => KbSortField;
111
+ };
112
+ /** Whether options speak #165's language. */
113
+ export declare function isTypedQuery(o: {
114
+ where?: unknown;
115
+ sort?: unknown[];
116
+ timezone?: string;
117
+ }): boolean;
118
+ /** The device's IANA zone ("Africa/Accra"), or undefined when the runtime cannot say -- the query then omits it and the server uses UTC. */
119
+ export declare function deviceZone(): string | undefined;