layercache 1.0.1 → 1.1.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/cli.cjs ADDED
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/cli.ts
32
+ var cli_exports = {};
33
+ __export(cli_exports, {
34
+ main: () => main
35
+ });
36
+ module.exports = __toCommonJS(cli_exports);
37
+ var import_ioredis = __toESM(require("ioredis"), 1);
38
+
39
+ // src/invalidation/PatternMatcher.ts
40
+ var PatternMatcher = class _PatternMatcher {
41
+ /**
42
+ * Tests whether a glob-style pattern matches a value.
43
+ * Supports `*` (any sequence of characters) and `?` (any single character).
44
+ * Uses a linear-time algorithm to avoid ReDoS vulnerabilities.
45
+ */
46
+ static matches(pattern, value) {
47
+ return _PatternMatcher.matchLinear(pattern, value);
48
+ }
49
+ /**
50
+ * Linear-time glob matching using dynamic programming.
51
+ * Avoids catastrophic backtracking that RegExp-based glob matching can cause.
52
+ */
53
+ static matchLinear(pattern, value) {
54
+ const m = pattern.length;
55
+ const n = value.length;
56
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(false));
57
+ dp[0][0] = true;
58
+ for (let i = 1; i <= m; i++) {
59
+ if (pattern[i - 1] === "*") {
60
+ dp[i][0] = dp[i - 1]?.[0];
61
+ }
62
+ }
63
+ for (let i = 1; i <= m; i++) {
64
+ for (let j = 1; j <= n; j++) {
65
+ const pc = pattern[i - 1];
66
+ if (pc === "*") {
67
+ dp[i][j] = dp[i - 1]?.[j] || dp[i]?.[j - 1];
68
+ } else if (pc === "?" || pc === value[j - 1]) {
69
+ dp[i][j] = dp[i - 1]?.[j - 1];
70
+ }
71
+ }
72
+ }
73
+ return dp[m]?.[n];
74
+ }
75
+ };
76
+
77
+ // src/invalidation/RedisTagIndex.ts
78
+ var RedisTagIndex = class {
79
+ client;
80
+ prefix;
81
+ scanCount;
82
+ constructor(options) {
83
+ this.client = options.client;
84
+ this.prefix = options.prefix ?? "layercache:tag-index";
85
+ this.scanCount = options.scanCount ?? 100;
86
+ }
87
+ async touch(key) {
88
+ await this.client.sadd(this.knownKeysKey(), key);
89
+ }
90
+ async track(key, tags) {
91
+ const keyTagsKey = this.keyTagsKey(key);
92
+ const existingTags = await this.client.smembers(keyTagsKey);
93
+ const pipeline = this.client.pipeline();
94
+ pipeline.sadd(this.knownKeysKey(), key);
95
+ for (const tag of existingTags) {
96
+ pipeline.srem(this.tagKeysKey(tag), key);
97
+ }
98
+ pipeline.del(keyTagsKey);
99
+ if (tags.length > 0) {
100
+ pipeline.sadd(keyTagsKey, ...tags);
101
+ for (const tag of new Set(tags)) {
102
+ pipeline.sadd(this.tagKeysKey(tag), key);
103
+ }
104
+ }
105
+ await pipeline.exec();
106
+ }
107
+ async remove(key) {
108
+ const keyTagsKey = this.keyTagsKey(key);
109
+ const existingTags = await this.client.smembers(keyTagsKey);
110
+ const pipeline = this.client.pipeline();
111
+ pipeline.srem(this.knownKeysKey(), key);
112
+ pipeline.del(keyTagsKey);
113
+ for (const tag of existingTags) {
114
+ pipeline.srem(this.tagKeysKey(tag), key);
115
+ }
116
+ await pipeline.exec();
117
+ }
118
+ async keysForTag(tag) {
119
+ return this.client.smembers(this.tagKeysKey(tag));
120
+ }
121
+ async matchPattern(pattern) {
122
+ const matches = [];
123
+ let cursor = "0";
124
+ do {
125
+ const [nextCursor, keys] = await this.client.sscan(
126
+ this.knownKeysKey(),
127
+ cursor,
128
+ "MATCH",
129
+ pattern,
130
+ "COUNT",
131
+ this.scanCount
132
+ );
133
+ cursor = nextCursor;
134
+ matches.push(...keys.filter((key) => PatternMatcher.matches(pattern, key)));
135
+ } while (cursor !== "0");
136
+ return matches;
137
+ }
138
+ async clear() {
139
+ const indexKeys = await this.scanIndexKeys();
140
+ if (indexKeys.length === 0) {
141
+ return;
142
+ }
143
+ await this.client.del(...indexKeys);
144
+ }
145
+ async scanIndexKeys() {
146
+ const matches = [];
147
+ let cursor = "0";
148
+ const pattern = `${this.prefix}:*`;
149
+ do {
150
+ const [nextCursor, keys] = await this.client.scan(cursor, "MATCH", pattern, "COUNT", this.scanCount);
151
+ cursor = nextCursor;
152
+ matches.push(...keys);
153
+ } while (cursor !== "0");
154
+ return matches;
155
+ }
156
+ knownKeysKey() {
157
+ return `${this.prefix}:keys`;
158
+ }
159
+ keyTagsKey(key) {
160
+ return `${this.prefix}:key:${encodeURIComponent(key)}`;
161
+ }
162
+ tagKeysKey(tag) {
163
+ return `${this.prefix}:tag:${encodeURIComponent(tag)}`;
164
+ }
165
+ };
166
+
167
+ // src/cli.ts
168
+ var CONNECT_TIMEOUT_MS = 5e3;
169
+ async function main(argv = process.argv.slice(2)) {
170
+ const args = parseArgs(argv);
171
+ if (!args.command || !args.redisUrl) {
172
+ printUsage();
173
+ process.exitCode = 1;
174
+ return;
175
+ }
176
+ const redisUrl = validateRedisUrl(args.redisUrl);
177
+ if (!redisUrl) {
178
+ process.stderr.write(
179
+ `Error: invalid Redis URL "${args.redisUrl}". Expected format: redis://[user:password@]host[:port][/db]
180
+ `
181
+ );
182
+ process.exitCode = 1;
183
+ return;
184
+ }
185
+ const redis = new import_ioredis.default(redisUrl, {
186
+ connectTimeout: CONNECT_TIMEOUT_MS,
187
+ lazyConnect: true,
188
+ enableReadyCheck: false
189
+ });
190
+ try {
191
+ await redis.connect().catch((error) => {
192
+ const message = error instanceof Error ? error.message : String(error);
193
+ throw new Error(`Failed to connect to Redis at "${redisUrl}": ${message}`);
194
+ });
195
+ if (args.command === "stats") {
196
+ const keys = await scanKeys(redis, args.pattern ?? "*");
197
+ process.stdout.write(`${JSON.stringify({ totalKeys: keys.length, pattern: args.pattern ?? "*" }, null, 2)}
198
+ `);
199
+ return;
200
+ }
201
+ if (args.command === "keys") {
202
+ const keys = await scanKeys(redis, args.pattern ?? "*");
203
+ if (keys.length > 0) {
204
+ process.stdout.write(`${keys.join("\n")}
205
+ `);
206
+ }
207
+ return;
208
+ }
209
+ if (args.command === "invalidate") {
210
+ if (args.tag) {
211
+ const tagIndex = new RedisTagIndex({ client: redis, prefix: args.tagIndexPrefix ?? "layercache:tag-index" });
212
+ const keys2 = await tagIndex.keysForTag(args.tag);
213
+ if (keys2.length > 0) {
214
+ await redis.del(...keys2);
215
+ }
216
+ process.stdout.write(`${JSON.stringify({ deletedKeys: keys2.length, tag: args.tag }, null, 2)}
217
+ `);
218
+ return;
219
+ }
220
+ const keys = await scanKeys(redis, args.pattern ?? "*");
221
+ if (keys.length > 0) {
222
+ await redis.del(...keys);
223
+ }
224
+ process.stdout.write(`${JSON.stringify({ deletedKeys: keys.length, pattern: args.pattern ?? "*" }, null, 2)}
225
+ `);
226
+ return;
227
+ }
228
+ printUsage();
229
+ process.exitCode = 1;
230
+ } catch (error) {
231
+ const message = error instanceof Error ? error.message : String(error);
232
+ process.stderr.write(`Error: ${message}
233
+ `);
234
+ process.exitCode = 1;
235
+ } finally {
236
+ redis.disconnect();
237
+ }
238
+ }
239
+ function validateRedisUrl(url) {
240
+ try {
241
+ const parsed = new URL(url);
242
+ if (parsed.protocol !== "redis:" && parsed.protocol !== "rediss:") {
243
+ return null;
244
+ }
245
+ return url;
246
+ } catch {
247
+ if (/^[A-Za-z0-9._-]+(:\d+)?$/.test(url)) {
248
+ return url;
249
+ }
250
+ return null;
251
+ }
252
+ }
253
+ function parseArgs(argv) {
254
+ const [command, ...rest] = argv;
255
+ const parsed = { command };
256
+ for (let index = 0; index < rest.length; index += 1) {
257
+ const token = rest[index];
258
+ const value = rest[index + 1];
259
+ if (token === "--redis") {
260
+ parsed.redisUrl = value;
261
+ index += 1;
262
+ } else if (token === "--pattern") {
263
+ parsed.pattern = value;
264
+ index += 1;
265
+ } else if (token === "--tag") {
266
+ parsed.tag = value;
267
+ index += 1;
268
+ } else if (token === "--tag-index-prefix") {
269
+ parsed.tagIndexPrefix = value;
270
+ index += 1;
271
+ }
272
+ }
273
+ return parsed;
274
+ }
275
+ async function scanKeys(redis, pattern) {
276
+ const keys = [];
277
+ let cursor = "0";
278
+ do {
279
+ const [nextCursor, batch] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
280
+ cursor = nextCursor;
281
+ keys.push(...batch);
282
+ } while (cursor !== "0");
283
+ return keys;
284
+ }
285
+ function printUsage() {
286
+ process.stdout.write(
287
+ "Usage:\n layercache stats --redis <url> [--pattern <glob>]\n layercache keys --redis <url> [--pattern <glob>]\n layercache invalidate --redis <url> [--pattern <glob> | --tag <tag>] [--tag-index-prefix <prefix>]\n\nOptions:\n --redis <url> Redis connection URL (e.g. redis://localhost:6379)\n --pattern <glob> Glob pattern to filter keys (default: *)\n --tag <tag> Invalidate by tag name\n --tag-index-prefix <prefix> Redis key prefix for tag index (default: layercache:tag-index)\n"
288
+ );
289
+ }
290
+ if (process.argv[1]?.includes("cli.")) {
291
+ void main();
292
+ }
293
+ // Annotate the CommonJS export names for ESM import in node:
294
+ 0 && (module.exports = {
295
+ main
296
+ });
package/dist/cli.d.cts ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ declare function main(argv?: string[]): Promise<void>;
3
+
4
+ export { main };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ declare function main(argv?: string[]): Promise<void>;
3
+
4
+ export { main };
package/dist/cli.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ RedisTagIndex
4
+ } from "./chunk-QUB5VZFZ.js";
5
+
6
+ // src/cli.ts
7
+ import Redis from "ioredis";
8
+ var CONNECT_TIMEOUT_MS = 5e3;
9
+ async function main(argv = process.argv.slice(2)) {
10
+ const args = parseArgs(argv);
11
+ if (!args.command || !args.redisUrl) {
12
+ printUsage();
13
+ process.exitCode = 1;
14
+ return;
15
+ }
16
+ const redisUrl = validateRedisUrl(args.redisUrl);
17
+ if (!redisUrl) {
18
+ process.stderr.write(
19
+ `Error: invalid Redis URL "${args.redisUrl}". Expected format: redis://[user:password@]host[:port][/db]
20
+ `
21
+ );
22
+ process.exitCode = 1;
23
+ return;
24
+ }
25
+ const redis = new Redis(redisUrl, {
26
+ connectTimeout: CONNECT_TIMEOUT_MS,
27
+ lazyConnect: true,
28
+ enableReadyCheck: false
29
+ });
30
+ try {
31
+ await redis.connect().catch((error) => {
32
+ const message = error instanceof Error ? error.message : String(error);
33
+ throw new Error(`Failed to connect to Redis at "${redisUrl}": ${message}`);
34
+ });
35
+ if (args.command === "stats") {
36
+ const keys = await scanKeys(redis, args.pattern ?? "*");
37
+ process.stdout.write(`${JSON.stringify({ totalKeys: keys.length, pattern: args.pattern ?? "*" }, null, 2)}
38
+ `);
39
+ return;
40
+ }
41
+ if (args.command === "keys") {
42
+ const keys = await scanKeys(redis, args.pattern ?? "*");
43
+ if (keys.length > 0) {
44
+ process.stdout.write(`${keys.join("\n")}
45
+ `);
46
+ }
47
+ return;
48
+ }
49
+ if (args.command === "invalidate") {
50
+ if (args.tag) {
51
+ const tagIndex = new RedisTagIndex({ client: redis, prefix: args.tagIndexPrefix ?? "layercache:tag-index" });
52
+ const keys2 = await tagIndex.keysForTag(args.tag);
53
+ if (keys2.length > 0) {
54
+ await redis.del(...keys2);
55
+ }
56
+ process.stdout.write(`${JSON.stringify({ deletedKeys: keys2.length, tag: args.tag }, null, 2)}
57
+ `);
58
+ return;
59
+ }
60
+ const keys = await scanKeys(redis, args.pattern ?? "*");
61
+ if (keys.length > 0) {
62
+ await redis.del(...keys);
63
+ }
64
+ process.stdout.write(`${JSON.stringify({ deletedKeys: keys.length, pattern: args.pattern ?? "*" }, null, 2)}
65
+ `);
66
+ return;
67
+ }
68
+ printUsage();
69
+ process.exitCode = 1;
70
+ } catch (error) {
71
+ const message = error instanceof Error ? error.message : String(error);
72
+ process.stderr.write(`Error: ${message}
73
+ `);
74
+ process.exitCode = 1;
75
+ } finally {
76
+ redis.disconnect();
77
+ }
78
+ }
79
+ function validateRedisUrl(url) {
80
+ try {
81
+ const parsed = new URL(url);
82
+ if (parsed.protocol !== "redis:" && parsed.protocol !== "rediss:") {
83
+ return null;
84
+ }
85
+ return url;
86
+ } catch {
87
+ if (/^[A-Za-z0-9._-]+(:\d+)?$/.test(url)) {
88
+ return url;
89
+ }
90
+ return null;
91
+ }
92
+ }
93
+ function parseArgs(argv) {
94
+ const [command, ...rest] = argv;
95
+ const parsed = { command };
96
+ for (let index = 0; index < rest.length; index += 1) {
97
+ const token = rest[index];
98
+ const value = rest[index + 1];
99
+ if (token === "--redis") {
100
+ parsed.redisUrl = value;
101
+ index += 1;
102
+ } else if (token === "--pattern") {
103
+ parsed.pattern = value;
104
+ index += 1;
105
+ } else if (token === "--tag") {
106
+ parsed.tag = value;
107
+ index += 1;
108
+ } else if (token === "--tag-index-prefix") {
109
+ parsed.tagIndexPrefix = value;
110
+ index += 1;
111
+ }
112
+ }
113
+ return parsed;
114
+ }
115
+ async function scanKeys(redis, pattern) {
116
+ const keys = [];
117
+ let cursor = "0";
118
+ do {
119
+ const [nextCursor, batch] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
120
+ cursor = nextCursor;
121
+ keys.push(...batch);
122
+ } while (cursor !== "0");
123
+ return keys;
124
+ }
125
+ function printUsage() {
126
+ process.stdout.write(
127
+ "Usage:\n layercache stats --redis <url> [--pattern <glob>]\n layercache keys --redis <url> [--pattern <glob>]\n layercache invalidate --redis <url> [--pattern <glob> | --tag <tag>] [--tag-index-prefix <prefix>]\n\nOptions:\n --redis <url> Redis connection URL (e.g. redis://localhost:6379)\n --pattern <glob> Glob pattern to filter keys (default: *)\n --tag <tag> Invalidate by tag name\n --tag-index-prefix <prefix> Redis key prefix for tag index (default: layercache:tag-index)\n"
128
+ );
129
+ }
130
+ if (process.argv[1]?.includes("cli.")) {
131
+ void main();
132
+ }
133
+ export {
134
+ main
135
+ };