@katlux/providers 0.1.1-alpha.134 → 0.1.1-alpha.135

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.cjs CHANGED
@@ -1256,6 +1256,12 @@ function foldAscii(value) {
1256
1256
  if (!value) return "";
1257
1257
  return value.replace(/\u0419/g, "\uE000").replace(/\u0439/g, "\uE001").replace(EXTENDED_LATIN_CHARS, (ch) => EXTENDED_LATIN_FOLD_MAP[ch] || ch).normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\uE000/g, "\u0439").replace(/\uE001/g, "\u0439").toLowerCase().replace(/\u0307/g, "").replace(/\u03C2/g, "\u03C3").normalize("NFKC");
1258
1258
  }
1259
+ function isAsciiString(str) {
1260
+ for (let i = 0; i < str.length; i++) {
1261
+ if (str.charCodeAt(i) > 127) return false;
1262
+ }
1263
+ return true;
1264
+ }
1259
1265
  function normalizeFilterValue(value, options) {
1260
1266
  if (value === null || value === void 0) {
1261
1267
  return "";
@@ -1263,6 +1269,9 @@ function normalizeFilterValue(value, options) {
1263
1269
  if (typeof value === "function" || typeof value === "symbol") {
1264
1270
  throw new TypeError(`[normalizeFilterValue] Unsupported non-serializable filter value of type "${typeof value}".`);
1265
1271
  }
1272
+ if (typeof value === "string" && !options?.locale && !options?.normalizer && isAsciiString(value)) {
1273
+ return value.trim().toLowerCase();
1274
+ }
1266
1275
  let rawStr;
1267
1276
  if (typeof value === "object") {
1268
1277
  if (value instanceof Date) {
@@ -4425,6 +4434,12 @@ class CWebCryptoEncryptionProvider extends AEncryptionProvider {
4425
4434
  this._keyringCache.clear();
4426
4435
  this._inflightKeyCache.clear();
4427
4436
  }
4437
+ setKeyring(keys, activeKid) {
4438
+ super.setKeyring(keys, activeKid);
4439
+ this._decryptSaltCache.clear();
4440
+ this._keyringCache.clear();
4441
+ this._inflightKeyCache.clear();
4442
+ }
4428
4443
  constructor(key, options) {
4429
4444
  super(key, options);
4430
4445
  if (options) {
@@ -4801,6 +4816,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4801
4816
  _cachedKeyId;
4802
4817
  _kdfOptions;
4803
4818
  _decryptSaltCache = /* @__PURE__ */ new Map();
4819
+ _inflightKeyCache = /* @__PURE__ */ new Map();
4804
4820
  constructor(key, options) {
4805
4821
  if (key && typeof key === "object" && !("algorithm" in key) && !("publicKey" in key) && !ArrayBuffer.isView(key) && !(key instanceof ArrayBuffer) && (key.keys || key.activeKid || key.allowedKids || key.kdf)) {
4806
4822
  options = key;
@@ -4834,6 +4850,7 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4834
4850
  this._cachedHash = void 0;
4835
4851
  this._cachedKeyId = void 0;
4836
4852
  this._decryptSaltCache.clear();
4853
+ this._inflightKeyCache.clear();
4837
4854
  }
4838
4855
  clearKeys() {
4839
4856
  super.clearKeys();
@@ -4845,6 +4862,19 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4845
4862
  this._cachedHash = void 0;
4846
4863
  this._cachedKeyId = void 0;
4847
4864
  this._decryptSaltCache.clear();
4865
+ this._inflightKeyCache.clear();
4866
+ }
4867
+ setKeyring(keys, activeKid) {
4868
+ super.setKeyring(keys, activeKid);
4869
+ this._cachedEncKey = void 0;
4870
+ this._cachedMacKey = void 0;
4871
+ this._cachedSalt = void 0;
4872
+ this._cachedKdf = void 0;
4873
+ this._cachedIter = void 0;
4874
+ this._cachedHash = void 0;
4875
+ this._cachedKeyId = void 0;
4876
+ this._decryptSaltCache.clear();
4877
+ this._inflightKeyCache.clear();
4848
4878
  }
4849
4879
  async warmupKey(options) {
4850
4880
  const res = await this.resolveCBCKeys(options?.key, void 0, void 0, options);
@@ -4903,15 +4933,15 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4903
4933
  }
4904
4934
  }
4905
4935
  if (rawKey && typeof rawKey === "object" && "encKey" in rawKey && "macKey" in rawKey && rawKey.encKey?.algorithm && rawKey.macKey?.algorithm) {
4906
- const encKey2 = rawKey.encKey;
4907
- const macKey2 = rawKey.macKey;
4936
+ const encKey = rawKey.encKey;
4937
+ const macKey = rawKey.macKey;
4908
4938
  if (!keyProvider) {
4909
- this._cachedEncKey = encKey2;
4910
- this._cachedMacKey = macKey2;
4939
+ this._cachedEncKey = encKey;
4940
+ this._cachedMacKey = macKey;
4911
4941
  this._cachedKdf = "direct-pair";
4912
4942
  this._cachedKeyId = currentKeyId;
4913
4943
  }
4914
- return { encKey: encKey2, macKey: macKey2, kdf: "direct-pair", keyId: currentKeyId };
4944
+ return { encKey, macKey, kdf: "direct-pair", keyId: currentKeyId };
4915
4945
  }
4916
4946
  if (typeof rawKey !== "string" && rawKey.algorithm) {
4917
4947
  const cryptoKey = rawKey;
@@ -4927,14 +4957,14 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4927
4957
  } finally {
4928
4958
  new Uint8Array(rawBits).fill(0);
4929
4959
  }
4930
- const encKey2 = await subtle.deriveKey(
4960
+ const encKey = await subtle.deriveKey(
4931
4961
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-enc"), hash: "SHA-256" },
4932
4962
  hkdfBase,
4933
4963
  { name: "AES-CBC", length: 256 },
4934
4964
  false,
4935
4965
  ["encrypt", "decrypt"]
4936
4966
  );
4937
- const macKey2 = await subtle.deriveKey(
4967
+ const macKey = await subtle.deriveKey(
4938
4968
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-mac"), hash: "SHA-256" },
4939
4969
  hkdfBase,
4940
4970
  { name: "HMAC", hash: "SHA-256" },
@@ -4942,61 +4972,61 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
4942
4972
  ["sign", "verify"]
4943
4973
  );
4944
4974
  if (!keyProvider) {
4945
- this._cachedEncKey = encKey2;
4946
- this._cachedMacKey = macKey2;
4975
+ this._cachedEncKey = encKey;
4976
+ this._cachedMacKey = macKey;
4947
4977
  this._cachedKdf = "hkdf-direct";
4948
4978
  this._cachedKeyId = currentKeyId;
4949
4979
  }
4950
- return { encKey: encKey2, macKey: macKey2, kdf: "hkdf-direct", keyId: currentKeyId };
4980
+ return { encKey, macKey, kdf: "hkdf-direct", keyId: currentKeyId };
4951
4981
  }
4952
4982
  if (rawKey instanceof Uint8Array || rawKey instanceof ArrayBuffer) {
4953
4983
  const rawBytes = rawKey instanceof Uint8Array ? rawKey : new Uint8Array(rawKey);
4954
4984
  if (rawBytes.length === 64) {
4955
- const encKeyBytes2 = rawBytes.slice(0, 32);
4956
- const macKeyBytes2 = rawBytes.slice(32, 64);
4957
- let encKey2;
4958
- let macKey2;
4985
+ const encKeyBytes = rawBytes.slice(0, 32);
4986
+ const macKeyBytes = rawBytes.slice(32, 64);
4987
+ let encKey;
4988
+ let macKey;
4959
4989
  try {
4960
- encKey2 = await subtle.importKey(
4990
+ encKey = await subtle.importKey(
4961
4991
  "raw",
4962
- encKeyBytes2,
4992
+ encKeyBytes,
4963
4993
  { name: "AES-CBC" },
4964
4994
  false,
4965
4995
  ["encrypt", "decrypt"]
4966
4996
  );
4967
- macKey2 = await subtle.importKey(
4997
+ macKey = await subtle.importKey(
4968
4998
  "raw",
4969
- macKeyBytes2,
4999
+ macKeyBytes,
4970
5000
  { name: "HMAC", hash: "SHA-256" },
4971
5001
  false,
4972
5002
  ["sign", "verify"]
4973
5003
  );
4974
5004
  } finally {
4975
- encKeyBytes2.fill(0);
4976
- macKeyBytes2.fill(0);
5005
+ encKeyBytes.fill(0);
5006
+ macKeyBytes.fill(0);
4977
5007
  }
4978
5008
  if (!keyProvider) {
4979
- this._cachedEncKey = encKey2;
4980
- this._cachedMacKey = macKey2;
5009
+ this._cachedEncKey = encKey;
5010
+ this._cachedMacKey = macKey;
4981
5011
  this._cachedKdf = "raw";
4982
5012
  this._cachedKeyId = currentKeyId;
4983
5013
  }
4984
- return { encKey: encKey2, macKey: macKey2, kdf: "raw", keyId: currentKeyId };
5014
+ return { encKey, macKey, kdf: "raw", keyId: currentKeyId };
4985
5015
  }
4986
5016
  if (rawBytes.length === 32) {
4987
5017
  const rawBytesCopy = rawBytes.slice();
4988
- let encKey2;
4989
- let macKey2;
5018
+ let encKey;
5019
+ let macKey;
4990
5020
  try {
4991
5021
  const hkdfBase = await subtle.importKey("raw", rawBytesCopy, "HKDF", false, ["deriveKey"]);
4992
- encKey2 = await subtle.deriveKey(
5022
+ encKey = await subtle.deriveKey(
4993
5023
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-enc"), hash: "SHA-256" },
4994
5024
  hkdfBase,
4995
5025
  { name: "AES-CBC", length: 256 },
4996
5026
  false,
4997
5027
  ["encrypt", "decrypt"]
4998
5028
  );
4999
- macKey2 = await subtle.deriveKey(
5029
+ macKey = await subtle.deriveKey(
5000
5030
  { name: "HKDF", salt: new Uint8Array(0), info: textEncoder.encode("katlux-cbc-mac"), hash: "SHA-256" },
5001
5031
  hkdfBase,
5002
5032
  { name: "HMAC", hash: "SHA-256" },
@@ -5007,133 +5037,154 @@ class CWebCryptoAESCBCProvider extends AEncryptionProvider {
5007
5037
  rawBytesCopy.fill(0);
5008
5038
  }
5009
5039
  if (!keyProvider) {
5010
- this._cachedEncKey = encKey2;
5011
- this._cachedMacKey = macKey2;
5040
+ this._cachedEncKey = encKey;
5041
+ this._cachedMacKey = macKey;
5012
5042
  this._cachedKdf = "raw";
5013
5043
  this._cachedKeyId = currentKeyId;
5014
5044
  }
5015
- return { encKey: encKey2, macKey: macKey2, kdf: "raw", keyId: currentKeyId };
5045
+ return { encKey, macKey, kdf: "raw", keyId: currentKeyId };
5016
5046
  }
5017
5047
  throw new Error(
5018
5048
  `[CWebCryptoAESCBCProvider] AES-CBC requires a 32-byte or 64-byte key. Received a binary key of ${rawBytes.length} bytes. Provide exactly 32 bytes (for HKDF companion key derivation) or 64 bytes (split AES/HMAC), or a string passphrase.`
5019
5049
  );
5020
5050
  }
5021
- const passphraseBytes = textEncoder.encode(rawKey);
5022
5051
  const kdf = (kdfOverride || options?.kdf || this._defaultKdf || "pbkdf2").toLowerCase();
5023
- if (kdf === "hkdf" && typeof rawKey === "string") {
5024
- console.warn(
5025
- '[CWebCryptoAESCBCProvider] ADVISORY: HKDF is designed for high-entropy input key material (IKM), not low-entropy human passphrases. Use "pbkdf2" for password-derived encryption.'
5026
- );
5027
- }
5028
- let raw512;
5029
- let saltStr;
5030
- let kdfType;
5031
- let iterNum;
5032
- try {
5033
- if (kdf === "pbkdf2") {
5034
- const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5035
- const saltBytes = CKeyManager.resolveSalt(s);
5036
- saltStr = CKeyManager.toBase64(saltBytes);
5037
- kdfType = "PBKDF2";
5038
- const iterations = resolveAndClampPbkdf2Iterations({
5039
- iterationsOverride,
5040
- optionsIterations: options?.kdfIterations,
5041
- defaultIterations: this._kdfOptions?.iterations,
5042
- optionsMaxAllowed: options?.maxAllowedIterations,
5043
- providerMaxAllowed: this._maxAllowedIterations,
5044
- context: "[CWebCryptoAESCBCProvider]"
5045
- });
5046
- iterNum = iterations;
5047
- const baseKey = await subtle.importKey(
5052
+ const canDedupeInflight = !saltOverride && !options?.kdfSalt && kdf === "pbkdf2";
5053
+ const targetIterForKey = iterationsOverride || options?.kdfIterations || this._kdfOptions?.iterations || "";
5054
+ const targetHashForKey = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5055
+ const inflightKey = canDedupeInflight ? `${currentKeyId}:pbkdf2:${targetIterForKey}:${targetHashForKey}` : "";
5056
+ if (canDedupeInflight) {
5057
+ const existingInflight = this._inflightKeyCache.get(inflightKey);
5058
+ if (existingInflight) {
5059
+ return await existingInflight;
5060
+ }
5061
+ }
5062
+ const derivePromise = (async () => {
5063
+ const passphraseBytes = textEncoder.encode(rawKey);
5064
+ if (kdf === "hkdf" && typeof rawKey === "string") {
5065
+ console.warn(
5066
+ '[CWebCryptoAESCBCProvider] ADVISORY: HKDF is designed for high-entropy input key material (IKM), not low-entropy human passphrases. Use "pbkdf2" for password-derived encryption.'
5067
+ );
5068
+ }
5069
+ let raw512;
5070
+ let saltStr;
5071
+ let kdfType;
5072
+ let iterNum;
5073
+ try {
5074
+ if (kdf === "pbkdf2") {
5075
+ const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5076
+ const saltBytes = CKeyManager.resolveSalt(s);
5077
+ saltStr = CKeyManager.toBase64(saltBytes);
5078
+ kdfType = "PBKDF2";
5079
+ const iterations = resolveAndClampPbkdf2Iterations({
5080
+ iterationsOverride,
5081
+ optionsIterations: options?.kdfIterations,
5082
+ defaultIterations: this._kdfOptions?.iterations,
5083
+ optionsMaxAllowed: options?.maxAllowedIterations,
5084
+ providerMaxAllowed: this._maxAllowedIterations,
5085
+ context: "[CWebCryptoAESCBCProvider]"
5086
+ });
5087
+ iterNum = iterations;
5088
+ const baseKey = await subtle.importKey(
5089
+ "raw",
5090
+ passphraseBytes,
5091
+ "PBKDF2",
5092
+ false,
5093
+ ["deriveBits"]
5094
+ );
5095
+ raw512 = await subtle.deriveBits(
5096
+ {
5097
+ name: "PBKDF2",
5098
+ salt: saltBytes,
5099
+ iterations,
5100
+ hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5101
+ },
5102
+ baseKey,
5103
+ 512
5104
+ );
5105
+ } else if (kdf === "hkdf") {
5106
+ const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5107
+ const saltBytes = CKeyManager.resolveSalt(s);
5108
+ saltStr = CKeyManager.toBase64(saltBytes);
5109
+ kdfType = "HKDF";
5110
+ const baseKey = await subtle.importKey(
5111
+ "raw",
5112
+ passphraseBytes,
5113
+ "HKDF",
5114
+ false,
5115
+ ["deriveBits"]
5116
+ );
5117
+ raw512 = await subtle.deriveBits(
5118
+ {
5119
+ name: "HKDF",
5120
+ salt: saltBytes,
5121
+ info: resolveInfoBytes(options?.info || this._kdfOptions?.info, "katlux-aescbc-hmac-key"),
5122
+ hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5123
+ },
5124
+ baseKey,
5125
+ 512
5126
+ );
5127
+ } else {
5128
+ raw512 = await subtle.digest("SHA-512", passphraseBytes);
5129
+ }
5130
+ } finally {
5131
+ if (typeof rawKey === "string") {
5132
+ passphraseBytes.fill(0);
5133
+ }
5134
+ }
5135
+ const bytes = new Uint8Array(raw512);
5136
+ const encKeyBytes = bytes.slice(0, 32);
5137
+ const macKeyBytes = bytes.slice(32, 64);
5138
+ let encKey;
5139
+ let macKey;
5140
+ try {
5141
+ encKey = await subtle.importKey(
5048
5142
  "raw",
5049
- passphraseBytes,
5050
- "PBKDF2",
5143
+ encKeyBytes,
5144
+ { name: "AES-CBC" },
5051
5145
  false,
5052
- ["deriveBits"]
5053
- );
5054
- raw512 = await subtle.deriveBits(
5055
- {
5056
- name: "PBKDF2",
5057
- salt: saltBytes,
5058
- iterations,
5059
- hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5060
- },
5061
- baseKey,
5062
- 512
5146
+ ["encrypt", "decrypt"]
5063
5147
  );
5064
- } else if (kdf === "hkdf") {
5065
- const s = saltOverride || options?.kdfSalt || this._kdfOptions?.salt;
5066
- const saltBytes = CKeyManager.resolveSalt(s);
5067
- saltStr = CKeyManager.toBase64(saltBytes);
5068
- kdfType = "HKDF";
5069
- const baseKey = await subtle.importKey(
5148
+ macKey = await subtle.importKey(
5070
5149
  "raw",
5071
- passphraseBytes,
5072
- "HKDF",
5150
+ macKeyBytes,
5151
+ { name: "HMAC", hash: "SHA-256" },
5073
5152
  false,
5074
- ["deriveBits"]
5075
- );
5076
- raw512 = await subtle.deriveBits(
5077
- {
5078
- name: "HKDF",
5079
- salt: saltBytes,
5080
- info: resolveInfoBytes(options?.info || this._kdfOptions?.info, "katlux-aescbc-hmac-key"),
5081
- hash: options?.kdfHash || this._kdfOptions?.hash || "SHA-512"
5082
- },
5083
- baseKey,
5084
- 512
5153
+ ["sign", "verify"]
5085
5154
  );
5086
- } else {
5087
- raw512 = await subtle.digest("SHA-512", passphraseBytes);
5155
+ } finally {
5156
+ bytes.fill(0);
5157
+ encKeyBytes.fill(0);
5158
+ macKeyBytes.fill(0);
5159
+ new Uint8Array(raw512).fill(0);
5160
+ }
5161
+ if (!keyProvider && !saltOverride && !options?.kdfSalt) {
5162
+ this._cachedEncKey = encKey;
5163
+ this._cachedMacKey = macKey;
5164
+ this._cachedSalt = saltStr;
5165
+ this._cachedKdf = kdfType || "none";
5166
+ this._cachedIter = iterNum;
5167
+ this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5168
+ this._cachedKeyId = currentKeyId;
5088
5169
  }
5089
- } finally {
5090
- if (typeof rawKey === "string") {
5091
- passphraseBytes.fill(0);
5170
+ return {
5171
+ encKey,
5172
+ macKey,
5173
+ salt: saltStr,
5174
+ kdf: kdfType,
5175
+ iter: iterNum,
5176
+ keyId: currentKeyId
5177
+ };
5178
+ })();
5179
+ if (canDedupeInflight) {
5180
+ this._inflightKeyCache.set(inflightKey, derivePromise);
5181
+ try {
5182
+ return await derivePromise;
5183
+ } finally {
5184
+ this._inflightKeyCache.delete(inflightKey);
5092
5185
  }
5093
5186
  }
5094
- const bytes = new Uint8Array(raw512);
5095
- const encKeyBytes = bytes.slice(0, 32);
5096
- const macKeyBytes = bytes.slice(32, 64);
5097
- let encKey;
5098
- let macKey;
5099
- try {
5100
- encKey = await subtle.importKey(
5101
- "raw",
5102
- encKeyBytes,
5103
- { name: "AES-CBC" },
5104
- false,
5105
- ["encrypt", "decrypt"]
5106
- );
5107
- macKey = await subtle.importKey(
5108
- "raw",
5109
- macKeyBytes,
5110
- { name: "HMAC", hash: "SHA-256" },
5111
- false,
5112
- ["sign", "verify"]
5113
- );
5114
- } finally {
5115
- bytes.fill(0);
5116
- encKeyBytes.fill(0);
5117
- macKeyBytes.fill(0);
5118
- new Uint8Array(raw512).fill(0);
5119
- }
5120
- if (!keyProvider && !saltOverride && !options?.kdfSalt) {
5121
- this._cachedEncKey = encKey;
5122
- this._cachedMacKey = macKey;
5123
- this._cachedSalt = saltStr;
5124
- this._cachedKdf = kdfType || "none";
5125
- this._cachedIter = iterNum;
5126
- this._cachedHash = options?.kdfHash || this._kdfOptions?.hash || "SHA-512";
5127
- this._cachedKeyId = currentKeyId;
5128
- }
5129
- return {
5130
- encKey,
5131
- macKey,
5132
- salt: saltStr,
5133
- kdf: kdfType,
5134
- iter: iterNum,
5135
- keyId: currentKeyId
5136
- };
5187
+ return await derivePromise;
5137
5188
  }
5138
5189
  static isEncrypted(payload) {
5139
5190
  if (!payload || typeof payload !== "object") return false;
@@ -6010,12 +6061,7 @@ class CNodeCryptoEncryptionProvider extends AEncryptionProvider {
6010
6061
  }
6011
6062
  setKeyring(keys, activeKid) {
6012
6063
  super.setKeyring(keys, activeKid);
6013
- for (const entry of this._decryptSaltCache.values()) {
6014
- if (entry.key !== this._cachedKey) entry.key.fill(0);
6015
- }
6016
- this._decryptSaltCache.clear();
6017
- this._inFlightSaltDerivations.clear();
6018
- this._keyringCache.clear();
6064
+ this._wipeCachedBuffers();
6019
6065
  }
6020
6066
  _setPrimaryCached(res, keyId, options) {
6021
6067
  this._cachedKey = res.key;
@@ -9463,6 +9509,153 @@ const normalizeFilter = (filter) => {
9463
9509
  }
9464
9510
  return null;
9465
9511
  };
9512
+ const compileFilter = (filter, options) => {
9513
+ if (!filter || filter.active === false) return () => true;
9514
+ const norm = normalizeFilter(filter);
9515
+ if (!norm || norm.active === false) return () => true;
9516
+ const compileNode = (node) => {
9517
+ if (!node || node.active === false) return () => true;
9518
+ const op = node.operator;
9519
+ if (op === "not") {
9520
+ const childFn = compileNode(node.field);
9521
+ return (row) => !childFn(row);
9522
+ }
9523
+ if (op === EDataFilterOperator.And || op === EDataFilterOperator.Or || op === EDataFilterOperator.Nand || op === EDataFilterOperator.Nor) {
9524
+ const subFilters = Array.isArray(node.field) ? node.field : [];
9525
+ const compiled = subFilters.map(compileNode);
9526
+ const count = compiled.length;
9527
+ if (op === EDataFilterOperator.And) {
9528
+ if (count === 0) return () => true;
9529
+ if (count === 1) return compiled[0];
9530
+ if (count === 2) {
9531
+ const f0 = compiled[0];
9532
+ const f1 = compiled[1];
9533
+ return (row) => f0(row) && f1(row);
9534
+ }
9535
+ return (row) => {
9536
+ for (let i = 0; i < count; i++) {
9537
+ if (!compiled[i](row)) return false;
9538
+ }
9539
+ return true;
9540
+ };
9541
+ }
9542
+ if (op === EDataFilterOperator.Or) {
9543
+ if (count === 0) return () => false;
9544
+ if (count === 1) return compiled[0];
9545
+ if (count === 2) {
9546
+ const f0 = compiled[0];
9547
+ const f1 = compiled[1];
9548
+ return (row) => f0(row) || f1(row);
9549
+ }
9550
+ return (row) => {
9551
+ for (let i = 0; i < count; i++) {
9552
+ if (compiled[i](row)) return true;
9553
+ }
9554
+ return false;
9555
+ };
9556
+ }
9557
+ if (op === EDataFilterOperator.Nand) {
9558
+ if (count === 0) return () => false;
9559
+ return (row) => {
9560
+ for (let i = 0; i < count; i++) {
9561
+ if (!compiled[i](row)) return true;
9562
+ }
9563
+ return false;
9564
+ };
9565
+ }
9566
+ if (count === 0) return () => true;
9567
+ return (row) => {
9568
+ for (let i = 0; i < count; i++) {
9569
+ if (compiled[i](row)) return false;
9570
+ }
9571
+ return true;
9572
+ };
9573
+ }
9574
+ const field = node.field;
9575
+ if (!field || typeof field !== "object") return () => true;
9576
+ const entries = Object.entries(field);
9577
+ if (entries.length === 0) return () => true;
9578
+ const predicates = entries.map(([key, filterValue]) => {
9579
+ if (op === EDataFilterOperator.Equal || op === EDataFilterOperator.NotEqual) {
9580
+ const negate = op === EDataFilterOperator.NotEqual;
9581
+ if (typeof filterValue === "string") {
9582
+ const normFilter = normalizeFilterValue(filterValue, options);
9583
+ return (row) => {
9584
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9585
+ const match = typeof rv === "string" ? normalizeFilterValue(rv, options) === normFilter : compareEqual(rv, filterValue, options);
9586
+ return negate ? !match : match;
9587
+ };
9588
+ }
9589
+ return (row) => {
9590
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9591
+ const match = compareEqual(rv, filterValue, options);
9592
+ return negate ? !match : match;
9593
+ };
9594
+ } else if (op === EDataFilterOperator.Contains) {
9595
+ const negate = false;
9596
+ if (filterValue === null || filterValue === void 0 || filterValue === "") {
9597
+ return () => !negate;
9598
+ }
9599
+ if (typeof filterValue === "string") {
9600
+ const normFilter = normalizeFilterValue(filterValue, options);
9601
+ return (row) => {
9602
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9603
+ if (rv === null || rv === void 0) return negate;
9604
+ if (typeof rv === "string") {
9605
+ const match2 = normalizeFilterValue(rv, options).includes(normFilter);
9606
+ return match2;
9607
+ }
9608
+ const match = compareContains(rv, filterValue, options);
9609
+ return match;
9610
+ };
9611
+ }
9612
+ return (row) => {
9613
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9614
+ if (rv === null || rv === void 0) return negate;
9615
+ const match = compareContains(rv, filterValue, options);
9616
+ return match;
9617
+ };
9618
+ } else if (op === EDataFilterOperator.In || op === EDataFilterOperator.NotIn) {
9619
+ const negate = op === EDataFilterOperator.NotIn;
9620
+ if (Array.isArray(filterValue) || filterValue instanceof Set) {
9621
+ const normStrings = /* @__PURE__ */ new Set();
9622
+ const rawValues = /* @__PURE__ */ new Set();
9623
+ for (const item of filterValue) {
9624
+ if (typeof item === "string") {
9625
+ normStrings.add(normalizeFilterValue(item, options));
9626
+ } else {
9627
+ rawValues.add(item);
9628
+ }
9629
+ }
9630
+ return (row) => {
9631
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9632
+ if (typeof rv === "string") {
9633
+ const match2 = normStrings.has(normalizeFilterValue(rv, options)) || rawValues.size > 0 && compareIn(rv, filterValue, options);
9634
+ return negate ? !match2 : match2;
9635
+ }
9636
+ if (rv !== null && typeof rv !== "object" && rawValues.has(rv)) {
9637
+ return !negate;
9638
+ }
9639
+ const match = compareIn(rv, filterValue, options);
9640
+ return negate ? !match : match;
9641
+ };
9642
+ }
9643
+ }
9644
+ return (row) => {
9645
+ const rv = row ? row[key] !== void 0 ? row[key] : row.data && typeof row.data === "object" ? row.data[key] : void 0 : void 0;
9646
+ return applyOperator(op, rv, filterValue, options);
9647
+ };
9648
+ });
9649
+ if (predicates.length === 1) return predicates[0];
9650
+ return (row) => {
9651
+ for (let i = 0; i < predicates.length; i++) {
9652
+ if (!predicates[i](row)) return false;
9653
+ }
9654
+ return true;
9655
+ };
9656
+ };
9657
+ return compileNode(norm);
9658
+ };
9466
9659
  const evaluateFilter = (filter, row, options) => {
9467
9660
  if (!filter || filter.active === false) return true;
9468
9661
  const norm = normalizeFilter(filter);
@@ -9503,9 +9696,10 @@ const filterTreeData = (nodes, filter, options) => {
9503
9696
  const matchingNodeIds = /* @__PURE__ */ new Set();
9504
9697
  const expandedNodes = /* @__PURE__ */ new Set();
9505
9698
  const visibleNodeIds = /* @__PURE__ */ new Set();
9699
+ const evaluator = compileFilter(filter, normalizeOptions);
9506
9700
  nodes.forEach((node) => {
9507
9701
  const evalRow = node.data ? { ...node.data, ...node } : node;
9508
- if (evaluateFilter(filter, evalRow, normalizeOptions)) {
9702
+ if (evaluator(evalRow)) {
9509
9703
  matchingNodeIds.add(node[idKey]);
9510
9704
  }
9511
9705
  });
@@ -9569,7 +9763,7 @@ const filterData = (data, filter, options) => {
9569
9763
  }
9570
9764
  }
9571
9765
  }
9572
- const evaluator = options?.rowEvaluator ? options.rowEvaluator : (item) => evaluateFilter(filter, item, options?.normalizeOptions);
9766
+ const evaluator = options?.rowEvaluator ? options.rowEvaluator : compileFilter(filter, options?.normalizeOptions);
9573
9767
  for (let i = 0; i < len; i++) {
9574
9768
  const item = data[i];
9575
9769
  if (item === void 0 || item === null) continue;
@@ -11470,11 +11664,49 @@ class CSearchIndex {
11470
11664
  }
11471
11665
  }
11472
11666
 
11667
+ class CLruMap extends Map {
11668
+ maxSize;
11669
+ _onEvict;
11670
+ constructor(maxSize = 5e3, onEvict) {
11671
+ super();
11672
+ this.maxSize = Math.max(1, Math.floor(maxSize));
11673
+ this._onEvict = onEvict;
11674
+ }
11675
+ get(key) {
11676
+ if (!super.has(key)) return void 0;
11677
+ const value = super.get(key);
11678
+ super.delete(key);
11679
+ super.set(key, value);
11680
+ return value;
11681
+ }
11682
+ set(key, value) {
11683
+ if (super.has(key)) {
11684
+ super.delete(key);
11685
+ }
11686
+ super.set(key, value);
11687
+ while (super.size > this.maxSize) {
11688
+ const first = super.entries().next().value;
11689
+ if (!first) break;
11690
+ const [oldestKey, oldestValue] = first;
11691
+ super.delete(oldestKey);
11692
+ this._onEvict?.(oldestKey, oldestValue);
11693
+ }
11694
+ return this;
11695
+ }
11696
+ }
11697
+
11473
11698
  class AEncryptedClientProvider extends ADataProvider {
11474
11699
  encryption;
11475
11700
  _searchIndex;
11476
- _decryptedCache = /* @__PURE__ */ new Map();
11477
11701
  _decryptedRefCache = /* @__PURE__ */ new WeakMap();
11702
+ _idToEncryptedRef = /* @__PURE__ */ new Map();
11703
+ _decryptedCache = new CLruMap(5e3, (evictedId) => {
11704
+ const ref = this._idToEncryptedRef.get(evictedId);
11705
+ if (ref) {
11706
+ this._decryptedRefCache.delete(ref);
11707
+ this._idToEncryptedRef.delete(evictedId);
11708
+ }
11709
+ });
11478
11710
  constructor(options) {
11479
11711
  super(options);
11480
11712
  if (options?.encryption) {
@@ -11536,6 +11768,7 @@ class AEncryptedClientProvider extends ADataProvider {
11536
11768
  this._decryptedRefCache.set(rowOrId, decryptedRow);
11537
11769
  const id = rowOrId[this.idKey] ?? rowOrId.id ?? rowOrId._id;
11538
11770
  if (id !== void 0 && id !== null) {
11771
+ this._idToEncryptedRef.set(id, rowOrId);
11539
11772
  this._decryptedCache.set(id, decryptedRow);
11540
11773
  }
11541
11774
  } else if (rowOrId !== void 0 && rowOrId !== null) {
@@ -11544,6 +11777,7 @@ class AEncryptedClientProvider extends ADataProvider {
11544
11777
  }
11545
11778
  clearDecryptedCache() {
11546
11779
  this._decryptedCache.clear();
11780
+ this._idToEncryptedRef.clear();
11547
11781
  this._decryptedRefCache = /* @__PURE__ */ new WeakMap();
11548
11782
  }
11549
11783
  /**
@@ -11558,8 +11792,16 @@ class AEncryptedClientProvider extends ADataProvider {
11558
11792
  const idKey = this.idKey || "id";
11559
11793
  const rowId = rowOrId[idKey] ?? rowOrId.id ?? rowOrId._id;
11560
11794
  this._deleteCacheIdVariants(this._decryptedCache, rowId);
11795
+ if (rowId !== void 0 && rowId !== null) {
11796
+ this._idToEncryptedRef.delete(rowId);
11797
+ }
11561
11798
  return;
11562
11799
  }
11800
+ const ref = this._idToEncryptedRef.get(rowOrId);
11801
+ if (ref) {
11802
+ this._decryptedRefCache.delete(ref);
11803
+ this._idToEncryptedRef.delete(rowOrId);
11804
+ }
11563
11805
  this._deleteCacheIdVariants(this._decryptedCache, rowOrId);
11564
11806
  }
11565
11807
  /**
@@ -11568,15 +11810,30 @@ class AEncryptedClientProvider extends ADataProvider {
11568
11810
  evictDecryptedRow(rowOrId) {
11569
11811
  this.invalidateDecryptedRow(rowOrId);
11570
11812
  }
11571
- async populateDecryptedCache(rows) {
11813
+ async _forEachChunk(items, options, fn) {
11814
+ const chunkSize = options?.chunkSize ?? 100;
11815
+ for (let offset = 0; offset < items.length; offset += chunkSize) {
11816
+ if (options?.isStale?.()) return;
11817
+ const chunk = items.slice(offset, offset + chunkSize);
11818
+ await fn(chunk);
11819
+ if (options?.isStale?.()) return;
11820
+ if (offset + chunkSize < items.length) {
11821
+ await new Promise((resolve) => setTimeout(resolve, 0));
11822
+ }
11823
+ }
11824
+ }
11825
+ async populateDecryptedCache(rows, options) {
11572
11826
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) return;
11573
11827
  try {
11574
- const { rows: decrypted, decrypted: success } = await this.decryptRows(rows);
11575
- if (success && decrypted) {
11576
- for (let i = 0; i < rows.length; i++) {
11577
- this.cacheDecryptedRow(rows[i], decrypted[i]);
11828
+ await this._forEachChunk(rows, options, async (chunk) => {
11829
+ const { rows: decrypted, decrypted: success } = await this.decryptRows(chunk);
11830
+ if (options?.isStale?.()) return;
11831
+ if (success && decrypted) {
11832
+ for (let i = 0; i < chunk.length; i++) {
11833
+ this.cacheDecryptedRow(chunk[i], decrypted[i]);
11834
+ }
11578
11835
  }
11579
- }
11836
+ });
11580
11837
  } catch (err) {
11581
11838
  console.warn("[Katlux Providers] Failed to populate decrypted cache:", err);
11582
11839
  }
@@ -11687,28 +11944,35 @@ class AEncryptedClientProvider extends ADataProvider {
11687
11944
  this._searchIndex = void 0;
11688
11945
  this.clearDecryptedCache();
11689
11946
  }
11947
+ _getApiUrl() {
11948
+ return void 0;
11949
+ }
11950
+ _extractPlainFields(row, fields) {
11951
+ const plainFields = {};
11952
+ if (!row || typeof row !== "object") return plainFields;
11953
+ const targetFields = fields && fields.length > 0 ? fields : Object.keys(row);
11954
+ for (const f of targetFields) {
11955
+ if (row[f] !== void 0) {
11956
+ plainFields[f] = row[f];
11957
+ }
11958
+ }
11959
+ return plainFields;
11960
+ }
11961
+ async _indexEncryptedRows(encryptedRows, plainRows) {
11962
+ if (!this._searchIndex) return;
11963
+ await Promise.all(encryptedRows.map((encRow, idx) => {
11964
+ const plainFields = this._extractPlainFields(plainRows[idx], this.encryption?.fields);
11965
+ return this._searchIndex.indexRow(encRow, plainFields);
11966
+ }));
11967
+ }
11690
11968
  async encryptRows(rows) {
11691
11969
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) {
11692
11970
  return rows;
11693
11971
  }
11694
- const plainMap = /* @__PURE__ */ new Map();
11695
- if (this._searchIndex) {
11696
- for (const r of rows) {
11697
- const plainFields = {};
11698
- const allKeys = /* @__PURE__ */ new Set([...Object.keys(r || {}), ...this.encryption?.fields || []]);
11699
- for (const f of allKeys) {
11700
- plainFields[f] = r[f];
11701
- }
11702
- plainMap.set(r, plainFields);
11703
- }
11704
- }
11705
- const url = this.apiUrl || void 0;
11706
- const encryptedRows = await encryptRows(rows, this.encryption, url, this.idKey);
11972
+ const plainRows = this._searchIndex ? rows.map((r) => this._extractPlainFields(r, this.encryption?.fields)) : [];
11973
+ const encryptedRows = await encryptRows(rows, this.encryption, this._getApiUrl(), this.idKey);
11707
11974
  if (this._searchIndex) {
11708
- await Promise.all(encryptedRows.map((encRow, i) => {
11709
- const plain = plainMap.get(rows[i]);
11710
- return this._searchIndex.indexRow(encRow, plain);
11711
- }));
11975
+ await this._indexEncryptedRows(encryptedRows, plainRows);
11712
11976
  }
11713
11977
  return encryptedRows;
11714
11978
  }
@@ -11718,57 +11982,37 @@ class AEncryptedClientProvider extends ADataProvider {
11718
11982
  return rows;
11719
11983
  }
11720
11984
  const indexChunk = this._searchIndex ? async (chunkPlain, chunkEncrypted) => {
11721
- const plainMap = /* @__PURE__ */ new Map();
11722
- for (const r of chunkPlain) {
11723
- const plainFields = {};
11724
- for (const f of this.encryption?.fields || Object.keys(r)) {
11725
- plainFields[f] = r[f];
11726
- }
11727
- plainMap.set(r, plainFields);
11728
- }
11729
- await Promise.all(chunkEncrypted.map((encRow, idx) => {
11730
- const plain = plainMap.get(chunkPlain[idx]);
11731
- return this._searchIndex.indexRow(encRow, plain);
11732
- }));
11985
+ await this._indexEncryptedRows(chunkEncrypted, chunkPlain);
11733
11986
  } : void 0;
11734
- return await encryptRowsChunked(rows, this.encryption, options, void 0, this.idKey, indexChunk);
11987
+ return await encryptRowsChunked(rows, this.encryption, options, this._getApiUrl(), this.idKey, indexChunk);
11735
11988
  }
11736
11989
  /**
11737
11990
  * Indexes pre-encrypted rows by performing a transient in-memory decryption pass
11738
11991
  * on search fields to populate CSearchIndex without mutating underlying encrypted records in allData.
11739
11992
  */
11740
- async indexPreEncryptedRows(rows) {
11993
+ async indexPreEncryptedRows(rows, options) {
11741
11994
  if (!this.isEncryptionEnabled || !this._searchIndex || !rows || rows.length === 0) {
11742
11995
  return;
11743
11996
  }
11744
11997
  const cipher = getCipherProvider(this.encryption);
11745
11998
  if (!cipher) return;
11746
- const ctx = buildEncryptionContext(this.encryption, this.apiUrl, this.idKey);
11747
- let decryptedRows = [];
11999
+ const ctx = buildEncryptionContext(this.encryption, this._getApiUrl(), this.idKey);
11748
12000
  try {
11749
- const decResult = await cipher.decrypt(rows, ctx);
11750
- decryptedRows = Array.isArray(decResult) ? decResult : [decResult];
12001
+ await this._forEachChunk(rows, options, async (chunk) => {
12002
+ const decResult = await cipher.decrypt(chunk, ctx);
12003
+ if (options?.isStale?.()) return;
12004
+ const decryptedRows = Array.isArray(decResult) ? decResult : [decResult];
12005
+ await this._indexEncryptedRows(chunk, decryptedRows);
12006
+ });
11751
12007
  } catch (err) {
11752
12008
  console.warn("[Katlux Providers] indexPreEncryptedRows: Decryption failed during search index build", err);
11753
- return;
11754
12009
  }
11755
- await Promise.all(rows.map((row, idx) => {
11756
- const decRow = decryptedRows[idx];
11757
- const plainFields = {};
11758
- for (const f of this.encryption?.fields || Object.keys(decRow || {})) {
11759
- if (decRow && decRow[f] !== void 0) {
11760
- plainFields[f] = decRow[f];
11761
- }
11762
- }
11763
- return this._searchIndex.indexRow(row, plainFields);
11764
- }));
11765
12010
  }
11766
12011
  async decryptRows(rows) {
11767
12012
  if (!this.isEncryptionEnabled || !rows || rows.length === 0) {
11768
12013
  return { rows, decrypted: false };
11769
12014
  }
11770
- const url = this.apiUrl || void 0;
11771
- return await decryptPageRows(rows, this.encryption, url, this.idKey);
12015
+ return await decryptPageRows(rows, this.encryption, this._getApiUrl(), this.idKey);
11772
12016
  }
11773
12017
  async setDataChunked(data, options) {
11774
12018
  const ret = this.setData(data);
@@ -11913,14 +12157,15 @@ async function prepareIncomingEncryptedRows(host, rows, options) {
11913
12157
  }
11914
12158
  if (isPreEnc) {
11915
12159
  if (host.searchIndex) {
11916
- await host.indexPreEncryptedRows(rows);
12160
+ await host.indexPreEncryptedRows(rows, { isStale: options?.isStale });
11917
12161
  if (options?.isStale?.()) return { rows, preEncrypted: true, stale: true };
11918
12162
  }
11919
12163
  if (options?.populateCache && host.encryption?.decryptedCache) {
11920
- await host.populateDecryptedCache(rows);
12164
+ await host.populateDecryptedCache(rows, { isStale: options?.isStale });
12165
+ if (options?.isStale?.()) return { rows, preEncrypted: true, stale: true };
11921
12166
  if (options?.decryptedNodeMap) {
11922
- for (const r of rows) {
11923
- recordDecryptedNodeMap(options.decryptedNodeMap, host.idKey, r, host.getDecryptedRow(r));
12167
+ for (let i = 0; i < rows.length; i++) {
12168
+ recordDecryptedNodeMap(options.decryptedNodeMap, host.idKey, rows[i], host.getDecryptedRow(rows[i]));
11924
12169
  }
11925
12170
  }
11926
12171
  }
@@ -12121,12 +12366,14 @@ function areAllBatchesLoaded(batchSize, totalRows, loadedCount) {
12121
12366
  const totalBatches = Math.ceil(totalRows / batchSize);
12122
12367
  return loadedCount >= totalBatches;
12123
12368
  }
12124
- async function applyOnDemandPolicy(policy, contextLabel, ingestAllFn, batchNoun = "batches") {
12369
+ async function applyOnDemandPolicy(policy, contextLabel, ingestAllFn, batchNoun = "batches", onComplete) {
12125
12370
  if (policy === "ingestAll") {
12126
12371
  console.warn(
12127
12372
  `[Katlux Providers] ${contextLabel} applied with partial on-demand ${batchNoun}. Ingesting all remaining batches in background to ensure accurate results.`
12128
12373
  );
12129
- await ingestAllFn();
12374
+ void Promise.resolve(ingestAllFn()).then(() => onComplete?.()).catch((err) => {
12375
+ console.error(`[Katlux Providers] Background ${batchNoun} ingestion failed during ${contextLabel}:`, err);
12376
+ });
12130
12377
  } else {
12131
12378
  console.warn(
12132
12379
  `[Katlux Providers] ${contextLabel} applied while on-demand ${batchNoun} are partially loaded. Some matching records may not be in memory.`
@@ -12243,6 +12490,7 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12243
12490
  batchSize = false;
12244
12491
  batchLoad = "initially";
12245
12492
  onDemandFilterPolicy = "ingestAll";
12493
+ maxCachedBatches;
12246
12494
  onBatchLoaded;
12247
12495
  loadedBatches = /* @__PURE__ */ new Set();
12248
12496
  _rawSourceData;
@@ -12273,8 +12521,34 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12273
12521
  if (options?.batchSize !== void 0) this.batchSize = options.batchSize;
12274
12522
  if (options?.batchLoad) this.batchLoad = options.batchLoad;
12275
12523
  if (options?.onDemandFilterPolicy) this.onDemandFilterPolicy = options.onDemandFilterPolicy;
12524
+ if (options?.maxCachedBatches !== void 0) this.maxCachedBatches = options.maxCachedBatches;
12276
12525
  if (options?.onBatchLoaded) this.onBatchLoaded = options.onBatchLoaded;
12277
12526
  }
12527
+ /**
12528
+ * Evicts oldest loaded batches when maxCachedBatches is configured and exceeded,
12529
+ * clearing their slots in _allData so they can be re-fetched on demand.
12530
+ */
12531
+ _evictOldestBatchesIfNeeded(activeBatch) {
12532
+ if (this.maxCachedBatches === void 0 || this.maxCachedBatches <= 0) return;
12533
+ if (typeof this.batchSize !== "number" || this.batchSize <= 0) return;
12534
+ while (this.loadedBatches.size > this.maxCachedBatches) {
12535
+ let evicted;
12536
+ for (const b of this.loadedBatches) {
12537
+ if (b !== activeBatch) {
12538
+ evicted = b;
12539
+ break;
12540
+ }
12541
+ }
12542
+ if (evicted === void 0) break;
12543
+ this.loadedBatches.delete(evicted);
12544
+ const start = (evicted - 1) * this.batchSize;
12545
+ const end = Math.min(evicted * this.batchSize, this._allData.length);
12546
+ for (let i = start; i < end; i++) {
12547
+ this._allData[i] = void 0;
12548
+ }
12549
+ this._isSparse = true;
12550
+ }
12551
+ }
12278
12552
  _assignAllData(data, preserveDecryptedCache = false) {
12279
12553
  this._allData = Array.isArray(data) ? data : [];
12280
12554
  this._filterDirty = true;
@@ -12353,7 +12627,9 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12353
12627
  }
12354
12628
  this._filterDirty = true;
12355
12629
  this._sortDirty = true;
12356
- await this.loadPageData();
12630
+ if (!(this.pageSize > 0 && (this.pageData?.length ?? 0) >= this.pageSize)) {
12631
+ await this.loadPageData();
12632
+ }
12357
12633
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: pageNum, rows: nextChunk, totalLoaded: this.allData.length, rowCount: total });
12358
12634
  this.loadedBatches.add(pageNum);
12359
12635
  this.batchProgress = computeBatchProgress(this.allData.length, total);
@@ -12361,6 +12637,10 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12361
12637
  pageNum++;
12362
12638
  }
12363
12639
  if (batchGen === this._batchGeneration) {
12640
+ if (this._filterDirty || this._sortDirty) {
12641
+ await this.loadPageData();
12642
+ if (batchGen !== this._batchGeneration) return;
12643
+ }
12364
12644
  this.isBatchLoading = false;
12365
12645
  this.batchProgress = { loaded: this.allData.length, total, percent: 100 };
12366
12646
  this.notify();
@@ -12634,7 +12914,8 @@ class CFlatClientDataProvider extends AEncryptedClientProvider {
12634
12914
  this.error = null;
12635
12915
  try {
12636
12916
  if (this.encryption?.decryptedCache && this.sortList.length > 0) {
12637
- if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData))) {
12917
+ const rangeBuckets = this.encryption?.rangeBuckets || this.encryption?.shadowBuckets;
12918
+ if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData) && !rangeBuckets?.[s.field])) {
12638
12919
  const uncached = this.allData.filter((r) => r !== void 0 && r !== null && !this.getDecryptedRow(r));
12639
12920
  if (uncached.length > 0) await this.populateDecryptedCache(uncached);
12640
12921
  }
@@ -12827,6 +13108,9 @@ class CAPIFlatClientDataProvider extends CFlatClientDataProvider {
12827
13108
  _lastDataReceivedPromise = null;
12828
13109
  _lastBatch1CallbackGen = -1;
12829
13110
  _suppressOnDemandWarn = false;
13111
+ _getApiUrl() {
13112
+ return this.apiUrl || void 0;
13113
+ }
12830
13114
  setData(data) {
12831
13115
  this._bumpRequestGeneration();
12832
13116
  this._isStreamingBatches = false;
@@ -15581,17 +15865,6 @@ function computeRetainedExpandedNodes(staticNodes, expandedNodes, expandedByDefa
15581
15865
  const parentIds = staticNodes.filter((n) => n.hasChildren).map((n) => n.id);
15582
15866
  return /* @__PURE__ */ new Set([...validExisting, ...parentIds]);
15583
15867
  }
15584
- function mergeUniqueTreeRows(existingData, incomingRows, idKey) {
15585
- const existingIds = new Set(
15586
- existingData.map((r) => r && typeof r === "object" ? r[idKey] : void 0).filter((id) => id !== void 0 && id !== null)
15587
- );
15588
- const uniqueIncoming = existingIds.size > 0 ? incomingRows.filter((r) => {
15589
- const id = r && typeof r === "object" ? r[idKey] : void 0;
15590
- return id === void 0 || id === null || !existingIds.has(id);
15591
- }) : incomingRows;
15592
- if (uniqueIncoming.length === 0) return null;
15593
- return [...existingData, ...uniqueIncoming];
15594
- }
15595
15868
 
15596
15869
  class CTreeClientDataProvider extends CFlatClientDataProvider {
15597
15870
  parentKey = "parentId";
@@ -15604,7 +15877,8 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15604
15877
  _sortedNodeIdsCache = null;
15605
15878
  _filteredNodesCache = null;
15606
15879
  _allVisibleRowsCache = null;
15607
- _decryptedNodeMap = /* @__PURE__ */ new Map();
15880
+ _decryptedNodeMap = new CLruMap(5e3);
15881
+ _knownIds = /* @__PURE__ */ new Set();
15608
15882
  clearDecryptedCache() {
15609
15883
  super.clearDecryptedCache();
15610
15884
  this._decryptedNodeMap.clear();
@@ -15628,8 +15902,36 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15628
15902
  _assignAllData(data, preserveDecryptedCache = false) {
15629
15903
  super._assignAllData(data, preserveDecryptedCache);
15630
15904
  if (!preserveDecryptedCache) this._decryptedNodeMap.clear();
15905
+ this._knownIds.clear();
15906
+ const idKey = this.idKey || "id";
15907
+ for (let i = 0; i < this.allData.length; i++) {
15908
+ const id = this.allData[i]?.[idKey];
15909
+ if (id !== void 0 && id !== null) this._knownIds.add(id);
15910
+ }
15631
15911
  this.invalidateStaticCache();
15632
15912
  }
15913
+ /** Appends unique rows in-place using _knownIds without cloning allData. */
15914
+ _appendUniqueTreeRows(rows) {
15915
+ if (!Array.isArray(rows) || rows.length === 0) return false;
15916
+ const idKey = this.idKey || "id";
15917
+ let appended = false;
15918
+ for (let i = 0; i < rows.length; i++) {
15919
+ const row = rows[i];
15920
+ const id = row?.[idKey];
15921
+ if (id === void 0 || id === null || !this._knownIds.has(id)) {
15922
+ if (id !== void 0 && id !== null) this._knownIds.add(id);
15923
+ this.allData.push(row);
15924
+ appended = true;
15925
+ }
15926
+ }
15927
+ if (appended) {
15928
+ this.invalidateStaticCache();
15929
+ this._filterDirty = true;
15930
+ this._sortDirty = true;
15931
+ this.expandedNodes = computeRetainedExpandedNodes(this._staticNodes, this.expandedNodes, this.expandedByDefault);
15932
+ }
15933
+ return appended;
15934
+ }
15633
15935
  get allData() {
15634
15936
  return super.allData;
15635
15937
  }
@@ -15774,11 +16076,13 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15774
16076
  if (batchGen !== this._batchGeneration) return;
15775
16077
  const nextChunk = data.slice(i, i + batchSize);
15776
16078
  const processedRes = await prepareIncomingEncryptedRows(this._getEncryptionHost(), nextChunk, { populateCache: true });
15777
- this._applyTreeData([...this.allData, ...processedRes.rows], true);
16079
+ this._appendUniqueTreeRows(processedRes.rows);
15778
16080
  if (this.isEncryptionEnabled && this.encryption?.decryptedCache) {
15779
16081
  for (const [id, dec] of this._decryptedCache.entries()) this._decryptedNodeMap.set(id, dec);
15780
16082
  }
15781
- await this.loadPageData();
16083
+ if (!(this.pageSize > 0 && (this.pageData?.length ?? 0) >= this.pageSize)) {
16084
+ await this.loadPageData();
16085
+ }
15782
16086
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: pageNum, rows: nextChunk, totalLoaded: this.allData.length, rowCount: total });
15783
16087
  this.loadedBatches.add(pageNum);
15784
16088
  this.batchProgress = computeBatchProgress(this.allData.length, total);
@@ -15786,6 +16090,10 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15786
16090
  pageNum++;
15787
16091
  }
15788
16092
  if (batchGen === this._batchGeneration) {
16093
+ if (this._filterDirty || this._sortDirty) {
16094
+ await this.loadPageData();
16095
+ if (batchGen !== this._batchGeneration) return;
16096
+ }
15789
16097
  this.isBatchLoading = false;
15790
16098
  this.batchProgress = { loaded: this.allData.length, total, percent: 100 };
15791
16099
  this.notify();
@@ -15938,10 +16246,13 @@ class CTreeClientDataProvider extends CFlatClientDataProvider {
15938
16246
  this.loading = true;
15939
16247
  this.error = null;
15940
16248
  try {
15941
- if (this.encryption?.decryptedCache && this.sortList.length > 0 && this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData))) {
15942
- const uncached = this._staticNodes.filter((n) => !this._decryptedNodeMap.has(n.id) && !this.getDecryptedRow(n.data));
15943
- if (await this._decryptAndCacheTreeNodes(uncached)) {
15944
- this._sortedNodeIdsCache = null;
16249
+ if (this.encryption?.decryptedCache && this.sortList.length > 0) {
16250
+ const rangeBuckets = this.encryption?.rangeBuckets || this.encryption?.shadowBuckets;
16251
+ if (this.sortList.some((s) => this.isFieldEncrypted(s.field, this.allData) && !rangeBuckets?.[s.field])) {
16252
+ const uncached = this._staticNodes.filter((n) => !this._decryptedNodeMap.has(n.id) && !this.getDecryptedRow(n.data));
16253
+ if (await this._decryptAndCacheTreeNodes(uncached)) {
16254
+ this._sortedNodeIdsCache = null;
16255
+ }
15945
16256
  }
15946
16257
  }
15947
16258
  const needsVerification = Boolean(
@@ -16121,6 +16432,9 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16121
16432
  _abortController;
16122
16433
  _lastDataReceivedPromise = null;
16123
16434
  _lastBatch1CallbackGen = -1;
16435
+ _getApiUrl() {
16436
+ return this.apiUrl || void 0;
16437
+ }
16124
16438
  setData(data) {
16125
16439
  this._bumpRequestGeneration();
16126
16440
  this._isAccumulating = false;
@@ -16214,8 +16528,7 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16214
16528
  }
16215
16529
  /** Deduplicates incoming tree rows by idKey and appends them to the existing tree buffer. */
16216
16530
  _mergeTreeRows(rows) {
16217
- const merged = mergeUniqueTreeRows(this.allData, rows, this.idKey || "id");
16218
- if (merged) this._applyTreeData(merged, true);
16531
+ this._appendUniqueTreeRows(rows);
16219
16532
  }
16220
16533
  setEncryption(encryption) {
16221
16534
  super.setEncryption(encryption);
@@ -16493,7 +16806,7 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16493
16806
  this.notify();
16494
16807
  }
16495
16808
  }
16496
- async loadBatch(batchNumber) {
16809
+ async loadBatch(batchNumber, options) {
16497
16810
  if (typeof this.batchSize !== "number" || this.batchSize <= 0 || this.loadedBatches.has(batchNumber)) return;
16498
16811
  if (this._inFlightBatches.has(batchNumber)) return this._inFlightBatches.get(batchNumber);
16499
16812
  const reqGen = this._requestGeneration;
@@ -16535,8 +16848,10 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16535
16848
  this.loadedBatches.add(batchNumber);
16536
16849
  this._filterDirty = true;
16537
16850
  this._sortDirty = true;
16538
- await super.loadPageData();
16539
- if (isStale()) return;
16851
+ if (!options?.skipPageLoad) {
16852
+ await super.loadPageData();
16853
+ if (isStale()) return;
16854
+ }
16540
16855
  const totalExpected = this._expectedRowCount ?? this.rowCount;
16541
16856
  emitBatchLoaded(this.onBatchLoaded, { pageNumber: batchNumber, rows: rawRows, totalLoaded: this.allData.length, rowCount: totalExpected });
16542
16857
  this.batchProgress = computeBatchProgress(this.allData.length, totalExpected);
@@ -16583,8 +16898,15 @@ class CAPITreeClientDataProvider extends CTreeClientDataProvider {
16583
16898
  const total = this._expectedRowCount ?? this.rowCount;
16584
16899
  if (total <= 0) return;
16585
16900
  const totalBatches = Math.ceil(total / this.batchSize);
16901
+ let loadedAny = false;
16586
16902
  for (let b = 1; b <= totalBatches; b++) {
16587
- if (!this.loadedBatches.has(b)) await this.loadBatch(b);
16903
+ if (!this.loadedBatches.has(b)) {
16904
+ await this.loadBatch(b, { skipPageLoad: true });
16905
+ loadedAny = true;
16906
+ }
16907
+ }
16908
+ if (loadedAny && (this._filterDirty || this._sortDirty)) {
16909
+ await super.loadPageData();
16588
16910
  }
16589
16911
  }
16590
16912
  async setFilter(filter, immediate = false) {
@@ -20645,6 +20967,7 @@ exports.compareOr = compareOr;
20645
20967
  exports.compareRangeBuckets = compareRangeBuckets;
20646
20968
  exports.compareSteppedBuckets = compareSteppedBuckets;
20647
20969
  exports.compareValues = compareValues;
20970
+ exports.compileFilter = compileFilter;
20648
20971
  exports.computeBlindIndex = computeBlindIndex;
20649
20972
  exports.computeBlindIndexSchemeId = computeBlindIndexSchemeId;
20650
20973
  exports.computeDateBucket = computeDateBucket;