@noy-db/core 0.2.0 → 0.3.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.js CHANGED
@@ -583,7 +583,627 @@ function formatDiff(changes) {
583
583
  }).join("\n");
584
584
  }
585
585
 
586
+ // src/query/predicate.ts
587
+ function readPath(record, path) {
588
+ if (record === null || record === void 0) return void 0;
589
+ if (!path.includes(".")) {
590
+ return record[path];
591
+ }
592
+ const segments = path.split(".");
593
+ let cursor = record;
594
+ for (const segment of segments) {
595
+ if (cursor === null || cursor === void 0) return void 0;
596
+ cursor = cursor[segment];
597
+ }
598
+ return cursor;
599
+ }
600
+ function evaluateFieldClause(record, clause) {
601
+ const actual = readPath(record, clause.field);
602
+ const { op, value } = clause;
603
+ switch (op) {
604
+ case "==":
605
+ return actual === value;
606
+ case "!=":
607
+ return actual !== value;
608
+ case "<":
609
+ return isComparable(actual, value) && actual < value;
610
+ case "<=":
611
+ return isComparable(actual, value) && actual <= value;
612
+ case ">":
613
+ return isComparable(actual, value) && actual > value;
614
+ case ">=":
615
+ return isComparable(actual, value) && actual >= value;
616
+ case "in":
617
+ return Array.isArray(value) && value.includes(actual);
618
+ case "contains":
619
+ if (typeof actual === "string") return typeof value === "string" && actual.includes(value);
620
+ if (Array.isArray(actual)) return actual.includes(value);
621
+ return false;
622
+ case "startsWith":
623
+ return typeof actual === "string" && typeof value === "string" && actual.startsWith(value);
624
+ case "between": {
625
+ if (!Array.isArray(value) || value.length !== 2) return false;
626
+ const [lo, hi] = value;
627
+ if (!isComparable(actual, lo) || !isComparable(actual, hi)) return false;
628
+ return actual >= lo && actual <= hi;
629
+ }
630
+ default: {
631
+ const _exhaustive = op;
632
+ void _exhaustive;
633
+ return false;
634
+ }
635
+ }
636
+ }
637
+ function isComparable(a, b) {
638
+ if (typeof a === "number" && typeof b === "number") return true;
639
+ if (typeof a === "string" && typeof b === "string") return true;
640
+ if (a instanceof Date && b instanceof Date) return true;
641
+ return false;
642
+ }
643
+ function evaluateClause(record, clause) {
644
+ switch (clause.type) {
645
+ case "field":
646
+ return evaluateFieldClause(record, clause);
647
+ case "filter":
648
+ return clause.fn(record);
649
+ case "group":
650
+ if (clause.op === "and") {
651
+ for (const child of clause.clauses) {
652
+ if (!evaluateClause(record, child)) return false;
653
+ }
654
+ return true;
655
+ } else {
656
+ for (const child of clause.clauses) {
657
+ if (evaluateClause(record, child)) return true;
658
+ }
659
+ return false;
660
+ }
661
+ }
662
+ }
663
+
664
+ // src/query/builder.ts
665
+ var EMPTY_PLAN = {
666
+ clauses: [],
667
+ orderBy: [],
668
+ limit: void 0,
669
+ offset: 0
670
+ };
671
+ var Query = class _Query {
672
+ source;
673
+ plan;
674
+ constructor(source, plan = EMPTY_PLAN) {
675
+ this.source = source;
676
+ this.plan = plan;
677
+ }
678
+ /** Add a field comparison. Multiple where() calls are AND-combined. */
679
+ where(field, op, value) {
680
+ const clause = { type: "field", field, op, value };
681
+ return new _Query(this.source, {
682
+ ...this.plan,
683
+ clauses: [...this.plan.clauses, clause]
684
+ });
685
+ }
686
+ /**
687
+ * Logical OR group. Pass a callback that builds a sub-query.
688
+ * Each clause inside the callback is OR-combined; the group itself
689
+ * joins the parent plan with AND.
690
+ */
691
+ or(builder) {
692
+ const sub = builder(new _Query(this.source));
693
+ const group = {
694
+ type: "group",
695
+ op: "or",
696
+ clauses: sub.plan.clauses
697
+ };
698
+ return new _Query(this.source, {
699
+ ...this.plan,
700
+ clauses: [...this.plan.clauses, group]
701
+ });
702
+ }
703
+ /**
704
+ * Logical AND group. Same shape as `or()` but every clause inside the group
705
+ * must match. Useful for explicit grouping inside a larger OR.
706
+ */
707
+ and(builder) {
708
+ const sub = builder(new _Query(this.source));
709
+ const group = {
710
+ type: "group",
711
+ op: "and",
712
+ clauses: sub.plan.clauses
713
+ };
714
+ return new _Query(this.source, {
715
+ ...this.plan,
716
+ clauses: [...this.plan.clauses, group]
717
+ });
718
+ }
719
+ /** Escape hatch: add an arbitrary predicate function. Not serializable. */
720
+ filter(fn) {
721
+ const clause = {
722
+ type: "filter",
723
+ fn
724
+ };
725
+ return new _Query(this.source, {
726
+ ...this.plan,
727
+ clauses: [...this.plan.clauses, clause]
728
+ });
729
+ }
730
+ /** Sort by a field. Subsequent calls are tie-breakers. */
731
+ orderBy(field, direction = "asc") {
732
+ return new _Query(this.source, {
733
+ ...this.plan,
734
+ orderBy: [...this.plan.orderBy, { field, direction }]
735
+ });
736
+ }
737
+ /** Cap the result size. */
738
+ limit(n) {
739
+ return new _Query(this.source, { ...this.plan, limit: n });
740
+ }
741
+ /** Skip the first N matching records (after ordering). */
742
+ offset(n) {
743
+ return new _Query(this.source, { ...this.plan, offset: n });
744
+ }
745
+ /** Execute the plan and return the matching records. */
746
+ toArray() {
747
+ return executePlanWithSource(this.source, this.plan);
748
+ }
749
+ /** Return the first matching record, or null. */
750
+ first() {
751
+ const result = executePlanWithSource(this.source, { ...this.plan, limit: 1 });
752
+ return result[0] ?? null;
753
+ }
754
+ /** Return the number of matching records (after where/filter, before limit). */
755
+ count() {
756
+ const { candidates, remainingClauses } = candidateRecords(this.source, this.plan.clauses);
757
+ if (remainingClauses.length === 0) return candidates.length;
758
+ return filterRecords(candidates, remainingClauses).length;
759
+ }
760
+ /**
761
+ * Re-run the query whenever the source notifies of changes.
762
+ * Returns an unsubscribe function. The callback receives the latest result.
763
+ * Throws if the source does not support subscriptions.
764
+ */
765
+ subscribe(cb) {
766
+ if (!this.source.subscribe) {
767
+ throw new Error("Query source does not support subscriptions. Pass a source with a subscribe() method.");
768
+ }
769
+ cb(this.toArray());
770
+ return this.source.subscribe(() => cb(this.toArray()));
771
+ }
772
+ /**
773
+ * Return the plan as a JSON-friendly object. FilterClause entries are
774
+ * stripped (their `fn` cannot be serialized) and replaced with
775
+ * { type: 'filter', fn: '[function]' } so devtools can still see them.
776
+ */
777
+ toPlan() {
778
+ return serializePlan(this.plan);
779
+ }
780
+ };
781
+ function executePlanWithSource(source, plan) {
782
+ const { candidates, remainingClauses } = candidateRecords(source, plan.clauses);
783
+ let result = remainingClauses.length === 0 ? [...candidates] : filterRecords(candidates, remainingClauses);
784
+ if (plan.orderBy.length > 0) {
785
+ result = sortRecords(result, plan.orderBy);
786
+ }
787
+ if (plan.offset > 0) {
788
+ result = result.slice(plan.offset);
789
+ }
790
+ if (plan.limit !== void 0) {
791
+ result = result.slice(0, plan.limit);
792
+ }
793
+ return result;
794
+ }
795
+ function candidateRecords(source, clauses) {
796
+ const indexes = source.getIndexes?.();
797
+ if (!indexes || !source.lookupById || clauses.length === 0) {
798
+ return { candidates: source.snapshot(), remainingClauses: clauses };
799
+ }
800
+ const lookupById = (id) => source.lookupById?.(id);
801
+ for (let i = 0; i < clauses.length; i++) {
802
+ const clause = clauses[i];
803
+ if (clause.type !== "field") continue;
804
+ if (!indexes.has(clause.field)) continue;
805
+ let ids = null;
806
+ if (clause.op === "==") {
807
+ ids = indexes.lookupEqual(clause.field, clause.value);
808
+ } else if (clause.op === "in" && Array.isArray(clause.value)) {
809
+ ids = indexes.lookupIn(clause.field, clause.value);
810
+ }
811
+ if (ids !== null) {
812
+ const remaining = [];
813
+ for (let j = 0; j < clauses.length; j++) {
814
+ if (j !== i) remaining.push(clauses[j]);
815
+ }
816
+ return {
817
+ candidates: materializeIds(ids, lookupById),
818
+ remainingClauses: remaining
819
+ };
820
+ }
821
+ }
822
+ return { candidates: source.snapshot(), remainingClauses: clauses };
823
+ }
824
+ function materializeIds(ids, lookupById) {
825
+ const out = [];
826
+ for (const id of ids) {
827
+ const record = lookupById(id);
828
+ if (record !== void 0) out.push(record);
829
+ }
830
+ return out;
831
+ }
832
+ function executePlan(records, plan) {
833
+ let result = filterRecords(records, plan.clauses);
834
+ if (plan.orderBy.length > 0) {
835
+ result = sortRecords(result, plan.orderBy);
836
+ }
837
+ if (plan.offset > 0) {
838
+ result = result.slice(plan.offset);
839
+ }
840
+ if (plan.limit !== void 0) {
841
+ result = result.slice(0, plan.limit);
842
+ }
843
+ return result;
844
+ }
845
+ function filterRecords(records, clauses) {
846
+ if (clauses.length === 0) return [...records];
847
+ const out = [];
848
+ for (const r of records) {
849
+ let matches = true;
850
+ for (const clause of clauses) {
851
+ if (!evaluateClause(r, clause)) {
852
+ matches = false;
853
+ break;
854
+ }
855
+ }
856
+ if (matches) out.push(r);
857
+ }
858
+ return out;
859
+ }
860
+ function sortRecords(records, orderBy) {
861
+ return [...records].sort((a, b) => {
862
+ for (const { field, direction } of orderBy) {
863
+ const av = readField(a, field);
864
+ const bv = readField(b, field);
865
+ const cmp = compareValues(av, bv);
866
+ if (cmp !== 0) return direction === "asc" ? cmp : -cmp;
867
+ }
868
+ return 0;
869
+ });
870
+ }
871
+ function readField(record, field) {
872
+ if (record === null || record === void 0) return void 0;
873
+ if (!field.includes(".")) {
874
+ return record[field];
875
+ }
876
+ const segments = field.split(".");
877
+ let cursor = record;
878
+ for (const segment of segments) {
879
+ if (cursor === null || cursor === void 0) return void 0;
880
+ cursor = cursor[segment];
881
+ }
882
+ return cursor;
883
+ }
884
+ function compareValues(a, b) {
885
+ if (a === void 0 || a === null) return b === void 0 || b === null ? 0 : 1;
886
+ if (b === void 0 || b === null) return -1;
887
+ if (typeof a === "number" && typeof b === "number") return a - b;
888
+ if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
889
+ if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
890
+ return 0;
891
+ }
892
+ function serializePlan(plan) {
893
+ return {
894
+ clauses: plan.clauses.map(serializeClause),
895
+ orderBy: plan.orderBy,
896
+ limit: plan.limit,
897
+ offset: plan.offset
898
+ };
899
+ }
900
+ function serializeClause(clause) {
901
+ if (clause.type === "filter") {
902
+ return { type: "filter", fn: "[function]" };
903
+ }
904
+ if (clause.type === "group") {
905
+ return {
906
+ type: "group",
907
+ op: clause.op,
908
+ clauses: clause.clauses.map(serializeClause)
909
+ };
910
+ }
911
+ return clause;
912
+ }
913
+
914
+ // src/query/indexes.ts
915
+ var CollectionIndexes = class {
916
+ indexes = /* @__PURE__ */ new Map();
917
+ /**
918
+ * Declare an index. Subsequent record additions are tracked under it.
919
+ * Calling this twice for the same field is a no-op (idempotent).
920
+ */
921
+ declare(field) {
922
+ if (this.indexes.has(field)) return;
923
+ this.indexes.set(field, { field, buckets: /* @__PURE__ */ new Map() });
924
+ }
925
+ /** True if the given field has a declared index. */
926
+ has(field) {
927
+ return this.indexes.has(field);
928
+ }
929
+ /** All declared field names, in declaration order. */
930
+ fields() {
931
+ return [...this.indexes.keys()];
932
+ }
933
+ /**
934
+ * Build all declared indexes from a snapshot of records.
935
+ * Called once per hydration. O(N × indexes.size).
936
+ */
937
+ build(records) {
938
+ for (const idx of this.indexes.values()) {
939
+ idx.buckets.clear();
940
+ for (const { id, record } of records) {
941
+ addToIndex(idx, id, record);
942
+ }
943
+ }
944
+ }
945
+ /**
946
+ * Insert or update a single record across all indexes.
947
+ * Called by `Collection.put()` after the encrypted write succeeds.
948
+ *
949
+ * If `previousRecord` is provided, the record is removed from any old
950
+ * buckets first — this is the update path. Pass `null` for fresh adds.
951
+ */
952
+ upsert(id, newRecord, previousRecord) {
953
+ if (this.indexes.size === 0) return;
954
+ if (previousRecord !== null) {
955
+ this.remove(id, previousRecord);
956
+ }
957
+ for (const idx of this.indexes.values()) {
958
+ addToIndex(idx, id, newRecord);
959
+ }
960
+ }
961
+ /**
962
+ * Remove a record from all indexes. Called by `Collection.delete()`
963
+ * (and as the first half of `upsert` for the update path).
964
+ */
965
+ remove(id, record) {
966
+ if (this.indexes.size === 0) return;
967
+ for (const idx of this.indexes.values()) {
968
+ removeFromIndex(idx, id, record);
969
+ }
970
+ }
971
+ /** Drop all index data. Called when the collection is invalidated. */
972
+ clear() {
973
+ for (const idx of this.indexes.values()) {
974
+ idx.buckets.clear();
975
+ }
976
+ }
977
+ /**
978
+ * Equality lookup: return the set of record ids whose `field` matches
979
+ * the given value. Returns `null` if no index covers the field — the
980
+ * caller should fall back to a linear scan.
981
+ *
982
+ * The returned Set is a reference to the index's internal storage —
983
+ * callers must NOT mutate it.
984
+ */
985
+ lookupEqual(field, value) {
986
+ const idx = this.indexes.get(field);
987
+ if (!idx) return null;
988
+ const key = stringifyKey(value);
989
+ return idx.buckets.get(key) ?? EMPTY_SET;
990
+ }
991
+ /**
992
+ * Set lookup: return the union of record ids whose `field` matches any
993
+ * of the given values. Returns `null` if no index covers the field.
994
+ */
995
+ lookupIn(field, values) {
996
+ const idx = this.indexes.get(field);
997
+ if (!idx) return null;
998
+ const out = /* @__PURE__ */ new Set();
999
+ for (const value of values) {
1000
+ const key = stringifyKey(value);
1001
+ const bucket = idx.buckets.get(key);
1002
+ if (bucket) {
1003
+ for (const id of bucket) out.add(id);
1004
+ }
1005
+ }
1006
+ return out;
1007
+ }
1008
+ };
1009
+ var EMPTY_SET = /* @__PURE__ */ new Set();
1010
+ function stringifyKey(value) {
1011
+ if (value === null || value === void 0) return "\0NULL\0";
1012
+ if (typeof value === "string") return value;
1013
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1014
+ if (value instanceof Date) return value.toISOString();
1015
+ return "\0OBJECT\0";
1016
+ }
1017
+ function addToIndex(idx, id, record) {
1018
+ const value = readPath(record, idx.field);
1019
+ if (value === null || value === void 0) return;
1020
+ const key = stringifyKey(value);
1021
+ let bucket = idx.buckets.get(key);
1022
+ if (!bucket) {
1023
+ bucket = /* @__PURE__ */ new Set();
1024
+ idx.buckets.set(key, bucket);
1025
+ }
1026
+ bucket.add(id);
1027
+ }
1028
+ function removeFromIndex(idx, id, record) {
1029
+ const value = readPath(record, idx.field);
1030
+ if (value === null || value === void 0) return;
1031
+ const key = stringifyKey(value);
1032
+ const bucket = idx.buckets.get(key);
1033
+ if (!bucket) return;
1034
+ bucket.delete(id);
1035
+ if (bucket.size === 0) idx.buckets.delete(key);
1036
+ }
1037
+
1038
+ // src/cache/lru.ts
1039
+ var Lru = class {
1040
+ entries = /* @__PURE__ */ new Map();
1041
+ maxRecords;
1042
+ maxBytes;
1043
+ currentBytes = 0;
1044
+ hits = 0;
1045
+ misses = 0;
1046
+ evictions = 0;
1047
+ constructor(options) {
1048
+ if (options.maxRecords === void 0 && options.maxBytes === void 0) {
1049
+ throw new Error("Lru: must specify maxRecords, maxBytes, or both");
1050
+ }
1051
+ this.maxRecords = options.maxRecords;
1052
+ this.maxBytes = options.maxBytes;
1053
+ }
1054
+ /**
1055
+ * Look up a key. Hits promote the entry to most-recently-used; misses
1056
+ * return undefined. Both update the running stats counters.
1057
+ */
1058
+ get(key) {
1059
+ const entry = this.entries.get(key);
1060
+ if (!entry) {
1061
+ this.misses++;
1062
+ return void 0;
1063
+ }
1064
+ this.entries.delete(key);
1065
+ this.entries.set(key, entry);
1066
+ this.hits++;
1067
+ return entry.value;
1068
+ }
1069
+ /**
1070
+ * Insert or update a key. If the key already exists, its size is
1071
+ * accounted for and the entry is promoted to MRU. After insertion,
1072
+ * eviction runs to maintain both budgets.
1073
+ */
1074
+ set(key, value, size) {
1075
+ const existing = this.entries.get(key);
1076
+ if (existing) {
1077
+ this.currentBytes -= existing.size;
1078
+ this.entries.delete(key);
1079
+ }
1080
+ this.entries.set(key, { value, size });
1081
+ this.currentBytes += size;
1082
+ this.evictUntilUnderBudget();
1083
+ }
1084
+ /**
1085
+ * Remove a key without affecting hit/miss stats. Used by `Collection.delete()`.
1086
+ * Returns true if the key was present.
1087
+ */
1088
+ remove(key) {
1089
+ const existing = this.entries.get(key);
1090
+ if (!existing) return false;
1091
+ this.currentBytes -= existing.size;
1092
+ this.entries.delete(key);
1093
+ return true;
1094
+ }
1095
+ /** True if the cache currently holds an entry for the given key. */
1096
+ has(key) {
1097
+ return this.entries.has(key);
1098
+ }
1099
+ /**
1100
+ * Drop every entry. Stats counters survive — call `resetStats()` if you
1101
+ * want a clean slate. Used by `Collection.invalidate()` on key rotation.
1102
+ */
1103
+ clear() {
1104
+ this.entries.clear();
1105
+ this.currentBytes = 0;
1106
+ }
1107
+ /** Reset hit/miss/eviction counters to zero. Does NOT touch entries. */
1108
+ resetStats() {
1109
+ this.hits = 0;
1110
+ this.misses = 0;
1111
+ this.evictions = 0;
1112
+ }
1113
+ /** Snapshot of current cache statistics. Cheap — no copying. */
1114
+ stats() {
1115
+ return {
1116
+ hits: this.hits,
1117
+ misses: this.misses,
1118
+ evictions: this.evictions,
1119
+ size: this.entries.size,
1120
+ bytes: this.currentBytes
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Iterate over all currently-cached values. Order is least-recently-used
1125
+ * first. Used by tests and devtools — production callers should use
1126
+ * `Collection.scan()` instead.
1127
+ */
1128
+ *values() {
1129
+ for (const entry of this.entries.values()) yield entry.value;
1130
+ }
1131
+ /**
1132
+ * Walk the cache from the LRU end and drop entries until both budgets
1133
+ * are satisfied. Called after every `set()`. Single pass — entries are
1134
+ * never re-promoted during eviction.
1135
+ */
1136
+ evictUntilUnderBudget() {
1137
+ while (this.overBudget()) {
1138
+ const oldest = this.entries.keys().next();
1139
+ if (oldest.done) return;
1140
+ const key = oldest.value;
1141
+ const entry = this.entries.get(key);
1142
+ if (entry) this.currentBytes -= entry.size;
1143
+ this.entries.delete(key);
1144
+ this.evictions++;
1145
+ }
1146
+ }
1147
+ overBudget() {
1148
+ if (this.maxRecords !== void 0 && this.entries.size > this.maxRecords) return true;
1149
+ if (this.maxBytes !== void 0 && this.currentBytes > this.maxBytes) return true;
1150
+ return false;
1151
+ }
1152
+ };
1153
+
1154
+ // src/cache/policy.ts
1155
+ var UNITS = {
1156
+ "": 1,
1157
+ "B": 1,
1158
+ "KB": 1024,
1159
+ "MB": 1024 * 1024,
1160
+ "GB": 1024 * 1024 * 1024
1161
+ // 'TB' deliberately not supported — if you need it, you're not using NOYDB.
1162
+ };
1163
+ function parseBytes(input) {
1164
+ if (typeof input === "number") {
1165
+ if (!Number.isFinite(input) || input <= 0) {
1166
+ throw new Error(`parseBytes: numeric input must be a positive finite number, got ${String(input)}`);
1167
+ }
1168
+ return Math.floor(input);
1169
+ }
1170
+ const trimmed = input.trim();
1171
+ if (trimmed === "") {
1172
+ throw new Error("parseBytes: empty string is not a valid byte budget");
1173
+ }
1174
+ const match = /^([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)$/.exec(trimmed);
1175
+ if (!match) {
1176
+ throw new Error(`parseBytes: invalid byte budget "${input}". Expected format: "1024", "50KB", "50MB", "1GB"`);
1177
+ }
1178
+ const value = parseFloat(match[1]);
1179
+ const unit = (match[2] ?? "").toUpperCase();
1180
+ if (!(unit in UNITS)) {
1181
+ throw new Error(`parseBytes: unknown unit "${match[2]}" in "${input}". Supported: B, KB, MB, GB`);
1182
+ }
1183
+ const bytes = Math.floor(value * UNITS[unit]);
1184
+ if (bytes <= 0) {
1185
+ throw new Error(`parseBytes: byte budget must be > 0, got ${bytes} from "${input}"`);
1186
+ }
1187
+ return bytes;
1188
+ }
1189
+ function estimateRecordBytes(record) {
1190
+ try {
1191
+ return JSON.stringify(record).length;
1192
+ } catch {
1193
+ return 0;
1194
+ }
1195
+ }
1196
+
586
1197
  // src/collection.ts
1198
+ var fallbackWarned = /* @__PURE__ */ new Set();
1199
+ function warnOnceFallback(adapterName) {
1200
+ if (fallbackWarned.has(adapterName)) return;
1201
+ fallbackWarned.add(adapterName);
1202
+ if (typeof process !== "undefined" && process.env["NODE_ENV"] === "test") return;
1203
+ console.warn(
1204
+ `[noy-db] Adapter "${adapterName}" does not implement listPage(); Collection.scan()/listPage() are using a synthetic fallback (slower). Add a listPage method to opt into the streaming fast path.`
1205
+ );
1206
+ }
587
1207
  var Collection = class {
588
1208
  adapter;
589
1209
  compartment;
@@ -594,9 +1214,41 @@ var Collection = class {
594
1214
  getDEK;
595
1215
  onDirty;
596
1216
  historyConfig;
597
- // In-memory cache of decrypted records
1217
+ // In-memory cache of decrypted records (eager mode only). Lazy mode
1218
+ // uses `lru` instead. Both fields exist so a single Collection instance
1219
+ // doesn't need a runtime branch on every cache access.
598
1220
  cache = /* @__PURE__ */ new Map();
599
1221
  hydrated = false;
1222
+ /**
1223
+ * Lazy mode flag. `true` when constructed with `prefetch: false`.
1224
+ * In lazy mode the cache is bounded by an LRU and `list()`/`query()`
1225
+ * throw — callers must use `scan()` or per-id `get()` instead.
1226
+ */
1227
+ lazy;
1228
+ /**
1229
+ * LRU cache for lazy mode. Only allocated when `prefetch: false` is set.
1230
+ * Stores `{ record, version }` entries the same shape as `this.cache`.
1231
+ * Tree-shaking note: importing Collection without setting `prefetch:false`
1232
+ * still pulls in the Lru class today; future bundle-size work could
1233
+ * lazy-import the cache module.
1234
+ */
1235
+ lru;
1236
+ /**
1237
+ * In-memory secondary indexes for the query DSL.
1238
+ *
1239
+ * Built during `ensureHydrated()` and maintained on every put/delete.
1240
+ * The query executor consults these for `==` and `in` operators on
1241
+ * indexed fields, falling back to a linear scan for unindexed fields
1242
+ * or unsupported operators.
1243
+ *
1244
+ * v0.3 ships in-memory only — persistence as encrypted blobs is a
1245
+ * follow-up. See `query/indexes.ts` for the design rationale.
1246
+ *
1247
+ * Indexes are INCOMPATIBLE with lazy mode in v0.3 — the constructor
1248
+ * rejects the combination because evicted records would silently
1249
+ * disappear from the index without notification.
1250
+ */
1251
+ indexes = new CollectionIndexes();
600
1252
  constructor(opts) {
601
1253
  this.adapter = opts.adapter;
602
1254
  this.compartment = opts.compartment;
@@ -607,9 +1259,43 @@ var Collection = class {
607
1259
  this.getDEK = opts.getDEK;
608
1260
  this.onDirty = opts.onDirty;
609
1261
  this.historyConfig = opts.historyConfig ?? { enabled: true };
1262
+ this.lazy = opts.prefetch === false;
1263
+ if (this.lazy) {
1264
+ if (opts.indexes && opts.indexes.length > 0) {
1265
+ throw new Error(
1266
+ `Collection "${this.name}": secondary indexes are not supported in lazy mode (prefetch: false). Either remove the indexes option or use prefetch: true. Index + lazy support is tracked as a v0.4 follow-up.`
1267
+ );
1268
+ }
1269
+ if (!opts.cache || opts.cache.maxRecords === void 0 && opts.cache.maxBytes === void 0) {
1270
+ throw new Error(
1271
+ `Collection "${this.name}": lazy mode (prefetch: false) requires a cache option with maxRecords and/or maxBytes. An unbounded lazy cache defeats the purpose.`
1272
+ );
1273
+ }
1274
+ const lruOptions = {};
1275
+ if (opts.cache.maxRecords !== void 0) lruOptions.maxRecords = opts.cache.maxRecords;
1276
+ if (opts.cache.maxBytes !== void 0) lruOptions.maxBytes = parseBytes(opts.cache.maxBytes);
1277
+ this.lru = new Lru(lruOptions);
1278
+ this.hydrated = true;
1279
+ } else {
1280
+ this.lru = null;
1281
+ if (opts.indexes) {
1282
+ for (const def of opts.indexes) {
1283
+ this.indexes.declare(def);
1284
+ }
1285
+ }
1286
+ }
610
1287
  }
611
1288
  /** Get a single record by ID. Returns null if not found. */
612
1289
  async get(id) {
1290
+ if (this.lazy && this.lru) {
1291
+ const cached = this.lru.get(id);
1292
+ if (cached) return cached.record;
1293
+ const envelope = await this.adapter.get(this.compartment, this.name, id);
1294
+ if (!envelope) return null;
1295
+ const record = await this.decryptRecord(envelope);
1296
+ this.lru.set(id, { record, version: envelope._v }, estimateRecordBytes(record));
1297
+ return record;
1298
+ }
613
1299
  await this.ensureHydrated();
614
1300
  const entry = this.cache.get(id);
615
1301
  return entry ? entry.record : null;
@@ -619,8 +1305,20 @@ var Collection = class {
619
1305
  if (!hasWritePermission(this.keyring, this.name)) {
620
1306
  throw new ReadOnlyError();
621
1307
  }
622
- await this.ensureHydrated();
623
- const existing = this.cache.get(id);
1308
+ let existing;
1309
+ if (this.lazy && this.lru) {
1310
+ existing = this.lru.get(id);
1311
+ if (!existing) {
1312
+ const previousEnvelope = await this.adapter.get(this.compartment, this.name, id);
1313
+ if (previousEnvelope) {
1314
+ const previousRecord = await this.decryptRecord(previousEnvelope);
1315
+ existing = { record: previousRecord, version: previousEnvelope._v };
1316
+ }
1317
+ }
1318
+ } else {
1319
+ await this.ensureHydrated();
1320
+ existing = this.cache.get(id);
1321
+ }
624
1322
  const version = existing ? existing.version + 1 : 1;
625
1323
  if (existing && this.historyConfig.enabled !== false) {
626
1324
  const historyEnvelope = await this.encryptRecord(existing.record, existing.version);
@@ -639,7 +1337,12 @@ var Collection = class {
639
1337
  }
640
1338
  const envelope = await this.encryptRecord(record, version);
641
1339
  await this.adapter.put(this.compartment, this.name, id, envelope);
642
- this.cache.set(id, { record, version });
1340
+ if (this.lazy && this.lru) {
1341
+ this.lru.set(id, { record, version }, estimateRecordBytes(record));
1342
+ } else {
1343
+ this.cache.set(id, { record, version });
1344
+ this.indexes.upsert(id, record, existing ? existing.record : null);
1345
+ }
643
1346
  await this.onDirty?.(this.name, id, "put", version);
644
1347
  this.emitter.emit("change", {
645
1348
  compartment: this.compartment,
@@ -653,13 +1356,32 @@ var Collection = class {
653
1356
  if (!hasWritePermission(this.keyring, this.name)) {
654
1357
  throw new ReadOnlyError();
655
1358
  }
656
- const existing = this.cache.get(id);
1359
+ let existing;
1360
+ if (this.lazy && this.lru) {
1361
+ existing = this.lru.get(id);
1362
+ if (!existing && this.historyConfig.enabled !== false) {
1363
+ const previousEnvelope = await this.adapter.get(this.compartment, this.name, id);
1364
+ if (previousEnvelope) {
1365
+ const previousRecord = await this.decryptRecord(previousEnvelope);
1366
+ existing = { record: previousRecord, version: previousEnvelope._v };
1367
+ }
1368
+ }
1369
+ } else {
1370
+ existing = this.cache.get(id);
1371
+ }
657
1372
  if (existing && this.historyConfig.enabled !== false) {
658
1373
  const historyEnvelope = await this.encryptRecord(existing.record, existing.version);
659
1374
  await saveHistory(this.adapter, this.compartment, this.name, id, historyEnvelope);
660
1375
  }
661
1376
  await this.adapter.delete(this.compartment, this.name, id);
662
- this.cache.delete(id);
1377
+ if (this.lazy && this.lru) {
1378
+ this.lru.remove(id);
1379
+ } else {
1380
+ this.cache.delete(id);
1381
+ if (existing) {
1382
+ this.indexes.remove(id, existing.record);
1383
+ }
1384
+ }
663
1385
  await this.onDirty?.(this.name, id, "delete", existing?.version ?? 0);
664
1386
  this.emitter.emit("change", {
665
1387
  compartment: this.compartment,
@@ -668,14 +1390,70 @@ var Collection = class {
668
1390
  action: "delete"
669
1391
  });
670
1392
  }
671
- /** List all records in the collection. */
1393
+ /**
1394
+ * List all records in the collection.
1395
+ *
1396
+ * Throws in lazy mode — bulk listing defeats the purpose of lazy
1397
+ * hydration. Use `scan()` to iterate over the full collection
1398
+ * page-by-page without holding more than `pageSize` records in memory.
1399
+ */
672
1400
  async list() {
1401
+ if (this.lazy) {
1402
+ throw new Error(
1403
+ `Collection "${this.name}": list() is not available in lazy mode (prefetch: false). Use collection.scan({ pageSize }) to iterate over the full collection.`
1404
+ );
1405
+ }
673
1406
  await this.ensureHydrated();
674
1407
  return [...this.cache.values()].map((e) => e.record);
675
1408
  }
676
- /** Filter records by a predicate. */
677
1409
  query(predicate) {
678
- return [...this.cache.values()].map((e) => e.record).filter(predicate);
1410
+ if (this.lazy) {
1411
+ throw new Error(
1412
+ `Collection "${this.name}": query() is not available in lazy mode (prefetch: false). Use collection.scan({ pageSize }) and filter the streamed records with a regular for-await loop. Streaming queries land in v0.4.`
1413
+ );
1414
+ }
1415
+ if (predicate !== void 0) {
1416
+ return [...this.cache.values()].map((e) => e.record).filter(predicate);
1417
+ }
1418
+ const source = {
1419
+ snapshot: () => [...this.cache.values()].map((e) => e.record),
1420
+ subscribe: (cb) => {
1421
+ const handler = (event) => {
1422
+ if (event.compartment === this.compartment && event.collection === this.name) {
1423
+ cb();
1424
+ }
1425
+ };
1426
+ this.emitter.on("change", handler);
1427
+ return () => this.emitter.off("change", handler);
1428
+ },
1429
+ // Index-aware fast path for `==` and `in` operators on indexed
1430
+ // fields. The Query builder consults these when present and falls
1431
+ // back to a linear scan otherwise.
1432
+ getIndexes: () => this.getIndexes(),
1433
+ lookupById: (id) => this.cache.get(id)?.record
1434
+ };
1435
+ return new Query(source);
1436
+ }
1437
+ /**
1438
+ * Cache statistics — useful for devtools, monitoring, and verifying
1439
+ * that LRU eviction is happening as expected in lazy mode.
1440
+ *
1441
+ * In eager mode, returns size only (no hits/misses are tracked because
1442
+ * every read is a cache hit by construction). In lazy mode, returns
1443
+ * the full LRU stats: `{ hits, misses, evictions, size, bytes }`.
1444
+ */
1445
+ cacheStats() {
1446
+ if (this.lazy && this.lru) {
1447
+ return { ...this.lru.stats(), lazy: true };
1448
+ }
1449
+ return {
1450
+ hits: 0,
1451
+ misses: 0,
1452
+ evictions: 0,
1453
+ size: this.cache.size,
1454
+ bytes: 0,
1455
+ lazy: false
1456
+ };
679
1457
  }
680
1458
  // ─── History Methods ────────────────────────────────────────────
681
1459
  /** Get version history for a record, newest first. */
@@ -766,11 +1544,105 @@ var Collection = class {
766
1544
  return clearHistory(this.adapter, this.compartment, this.name, id);
767
1545
  }
768
1546
  // ─── Core Methods ─────────────────────────────────────────────
769
- /** Count records in the collection. */
1547
+ /**
1548
+ * Count records in the collection.
1549
+ *
1550
+ * In eager mode this returns the in-memory cache size (instant). In
1551
+ * lazy mode it asks the adapter via `list()` to enumerate ids — slower
1552
+ * but still correct, and avoids loading any record bodies into memory.
1553
+ */
770
1554
  async count() {
1555
+ if (this.lazy) {
1556
+ const ids = await this.adapter.list(this.compartment, this.name);
1557
+ return ids.length;
1558
+ }
771
1559
  await this.ensureHydrated();
772
1560
  return this.cache.size;
773
1561
  }
1562
+ // ─── Pagination & Streaming ───────────────────────────────────
1563
+ /**
1564
+ * Fetch a single page of records via the adapter's optional `listPage`
1565
+ * extension. Returns the decrypted records for this page plus an opaque
1566
+ * cursor for the next page.
1567
+ *
1568
+ * Pass `cursor: undefined` (or omit it) to start from the beginning.
1569
+ * The final page returns `nextCursor: null`.
1570
+ *
1571
+ * If the adapter does NOT implement `listPage`, this falls back to a
1572
+ * synthetic implementation: it loads all ids via `list()`, sorts them,
1573
+ * and slices a window. The first call emits a one-time console.warn so
1574
+ * developers can spot adapters that should opt into the fast path.
1575
+ */
1576
+ async listPage(opts = {}) {
1577
+ const limit = opts.limit ?? 100;
1578
+ if (this.adapter.listPage) {
1579
+ const result = await this.adapter.listPage(this.compartment, this.name, opts.cursor, limit);
1580
+ const decrypted = [];
1581
+ for (const { record, version, id } of await this.decryptPage(result.items)) {
1582
+ if (!this.lazy && !this.cache.has(id)) {
1583
+ this.cache.set(id, { record, version });
1584
+ }
1585
+ decrypted.push(record);
1586
+ }
1587
+ return { items: decrypted, nextCursor: result.nextCursor };
1588
+ }
1589
+ warnOnceFallback(this.adapter.name ?? "unknown");
1590
+ const ids = (await this.adapter.list(this.compartment, this.name)).slice().sort();
1591
+ const start = opts.cursor ? parseInt(opts.cursor, 10) : 0;
1592
+ const end = Math.min(start + limit, ids.length);
1593
+ const items = [];
1594
+ for (let i = start; i < end; i++) {
1595
+ const id = ids[i];
1596
+ const envelope = await this.adapter.get(this.compartment, this.name, id);
1597
+ if (envelope) {
1598
+ const record = await this.decryptRecord(envelope);
1599
+ items.push(record);
1600
+ if (!this.lazy && !this.cache.has(id)) {
1601
+ this.cache.set(id, { record, version: envelope._v });
1602
+ }
1603
+ }
1604
+ }
1605
+ return {
1606
+ items,
1607
+ nextCursor: end < ids.length ? String(end) : null
1608
+ };
1609
+ }
1610
+ /**
1611
+ * Stream every record in the collection page-by-page, yielding decrypted
1612
+ * records as an `AsyncIterable<T>`. The whole point: process collections
1613
+ * larger than RAM without ever holding more than `pageSize` records
1614
+ * decrypted at once.
1615
+ *
1616
+ * @example
1617
+ * ```ts
1618
+ * for await (const record of invoices.scan({ pageSize: 500 })) {
1619
+ * await processOne(record)
1620
+ * }
1621
+ * ```
1622
+ *
1623
+ * Uses `adapter.listPage` when available; otherwise falls back to the
1624
+ * synthetic pagination path with the same one-time warning.
1625
+ */
1626
+ async *scan(opts = {}) {
1627
+ const pageSize = opts.pageSize ?? 100;
1628
+ let page = await this.listPage({ limit: pageSize });
1629
+ while (true) {
1630
+ for (const item of page.items) {
1631
+ yield item;
1632
+ }
1633
+ if (page.nextCursor === null) return;
1634
+ page = await this.listPage({ cursor: page.nextCursor, limit: pageSize });
1635
+ }
1636
+ }
1637
+ /** Decrypt a page of envelopes returned by `adapter.listPage`. */
1638
+ async decryptPage(items) {
1639
+ const out = [];
1640
+ for (const { id, envelope } of items) {
1641
+ const record = await this.decryptRecord(envelope);
1642
+ out.push({ id, record, version: envelope._v });
1643
+ }
1644
+ return out;
1645
+ }
774
1646
  // ─── Internal ──────────────────────────────────────────────────
775
1647
  /** Load all records from adapter into memory cache. */
776
1648
  async ensureHydrated() {
@@ -784,6 +1656,7 @@ var Collection = class {
784
1656
  }
785
1657
  }
786
1658
  this.hydrated = true;
1659
+ this.rebuildIndexes();
787
1660
  }
788
1661
  /** Hydrate from a pre-loaded snapshot (used by Compartment). */
789
1662
  async hydrateFromSnapshot(records) {
@@ -792,6 +1665,34 @@ var Collection = class {
792
1665
  this.cache.set(id, { record, version: envelope._v });
793
1666
  }
794
1667
  this.hydrated = true;
1668
+ this.rebuildIndexes();
1669
+ }
1670
+ /**
1671
+ * Rebuild secondary indexes from the current in-memory cache.
1672
+ *
1673
+ * Called after any bulk hydration. Incremental put/delete updates
1674
+ * are handled by `indexes.upsert()` / `indexes.remove()` directly,
1675
+ * so this only fires for full reloads.
1676
+ *
1677
+ * Synchronous and O(N × indexes.size); for the v0.3 target scale of
1678
+ * 1K–50K records this completes in single-digit milliseconds.
1679
+ */
1680
+ rebuildIndexes() {
1681
+ if (this.indexes.fields().length === 0) return;
1682
+ const snapshot = [];
1683
+ for (const [id, entry] of this.cache) {
1684
+ snapshot.push({ id, record: entry.record });
1685
+ }
1686
+ this.indexes.build(snapshot);
1687
+ }
1688
+ /**
1689
+ * Get the in-memory index store. Used by `Query` to short-circuit
1690
+ * `==` and `in` lookups when an index covers the where clause.
1691
+ *
1692
+ * Returns `null` if no indexes are declared on this collection.
1693
+ */
1694
+ getIndexes() {
1695
+ return this.indexes.fields().length > 0 ? this.indexes : null;
795
1696
  }
796
1697
  /** Get all records as encrypted envelopes (for dump). */
797
1698
  async dumpEnvelopes() {
@@ -863,11 +1764,25 @@ var Compartment = class {
863
1764
  return getDEKFn(collectionName);
864
1765
  };
865
1766
  }
866
- /** Open a typed collection within this compartment. */
867
- collection(collectionName) {
1767
+ /**
1768
+ * Open a typed collection within this compartment.
1769
+ *
1770
+ * - `options.indexes` declares secondary indexes for the query DSL.
1771
+ * Indexes are computed in memory after decryption; adapters never
1772
+ * see plaintext index data.
1773
+ * - `options.prefetch` (default `true`) controls hydration. Eager mode
1774
+ * loads everything on first access; lazy mode (`prefetch: false`)
1775
+ * loads records on demand and bounds memory via the LRU cache.
1776
+ * - `options.cache` configures the LRU bounds. Required in lazy mode.
1777
+ * Accepts `{ maxRecords, maxBytes: '50MB' | 1024 }`.
1778
+ *
1779
+ * Lazy mode + indexes is rejected at construction time — see the
1780
+ * Collection constructor for the rationale.
1781
+ */
1782
+ collection(collectionName, options) {
868
1783
  let coll = this.collectionCache.get(collectionName);
869
1784
  if (!coll) {
870
- coll = new Collection({
1785
+ const collOpts = {
871
1786
  adapter: this.adapter,
872
1787
  compartment: this.name,
873
1788
  name: collectionName,
@@ -877,7 +1792,11 @@ var Compartment = class {
877
1792
  getDEK: this.getDEK,
878
1793
  onDirty: this.onDirty,
879
1794
  historyConfig: this.historyConfig
880
- });
1795
+ };
1796
+ if (options?.indexes !== void 0) collOpts.indexes = options.indexes;
1797
+ if (options?.prefetch !== void 0) collOpts.prefetch = options.prefetch;
1798
+ if (options?.cache !== void 0) collOpts.cache = options.cache;
1799
+ coll = new Collection(collOpts);
881
1800
  this.collectionCache.set(collectionName, coll);
882
1801
  }
883
1802
  return coll;
@@ -1577,10 +2496,12 @@ function estimateEntropy(passphrase) {
1577
2496
  }
1578
2497
  export {
1579
2498
  Collection,
2499
+ CollectionIndexes,
1580
2500
  Compartment,
1581
2501
  ConflictError,
1582
2502
  DecryptionError,
1583
2503
  InvalidKeyError,
2504
+ Lru,
1584
2505
  NOYDB_BACKUP_VERSION,
1585
2506
  NOYDB_FORMAT_VERSION,
1586
2507
  NOYDB_KEYRING_VERSION,
@@ -1591,6 +2512,7 @@ export {
1591
2512
  Noydb,
1592
2513
  NoydbError,
1593
2514
  PermissionDeniedError,
2515
+ Query,
1594
2516
  ReadOnlyError,
1595
2517
  SyncEngine,
1596
2518
  TamperedError,
@@ -1600,9 +2522,15 @@ export {
1600
2522
  diff,
1601
2523
  enrollBiometric,
1602
2524
  estimateEntropy,
2525
+ estimateRecordBytes,
2526
+ evaluateClause,
2527
+ evaluateFieldClause,
2528
+ executePlan,
1603
2529
  formatDiff,
1604
2530
  isBiometricAvailable,
1605
2531
  loadBiometric,
2532
+ parseBytes,
2533
+ readPath,
1606
2534
  removeBiometric,
1607
2535
  saveBiometric,
1608
2536
  unlockBiometric,