@appweaver/redis 0.0.0-stage → 2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Luka Matosevic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://appweaver.co" target="_blank"><img src="https://raw.githubusercontent.com/lmatosevic/appweaver/refs/heads/main/resources/appweaver-logo.svg" width="460" alt="Appweaver Logo" /></a>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <p align="center">
6
+ The ioredis driver of Appweaver, the AI-first <a href="https://nodejs.org" target="_blank">Node.js</a> framework for backends built with agents.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@appweaver/redis" target="_blank"><img src="https://img.shields.io/npm/v/@appweaver/redis.svg" alt="NPM Version" /></a>
11
+ <a href="https://github.com/lmatosevic/appweaver/blob/main/LICENSE" target="_blank"><img src="https://img.shields.io/npm/l/@appweaver/redis.svg" alt="Package License" /></a>
12
+ <a href="https://www.npmjs.com/package/@appweaver/redis" target="_blank"><img src="https://img.shields.io/npm/dw/@appweaver/redis.svg" alt="NPM Downloads" /></a>
13
+ </p>
14
+
15
+ ## Description
16
+
17
+ `@appweaver/redis` is the Redis memory of [Appweaver](https://github.com/lmatosevic/appweaver), a module enabled by
18
+ installing it, which provides the `redis` `Memory` provider. With `auto`, the default of the `memory.provider` config key,
19
+ it is selected whenever the module is installed.
20
+
21
+ ## Installation
22
+
23
+ ```sh
24
+ npm install @appweaver/redis
25
+ ```
26
+
27
+ or `weaver module add redis` in a project created with `@appweaver/create`.
28
+
29
+ The connection URL is `memory.redis.url` (`MEMORY_REDIS_URL`). The cache, the rate limit (`rateLimit.store` `auto`) and the BullMQ queue use its connection.
30
+
31
+ ## Documentation
32
+
33
+ - [Appweaver README](https://github.com/lmatosevic/appweaver#readme) – getting started, configuration, and the overview of every package
34
+ - [Agent skill](https://github.com/lmatosevic/appweaver/blob/main/skill/SKILL.md) – the complete framework reference shipped to every scaffolded project
35
+
36
+ ## License
37
+
38
+ Appweaver is [MIT licensed](LICENSE).
package/config.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare const redisConfig: Readonly<{
2
+ URL: string;
3
+ }>;
package/config.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.redisConfig = void 0;
4
+ const typebox_1 = require("@sinclair/typebox");
5
+ const common_1 = require("@appweaver/common");
6
+ exports.redisConfig = (0, common_1.defineConfig)('memory.redis', {
7
+ /** Redis connection URL. Default: `'redis://localhost:6379/0'`. */
8
+ URL: typebox_1.Type.String({ default: 'redis://localhost:6379/0' })
9
+ });
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './config';
2
+ export * from './redis-memory';
package/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./config"), exports);
18
+ __exportStar(require("./redis-memory"), exports);
package/module.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The Redis memory, also the store of the cache, the rate limit and the BullMQ queue. */
2
+ declare const _default: import("@appweaver/common").Module;
3
+ export default _default;
package/module.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const common_1 = require("@appweaver/common");
37
+ const config_1 = require("./config");
38
+ /** The Redis memory, also the store of the cache, the rate limit and the BullMQ queue. */
39
+ exports.default = (0, common_1.defineModule)({
40
+ name: '@appweaver/redis',
41
+ config: [config_1.redisConfig],
42
+ providers: [
43
+ {
44
+ contract: common_1.Memory,
45
+ name: 'redis',
46
+ load: () => Promise.resolve().then(() => __importStar(require('./redis-memory')))
47
+ }
48
+ ]
49
+ });
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@appweaver/redis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0",
4
+ "description": "Appweaver - the backend framework for AI-first development (@redis)",
5
+ "author": "Luka Matosevic",
6
+ "license": "MIT",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "default": "./index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "keywords": [
17
+ "appweaver",
18
+ "appweaver-module"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/lmatosevic/appweaver.git",
23
+ "directory": "packages/redis"
24
+ },
25
+ "maintainers": [
26
+ {
27
+ "name": "Luka Matosevic",
28
+ "email": "lukamatosevic5@gmail.com",
29
+ "web": "https://lukamatosevic.com"
30
+ }
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "engines": {
36
+ "node": ">= 24.7"
37
+ },
38
+ "appweaver": {
39
+ "module": "./module.js"
40
+ },
41
+ "dependencies": {
42
+ "@sinclair/typebox": "0.34.49",
43
+ "ioredis": "5.11.1",
44
+ "flatted": "3.4.2"
45
+ },
46
+ "peerDependencies": {
47
+ "@appweaver/common": "^2.0.0",
48
+ "@appweaver/core": "^2.0.0"
49
+ },
50
+ "devDependencies": {
51
+ "@appweaver/common": "^1.12.2",
52
+ "@appweaver/core": "^1.12.2"
53
+ }
6
54
  }
@@ -0,0 +1,27 @@
1
+ import { Redis as RedisClient, RedisOptions } from 'ioredis';
2
+ import { HealthCheckConfig, HealthCheckResult, Memory } from '@appweaver/common';
3
+ export declare class RedisMemory extends Memory<RedisOptions, RedisClient> {
4
+ constructor();
5
+ onInit(): Promise<void>;
6
+ onDestroy(): Promise<void>;
7
+ createClient(options?: RedisOptions): RedisClient;
8
+ connect(): Promise<void>;
9
+ disconnect(): Promise<void>;
10
+ get<T = any>(key: string): Promise<T | null>;
11
+ set(key: string, value: any, ttl?: number): Promise<boolean>;
12
+ has(key: string): Promise<boolean>;
13
+ delete(key: string): Promise<boolean>;
14
+ deleteMatching(pattern?: string): Promise<number>;
15
+ keys(pattern?: string): Promise<string[]>;
16
+ sizeBytes(key: string): Promise<number | null>;
17
+ lock(resource: string, lockConfig?: {
18
+ expireMs?: number;
19
+ retryCount?: number;
20
+ retryDelay?: number;
21
+ }): Promise<{
22
+ release: () => Promise<boolean>;
23
+ }>;
24
+ checkHealth(): Promise<HealthCheckResult>;
25
+ isAvailable(): boolean;
26
+ checkHealthConfig(): HealthCheckConfig;
27
+ }
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RedisMemory = void 0;
4
+ const promises_1 = require("node:timers/promises");
5
+ const ioredis_1 = require("ioredis");
6
+ const flatted_1 = require("flatted");
7
+ const common_1 = require("@appweaver/common");
8
+ const config_1 = require("./config");
9
+ class RedisMemory extends common_1.Memory {
10
+ /** @internal */
11
+ _options;
12
+ /** @internal */
13
+ _client;
14
+ constructor() {
15
+ super();
16
+ this._options = this.parseConnectionUrl(config_1.redisConfig.URL);
17
+ // Commands fail right away while disconnected instead of queueing, so the
18
+ // callers can fall back without waiting for the reconnection
19
+ this._client = this.createClient({
20
+ connectionName: 'appweaver',
21
+ lazyConnect: true,
22
+ enableOfflineQueue: false,
23
+ maxRetriesPerRequest: 1
24
+ });
25
+ }
26
+ async onInit() {
27
+ try {
28
+ await this.connect();
29
+ }
30
+ catch {
31
+ // Logged by the connection monitor, the client keeps reconnecting
32
+ }
33
+ }
34
+ async onDestroy() {
35
+ await this.disconnect();
36
+ }
37
+ createClient(options = {}) {
38
+ const client = new ioredis_1.Redis({
39
+ ...this._options,
40
+ ...options
41
+ });
42
+ this.monitorConnection(client);
43
+ return client;
44
+ }
45
+ async connect() {
46
+ await this._client.connect();
47
+ }
48
+ async disconnect() {
49
+ try {
50
+ await this._client.quit();
51
+ }
52
+ catch {
53
+ // Stops the reconnection of a connection that is down
54
+ this._client.disconnect();
55
+ }
56
+ }
57
+ async get(key) {
58
+ const value = await this._client.get(key);
59
+ return value ? (0, flatted_1.parse)(value) : null;
60
+ }
61
+ async set(key, value, ttl) {
62
+ const jsonValue = (0, flatted_1.stringify)(value);
63
+ const result = ttl
64
+ ? await this._client.set(key, jsonValue, 'PX', ttl)
65
+ : await this._client.set(key, jsonValue);
66
+ return result === 'OK';
67
+ }
68
+ async has(key) {
69
+ const result = await this._client.exists(key);
70
+ return result === 1;
71
+ }
72
+ async delete(key) {
73
+ const result = await this._client.del(key);
74
+ return result > 0;
75
+ }
76
+ async deleteMatching(pattern = '*') {
77
+ const keys = await this.keys(pattern);
78
+ if (keys.length === 0) {
79
+ return 0;
80
+ }
81
+ return this._client.del(...keys);
82
+ }
83
+ async keys(pattern = '*') {
84
+ return new Promise((resolve, reject) => {
85
+ const stream = this._client.scanStream({
86
+ match: pattern,
87
+ count: 10000
88
+ });
89
+ const keysSet = new Set();
90
+ stream.on('data', (keys) => {
91
+ stream.pause();
92
+ keys.forEach((key) => keysSet.add(key));
93
+ stream.resume();
94
+ });
95
+ stream.on('end', () => {
96
+ resolve([...keysSet]);
97
+ });
98
+ stream.on('error', reject);
99
+ });
100
+ }
101
+ async sizeBytes(key) {
102
+ return this._client.memory('USAGE', key);
103
+ }
104
+ async lock(resource, lockConfig = {}) {
105
+ const redisLock = new RedisLock(this._client, resource, lockConfig.expireMs, lockConfig.retryCount, lockConfig.retryDelay);
106
+ return await redisLock.lock();
107
+ }
108
+ async checkHealth() {
109
+ try {
110
+ const result = await this._client.ping();
111
+ return { success: result === 'PONG' };
112
+ }
113
+ catch (e) {
114
+ return { success: false, message: e.message };
115
+ }
116
+ }
117
+ isAvailable() {
118
+ return this._client.status === 'ready';
119
+ }
120
+ checkHealthConfig() {
121
+ return { name: 'redis' };
122
+ }
123
+ /** @internal */
124
+ monitorConnection(client) {
125
+ const name = client.options.connectionName ?? 'redis';
126
+ let lost = false;
127
+ // Logs only the first error of an outage, the client emits one on every
128
+ // failed reconnection attempt
129
+ client.on('error', (error) => {
130
+ if (!lost) {
131
+ lost = true;
132
+ common_1.logger.error(error, `Redis connection '${name}' is down, reconnecting in background`);
133
+ }
134
+ });
135
+ client.on('ready', () => {
136
+ if (lost) {
137
+ lost = false;
138
+ common_1.logger.info(`Redis connection '${name}' is restored`);
139
+ }
140
+ });
141
+ }
142
+ /** @internal */
143
+ parseConnectionUrl(url) {
144
+ const urlPattern = /redis:\/\/(?:(.*?)(?::(.*?))?@)?(.*?):(\d+)(?:\/(\d+))?/;
145
+ const match = url.match(urlPattern);
146
+ if (!match) {
147
+ return { host: 'localhost', port: 6379 };
148
+ }
149
+ const username = match[2] ? match[1] : undefined;
150
+ const password = match[2] || match[1];
151
+ const host = match[3] || 'localhost';
152
+ const port = parseInt(match[4], 10) || 6379;
153
+ const db = match[5] ? parseInt(match[5], 10) : undefined;
154
+ return { username, password, host, port, db };
155
+ }
156
+ }
157
+ exports.RedisMemory = RedisMemory;
158
+ class RedisLock {
159
+ client;
160
+ resource;
161
+ expireMs;
162
+ retryCount;
163
+ retryDelay;
164
+ /** @internal */
165
+ _releaseLockCommand = 'releaseLock';
166
+ constructor(client, resource, expireMs = 5000, retryCount = 10, retryDelay = 200) {
167
+ this.client = client;
168
+ this.resource = resource;
169
+ this.expireMs = expireMs;
170
+ this.retryCount = retryCount;
171
+ this.retryDelay = retryDelay;
172
+ this.initReleaseLockScript();
173
+ }
174
+ async lock() {
175
+ const resourceKey = `lock:${this.resource}`;
176
+ const lockValue = (0, common_1.uuid)();
177
+ let retries = 0;
178
+ do {
179
+ const result = await this.client.set(resourceKey, lockValue, 'PX', this.expireMs, 'NX');
180
+ if (result === 'OK') {
181
+ return {
182
+ release: async () => (await this.client[this._releaseLockCommand](resourceKey, lockValue)) > 0
183
+ };
184
+ }
185
+ else {
186
+ await (0, promises_1.setTimeout)(this.retryDelay);
187
+ retries++;
188
+ }
189
+ } while (retries < this.retryCount);
190
+ throw new common_1.LockError(common_1.ErrorCode.LockNotAcquired, 'Unable to acquire lock on requested resource');
191
+ }
192
+ initReleaseLockScript() {
193
+ if (this._releaseLockCommand in this.client) {
194
+ return;
195
+ }
196
+ this.client.defineCommand(this._releaseLockCommand, {
197
+ numberOfKeys: 1,
198
+ lua: 'if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end'
199
+ });
200
+ }
201
+ }