tricache 0.9.0 → 1.0.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.
Files changed (47) hide show
  1. package/README.md +7 -3
  2. package/dist/{cache-service-KI5ACF3F.js → cache-service-26GCO3UU.js} +3 -3
  3. package/dist/{cache-service-DVvroyqA.d.ts → cache-service-pJ-nFcVj.d.ts} +29 -12
  4. package/dist/{chunk-XZL45ABR.js → chunk-2AJKEQMZ.js} +54 -1
  5. package/dist/{chunk-PL5J3ZNT.js → chunk-7SZSQS55.js} +201 -34
  6. package/dist/{chunk-LJ5QJB5O.js → chunk-UBWLPKTI.js} +127 -11
  7. package/dist/cli.cjs +376 -50
  8. package/dist/cli.js +4 -4
  9. package/dist/dashboard/index.d.ts +2 -2
  10. package/dist/drizzle/index.cjs +384 -51
  11. package/dist/drizzle/index.d.ts +2 -2
  12. package/dist/drizzle/index.js +1 -1
  13. package/dist/edge/index.cjs +64 -8
  14. package/dist/edge/index.d.ts +3 -3
  15. package/dist/edge/index.js +37 -9
  16. package/dist/hono/index.cjs +384 -51
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +1 -1
  19. package/dist/{hono-VA9A1m0I.d.ts → hono-DuNvciyq.d.ts} +4 -4
  20. package/dist/http/index.cjs +384 -51
  21. package/dist/http/index.d.ts +3 -3
  22. package/dist/http/index.js +8 -8
  23. package/dist/index.cjs +385 -49
  24. package/dist/index.d.ts +35 -6
  25. package/dist/index.js +16 -6
  26. package/dist/nestjs/index.cjs +375 -49
  27. package/dist/nestjs/index.d.ts +2 -2
  28. package/dist/nestjs/index.js +4 -4
  29. package/dist/next/index.cjs +375 -49
  30. package/dist/next/index.d.ts +2 -2
  31. package/dist/next/index.js +3 -3
  32. package/dist/prisma/index.d.ts +2 -2
  33. package/dist/serialize-worker.cjs +127 -9
  34. package/dist/serialize-worker.js +8 -4
  35. package/dist/{types-B_QkVwJ7.d.ts → types-5HXqBfAf.d.ts} +51 -7
  36. package/package.json +7 -4
  37. package/src/cache-service.ts +238 -33
  38. package/src/cli.ts +1 -1
  39. package/src/compression.ts +193 -15
  40. package/src/cross-region.ts +1 -1
  41. package/src/edge/cache.ts +38 -11
  42. package/src/env.d.ts +13 -0
  43. package/src/index.ts +9 -1
  44. package/src/serialize-worker.ts +6 -2
  45. package/src/types.ts +43 -5
  46. package/src/utils/tag-matcher.ts +90 -0
  47. /package/dist/{chunk-QNU7B43J.js → chunk-VXFTFZ5N.js} +0 -0
@@ -1914,13 +1914,38 @@ var import_os2 = __toESM(require("os"), 1);
1914
1914
 
1915
1915
  // src/compression.ts
1916
1916
  var import_zlib = __toESM(require("zlib"), 1);
1917
+ var import_lz4js = __toESM(require("lz4js"), 1);
1918
+ var import_zstd_codec = require("zstd-codec");
1917
1919
  var PREFIX_COMPRESSED = "cmp:v1:";
1918
1920
  var PREFIX_ENC_COMPRESSED = "ecp:v1:";
1919
1921
  var COMPRESSION_MAGIC = Buffer.from([84, 82, 67, 1]);
1922
+ var zstdSimple = null;
1923
+ var zstdInitPromise = null;
1924
+ function initZstd() {
1925
+ if (zstdSimple) return Promise.resolve(zstdSimple);
1926
+ if (!zstdInitPromise) {
1927
+ zstdInitPromise = new Promise((resolve) => {
1928
+ try {
1929
+ import_zstd_codec.ZstdCodec.run((zstd) => {
1930
+ zstdSimple = new zstd.Simple();
1931
+ resolve(zstdSimple);
1932
+ });
1933
+ } catch {
1934
+ resolve(null);
1935
+ }
1936
+ });
1937
+ }
1938
+ return zstdInitPromise;
1939
+ }
1940
+ initZstd().catch(() => {
1941
+ });
1920
1942
  function isCompressed(buf) {
1921
1943
  return buf.length >= 4 && buf[0] === 84 && buf[1] === 82 && buf[2] === 67 && buf[3] === 1;
1922
1944
  }
