@koolbase/core 12.31.0 → 12.33.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/dist/cjs/auth.js +13 -1
- package/dist/cjs/collection-controller.d.ts +8 -0
- package/dist/cjs/collection-controller.js +6 -0
- package/dist/cjs/database-errors.js +15 -0
- package/dist/cjs/database.d.ts +6 -0
- package/dist/cjs/database.js +28 -3
- package/dist/cjs/errors.d.ts +14 -0
- package/dist/cjs/errors.js +32 -1
- package/dist/cjs/fiscal.js +7 -1
- package/dist/cjs/function-errors.d.ts +1 -1
- package/dist/cjs/function-errors.js +6 -1
- package/dist/cjs/functions.js +2 -2
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/network.d.ts +2 -1
- package/dist/cjs/network.js +60 -7
- package/dist/cjs/query-builder.d.ts +119 -0
- package/dist/cjs/query-builder.js +136 -0
- package/dist/cjs/storage-errors.js +4 -0
- package/dist/cjs/sync-engine.js +5 -2
- package/dist/cjs/types.d.ts +10 -0
- package/dist/esm/auth.js +13 -1
- package/dist/esm/collection-controller.d.ts +8 -0
- package/dist/esm/collection-controller.js +6 -0
- package/dist/esm/database-errors.js +15 -0
- package/dist/esm/database.d.ts +6 -0
- package/dist/esm/database.js +28 -3
- package/dist/esm/errors.d.ts +14 -0
- package/dist/esm/errors.js +29 -0
- package/dist/esm/fiscal.js +7 -1
- package/dist/esm/function-errors.d.ts +1 -1
- package/dist/esm/function-errors.js +6 -1
- package/dist/esm/functions.js +2 -2
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/network.d.ts +2 -1
- package/dist/esm/network.js +60 -7
- package/dist/esm/query-builder.d.ts +119 -0
- package/dist/esm/query-builder.js +130 -0
- package/dist/esm/storage-errors.js +4 -0
- package/dist/esm/sync-engine.js +5 -2
- package/dist/esm/types.d.ts +10 -0
- package/package.json +1 -1
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The typed query (#165): which records to read, written as a tree the
|
|
4
|
+
* server validates against the collection's declared fields and runs after
|
|
5
|
+
* its read rule, so a filter can only narrow what the caller may read.
|
|
6
|
+
* Same names and the same JSON as the Flutter SDK's KbWhere.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* await Koolbase.db.query('events', {
|
|
10
|
+
* where: KbWhere.and([
|
|
11
|
+
* KbField('starts_at').after(KbValue.now()),
|
|
12
|
+
* KbWhere.or([KbField('category').isIn(['music', 'food']), KbField('price').eq(0)]),
|
|
13
|
+
* ]),
|
|
14
|
+
* sort: [KbSort.desc('featured'), KbSort.asc('starts_at')],
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Operators follow the field's declared type; the server refuses one the
|
|
19
|
+
* type does not take (`query_operator_invalid`), or a range or date operator
|
|
20
|
+
* on an undeclared field (`query_field_untyped`). Limits, the server's:
|
|
21
|
+
* groups 3 deep (the outer group is 1), 20 conditions, 100 values in a list.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.KbSort = exports.KbValue = exports.KbWhere = void 0;
|
|
25
|
+
exports.KbField = KbField;
|
|
26
|
+
exports.isTypedQuery = isTypedQuery;
|
|
27
|
+
exports.deviceZone = deviceZone;
|
|
28
|
+
function group(op, conditions) {
|
|
29
|
+
if (conditions.length === 0)
|
|
30
|
+
throw new TypeError('a group needs at least one condition');
|
|
31
|
+
return { op, conditions: [...conditions] };
|
|
32
|
+
}
|
|
33
|
+
exports.KbWhere = {
|
|
34
|
+
/** Every condition must hold. */
|
|
35
|
+
and: (all) => group('and', all),
|
|
36
|
+
/** At least one condition must hold. */
|
|
37
|
+
or: (any) => group('or', any),
|
|
38
|
+
};
|
|
39
|
+
function plain(v) {
|
|
40
|
+
return v instanceof Date ? v.toISOString() : v;
|
|
41
|
+
}
|
|
42
|
+
exports.KbValue = {
|
|
43
|
+
/** v as an operand: a KbValueJson as is; a Date as an instant (UTC, ISO 8601); a list item by item. */
|
|
44
|
+
of(v) {
|
|
45
|
+
if (v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date) && 'kind' in v) {
|
|
46
|
+
return v;
|
|
47
|
+
}
|
|
48
|
+
if (Array.isArray(v))
|
|
49
|
+
return { kind: 'literal', value: v.map(plain) };
|
|
50
|
+
return { kind: 'literal', value: plain(v) };
|
|
51
|
+
},
|
|
52
|
+
/** The server's clock now, optionally moved. */
|
|
53
|
+
now(offset = {}) {
|
|
54
|
+
const m = (offset.hours ?? 0) * 60 + (offset.minutes ?? 0);
|
|
55
|
+
if (m === 0)
|
|
56
|
+
return { kind: 'relative_time', preset: 'now' };
|
|
57
|
+
return {
|
|
58
|
+
kind: 'relative_time',
|
|
59
|
+
preset: 'now',
|
|
60
|
+
offset: m % 60 === 0 ? { amount: m / 60, unit: 'hours' } : { amount: m, unit: 'minutes' },
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
/** The start of today in the query's zone, optionally `days` later (calendar days). */
|
|
64
|
+
startOfToday(opts = {}) {
|
|
65
|
+
return opts.days
|
|
66
|
+
? { kind: 'relative_time', preset: 'start_of_today', offset: { amount: opts.days, unit: 'days' } }
|
|
67
|
+
: { kind: 'relative_time', preset: 'start_of_today' };
|
|
68
|
+
},
|
|
69
|
+
startOfTomorrow: () => ({ kind: 'relative_time', preset: 'start_of_tomorrow' }),
|
|
70
|
+
/** Weeks start on Monday. */
|
|
71
|
+
startOfWeek: () => ({ kind: 'relative_time', preset: 'start_of_week' }),
|
|
72
|
+
startOfNextWeek: () => ({ kind: 'relative_time', preset: 'start_of_next_week' }),
|
|
73
|
+
startOfMonth: () => ({ kind: 'relative_time', preset: 'start_of_month' }),
|
|
74
|
+
/** The signed-in user's id, from the session. Refused (caller_required) signed out. */
|
|
75
|
+
callerUserId: () => ({ kind: 'caller', path: 'user_id' }),
|
|
76
|
+
/** One of the signed-in user's claims, as the server set it. Refused (caller_claim_missing) without it. */
|
|
77
|
+
callerClaim: (name) => ({ kind: 'caller', path: `claims.${name}` }),
|
|
78
|
+
};
|
|
79
|
+
/** A record field to filter on: a declared field, or id, created_at, updated_at, created_by. */
|
|
80
|
+
function KbField(name) {
|
|
81
|
+
const withValue = (operator, v) => {
|
|
82
|
+
if (v === null || v === undefined)
|
|
83
|
+
throw new TypeError(`${name}: no value; use isEmpty() for "has none"`);
|
|
84
|
+
return { field: name, operator, value: exports.KbValue.of(v) };
|
|
85
|
+
};
|
|
86
|
+
const bare = (operator) => ({ field: name, operator });
|
|
87
|
+
return {
|
|
88
|
+
eq: (v) => withValue('eq', v),
|
|
89
|
+
neq: (v) => withValue('neq', v),
|
|
90
|
+
gt: (v) => withValue('gt', v),
|
|
91
|
+
gte: (v) => withValue('gte', v),
|
|
92
|
+
lt: (v) => withValue('lt', v),
|
|
93
|
+
lte: (v) => withValue('lte', v),
|
|
94
|
+
contains: (text) => withValue('contains', text),
|
|
95
|
+
startsWith: (text) => withValue('starts_with', text),
|
|
96
|
+
/** One of the values: a list, or the caller's claim that holds one. */
|
|
97
|
+
isIn: (values) => withValue('in', values),
|
|
98
|
+
notIn: (values) => withValue('not_in', values),
|
|
99
|
+
/** Inclusive at both ends. */
|
|
100
|
+
between: (from, to) => ({
|
|
101
|
+
field: name,
|
|
102
|
+
operator: 'between',
|
|
103
|
+
value: { kind: 'range', from: exports.KbValue.of(from), to: exports.KbValue.of(to) },
|
|
104
|
+
}),
|
|
105
|
+
before: (when) => withValue('before', when),
|
|
106
|
+
after: (when) => withValue('after', when),
|
|
107
|
+
onOrBefore: (when) => withValue('on_or_before', when),
|
|
108
|
+
onOrAfter: (when) => withValue('on_or_after', when),
|
|
109
|
+
/** The calendar day of `when` in the query's zone. */
|
|
110
|
+
on: (when) => withValue('on', when),
|
|
111
|
+
/** No value: missing, null or an empty list. 0, false and an empty text are values. */
|
|
112
|
+
isEmpty: () => bare('is_empty'),
|
|
113
|
+
isNotEmpty: () => bare('is_not_empty'),
|
|
114
|
+
isTrue: () => bare('is_true'),
|
|
115
|
+
isFalse: () => bare('is_false'),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** One sort field. Typed by the declaration; empty values last both ways; the id breaks ties. */
|
|
119
|
+
exports.KbSort = {
|
|
120
|
+
asc: (field) => ({ field, dir: 'asc' }),
|
|
121
|
+
desc: (field) => ({ field, dir: 'desc' }),
|
|
122
|
+
};
|
|
123
|
+
/** Whether options speak #165's language. */
|
|
124
|
+
function isTypedQuery(o) {
|
|
125
|
+
return o.where !== undefined || (o.sort !== undefined && o.sort.length > 0) || (o.timezone ?? '') !== '';
|
|
126
|
+
}
|
|
127
|
+
/** The device's IANA zone ("Africa/Accra"), or undefined when the runtime cannot say -- the query then omits it and the server uses UTC. */
|
|
128
|
+
function deviceZone() {
|
|
129
|
+
try {
|
|
130
|
+
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
131
|
+
return typeof zone === 'string' && zone !== '' && zone !== 'Etc/Unknown' ? zone : undefined;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.KoolbaseStorageQuarantinedError = exports.KoolbaseStorageMalwareError = exports.KoolbaseStorageNameHasHistoryError = exports.KoolbaseStorageFileInUseError = exports.KoolbaseDownloadCancelledError = exports.KoolbaseUploadIncompleteError = exports.KoolbaseStorageSignInRequiredError = exports.KoolbaseStorageInvalidCursorError = exports.KoolbaseStorageBusyError = exports.KoolbaseUploadNotFoundError = exports.KoolbaseUploadCancelledError = exports.KoolbaseStorageMetadataInvalidError = exports.KoolbaseStorageMimeTypeError = exports.KoolbaseStorageFileTooLargeError = exports.KoolbaseStorageQuotaError = exports.KoolbaseCapBelowUsageError = exports.KoolbaseUploadExpiredError = exports.KoolbaseUploadURLFailedError = exports.KoolbaseStoragePermissionError = exports.KoolbaseStorageValidationError = exports.KoolbaseStorageNotFoundError = exports.KoolbaseStorageConflictError = exports.KoolbaseStorageProjectIdentityError = exports.KoolbaseStorageError = void 0;
|
|
4
4
|
exports.koolbaseStorageError = koolbaseStorageError;
|
|
5
5
|
exports.koolbaseStorageErrorFromResponse = koolbaseStorageErrorFromResponse;
|
|
6
|
+
const errors_1 = require("./errors");
|
|
6
7
|
const errors_js_1 = require("./errors.js");
|
|
7
8
|
/**
|
|
8
9
|
* Base error type for all Koolbase storage errors. Catchable via
|
|
@@ -471,6 +472,9 @@ function koolbaseStorageError(status, body, fallbackMessage = 'Storage request f
|
|
|
471
472
|
case 404:
|
|
472
473
|
return new KoolbaseStorageNotFoundError(message);
|
|
473
474
|
case 401:
|
|
475
|
+
// A refused app key is setup, not a session (#169): never signs out.
|
|
476
|
+
if (code === 'invalid_public_key')
|
|
477
|
+
return new errors_1.KoolbaseInvalidPublicKeyError(message);
|
|
474
478
|
// A rejected credential is not a storage problem: a session stops
|
|
475
479
|
// working for the whole SDK at once, so it raises the shared type.
|
|
476
480
|
return new errors_js_1.KoolbaseUnauthenticatedError(message);
|
package/dist/cjs/sync-engine.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SyncEngine = void 0;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
4
5
|
const network_js_1 = require("./network.js");
|
|
5
6
|
const offline_state_js_1 = require("./offline-state.js");
|
|
6
7
|
const errors_js_1 = require("./errors.js");
|
|
@@ -294,8 +295,10 @@ class SyncEngine {
|
|
|
294
295
|
: '';
|
|
295
296
|
res = await (0, network_js_1.sessionFetch)(`${url}${q}`, { method: 'DELETE', headers });
|
|
296
297
|
}
|
|
297
|
-
if (res.status === 401)
|
|
298
|
-
|
|
298
|
+
if (res.status === 401) {
|
|
299
|
+
// A refused app key is setup, not a session (#169): never signs out.
|
|
300
|
+
throw (0, errors_1.invalidPublicKeyIn)(await res.clone().text()) ?? new errors_js_1.KoolbaseUnauthenticatedError('unauthorized');
|
|
301
|
+
}
|
|
299
302
|
if (res.status === 409) {
|
|
300
303
|
const body = await res.json().catch(() => ({}));
|
|
301
304
|
if (body?.code === 'revision_mismatch') {
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { KbSortField, KbWhereNode } from './query-builder.js';
|
|
1
2
|
export interface KoolbaseConfig {
|
|
2
3
|
/**
|
|
3
4
|
* Host platform adapter. Defaults to React Native. A web package or a test
|
|
@@ -295,6 +296,15 @@ export interface QueryOptions {
|
|
|
295
296
|
populate?: string[];
|
|
296
297
|
/** A search over the fields it names, on the server (#160). Empty text: none. */
|
|
297
298
|
fieldSearch?: FieldSearch;
|
|
299
|
+
/**
|
|
300
|
+
* The typed query (#165): a where tree (KbWhere), a sort (KbSort, up to
|
|
301
|
+
* 3 fields) and the IANA zone its relative times resolve in -- the
|
|
302
|
+
* device's own unless named. Not combined with filters, orderBy or
|
|
303
|
+
* orderDesc: use one or the other.
|
|
304
|
+
*/
|
|
305
|
+
where?: KbWhereNode;
|
|
306
|
+
sort?: KbSortField[];
|
|
307
|
+
timezone?: string;
|
|
298
308
|
/**
|
|
299
309
|
* How to read: 'default' is cache-first, refreshed in the background;
|
|
300
310
|
* 'network-only' skips the cache and waits for the server (the result still
|
package/dist/esm/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { KoolbaseInvalidPublicKeyError } from './errors';
|
|
1
2
|
import { koolbaseFetch } from './network.js';
|
|
2
3
|
import { RestoreResult, } from './types.js';
|
|
3
4
|
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';
|
|
@@ -490,6 +491,8 @@ export class KoolbaseAuth {
|
|
|
490
491
|
}
|
|
491
492
|
throw new KoolbaseAuthError(`google sign-in failed: ${errorMessage}`, 'google_signin_failed');
|
|
492
493
|
}
|
|
494
|
+
if (code === 'invalid_public_key')
|
|
495
|
+
throw new KoolbaseInvalidPublicKeyError(errorMessage || undefined);
|
|
493
496
|
if (res.status === 401)
|
|
494
497
|
throw new InvalidGoogleTokenError();
|
|
495
498
|
if (res.status === 403)
|
|
@@ -546,6 +549,8 @@ export class KoolbaseAuth {
|
|
|
546
549
|
}
|
|
547
550
|
throw new KoolbaseAuthError(`apple sign-in failed: ${errorMessage}`, 'apple_signin_failed');
|
|
548
551
|
}
|
|
552
|
+
if (code === 'invalid_public_key')
|
|
553
|
+
throw new KoolbaseInvalidPublicKeyError(errorMessage || undefined);
|
|
549
554
|
if (res.status === 401)
|
|
550
555
|
throw new InvalidAppleTokenError();
|
|
551
556
|
if (res.status === 403)
|
|
@@ -1309,6 +1314,8 @@ export class KoolbaseAuth {
|
|
|
1309
1314
|
throw new MfaEnrollmentNotFoundError();
|
|
1310
1315
|
case 'mfa_not_enabled':
|
|
1311
1316
|
throw new MfaNotEnabledError();
|
|
1317
|
+
case 'invalid_public_key':
|
|
1318
|
+
throw new KoolbaseInvalidPublicKeyError(msg || undefined);
|
|
1312
1319
|
case 'invalid_credentials':
|
|
1313
1320
|
throw new InvalidCredentialsError();
|
|
1314
1321
|
case 'email_in_use':
|
|
@@ -1394,7 +1401,12 @@ export class KoolbaseAuth {
|
|
|
1394
1401
|
if (res.status === 409)
|
|
1395
1402
|
throw new EmailAlreadyInUseError();
|
|
1396
1403
|
if (res.status === 401) {
|
|
1397
|
-
|
|
1404
|
+
// Never a wrong password by guesswork (#168): the server says
|
|
1405
|
+
// invalid_credentials when it means it, and an unrecognised 401 -- a
|
|
1406
|
+
// missing key, a request the app may not make -- is not one.
|
|
1407
|
+
if (isRefresh)
|
|
1408
|
+
throw new SessionExpiredError();
|
|
1409
|
+
throw new KoolbaseAuthError(msg || 'The request was not authorised.', code || 'unauthenticated');
|
|
1398
1410
|
}
|
|
1399
1411
|
if (res.status === 403)
|
|
1400
1412
|
throw new 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;
|
|
@@ -71,6 +71,9 @@ export function collectionQueryKey(collection, query = {}) {
|
|
|
71
71
|
query.orderBy ?? null,
|
|
72
72
|
query.orderDesc === true,
|
|
73
73
|
query.limit ?? null,
|
|
74
|
+
query.filter ?? null,
|
|
75
|
+
query.sort ?? null,
|
|
76
|
+
query.timezone ?? null,
|
|
74
77
|
// Only when live: every other query keeps the key it always had.
|
|
75
78
|
...(query.live === true ? ['live'] : []),
|
|
76
79
|
]);
|
|
@@ -374,6 +377,9 @@ export class KoolbaseCollectionController {
|
|
|
374
377
|
offset,
|
|
375
378
|
orderBy: this.spec.orderBy,
|
|
376
379
|
orderDesc: this.spec.orderDesc,
|
|
380
|
+
...(this.spec.filter ? { where: this.spec.filter } : {}),
|
|
381
|
+
...(this.spec.sort && this.spec.sort.length > 0 ? { sort: this.spec.sort } : {}),
|
|
382
|
+
...(this.spec.timezone ? { timezone: this.spec.timezone } : {}),
|
|
377
383
|
...(this.serverSearch() ? { fieldSearch: this.serverSearch() } : {}),
|
|
378
384
|
cache,
|
|
379
385
|
onRefresh,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { KoolbaseInvalidPublicKeyError } from './errors';
|
|
1
2
|
import { KoolbaseError, KoolbasePlanLimitError, KoolbaseServiceUnavailableError, KoolbaseUnauthenticatedError } from './errors.js';
|
|
2
3
|
/**
|
|
3
4
|
* Base class for errors surfaced by the Koolbase data layer (database reads
|
|
@@ -484,6 +485,11 @@ export function koolbaseDataError(status, body, fallbackMessage = 'Request faile
|
|
|
484
485
|
// Status-first for auth: a 401 means the credentials were not accepted,
|
|
485
486
|
// whatever code the body claims. Trusting a mislabelled body here bypasses
|
|
486
487
|
// session-clearing and strands the app signed-in with dead credentials.
|
|
488
|
+
// A refused app key is setup, not a session (#169): never signs anyone
|
|
489
|
+
// out. Ahead of status-first because the code is the server's own refusal
|
|
490
|
+
// of the key, not a body's claim about a session.
|
|
491
|
+
if (code === 'invalid_public_key')
|
|
492
|
+
return attach(new KoolbaseInvalidPublicKeyError(message));
|
|
487
493
|
if (status === 401) {
|
|
488
494
|
return new KoolbaseUnauthenticatedError(message);
|
|
489
495
|
}
|
|
@@ -579,6 +585,15 @@ export function koolbaseDataError(status, body, fallbackMessage = 'Request faile
|
|
|
579
585
|
return attach(new KoolbasePermissionError(message));
|
|
580
586
|
case 'rate_limit':
|
|
581
587
|
return attach(new KoolbaseRateLimitError(message));
|
|
588
|
+
// A refused typed query (#165): the field, operator or value it names.
|
|
589
|
+
case 'query_invalid':
|
|
590
|
+
case 'query_too_complex':
|
|
591
|
+
case 'query_operator_invalid':
|
|
592
|
+
case 'query_field_untyped':
|
|
593
|
+
case 'query_timezone_invalid':
|
|
594
|
+
case 'query_caller_path_invalid':
|
|
595
|
+
case 'query_sort_invalid':
|
|
596
|
+
case 'query_sort_untyped':
|
|
582
597
|
case 'validation_error':
|
|
583
598
|
case 'vector_collection_mismatch':
|
|
584
599
|
case 'unsupported_dimension':
|
package/dist/esm/database.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { KbWhereNode } from './query-builder.js';
|
|
1
2
|
import { KoolbaseAggregateRequest, KoolbaseAggregateResult } from './aggregate.js';
|
|
2
3
|
import { KoolbaseConflict } from './conflict.js';
|
|
3
4
|
import { PendingWrite } from './pending-write.js';
|
|
@@ -376,6 +377,11 @@ export declare class KoolbaseDatabase {
|
|
|
376
377
|
where?: Record<string, unknown>;
|
|
377
378
|
mode?: SearchMode;
|
|
378
379
|
minSimilarity?: number;
|
|
380
|
+
/** The typed filter (#165, #173): the tree list queries take, applied
|
|
381
|
+
* inside the collection's read rule in every mode. Not with `where`. */
|
|
382
|
+
filter?: KbWhereNode;
|
|
383
|
+
/** The IANA zone the filter's days are read in; the device's if unset. */
|
|
384
|
+
timezone?: string;
|
|
379
385
|
}): Promise<SemanticSearchResult>;
|
|
380
386
|
syncPendingWrites(): Promise<void>;
|
|
381
387
|
}
|
package/dist/esm/database.js
CHANGED
|
@@ -11,6 +11,7 @@ import { getCached, setCached, invalidateCache, optimisticallyInsert, hashQuery,
|
|
|
11
11
|
import { SyncEngine } from './sync-engine.js';
|
|
12
12
|
import { recordFromWire } from './record.js';
|
|
13
13
|
import { koolbaseDataError, KoolbaseDataError } from './database-errors.js';
|
|
14
|
+
import { deviceZone, isTypedQuery } from './query-builder.js';
|
|
14
15
|
function generateWriteId() {
|
|
15
16
|
return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
16
17
|
}
|
|
@@ -159,13 +160,21 @@ export class KoolbaseDatabase {
|
|
|
159
160
|
}
|
|
160
161
|
// ─── Query (cache-first) ───────────────────────────────────────────────────
|
|
161
162
|
async runQuery(collection, options) {
|
|
163
|
+
// One language per request (#165): the server refuses both.
|
|
164
|
+
const typed = isTypedQuery(options);
|
|
165
|
+
if (typed && (Object.keys(options.filters ?? {}).length > 0 || options.orderBy || options.orderDesc)) {
|
|
166
|
+
throw new TypeError('where, sort and timezone are not combined with filters, orderBy or orderDesc: use one or the other');
|
|
167
|
+
}
|
|
162
168
|
const raw = await this.request('POST', '/v1/sdk/db/query', {
|
|
163
169
|
collection,
|
|
164
|
-
|
|
170
|
+
...(typed
|
|
171
|
+
? {}
|
|
172
|
+
: { filters: options.filters ?? {}, order_by: options.orderBy, order_desc: options.orderDesc ?? false }),
|
|
165
173
|
limit: options.limit ?? 20,
|
|
166
174
|
offset: options.offset ?? 0,
|
|
167
|
-
|
|
168
|
-
|
|
175
|
+
...(options.where ? { where: options.where } : {}),
|
|
176
|
+
...(options.sort && options.sort.length > 0 ? { sort: options.sort } : {}),
|
|
177
|
+
...(options.timezone ? { timezone: options.timezone } : {}),
|
|
169
178
|
populate: options.populate ?? [],
|
|
170
179
|
// #160: only with text to search; the server checks the rest.
|
|
171
180
|
...(options.fieldSearch && options.fieldSearch.text.trim() !== ''
|
|
@@ -217,6 +226,13 @@ export class KoolbaseDatabase {
|
|
|
217
226
|
// query's identity, so both policies share one cache entry. onRefresh is
|
|
218
227
|
// who to tell, not what to read, so it stays out the same way.
|
|
219
228
|
const { cache: cachePolicy, onRefresh, ...queryOptions } = options;
|
|
229
|
+
// #165: a typed query carries the device's zone unless it names one --
|
|
230
|
+
// resolved before the hash, so the zone is part of its identity.
|
|
231
|
+
if (isTypedQuery(queryOptions) && !queryOptions.timezone) {
|
|
232
|
+
const zone = deviceZone();
|
|
233
|
+
if (zone)
|
|
234
|
+
queryOptions.timezone = zone;
|
|
235
|
+
}
|
|
220
236
|
const queryHash = hashQuery(collection, queryOptions);
|
|
221
237
|
// A search's answer is the server's (#160): never served from the cache,
|
|
222
238
|
// and not kept there -- one entry per search typed would pile up.
|
|
@@ -1042,6 +1058,9 @@ export class KoolbaseDatabase {
|
|
|
1042
1058
|
* server on lexical mode.
|
|
1043
1059
|
*/
|
|
1044
1060
|
async searchSemantic(opts) {
|
|
1061
|
+
if (opts.filter && opts.where && Object.keys(opts.where).length > 0) {
|
|
1062
|
+
throw new TypeError('searchSemantic: provide filter or where, not both.');
|
|
1063
|
+
}
|
|
1045
1064
|
const hasVector = Array.isArray(opts.queryVector) && opts.queryVector.length > 0;
|
|
1046
1065
|
const hasText = typeof opts.queryText === 'string' && opts.queryText.trim().length > 0;
|
|
1047
1066
|
if (!hasVector && !hasText) {
|
|
@@ -1074,6 +1093,12 @@ export class KoolbaseDatabase {
|
|
|
1074
1093
|
if (opts.minSimilarity !== undefined) {
|
|
1075
1094
|
body.min_similarity = opts.minSimilarity;
|
|
1076
1095
|
}
|
|
1096
|
+
if (opts.filter) {
|
|
1097
|
+
body.filter = opts.filter;
|
|
1098
|
+
const zone = opts.timezone ?? deviceZone();
|
|
1099
|
+
if (zone)
|
|
1100
|
+
body.timezone = zone;
|
|
1101
|
+
}
|
|
1077
1102
|
const raw = await this.request('POST', '/v1/sdk/db/search-semantic', body);
|
|
1078
1103
|
// A hit carries the complete public record, not a projection, so these are
|
|
1079
1104
|
// safe to cache as baselines. A trimmed record would be worse than none: an
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -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;
|
package/dist/esm/errors.js
CHANGED
|
@@ -112,3 +112,32 @@ export class KoolbaseOfflineBaselineUnavailableError extends KoolbaseError {
|
|
|
112
112
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
|
+
/** What the server says for a refused app key, word for word. */
|
|
116
|
+
export const INVALID_PUBLIC_KEY_MESSAGE = "This app's Koolbase key isn't valid for this project.";
|
|
117
|
+
/**
|
|
118
|
+
* The app's Koolbase key was refused (`invalid_public_key`, #169): unknown or
|
|
119
|
+
* revoked, or its project deleted or not ready. The developer's setup, not the
|
|
120
|
+
* user's session: deliberately NOT a KoolbaseUnauthenticatedError, so it never
|
|
121
|
+
* signs anyone out. Raised by any surface, since every request carries the key.
|
|
122
|
+
*/
|
|
123
|
+
export class KoolbaseInvalidPublicKeyError extends KoolbaseError {
|
|
124
|
+
constructor(message = INVALID_PUBLIC_KEY_MESSAGE) {
|
|
125
|
+
super(message, 'invalid_public_key');
|
|
126
|
+
this.name = 'KoolbaseInvalidPublicKeyError';
|
|
127
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** The refusal in a failed response's body, when it is a refused app key
|
|
131
|
+
* (#169); null otherwise. For paths that read a status before a code. */
|
|
132
|
+
export function invalidPublicKeyIn(body) {
|
|
133
|
+
try {
|
|
134
|
+
const j = JSON.parse(body);
|
|
135
|
+
if (j && typeof j === 'object' && j.code === 'invalid_public_key') {
|
|
136
|
+
return new KoolbaseInvalidPublicKeyError(typeof j.error === 'string' && j.error ? j.error : undefined);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// not JSON: not this refusal
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
package/dist/esm/fiscal.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { invalidPublicKeyIn } from './errors';
|
|
1
2
|
import { sessionFetch } from './network.js';
|
|
2
3
|
import { KoolbaseError, KoolbaseUnauthenticatedError } from './errors.js';
|
|
3
4
|
const KNOWN_STATUSES = [
|
|
@@ -81,11 +82,16 @@ export class KoolbaseFiscal {
|
|
|
81
82
|
};
|
|
82
83
|
}
|
|
83
84
|
async decode(res) {
|
|
85
|
+
const text = await res.text();
|
|
86
|
+
// A refused app key is setup, not a session (#169): never signs out.
|
|
87
|
+
const badKey = invalidPublicKeyIn(text);
|
|
88
|
+
if (badKey)
|
|
89
|
+
throw badKey;
|
|
84
90
|
if (res.status === 401 || res.status === 403) {
|
|
85
91
|
await this.onSessionExpired?.();
|
|
86
92
|
throw new KoolbaseUnauthenticatedError(`fiscal: unauthenticated (${res.status})`);
|
|
87
93
|
}
|
|
88
|
-
return decodeFiscalResponse(res.status,
|
|
94
|
+
return decodeFiscalResponse(res.status, text);
|
|
89
95
|
}
|
|
90
96
|
/**
|
|
91
97
|
* 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;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { KoolbaseInvalidPublicKeyError, INVALID_PUBLIC_KEY_MESSAGE } from './errors';
|
|
1
2
|
import { KoolbaseError, KoolbaseUnauthenticatedError } from './errors.js';
|
|
2
3
|
/**
|
|
3
4
|
* A Function call did not succeed.
|
|
@@ -99,9 +100,13 @@ export class FunctionRateLimitError extends FunctionInvokeError {
|
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
/** Builds the right error for a failed invocation. */
|
|
102
|
-
export function functionInvokeError(status, message) {
|
|
103
|
+
export function functionInvokeError(status, message, code) {
|
|
103
104
|
switch (status) {
|
|
104
105
|
case 401:
|
|
106
|
+
// A refused app key is setup, not a session (#169): never signs out.
|
|
107
|
+
if (code === 'invalid_public_key' || message === INVALID_PUBLIC_KEY_MESSAGE) {
|
|
108
|
+
return new KoolbaseInvalidPublicKeyError(message);
|
|
109
|
+
}
|
|
105
110
|
// Not a Function failure. A rejected credential stops the whole SDK
|
|
106
111
|
// working, so it raises the shared type.
|
|
107
112
|
return new KoolbaseUnauthenticatedError(message);
|
package/dist/esm/functions.js
CHANGED
|
@@ -28,7 +28,7 @@ export class KoolbaseFunctions {
|
|
|
28
28
|
if (!res.ok) {
|
|
29
29
|
const message = data?.error ??
|
|
30
30
|
'Function deploy failed';
|
|
31
|
-
const err = functionInvokeError(res.status, message);
|
|
31
|
+
const err = functionInvokeError(res.status, message, data?.code);
|
|
32
32
|
if (err instanceof KoolbaseUnauthenticatedError) {
|
|
33
33
|
await this.onSessionExpired?.();
|
|
34
34
|
}
|
|
@@ -65,7 +65,7 @@ export class KoolbaseFunctions {
|
|
|
65
65
|
if (!success) {
|
|
66
66
|
const message = data?.error ??
|
|
67
67
|
'Function invocation failed';
|
|
68
|
-
const err = functionInvokeError(res.status, message);
|
|
68
|
+
const err = functionInvokeError(res.status, message, data?.code);
|
|
69
69
|
if (err instanceof KoolbaseUnauthenticatedError) {
|
|
70
70
|
await this.onSessionExpired?.();
|
|
71
71
|
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -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/esm/index.js
CHANGED
|
@@ -36,3 +36,4 @@ export { getOrCreateDeviceId } from './device-id.js';
|
|
|
36
36
|
export { koolbaseSdkVersion } from './device-metadata.js';
|
|
37
37
|
export { RestoreResult } from './types.js';
|
|
38
38
|
export { setPlatform, getPlatform, memoryPlatform, } from './platform.js';
|
|
39
|
+
export * from './query-builder.js';
|
package/dist/esm/network.d.ts
CHANGED
|
@@ -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. */
|
package/dist/esm/network.js
CHANGED
|
@@ -35,8 +35,9 @@ export class KoolbaseNetworkError extends TypeError {
|
|
|
35
35
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
/** fetch, with network failures turned into a KoolbaseNetworkError.
|
|
39
|
-
|
|
38
|
+
/** fetch, with network failures turned into a KoolbaseNetworkError. Not
|
|
39
|
+
* logged: sessionFetch's first attempt may yet be answered by renewal. */
|
|
40
|
+
async function sendOnce(input, init) {
|
|
40
41
|
try {
|
|
41
42
|
return await fetch(input, init);
|
|
42
43
|
}
|
|
@@ -47,6 +48,56 @@ export async function koolbaseFetch(input, init) {
|
|
|
47
48
|
throw new KoolbaseNetworkError(input, e);
|
|
48
49
|
}
|
|
49
50
|
}
|
|
51
|
+
/** fetch, with network failures turned into a KoolbaseNetworkError, and a
|
|
52
|
+
* failed answer traced in a development build (#169). */
|
|
53
|
+
export async function koolbaseFetch(input, init) {
|
|
54
|
+
return logFailure(input, init, await sendOnce(input, init));
|
|
55
|
+
}
|
|
56
|
+
// ─── Tracing a failed request (#169) ──────────────────────────────────
|
|
57
|
+
/** A development build: React Native's and Expo's __DEV__, else the
|
|
58
|
+
* bundler's NODE_ENV (written literally, so a bundler replaces it). An
|
|
59
|
+
* unbundled release with neither prints nothing. */
|
|
60
|
+
function devBuild() {
|
|
61
|
+
const dev = globalThis.__DEV__;
|
|
62
|
+
if (typeof dev === 'boolean')
|
|
63
|
+
return dev;
|
|
64
|
+
try {
|
|
65
|
+
// @ts-ignore -- `process` is the bundler's, not a type this package declares
|
|
66
|
+
return process.env.NODE_ENV !== 'production';
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* One line for a failure the caller receives:
|
|
74
|
+
* `[Koolbase] POST /v1/sdk/auth/email/code -> 401 invalid_public_key: ...`.
|
|
75
|
+
* The method, the path, the status and the server's reason; never the host,
|
|
76
|
+
* the query, a header, the key, a token or the request body. The body is
|
|
77
|
+
* read from a clone, so the caller still reads all of it.
|
|
78
|
+
*/
|
|
79
|
+
async function logFailure(input, init, res) {
|
|
80
|
+
if (res.status < 400 || !devBuild())
|
|
81
|
+
return res;
|
|
82
|
+
let path = input.split('?')[0];
|
|
83
|
+
try {
|
|
84
|
+
path = new URL(input).pathname;
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// a relative url: its path is what is left before the query
|
|
88
|
+
}
|
|
89
|
+
let reason = '';
|
|
90
|
+
try {
|
|
91
|
+
const j = JSON.parse(await res.clone().text());
|
|
92
|
+
reason = [j?.code, j?.error].filter((x) => typeof x === 'string' && x !== '').join(': ');
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// not JSON: method, path and status are still worth the line
|
|
96
|
+
}
|
|
97
|
+
const method = (init?.method ?? 'GET').toUpperCase();
|
|
98
|
+
console.warn(`[Koolbase] ${method} ${path} -> ${res.status}${reason ? ` ${reason}` : ''}`);
|
|
99
|
+
return res;
|
|
100
|
+
}
|
|
50
101
|
let renewal = null;
|
|
51
102
|
/** Installed by Koolbase.initialize: renews the session a request was refused with. */
|
|
52
103
|
export function setSessionRenewal(fn) {
|
|
@@ -91,17 +142,19 @@ function withHeader(headers, name, value) {
|
|
|
91
142
|
* client's onSessionExpired, which ends the session.
|
|
92
143
|
*/
|
|
93
144
|
export async function sessionFetch(input, init) {
|
|
94
|
-
|
|
145
|
+
// The first answer is traced only if the caller receives it (#169): a 401
|
|
146
|
+
// renewal answers is not a failure anyone sees.
|
|
147
|
+
const res = await sendOnce(input, init);
|
|
95
148
|
if (res.status !== 401 || !renewal)
|
|
96
|
-
return res;
|
|
149
|
+
return logFailure(input, init, res);
|
|
97
150
|
const auth = headerOf(init?.headers, 'Authorization');
|
|
98
151
|
if (!auth || !auth.startsWith('Bearer '))
|
|
99
|
-
return res;
|
|
152
|
+
return logFailure(input, init, res);
|
|
100
153
|
// Only a body that can be sent twice. Data requests send JSON text.
|
|
101
154
|
if (init?.body !== undefined && init.body !== null && typeof init.body !== 'string')
|
|
102
|
-
return res;
|
|
155
|
+
return logFailure(input, init, res);
|
|
103
156
|
const fresh = await renewal(auth.slice('Bearer '.length));
|
|
104
157
|
if (!fresh)
|
|
105
|
-
return res;
|
|
158
|
+
return logFailure(input, init, res);
|
|
106
159
|
return koolbaseFetch(input, { ...init, headers: withHeader(init?.headers, 'Authorization', `Bearer ${fresh}`) });
|
|
107
160
|
}
|