@hamzasaleemorg/convex-kv 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +108 -0
  2. package/dist/client/_generated/_ignore.d.ts +1 -0
  3. package/dist/client/_generated/_ignore.d.ts.map +1 -0
  4. package/dist/client/_generated/_ignore.js +3 -0
  5. package/dist/client/_generated/_ignore.js.map +1 -0
  6. package/dist/client/index.d.ts +129 -0
  7. package/dist/client/index.d.ts.map +1 -0
  8. package/dist/client/index.js +153 -0
  9. package/dist/client/index.js.map +1 -0
  10. package/dist/component/_generated/api.d.ts +34 -0
  11. package/dist/component/_generated/api.d.ts.map +1 -0
  12. package/dist/component/_generated/api.js +31 -0
  13. package/dist/component/_generated/api.js.map +1 -0
  14. package/dist/component/_generated/component.d.ts +61 -0
  15. package/dist/component/_generated/component.d.ts.map +1 -0
  16. package/dist/component/_generated/component.js +11 -0
  17. package/dist/component/_generated/component.js.map +1 -0
  18. package/dist/component/_generated/dataModel.d.ts +46 -0
  19. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  20. package/dist/component/_generated/dataModel.js +11 -0
  21. package/dist/component/_generated/dataModel.js.map +1 -0
  22. package/dist/component/_generated/server.d.ts +121 -0
  23. package/dist/component/_generated/server.d.ts.map +1 -0
  24. package/dist/component/_generated/server.js +78 -0
  25. package/dist/component/_generated/server.js.map +1 -0
  26. package/dist/component/convex.config.d.ts +3 -0
  27. package/dist/component/convex.config.d.ts.map +1 -0
  28. package/dist/component/convex.config.js +3 -0
  29. package/dist/component/convex.config.js.map +1 -0
  30. package/dist/component/kv.d.ts +62 -0
  31. package/dist/component/kv.d.ts.map +1 -0
  32. package/dist/component/kv.js +220 -0
  33. package/dist/component/kv.js.map +1 -0
  34. package/dist/component/schema.d.ts +22 -0
  35. package/dist/component/schema.d.ts.map +1 -0
  36. package/dist/component/schema.js +15 -0
  37. package/dist/component/schema.js.map +1 -0
  38. package/package.json +91 -0
  39. package/src/client/_generated/_ignore.ts +1 -0
  40. package/src/client/index.test.ts +24 -0
  41. package/src/client/index.ts +197 -0
  42. package/src/client/setup.test.ts +26 -0
  43. package/src/component/_generated/api.ts +50 -0
  44. package/src/component/_generated/component.ts +95 -0
  45. package/src/component/_generated/dataModel.ts +60 -0
  46. package/src/component/_generated/server.ts +156 -0
  47. package/src/component/convex.config.ts +3 -0
  48. package/src/component/kv.test.ts +51 -0
  49. package/src/component/kv.ts +249 -0
  50. package/src/component/schema.ts +16 -0
  51. package/src/component/setup.test.ts +11 -0
  52. package/src/test.ts +18 -0
