@spacelr/sdk 0.10.10 → 0.10.11

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.mjs CHANGED
@@ -684,6 +684,33 @@ function whereValueMatches(actual, expected) {
684
684
  if (Array.isArray(actual)) return actual.includes(expected);
685
685
  return actual === expected;
686
686
  }
687
+ var TYPED_EQUALITY_MAX_COMPARAND_LENGTH = 64;
688
+ 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})$/;
689
+ var TYPED_EQUALITY_OBJECT_ID_HEX = /^[0-9a-f]{24}$/i;
690
+ var NEVER_TYPED_FIELD = "_id";
691
+ function resolveFieldTypeTag(t, key) {
692
+ if (key === NEVER_TYPED_FIELD) return void 0;
693
+ if (!t || t.incomplete) return void 0;
694
+ const tag = t.fields?.[key];
695
+ return tag === "date" || tag === "objectId" ? tag : void 0;
696
+ }
697
+ function whereValueMatchesTyped(actual, expected, fieldType) {
698
+ if (fieldType === "date" && typeof actual === "string" && typeof expected === "string") {
699
+ 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)) {
700
+ const a = Date.parse(actual);
701
+ const e = Date.parse(expected);
702
+ if (!Number.isNaN(a) && !Number.isNaN(e)) return a === e;
703
+ }
704
+ return whereValueMatches(actual, expected);
705
+ }
706
+ if (fieldType === "objectId" && typeof actual === "string" && typeof expected === "string") {
707
+ 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)) {
708
+ return actual.toLowerCase() === expected.toLowerCase();
709
+ }
710
+ return whereValueMatches(actual, expected);
711
+ }
712
+ return whereValueMatches(actual, expected);
713
+ }
687
714
  function isFiniteScalar(v) {
688
715
  const t = typeof v;
689
716
  if (t === "string" || t === "boolean") return true;
@@ -1069,7 +1096,8 @@ var RealtimeClient = class {
1069
1096
  if (!where || Object.keys(where).length === 0) return true;
1070
1097
  if (!event.document) return true;
1071
1098
  for (const [key, value] of Object.entries(where)) {
1072
- if (!whereValueMatches(resolveWherePath(event.document, key), value)) {
1099
+ const fieldType = resolveFieldTypeTag(event.__t, key);
1100
+ if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
1073
1101
  return false;
1074
1102
  }
1075
1103
  }
@@ -1235,7 +1263,8 @@ var RealtimeClient = class {
1235
1263
  if (!where) return false;
1236
1264
  if (!event.document) return false;
1237
1265
  for (const [key, value] of Object.entries(where)) {
1238
- if (!whereValueMatches(resolveWherePath(event.document, key), value)) {
1266
+ const fieldType = resolveFieldTypeTag(event.__t, key);
1267
+ if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
1239
1268
  return false;
1240
1269
  }
1241
1270
  }
@@ -2348,6 +2377,262 @@ function isTimelineSourceStats(value) {
2348
2377
  return true;
2349
2378
  }
2350
2379
 
2380
+ // libs/sdk/src/core/typed-matcher.ts
2381
+ var MAX_WHERE_DEPTH2 = 10;
2382
+ var RESERVED_FIELD_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2383
+ var SCALAR_OPS = ["$eq", "$ne", "$gt", "$gte", "$lt", "$lte"];
2384
+ var ARRAY_ELEMENT_OPS = ["$in", "$nin"];
2385
+ function isScalarOp(op) {
2386
+ return SCALAR_OPS.includes(op);
2387
+ }
2388
+ function isArrayElementOp(op) {
2389
+ return ARRAY_ELEMENT_OPS.includes(op);
2390
+ }
2391
+ function isPlainObject(value) {
2392
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2393
+ }
2394
+ function isSafeComparableNumber(n) {
2395
+ return Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER;
2396
+ }
2397
+ function compileComparand(leaf, rawValue, allowScalar) {
2398
+ if (leaf?.kind === "date") return { kind: "date", epochMs: leaf.epochMs };
2399
+ if (leaf?.kind === "objectId") return { kind: "objectId", hex: leaf.hex };
2400
+ if (leaf?.kind === "raw") return null;
2401
+ if (typeof rawValue === "number" && isSafeComparableNumber(rawValue)) return { kind: "number", value: rawValue };
2402
+ if (allowScalar && (typeof rawValue === "string" || typeof rawValue === "boolean")) {
2403
+ return { kind: "scalar", value: rawValue };
2404
+ }
2405
+ return null;
2406
+ }
2407
+ function comparableValue(comparand) {
2408
+ switch (comparand.kind) {
2409
+ case "date":
2410
+ return comparand.epochMs;
2411
+ case "objectId":
2412
+ return comparand.hex;
2413
+ case "number":
2414
+ return comparand.value;
2415
+ case "scalar":
2416
+ return comparand.value;
2417
+ }
2418
+ }
2419
+ function scalarActualKind(raw, tag, untrusted) {
2420
+ if (untrusted) return "unknown";
2421
+ if (tag === "date") return "date";
2422
+ if (tag === "objectId") return "objectId";
2423
+ if (typeof raw === "number") return isSafeComparableNumber(raw) ? "number" : "unknown";
2424
+ if (typeof raw === "string" || typeof raw === "boolean") return "scalar";
2425
+ return "unknown";
2426
+ }
2427
+ function comparandNeedsTag(comparand) {
2428
+ return comparand.kind === "date" || comparand.kind === "objectId";
2429
+ }
2430
+ function isUntrusted(t, comparand) {
2431
+ if (t?.incomplete === true) return true;
2432
+ return comparandNeedsTag(comparand) && t?.fields === void 0;
2433
+ }
2434
+ function toEpochMs(raw) {
2435
+ if (typeof raw === "string") {
2436
+ const parsed = Date.parse(raw);
2437
+ return Number.isNaN(parsed) ? void 0 : parsed;
2438
+ }
2439
+ if (typeof raw === "number" && Number.isFinite(raw)) return raw;
2440
+ return void 0;
2441
+ }
2442
+ function resolveScalar(comparand, present, raw, actualKind) {
2443
+ if (!present) return { status: "absent" };
2444
+ if (actualKind === "unknown") return { status: "unknown" };
2445
+ if (comparand.kind === "date") {
2446
+ if (actualKind !== "date") return { status: "cross" };
2447
+ const epoch = toEpochMs(raw);
2448
+ if (epoch === void 0) return { status: "unknown" };
2449
+ return { status: "ok", value: epoch };
2450
+ }
2451
+ if (comparand.kind === "objectId") {
2452
+ if (actualKind !== "objectId") return { status: "cross" };
2453
+ if (typeof raw !== "string") return { status: "unknown" };
2454
+ return { status: "ok", value: raw.toLowerCase() };
2455
+ }
2456
+ if (actualKind === "date" || actualKind === "objectId") return { status: "unknown" };
2457
+ if (comparand.kind === "number") {
2458
+ if (actualKind !== "number") return { status: "cross" };
2459
+ return { status: "ok", value: raw };
2460
+ }
2461
+ if (actualKind !== "scalar" || typeof raw !== typeof comparand.value) return { status: "cross" };
2462
+ return { status: "ok", value: raw };
2463
+ }
2464
+ function confirmedEqual(resolved, comparand) {
2465
+ return resolved.status === "ok" && resolved.value === comparableValue(comparand);
2466
+ }
2467
+ function maybeEqual(resolved, comparand) {
2468
+ return resolved.status === "unknown" || confirmedEqual(resolved, comparand);
2469
+ }
2470
+ function compareOrder(a, b) {
2471
+ if (a === b) return 0;
2472
+ return a < b ? -1 : 1;
2473
+ }
2474
+ function satisfiesRange(op, cmp) {
2475
+ switch (op) {
2476
+ case "$gt":
2477
+ return cmp > 0;
2478
+ case "$gte":
2479
+ return cmp >= 0;
2480
+ case "$lt":
2481
+ return cmp < 0;
2482
+ case "$lte":
2483
+ return cmp <= 0;
2484
+ default:
2485
+ return false;
2486
+ }
2487
+ }
2488
+ function maybeSatisfiesRange(resolved, comparand, op) {
2489
+ if (resolved.status === "unknown") return true;
2490
+ if (resolved.status !== "ok") return false;
2491
+ return satisfiesRange(op, compareOrder(resolved.value, comparableValue(comparand)));
2492
+ }
2493
+ function fieldPresent(document2, field) {
2494
+ return Object.prototype.hasOwnProperty.call(document2, field);
2495
+ }
2496
+ function fieldTag(t, field) {
2497
+ return t?.fields?.[field];
2498
+ }
2499
+ function isArrayTag(tag) {
2500
+ return typeof tag === "object" && tag !== null && "array" in tag;
2501
+ }
2502
+ function evalScalarLeaf(field, op, comparand) {
2503
+ return (document2, t) => {
2504
+ const present = fieldPresent(document2, field);
2505
+ const raw = present ? document2[field] : void 0;
2506
+ const untrusted = isUntrusted(t, comparand);
2507
+ const tag = fieldTag(t, field);
2508
+ if (present && Array.isArray(raw)) {
2509
+ const arrayTag = isArrayTag(tag) ? tag.array : void 0;
2510
+ return evalArrayLeaf(raw, arrayTag, untrusted, op, comparand);
2511
+ }
2512
+ const scalarTag = isArrayTag(tag) ? void 0 : tag;
2513
+ const actualKind = scalarActualKind(raw, scalarTag, untrusted);
2514
+ const resolved = resolveScalar(comparand, present, raw, actualKind);
2515
+ if (op === "$ne") return !confirmedEqual(resolved, comparand);
2516
+ if (op === "$eq") return maybeEqual(resolved, comparand);
2517
+ return maybeSatisfiesRange(resolved, comparand, op);
2518
+ };
2519
+ }
2520
+ function evalArrayLeaf(raw, arrayTag, untrusted, op, comparand) {
2521
+ const resolvedElements = raw.map((el, i) => {
2522
+ const tag = arrayTag?.[i];
2523
+ const scalarTag = tag === "date" || tag === "objectId" ? tag : void 0;
2524
+ const actualKind = scalarActualKind(el, scalarTag, untrusted);
2525
+ return resolveScalar(comparand, true, el, actualKind);
2526
+ });
2527
+ if (op === "$ne") {
2528
+ return !resolvedElements.some((r) => confirmedEqual(r, comparand));
2529
+ }
2530
+ if (op === "$eq") {
2531
+ return resolvedElements.some((r) => maybeEqual(r, comparand));
2532
+ }
2533
+ return resolvedElements.some((r) => maybeSatisfiesRange(r, comparand, op));
2534
+ }
2535
+ function evalArrayElementOpLeaf(field, op, comparands) {
2536
+ return (document2, t) => {
2537
+ const present = fieldPresent(document2, field);
2538
+ const raw = present ? document2[field] : void 0;
2539
+ const tag = fieldTag(t, field);
2540
+ const evalOne = (comparand) => {
2541
+ const untrusted = isUntrusted(t, comparand);
2542
+ if (present && Array.isArray(raw)) {
2543
+ const arrayTag = isArrayTag(tag) ? tag.array : void 0;
2544
+ const resolvedElements = raw.map((el, i) => {
2545
+ const elTag = arrayTag?.[i];
2546
+ const scalarTag2 = elTag === "date" || elTag === "objectId" ? elTag : void 0;
2547
+ const actualKind2 = scalarActualKind(el, scalarTag2, untrusted);
2548
+ return resolveScalar(comparand, true, el, actualKind2);
2549
+ });
2550
+ return {
2551
+ any: resolvedElements.some((r) => maybeEqual(r, comparand)),
2552
+ confirmed: resolvedElements.some((r) => confirmedEqual(r, comparand))
2553
+ };
2554
+ }
2555
+ const scalarTag = isArrayTag(tag) ? void 0 : tag;
2556
+ const actualKind = scalarActualKind(raw, scalarTag, untrusted);
2557
+ const resolved = resolveScalar(comparand, present, raw, actualKind);
2558
+ return { any: maybeEqual(resolved, comparand), confirmed: confirmedEqual(resolved, comparand) };
2559
+ };
2560
+ const perCandidate = comparands.map(evalOne);
2561
+ const inMatch = perCandidate.some((r) => r.any);
2562
+ const confirmedAny = perCandidate.some((r) => r.confirmed);
2563
+ return op === "$in" ? inMatch : !confirmedAny;
2564
+ };
2565
+ }
2566
+ function compileFieldClause(field, value, plan, pathPrefix) {
2567
+ if (field.includes(".") || RESERVED_FIELD_NAMES.has(field) || field.startsWith("$")) return null;
2568
+ const planPath = `${pathPrefix}${field}`;
2569
+ if (!isPlainObject(value)) {
2570
+ const comparand = compileComparand(plan[planPath], value, true);
2571
+ if (!comparand) return null;
2572
+ return evalScalarLeaf(field, "$eq", comparand);
2573
+ }
2574
+ const entries = Object.entries(value);
2575
+ const predicates = [];
2576
+ for (const [op, opValue] of entries) {
2577
+ if (!op.startsWith("$")) return null;
2578
+ if (isScalarOp(op)) {
2579
+ const leaf = plan[`${planPath}.${op}`];
2580
+ const allowScalar = op === "$eq";
2581
+ const comparand = compileComparand(leaf, opValue, allowScalar);
2582
+ if (!comparand) return null;
2583
+ predicates.push(evalScalarLeaf(field, op, comparand));
2584
+ continue;
2585
+ }
2586
+ if (isArrayElementOp(op)) {
2587
+ if (!Array.isArray(opValue) || opValue.length === 0) return null;
2588
+ const allowScalar = op === "$in";
2589
+ const comparands = [];
2590
+ for (let i = 0; i < opValue.length; i += 1) {
2591
+ const leaf = plan[`${planPath}.${op}.${i}`];
2592
+ const comparand = compileComparand(leaf, opValue[i], allowScalar);
2593
+ if (!comparand) return null;
2594
+ comparands.push(comparand);
2595
+ }
2596
+ predicates.push(evalArrayElementOpLeaf(field, op, comparands));
2597
+ continue;
2598
+ }
2599
+ return null;
2600
+ }
2601
+ if (predicates.length === 0) return null;
2602
+ return (document2, t) => predicates.every((p) => p(document2, t));
2603
+ }
2604
+ function compileWhereObject(where, plan, depth, pathPrefix) {
2605
+ if (depth > MAX_WHERE_DEPTH2) return null;
2606
+ const predicates = [];
2607
+ for (const [key, value] of Object.entries(where)) {
2608
+ if (key === "$and" || key === "$or") {
2609
+ if (!Array.isArray(value) || value.length === 0) return null;
2610
+ const subPredicates = [];
2611
+ for (let i = 0; i < value.length; i += 1) {
2612
+ const clause = value[i];
2613
+ if (!isPlainObject(clause)) return null;
2614
+ const compiled2 = compileWhereObject(clause, plan, depth + 1, `${pathPrefix}${key}.${i}.`);
2615
+ if (!compiled2) return null;
2616
+ subPredicates.push(compiled2);
2617
+ }
2618
+ predicates.push(
2619
+ key === "$and" ? (document2, t) => subPredicates.every((p) => p(document2, t)) : (document2, t) => subPredicates.some((p) => p(document2, t))
2620
+ );
2621
+ continue;
2622
+ }
2623
+ if (key.startsWith("$")) return null;
2624
+ const compiled = compileFieldClause(key, value, plan, pathPrefix);
2625
+ if (!compiled) return null;
2626
+ predicates.push(compiled);
2627
+ }
2628
+ return (document2, t) => predicates.every((p) => p(document2, t));
2629
+ }
2630
+ function compileMatcher(where, plan) {
2631
+ const compiled = compileWhereObject(where, plan, 0, "");
2632
+ if (!compiled) return null;
2633
+ return { matches: (document2, t) => compiled(document2, t) };
2634
+ }
2635
+
2351
2636
  // libs/sdk/src/modules/database.module.ts
2352
2637
  var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
2353
2638
  var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
@@ -2414,6 +2699,10 @@ var Paginator = class {
2414
2699
  return { documents: result.documents, hasMore };
2415
2700
  }
2416
2701
  };
2702
+ var typedWhereV1Flags = /* @__PURE__ */ new WeakMap();
2703
+ function enableTypedWhereV1(builder) {
2704
+ typedWhereV1Flags.set(builder, true);
2705
+ }
2417
2706
  var QueryBuilder = class {
2418
2707
  constructor(http, basePath, filter) {
2419
2708
  this.http = http;
@@ -2496,6 +2785,7 @@ var QueryBuilder = class {
2496
2785
  if (this._before !== void 0) query["before"] = this._before;
2497
2786
  if (this._after !== void 0) query["after"] = this._after;
2498
2787
  if (this._fields) query["fields"] = this._fields.join(",");
2788
+ if (typedWhereV1Flags.get(this)) query["typedWhereV1"] = "true";
2499
2789
  if (this._populate.length) {
2500
2790
  query["populate"] = this._populate.map(
2501
2791
  (p) => p.foreignField ? `${p.field}:${p.collection}:${p.foreignField}` : `${p.field}:${p.collection}`
@@ -2805,8 +3095,9 @@ var CollectionRef = class {
2805
3095
  if (opts.sort) builder.sort(opts.sort);
2806
3096
  if (opts.limit !== void 0) builder.limit(opts.limit);
2807
3097
  if (opts.select) builder.select(opts.select);
3098
+ enableTypedWhereV1(builder);
2808
3099
  const result = await builder.execute(signal);
2809
- return result.documents;
3100
+ return { documents: result.documents, coercionPlan: result.coercionPlan };
2810
3101
  }
2811
3102
  const asCap = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : def;
2812
3103
  const asPageSize = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : def;
@@ -2815,10 +3106,21 @@ var CollectionRef = class {
2815
3106
  const pageSize = asPageSize(opts.limit, DEFAULT_CATCHUP_PAGE_SIZE);
2816
3107
  const all = [];
2817
3108
  let cursor;
3109
+ let coercionPlan;
3110
+ let coercionPlanCaptured = false;
3111
+ let coercionPlanMismatch = false;
2818
3112
  for (let page = 0; page < maxPages && all.length < maxDocs; page++) {
2819
3113
  const builder = this.find(opts.where).sort({ _id: 1 }).limit(pageSize);
2820
3114
  if (opts.select) builder.select(opts.select);
3115
+ enableTypedWhereV1(builder);
2821
3116
  const result = cursor === void 0 ? await builder.execute(signal) : await builder.after(cursor).execute(signal);
3117
+ if (!coercionPlanCaptured) {
3118
+ coercionPlan = result.coercionPlan;
3119
+ coercionPlanCaptured = true;
3120
+ } else if (!coercionPlanMismatch && JSON.stringify(result.coercionPlan) !== JSON.stringify(coercionPlan)) {
3121
+ coercionPlanMismatch = true;
3122
+ coercionPlan = void 0;
3123
+ }
2822
3124
  const docs = result.documents;
2823
3125
  if (docs.length === 0) break;
2824
3126
  const room = maxDocs - all.length;
@@ -2835,7 +3137,7 @@ var CollectionRef = class {
2835
3137
  }
2836
3138
  cursor = nextCursor;
2837
3139
  }
2838
- return all;
3140
+ return { documents: all, coercionPlan };
2839
3141
  }
2840
3142
  async subscribeWithSnapshot(opts) {
2841
3143
  if (!this.realtime) {
@@ -2850,7 +3152,7 @@ var CollectionRef = class {
2850
3152
  if (!opts.where) return void 0;
2851
3153
  const out = {};
2852
3154
  for (const [k, v] of Object.entries(opts.where)) {
2853
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
3155
+ if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") {
2854
3156
  out[k] = v;
2855
3157
  }
2856
3158
  }
@@ -2858,11 +3160,39 @@ var CollectionRef = class {
2858
3160
  })();
2859
3161
  const postFilterWhere = opts.where && Object.keys(opts.where).length > 0 && isMongoWhereFullySupported(opts.where) ? opts.where : void 0;
2860
3162
  const postFilter = postFilterWhere !== void 0;
2861
- if (opts.where && Object.keys(opts.where).length > 0 && !postFilter) {
2862
- console.warn(
2863
- `[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.`
2864
- );
2865
- }
3163
+ let typedMatcherPlan = null;
3164
+ let planCoercedSomething = false;
3165
+ const recomputeTypedMatcherPlan = (coercionPlan) => {
3166
+ planCoercedSomething = coercionPlan ? Object.values(coercionPlan).some((leaf) => leaf.kind !== "raw") : false;
3167
+ typedMatcherPlan = opts.where && Object.keys(opts.where).length > 0 && coercionPlan ? compileMatcher(opts.where, coercionPlan) : null;
3168
+ };
3169
+ const passesLiveGate = (event) => {
3170
+ if (typedMatcherPlan) {
3171
+ return !!event.document && typedMatcherPlan.matches(event.document, event.__t);
3172
+ }
3173
+ if (planCoercedSomething) {
3174
+ return true;
3175
+ }
3176
+ if (postFilterWhere) {
3177
+ return !!event.document && matchesMongoWhere(event.document, postFilterWhere);
3178
+ }
3179
+ return true;
3180
+ };
3181
+ let warnedAboutFallback = false;
3182
+ const warnIfNoGateAvailable = () => {
3183
+ if (warnedAboutFallback) return;
3184
+ if (opts.where && Object.keys(opts.where).length > 0 && !typedMatcherPlan && // No usable gate: either the #719 subset check failed, OR the snapshot
3185
+ // coerced a leaf but no typed matcher compiled (#725 C-1) — in the
3186
+ // latter case `passesLiveGate` deliberately over-delivers, which is
3187
+ // exactly the "onChange volume higher than expected" the warning
3188
+ // exists to explain.
3189
+ (!postFilter || planCoercedSomething)) {
3190
+ warnedAboutFallback = true;
3191
+ console.warn(
3192
+ `[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.`
3193
+ );
3194
+ }
3195
+ };
2866
3196
  const runRecovery = async () => {
2867
3197
  currentUnsubscribe?.();
2868
3198
  currentUnsubscribe = null;
@@ -2870,6 +3200,7 @@ var CollectionRef = class {
2870
3200
  let recoveryAckResolved = false;
2871
3201
  let recoverySnapshotDelivered = false;
2872
3202
  const pendingRecoveryEvents = [];
3203
+ let freshRecoveryPlanReady = false;
2873
3204
  let next;
2874
3205
  try {
2875
3206
  next = await realtime.subscribeWithCursorWithMeta({
@@ -2879,8 +3210,8 @@ var CollectionRef = class {
2879
3210
  where: streamWhere,
2880
3211
  onEvent: async ({ event }) => {
2881
3212
  if (!isActive) return;
2882
- if (postFilterWhere && (!event.document || !matchesMongoWhere(event.document, postFilterWhere))) {
2883
- return;
3213
+ if (freshRecoveryPlanReady) {
3214
+ if (!passesLiveGate(event)) return;
2884
3215
  }
2885
3216
  if (!recoverySnapshotDelivered) {
2886
3217
  pendingRecoveryEvents.push(event);
@@ -2913,7 +3244,16 @@ var CollectionRef = class {
2913
3244
  snapshotAbort = new AbortController();
2914
3245
  let recoveryDocs;
2915
3246
  try {
2916
- recoveryDocs = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3247
+ const recoveryResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3248
+ recoveryDocs = recoveryResult.documents;
3249
+ recomputeTypedMatcherPlan(recoveryResult.coercionPlan);
3250
+ warnIfNoGateAvailable();
3251
+ freshRecoveryPlanReady = true;
3252
+ for (let i = pendingRecoveryEvents.length - 1; i >= 0; i--) {
3253
+ if (!passesLiveGate(pendingRecoveryEvents[i])) {
3254
+ pendingRecoveryEvents.splice(i, 1);
3255
+ }
3256
+ }
2917
3257
  } catch (err) {
2918
3258
  if (!isActive) return;
2919
3259
  if (err instanceof DOMException && err.name === "AbortError") return;
@@ -3004,6 +3344,7 @@ var CollectionRef = class {
3004
3344
  let subscribeAckResolved = false;
3005
3345
  let initialSnapshotDelivered = false;
3006
3346
  const pendingInitialEvents = [];
3347
+ let initialPlanReady = false;
3007
3348
  let initial;
3008
3349
  try {
3009
3350
  initial = await realtime.subscribeWithCursorWithMeta({
@@ -3013,7 +3354,7 @@ var CollectionRef = class {
3013
3354
  where: streamWhere,
3014
3355
  onEvent: async ({ event }) => {
3015
3356
  if (!isActive) return;
3016
- if (postFilterWhere && (!event.document || !matchesMongoWhere(event.document, postFilterWhere))) {
3357
+ if (initialPlanReady && !passesLiveGate(event)) {
3017
3358
  return;
3018
3359
  }
3019
3360
  if (!initialSnapshotDelivered) {
@@ -3060,7 +3401,16 @@ var CollectionRef = class {
3060
3401
  currentUnsubscribe = initial.unsubscribe;
3061
3402
  let snapshotDocs;
3062
3403
  try {
3063
- snapshotDocs = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3404
+ const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
3405
+ snapshotDocs = snapshotResult.documents;
3406
+ recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
3407
+ initialPlanReady = true;
3408
+ for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
3409
+ if (!passesLiveGate(pendingInitialEvents[i])) {
3410
+ pendingInitialEvents.splice(i, 1);
3411
+ }
3412
+ }
3413
+ warnIfNoGateAvailable();
3064
3414
  } catch (err) {
3065
3415
  currentUnsubscribe?.();
3066
3416
  isActive = false;