@sebspark/redis-live 0.0.0-stage → 0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [SEB]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # @sebspark/redis-live
2
2
 
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.
3
+ A local, in-memory map in every process, backed by Redis and eventually consistent between processes. It makes settings and data shared between processes as easy to use as a local `Map`. Built on Redis publish/subscribe and [node-redis](https://github.com/redis/node-redis) (the `redis` package).
4
+
5
+ Work with the map as if it were local: `get` and `has` read from memory, synchronously; `set` and `del` change memory at once. In the background, every write is stored in Redis and published, and every other process holding the map applies it and tells you exactly what changed, including entries that expire. Redis is the backing store, so a process that starts or reconnects loads every entry from there.
6
+
7
+ Processes see each other's writes shortly after they happen, not at the same instant. All of them end up with the same value as Redis. Full consistency between processes can never be guaranteed anyway; redis-live gives you eventual consistency without making you wait for it.
8
+
9
+ Made for hot paths that cannot afford a round trip per lookup. For example, a service saves user preferences with `set()`, while every worker that decides on incoming events whether to notify a user reads them with `get()` from memory. Because the methods mirror a Redis client's, code that reads a Redis cache can switch over with few changes.
10
+
11
+ ## The cost: memory
12
+
13
+ Every process holds every entry in memory, so lookups take micro- rather than milliseconds. That speed is paid for in memory, once per process.
14
+
15
+ For example, 700,000 users with an id, a push token, an X-Wing public key (1,216 bytes, base64) and a locale take about 2 KB each in Node, around 1.3 GB of heap per process. With four processes, that is over 5 GB.
16
+
17
+ It is worth it only where lookups must take micro- to milliseconds, faster than a round trip to Redis allows. Otherwise, use Redis directly.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @sebspark/redis-live redis
23
+ ```
24
+
25
+ ## Define a collection
26
+
27
+ Every process that uses the collection defines it the same way, so they agree on where entries live and how changes are announced.
28
+
29
+ ```ts
30
+ import { defineCollection } from '@sebspark/redis-live'
31
+
32
+ type UserPrefs = {
33
+ userId: string
34
+ channels: string[]
35
+ quietHours: { from: string; to: string } | null
36
+ }
37
+
38
+ export const userPrefs = defineCollection<UserPrefs>({
39
+ namespace: 'user_prefs',
40
+ key: 'userId', // must be a property of UserPrefs
41
+ })
42
+ ```
43
+
44
+ | Option | Meaning |
45
+ | --- | --- |
46
+ | `namespace` | Namespace of the collection, like a table name. |
47
+ | `key` | Property of an entry that holds its id. Its value must be a string. |
48
+ | `channel` | Optional. Channel the changes are published on. Default: `<namespace>:changed`. |
49
+
50
+ Each entry is stored as JSON under its own Redis key, `<namespace>:<id>`. The entry `{ userId: 'anna', ... }` above is stored as `user_prefs:anna`.
51
+
52
+ Entries are JSON objects: their values can be objects, arrays, strings, numbers, booleans and `null`. A `Date` arrives as an ISO string.
53
+
54
+ ## Use a live collection
55
+
56
+ ```ts
57
+ import { createClient } from 'redis'
58
+ import { live } from '@sebspark/redis-live'
59
+ import { userPrefs } from './collections'
60
+
61
+ const client = await createClient({ url }).connect()
62
+
63
+ const prefs = await live(userPrefs, { client })
64
+
65
+ prefs.get('anna') // the entry, from memory, or null
66
+ prefs.has('anna') // whether an entry exists, from memory
67
+
68
+ await prefs.set({ userId: 'anna', channels: ['push'], quietHours: null })
69
+ await prefs.del('anna')
70
+ ```
71
+
72
+ `await live()` resolves when every entry is loaded, so `get` is ready to use from then on.
73
+
74
+ `get` and `has` read from memory and return right away; they never touch Redis. `set` and `del` update memory immediately, then write to Redis and return a promise that resolves when Redis has stored and published the change.
75
+
76
+ So once `live()` has resolved, the collection can be used as if it were synchronous: read with `get`, write with `set` and `del` without awaiting them, and every later `get` already sees the write.
77
+
78
+ Code written against a Redis client usually keeps working: `await prefs.get(id)` returns the entry, because `await` accepts plain values. Only code that calls `.then()` on the result of `get` needs changing.
79
+
80
+ `live()` duplicates the client you give it (`client.duplicate()`) for its subscription, because a Redis connection that subscribes cannot run other commands. It uses your client for loading and writing entries.
81
+
82
+ | Option | Meaning |
83
+ | --- | --- |
84
+ | `client` | A connected `redis` client, created with `createClient()`. Clients using `RESP: 2` are not supported. |
85
+
86
+ ### Writing
87
+
88
+ `set` takes the id from the entry's `key` property. `set` and `del` change memory first, so `get` returns the change right away, and emit `add`, `update` or `delete` at once. Then they run the write and the publish in one `MULTI` transaction, so no process hears about a change that was not stored, and a stored change is always announced.
89
+
90
+ Every process applies changes in the order Redis published them, including its own, which come back over the subscription. If another process wrote the same entry just before, its change can show briefly, until this process's own change arrives and is applied again. All processes end on the same value as Redis.
91
+
92
+ If the write fails, the entry is read back from Redis, so memory never keeps a change Redis does not have, and the failure is reported as an `error` event (see [Errors](#errors)).
93
+
94
+ ### Entries that expire
95
+
96
+ `set` takes the same `expiration` option as node-redis's `SET`:
97
+
98
+ ```ts
99
+ await prefs.set(entry, {
100
+ expiration: { type: 'PX', value: 60_000 }, // or EX, EXAT, PXAT
101
+ })
102
+ ```
103
+
104
+ Redis deletes the key when it expires and announces it as an expired-key event; every process then removes the entry and emits `expired`. Redis only sends those events if its `notify-keyspace-events` setting includes expired events (`E` and `x`, e.g. `Ex`). It is off by default:
105
+
106
+ ```bash
107
+ redis-cli CONFIG SET notify-keyspace-events Ex
108
+ ```
109
+
110
+ Like every `set`, a `set` with an `expiration` changes memory at once. Before writing to Redis, it checks this setting once per live collection. If expired events are not enabled, the write is refused like any write Redis refuses (see [Errors](#errors)), because processes would otherwise keep expired entries forever. On managed Redis services that disable `CONFIG`, enable it through the service's own settings.
111
+
112
+ ### Events
113
+
114
+ ```ts
115
+ prefs.on('add', (entry) => {}) // an entry that was not in memory
116
+ prefs.on('update', (entry) => {}) // an entry that was in memory and changed
117
+ prefs.on('delete', (id) => {}) // an entry removed with del
118
+ prefs.on('expired', (id) => {}) // an entry that expired
119
+
120
+ prefs.on('change', (type, payload) => {
121
+ // every add, update, delete and expired; payload is an entry, or an id for 'delete' and 'expired'
122
+ })
123
+ ```
124
+
125
+ Events report every change after `live()` resolves, whichever process made it, this one included; a process's own `set` or `del` emits at once. The entries loaded at startup do not emit `add`, and an entry that arrives identical to the one already in memory emits nothing. `on`, `once` and `off` behave like Node's `EventEmitter`, but only accept these events and `error`, so a misspelled event name is a type error.
126
+
127
+ ### Errors
128
+
129
+ ```ts
130
+ prefs.on('error', (error) => {
131
+ logger.error(error) // a failed write, or the entries could not be read again after a reconnect
132
+ })
133
+ ```
134
+
135
+ A lost connection is not an error: node-redis reconnects on its own, and the collection loads again.
136
+
137
+ Failures are reported on the live object, like Node's `EventEmitter`: with an `error` listener, they go to it. Without one, the error is thrown. For a failed `set` or `del`, that means its promise rejects, so a write that nobody awaits ends the process like any unhandled rejection. Add an `error` listener when you write without awaiting.
138
+
139
+ ### What `live()` does
140
+
141
+ 1. Subscribes to the collection's channel and to Redis's expired-key events.
142
+ 2. Only after subscribing, loads every entry: `SCAN` for `<namespace>:*`, then `MGET`. Changes that arrive meanwhile are held and applied after, so none slips in between.
143
+ 3. On each message, applies the entry it carries, or deletes the id.
144
+ 4. On each expired-key event for one of the collection's keys, removes that id.
145
+ 5. On reconnect, loads every entry again, because messages published while disconnected are not replayed. Events are emitted for the difference between before and after.
146
+
147
+ ## Schema changes
148
+
149
+ Processes deploy separately, so for a while they disagree on the shape of an entry. To add a property:
150
+
151
+ 1. **Deploy the processes that read it** so they accept the property being missing.
152
+ 2. **Deploy the processes that write it.**
153
+
154
+ Entries written before then do not have the property until they are written again. Type it as optional, e.g. `locale?: string`. To remove a property, stop reading it first, then stop writing it. Never change the `key` property or the namespace in place; treat that as a new collection.
155
+
156
+ ## Guarantees and limits
157
+
158
+ - Eventually consistent: after a write, other processes may still read the old value until the message reaches them. When two processes write the same entry at once, the one Redis publishes last wins, everywhere.
159
+ - A `set` or `del` and its message are one `MULTI` transaction.
160
+ - Changes are applied in the order Redis published them, in every process.
161
+ - Messages are delivered to connected subscribers, in the order they were published. There is no replay; that is why `live()` loads every entry again on reconnect.
162
+ - Redis sends an expired-key event when it actually deletes the key. That happens when the key is next accessed or when Redis's background expiry finds it, so it can come somewhat after the expiry time.
163
+ - Expired-key events are sent per database (`__keyevent@<db>__:expired`); `live()` listens on the database its client uses.
164
+
165
+ ## Graceful shutdown
166
+
167
+ ```ts
168
+ process.on('SIGTERM', async () => {
169
+ await prefs.close() // wait for pending writes, unsubscribe, close the duplicated connection
170
+ // ... then close the HTTP server and your client
171
+ })
172
+ ```
173
+
174
+ ## Non-goals
175
+
176
+ - Not for entries written outside redis-live. Every write must go through `set` or `del`, or other processes will not hear about it. Expiry is the only exception.
177
+ - Not a durable message queue. If delivery must not be missed, use Redis Streams or a real queue.
178
+ - Not a query layer. A collection is every entry in one namespace.
@@ -0,0 +1,75 @@
1
+ import { RedisClientType } from "redis";
2
+ /** A collection kept live: every process that uses it defines it the same way. */
3
+ type Collection<T, K extends keyof T> = {
4
+ namespace: string;
5
+ /** Property of an entry that holds its id. */
6
+ key: K;
7
+ channel: string;
8
+ };
9
+ type CollectionOptions<T> = {
10
+ /** Namespace of the collection, like a table name. */
11
+ namespace: string;
12
+ /** Property of an entry that holds its id. Its value must be a string. */
13
+ key: keyof T & string;
14
+ /** Channel the changes are published on. Default: `<namespace>:changed`. */
15
+ channel?: string;
16
+ };
17
+ /** Defines a live collection. Declare the entry type with a type parameter. */
18
+ export declare const defineCollection: <T = Record<string, unknown>>({ namespace, key, channel }: CollectionOptions<T>) => Collection<T, keyof T & string>;
19
+ /**
20
+ * The payload of each event: the entry for `add` and `update`, the id for
21
+ * `delete` and `expired`.
22
+ */
23
+ type Events<T, K extends keyof T> = {
24
+ add: T;
25
+ update: T;
26
+ delete: T[K];
27
+ expired: T[K];
28
+ };
29
+ /** Listener for `change`: called with the event type, and its payload narrowed by that type. */
30
+ type ChangeListener<T, K extends keyof T> = (...args: { [E in keyof Events<T, K>]: [type: E, payload: Events<T, K>[E]]; }[keyof Events<T, K>]) => void;
31
+ type Subscribe<T, K extends keyof T, Self> = {
32
+ <E extends keyof Events<T, K>>(event: E, listener: (payload: Events<T, K>[E]) => void): Self;
33
+ (event: 'change', listener: ChangeListener<T, K>): Self;
34
+ (event: 'error', listener: (error: unknown) => void): Self;
35
+ };
36
+ /** Every entry of a collection, kept current: reads, events and close. */
37
+ type Live<T, K extends keyof T> = {
38
+ /** Whether an entry exists for `id`. Reads from memory. */
39
+ has(id: T[K]): boolean;
40
+ /** The entry for `id`, or `null`, like Redis. Reads from memory. */
41
+ get(id: T[K]): T | null;
42
+ on: Subscribe<T, K, Live<T, K>>;
43
+ once: Subscribe<T, K, Live<T, K>>;
44
+ off: Subscribe<T, K, Live<T, K>>;
45
+ /**
46
+ * Waits for pending writes, then stops applying changes. Safe to call more
47
+ * than once: every call resolves when closing has finished.
48
+ */
49
+ close(): Promise<void>;
50
+ };
51
+ type WriteOptions = {
52
+ /** The same as node-redis's `SET` expiration. Needs expired-key events. */
53
+ expiration?: {
54
+ type: 'EX' | 'PX' | 'EXAT' | 'PXAT';
55
+ value: number;
56
+ };
57
+ };
58
+ /** A live collection: reads from memory, writes through Redis, events for every change. */
59
+ type LiveCollection<T, K extends keyof T = keyof T> = Live<T, K> & {
60
+ /** Stores the entry, changing memory at once. Resolves when Redis has stored and published it. */
61
+ set(entry: T, options?: WriteOptions): Promise<void>;
62
+ /** Deletes the entry, changing memory at once. Resolves when Redis has deleted and published it. */
63
+ del(id: T[K]): Promise<void>;
64
+ };
65
+ type LiveOptions = {
66
+ /** A connected `redis` client. Duplicated for the subscription. */
67
+ client: RedisClientType;
68
+ };
69
+ /**
70
+ * Keeps every entry of `collection` in memory and applies every change as it
71
+ * arrives. Resolves when the entries are loaded.
72
+ */
73
+ export declare const live: <T, K extends keyof T>(collection: Collection<T, K>, { client }: LiveOptions) => Promise<LiveCollection<T, K>>;
74
+ export type { ChangeListener, Collection, CollectionOptions, Events, Live, LiveCollection, LiveOptions, WriteOptions };
75
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/collection.ts","../src/types.ts","../src/live.ts"],"mappings":";;KACY,WAAW,GAAG,gBAAgB;EACxC;;EAEA,KAAK;EACL;;KAGU,kBAAkB;;EAE5B;;EAEA,WAAW;;EAEX;;;qBAIW,mBAAoB,IAAI,2BAAuB,WAAA,KAAA,WAIzD,kBAAkB,OAAK,WAAW,SAAS;;;;;KClBlC,OAAO,GAAG,gBAAgB;EACpC,KAAK;EACL,QAAQ;EACR,QAAQ,EAAE;EACV,SAAS,EAAE;;;KAID,eAAe,GAAG,gBAAgB,SACzC,SACA,WAAW,OAAO,GAAG,MAAM,MAAM,GAAG,SAAS,OAAO,GAAG,GAAG,aACrD,OAAO,GAAG;KAGf,UAAU,GAAG,gBAAgB,GAAG;GAClC,gBAAgB,OAAO,GAAG,IACzB,OAAO,GACP,WAAW,SAAS,OAAO,GAAG,GAAG,cAChC;GACF,iBAAiB,UAAU,eAAe,GAAG,KAAK;GAClD,gBAAgB,WAAW,0BAA0B;;;KAI5C,KAAK,GAAG,gBAAgB;;EAElC,IAAI,IAAI,EAAE;;EAEV,IAAI,IAAI,EAAE,KAAK;EACf,IAAI,UAAU,GAAG,GAAG,KAAK,GAAG;EAC5B,MAAM,UAAU,GAAG,GAAG,KAAK,GAAG;EAC9B,KAAK,UAAU,GAAG,GAAG,KAAK,GAAG;;;;;EAK7B,SAAS;;KCnCC;;EAEV;IAAe;IAAqC;;;;KAI1C,eAAe,GAAG,gBAAgB,UAAU,KAAK,KAAK,GAAG;;EAEnE,IAAI,OAAO,GAAG,UAAU,eAAe;;EAEvC,IAAI,IAAI,EAAE,KAAK;;KAGL;;EAEV,QAAQ;;;;;;qBASG,OAAc,GAAG,gBAAgB,GAAC,YACjC,WAAW,GAAG,MAAE,UAChB,gBACX,QAAQ,eAAe,GAAG"}
package/dist/index.mjs ADDED
@@ -0,0 +1,196 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ // src/collection.ts
4
+ /** Defines a live collection. Declare the entry type with a type parameter. */
5
+ const defineCollection = ({ namespace, key, channel = `${namespace}:changed` }) => ({
6
+ namespace,
7
+ key,
8
+ channel
9
+ });
10
+ /** The Redis key an entry is stored under: `<namespace>:<id>`. */
11
+ const redisKey = ({ namespace }, id) => `${namespace}:${String(id)}`;
12
+ // src/store.ts
13
+ var LiveEntries = class {
14
+ #entries;
15
+ #events;
16
+ #close;
17
+ constructor(entries, events, close) {
18
+ this.#entries = entries;
19
+ this.#events = events;
20
+ this.#close = close;
21
+ }
22
+ has(id) {
23
+ return this.#entries.has(id);
24
+ }
25
+ get(id) {
26
+ return this.#entries.get(id) ?? null;
27
+ }
28
+ on(event, listener) {
29
+ this.#events.on(event, listener);
30
+ return this;
31
+ }
32
+ once(event, listener) {
33
+ this.#events.once(event, listener);
34
+ return this;
35
+ }
36
+ off(event, listener) {
37
+ this.#events.off(event, listener);
38
+ return this;
39
+ }
40
+ close() {
41
+ return this.#close();
42
+ }
43
+ };
44
+ /**
45
+ * The in-memory entries behind `live()`. `live` is handed to callers;
46
+ * `upsert`, `remove`, `expire`, `replaceAll` and `fail` are for redis-live only.
47
+ */
48
+ const createStore = (key, onClose = () => {}) => {
49
+ const entries = /* @__PURE__ */ new Map();
50
+ const events = new EventEmitter();
51
+ let closed = false;
52
+ const upsert = (entry) => {
53
+ if (closed) return;
54
+ const id = entry[key];
55
+ const exists = entries.has(id);
56
+ if (exists && isDeepStrictEqual(entries.get(id), entry)) return;
57
+ const type = exists ? "update" : "add";
58
+ entries.set(id, entry);
59
+ events.emit(type, entry);
60
+ events.emit("change", type, entry);
61
+ };
62
+ const removeAs = (type) => (id) => {
63
+ if (closed || !entries.delete(id)) return;
64
+ events.emit(type, id);
65
+ events.emit("change", type, id);
66
+ };
67
+ const replaceAll = (next) => {
68
+ if (closed) return;
69
+ const nextIds = new Set(next.map((entry) => entry[key]));
70
+ for (const id of [...entries.keys()]) if (!nextIds.has(id)) removeAs("delete")(id);
71
+ for (const entry of next) upsert(entry);
72
+ };
73
+ const fail = (error) => {
74
+ if (closed) return;
75
+ events.emit("error", error);
76
+ };
77
+ let closing;
78
+ return {
79
+ live: new LiveEntries(entries, events, () => {
80
+ closing ??= (async () => {
81
+ await onClose();
82
+ closed = true;
83
+ events.removeAllListeners();
84
+ })();
85
+ return closing;
86
+ }),
87
+ upsert,
88
+ remove: removeAs("delete"),
89
+ expire: removeAs("expired"),
90
+ replaceAll,
91
+ fail
92
+ };
93
+ };
94
+ // src/live.ts
95
+ /**
96
+ * Keeps every entry of `collection` in memory and applies every change as it
97
+ * arrives. Resolves when the entries are loaded.
98
+ */
99
+ const live = async (collection, { client }) => {
100
+ const prefix = `${collection.namespace}:`;
101
+ const pending = /* @__PURE__ */ new Set();
102
+ const subscriber = client.duplicate();
103
+ subscriber.on("error", () => {});
104
+ const store = createStore(collection.key, async () => {
105
+ await Promise.allSettled([...pending]);
106
+ await subscriber.close();
107
+ });
108
+ const report = (error) => {
109
+ setImmediate(() => store.fail(error));
110
+ };
111
+ const parse = (text) => JSON.parse(text);
112
+ const parseMessage = (text) => JSON.parse(text);
113
+ const idFrom = (key) => key.slice(prefix.length);
114
+ const readAll = async () => {
115
+ const keys = [];
116
+ for await (const batch of client.scanIterator({
117
+ MATCH: `${prefix}*`,
118
+ COUNT: 1e3
119
+ })) keys.push(...batch);
120
+ if (keys.length === 0) return [];
121
+ return (await client.mGet(keys)).flatMap((value) => value === null ? [] : [parse(value)]);
122
+ };
123
+ const hydrate = async () => store.replaceAll(await readAll());
124
+ const apply = (text) => {
125
+ const message = parseMessage(text);
126
+ if ("set" in message) store.upsert(message.set);
127
+ else store.remove(message.del);
128
+ };
129
+ let startLoading = () => {};
130
+ const loaded = new Promise((resolve) => {
131
+ startLoading = resolve;
132
+ }).then(hydrate);
133
+ let queue = loaded.catch(() => {});
134
+ const enqueue = (task) => {
135
+ queue = queue.then(task).catch(report);
136
+ };
137
+ let connectedBefore = false;
138
+ subscriber.on("ready", () => {
139
+ if (connectedBefore) enqueue(hydrate);
140
+ connectedBefore = true;
141
+ });
142
+ const database = client.options?.database ?? 0;
143
+ await subscriber.connect();
144
+ await subscriber.subscribe(collection.channel, (text) => enqueue(() => apply(text)));
145
+ await subscriber.subscribe(`__keyevent@${database}__:expired`, (key) => {
146
+ if (key.startsWith(prefix)) enqueue(() => store.expire(idFrom(key)));
147
+ });
148
+ startLoading();
149
+ await loaded.catch(async (error) => {
150
+ await store.live.close();
151
+ throw error;
152
+ });
153
+ const track = (write) => {
154
+ pending.add(write);
155
+ const forget = () => {
156
+ pending.delete(write);
157
+ };
158
+ write.then(forget, forget);
159
+ return write;
160
+ };
161
+ const persist = async (id, write) => {
162
+ try {
163
+ await write();
164
+ } catch (error) {
165
+ const stored = await client.get(redisKey(collection, id));
166
+ if (stored === null) store.remove(id);
167
+ else store.upsert(parse(stored));
168
+ store.fail(error);
169
+ }
170
+ };
171
+ let expiredEventsChecked = false;
172
+ const checkExpiredEvents = async () => {
173
+ if (expiredEventsChecked) return;
174
+ const flags = (await client.configGet("notify-keyspace-events"))["notify-keyspace-events"] ?? "";
175
+ if (!flags.includes("E") || !(flags.includes("x") || flags.includes("A"))) throw new Error("Redis does not send expired-key events, so expired entries would stay in memory. Set notify-keyspace-events to include E and x, e.g. \"Ex\".");
176
+ expiredEventsChecked = true;
177
+ };
178
+ const set = (entry, { expiration } = {}) => {
179
+ store.upsert(entry);
180
+ return track(persist(entry[collection.key], async () => {
181
+ if (expiration) await checkExpiredEvents();
182
+ await client.multi().set(redisKey(collection, entry[collection.key]), JSON.stringify(entry), expiration ? { expiration } : void 0).publish(collection.channel, JSON.stringify({ set: entry })).exec();
183
+ }));
184
+ };
185
+ const del = (id) => {
186
+ store.remove(id);
187
+ return track(persist(id, () => client.multi().del(redisKey(collection, id)).publish(collection.channel, JSON.stringify({ del: id })).exec()));
188
+ };
189
+ return Object.assign(store.live, {
190
+ set,
191
+ del
192
+ });
193
+ };
194
+ export { defineCollection, live };
195
+
196
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/collection.ts","../src/store.ts","../src/live.ts"],"sourcesContent":["/** A collection kept live: every process that uses it defines it the same way. */\nexport type Collection<T, K extends keyof T> = {\n namespace: string\n /** Property of an entry that holds its id. */\n key: K\n channel: string\n}\n\nexport type CollectionOptions<T> = {\n /** Namespace of the collection, like a table name. */\n namespace: string\n /** Property of an entry that holds its id. Its value must be a string. */\n key: keyof T & string\n /** Channel the changes are published on. Default: `<namespace>:changed`. */\n channel?: string\n}\n\n/** Defines a live collection. Declare the entry type with a type parameter. */\nexport const defineCollection = <T = Record<string, unknown>>({\n namespace,\n key,\n channel = `${namespace}:changed`,\n}: CollectionOptions<T>): Collection<T, keyof T & string> => ({\n namespace,\n key,\n channel,\n})\n\n/** The Redis key an entry is stored under: `<namespace>:<id>`. */\nexport const redisKey = <T, K extends keyof T>(\n { namespace }: Collection<T, K>,\n id: T[K]\n) => `${namespace}:${String(id)}`\n","import { EventEmitter } from 'node:events'\nimport { isDeepStrictEqual } from 'node:util'\nimport type { ChangeListener, Events, Live } from './types'\n\ntype AnyListener<T, K extends keyof T> =\n | ((payload: Events<T, K>[keyof Events<T, K>]) => void)\n | ChangeListener<T, K>\n | ((error: unknown) => void)\n\ntype EventName<T, K extends keyof T> = keyof Events<T, K> | 'change' | 'error'\n\nclass LiveEntries<T, K extends keyof T> {\n readonly #entries: ReadonlyMap<T[K], T>\n readonly #events: EventEmitter\n readonly #close: () => Promise<void>\n\n constructor(\n entries: ReadonlyMap<T[K], T>,\n events: EventEmitter,\n close: () => Promise<void>\n ) {\n this.#entries = entries\n this.#events = events\n this.#close = close\n }\n\n has(id: T[K]): boolean {\n return this.#entries.has(id)\n }\n\n get(id: T[K]): T | null {\n return this.#entries.get(id) ?? null\n }\n\n on<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n on(event: 'change', listener: ChangeListener<T, K>): this\n on(event: 'error', listener: (error: unknown) => void): this\n on(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.on(event, listener)\n return this\n }\n\n once<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n once(event: 'change', listener: ChangeListener<T, K>): this\n once(event: 'error', listener: (error: unknown) => void): this\n once(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.once(event, listener)\n return this\n }\n\n off<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n off(event: 'change', listener: ChangeListener<T, K>): this\n off(event: 'error', listener: (error: unknown) => void): this\n off(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.off(event, listener)\n return this\n }\n\n close(): Promise<void> {\n return this.#close()\n }\n}\n\n/**\n * The in-memory entries behind `live()`. `live` is handed to callers;\n * `upsert`, `remove`, `expire`, `replaceAll` and `fail` are for redis-live only.\n */\nexport const createStore = <T, K extends keyof T>(\n key: K,\n onClose: () => void | Promise<void> = () => {}\n) => {\n const entries = new Map<T[K], T>()\n const events = new EventEmitter()\n let closed = false\n\n const upsert = (entry: T) => {\n if (closed) return\n const id = entry[key]\n const exists = entries.has(id)\n if (exists && isDeepStrictEqual(entries.get(id), entry)) return\n const type = exists ? 'update' : 'add'\n entries.set(id, entry)\n events.emit(type, entry)\n events.emit('change', type, entry)\n }\n\n const removeAs = (type: 'delete' | 'expired') => (id: T[K]) => {\n if (closed || !entries.delete(id)) return\n events.emit(type, id)\n events.emit('change', type, id)\n }\n\n // Applies a full read of the collection, emitting only what differs\n const replaceAll = (next: T[]) => {\n if (closed) return\n const nextIds = new Set(next.map((entry) => entry[key]))\n for (const id of [...entries.keys()]) {\n if (!nextIds.has(id)) removeAs('delete')(id)\n }\n for (const entry of next) upsert(entry)\n }\n\n // Reports an error like EventEmitter: to `error` listeners, or thrown if there are none\n const fail = (error: unknown) => {\n if (closed) return\n events.emit('error', error)\n }\n\n let closing: Promise<void> | undefined\n const live: Live<T, K> = new LiveEntries<T, K>(entries, events, () => {\n closing ??= (async () => {\n // Pending writes still apply, so the entries close only after them\n await onClose()\n closed = true\n events.removeAllListeners()\n })()\n return closing\n })\n\n return {\n live,\n upsert,\n remove: removeAs('delete'),\n expire: removeAs('expired'),\n replaceAll,\n fail,\n }\n}\n","import type { RedisClientType } from 'redis'\nimport { type Collection, redisKey } from './collection'\nimport { createStore } from './store'\nimport type { Live } from './types'\n\nexport type WriteOptions = {\n /** The same as node-redis's `SET` expiration. Needs expired-key events. */\n expiration?: { type: 'EX' | 'PX' | 'EXAT' | 'PXAT'; value: number }\n}\n\n/** A live collection: reads from memory, writes through Redis, events for every change. */\nexport type LiveCollection<T, K extends keyof T = keyof T> = Live<T, K> & {\n /** Stores the entry, changing memory at once. Resolves when Redis has stored and published it. */\n set(entry: T, options?: WriteOptions): Promise<void>\n /** Deletes the entry, changing memory at once. Resolves when Redis has deleted and published it. */\n del(id: T[K]): Promise<void>\n}\n\nexport type LiveOptions = {\n /** A connected `redis` client. Duplicated for the subscription. */\n client: RedisClientType\n}\n\ntype Message<T, K extends keyof T> = { set: T } | { del: T[K] }\n\n/**\n * Keeps every entry of `collection` in memory and applies every change as it\n * arrives. Resolves when the entries are loaded.\n */\nexport const live = async <T, K extends keyof T>(\n collection: Collection<T, K>,\n { client }: LiveOptions\n): Promise<LiveCollection<T, K>> => {\n const prefix = `${collection.namespace}:`\n const pending = new Set<Promise<void>>()\n\n // A subscribing connection cannot run other commands, so it gets its own.\n // node-redis reconnects it on its own, so a lost connection is not an error.\n const subscriber = client.duplicate()\n subscriber.on('error', () => {})\n\n const store = createStore<T, K>(collection.key, async () => {\n await Promise.allSettled([...pending])\n await subscriber.close()\n })\n\n // On a later tick, so a thrown error (no `error` listener) cannot stop the queue\n const report = (error: unknown) => {\n setImmediate(() => store.fail(error))\n }\n\n // The caller declares the entry type through the collection's type parameter\n const parse = (text: string): T => JSON.parse(text)\n const parseMessage = (text: string): Message<T, K> => JSON.parse(text)\n // biome-ignore lint/plugin/no-type-assertion: ids are strings, by the collection's contract\n const idFrom = (key: string) => key.slice(prefix.length) as T[K]\n\n const readAll = async () => {\n const keys: string[] = []\n for await (const batch of client.scanIterator({\n MATCH: `${prefix}*`,\n COUNT: 1000,\n })) {\n keys.push(...batch)\n }\n if (keys.length === 0) return []\n const values = await client.mGet(keys)\n return values.flatMap((value) => (value === null ? [] : [parse(value)]))\n }\n\n const hydrate = async () => store.replaceAll(await readAll())\n\n const apply = (text: string) => {\n const message = parseMessage(text)\n if ('set' in message) store.upsert(message.set)\n else store.remove(message.del)\n }\n\n // Changes are applied one at a time, in the order they arrived, and only\n // once the first load has run\n let startLoading = () => {}\n const subscribed = new Promise<void>((resolve) => {\n startLoading = resolve\n })\n const loaded = subscribed.then(hydrate)\n let queue: Promise<void> = loaded.catch(() => {})\n const enqueue = (task: () => void | Promise<void>) => {\n queue = queue.then(task).catch(report)\n }\n\n // Messages sent while disconnected are not replayed, so load again\n let connectedBefore = false\n subscriber.on('ready', () => {\n if (connectedBefore) enqueue(hydrate)\n connectedBefore = true\n })\n\n const database = client.options?.database ?? 0\n await subscriber.connect()\n await subscriber.subscribe(collection.channel, (text) =>\n enqueue(() => apply(text))\n )\n await subscriber.subscribe(`__keyevent@${database}__:expired`, (key) => {\n if (key.startsWith(prefix)) enqueue(() => store.expire(idFrom(key)))\n })\n startLoading()\n\n await loaded.catch(async (error) => {\n await store.live.close()\n throw error\n })\n\n const track = (write: Promise<void>) => {\n pending.add(write)\n const forget = () => {\n pending.delete(write)\n }\n write.then(forget, forget)\n return write\n }\n\n // Memory has already changed; if Redis refuses, go back to what Redis has\n const persist = async (id: T[K], write: () => Promise<unknown>) => {\n try {\n await write()\n } catch (error) {\n const stored = await client.get(redisKey(collection, id))\n if (stored === null) store.remove(id)\n else store.upsert(parse(stored))\n // To `error` listeners, or thrown, which rejects this write\n store.fail(error)\n }\n }\n\n let expiredEventsChecked = false\n const checkExpiredEvents = async () => {\n if (expiredEventsChecked) return\n const config = await client.configGet('notify-keyspace-events')\n const flags = config['notify-keyspace-events'] ?? ''\n if (!flags.includes('E') || !(flags.includes('x') || flags.includes('A'))) {\n throw new Error(\n 'Redis does not send expired-key events, so expired entries would stay in memory. Set notify-keyspace-events to include E and x, e.g. \"Ex\".'\n )\n }\n expiredEventsChecked = true\n }\n\n const set = (entry: T, { expiration }: WriteOptions = {}) => {\n store.upsert(entry)\n return track(\n persist(entry[collection.key], async () => {\n if (expiration) await checkExpiredEvents()\n await client\n .multi()\n .set(\n redisKey(collection, entry[collection.key]),\n JSON.stringify(entry),\n expiration ? { expiration } : undefined\n )\n .publish(collection.channel, JSON.stringify({ set: entry }))\n .exec()\n })\n )\n }\n\n const del = (id: T[K]) => {\n store.remove(id)\n return track(\n persist(id, () =>\n client\n .multi()\n .del(redisKey(collection, id))\n .publish(collection.channel, JSON.stringify({ del: id }))\n .exec()\n )\n )\n }\n\n return Object.assign(store.live, { set, del })\n}\n"],"mappings":";;;;AAkBA,MAAa,oBAAiD,EAC5D,WACA,KACA,UAAU,GAAG,UAAU,iBACqC;CAC5D;CACA;CACA;AACF;;AAGA,MAAa,YACX,EAAE,aACF,OACG,GAAG,UAAU,GAAG,OAAO,EAAE;;ACrB9B,IAAM,cAAN,MAAwC;CACtC;CACA;CACA;CAEA,YACE,SACA,QACA,OACA;EACA,KAAK,WAAW;EAChB,KAAK,UAAU;EACf,KAAK,SAAS;CAChB;CAEA,IAAI,IAAmB;EACrB,OAAO,KAAK,SAAS,IAAI,EAAE;CAC7B;CAEA,IAAI,IAAoB;EACtB,OAAO,KAAK,SAAS,IAAI,EAAE,KAAK;CAClC;CAQA,GAAG,OAAwB,UAAmC;EAC5D,KAAK,QAAQ,GAAG,OAAO,QAAQ;EAC/B,OAAO;CACT;CAQA,KAAK,OAAwB,UAAmC;EAC9D,KAAK,QAAQ,KAAK,OAAO,QAAQ;EACjC,OAAO;CACT;CAQA,IAAI,OAAwB,UAAmC;EAC7D,KAAK,QAAQ,IAAI,OAAO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,IAAI,MACR,8IACF;EAEF,uBAAuB;CACzB;CAEA,MAAM,OAAO,OAAU,EAAE,eAA6B,CAAC,MAAM;EAC3D,MAAM,OAAO,KAAK;EAClB,OAAO,MACL,QAAQ,MAAM,WAAW,MAAM,YAAY;GACzC,IAAI,YAAY,MAAM,mBAAmB;GACzC,MAAM,OACH,MAAM,CAAC,CACP,IACC,SAAS,YAAY,MAAM,WAAW,IAAI,GAC1C,KAAK,UAAU,KAAK,GACpB,aAAa,EAAE,WAAW,IAAI,KAAA,CAChC,CAAC,CACA,QAAQ,WAAW,SAAS,KAAK,UAAU,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC,CAC3D,KAAK;EACV,CAAC,CACH;CACF;CAEA,MAAM,OAAO,OAAa;EACxB,MAAM,OAAO,EAAE;EACf,OAAO,MACL,QAAQ,UACN,OACG,MAAM,CAAC,CACP,IAAI,SAAS,YAAY,EAAE,CAAC,CAAC,CAC7B,QAAQ,WAAW,SAAS,KAAK,UAAU,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CACxD,KAAK,CACV,CACF;CACF;CAEA,OAAO,OAAO,OAAO,MAAM,MAAM;EAAE;EAAK;CAAI,CAAC;AAC/C"}
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@sebspark/redis-live",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "dist/index.mjs",
7
+ "types": "dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "@sebspark/source": "./src/index.ts",
11
+ "types": "./dist/index.d.mts",
12
+ "import": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "spark-build src/index.ts",
20
+ "dev": "tsc --watch --noEmit",
21
+ "lint": "biome check --write .",
22
+ "test": "vitest run --passWithNoTests --coverage --fsModuleCachePath node_modules/.vitest-cache",
23
+ "test:e2e": "vitest --config vitest.config.e2e.ts --run --fsModuleCachePath node_modules/.vitest-cache",
24
+ "typecheck": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run --fsModuleCachePath node_modules/.vitest-cache"
25
+ },
26
+ "devDependencies": {
27
+ "@biomejs/biome": "2.6.8",
28
+ "@sebspark/expect-eventually": "0.1.17",
29
+ "@sebspark/tsconfig": "3.0.31",
30
+ "@testcontainers/redis": "12.2.2",
31
+ "redis": "6.4.0",
32
+ "typescript": "7.0.2",
33
+ "vite": "8.3.8",
34
+ "vitest": "5.1.1"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/seb-oss/Spark-packages.git"
39
+ },
40
+ "peerDependencies": {
41
+ "redis": ">=6"
42
+ }
43
+ }