@vllnt/convex-progression 0.1.0-canary.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/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +144 -0
- package/dist/client/index.d.ts +61 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +64 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +20 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +3 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +40 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +82 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +133 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +80 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +4 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/mutations.d.ts +43 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +179 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +14 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +45 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +32 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +21 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validation.d.ts +4 -0
- package/dist/component/validation.d.ts.map +1 -0
- package/dist/component/validation.js +22 -0
- package/dist/component/validation.js.map +1 -0
- package/dist/component/validators.d.ts +52 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +20 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +36 -0
- package/dist/shared.js.map +1 -0
- package/docs/API.md +69 -0
- package/llms-full.txt +930 -0
- package/llms.txt +35 -0
- package/package.json +92 -0
- package/src/client/index.ts +191 -0
- package/src/client/types.ts +23 -0
- package/src/component/_generated/api.ts +56 -0
- package/src/component/_generated/component.ts +107 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +169 -0
- package/src/component/convex.config.ts +5 -0
- package/src/component/mutations.ts +205 -0
- package/src/component/queries.ts +50 -0
- package/src/component/schema.ts +21 -0
- package/src/component/validation.ts +30 -0
- package/src/component/validators.ts +23 -0
- package/src/shared.ts +47 -0
- package/src/test.ts +15 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated utilities for implementing server-side Convex query and mutation functions.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ActionBuilder,
|
|
13
|
+
HttpActionBuilder,
|
|
14
|
+
MutationBuilder,
|
|
15
|
+
QueryBuilder,
|
|
16
|
+
GenericActionCtx,
|
|
17
|
+
GenericMutationCtx,
|
|
18
|
+
GenericQueryCtx,
|
|
19
|
+
GenericDatabaseReader,
|
|
20
|
+
GenericDatabaseWriter,
|
|
21
|
+
} from "convex/server";
|
|
22
|
+
import {
|
|
23
|
+
actionGeneric,
|
|
24
|
+
httpActionGeneric,
|
|
25
|
+
queryGeneric,
|
|
26
|
+
mutationGeneric,
|
|
27
|
+
internalActionGeneric,
|
|
28
|
+
internalMutationGeneric,
|
|
29
|
+
internalQueryGeneric,
|
|
30
|
+
} from "convex/server";
|
|
31
|
+
import type { DataModel } from "./dataModel.js";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Typesafe environment variables.
|
|
35
|
+
*
|
|
36
|
+
* This includes platform-provided env vars and any variables declared in
|
|
37
|
+
* `convex.config.ts`.
|
|
38
|
+
*/
|
|
39
|
+
type Env = {
|
|
40
|
+
readonly CONVEX_CLOUD_URL: string;
|
|
41
|
+
readonly CONVEX_SITE_URL: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Define a query in this Convex app's public API.
|
|
46
|
+
*
|
|
47
|
+
* This function will be allowed to read your Convex database and will be accessible from the client.
|
|
48
|
+
*
|
|
49
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
50
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
51
|
+
*/
|
|
52
|
+
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Define a query that is only accessible from other Convex functions (but not from the client).
|
|
56
|
+
*
|
|
57
|
+
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
|
|
58
|
+
*
|
|
59
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
60
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
61
|
+
*/
|
|
62
|
+
export const internalQuery: QueryBuilder<DataModel, "internal"> =
|
|
63
|
+
internalQueryGeneric;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Define a mutation in this Convex app's public API.
|
|
67
|
+
*
|
|
68
|
+
* This function will be allowed to modify your Convex database and will be accessible from the client.
|
|
69
|
+
*
|
|
70
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
71
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
72
|
+
*/
|
|
73
|
+
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Define a mutation that is only accessible from other Convex functions (but not from the client).
|
|
77
|
+
*
|
|
78
|
+
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
|
|
79
|
+
*
|
|
80
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
81
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
82
|
+
*/
|
|
83
|
+
export const internalMutation: MutationBuilder<DataModel, "internal"> =
|
|
84
|
+
internalMutationGeneric;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Define an action in this Convex app's public API.
|
|
88
|
+
*
|
|
89
|
+
* An action is a function which can execute any JavaScript code, including non-deterministic
|
|
90
|
+
* code and code with side-effects, like calling third-party services.
|
|
91
|
+
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
|
|
92
|
+
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
|
|
93
|
+
*
|
|
94
|
+
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
|
|
95
|
+
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
|
|
96
|
+
*/
|
|
97
|
+
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Define an action that is only accessible from other Convex functions (but not from the client).
|
|
101
|
+
*
|
|
102
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
|
|
103
|
+
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
|
|
104
|
+
*/
|
|
105
|
+
export const internalAction: ActionBuilder<DataModel, "internal"> =
|
|
106
|
+
internalActionGeneric;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Define an HTTP action.
|
|
110
|
+
*
|
|
111
|
+
* The wrapped function will be used to respond to HTTP requests received
|
|
112
|
+
* by a Convex deployment if the requests matches the path and method where
|
|
113
|
+
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
|
|
114
|
+
*
|
|
115
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument
|
|
116
|
+
* and a Fetch API `Request` object as its second.
|
|
117
|
+
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
|
|
118
|
+
*/
|
|
119
|
+
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
120
|
+
export const env: Env = (globalThis as unknown as { process: { env: Env } })
|
|
121
|
+
.process.env;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A set of services for use within Convex query functions.
|
|
125
|
+
*
|
|
126
|
+
* The query context is passed as the first argument to any Convex query
|
|
127
|
+
* function run on the server.
|
|
128
|
+
*
|
|
129
|
+
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
|
|
130
|
+
*/
|
|
131
|
+
export type QueryCtx = GenericQueryCtx<DataModel>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A set of services for use within Convex mutation functions.
|
|
135
|
+
*
|
|
136
|
+
* The mutation context is passed as the first argument to any Convex mutation
|
|
137
|
+
* function run on the server.
|
|
138
|
+
*
|
|
139
|
+
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
|
|
140
|
+
*/
|
|
141
|
+
export type MutationCtx = GenericMutationCtx<DataModel>;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A set of services for use within Convex action functions.
|
|
145
|
+
*
|
|
146
|
+
* The action context is passed as the first argument to any Convex action
|
|
147
|
+
* function run on the server.
|
|
148
|
+
*/
|
|
149
|
+
export type ActionCtx = GenericActionCtx<DataModel>;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* An interface to read from the database within Convex query functions.
|
|
153
|
+
*
|
|
154
|
+
* The two entry points are {@link DatabaseReader.get}, which fetches a single
|
|
155
|
+
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
|
|
156
|
+
* building a query.
|
|
157
|
+
*/
|
|
158
|
+
export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* An interface to read from and write to the database within Convex mutation
|
|
162
|
+
* functions.
|
|
163
|
+
*
|
|
164
|
+
* Convex guarantees that all writes within a single mutation are
|
|
165
|
+
* executed atomically, so you never have to worry about partial writes leaving
|
|
166
|
+
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
|
|
167
|
+
* for the guarantees Convex provides your functions.
|
|
168
|
+
*/
|
|
169
|
+
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
|
|
3
|
+
import { DEFAULT_ERASE_BATCH, levelForXp, MAX_ERASE_BATCH } from "../shared";
|
|
4
|
+
|
|
5
|
+
import { api } from "./_generated/api";
|
|
6
|
+
import { mutation } from "./_generated/server";
|
|
7
|
+
import { fail, parseThresholds, requireRef } from "./validation";
|
|
8
|
+
import { accrueResult, activityResult } from "./validators";
|
|
9
|
+
|
|
10
|
+
export const accrue = mutation({
|
|
11
|
+
args: {
|
|
12
|
+
delta: v.number(),
|
|
13
|
+
key: v.string(),
|
|
14
|
+
scope: v.string(),
|
|
15
|
+
subjectRef: v.string(),
|
|
16
|
+
thresholds: v.array(v.number()),
|
|
17
|
+
},
|
|
18
|
+
// Keep each atomic transaction readable as one handler.
|
|
19
|
+
// eslint-disable-next-line max-lines-per-function
|
|
20
|
+
handler: async (ctx, arguments_) => {
|
|
21
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
22
|
+
requireRef(arguments_.key, "key");
|
|
23
|
+
requireRef(arguments_.scope, "scope");
|
|
24
|
+
if (
|
|
25
|
+
!Number.isFinite(arguments_.delta) ||
|
|
26
|
+
arguments_.delta <= 0 ||
|
|
27
|
+
arguments_.delta > Number.MAX_SAFE_INTEGER
|
|
28
|
+
) {
|
|
29
|
+
fail(
|
|
30
|
+
"INVALID_DELTA",
|
|
31
|
+
"delta must be positive and at most MAX_SAFE_INTEGER",
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
const thresholds = parseThresholds(arguments_.thresholds);
|
|
35
|
+
const existing = await ctx.db
|
|
36
|
+
.query("progress")
|
|
37
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
38
|
+
q
|
|
39
|
+
.eq("scope", arguments_.scope)
|
|
40
|
+
.eq("subjectRef", arguments_.subjectRef)
|
|
41
|
+
.eq("key", arguments_.key),
|
|
42
|
+
)
|
|
43
|
+
.unique();
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
const previousLevel = existing?.level ?? 0;
|
|
46
|
+
const xp = (existing?.xp ?? 0) + arguments_.delta;
|
|
47
|
+
if (
|
|
48
|
+
!Number.isFinite(xp) ||
|
|
49
|
+
xp > Number.MAX_SAFE_INTEGER ||
|
|
50
|
+
xp <= (existing?.xp ?? 0)
|
|
51
|
+
) {
|
|
52
|
+
fail(
|
|
53
|
+
"XP_OVERFLOW",
|
|
54
|
+
"XP exceeds the safe bound or delta is lost to floating-point precision",
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const level = levelForXp(xp, thresholds);
|
|
58
|
+
const row = {
|
|
59
|
+
lastPeriodKey: existing?.lastPeriodKey,
|
|
60
|
+
level,
|
|
61
|
+
maxStreak: existing?.maxStreak ?? 0,
|
|
62
|
+
streak: existing?.streak ?? 0,
|
|
63
|
+
updatedAt: now,
|
|
64
|
+
xp,
|
|
65
|
+
};
|
|
66
|
+
await (existing === null
|
|
67
|
+
? ctx.db.insert("progress", {
|
|
68
|
+
key: arguments_.key,
|
|
69
|
+
scope: arguments_.scope,
|
|
70
|
+
subjectRef: arguments_.subjectRef,
|
|
71
|
+
...row,
|
|
72
|
+
})
|
|
73
|
+
: ctx.db.patch("progress", existing._id, row));
|
|
74
|
+
return { ...row, leveledUp: level > previousLevel, previousLevel };
|
|
75
|
+
},
|
|
76
|
+
returns: accrueResult,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
export const recordActivity = mutation({
|
|
80
|
+
args: {
|
|
81
|
+
expectedPrevious: v.optional(v.string()),
|
|
82
|
+
key: v.string(),
|
|
83
|
+
periodKey: v.string(),
|
|
84
|
+
scope: v.string(),
|
|
85
|
+
subjectRef: v.string(),
|
|
86
|
+
thresholds: v.array(v.number()),
|
|
87
|
+
},
|
|
88
|
+
// Keep each atomic transaction readable as one handler.
|
|
89
|
+
// eslint-disable-next-line max-lines-per-function
|
|
90
|
+
handler: async (ctx, arguments_) => {
|
|
91
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
92
|
+
requireRef(arguments_.key, "key");
|
|
93
|
+
requireRef(arguments_.scope, "scope");
|
|
94
|
+
requireRef(arguments_.periodKey, "periodKey");
|
|
95
|
+
if (arguments_.expectedPrevious !== undefined) {
|
|
96
|
+
requireRef(arguments_.expectedPrevious, "expectedPrevious");
|
|
97
|
+
}
|
|
98
|
+
const thresholds = parseThresholds(arguments_.thresholds);
|
|
99
|
+
const existing = await ctx.db
|
|
100
|
+
.query("progress")
|
|
101
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
102
|
+
q
|
|
103
|
+
.eq("scope", arguments_.scope)
|
|
104
|
+
.eq("subjectRef", arguments_.subjectRef)
|
|
105
|
+
.eq("key", arguments_.key),
|
|
106
|
+
)
|
|
107
|
+
.unique();
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
const xp = existing?.xp ?? 0;
|
|
110
|
+
const lastPeriodKey = existing?.lastPeriodKey;
|
|
111
|
+
const samePeriod = lastPeriodKey === arguments_.periodKey;
|
|
112
|
+
const consecutive =
|
|
113
|
+
lastPeriodKey !== undefined &&
|
|
114
|
+
lastPeriodKey === arguments_.expectedPrevious;
|
|
115
|
+
const continuedStreak =
|
|
116
|
+
consecutive && existing !== null ? existing.streak + 1 : 1;
|
|
117
|
+
const streak =
|
|
118
|
+
samePeriod && existing !== null ? existing.streak : continuedStreak;
|
|
119
|
+
if (!Number.isSafeInteger(streak)) {
|
|
120
|
+
fail("STREAK_OVERFLOW", "streak exceeds MAX_SAFE_INTEGER");
|
|
121
|
+
}
|
|
122
|
+
const streakDelta = samePeriod ? 0 : 1;
|
|
123
|
+
const row = {
|
|
124
|
+
lastPeriodKey: arguments_.periodKey,
|
|
125
|
+
level: levelForXp(xp, thresholds),
|
|
126
|
+
maxStreak: Math.max(existing?.maxStreak ?? 0, streak),
|
|
127
|
+
streak,
|
|
128
|
+
updatedAt: now,
|
|
129
|
+
xp,
|
|
130
|
+
};
|
|
131
|
+
await (existing === null
|
|
132
|
+
? ctx.db.insert("progress", {
|
|
133
|
+
key: arguments_.key,
|
|
134
|
+
scope: arguments_.scope,
|
|
135
|
+
subjectRef: arguments_.subjectRef,
|
|
136
|
+
...row,
|
|
137
|
+
})
|
|
138
|
+
: ctx.db.patch("progress", existing._id, row));
|
|
139
|
+
return { ...row, streakDelta };
|
|
140
|
+
},
|
|
141
|
+
returns: activityResult,
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
export const reset = mutation({
|
|
145
|
+
args: {
|
|
146
|
+
key: v.string(),
|
|
147
|
+
scope: v.string(),
|
|
148
|
+
subjectRef: v.string(),
|
|
149
|
+
},
|
|
150
|
+
handler: async (ctx, arguments_) => {
|
|
151
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
152
|
+
requireRef(arguments_.key, "key");
|
|
153
|
+
requireRef(arguments_.scope, "scope");
|
|
154
|
+
const existing = await ctx.db
|
|
155
|
+
.query("progress")
|
|
156
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
157
|
+
q
|
|
158
|
+
.eq("scope", arguments_.scope)
|
|
159
|
+
.eq("subjectRef", arguments_.subjectRef)
|
|
160
|
+
.eq("key", arguments_.key),
|
|
161
|
+
)
|
|
162
|
+
.unique();
|
|
163
|
+
if (existing !== null) {
|
|
164
|
+
await ctx.db.delete("progress", existing._id);
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
},
|
|
168
|
+
returns: v.null(),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
export const eraseSubject = mutation({
|
|
172
|
+
args: {
|
|
173
|
+
batch: v.optional(v.number()),
|
|
174
|
+
scope: v.string(),
|
|
175
|
+
subjectRef: v.string(),
|
|
176
|
+
},
|
|
177
|
+
handler: async (ctx, arguments_) => {
|
|
178
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
179
|
+
requireRef(arguments_.scope, "scope");
|
|
180
|
+
const raw = arguments_.batch ?? DEFAULT_ERASE_BATCH;
|
|
181
|
+
if (!Number.isInteger(raw)) {
|
|
182
|
+
fail("INVALID_BATCH", "batch must be a positive integer");
|
|
183
|
+
}
|
|
184
|
+
if (raw < 1) {
|
|
185
|
+
fail("INVALID_BATCH", "batch must be a positive integer");
|
|
186
|
+
}
|
|
187
|
+
const batch = Math.min(raw, MAX_ERASE_BATCH);
|
|
188
|
+
const rows = await ctx.db
|
|
189
|
+
.query("progress")
|
|
190
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
191
|
+
q.eq("scope", arguments_.scope).eq("subjectRef", arguments_.subjectRef),
|
|
192
|
+
)
|
|
193
|
+
.take(batch);
|
|
194
|
+
await Promise.all(rows.map((row) => ctx.db.delete("progress", row._id)));
|
|
195
|
+
if (rows.length === batch) {
|
|
196
|
+
await ctx.scheduler.runAfter(0, api.mutations.eraseSubject, {
|
|
197
|
+
batch,
|
|
198
|
+
scope: arguments_.scope,
|
|
199
|
+
subjectRef: arguments_.subjectRef,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return rows.length;
|
|
203
|
+
},
|
|
204
|
+
returns: v.number(),
|
|
205
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
|
|
3
|
+
import { levelForXp } from "../shared";
|
|
4
|
+
|
|
5
|
+
import { query } from "./_generated/server";
|
|
6
|
+
import { parseThresholds, requireRef } from "./validation";
|
|
7
|
+
import { progressState } from "./validators";
|
|
8
|
+
|
|
9
|
+
export const get = query({
|
|
10
|
+
args: {
|
|
11
|
+
key: v.string(),
|
|
12
|
+
scope: v.string(),
|
|
13
|
+
subjectRef: v.string(),
|
|
14
|
+
thresholds: v.optional(v.array(v.number())),
|
|
15
|
+
},
|
|
16
|
+
// Keep boundary validation and indexed read together.
|
|
17
|
+
// eslint-disable-next-line max-lines-per-function
|
|
18
|
+
handler: async (ctx, arguments_) => {
|
|
19
|
+
requireRef(arguments_.subjectRef, "subjectRef");
|
|
20
|
+
requireRef(arguments_.key, "key");
|
|
21
|
+
requireRef(arguments_.scope, "scope");
|
|
22
|
+
if (arguments_.thresholds !== undefined) {
|
|
23
|
+
parseThresholds(arguments_.thresholds);
|
|
24
|
+
}
|
|
25
|
+
const row = await ctx.db
|
|
26
|
+
.query("progress")
|
|
27
|
+
.withIndex("by_scope_subject_key", (q) =>
|
|
28
|
+
q
|
|
29
|
+
.eq("scope", arguments_.scope)
|
|
30
|
+
.eq("subjectRef", arguments_.subjectRef)
|
|
31
|
+
.eq("key", arguments_.key),
|
|
32
|
+
)
|
|
33
|
+
.unique();
|
|
34
|
+
if (row === null) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
lastPeriodKey: row.lastPeriodKey,
|
|
39
|
+
level:
|
|
40
|
+
arguments_.thresholds === undefined
|
|
41
|
+
? row.level
|
|
42
|
+
: levelForXp(row.xp, arguments_.thresholds),
|
|
43
|
+
maxStreak: row.maxStreak,
|
|
44
|
+
streak: row.streak,
|
|
45
|
+
updatedAt: row.updatedAt,
|
|
46
|
+
xp: row.xp,
|
|
47
|
+
};
|
|
48
|
+
},
|
|
49
|
+
returns: v.union(v.null(), progressState),
|
|
50
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { defineSchema, defineTable } from "convex/server";
|
|
2
|
+
import { v } from "convex/values";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Sandboxed tables — XP / level / streak per opaque `(scope, subjectRef, key)`.
|
|
6
|
+
* Thresholds are host-supplied on each write so the component never stores a
|
|
7
|
+
* domain-shaped definition table.
|
|
8
|
+
*/
|
|
9
|
+
export default defineSchema({
|
|
10
|
+
progress: defineTable({
|
|
11
|
+
key: v.string(),
|
|
12
|
+
lastPeriodKey: v.optional(v.string()),
|
|
13
|
+
level: v.number(),
|
|
14
|
+
maxStreak: v.number(),
|
|
15
|
+
scope: v.string(),
|
|
16
|
+
streak: v.number(),
|
|
17
|
+
subjectRef: v.string(),
|
|
18
|
+
updatedAt: v.number(),
|
|
19
|
+
xp: v.number(),
|
|
20
|
+
}).index("by_scope_subject_key", ["scope", "subjectRef", "key"]),
|
|
21
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ConvexError } from "convex/values";
|
|
2
|
+
|
|
3
|
+
import { assertThresholds, MAX_REF_LENGTH } from "../shared";
|
|
4
|
+
|
|
5
|
+
export function fail(code: string, message: string): never {
|
|
6
|
+
throw new ConvexError({ code, message });
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function requireRef(value: string, name: string): void {
|
|
10
|
+
if (value.length === 0 || value.length > MAX_REF_LENGTH) {
|
|
11
|
+
fail(
|
|
12
|
+
"INVALID_REF",
|
|
13
|
+
`${name} must be 1..${String(MAX_REF_LENGTH)} characters`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function parseThresholds(thresholds: number[]): number[] {
|
|
19
|
+
try {
|
|
20
|
+
assertThresholds(thresholds);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
fail(
|
|
23
|
+
"INVALID_THRESHOLDS",
|
|
24
|
+
String(error)
|
|
25
|
+
.replace(/^Error:\s*/, "")
|
|
26
|
+
.replace(/^INVALID_THRESHOLDS:\s*/, ""),
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return thresholds;
|
|
30
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
|
|
3
|
+
const progressFields = {
|
|
4
|
+
lastPeriodKey: v.optional(v.string()),
|
|
5
|
+
level: v.number(),
|
|
6
|
+
maxStreak: v.number(),
|
|
7
|
+
streak: v.number(),
|
|
8
|
+
updatedAt: v.number(),
|
|
9
|
+
xp: v.number(),
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const progressState = v.object(progressFields);
|
|
13
|
+
|
|
14
|
+
export const accrueResult = v.object({
|
|
15
|
+
...progressFields,
|
|
16
|
+
leveledUp: v.boolean(),
|
|
17
|
+
previousLevel: v.number(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export const activityResult = v.object({
|
|
21
|
+
...progressFields,
|
|
22
|
+
streakDelta: v.number(),
|
|
23
|
+
});
|
package/src/shared.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Shared constants used by both `client/` and `component/`. */
|
|
2
|
+
|
|
3
|
+
export const COMPONENT_NAME = "progression";
|
|
4
|
+
|
|
5
|
+
/** Default namespace when the host does not scope progress. */
|
|
6
|
+
export const DEFAULT_SCOPE = "global";
|
|
7
|
+
|
|
8
|
+
export const MAX_REF_LENGTH = 256;
|
|
9
|
+
export const DEFAULT_ERASE_BATCH = 200;
|
|
10
|
+
export const MAX_ERASE_BATCH = 500;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Level is the count of thresholds the current XP has reached.
|
|
14
|
+
* `thresholds` must be strictly increasing non-negative numbers.
|
|
15
|
+
*/
|
|
16
|
+
export function levelForXp(xp: number, thresholds: readonly number[]): number {
|
|
17
|
+
return thresholds.reduce((level, threshold) => {
|
|
18
|
+
return xp >= threshold ? level + 1 : level;
|
|
19
|
+
}, 0);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function assertThresholds(thresholds: readonly number[]): void {
|
|
23
|
+
thresholds.reduce<number>((previous, threshold) => {
|
|
24
|
+
if (
|
|
25
|
+
!Number.isFinite(threshold) ||
|
|
26
|
+
threshold < 0 ||
|
|
27
|
+
threshold > Number.MAX_SAFE_INTEGER
|
|
28
|
+
) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"INVALID_THRESHOLDS: thresholds must be finite and in 0..MAX_SAFE_INTEGER",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
if (threshold <= previous) {
|
|
34
|
+
throw new Error(
|
|
35
|
+
"INVALID_THRESHOLDS: thresholds must be strictly increasing",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
return threshold;
|
|
39
|
+
}, -1);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function clampEraseBatch(batch: number): number {
|
|
43
|
+
if (!Number.isInteger(batch) || batch < 1) {
|
|
44
|
+
throw new Error("INVALID_BATCH: batch must be a positive integer");
|
|
45
|
+
}
|
|
46
|
+
return Math.min(batch, MAX_ERASE_BATCH);
|
|
47
|
+
}
|
package/src/test.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { TestConvex } from "convex-test";
|
|
2
|
+
|
|
3
|
+
import schema from "./component/schema.js";
|
|
4
|
+
|
|
5
|
+
const modules = import.meta.glob([
|
|
6
|
+
"./component/**/*.ts",
|
|
7
|
+
"!./component/**/*.test.ts",
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
export function register(
|
|
11
|
+
t: Pick<TestConvex<typeof schema>, "registerComponent">,
|
|
12
|
+
name = "progression",
|
|
13
|
+
): void {
|
|
14
|
+
t.registerComponent(name, schema, modules);
|
|
15
|
+
}
|