@speeq/store-memory 0.0.0-stage → 0.2.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 speeq contributors
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,25 @@
1
- # Temporary Holding Version
1
+ # @speeq/store-memory
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
+ An in-memory `ConversationStore` for [speeq](../../../README.md). Use it to try speeq locally and
4
+ in tests.
5
+
6
+ > **Not for production or serverless.** Data is lost when the process restarts, and serverless
7
+ > platforms (Vercel, Netlify, Lambda) run many short-lived instances that do not share memory, so
8
+ > sessions, history and confirmations would randomly disappear. Use
9
+ > [`@speeq/store-mongodb`](../store-mongodb) or write your own adapter.
10
+
11
+ ```bash
12
+ pnpm add @speeq/store-memory@next
13
+ ```
14
+
15
+ ```ts
16
+ import { createMemoryStore } from "@speeq/store-memory";
17
+
18
+ // Keep one instance across Next.js dev hot reloads:
19
+ const g = globalThis as { speeqStore?: ReturnType<typeof createMemoryStore> };
20
+ export const store = (g.speeqStore ??= createMemoryStore());
21
+ ```
22
+
23
+ It passes the shared store contract (`@speeq/testing/store-contract`).
24
+
25
+ [Related guide or reference](../../../docs/guides/stores.md)
package/dist/index.cjs ADDED
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ MemoryStore: () => MemoryStore,
24
+ createMemoryStore: () => createMemoryStore
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+ var import_core = require("@speeq/core");
28
+ var warned = false;
29
+ var MemoryStore = class {
30
+ kind = "memory";
31
+ sessions = /* @__PURE__ */ new Map();
32
+ constructor(options = {}) {
33
+ if (!options.quiet && !warned && isProduction()) {
34
+ warned = true;
35
+ console.warn(
36
+ "[speeq] @speeq/store-memory is for development and tests only. Data is lost on restart and is not shared between serverless instances."
37
+ );
38
+ }
39
+ }
40
+ async createSession(session) {
41
+ if (this.sessions.has(session.id))
42
+ throw new import_core.SpeeqError("CONFLICT", { message: "Session exists." });
43
+ this.sessions.set(session.id, {
44
+ summary: (0, import_core.emptySummary)(session),
45
+ events: [],
46
+ dedupeKeys: /* @__PURE__ */ new Set()
47
+ });
48
+ }
49
+ async appendEvents(sessionId, events) {
50
+ const entry = this.sessions.get(sessionId);
51
+ if (!entry) throw new import_core.SpeeqError("NOT_FOUND", { message: "Session not found." });
52
+ const keys = events.map((e) => e.dedupeKey).filter((k) => k !== void 0);
53
+ if (keys.some((k) => entry.dedupeKeys.has(k)) || new Set(keys).size !== keys.length) {
54
+ throw new import_core.SpeeqError("CONFLICT");
55
+ }
56
+ const stored = events.map(
57
+ (e, i) => ({ ...e, seq: entry.events.length + i })
58
+ );
59
+ for (const e of stored) {
60
+ entry.events.push(structuredClone(e));
61
+ entry.summary = (0, import_core.applyEventToSummary)(entry.summary, e);
62
+ }
63
+ for (const k of keys) entry.dedupeKeys.add(k);
64
+ return stored;
65
+ }
66
+ async listEvents(sessionId, options = {}) {
67
+ const all = this.sessions.get(sessionId)?.events ?? [];
68
+ let out = options.afterSeq === void 0 ? all : all.filter((e) => e.seq > (options.afterSeq ?? -1));
69
+ if (options.limit !== void 0) {
70
+ out = options.last ? out.slice(-options.limit) : out.slice(0, options.limit);
71
+ }
72
+ return structuredClone(out);
73
+ }
74
+ async listSessions(filter, cursor) {
75
+ const limit = filter.limit ?? 20;
76
+ const after = cursor ? (0, import_core.decodeCursor)(cursor) : null;
77
+ const matching = [...this.sessions.values()].map((e) => e.summary).filter((s) => filter.userId === void 0 || s.userId === filter.userId).filter((s) => filter.from === void 0 || s.startedAt >= filter.from).filter((s) => filter.to === void 0 || s.startedAt <= filter.to).filter((s) => after === null || (0, import_core.isAfterCursor)(s, after)).sort(
78
+ (a, b) => a.startedAt === b.startedAt ? a.id < b.id ? 1 : -1 : a.startedAt < b.startedAt ? 1 : -1
79
+ );
80
+ const page = matching.slice(0, limit);
81
+ const last = page.at(-1);
82
+ return {
83
+ sessions: structuredClone(page),
84
+ nextCursor: matching.length > limit && last ? (0, import_core.encodeCursor)(last.startedAt, last.id) : null
85
+ };
86
+ }
87
+ async getSessionSummary(sessionId) {
88
+ const s = this.sessions.get(sessionId)?.summary;
89
+ return s ? structuredClone(s) : null;
90
+ }
91
+ async deleteOlderThan(date) {
92
+ const cutoff = date.toISOString();
93
+ const result = { sessions: 0, events: 0 };
94
+ for (const [id, entry] of this.sessions) {
95
+ if (entry.summary.lastEventAt < cutoff) {
96
+ result.sessions += 1;
97
+ result.events += entry.events.length;
98
+ this.sessions.delete(id);
99
+ }
100
+ }
101
+ return result;
102
+ }
103
+ };
104
+ function createMemoryStore(options = {}) {
105
+ return new MemoryStore(options);
106
+ }
107
+ function isProduction() {
108
+ const g = globalThis;
109
+ return g.process?.env?.NODE_ENV === "production";
110
+ }
111
+ // Annotate the CommonJS export names for ESM import in node:
112
+ 0 && (module.exports = {
113
+ MemoryStore,
114
+ createMemoryStore
115
+ });
116
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/store-memory`: a Map-based {@link ConversationStore} for development and tests.\n *\n * **Not for production or serverless.** Data lives in one process's memory: it is lost on\n * restart, and serverless platforms run many short-lived instances that do not share it.\n * Use `@speeq/store-mongodb` (or your own adapter) in production.\n * @packageDocumentation\n */\nimport {\n applyEventToSummary,\n type ConversationEvent,\n type ConversationStore,\n decodeCursor,\n emptySummary,\n encodeCursor,\n isAfterCursor,\n type ListEventsOptions,\n type NewConversationEvent,\n type NewSession,\n type RetentionResult,\n type SessionFilter,\n type SessionPage,\n type SessionSummary,\n SpeeqError,\n} from \"@speeq/core\";\n\n/** Options for {@link createMemoryStore}. */\nexport interface MemoryStoreOptions {\n /** Silence the one-time \"not for production\" warning. */\n quiet?: boolean;\n}\n\ninterface Entry {\n summary: SessionSummary;\n events: ConversationEvent[];\n dedupeKeys: Set<string>;\n}\n\nlet warned = false;\n\n/** An in-memory {@link ConversationStore}. See the package docs for its limits. */\nexport class MemoryStore implements ConversationStore {\n readonly kind = \"memory\";\n private readonly sessions = new Map<string, Entry>();\n\n constructor(options: MemoryStoreOptions = {}) {\n if (!options.quiet && !warned && isProduction()) {\n warned = true;\n console.warn(\n \"[speeq] @speeq/store-memory is for development and tests only. Data is lost on restart and is not shared between serverless instances.\",\n );\n }\n }\n\n async createSession(session: NewSession): Promise<void> {\n if (this.sessions.has(session.id))\n throw new SpeeqError(\"CONFLICT\", { message: \"Session exists.\" });\n this.sessions.set(session.id, {\n summary: emptySummary(session),\n events: [],\n dedupeKeys: new Set(),\n });\n }\n\n async appendEvents(\n sessionId: string,\n events: NewConversationEvent[],\n ): Promise<ConversationEvent[]> {\n const entry = this.sessions.get(sessionId);\n if (!entry) throw new SpeeqError(\"NOT_FOUND\", { message: \"Session not found.\" });\n const keys = events.map((e) => e.dedupeKey).filter((k): k is string => k !== undefined);\n if (keys.some((k) => entry.dedupeKeys.has(k)) || new Set(keys).size !== keys.length) {\n throw new SpeeqError(\"CONFLICT\");\n }\n const stored = events.map(\n (e, i) => ({ ...e, seq: entry.events.length + i }) as ConversationEvent,\n );\n for (const e of stored) {\n entry.events.push(structuredClone(e));\n entry.summary = applyEventToSummary(entry.summary, e);\n }\n for (const k of keys) entry.dedupeKeys.add(k);\n return stored;\n }\n\n async listEvents(\n sessionId: string,\n options: ListEventsOptions = {},\n ): Promise<ConversationEvent[]> {\n const all = this.sessions.get(sessionId)?.events ?? [];\n let out =\n options.afterSeq === undefined ? all : all.filter((e) => e.seq > (options.afterSeq ?? -1));\n if (options.limit !== undefined) {\n out = options.last ? out.slice(-options.limit) : out.slice(0, options.limit);\n }\n return structuredClone(out);\n }\n\n async listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage> {\n const limit = filter.limit ?? 20;\n const after = cursor ? decodeCursor(cursor) : null;\n const matching = [...this.sessions.values()]\n .map((e) => e.summary)\n .filter((s) => filter.userId === undefined || s.userId === filter.userId)\n .filter((s) => filter.from === undefined || s.startedAt >= filter.from)\n .filter((s) => filter.to === undefined || s.startedAt <= filter.to)\n .filter((s) => after === null || isAfterCursor(s, after))\n .sort((a, b) =>\n a.startedAt === b.startedAt ? (a.id < b.id ? 1 : -1) : a.startedAt < b.startedAt ? 1 : -1,\n );\n const page = matching.slice(0, limit);\n const last = page.at(-1);\n return {\n sessions: structuredClone(page),\n nextCursor: matching.length > limit && last ? encodeCursor(last.startedAt, last.id) : null,\n };\n }\n\n async getSessionSummary(sessionId: string): Promise<SessionSummary | null> {\n const s = this.sessions.get(sessionId)?.summary;\n return s ? structuredClone(s) : null;\n }\n\n async deleteOlderThan(date: Date): Promise<RetentionResult> {\n const cutoff = date.toISOString();\n const result: RetentionResult = { sessions: 0, events: 0 };\n for (const [id, entry] of this.sessions) {\n if (entry.summary.lastEventAt < cutoff) {\n result.sessions += 1;\n result.events += entry.events.length;\n this.sessions.delete(id);\n }\n }\n return result;\n }\n}\n\n/**\n * Creates an in-memory store. In Next.js dev mode, keep one instance on `globalThis` so hot\n * reloads do not wipe it (see the demo app).\n */\nexport function createMemoryStore(options: MemoryStoreOptions = {}): MemoryStore {\n return new MemoryStore(options);\n}\n\nfunction isProduction(): boolean {\n const g = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return g.process?.env?.NODE_ENV === \"production\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,kBAgBO;AAcP,IAAI,SAAS;AAGN,IAAM,cAAN,MAA+C;AAAA,EAC3C,OAAO;AAAA,EACC,WAAW,oBAAI,IAAmB;AAAA,EAEnD,YAAY,UAA8B,CAAC,GAAG;AAC5C,QAAI,CAAC,QAAQ,SAAS,CAAC,UAAU,aAAa,GAAG;AAC/C,eAAS;AACT,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,SAAoC;AACtD,QAAI,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K,UAAU;AACvC,UAAI,MAAM,QAAQ,cAAc,QAAQ;AACtC,eAAO,YAAY;AACnB,eAAO,UAAU,MAAM,OAAO;AAC9B,aAAK,SAAS,OAAO,EAAE;AAAA,MACzB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBAAkB,UAA8B,CAAC,GAAgB;AAC/E,SAAO,IAAI,YAAY,OAAO;AAChC;AAEA,SAAS,eAAwB;AAC/B,QAAM,IAAI;AACV,SAAO,EAAE,SAAS,KAAK,aAAa;AACtC;","names":[]}
@@ -0,0 +1,36 @@
1
+ import { ConversationStore, NewSession, NewConversationEvent, ConversationEvent, ListEventsOptions, SessionFilter, SessionPage, SessionSummary, RetentionResult } from '@speeq/core';
2
+
3
+ /**
4
+ * `@speeq/store-memory`: a Map-based {@link ConversationStore} for development and tests.
5
+ *
6
+ * **Not for production or serverless.** Data lives in one process's memory: it is lost on
7
+ * restart, and serverless platforms run many short-lived instances that do not share it.
8
+ * Use `@speeq/store-mongodb` (or your own adapter) in production.
9
+ * @packageDocumentation
10
+ */
11
+
12
+ /** Options for {@link createMemoryStore}. */
13
+ interface MemoryStoreOptions {
14
+ /** Silence the one-time "not for production" warning. */
15
+ quiet?: boolean;
16
+ }
17
+ /** An in-memory {@link ConversationStore}. See the package docs for its limits. */
18
+ declare class MemoryStore implements ConversationStore {
19
+ readonly kind = "memory";
20
+ private readonly sessions;
21
+ constructor(options?: MemoryStoreOptions);
22
+ createSession(session: NewSession): Promise<void>;
23
+ appendEvents(sessionId: string, events: NewConversationEvent[]): Promise<ConversationEvent[]>;
24
+ listEvents(sessionId: string, options?: ListEventsOptions): Promise<ConversationEvent[]>;
25
+ listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage>;
26
+ getSessionSummary(sessionId: string): Promise<SessionSummary | null>;
27
+ deleteOlderThan(date: Date): Promise<RetentionResult>;
28
+ }
29
+ /**
30
+ * Creates an in-memory store. In Next.js dev mode, keep one instance on `globalThis` so hot
31
+ * reloads do not wipe it (see the demo app).
32
+ */
33
+ declare function createMemoryStore(options?: MemoryStoreOptions): MemoryStore;
34
+
35
+ export { MemoryStore, createMemoryStore };
36
+ export type { MemoryStoreOptions };
@@ -0,0 +1,36 @@
1
+ import { ConversationStore, NewSession, NewConversationEvent, ConversationEvent, ListEventsOptions, SessionFilter, SessionPage, SessionSummary, RetentionResult } from '@speeq/core';
2
+
3
+ /**
4
+ * `@speeq/store-memory`: a Map-based {@link ConversationStore} for development and tests.
5
+ *
6
+ * **Not for production or serverless.** Data lives in one process's memory: it is lost on
7
+ * restart, and serverless platforms run many short-lived instances that do not share it.
8
+ * Use `@speeq/store-mongodb` (or your own adapter) in production.
9
+ * @packageDocumentation
10
+ */
11
+
12
+ /** Options for {@link createMemoryStore}. */
13
+ interface MemoryStoreOptions {
14
+ /** Silence the one-time "not for production" warning. */
15
+ quiet?: boolean;
16
+ }
17
+ /** An in-memory {@link ConversationStore}. See the package docs for its limits. */
18
+ declare class MemoryStore implements ConversationStore {
19
+ readonly kind = "memory";
20
+ private readonly sessions;
21
+ constructor(options?: MemoryStoreOptions);
22
+ createSession(session: NewSession): Promise<void>;
23
+ appendEvents(sessionId: string, events: NewConversationEvent[]): Promise<ConversationEvent[]>;
24
+ listEvents(sessionId: string, options?: ListEventsOptions): Promise<ConversationEvent[]>;
25
+ listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage>;
26
+ getSessionSummary(sessionId: string): Promise<SessionSummary | null>;
27
+ deleteOlderThan(date: Date): Promise<RetentionResult>;
28
+ }
29
+ /**
30
+ * Creates an in-memory store. In Next.js dev mode, keep one instance on `globalThis` so hot
31
+ * reloads do not wipe it (see the demo app).
32
+ */
33
+ declare function createMemoryStore(options?: MemoryStoreOptions): MemoryStore;
34
+
35
+ export { MemoryStore, createMemoryStore };
36
+ export type { MemoryStoreOptions };
package/dist/index.js ADDED
@@ -0,0 +1,97 @@
1
+ // src/index.ts
2
+ import {
3
+ applyEventToSummary,
4
+ decodeCursor,
5
+ emptySummary,
6
+ encodeCursor,
7
+ isAfterCursor,
8
+ SpeeqError
9
+ } from "@speeq/core";
10
+ var warned = false;
11
+ var MemoryStore = class {
12
+ kind = "memory";
13
+ sessions = /* @__PURE__ */ new Map();
14
+ constructor(options = {}) {
15
+ if (!options.quiet && !warned && isProduction()) {
16
+ warned = true;
17
+ console.warn(
18
+ "[speeq] @speeq/store-memory is for development and tests only. Data is lost on restart and is not shared between serverless instances."
19
+ );
20
+ }
21
+ }
22
+ async createSession(session) {
23
+ if (this.sessions.has(session.id))
24
+ throw new SpeeqError("CONFLICT", { message: "Session exists." });
25
+ this.sessions.set(session.id, {
26
+ summary: emptySummary(session),
27
+ events: [],
28
+ dedupeKeys: /* @__PURE__ */ new Set()
29
+ });
30
+ }
31
+ async appendEvents(sessionId, events) {
32
+ const entry = this.sessions.get(sessionId);
33
+ if (!entry) throw new SpeeqError("NOT_FOUND", { message: "Session not found." });
34
+ const keys = events.map((e) => e.dedupeKey).filter((k) => k !== void 0);
35
+ if (keys.some((k) => entry.dedupeKeys.has(k)) || new Set(keys).size !== keys.length) {
36
+ throw new SpeeqError("CONFLICT");
37
+ }
38
+ const stored = events.map(
39
+ (e, i) => ({ ...e, seq: entry.events.length + i })
40
+ );
41
+ for (const e of stored) {
42
+ entry.events.push(structuredClone(e));
43
+ entry.summary = applyEventToSummary(entry.summary, e);
44
+ }
45
+ for (const k of keys) entry.dedupeKeys.add(k);
46
+ return stored;
47
+ }
48
+ async listEvents(sessionId, options = {}) {
49
+ const all = this.sessions.get(sessionId)?.events ?? [];
50
+ let out = options.afterSeq === void 0 ? all : all.filter((e) => e.seq > (options.afterSeq ?? -1));
51
+ if (options.limit !== void 0) {
52
+ out = options.last ? out.slice(-options.limit) : out.slice(0, options.limit);
53
+ }
54
+ return structuredClone(out);
55
+ }
56
+ async listSessions(filter, cursor) {
57
+ const limit = filter.limit ?? 20;
58
+ const after = cursor ? decodeCursor(cursor) : null;
59
+ const matching = [...this.sessions.values()].map((e) => e.summary).filter((s) => filter.userId === void 0 || s.userId === filter.userId).filter((s) => filter.from === void 0 || s.startedAt >= filter.from).filter((s) => filter.to === void 0 || s.startedAt <= filter.to).filter((s) => after === null || isAfterCursor(s, after)).sort(
60
+ (a, b) => a.startedAt === b.startedAt ? a.id < b.id ? 1 : -1 : a.startedAt < b.startedAt ? 1 : -1
61
+ );
62
+ const page = matching.slice(0, limit);
63
+ const last = page.at(-1);
64
+ return {
65
+ sessions: structuredClone(page),
66
+ nextCursor: matching.length > limit && last ? encodeCursor(last.startedAt, last.id) : null
67
+ };
68
+ }
69
+ async getSessionSummary(sessionId) {
70
+ const s = this.sessions.get(sessionId)?.summary;
71
+ return s ? structuredClone(s) : null;
72
+ }
73
+ async deleteOlderThan(date) {
74
+ const cutoff = date.toISOString();
75
+ const result = { sessions: 0, events: 0 };
76
+ for (const [id, entry] of this.sessions) {
77
+ if (entry.summary.lastEventAt < cutoff) {
78
+ result.sessions += 1;
79
+ result.events += entry.events.length;
80
+ this.sessions.delete(id);
81
+ }
82
+ }
83
+ return result;
84
+ }
85
+ };
86
+ function createMemoryStore(options = {}) {
87
+ return new MemoryStore(options);
88
+ }
89
+ function isProduction() {
90
+ const g = globalThis;
91
+ return g.process?.env?.NODE_ENV === "production";
92
+ }
93
+ export {
94
+ MemoryStore,
95
+ createMemoryStore
96
+ };
97
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@speeq/store-memory`: a Map-based {@link ConversationStore} for development and tests.\n *\n * **Not for production or serverless.** Data lives in one process's memory: it is lost on\n * restart, and serverless platforms run many short-lived instances that do not share it.\n * Use `@speeq/store-mongodb` (or your own adapter) in production.\n * @packageDocumentation\n */\nimport {\n applyEventToSummary,\n type ConversationEvent,\n type ConversationStore,\n decodeCursor,\n emptySummary,\n encodeCursor,\n isAfterCursor,\n type ListEventsOptions,\n type NewConversationEvent,\n type NewSession,\n type RetentionResult,\n type SessionFilter,\n type SessionPage,\n type SessionSummary,\n SpeeqError,\n} from \"@speeq/core\";\n\n/** Options for {@link createMemoryStore}. */\nexport interface MemoryStoreOptions {\n /** Silence the one-time \"not for production\" warning. */\n quiet?: boolean;\n}\n\ninterface Entry {\n summary: SessionSummary;\n events: ConversationEvent[];\n dedupeKeys: Set<string>;\n}\n\nlet warned = false;\n\n/** An in-memory {@link ConversationStore}. See the package docs for its limits. */\nexport class MemoryStore implements ConversationStore {\n readonly kind = \"memory\";\n private readonly sessions = new Map<string, Entry>();\n\n constructor(options: MemoryStoreOptions = {}) {\n if (!options.quiet && !warned && isProduction()) {\n warned = true;\n console.warn(\n \"[speeq] @speeq/store-memory is for development and tests only. Data is lost on restart and is not shared between serverless instances.\",\n );\n }\n }\n\n async createSession(session: NewSession): Promise<void> {\n if (this.sessions.has(session.id))\n throw new SpeeqError(\"CONFLICT\", { message: \"Session exists.\" });\n this.sessions.set(session.id, {\n summary: emptySummary(session),\n events: [],\n dedupeKeys: new Set(),\n });\n }\n\n async appendEvents(\n sessionId: string,\n events: NewConversationEvent[],\n ): Promise<ConversationEvent[]> {\n const entry = this.sessions.get(sessionId);\n if (!entry) throw new SpeeqError(\"NOT_FOUND\", { message: \"Session not found.\" });\n const keys = events.map((e) => e.dedupeKey).filter((k): k is string => k !== undefined);\n if (keys.some((k) => entry.dedupeKeys.has(k)) || new Set(keys).size !== keys.length) {\n throw new SpeeqError(\"CONFLICT\");\n }\n const stored = events.map(\n (e, i) => ({ ...e, seq: entry.events.length + i }) as ConversationEvent,\n );\n for (const e of stored) {\n entry.events.push(structuredClone(e));\n entry.summary = applyEventToSummary(entry.summary, e);\n }\n for (const k of keys) entry.dedupeKeys.add(k);\n return stored;\n }\n\n async listEvents(\n sessionId: string,\n options: ListEventsOptions = {},\n ): Promise<ConversationEvent[]> {\n const all = this.sessions.get(sessionId)?.events ?? [];\n let out =\n options.afterSeq === undefined ? all : all.filter((e) => e.seq > (options.afterSeq ?? -1));\n if (options.limit !== undefined) {\n out = options.last ? out.slice(-options.limit) : out.slice(0, options.limit);\n }\n return structuredClone(out);\n }\n\n async listSessions(filter: SessionFilter, cursor?: string | null): Promise<SessionPage> {\n const limit = filter.limit ?? 20;\n const after = cursor ? decodeCursor(cursor) : null;\n const matching = [...this.sessions.values()]\n .map((e) => e.summary)\n .filter((s) => filter.userId === undefined || s.userId === filter.userId)\n .filter((s) => filter.from === undefined || s.startedAt >= filter.from)\n .filter((s) => filter.to === undefined || s.startedAt <= filter.to)\n .filter((s) => after === null || isAfterCursor(s, after))\n .sort((a, b) =>\n a.startedAt === b.startedAt ? (a.id < b.id ? 1 : -1) : a.startedAt < b.startedAt ? 1 : -1,\n );\n const page = matching.slice(0, limit);\n const last = page.at(-1);\n return {\n sessions: structuredClone(page),\n nextCursor: matching.length > limit && last ? encodeCursor(last.startedAt, last.id) : null,\n };\n }\n\n async getSessionSummary(sessionId: string): Promise<SessionSummary | null> {\n const s = this.sessions.get(sessionId)?.summary;\n return s ? structuredClone(s) : null;\n }\n\n async deleteOlderThan(date: Date): Promise<RetentionResult> {\n const cutoff = date.toISOString();\n const result: RetentionResult = { sessions: 0, events: 0 };\n for (const [id, entry] of this.sessions) {\n if (entry.summary.lastEventAt < cutoff) {\n result.sessions += 1;\n result.events += entry.events.length;\n this.sessions.delete(id);\n }\n }\n return result;\n }\n}\n\n/**\n * Creates an in-memory store. In Next.js dev mode, keep one instance on `globalThis` so hot\n * reloads do not wipe it (see the demo app).\n */\nexport function createMemoryStore(options: MemoryStoreOptions = {}): MemoryStore {\n return new MemoryStore(options);\n}\n\nfunction isProduction(): boolean {\n const g = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return g.process?.env?.NODE_ENV === \"production\";\n}\n"],"mappings":";AAQA;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAQA;AAAA,OACK;AAcP,IAAI,SAAS;AAGN,IAAM,cAAN,MAA+C;AAAA,EAC3C,OAAO;AAAA,EACC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I,SAAS,GAAG;AACxC,WAAO,IAAI,gBAAgB,CAAC,IAAI;AAAA,EAClC;AAAA,EAEA,MAAM,gBAAgB,MAAsC;AAC1D,UAAM,SAAS,KAAK,YAAY;AAChC,UAAM,SAA0B,EAAE,UAAU,GAAG,QAAQ,EAAE;AACzD,eAAW,CAAC,IAAI,KAAK,KAAK,KAAK,UAAU;AACvC,UAAI,MAAM,QAAQ,cAAc,QAAQ;AACtC,eAAO,YAAY;AACnB,eAAO,UAAU,MAAM,OAAO;AAC9B,aAAK,SAAS,OAAO,EAAE;AAAA,MACzB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAMO,SAAS,kBAAkB,UAA8B,CAAC,GAAgB;AAC/E,SAAO,IAAI,YAAY,OAAO;AAChC;AAEA,SAAS,eAAwB;AAC/B,QAAM,IAAI;AACV,SAAO,EAAE,SAAS,KAAK,aAAa;AACtC;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@speeq/store-memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "In-memory ConversationStore for speeq (development and tests only).",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Mudavath-Giri-Naik/speeq.git",
11
+ "directory": "packages/adapters/store-memory"
12
+ },
13
+ "homepage": "https://github.com/Mudavath-Giri-Naik/speeq#readme",
14
+ "keywords": [
15
+ "speeq",
16
+ "voice",
17
+ "agent",
18
+ "conversational-ai",
19
+ "headless"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md"
27
+ ],
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "@speeq/source": "./src/index.ts",
34
+ "import": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ },
38
+ "require": {
39
+ "types": "./dist/index.d.cts",
40
+ "default": "./dist/index.cjs"
41
+ }
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "dependencies": {
49
+ "@speeq/core": "0.2.0"
50
+ },
51
+ "devDependencies": {
52
+ "@speeq/tsconfig": "0.0.0",
53
+ "@speeq/testing": "0.2.0",
54
+ "zod": "4.6.7"
55
+ },
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "typecheck": "tsc --noEmit",
59
+ "test": "vitest run"
60
+ }
6
61
  }