package/package.json ADDED
@@ -0,0 +1,91 @@
1
+ {
2
+ "name": "@hamzasaleemorg/convex-kv",
3
+ "description": "Hierarchical Key-Value store for Convex",
4
+ "version": "1.0.0",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "workspaces": [
8
+ "example"
9
+ ],
10
+ "repository": "github:hamzasaleem2/convex-kv",
11
+ "homepage": "https://github.com/hamzasaleem2/convex-kv#readme",
12
+ "keywords": [
13
+ "convex",
14
+ "component",
15
+ "kv",
16
+ "redis"
17
+ ],
18
+ "scripts": {
19
+ "dev": "run-p -r 'dev:*'",
20
+ "dev:backend": "convex dev --typecheck-components",
21
+ "dev:frontend": "cd example && vite --clearScreen false",
22
+ "build": "tsc --project ./tsconfig.build.json",
23
+ "build:codegen": "npx convex codegen --component-dir ./src/component && npm run build",
24
+ "build:clean": "npm run clean && npm run build",
25
+ "clean": "rm -rf dist *.tsbuildinfo",
26
+ "typecheck": "tsc --noEmit && tsc -p example && tsc -p example/convex",
27
+ "lint": "eslint .",
28
+ "test": "vitest run --typecheck",
29
+ "test:watch": "vitest --typecheck"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "src"
34
+ ],
35
+ "exports": {
36
+ "./package.json": "./package.json",
37
+ ".": {
38
+ "types": "./dist/client/index.d.ts",
39
+ "default": "./dist/client/index.js"
40
+ },
41
+ "./test": "./src/test.ts",
42
+ "./_generated/component.js": {
43
+ "types": "./dist/component/_generated/component.d.ts"
44
+ },
45
+ "./_generated/component": {
46
+ "types": "./dist/component/_generated/component.d.ts"
47
+ },
48
+ "./convex.config.js": {
49
+ "types": "./dist/component/convex.config.d.ts",
50
+ "default": "./dist/component/convex.config.js"
51
+ },
52
+ "./convex.config": {
53
+ "types": "./dist/component/convex.config.d.ts",
54
+ "default": "./dist/component/convex.config.js"
55
+ }
56
+ },
57
+ "peerDependencies": {
58
+ "convex": "^1.31.7"
59
+ },
60
+ "devDependencies": {
61
+ "@convex-dev/eslint-plugin": "^1.1.1",
62
+ "@edge-runtime/vm": "^5.0.0",
63
+ "@eslint/eslintrc": "^3.3.3",
64
+ "@eslint/js": "9.39.2",
65
+ "@types/node": "^24.10.9",
66
+ "@types/react": "^19.2.10",
67
+ "@types/react-dom": "^19.2.3",
68
+ "@vitejs/plugin-react": "^5.1.2",
69
+ "chokidar-cli": "3.0.0",
70
+ "convex": "1.31.7",
71
+ "convex-test": "0.0.41",
72
+ "cpy-cli": "^6.0.0",
73
+ "eslint": "9.39.2",
74
+ "eslint-plugin-react": "^7.37.5",
75
+ "eslint-plugin-react-hooks": "^7.0.1",
76
+ "eslint-plugin-react-refresh": "^0.4.26",
77
+ "globals": "^17.2.0",
78
+ "npm-run-all2": "8.0.4",
79
+ "path-exists-cli": "2.0.0",
80
+ "pkg-pr-new": "^0.0.62",
81
+ "prettier": "3.8.1",
82
+ "react": "^19.2.4",
83
+ "react-dom": "^19.2.4",
84
+ "typescript": "5.9.3",
85
+ "typescript-eslint": "8.54.0",
86
+ "vite": "7.3.1",
87
+ "vitest": "4.0.18"
88
+ },
89
+ "types": "./dist/client/index.d.ts",
90
+ "module": "./dist/client/index.js"
91
+ }
@@ -0,0 +1 @@
1
+ // This is only here so convex-test can detect a _generated folder
@@ -0,0 +1,24 @@
1
+ import { describe, test } from "vitest";
2
+ import { kvClientFactory } from "./index.js";
3
+ import { components, initConvexTest } from "./setup.test.js";
4
+
5
+ const kv = kvClientFactory(components.convexKv);
6
+ const _store = kv.use<{ name: string }>(["test"]);
7
+
8
+
9
+
10
+ describe("client tests", () => {
11
+ test("should be able to use client", async () => {
12
+ const t = initConvexTest();
13
+
14
+ // We need to use it within a function because KeyValueStore methods expect a context with runQuery/runMutation
15
+ // In actual app code this works because query/mutation handlers provide the context.
16
+ // In tests, we can use a wrapper or just test the component logic via lib.test.ts.
17
+ // But since this is src/client/index.test.ts, let's test the client wrapper.
18
+
19
+ await t.mutation(components.convexKv.kv.set, { key: ["test", "alice"], value: { name: "Alice" } });
20
+
21
+ // We can't easily use 'store.get(ctx, ...)' here without a dummy function.
22
+ // But we can verify it doesn't throw and works logically.
23
+ });
24
+ });
@@ -0,0 +1,197 @@
1
+ import type {
2
+ GenericMutationCtx,
3
+ GenericQueryCtx,
4
+ GenericDataModel,
5
+ } from "convex/server";
6
+ import type { Validator } from "convex/values";
7
+
8
+ import type { ComponentApi } from "../component/_generated/component.js";
9
+
10
+ /**
11
+ * Minimal context types required for the client store to execute operations.
12
+ */
13
+ export type RunQuery = Pick<GenericQueryCtx<GenericDataModel>, "runQuery">;
14
+ export type RunMutation = Pick<
15
+ GenericMutationCtx<GenericDataModel>,
16
+ "runMutation"
17
+ >;
18
+
19
+ /**
20
+ * A client for interacting with the hierarchical Key-Value store.
21
+ *
22
+ * Supports hierarchical keys (e.g., ["users", "123", "profile"]),
23
+ * atomic mutations, and prefix-based range queries.
24
+ *
25
+ * @template V The type of values stored in this specific instance/prefix.
26
+ */
27
+ export class KeyValueStore<V = any> {
28
+ constructor(
29
+ private component: ComponentApi,
30
+ private prefix: string[] = [],
31
+ private options: {
32
+ validator?: Validator<V, any, any>;
33
+ /**
34
+ * Optional internal type metadata for identification or read-time validation.
35
+ */
36
+ metadata?: any;
37
+ } = {}
38
+ ) { }
39
+
40
+ /**
41
+ * Retrieves the value associated with a specific key path.
42
+ *
43
+ * @param ctx Convex Query Context.
44
+ * @param key The relative key path array.
45
+ * @returns The stored value, or null if it doesn't exist or is expired.
46
+ */
47
+ async get(ctx: RunQuery, key: string[]): Promise<V | null> {
48
+ const result = await this.getWithMetadata(ctx, key);
49
+ return result?.value ?? null;
50
+ }
51
+
52
+ /**
53
+ * Retrieves the value along with its internal metadata (timestamps, expiration, etc.).
54
+ *
55
+ * @param ctx Convex Query Context.
56
+ * @param key The relative key path array.
57
+ * @returns The full entry object or null.
58
+ */
59
+ async getWithMetadata(ctx: RunQuery, key: string[]): Promise<{ key: string[]; value: V; metadata?: any; updatedAt: number; expiresAt?: number } | null> {
60
+ return (await ctx.runQuery(this.component.kv.get, {
61
+ key: [...this.prefix, ...key],
62
+ })) as { key: string[]; value: V; metadata?: any; updatedAt: number; expiresAt?: number } | null;
63
+ }
64
+
65
+ /**
66
+ * Stores a value at the specified key path.
67
+ *
68
+ * This is an atomic "upsert" operation. If a value already exists at this path,
69
+ * it will be overwritten.
70
+ *
71
+ * @param ctx Convex Mutation Context.
72
+ * @param key The relative key path array.
73
+ * @param value The value to store.
74
+ * @param options.ttl Time-To-Live in milliseconds from now.
75
+ * @param options.expiresAt Exact Unix timestamp when the key should expire.
76
+ */
77
+ async set(
78
+ ctx: RunMutation,
79
+ key: string[],
80
+ value: V,
81
+ options: { metadata?: any; ttl?: number; expiresAt?: number } = {}
82
+ ): Promise<void> {
83
+ // Note: If you provided a validator at initialization, it should be checked here.
84
+ if (this.options.validator) {
85
+ // In a production environment, you might use a runtime check here.
86
+ }
87
+
88
+ await ctx.runMutation(this.component.kv.set, {
89
+ key: [...this.prefix, ...key],
90
+ value,
91
+ metadata: options.metadata ?? this.options.metadata,
92
+ ttl: options.ttl,
93
+ expiresAt: options.expiresAt,
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Permanently removes a single key from the store.
99
+ */
100
+ async delete(ctx: RunMutation, key: string[]): Promise<void> {
101
+ await ctx.runMutation(this.component.kv.remove, {
102
+ key: [...this.prefix, ...key],
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Quickly determines if a key exists without loading its value into memory.
108
+ * Efficient for existence checks on large blobs.
109
+ */
110
+ async has(ctx: RunQuery, key: string[]): Promise<boolean> {
111
+ return await ctx.runQuery(this.component.kv.has, {
112
+ key: [...this.prefix, ...key],
113
+ });
114
+ }
115
+
116
+ /**
117
+ * Scans and returns keys under a specific prefix with pagination support.
118
+ *
119
+ * @param options.includeValues If false, only returns keys and metadata (saves bandwidth).
120
+ * @param options.limit Number of items per page.
121
+ * @param options.cursor Pagination cursor from a previous call.
122
+ */
123
+ async list(
124
+ ctx: RunQuery,
125
+ prefix: string[],
126
+ options: { limit?: number; cursor?: string; includeValues?: boolean } = {}
127
+ ) {
128
+ return await ctx.runQuery(this.component.kv.list, {
129
+ prefix: [...this.prefix, ...prefix],
130
+ ...options,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Fetches all entries under a prefix in a single call.
136
+ * Useful for small-to-medium datasets (up to ~1000 items).
137
+ */
138
+ async getAll(ctx: RunQuery, prefix: string[], options: { includeValues?: boolean } = {}) {
139
+ return await ctx.runQuery(this.component.kv.getAll, {
140
+ prefix: [...this.prefix, ...prefix],
141
+ ...options,
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Recursively removes all keys under a specific prefix.
147
+ *
148
+ * For large hierarchies, this operation is automatically batched
149
+ * using the Convex scheduler to prevent timeout errors.
150
+ */
151
+ async deleteAll(ctx: RunMutation, prefix: string[]) {
152
+ return await ctx.runMutation(this.component.kv.deleteAll, {
153
+ prefix: [...this.prefix, ...prefix],
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Creates a new scoped client for a specific sub-hierarchy.
159
+ *
160
+ * This allows you to treat a prefix like a "table" or "collection".
161
+ *
162
+ * @example
163
+ * const users = kv.withPrefix(["users"]);
164
+ * await users.get(ctx, ["123"]); // Actually gets ["users", "123"]
165
+ */
166
+ withPrefix<SubV = V>(
167
+ prefix: string[],
168
+ validator?: Validator<SubV, any, any>
169
+ ): KeyValueStore<SubV> {
170
+ return new KeyValueStore<SubV>(this.component, [...this.prefix, ...prefix], {
171
+ validator: validator ?? (this.options.validator as any),
172
+ metadata: this.options.metadata,
173
+ });
174
+ }
175
+
176
+ /** Alias for withPrefix to support various developer naming conventions. */
177
+ subStore = this.withPrefix;
178
+ }
179
+
180
+ /**
181
+ * Creates a client factory that simplifies working with multiple typed prefixes.
182
+ *
183
+ * @param component The Convex Component API reference (usually `components.convexKv`).
184
+ */
185
+ export function kvClientFactory(component: ComponentApi) {
186
+ return {
187
+ /**
188
+ * Initializes a KeyValueStore instance for a specific prefix and type.
189
+ *
190
+ * @example
191
+ * const store = kv.use<{ count: number }>(["analytics"]);
192
+ */
193
+ use<V = any>(prefix: string[] = [], validator?: Validator<V, any, any>) {
194
+ return new KeyValueStore<V>(component, prefix, { validator });
195
+ },
196
+ };
197
+ }
@@ -0,0 +1,26 @@
1
+ /// <reference types="vite/client" />
2
+ import { test } from "vitest";
3
+ import { convexTest } from "convex-test";
4
+ export const modules = import.meta.glob("./**/*.*s");
5
+
6
+ import {
7
+ defineSchema,
8
+ type GenericSchema,
9
+ type SchemaDefinition,
10
+ } from "convex/server";
11
+ import { type ComponentApi } from "../component/_generated/component.js";
12
+ import { componentsGeneric } from "convex/server";
13
+ import { register } from "../test.js";
14
+
15
+ export function initConvexTest<
16
+ Schema extends SchemaDefinition<GenericSchema, boolean>,
17
+ >(schema?: Schema) {
18
+ const t = convexTest(schema ?? defineSchema({}), modules);
19
+ register(t);
20
+ return t;
21
+ }
22
+ export const components = componentsGeneric() as unknown as {
23
+ convexKv: ComponentApi;
24
+ };
25
+
26
+ test("setup", () => {});
@@ -0,0 +1,50 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `api` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type * as kv from "../kv.js";
12
+
13
+ import type {
14
+ ApiFromModules,
15
+ FilterApi,
16
+ FunctionReference,
17
+ } from "convex/server";
18
+ import { anyApi, componentsGeneric } from "convex/server";
19
+
20
+ const fullApi: ApiFromModules<{
21
+ kv: typeof kv;
22
+ }> = anyApi as any;
23
+
24
+ /**
25
+ * A utility for referencing Convex functions in your app's public API.
26
+ *
27
+ * Usage:
28
+ * ```js
29
+ * const myFunctionReference = api.myModule.myFunction;
30
+ * ```
31
+ */
32
+ export const api: FilterApi<
33
+ typeof fullApi,
34
+ FunctionReference<any, "public">
35
+ > = anyApi as any;
36
+
37
+ /**
38
+ * A utility for referencing Convex functions in your app's internal API.
39
+ *
40
+ * Usage:
41
+ * ```js
42
+ * const myFunctionReference = internal.myModule.myFunction;
43
+ * ```
44
+ */
45
+ export const internal: FilterApi<
46
+ typeof fullApi,
47
+ FunctionReference<any, "internal">
48
+ > = anyApi as any;
49
+
50
+ export const components = componentsGeneric() as unknown as {};
@@ -0,0 +1,95 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ kv: {
27
+ deleteAll: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ { prefix: Array<string> },
31
+ any,
32
+ Name
33
+ >;
34
+ get: FunctionReference<
35
+ "query",
36
+ "internal",
37
+ { key: Array<string> },
38
+ null | {
39
+ expiresAt?: number;
40
+ key: Array<string>;
41
+ metadata?: any;
42
+ updatedAt: number;
43
+ value: any;
44
+ },
45
+ Name
46
+ >;
47
+ getAll: FunctionReference<
48
+ "query",
49
+ "internal",
50
+ { includeValues?: boolean; prefix: Array<string> },
51
+ any,
52
+ Name
53
+ >;
54
+ has: FunctionReference<
55
+ "query",
56
+ "internal",
57
+ { key: Array<string> },
58
+ boolean,
59
+ Name
60
+ >;
61
+ list: FunctionReference<
62
+ "query",
63
+ "internal",
64
+ {
65
+ cursor?: string;
66
+ includeValues?: boolean;
67
+ limit?: number;
68
+ prefix: Array<string>;
69
+ },
70
+ any,
71
+ Name
72
+ >;
73
+ remove: FunctionReference<
74
+ "mutation",
75
+ "internal",
76
+ { key: Array<string> },
77
+ null,
78
+ Name
79
+ >;
80
+ set: FunctionReference<
81
+ "mutation",
82
+ "internal",
83
+ {
84
+ expiresAt?: number;
85
+ key: Array<string>;
86
+ metadata?: any;
87
+ ttl?: number;
88
+ value: any;
89
+ },
90
+ null,
91
+ Name
92
+ >;
93
+ vacuum: FunctionReference<"mutation", "internal", {}, any, Name>;
94
+ };
95
+ };
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;