1923
- function compressBuffer(buf, algorithm) {
1945
+ function compressBuffer(buf, algorithm, custom) {
1946
+ if (custom) {
1947
+ return custom.compress(buf);
1948
+ }
1924
1949
  if (algorithm === "brotli") {
1925
1950
  return import_zlib.default.brotliCompressSync(buf, {
1926
1951
  params: {
@@ -1932,37 +1957,127 @@ function compressBuffer(buf, algorithm) {
1932
1957
  if (algorithm === "gzip") {
1933
1958
  return import_zlib.default.gzipSync(buf, { level: 6 });
1934
1959
  }
1960
+ if (algorithm === "lz4") {
1961
+ return Buffer.from(import_lz4js.default.compress(buf));
1962
+ }
1963
+ if (algorithm === "zstd") {
1964
+ if (!zstdSimple) {
1965
+ return import_zlib.default.brotliCompressSync(buf, {
1966
+ params: { [import_zlib.default.constants.BROTLI_PARAM_QUALITY]: 4 }
1967
+ });
1968
+ }
1969
+ return Buffer.from(zstdSimple.compress(buf));
1970
+ }
1935
1971
  return buf;
1936
1972
  }
1937
- function decompressBuffer(buf, algorithm = "brotli") {
1973
+ var MAX_DECOMPRESS_BYTES = 25 * 1024 * 1024;
1974
+ function decompressBuffer(buf, algorithm = "zstd", custom) {
1975
+ if (custom) {
1976
+ const res = custom.decompress(buf);
1977
+ if (res.length > MAX_DECOMPRESS_BYTES) {
1978
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1979
+ }
1980
+ return res;
1981
+ }
1982
+ const checkSafety = (decomp) => {
1983
+ if (decomp.length > MAX_DECOMPRESS_BYTES) {
1984
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
1985
+ }
1986
+ return decomp;
1987
+ };
1988
+ if (buf.length >= 4 && buf[0] === 40 && buf[1] === 181 && buf[2] === 47 && buf[3] === 253) {
1989
+ if (zstdSimple) {
1990
+ try {
1991
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
1992
+ } catch (err) {
1993
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
1994
+ }
1995
+ }
1996
+ }
1997
+ if (buf.length >= 4 && buf[0] === 4 && buf[1] === 34 && buf[2] === 77 && buf[3] === 24) {
1998
+ try {
1999
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2000
+ } catch (err) {
2001
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2002
+ }
2003
+ }
2004
+ if (buf.length >= 2 && buf[0] === 31 && buf[1] === 139) {
2005
+ try {
2006
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2007
+ } catch (err) {
2008
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2009
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2010
+ }
2011
+ }
2012
+ }
2013
+ if (algorithm === "none") {
2014
+ return buf;
2015
+ }
2016
+ if (algorithm === "lz4") {
2017
+ try {
2018
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2019
+ } catch (err) {
2020
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2021
+ }
2022
+ }
2023
+ if (algorithm === "zstd" && zstdSimple) {
2024
+ try {
2025
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2026
+ } catch (err) {
2027
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2028
+ }
2029
+ }
1938
2030
  const tryBrotli = () => {
1939
2031
  try {
1940
- return import_zlib.default.brotliDecompressSync(buf);
1941
- } catch {
2032
+ return import_zlib.default.brotliDecompressSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2033
+ } catch (err) {
2034
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2035
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2036
+ }
1942
2037
  return null;
1943
2038
  }
1944
2039
  };
1945
2040
  const tryGzip = () => {
1946
2041
  try {
1947
- return import_zlib.default.gunzipSync(buf);
1948
- } catch {
2042
+ return import_zlib.default.gunzipSync(buf, { maxOutputLength: MAX_DECOMPRESS_BYTES });
2043
+ } catch (err) {
2044
+ if (err?.code === "ERR_BUFFER_TOO_LARGE") {
2045
+ throw new Error(`tricache: decompressed payload exceeds maximum safety threshold of ${MAX_DECOMPRESS_BYTES} bytes`);
2046
+ }
1949
2047
  return null;
1950
2048
  }
1951
2049
  };
1952
- const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
2050
+ const tryLz4 = () => {
2051
+ try {
2052
+ return checkSafety(Buffer.from(import_lz4js.default.decompress(buf)));
2053
+ } catch (err) {
2054
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2055
+ return null;
2056
+ }
2057
+ };
2058
+ const tryZstd = () => {
2059
+ if (!zstdSimple) return null;
2060
+ try {
2061
+ return checkSafety(Buffer.from(zstdSimple.decompress(buf)));
2062
+ } catch (err) {
2063
+ if (err?.message?.includes("exceeds maximum safety threshold")) throw err;
2064
+ return null;
2065
+ }
2066
+ };
2067
+ const result = (algorithm === "gzip" ? tryGzip() : null) ?? (algorithm === "lz4" ? tryLz4() : null) ?? (algorithm === "zstd" ? tryZstd() : null) ?? tryBrotli() ?? tryGzip() ?? tryLz4() ?? tryZstd();
1953
2068
  if (result === null) {
1954
2069
  throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
1955
2070
  }
1956
2071
  return result;
1957
2072
  }
1958
- function compressWithHeader(buf, algorithm) {
2073
+ function compressWithHeader(buf, algorithm, custom) {
1959
2074
  if (algorithm === "none") return buf;
1960
- const compressed = compressBuffer(buf, algorithm);
2075
+ const compressed = compressBuffer(buf, algorithm, custom);
1961
2076
  return Buffer.concat([COMPRESSION_MAGIC, compressed]);
1962
2077
  }
1963
- function decompressWithHeader(buf, algorithm = "brotli") {
2078
+ function decompressWithHeader(buf, algorithm = "zstd", custom) {
1964
2079
  if (isCompressed(buf)) {
1965
- return decompressBuffer(buf.subarray(4), algorithm);
2080
+ return decompressBuffer(buf.subarray(4), algorithm, custom);
1966
2081
  }
1967
2082
  return buf;
1968
2083
  }
@@ -3577,6 +3692,55 @@ var IpcTelemetryServer = class {
3577
3692
  }
3578
3693
  };
3579
3694
 
3695
+ // src/utils/tag-matcher.ts
3696
+ var globRegexCache = /* @__PURE__ */ new Map();
3697
+ function isWildcardTag(tag) {
3698
+ return tag.includes("*") || tag.includes("?");
3699
+ }
3700
+ function matchesTagPattern(pattern, tag) {
3701
+ if (pattern === "*" || pattern === tag) return true;
3702
+ if (!pattern.includes("*") && !pattern.includes("?")) return pattern === tag;
3703
+ if (pattern.endsWith("*") && !pattern.slice(0, -1).includes("*") && !pattern.includes("?")) {
3704
+ const prefix = pattern.slice(0, -1);
3705
+ return tag.startsWith(prefix);
3706
+ }
3707
+ if (pattern.startsWith("*") && !pattern.slice(1).includes("*") && !pattern.includes("?")) {
3708
+ const suffix = pattern.slice(1);
3709
+ return tag.endsWith(suffix);
3710
+ }
3711
+ let re = globRegexCache.get(pattern);
3712
+ if (!re) {
3713
+ if (globRegexCache.size >= 1e3) globRegexCache.clear();
3714
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
3715
+ re = new RegExp(`^${escaped}$`);
3716
+ globRegexCache.set(pattern, re);
3717
+ }
3718
+ return re.test(tag);
3719
+ }
3720
+ function isChildTag(parentTag, candidateTag, delimiter = ":") {
3721
+ if (candidateTag === parentTag) return true;
3722
+ const prefix = parentTag.endsWith(delimiter) ? parentTag : `${parentTag}${delimiter}`;
3723
+ return candidateTag.startsWith(prefix);
3724
+ }
3725
+ function expandHierarchicalTags(tags, delimiter = ":") {
3726
+ if (!tags.length) return [];
3727
+ const result = /* @__PURE__ */ new Set();
3728
+ for (const tag of tags) {
3729
+ if (!tag) continue;
3730
+ const parts = tag.split(delimiter).filter((p) => p.length > 0);
3731
+ if (parts.length <= 1) {
3732
+ result.add(tag);
3733
+ continue;
3734
+ }
3735
+ let accumulated = "";
3736
+ for (let i = 0; i < parts.length; i++) {
3737
+ accumulated = i === 0 ? parts[i] : `${accumulated}${delimiter}${parts[i]}`;
3738
+ result.add(accumulated);
3739
+ }
3740
+ }
3741
+ return Array.from(result);
3742
+ }
3743
+
3580
3744
  // src/cache-service.ts
3581
3745
  var LUA_COMPARE_AND_DELETE = `
3582
3746
  local currentTs = redis.call('HGET', KEYS[1], 't')
@@ -3595,21 +3759,21 @@ var DEFAULT_CATEGORY_LIMITS = {
3595
3759
  var DEFAULT_FORBIDDEN_PREFIXES = ["auth:", "session:", "mfa:", "rate_limit:"];
3596
3760
  var DEFAULT_COUNTER_TTL_SECONDS = 60;
3597
3761
  var GLOB_REGEX_CACHE_MAX = 256;
3598
- var globRegexCache = /* @__PURE__ */ new Map();
3762
+ var globRegexCache2 = /* @__PURE__ */ new Map();
3599
3763
  function getGlobRegex(pattern) {
3600
- let re = globRegexCache.get(pattern);
3764
+ let re = globRegexCache2.get(pattern);
3601
3765
  if (re) {
3602
- globRegexCache.delete(pattern);
3603
- globRegexCache.set(pattern, re);
3766
+ globRegexCache2.delete(pattern);
3767
+ globRegexCache2.set(pattern, re);
3604
3768
  return re;
3605
3769
  }
3606
3770
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*+/g, ".*");
3607
3771
  re = new RegExp("^" + escaped + "$");
3608
- if (globRegexCache.size >= GLOB_REGEX_CACHE_MAX) {
3609
- const oldestKey = globRegexCache.keys().next().value;
3610
- if (oldestKey !== void 0) globRegexCache.delete(oldestKey);
3772
+ if (globRegexCache2.size >= GLOB_REGEX_CACHE_MAX) {
3773
+ const oldestKey = globRegexCache2.keys().next().value;
3774
+ if (oldestKey !== void 0) globRegexCache2.delete(oldestKey);
3611
3775
  }
3612
- globRegexCache.set(pattern, re);
3776
+ globRegexCache2.set(pattern, re);
3613
3777
  return re;
3614
3778
  }
3615
3779
  var L2CircuitBreaker = class {
@@ -3863,6 +4027,7 @@ var CacheService = class _CacheService {
3863
4027
  opts;
3864
4028
  /** Pre-computed once — opts.namespace never changes after construction. */
3865
4029
  _namespace;
4030
+ prefixLen;
3866
4031
  /** Pre-computed once — disableRedis and redisHost never change after construction. */
3867
4032
  _redisDisabled;
3868
4033
  watchdog;
@@ -4071,12 +4236,15 @@ var CacheService = class _CacheService {
4071
4236
  redisSentinel: options.redisSentinel,
4072
4237
  redisProtocol: options.redisProtocol,
4073
4238
  useShardedPubSub: options.useShardedPubSub ?? false,
4074
- compression: options.compression ?? "none",
4239
+ compression: options.compression ?? "zstd",
4240
+ customCompressor: options.customCompressor,
4075
4241
  compressionThresholdBytes: options.compressionThresholdBytes ?? 1024,
4076
4242
  strictSingleton: options.strictSingleton ?? false,
4077
4243
  failClosed: options.failClosed ?? false,
4078
4244
  tagStrategy: options.tagStrategy ?? "set",
4079
4245
  tagVersionTtlMs: options.tagVersionTtlMs ?? 5e3,
4246
+ hierarchicalTags: options.hierarchicalTags ?? false,
4247
+ tagHierarchyDelimiter: options.tagHierarchyDelimiter ?? ":",
4080
4248
  cloneStrategy: options.cloneStrategy ?? "none",
4081
4249
  backplaneMode: options.backplaneMode ?? "pubsub",
4082
4250
  backplaneStreamMaxLen: options.backplaneStreamMaxLen ?? 1e4,
@@ -4149,6 +4317,7 @@ var CacheService = class _CacheService {
4149
4317
  diskCircuitBreakerCooldownMs: this.opts.diskCircuitBreakerCooldownMs
4150
4318
  });
4151
4319
  this._namespace = ns;
4320
+ this.prefixLen = ns ? ns.length + 1 : 0;
4152
4321
  this._redisDisabled = this.opts.disableRedis || !this.opts.redisClient && !this.opts.redisHost && !this.opts.redisClusterNodes?.length && !this.opts.redisSentinel;
4153
4322
  this.watchdog = new TierLatencyWatchdog({
4154
4323
  enabled: options.diskLatencyWatchdog ?? true,
@@ -4258,6 +4427,9 @@ var CacheService = class _CacheService {
4258
4427
  this.backplaneStreamKey = options.backplaneStreamKey ?? `tricache:stream:{${ns || "default"}}`;
4259
4428
  this.initBackplane();
4260
4429
  const startupPromises = [];
4430
+ if (this.opts.compression === "zstd") {
4431
+ startupPromises.push(initZstd().then(() => void 0));
4432
+ }
4261
4433
  if (this.opts.remoteSnapshot) {
4262
4434
  startupPromises.push(this.loadRemoteSnapshot().then(() => void 0));
4263
4435
  }
@@ -4763,6 +4935,50 @@ var CacheService = class _CacheService {
4763
4935
  const tag = key;
4764
4936
  const ver = typeof tagVersion === "number" ? tagVersion : (this.tagVersions.get(tag)?.version ?? 0) + 1;
4765
4937
  this._setLocalTagVersion(tag, ver, performance.now());
4938
+ } else if (op === "tag_pattern_incr") {
4939
+ const pattern = key;
4940
+ const now = performance.now();
4941
+ for (const [tag, info] of this.tagVersions) {
4942
+ if (matchesTagPattern(pattern, tag)) {
4943
+ this._setLocalTagVersion(tag, info.version + 1, now);
4944
+ }
4945
+ }
4946
+ this.l1.scan((k, entry) => {
4947
+ if (entry.tagVersions) {
4948
+ for (const tag of Object.keys(entry.tagVersions)) {
4949
+ if (matchesTagPattern(pattern, tag)) {
4950
+ this.l1.delete(k);
4951
+ this._bumpKeyMutation(k);
4952
+ break;
4953
+ }
4954
+ }
4955
+ }
4956
+ }, 0);
4957
+ } else if (op === "tag_pattern_del") {
4958
+ const pattern = key;
4959
+ const matchedTagKeys = [];
4960
+ const prefix = this.nk("_tag_:");
4961
+ for (const [tagKey, members] of this.tagIndex) {
4962
+ const tag = tagKey.startsWith(prefix) ? tagKey.slice(prefix.length) : tagKey;
4963
+ if (matchesTagPattern(pattern, tag)) {
4964
+ matchedTagKeys.push(tagKey);
4965
+ for (const k of members) {
4966
+ this.l1.delete(k);
4967
+ this._bumpKeyMutation(k);
4968
+ this._pendingDiskDeletes.add(k);
4969
+ setImmediate(() => {
4970
+ try {
4971
+ if (!this._diskDisabled) this.disk.delete(k);
4972
+ } finally {
4973
+ this._pendingDiskDeletes.delete(k);
4974
+ }
4975
+ });
4976
+ }
4977
+ }
4978
+ }
4979
+ for (const tagKey of matchedTagKeys) {
4980
+ this.tagIndex.delete(tagKey);
4981
+ }
4766
4982
  }
4767
4983
  this.logger.debug("Backplane: invalidation applied", { op, key: key.slice(0, 60) });
4768
4984
  }
@@ -4770,7 +4986,7 @@ var CacheService = class _CacheService {
4770
4986
  _handleBackplaneMessage(message) {
4771
4987
  try {
4772
4988
  const msg = JSON.parse(message);
4773
- if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr") {
4989
+ if (!msg || typeof msg !== "object" || Array.isArray(msg) || typeof msg.src !== "string" || typeof msg.key !== "string" || msg.op !== "del" && msg.op !== "del-glob" && msg.op !== "tag_incr" && msg.op !== "tag_pattern_incr" && msg.op !== "tag_pattern_del") {
4774
4990
  this.logger.warn("Backplane: rejected invalid pubsub message format", {
4775
4991
  raw: typeof message === "string" ? message.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(message)
4776
4992
  });
@@ -4957,12 +5173,12 @@ var CacheService = class _CacheService {
4957
5173
  * Offloads to worker thread if pool is active and payload exceeds threshold.
4958
5174
  */
4959
5175
  async _serializeAndEncrypt(serialized) {
4960
- const isCompressed2 = this.opts.compression && this.opts.compression !== "none" && serialized.length > this.opts.compressionThresholdBytes;
4961
- if (this._workerPool && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
5176
+ const isCompressed2 = (this.opts.customCompressor || this.opts.compression && this.opts.compression !== "none") && serialized.length > this.opts.compressionThresholdBytes;
5177
+ if (this._workerPool && !this.opts.customCompressor && (this.enc.isEnabled || isCompressed2) && serialized.length > this.opts.workerThresholdBytes) {
4962
5178
  return this._workerPool.encrypt(serialized);
4963
5179
  }
4964
5180
  if (isCompressed2) {
4965
- const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression);
5181
+ const compressed = compressBuffer(Buffer.from(serialized, "utf8"), this.opts.compression, this.opts.customCompressor);
4966
5182
  if (this.enc.isEnabled) {
4967
5183
  const encrypted = this.enc.encryptBuffer(compressed);
4968
5184
  return PREFIX_ENC_COMPRESSED + encrypted.toString("base64");
@@ -4977,16 +5193,16 @@ var CacheService = class _CacheService {
4977
5193
  */
4978
5194
  async _decryptAndDeserialize(raw) {
4979
5195
  let plain;
4980
- if (this._workerPool && raw.length > this.opts.workerThresholdBytes) {
5196
+ if (this._workerPool && !this.opts.customCompressor && raw.length > this.opts.workerThresholdBytes) {
4981
5197
  plain = await this._workerPool.decrypt(raw);
4982
5198
  } else if (raw.startsWith(PREFIX_ENC_COMPRESSED)) {
4983
5199
  const encBuf = Buffer.from(raw.slice(PREFIX_ENC_COMPRESSED.length), "base64");
4984
5200
  const decBuf = this.enc.decryptBuffer(encBuf);
4985
- const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5201
+ const decompressed = decompressBuffer(decBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
4986
5202
  plain = decompressed.toString("utf8");
4987
5203
  } else if (raw.startsWith(PREFIX_COMPRESSED)) {
4988
5204
  const cmpBuf = Buffer.from(raw.slice(PREFIX_COMPRESSED.length), "base64");
4989
- const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli");
5205
+ const decompressed = decompressBuffer(cmpBuf, this.opts.compression !== "none" ? this.opts.compression : "brotli", this.opts.customCompressor);
4990
5206
  plain = decompressed.toString("utf8");
4991
5207
  } else if (raw.startsWith("enc:v1:") || this.enc.isEnabled) {
4992
5208
  plain = this.enc.decrypt(raw);
@@ -5382,7 +5598,7 @@ var CacheService = class _CacheService {
5382
5598
  const optRefreshAhead = opts.refreshAhead;
5383
5599
  const optXfetchBeta = opts.xfetchBeta;
5384
5600
  const optNotFoundTtl = opts.notFoundTtl;
5385
- const optTags = opts.tags;
5601
+ const optTags = opts.tags ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
5386
5602
  const l1Hit = this.l1.get(k);
5387
5603
  if (l1Hit !== null) {
5388
5604
  let isGenerationalStale = false;
@@ -5840,15 +6056,16 @@ var CacheService = class _CacheService {
5840
6056
  this._pendingDiskDeletes.delete(k);
5841
6057
  this.counters.sets++;
5842
6058
  let activeTagVersions;
5843
- if (opts?.tags?.length) {
6059
+ const tagsToRegister = opts?.tags?.length ? this.opts.hierarchicalTags ? expandHierarchicalTags(opts.tags, this.opts.tagHierarchyDelimiter) : opts.tags : void 0;
6060
+ if (tagsToRegister?.length) {
5844
6061
  if (this.opts.tagStrategy === "generational") {
5845
- const vers = await Promise.all(opts.tags.map((tag) => this._getTagVersion(tag)));
6062
+ const vers = await Promise.all(tagsToRegister.map((tag) => this._getTagVersion(tag)));
5846
6063
  activeTagVersions = {};
5847
- for (let i = 0; i < opts.tags.length; i++) {
5848
- activeTagVersions[opts.tags[i]] = vers[i];
6064
+ for (let i = 0; i < tagsToRegister.length; i++) {
6065
+ activeTagVersions[tagsToRegister[i]] = vers[i];
5849
6066
  }
5850
6067
  } else {
5851
- await this._registerTags(k, opts.tags, ttlSeconds);
6068
+ await this._registerTags(k, tagsToRegister, ttlSeconds);
5852
6069
  }
5853
6070
  }
5854
6071
  this.l1.set(k, data, ttlMs, p, void 0, void 0, activeTagVersions);
@@ -6463,16 +6680,23 @@ var CacheService = class _CacheService {
6463
6680
  }
6464
6681
  }
6465
6682
  }
6466
- if (missKeys.length > 0) {
6683
+ if (missKeys.length > 0 && fetchFn) {
6467
6684
  this.counters.fetches++;
6468
6685
  const fetched = await fetchFn(missKeys);
6686
+ const isMap = fetched instanceof Map;
6469
6687
  const setPromises = [];
6470
6688
  for (let j = 0; j < missKeys.length; j++) {
6471
- const v = fetched[missKeys[j]];
6689
+ const k = missKeys[j];
6690
+ const v = isMap ? fetched.get(k) : fetched[k];
6472
6691
  result[missIndexes[j]] = v;
6473
- if (v !== void 0) {
6474
- const resolvedTtl = typeof ttl === "function" ? ttl(missKeys[j]) : ttl;
6475
- setPromises.push(this.set(missKeys[j], v, resolvedTtl, priority));
6692
+ if (v !== void 0 && v !== null) {
6693
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6694
+ setPromises.push(this.set(k, v, resolvedTtl, priority));
6695
+ } else if (v == null && this.opts.notFoundTtl > 0) {
6696
+ setPromises.push(this.set(k, null, this.opts.notFoundTtl, priority));
6697
+ } else if (v === null) {
6698
+ const resolvedTtl = typeof ttl === "function" ? ttl(k) : ttl;
6699
+ setPromises.push(this.set(k, null, resolvedTtl, priority));
6476
6700
  }
6477
6701
  }
6478
6702
  if (setPromises.length > 0) {
@@ -6615,21 +6839,109 @@ var CacheService = class _CacheService {
6615
6839
  }
6616
6840
  }
6617
6841
  /**
6618
- * Invalidate all keys associated with a tag.
6619
- * Deletes from L1, disk, and Redis (both the keyed values and the tag set).
6842
+ * Discovers all concrete tag names in the system that match `tag` either via
6843
+ * glob wildcards ('*' or '?') or parent-child hierarchy cascading.
6844
+ * Scans local in-memory indices (tagIndex, tagVersions, L1 entries) and Redis (if connected).
6845
+ */
6846
+ async _resolveMatchingTags(tag, shouldCascade) {
6847
+ const isPattern = isWildcardTag(tag);
6848
+ const delim = this.opts.tagHierarchyDelimiter;
6849
+ const matched = /* @__PURE__ */ new Set();
6850
+ const tagMatches = (t) => {
6851
+ if (t === tag) return true;
6852
+ if (isPattern && matchesTagPattern(tag, t)) return true;
6853
+ if (shouldCascade && isChildTag(tag, t, delim)) return true;
6854
+ return false;
6855
+ };
6856
+ if (shouldCascade && !isPattern) {
6857
+ matched.add(tag);
6858
+ }
6859
+ const tagPrefix = this.nk("_tag_:");
6860
+ for (const tagKey of this.tagIndex.keys()) {
6861
+ const t = tagKey.startsWith(tagPrefix) ? tagKey.slice(tagPrefix.length) : tagKey;
6862
+ if (tagMatches(t)) matched.add(t);
6863
+ }
6864
+ for (const t of this.tagVersions.keys()) {
6865
+ if (tagMatches(t)) matched.add(t);
6866
+ }
6867
+ this.l1.scan((_k, entry) => {
6868
+ if (entry.tagVersions) {
6869
+ for (const t of Object.keys(entry.tagVersions)) {
6870
+ if (tagMatches(t)) matched.add(t);
6871
+ }
6872
+ }
6873
+ }, 0);
6874
+ if (!this._redisDisabled) {
6875
+ try {
6876
+ const client = await this.getRedis();
6877
+ if (this.opts.tagStrategy === "generational") {
6878
+ const redisPattern = isPattern ? this.nk(`tag_ver:${tag}`) : this.nk(`tag_ver:${tag}${delim}*`);
6879
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6880
+ const pfx = this.nk("tag_ver:");
6881
+ for (const sk of scannedKeys) {
6882
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6883
+ if (tagMatches(t)) matched.add(t);
6884
+ }
6885
+ } else {
6886
+ const redisPattern = isPattern ? this.nk(`_tag_:${tag}`) : this.nk(`_tag_:${tag}${delim}*`);
6887
+ const scannedKeys = await this._scanKeys(client, redisPattern);
6888
+ const pfx = this.nk("_tag_:");
6889
+ for (const sk of scannedKeys) {
6890
+ const t = sk.startsWith(pfx) ? sk.slice(pfx.length) : sk;
6891
+ if (tagMatches(t)) matched.add(t);
6892
+ }
6893
+ }
6894
+ } catch (err) {
6895
+ this.logger.debug("_resolveMatchingTags: Redis scan failed", { tag, error: err.message });
6896
+ }
6897
+ }
6898
+ return matched;
6899
+ }
6900
+ /**
6901
+ * Invalidate all keys associated with a tag, wildcard glob pattern, or hierarchical namespace.
6902
+ * Deletes from L1, disk, and Redis (both the keyed values and the tag metadata).
6903
+ *
6904
+ * @param tag Tag name or wildcard glob pattern (e.g. `'catalog'`, `'org:123:*'`, `'*:comments'`).
6905
+ * @param opts Optional invalidation options, including `{ cascade: true }` to invalidate child namespaces.
6620
6906
  *
6621
6907
  * @example
6622
6908
  * await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
6623
6909
  * await cache.invalidateTag('catalog'); // clears product:1 and any other tagged entries
6910
+ *
6911
+ * @example
6912
+ * // Wildcard pattern invalidation
6913
+ * await cache.invalidateTag('org:123:*');
6914
+ *
6915
+ * @example
6916
+ * // Hierarchical tag cascading (clears 'org:123' and all child tags like 'org:123:dept:456')
6917
+ * await cache.invalidateTag('org:123', { cascade: true });
6624
6918
  */
6625
- async invalidateTag(tag) {
6919
+ async invalidateTag(tag, opts) {
6626
6920
  this._assertActive("invalidateTag");
6627
6921
  const span = this._startSpan("tricache.invalidate_tag");
6628
6922
  if (this.opts.tracer) {
6629
6923
  span.setAttribute("cache.tag", tag);
6630
6924
  span.setAttribute("cache.tag_strategy", this.opts.tagStrategy);
6925
+ if (opts?.cascade) span.setAttribute("cache.cascade", true);
6631
6926
  }
6632
6927
  try {
6928
+ const isPattern = isWildcardTag(tag);
6929
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
6930
+ if (isPattern || shouldCascade) {
6931
+ const matchedTags = await this._resolveMatchingTags(tag, shouldCascade);
6932
+ const delim = this.opts.tagHierarchyDelimiter;
6933
+ const broadcastPattern = isPattern ? tag : `${tag}${delim}*`;
6934
+ if (matchedTags.size > 0) {
6935
+ await this.invalidateTags(Array.from(matchedTags));
6936
+ }
6937
+ const op = this.opts.tagStrategy === "generational" ? "tag_pattern_incr" : "tag_pattern_del";
6938
+ if (this.opts.awaitInvalidationBackplane) {
6939
+ await this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6940
+ } else {
6941
+ void this.publishInvalidation(op, broadcastPattern, void 0, false, true);
6942
+ }
6943
+ return;
6944
+ }
6633
6945
  if (this.opts.tagStrategy === "generational") {
6634
6946
  let newVer = 1;
6635
6947
  if (!this._redisDisabled) {
@@ -6692,21 +7004,35 @@ var CacheService = class _CacheService {
6692
7004
  }
6693
7005
  /**
6694
7006
  * Invalidate all keys associated with any of the given tags in a single operation.
6695
- * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
6696
- * reducing latency when invalidating several related tags together.
7007
+ * Supports discrete tags, wildcard glob patterns, and hierarchical cascading.
7008
+ * Combines multiple tag invalidations into Redis pipeline round-trips.
6697
7009
  *
6698
- * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
6699
- * synchronously before the Redis round-trip.
7010
+ * @param tags Array of tag names or wildcard patterns (e.g. `['case:acme', 'org:*']`).
7011
+ * @param opts Optional invalidation options, including `{ cascade: true }`.
6700
7012
  *
6701
7013
  * @example
6702
- * // Instead of three serial round-trips:
6703
- * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
7014
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:*']);
6704
7015
  */
6705
- async invalidateTags(tags) {
7016
+ async invalidateTags(tags, opts) {
6706
7017
  this._assertActive("invalidateTags");
6707
7018
  if (tags.length === 0) return;
7019
+ const hasWildcards = tags.some((t) => isWildcardTag(t));
7020
+ const shouldCascade = Boolean(opts?.cascade || this.opts.hierarchicalTags);
7021
+ if (hasWildcards || shouldCascade) {
7022
+ const allResolvedTags = /* @__PURE__ */ new Set();
7023
+ for (const t of tags) {
7024
+ if (isWildcardTag(t) || shouldCascade) {
7025
+ const resolved = await this._resolveMatchingTags(t, shouldCascade);
7026
+ for (const rt of resolved) allResolvedTags.add(rt);
7027
+ } else {
7028
+ allResolvedTags.add(t);
7029
+ }
7030
+ }
7031
+ if (allResolvedTags.size === 0) return;
7032
+ tags = Array.from(allResolvedTags);
7033
+ }
6708
7034
  if (tags.length === 1) {
6709
- await this.invalidateTag(tags[0]);
7035
+ await this.invalidateTag(tags[0], opts);
6710
7036
  return;
6711
7037
  }
6712
7038
  if (this.opts.tagStrategy === "generational") {
@@ -1,5 +1,5 @@
1
- import { C as CacheService } from '../cache-service-DVvroyqA.js';
2
- import { C as CacheOptions, h as ILogger } from '../types-B_QkVwJ7.js';
1
+ import { C as CacheService } from '../cache-service-pJ-nFcVj.js';
2
+ import { C as CacheOptions, i as ILogger } from '../types-5HXqBfAf.js';
3
3
  import 'crypto';
4
4
 
5
5
  /**
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  CacheService
3
- } from "../chunk-PL5J3ZNT.js";
3
+ } from "../chunk-7SZSQS55.js";
4
4
  import {
5
5
  consoleLogger
6
- } from "../chunk-LJ5QJB5O.js";
7
- import "../chunk-XZL45ABR.js";
6
+ } from "../chunk-UBWLPKTI.js";
7
+ import "../chunk-2AJKEQMZ.js";
8
8
 
9
9
  // src/next/cache-handler.ts
10
10
  var PRESET_CACHE_LIFE_PROFILES = {
@@ -1,5 +1,5 @@
1
- import { C as CacheService } from '../cache-service-DVvroyqA.js';
2
- import { W as WrapOptions } from '../types-B_QkVwJ7.js';
1
+ import { C as CacheService } from '../cache-service-pJ-nFcVj.js';
2
+ import { W as WrapOptions } from '../types-5HXqBfAf.js';
3
3
  import 'crypto';
4
4
 
5
5
  /**