@spacelr/sdk 0.10.10 → 0.11.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/index.d.mts +94 -6
- package/dist/index.d.ts +94 -6
- package/dist/index.js +457 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +457 -24
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -215,17 +215,27 @@ var HttpClient = class {
|
|
|
215
215
|
* caller should retry with a refreshed token. 403 is never routed here —
|
|
216
216
|
* it means "forbidden for this action" and must not trigger logout.
|
|
217
217
|
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
218
|
+
* Auth-loss ownership (#759 review):
|
|
219
|
+
* - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
|
|
220
|
+
* the outcome: it clears + emits on a server-confirmed rejection, and stays
|
|
221
|
+
* silent on a transient transport failure. We must not second-guess it, so
|
|
222
|
+
* we do NOT emit here — that avoids a double clear/emit and stops a transient
|
|
223
|
+
* blip during a 401 retry from ejecting the user.
|
|
224
|
+
* - When no refresh was possible (no refresh token), this 401 IS the confirmed
|
|
225
|
+
* loss and we own it: `notifyAuthLost` clears the dead session then emits.
|
|
226
|
+
* The single clear always runs before any listener, so a listener that
|
|
227
|
+
* re-logs-in via `setTokens()` can never have its fresh session erased.
|
|
220
228
|
*/
|
|
221
229
|
async recoverFromAuthFailure(isRetry) {
|
|
222
230
|
if (isRetry) {
|
|
223
|
-
this.tokenManager.
|
|
231
|
+
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
224
232
|
return false;
|
|
225
233
|
}
|
|
234
|
+
const hadRefreshToken = await this.tokenManager.hasRefreshToken();
|
|
226
235
|
const refreshed = await this.tokenManager.forceRefresh();
|
|
227
236
|
if (refreshed) return true;
|
|
228
|
-
|
|
237
|
+
if (hadRefreshToken) return false;
|
|
238
|
+
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
229
239
|
return false;
|
|
230
240
|
}
|
|
231
241
|
async uploadFormOnce(url, headers, formData, timeoutMs) {
|
|
@@ -457,6 +467,11 @@ var TokenManager = class {
|
|
|
457
467
|
// that hits `/auth/logout` with a dead token) don't re-emit and loop.
|
|
458
468
|
// Cleared by setTokens() / clearTokens() to re-arm for the next session.
|
|
459
469
|
this.authLostEmitted = false;
|
|
470
|
+
// The in-flight auth-loss storage wipe, if any. `setTokens` awaits it before
|
|
471
|
+
// writing so a re-login that lands DURING the wipe (e.g. an external
|
|
472
|
+
// auth-components bridge calling setTokens concurrently with a background
|
|
473
|
+
// refresh failure) is applied AFTER the wipe and never erased (#759 review).
|
|
474
|
+
this.pendingClear = null;
|
|
460
475
|
this.storage = storage ?? new MemoryTokenStorage();
|
|
461
476
|
this.refreshBufferSeconds = refreshBufferSeconds;
|
|
462
477
|
this.refreshLockName = refreshLockName;
|
|
@@ -478,6 +493,7 @@ var TokenManager = class {
|
|
|
478
493
|
return tokens.accessToken;
|
|
479
494
|
}
|
|
480
495
|
async setTokens(tokens) {
|
|
496
|
+
if (this.pendingClear) await this.pendingClear;
|
|
481
497
|
const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
|
|
482
498
|
const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
|
|
483
499
|
await this.storage.setTokens(normalised);
|
|
@@ -510,6 +526,16 @@ var TokenManager = class {
|
|
|
510
526
|
const refreshed = await this.tryRefresh(tokens);
|
|
511
527
|
return refreshed?.accessToken ?? null;
|
|
512
528
|
}
|
|
529
|
+
/**
|
|
530
|
+
* Whether the stored session currently carries a refresh token. Used by the
|
|
531
|
+
* 401-recovery path to decide whether a refresh was even possible, so it can
|
|
532
|
+
* let `doRefresh` own the auth-loss classification instead of second-guessing
|
|
533
|
+
* it. A rejecting storage backend reads as "no refresh token".
|
|
534
|
+
*/
|
|
535
|
+
async hasRefreshToken() {
|
|
536
|
+
const tokens = await this.safeGetTokens();
|
|
537
|
+
return !!tokens?.refreshToken;
|
|
538
|
+
}
|
|
513
539
|
onTokenRefreshed(listener) {
|
|
514
540
|
this.tokenRefreshedListeners.add(listener);
|
|
515
541
|
return () => this.tokenRefreshedListeners.delete(listener);
|
|
@@ -521,6 +547,9 @@ var TokenManager = class {
|
|
|
521
547
|
emitAuthLost(reason) {
|
|
522
548
|
if (this.authLostEmitted) return;
|
|
523
549
|
this.authLostEmitted = true;
|
|
550
|
+
this.dispatchAuthLost(reason);
|
|
551
|
+
}
|
|
552
|
+
dispatchAuthLost(reason) {
|
|
524
553
|
for (const listener of this.authLostListeners) {
|
|
525
554
|
try {
|
|
526
555
|
listener(reason);
|
|
@@ -528,6 +557,57 @@ var TokenManager = class {
|
|
|
528
557
|
}
|
|
529
558
|
}
|
|
530
559
|
}
|
|
560
|
+
/**
|
|
561
|
+
* Handle a server-confirmed auth loss: drop the dead session, THEN notify.
|
|
562
|
+
*
|
|
563
|
+
* The stored tokens are cleared **before** listeners run (#759) so that a
|
|
564
|
+
* reload lands on the login screen and `hasStoredSession()` reads false — and,
|
|
565
|
+
* critically, so a listener that re-logs-in via `setTokens()` (synchronously
|
|
566
|
+
* OR after an await) writes its new session strictly AFTER the clear and can
|
|
567
|
+
* never be erased by it. The clear is a storage-only wipe: we do NOT reset
|
|
568
|
+
* `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
|
|
569
|
+
* this lost session. A rejecting storage backend is swallowed — best-effort,
|
|
570
|
+
* the consumer is routed to logout regardless. `refreshPromise` is left to
|
|
571
|
+
* `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
|
|
572
|
+
* refresh.
|
|
573
|
+
*
|
|
574
|
+
* The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
|
|
575
|
+
* via `refreshPromise`) on a server-confirmed refresh rejection, and from
|
|
576
|
+
* `HttpClient` only when a 401 could not be refreshed AND no refresh was even
|
|
577
|
+
* attempted (no refresh token) — these are mutually exclusive, so there is
|
|
578
|
+
* exactly one clear per loss and it runs BEFORE any listener. A re-login a
|
|
579
|
+
* listener performs is therefore never erased.
|
|
580
|
+
*/
|
|
581
|
+
async notifyAuthLost(reason) {
|
|
582
|
+
if (this.authLostEmitted) return;
|
|
583
|
+
this.authLostEmitted = true;
|
|
584
|
+
this.pendingClear = this.storage.clearTokens().catch(() => {
|
|
585
|
+
});
|
|
586
|
+
await this.pendingClear;
|
|
587
|
+
this.pendingClear = null;
|
|
588
|
+
this.dispatchAuthLost(reason);
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* A refresh failure that is transient (retryable), not a server-confirmed auth
|
|
592
|
+
* loss — so it must NOT eject a local-first app; the next request retries.
|
|
593
|
+
* Covers:
|
|
594
|
+
* - a transport failure (offline, tunnel, captive portal, unreachable
|
|
595
|
+
* gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
|
|
596
|
+
* - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
|
|
597
|
+
* is momentarily down (#760/#762) — which is retryable infrastructure, not
|
|
598
|
+
* a token rejection.
|
|
599
|
+
* A real auth rejection (401/invalid_grant) or any other non-5xx server error
|
|
600
|
+
* is NOT transient and is treated as a server-confirmed loss.
|
|
601
|
+
*/
|
|
602
|
+
isTransientTransportError(error) {
|
|
603
|
+
if (error instanceof SpacelrNetworkError || error instanceof SpacelrTimeoutError) {
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
if (error instanceof SpacelrError && typeof error.statusCode === "number") {
|
|
607
|
+
return error.statusCode >= 500 && error.statusCode <= 599;
|
|
608
|
+
}
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
531
611
|
isTokenExpired(tokens) {
|
|
532
612
|
if (!tokens.expiresAt) return false;
|
|
533
613
|
return Date.now() >= tokens.expiresAt * 1e3;
|
|
@@ -566,15 +646,18 @@ var TokenManager = class {
|
|
|
566
646
|
return current;
|
|
567
647
|
}
|
|
568
648
|
const activeRefreshToken = current?.refreshToken || refreshToken;
|
|
649
|
+
let newTokens;
|
|
569
650
|
try {
|
|
570
|
-
|
|
571
|
-
await this.storage.setTokens(newTokens);
|
|
572
|
-
this.emitTokenRefreshed(newTokens);
|
|
573
|
-
return newTokens;
|
|
651
|
+
newTokens = await callback(activeRefreshToken);
|
|
574
652
|
} catch (error) {
|
|
575
|
-
this.
|
|
653
|
+
if (!this.isTransientTransportError(error)) {
|
|
654
|
+
await this.notifyAuthLost("refresh-failed");
|
|
655
|
+
}
|
|
576
656
|
throw error;
|
|
577
657
|
}
|
|
658
|
+
await this.storage.setTokens(newTokens);
|
|
659
|
+
this.emitTokenRefreshed(newTokens);
|
|
660
|
+
return newTokens;
|
|
578
661
|
}
|
|
579
662
|
async safeGetTokens() {
|
|
580
663
|
try {
|
|
@@ -728,6 +811,33 @@ function whereValueMatches(actual, expected) {
|
|
|
728
811
|
if (Array.isArray(actual)) return actual.includes(expected);
|
|
729
812
|
return actual === expected;
|
|
730
813
|
}
|
|
814
|
+
var TYPED_EQUALITY_MAX_COMPARAND_LENGTH = 64;
|
|
815
|
+
var TYPED_EQUALITY_RFC3339_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
816
|
+
var TYPED_EQUALITY_OBJECT_ID_HEX = /^[0-9a-f]{24}$/i;
|
|
817
|
+
var NEVER_TYPED_FIELD = "_id";
|
|
818
|
+
function resolveFieldTypeTag(t, key) {
|
|
819
|
+
if (key === NEVER_TYPED_FIELD) return void 0;
|
|
820
|
+
if (!t || t.incomplete) return void 0;
|
|
821
|
+
const tag = t.fields?.[key];
|
|
822
|
+
return tag === "date" || tag === "objectId" ? tag : void 0;
|
|
823
|
+
}
|
|
824
|
+
function whereValueMatchesTyped(actual, expected, fieldType) {
|
|
825
|
+
if (fieldType === "date" && typeof actual === "string" && typeof expected === "string") {
|
|
826
|
+
if (actual.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && expected.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && TYPED_EQUALITY_RFC3339_WITH_OFFSET.test(actual) && TYPED_EQUALITY_RFC3339_WITH_OFFSET.test(expected)) {
|
|
827
|
+
const a = Date.parse(actual);
|
|
828
|
+
const e = Date.parse(expected);
|
|
829
|
+
if (!Number.isNaN(a) && !Number.isNaN(e)) return a === e;
|
|
830
|
+
}
|
|
831
|
+
return whereValueMatches(actual, expected);
|
|
832
|
+
}
|
|
833
|
+
if (fieldType === "objectId" && typeof actual === "string" && typeof expected === "string") {
|
|
834
|
+
if (actual.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && expected.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && TYPED_EQUALITY_OBJECT_ID_HEX.test(actual) && TYPED_EQUALITY_OBJECT_ID_HEX.test(expected)) {
|
|
835
|
+
return actual.toLowerCase() === expected.toLowerCase();
|
|
836
|
+
}
|
|
837
|
+
return whereValueMatches(actual, expected);
|
|
838
|
+
}
|
|
839
|
+
return whereValueMatches(actual, expected);
|
|
840
|
+
}
|
|
731
841
|
function isFiniteScalar(v) {
|
|
732
842
|
const t = typeof v;
|
|
733
843
|
if (t === "string" || t === "boolean") return true;
|
|
@@ -1113,7 +1223,8 @@ var RealtimeClient = class {
|
|
|
1113
1223
|
if (!where || Object.keys(where).length === 0) return true;
|
|
1114
1224
|
if (!event.document) return true;
|
|
1115
1225
|
for (const [key, value] of Object.entries(where)) {
|
|
1116
|
-
|
|
1226
|
+
const fieldType = resolveFieldTypeTag(event.__t, key);
|
|
1227
|
+
if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
|
|
1117
1228
|
return false;
|
|
1118
1229
|
}
|
|
1119
1230
|
}
|
|
@@ -1279,7 +1390,8 @@ var RealtimeClient = class {
|
|
|
1279
1390
|
if (!where) return false;
|
|
1280
1391
|
if (!event.document) return false;
|
|
1281
1392
|
for (const [key, value] of Object.entries(where)) {
|
|
1282
|
-
|
|
1393
|
+
const fieldType = resolveFieldTypeTag(event.__t, key);
|
|
1394
|
+
if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
|
|
1283
1395
|
return false;
|
|
1284
1396
|
}
|
|
1285
1397
|
}
|
|
@@ -2392,6 +2504,262 @@ function isTimelineSourceStats(value) {
|
|
|
2392
2504
|
return true;
|
|
2393
2505
|
}
|
|
2394
2506
|
|
|
2507
|
+
// libs/sdk/src/core/typed-matcher.ts
|
|
2508
|
+
var MAX_WHERE_DEPTH2 = 10;
|
|
2509
|
+
var RESERVED_FIELD_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
2510
|
+
var SCALAR_OPS = ["$eq", "$ne", "$gt", "$gte", "$lt", "$lte"];
|
|
2511
|
+
var ARRAY_ELEMENT_OPS = ["$in", "$nin"];
|
|
2512
|
+
function isScalarOp(op) {
|
|
2513
|
+
return SCALAR_OPS.includes(op);
|
|
2514
|
+
}
|
|
2515
|
+
function isArrayElementOp(op) {
|
|
2516
|
+
return ARRAY_ELEMENT_OPS.includes(op);
|
|
2517
|
+
}
|
|
2518
|
+
function isPlainObject(value) {
|
|
2519
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2520
|
+
}
|
|
2521
|
+
function isSafeComparableNumber(n) {
|
|
2522
|
+
return Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER;
|
|
2523
|
+
}
|
|
2524
|
+
function compileComparand(leaf, rawValue, allowScalar) {
|
|
2525
|
+
if (leaf?.kind === "date") return { kind: "date", epochMs: leaf.epochMs };
|
|
2526
|
+
if (leaf?.kind === "objectId") return { kind: "objectId", hex: leaf.hex };
|
|
2527
|
+
if (leaf?.kind === "raw") return null;
|
|
2528
|
+
if (typeof rawValue === "number" && isSafeComparableNumber(rawValue)) return { kind: "number", value: rawValue };
|
|
2529
|
+
if (allowScalar && (typeof rawValue === "string" || typeof rawValue === "boolean")) {
|
|
2530
|
+
return { kind: "scalar", value: rawValue };
|
|
2531
|
+
}
|
|
2532
|
+
return null;
|
|
2533
|
+
}
|
|
2534
|
+
function comparableValue(comparand) {
|
|
2535
|
+
switch (comparand.kind) {
|
|
2536
|
+
case "date":
|
|
2537
|
+
return comparand.epochMs;
|
|
2538
|
+
case "objectId":
|
|
2539
|
+
return comparand.hex;
|
|
2540
|
+
case "number":
|
|
2541
|
+
return comparand.value;
|
|
2542
|
+
case "scalar":
|
|
2543
|
+
return comparand.value;
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
function scalarActualKind(raw, tag, untrusted) {
|
|
2547
|
+
if (untrusted) return "unknown";
|
|
2548
|
+
if (tag === "date") return "date";
|
|
2549
|
+
if (tag === "objectId") return "objectId";
|
|
2550
|
+
if (typeof raw === "number") return isSafeComparableNumber(raw) ? "number" : "unknown";
|
|
2551
|
+
if (typeof raw === "string" || typeof raw === "boolean") return "scalar";
|
|
2552
|
+
return "unknown";
|
|
2553
|
+
}
|
|
2554
|
+
function comparandNeedsTag(comparand) {
|
|
2555
|
+
return comparand.kind === "date" || comparand.kind === "objectId";
|
|
2556
|
+
}
|
|
2557
|
+
function isUntrusted(t, comparand) {
|
|
2558
|
+
if (t?.incomplete === true) return true;
|
|
2559
|
+
return comparandNeedsTag(comparand) && t?.fields === void 0;
|
|
2560
|
+
}
|
|
2561
|
+
function toEpochMs(raw) {
|
|
2562
|
+
if (typeof raw === "string") {
|
|
2563
|
+
const parsed = Date.parse(raw);
|
|
2564
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
2565
|
+
}
|
|
2566
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
2567
|
+
return void 0;
|
|
2568
|
+
}
|
|
2569
|
+
function resolveScalar(comparand, present, raw, actualKind) {
|
|
2570
|
+
if (!present) return { status: "absent" };
|
|
2571
|
+
if (actualKind === "unknown") return { status: "unknown" };
|
|
2572
|
+
if (comparand.kind === "date") {
|
|
2573
|
+
if (actualKind !== "date") return { status: "cross" };
|
|
2574
|
+
const epoch = toEpochMs(raw);
|
|
2575
|
+
if (epoch === void 0) return { status: "unknown" };
|
|
2576
|
+
return { status: "ok", value: epoch };
|
|
2577
|
+
}
|
|
2578
|
+
if (comparand.kind === "objectId") {
|
|
2579
|
+
if (actualKind !== "objectId") return { status: "cross" };
|
|
2580
|
+
if (typeof raw !== "string") return { status: "unknown" };
|
|
2581
|
+
return { status: "ok", value: raw.toLowerCase() };
|
|
2582
|
+
}
|
|
2583
|
+
if (actualKind === "date" || actualKind === "objectId") return { status: "unknown" };
|
|
2584
|
+
if (comparand.kind === "number") {
|
|
2585
|
+
if (actualKind !== "number") return { status: "cross" };
|
|
2586
|
+
return { status: "ok", value: raw };
|
|
2587
|
+
}
|
|
2588
|
+
if (actualKind !== "scalar" || typeof raw !== typeof comparand.value) return { status: "cross" };
|
|
2589
|
+
return { status: "ok", value: raw };
|
|
2590
|
+
}
|
|
2591
|
+
function confirmedEqual(resolved, comparand) {
|
|
2592
|
+
return resolved.status === "ok" && resolved.value === comparableValue(comparand);
|
|
2593
|
+
}
|
|
2594
|
+
function maybeEqual(resolved, comparand) {
|
|
2595
|
+
return resolved.status === "unknown" || confirmedEqual(resolved, comparand);
|
|
2596
|
+
}
|
|
2597
|
+
function compareOrder(a, b) {
|
|
2598
|
+
if (a === b) return 0;
|
|
2599
|
+
return a < b ? -1 : 1;
|
|
2600
|
+
}
|
|
2601
|
+
function satisfiesRange(op, cmp) {
|
|
2602
|
+
switch (op) {
|
|
2603
|
+
case "$gt":
|
|
2604
|
+
return cmp > 0;
|
|
2605
|
+
case "$gte":
|
|
2606
|
+
return cmp >= 0;
|
|
2607
|
+
case "$lt":
|
|
2608
|
+
return cmp < 0;
|
|
2609
|
+
case "$lte":
|
|
2610
|
+
return cmp <= 0;
|
|
2611
|
+
default:
|
|
2612
|
+
return false;
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
function maybeSatisfiesRange(resolved, comparand, op) {
|
|
2616
|
+
if (resolved.status === "unknown") return true;
|
|
2617
|
+
if (resolved.status !== "ok") return false;
|
|
2618
|
+
return satisfiesRange(op, compareOrder(resolved.value, comparableValue(comparand)));
|
|
2619
|
+
}
|
|
2620
|
+
function fieldPresent(document2, field) {
|
|
2621
|
+
return Object.prototype.hasOwnProperty.call(document2, field);
|
|
2622
|
+
}
|
|
2623
|
+
function fieldTag(t, field) {
|
|
2624
|
+
return t?.fields?.[field];
|
|
2625
|
+
}
|
|
2626
|
+
function isArrayTag(tag) {
|
|
2627
|
+
return typeof tag === "object" && tag !== null && "array" in tag;
|
|
2628
|
+
}
|
|
2629
|
+
function evalScalarLeaf(field, op, comparand) {
|
|
2630
|
+
return (document2, t) => {
|
|
2631
|
+
const present = fieldPresent(document2, field);
|
|
2632
|
+
const raw = present ? document2[field] : void 0;
|
|
2633
|
+
const untrusted = isUntrusted(t, comparand);
|
|
2634
|
+
const tag = fieldTag(t, field);
|
|
2635
|
+
if (present && Array.isArray(raw)) {
|
|
2636
|
+
const arrayTag = isArrayTag(tag) ? tag.array : void 0;
|
|
2637
|
+
return evalArrayLeaf(raw, arrayTag, untrusted, op, comparand);
|
|
2638
|
+
}
|
|
2639
|
+
const scalarTag = isArrayTag(tag) ? void 0 : tag;
|
|
2640
|
+
const actualKind = scalarActualKind(raw, scalarTag, untrusted);
|
|
2641
|
+
const resolved = resolveScalar(comparand, present, raw, actualKind);
|
|
2642
|
+
if (op === "$ne") return !confirmedEqual(resolved, comparand);
|
|
2643
|
+
if (op === "$eq") return maybeEqual(resolved, comparand);
|
|
2644
|
+
return maybeSatisfiesRange(resolved, comparand, op);
|
|
2645
|
+
};
|
|
2646
|
+
}
|
|
2647
|
+
function evalArrayLeaf(raw, arrayTag, untrusted, op, comparand) {
|
|
2648
|
+
const resolvedElements = raw.map((el, i) => {
|
|
2649
|
+
const tag = arrayTag?.[i];
|
|
2650
|
+
const scalarTag = tag === "date" || tag === "objectId" ? tag : void 0;
|
|
2651
|
+
const actualKind = scalarActualKind(el, scalarTag, untrusted);
|
|
2652
|
+
return resolveScalar(comparand, true, el, actualKind);
|
|
2653
|
+
});
|
|
2654
|
+
if (op === "$ne") {
|
|
2655
|
+
return !resolvedElements.some((r) => confirmedEqual(r, comparand));
|
|
2656
|
+
}
|
|
2657
|
+
if (op === "$eq") {
|
|
2658
|
+
return resolvedElements.some((r) => maybeEqual(r, comparand));
|
|
2659
|
+
}
|
|
2660
|
+
return resolvedElements.some((r) => maybeSatisfiesRange(r, comparand, op));
|
|
2661
|
+
}
|
|
2662
|
+
function evalArrayElementOpLeaf(field, op, comparands) {
|
|
2663
|
+
return (document2, t) => {
|
|
2664
|
+
const present = fieldPresent(document2, field);
|
|
2665
|
+
const raw = present ? document2[field] : void 0;
|
|
2666
|
+
const tag = fieldTag(t, field);
|
|
2667
|
+
const evalOne = (comparand) => {
|
|
2668
|
+
const untrusted = isUntrusted(t, comparand);
|
|
2669
|
+
if (present && Array.isArray(raw)) {
|
|
2670
|
+
const arrayTag = isArrayTag(tag) ? tag.array : void 0;
|
|
2671
|
+
const resolvedElements = raw.map((el, i) => {
|
|
2672
|
+
const elTag = arrayTag?.[i];
|
|
2673
|
+
const scalarTag2 = elTag === "date" || elTag === "objectId" ? elTag : void 0;
|
|
2674
|
+
const actualKind2 = scalarActualKind(el, scalarTag2, untrusted);
|
|
2675
|
+
return resolveScalar(comparand, true, el, actualKind2);
|
|
2676
|
+
});
|
|
2677
|
+
return {
|
|
2678
|
+
any: resolvedElements.some((r) => maybeEqual(r, comparand)),
|
|
2679
|
+
confirmed: resolvedElements.some((r) => confirmedEqual(r, comparand))
|
|
2680
|
+
};
|
|
2681
|
+
}
|
|
2682
|
+
const scalarTag = isArrayTag(tag) ? void 0 : tag;
|
|
2683
|
+
const actualKind = scalarActualKind(raw, scalarTag, untrusted);
|
|
2684
|
+
const resolved = resolveScalar(comparand, present, raw, actualKind);
|
|
2685
|
+
return { any: maybeEqual(resolved, comparand), confirmed: confirmedEqual(resolved, comparand) };
|
|
2686
|
+
};
|
|
2687
|
+
const perCandidate = comparands.map(evalOne);
|
|
2688
|
+
const inMatch = perCandidate.some((r) => r.any);
|
|
2689
|
+
const confirmedAny = perCandidate.some((r) => r.confirmed);
|
|
2690
|
+
return op === "$in" ? inMatch : !confirmedAny;
|
|
2691
|
+
};
|
|
2692
|
+
}
|
|
2693
|
+
function compileFieldClause(field, value, plan, pathPrefix) {
|
|
2694
|
+
if (field.includes(".") || RESERVED_FIELD_NAMES.has(field) || field.startsWith("$")) return null;
|
|
2695
|
+
const planPath = `${pathPrefix}${field}`;
|
|
2696
|
+
if (!isPlainObject(value)) {
|
|
2697
|
+
const comparand = compileComparand(plan[planPath], value, true);
|
|
2698
|
+
if (!comparand) return null;
|
|
2699
|
+
return evalScalarLeaf(field, "$eq", comparand);
|
|
2700
|
+
}
|
|
2701
|
+
const entries = Object.entries(value);
|
|
2702
|
+
const predicates = [];
|
|
2703
|
+
for (const [op, opValue] of entries) {
|
|
2704
|
+
if (!op.startsWith("$")) return null;
|
|
2705
|
+
if (isScalarOp(op)) {
|
|
2706
|
+
const leaf = plan[`${planPath}.${op}`];
|
|
2707
|
+
const allowScalar = op === "$eq";
|
|
2708
|
+
const comparand = compileComparand(leaf, opValue, allowScalar);
|
|
2709
|
+
if (!comparand) return null;
|
|
2710
|
+
predicates.push(evalScalarLeaf(field, op, comparand));
|
|
2711
|
+
continue;
|
|
2712
|
+
}
|
|
2713
|
+
if (isArrayElementOp(op)) {
|
|
2714
|
+
if (!Array.isArray(opValue) || opValue.length === 0) return null;
|
|
2715
|
+
const allowScalar = op === "$in";
|
|
2716
|
+
const comparands = [];
|
|
2717
|
+
for (let i = 0; i < opValue.length; i += 1) {
|
|
2718
|
+
const leaf = plan[`${planPath}.${op}.${i}`];
|
|
2719
|
+
const comparand = compileComparand(leaf, opValue[i], allowScalar);
|
|
2720
|
+
if (!comparand) return null;
|
|
2721
|
+
comparands.push(comparand);
|
|
2722
|
+
}
|
|
2723
|
+
predicates.push(evalArrayElementOpLeaf(field, op, comparands));
|
|
2724
|
+
continue;
|
|
2725
|
+
}
|
|
2726
|
+
return null;
|
|
2727
|
+
}
|
|
2728
|
+
if (predicates.length === 0) return null;
|
|
2729
|
+
return (document2, t) => predicates.every((p) => p(document2, t));
|
|
2730
|
+
}
|
|
2731
|
+
function compileWhereObject(where, plan, depth, pathPrefix) {
|
|
2732
|
+
if (depth > MAX_WHERE_DEPTH2) return null;
|
|
2733
|
+
const predicates = [];
|
|
2734
|
+
for (const [key, value] of Object.entries(where)) {
|
|
2735
|
+
if (key === "$and" || key === "$or") {
|
|
2736
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
2737
|
+
const subPredicates = [];
|
|
2738
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
2739
|
+
const clause = value[i];
|
|
2740
|
+
if (!isPlainObject(clause)) return null;
|
|
2741
|
+
const compiled2 = compileWhereObject(clause, plan, depth + 1, `${pathPrefix}${key}.${i}.`);
|
|
2742
|
+
if (!compiled2) return null;
|
|
2743
|
+
subPredicates.push(compiled2);
|
|
2744
|
+
}
|
|
2745
|
+
predicates.push(
|
|
2746
|
+
key === "$and" ? (document2, t) => subPredicates.every((p) => p(document2, t)) : (document2, t) => subPredicates.some((p) => p(document2, t))
|
|
2747
|
+
);
|
|
2748
|
+
continue;
|
|
2749
|
+
}
|
|
2750
|
+
if (key.startsWith("$")) return null;
|
|
2751
|
+
const compiled = compileFieldClause(key, value, plan, pathPrefix);
|
|
2752
|
+
if (!compiled) return null;
|
|
2753
|
+
predicates.push(compiled);
|
|
2754
|
+
}
|
|
2755
|
+
return (document2, t) => predicates.every((p) => p(document2, t));
|
|
2756
|
+
}
|
|
2757
|
+
function compileMatcher(where, plan) {
|
|
2758
|
+
const compiled = compileWhereObject(where, plan, 0, "");
|
|
2759
|
+
if (!compiled) return null;
|
|
2760
|
+
return { matches: (document2, t) => compiled(document2, t) };
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2395
2763
|
// libs/sdk/src/modules/database.module.ts
|
|
2396
2764
|
var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
|
|
2397
2765
|
var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
|
|
@@ -2458,6 +2826,10 @@ var Paginator = class {
|
|
|
2458
2826
|
return { documents: result.documents, hasMore };
|
|
2459
2827
|
}
|
|
2460
2828
|
};
|
|
2829
|
+
var typedWhereV1Flags = /* @__PURE__ */ new WeakMap();
|
|
2830
|
+
function enableTypedWhereV1(builder) {
|
|
2831
|
+
typedWhereV1Flags.set(builder, true);
|
|
2832
|
+
}
|
|
2461
2833
|
var QueryBuilder = class {
|
|
2462
2834
|
constructor(http, basePath, filter) {
|
|
2463
2835
|
this.http = http;
|
|
@@ -2540,6 +2912,7 @@ var QueryBuilder = class {
|
|
|
2540
2912
|
if (this._before !== void 0) query["before"] = this._before;
|
|
2541
2913
|
if (this._after !== void 0) query["after"] = this._after;
|
|
2542
2914
|
if (this._fields) query["fields"] = this._fields.join(",");
|
|
2915
|
+
if (typedWhereV1Flags.get(this)) query["typedWhereV1"] = "true";
|
|
2543
2916
|
if (this._populate.length) {
|
|
2544
2917
|
query["populate"] = this._populate.map(
|
|
2545
2918
|
(p) => p.foreignField ? `${p.field}:${p.collection}:${p.foreignField}` : `${p.field}:${p.collection}`
|
|
@@ -2849,8 +3222,9 @@ var CollectionRef = class {
|
|
|
2849
3222
|
if (opts.sort) builder.sort(opts.sort);
|
|
2850
3223
|
if (opts.limit !== void 0) builder.limit(opts.limit);
|
|
2851
3224
|
if (opts.select) builder.select(opts.select);
|
|
3225
|
+
enableTypedWhereV1(builder);
|
|
2852
3226
|
const result = await builder.execute(signal);
|
|
2853
|
-
return result.documents;
|
|
3227
|
+
return { documents: result.documents, coercionPlan: result.coercionPlan };
|
|
2854
3228
|
}
|
|
2855
3229
|
const asCap = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : def;
|
|
2856
3230
|
const asPageSize = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : def;
|
|
@@ -2859,10 +3233,21 @@ var CollectionRef = class {
|
|
|
2859
3233
|
const pageSize = asPageSize(opts.limit, DEFAULT_CATCHUP_PAGE_SIZE);
|
|
2860
3234
|
const all = [];
|
|
2861
3235
|
let cursor;
|
|
3236
|
+
let coercionPlan;
|
|
3237
|
+
let coercionPlanCaptured = false;
|
|
3238
|
+
let coercionPlanMismatch = false;
|
|
2862
3239
|
for (let page = 0; page < maxPages && all.length < maxDocs; page++) {
|
|
2863
3240
|
const builder = this.find(opts.where).sort({ _id: 1 }).limit(pageSize);
|
|
2864
3241
|
if (opts.select) builder.select(opts.select);
|
|
3242
|
+
enableTypedWhereV1(builder);
|
|
2865
3243
|
const result = cursor === void 0 ? await builder.execute(signal) : await builder.after(cursor).execute(signal);
|
|
3244
|
+
if (!coercionPlanCaptured) {
|
|
3245
|
+
coercionPlan = result.coercionPlan;
|
|
3246
|
+
coercionPlanCaptured = true;
|
|
3247
|
+
} else if (!coercionPlanMismatch && JSON.stringify(result.coercionPlan) !== JSON.stringify(coercionPlan)) {
|
|
3248
|
+
coercionPlanMismatch = true;
|
|
3249
|
+
coercionPlan = void 0;
|
|
3250
|
+
}
|
|
2866
3251
|
const docs = result.documents;
|
|
2867
3252
|
if (docs.length === 0) break;
|
|
2868
3253
|
const room = maxDocs - all.length;
|
|
@@ -2879,7 +3264,7 @@ var CollectionRef = class {
|
|
|
2879
3264
|
}
|
|
2880
3265
|
cursor = nextCursor;
|
|
2881
3266
|
}
|
|
2882
|
-
return all;
|
|
3267
|
+
return { documents: all, coercionPlan };
|
|
2883
3268
|
}
|
|
2884
3269
|
async subscribeWithSnapshot(opts) {
|
|
2885
3270
|
if (!this.realtime) {
|
|
@@ -2894,7 +3279,7 @@ var CollectionRef = class {
|
|
|
2894
3279
|
if (!opts.where) return void 0;
|
|
2895
3280
|
const out = {};
|
|
2896
3281
|
for (const [k, v] of Object.entries(opts.where)) {
|
|
2897
|
-
if (typeof v === "
|
|
3282
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") {
|
|
2898
3283
|
out[k] = v;
|
|
2899
3284
|
}
|
|
2900
3285
|
}
|
|
@@ -2902,11 +3287,39 @@ var CollectionRef = class {
|
|
|
2902
3287
|
})();
|
|
2903
3288
|
const postFilterWhere = opts.where && Object.keys(opts.where).length > 0 && isMongoWhereFullySupported(opts.where) ? opts.where : void 0;
|
|
2904
3289
|
const postFilter = postFilterWhere !== void 0;
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
);
|
|
2909
|
-
|
|
3290
|
+
let typedMatcherPlan = null;
|
|
3291
|
+
let planCoercedSomething = false;
|
|
3292
|
+
const recomputeTypedMatcherPlan = (coercionPlan) => {
|
|
3293
|
+
planCoercedSomething = coercionPlan ? Object.values(coercionPlan).some((leaf) => leaf.kind !== "raw") : false;
|
|
3294
|
+
typedMatcherPlan = opts.where && Object.keys(opts.where).length > 0 && coercionPlan ? compileMatcher(opts.where, coercionPlan) : null;
|
|
3295
|
+
};
|
|
3296
|
+
const passesLiveGate = (event) => {
|
|
3297
|
+
if (typedMatcherPlan) {
|
|
3298
|
+
return !!event.document && typedMatcherPlan.matches(event.document, event.__t);
|
|
3299
|
+
}
|
|
3300
|
+
if (planCoercedSomething) {
|
|
3301
|
+
return true;
|
|
3302
|
+
}
|
|
3303
|
+
if (postFilterWhere) {
|
|
3304
|
+
return !!event.document && matchesMongoWhere(event.document, postFilterWhere);
|
|
3305
|
+
}
|
|
3306
|
+
return true;
|
|
3307
|
+
};
|
|
3308
|
+
let warnedAboutFallback = false;
|
|
3309
|
+
const warnIfNoGateAvailable = () => {
|
|
3310
|
+
if (warnedAboutFallback) return;
|
|
3311
|
+
if (opts.where && Object.keys(opts.where).length > 0 && !typedMatcherPlan && // No usable gate: either the #719 subset check failed, OR the snapshot
|
|
3312
|
+
// coerced a leaf but no typed matcher compiled (#725 C-1) — in the
|
|
3313
|
+
// latter case `passesLiveGate` deliberately over-delivers, which is
|
|
3314
|
+
// exactly the "onChange volume higher than expected" the warning
|
|
3315
|
+
// exists to explain.
|
|
3316
|
+
(!postFilter || planCoercedSomething)) {
|
|
3317
|
+
warnedAboutFallback = true;
|
|
3318
|
+
console.warn(
|
|
3319
|
+
`[spacelr] subscribeWithSnapshot on ${this.projectId}:${this.collectionName}: 'where' filter contains clauses (e.g. $gt, $ne, Date, dotted paths) that may not be enforced on the live stream. onChange may receive events beyond the filter; snapshot is still fully filtered.`
|
|
3320
|
+
);
|
|
3321
|
+
}
|
|
3322
|
+
};
|
|
2910
3323
|
const runRecovery = async () => {
|
|
2911
3324
|
currentUnsubscribe?.();
|
|
2912
3325
|
currentUnsubscribe = null;
|
|
@@ -2914,6 +3327,7 @@ var CollectionRef = class {
|
|
|
2914
3327
|
let recoveryAckResolved = false;
|
|
2915
3328
|
let recoverySnapshotDelivered = false;
|
|
2916
3329
|
const pendingRecoveryEvents = [];
|
|
3330
|
+
let freshRecoveryPlanReady = false;
|
|
2917
3331
|
let next;
|
|
2918
3332
|
try {
|
|
2919
3333
|
next = await realtime.subscribeWithCursorWithMeta({
|
|
@@ -2923,8 +3337,8 @@ var CollectionRef = class {
|
|
|
2923
3337
|
where: streamWhere,
|
|
2924
3338
|
onEvent: async ({ event }) => {
|
|
2925
3339
|
if (!isActive) return;
|
|
2926
|
-
if (
|
|
2927
|
-
return;
|
|
3340
|
+
if (freshRecoveryPlanReady) {
|
|
3341
|
+
if (!passesLiveGate(event)) return;
|
|
2928
3342
|
}
|
|
2929
3343
|
if (!recoverySnapshotDelivered) {
|
|
2930
3344
|
pendingRecoveryEvents.push(event);
|
|
@@ -2957,7 +3371,16 @@ var CollectionRef = class {
|
|
|
2957
3371
|
snapshotAbort = new AbortController();
|
|
2958
3372
|
let recoveryDocs;
|
|
2959
3373
|
try {
|
|
2960
|
-
|
|
3374
|
+
const recoveryResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
|
|
3375
|
+
recoveryDocs = recoveryResult.documents;
|
|
3376
|
+
recomputeTypedMatcherPlan(recoveryResult.coercionPlan);
|
|
3377
|
+
warnIfNoGateAvailable();
|
|
3378
|
+
freshRecoveryPlanReady = true;
|
|
3379
|
+
for (let i = pendingRecoveryEvents.length - 1; i >= 0; i--) {
|
|
3380
|
+
if (!passesLiveGate(pendingRecoveryEvents[i])) {
|
|
3381
|
+
pendingRecoveryEvents.splice(i, 1);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
2961
3384
|
} catch (err) {
|
|
2962
3385
|
if (!isActive) return;
|
|
2963
3386
|
if (err instanceof DOMException && err.name === "AbortError") return;
|
|
@@ -3048,6 +3471,7 @@ var CollectionRef = class {
|
|
|
3048
3471
|
let subscribeAckResolved = false;
|
|
3049
3472
|
let initialSnapshotDelivered = false;
|
|
3050
3473
|
const pendingInitialEvents = [];
|
|
3474
|
+
let initialPlanReady = false;
|
|
3051
3475
|
let initial;
|
|
3052
3476
|
try {
|
|
3053
3477
|
initial = await realtime.subscribeWithCursorWithMeta({
|
|
@@ -3057,7 +3481,7 @@ var CollectionRef = class {
|
|
|
3057
3481
|
where: streamWhere,
|
|
3058
3482
|
onEvent: async ({ event }) => {
|
|
3059
3483
|
if (!isActive) return;
|
|
3060
|
-
if (
|
|
3484
|
+
if (initialPlanReady && !passesLiveGate(event)) {
|
|
3061
3485
|
return;
|
|
3062
3486
|
}
|
|
3063
3487
|
if (!initialSnapshotDelivered) {
|
|
@@ -3104,7 +3528,16 @@ var CollectionRef = class {
|
|
|
3104
3528
|
currentUnsubscribe = initial.unsubscribe;
|
|
3105
3529
|
let snapshotDocs;
|
|
3106
3530
|
try {
|
|
3107
|
-
|
|
3531
|
+
const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
|
|
3532
|
+
snapshotDocs = snapshotResult.documents;
|
|
3533
|
+
recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
|
|
3534
|
+
initialPlanReady = true;
|
|
3535
|
+
for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
|
|
3536
|
+
if (!passesLiveGate(pendingInitialEvents[i])) {
|
|
3537
|
+
pendingInitialEvents.splice(i, 1);
|
|
3538
|
+
}
|
|
3539
|
+
}
|
|
3540
|
+
warnIfNoGateAvailable();
|
|
3108
3541
|
} catch (err) {
|
|
3109
3542
|
currentUnsubscribe?.();
|
|
3110
3543
|
isActive = false;
|