@vllnt/convex-comments 0.1.0-canary.3e5064a

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -0
  3. package/dist/client/index.d.ts +146 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +133 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +51 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +40 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +98 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/crons.d.ts +16 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +19 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/mutations.d.ts +81 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +223 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +61 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +82 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +42 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +34 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +46 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +37 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/shared.d.ts +25 -0
  52. package/dist/shared.d.ts.map +1 -0
  53. package/dist/shared.js +26 -0
  54. package/dist/shared.js.map +1 -0
  55. package/package.json +98 -0
  56. package/src/client/index.ts +299 -0
  57. package/src/client/types.ts +55 -0
  58. package/src/component/_generated/api.ts +56 -0
  59. package/src/component/_generated/component.ts +129 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +156 -0
  62. package/src/component/convex.config.ts +9 -0
  63. package/src/component/crons.ts +23 -0
  64. package/src/component/mutations.ts +234 -0
  65. package/src/component/queries.ts +96 -0
  66. package/src/component/schema.ts +34 -0
  67. package/src/component/validators.ts +44 -0
  68. package/src/shared.ts +33 -0
  69. package/src/test.ts +15 -0
@@ -0,0 +1,156 @@
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
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ /**
111
+ * A set of services for use within Convex query functions.
112
+ *
113
+ * The query context is passed as the first argument to any Convex query
114
+ * function run on the server.
115
+ *
116
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
117
+ */
118
+ export type QueryCtx = GenericQueryCtx<DataModel>;
119
+
120
+ /**
121
+ * A set of services for use within Convex mutation functions.
122
+ *
123
+ * The mutation context is passed as the first argument to any Convex mutation
124
+ * function run on the server.
125
+ *
126
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
127
+ */
128
+ export type MutationCtx = GenericMutationCtx<DataModel>;
129
+
130
+ /**
131
+ * A set of services for use within Convex action functions.
132
+ *
133
+ * The action context is passed as the first argument to any Convex action
134
+ * function run on the server.
135
+ */
136
+ export type ActionCtx = GenericActionCtx<DataModel>;
137
+
138
+ /**
139
+ * An interface to read from the database within Convex query functions.
140
+ *
141
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
142
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
143
+ * building a query.
144
+ */
145
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
146
+
147
+ /**
148
+ * An interface to read from and write to the database within Convex mutation
149
+ * functions.
150
+ *
151
+ * Convex guarantees that all writes within a single mutation are
152
+ * executed atomically, so you never have to worry about partial writes leaving
153
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
154
+ * for the guarantees Convex provides your functions.
155
+ */
156
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,9 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ const component = defineComponent("comments");
4
+
5
+ // Nest official child components here, e.g.:
6
+ // import aggregate from "@convex-dev/aggregate/convex.config";
7
+ // component.use(aggregate);
8
+
9
+ export default component;
@@ -0,0 +1,23 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { api } from "./_generated/api";
3
+
4
+ /**
5
+ * Default sweep cadence and page size for the built-in prune cron. The cron is
6
+ * the component's own self-healing safety net — a host that wants a different
7
+ * cadence drives `prune` from its own scheduler instead (the client exposes it).
8
+ * Convex cron definitions are static per deployment, so cadence is a documented
9
+ * module constant rather than a mount-time option; the page size bounds each
10
+ * sweep and `prune` self-reschedules until the soft-deleted tail is clean.
11
+ */
12
+ export const PRUNE_INTERVAL = { hours: 24 } as const;
13
+
14
+ /** Rows deleted per `prune` pass before the sweep self-reschedules. */
15
+ export const PRUNE_BATCH = 200;
16
+
17
+ const crons = cronJobs();
18
+
19
+ crons.interval("comments:prune", PRUNE_INTERVAL, api.mutations.prune, {
20
+ batch: PRUNE_BATCH,
21
+ });
22
+
23
+ export default crons;
@@ -0,0 +1,234 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { api } from "./_generated/api";
3
+ import { mutation } from "./_generated/server";
4
+ import { jsonValue } from "./validators";
5
+
6
+ /**
7
+ * Post a comment on a resource and return its id. The comment is inserted `open`
8
+ * with `createdAt`/`updatedAt` stamped from the server clock (`Date.now()` inside
9
+ * the handler — never caller-supplied). `resourceRef` (the thing commented on) and
10
+ * `authorRef` (who wrote it) are opaque host refs the component never inspects;
11
+ * `body` is opaque host data narrowed by the host's `bodyValidator` at the client
12
+ * boundary. `parentId`, when given, threads this comment as a reply to an existing
13
+ * comment.
14
+ *
15
+ * @throws `ConvexError({ code: "PARENT_NOT_FOUND" })` when `parentId` names no
16
+ * comment.
17
+ * @throws `ConvexError({ code: "PARENT_MISMATCH" })` when the parent belongs to a
18
+ * different resource — a reply must live on the same resource as its parent.
19
+ * @throws `ConvexError({ code: "PARENT_DELETED" })` when the parent is soft-deleted
20
+ * — you cannot reply under a removed comment.
21
+ */
22
+ export const post = mutation({
23
+ args: {
24
+ resourceRef: v.string(),
25
+ authorRef: v.string(),
26
+ body: jsonValue,
27
+ parentId: v.optional(v.id("comments")),
28
+ },
29
+ returns: v.object({ commentId: v.id("comments") }),
30
+ handler: async (ctx, args) => {
31
+ if (args.parentId !== undefined) {
32
+ const parent = await ctx.db.get(args.parentId);
33
+ if (parent === null) {
34
+ throw new ConvexError({
35
+ code: "PARENT_NOT_FOUND",
36
+ message: `parent comment "${args.parentId}" not found`,
37
+ });
38
+ }
39
+ if (parent.resourceRef !== args.resourceRef) {
40
+ throw new ConvexError({
41
+ code: "PARENT_MISMATCH",
42
+ message: `parent comment belongs to a different resource`,
43
+ });
44
+ }
45
+ if (parent.status === "deleted") {
46
+ throw new ConvexError({
47
+ code: "PARENT_DELETED",
48
+ message: `cannot reply under a deleted comment`,
49
+ });
50
+ }
51
+ }
52
+
53
+ const now = Date.now();
54
+ const commentId = await ctx.db.insert("comments", {
55
+ resourceRef: args.resourceRef,
56
+ authorRef: args.authorRef,
57
+ parentId: args.parentId,
58
+ body: args.body,
59
+ status: "open",
60
+ createdAt: now,
61
+ updatedAt: now,
62
+ });
63
+ return { commentId };
64
+ },
65
+ });
66
+
67
+ /**
68
+ * Edit a comment's body. Only the original author may edit — a non-author caller
69
+ * is rejected (`NOT_AUTHOR`). A soft-deleted comment cannot be edited
70
+ * (`DELETED`). Records `editedAt` (and `updatedAt`) from the server clock; the
71
+ * new `body` is opaque host data narrowed at the client boundary.
72
+ *
73
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no comment has `commentId`.
74
+ * @throws `ConvexError({ code: "NOT_AUTHOR" })` when `authorRef` is not the author.
75
+ * @throws `ConvexError({ code: "DELETED" })` when the comment is soft-deleted.
76
+ */
77
+ export const edit = mutation({
78
+ args: {
79
+ commentId: v.id("comments"),
80
+ authorRef: v.string(),
81
+ body: jsonValue,
82
+ },
83
+ returns: v.null(),
84
+ handler: async (ctx, args) => {
85
+ const comment = await ctx.db.get(args.commentId);
86
+ if (comment === null) {
87
+ throw new ConvexError({
88
+ code: "NOT_FOUND",
89
+ message: `comment "${args.commentId}" not found`,
90
+ });
91
+ }
92
+ if (comment.authorRef !== args.authorRef) {
93
+ throw new ConvexError({
94
+ code: "NOT_AUTHOR",
95
+ message: `only the author may edit this comment`,
96
+ });
97
+ }
98
+ if (comment.status === "deleted") {
99
+ throw new ConvexError({
100
+ code: "DELETED",
101
+ message: `comment "${args.commentId}" is deleted and cannot be edited`,
102
+ });
103
+ }
104
+
105
+ const now = Date.now();
106
+ await ctx.db.patch(comment._id, {
107
+ body: args.body,
108
+ editedAt: now,
109
+ updatedAt: now,
110
+ });
111
+ return null;
112
+ },
113
+ });
114
+
115
+ /**
116
+ * Soft-delete a comment. Only the original author may delete it (`NOT_AUTHOR`).
117
+ * The row is kept (its replies are preserved) but moved to `deleted` status with
118
+ * its `body` cleared, so the prune cron can sweep it after the retention window.
119
+ * Idempotent — re-deleting an already-deleted comment is a no-op.
120
+ *
121
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no comment has `commentId`.
122
+ * @throws `ConvexError({ code: "NOT_AUTHOR" })` when `authorRef` is not the author.
123
+ */
124
+ export const remove = mutation({
125
+ args: { commentId: v.id("comments"), authorRef: v.string() },
126
+ returns: v.null(),
127
+ handler: async (ctx, args) => {
128
+ const comment = await ctx.db.get(args.commentId);
129
+ if (comment === null) {
130
+ throw new ConvexError({
131
+ code: "NOT_FOUND",
132
+ message: `comment "${args.commentId}" not found`,
133
+ });
134
+ }
135
+ if (comment.authorRef !== args.authorRef) {
136
+ throw new ConvexError({
137
+ code: "NOT_AUTHOR",
138
+ message: `only the author may delete this comment`,
139
+ });
140
+ }
141
+ if (comment.status === "deleted") {
142
+ return null;
143
+ }
144
+ await ctx.db.patch(comment._id, {
145
+ status: "deleted",
146
+ body: undefined,
147
+ updatedAt: Date.now(),
148
+ });
149
+ return null;
150
+ },
151
+ });
152
+
153
+ /**
154
+ * Toggle a comment's resolved state. Only the original author may resolve/reopen
155
+ * (`NOT_AUTHOR`); a soft-deleted comment cannot be resolved (`DELETED`). Setting
156
+ * `resolved: true` moves an `open` comment to `resolved`; `false` reopens it. The
157
+ * target is idempotent — setting the state it already holds is a no-op.
158
+ *
159
+ * @throws `ConvexError({ code: "NOT_FOUND" })` when no comment has `commentId`.
160
+ * @throws `ConvexError({ code: "NOT_AUTHOR" })` when `authorRef` is not the author.
161
+ * @throws `ConvexError({ code: "DELETED" })` when the comment is soft-deleted.
162
+ */
163
+ export const resolve = mutation({
164
+ args: {
165
+ commentId: v.id("comments"),
166
+ authorRef: v.string(),
167
+ resolved: v.boolean(),
168
+ },
169
+ returns: v.null(),
170
+ handler: async (ctx, args) => {
171
+ const comment = await ctx.db.get(args.commentId);
172
+ if (comment === null) {
173
+ throw new ConvexError({
174
+ code: "NOT_FOUND",
175
+ message: `comment "${args.commentId}" not found`,
176
+ });
177
+ }
178
+ if (comment.authorRef !== args.authorRef) {
179
+ throw new ConvexError({
180
+ code: "NOT_AUTHOR",
181
+ message: `only the author may resolve this comment`,
182
+ });
183
+ }
184
+ if (comment.status === "deleted") {
185
+ throw new ConvexError({
186
+ code: "DELETED",
187
+ message: `comment "${args.commentId}" is deleted and cannot be resolved`,
188
+ });
189
+ }
190
+ const target = args.resolved ? "resolved" : "open";
191
+ if (comment.status === target) {
192
+ return null;
193
+ }
194
+ await ctx.db.patch(comment._id, { status: target, updatedAt: Date.now() });
195
+ return null;
196
+ },
197
+ });
198
+
199
+ /**
200
+ * Delete up to `batch` soft-deleted comments whose `updatedAt < before`, oldest
201
+ * first, via the `by_status_updated` index. `before` defaults to the server clock
202
+ * (`Date.now()`) when omitted, so the built-in cron sweeps exactly the comments
203
+ * deleted-and-stale as of the run. If a full batch was removed there may be more,
204
+ * so the sweep self-reschedules through `ctx.scheduler` until a short batch
205
+ * signals the tail is clean. Idempotent: only ever removes already-`deleted`,
206
+ * past-retention rows. Open and resolved comments are never pruned.
207
+ */
208
+ export const prune = mutation({
209
+ args: { before: v.optional(v.number()), batch: v.number() },
210
+ returns: v.number(),
211
+ handler: async (ctx, args) => {
212
+ const before = args.before ?? Date.now();
213
+
214
+ const stale = await ctx.db
215
+ .query("comments")
216
+ .withIndex("by_status_updated", (q) =>
217
+ q.eq("status", "deleted").lt("updatedAt", before),
218
+ )
219
+ .take(args.batch);
220
+
221
+ for (const row of stale) {
222
+ await ctx.db.delete(row._id);
223
+ }
224
+ const removed = stale.length;
225
+
226
+ if (removed === args.batch) {
227
+ await ctx.scheduler.runAfter(0, api.mutations.prune, {
228
+ before,
229
+ batch: args.batch,
230
+ });
231
+ }
232
+ return removed;
233
+ },
234
+ });
@@ -0,0 +1,96 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator } from "convex/server";
3
+ import { query } from "./_generated/server";
4
+ import { commentView } from "./validators";
5
+ import { VISIBLE_STATUSES } from "../shared";
6
+ import type { Doc } from "./_generated/dataModel";
7
+
8
+ /** Project a stored comment row to its public view (exposes the id as a string). */
9
+ function view(comment: Doc<"comments">) {
10
+ return {
11
+ commentId: comment._id,
12
+ resourceRef: comment.resourceRef,
13
+ authorRef: comment.authorRef,
14
+ parentId: comment.parentId,
15
+ body: comment.body,
16
+ status: comment.status,
17
+ editedAt: comment.editedAt,
18
+ createdAt: comment.createdAt,
19
+ updatedAt: comment.updatedAt,
20
+ };
21
+ }
22
+
23
+ /** The current view of one comment, or `null` if no such id is held. */
24
+ export const get = query({
25
+ args: { commentId: v.id("comments") },
26
+ returns: v.union(v.null(), commentView),
27
+ handler: async (ctx, args) => {
28
+ const comment = await ctx.db.get(args.commentId);
29
+ return comment === null ? null : view(comment);
30
+ },
31
+ });
32
+
33
+ /**
34
+ * Page comments on one `resourceRef`, oldest first. By default only top-level
35
+ * comments are returned (`parentId === undefined`); pass `parentId` to page one
36
+ * comment's direct replies via the `by_resource_parent` index. Soft-deleted
37
+ * comments are excluded unless `includeDeleted` is set. Returns the standard
38
+ * Convex paginated envelope (`page`, `isDone`, `continueCursor`) so the host can
39
+ * render a thread reactively.
40
+ */
41
+ export const list = query({
42
+ args: {
43
+ resourceRef: v.string(),
44
+ parentId: v.optional(v.id("comments")),
45
+ includeDeleted: v.optional(v.boolean()),
46
+ paginationOpts: paginationOptsValidator,
47
+ },
48
+ returns: v.object({
49
+ page: v.array(commentView),
50
+ isDone: v.boolean(),
51
+ continueCursor: v.string(),
52
+ splitCursor: v.optional(v.union(v.string(), v.null())),
53
+ pageStatus: v.optional(
54
+ v.union(
55
+ v.literal("SplitRecommended"),
56
+ v.literal("SplitRequired"),
57
+ v.null(),
58
+ ),
59
+ ),
60
+ }),
61
+ handler: async (ctx, args) => {
62
+ // `by_resource_parent` keys on (resourceRef, parentId): an omitted `parentId`
63
+ // pages the resource's top level (root comments, `parentId === undefined`); a
64
+ // given `parentId` pages that comment's direct replies.
65
+ const base = ctx.db
66
+ .query("comments")
67
+ .withIndex("by_resource_parent", (q) =>
68
+ q.eq("resourceRef", args.resourceRef).eq("parentId", args.parentId),
69
+ );
70
+
71
+ const filtered = args.includeDeleted
72
+ ? base
73
+ : base.filter((q) => q.neq(q.field("status"), "deleted"));
74
+
75
+ const result = await filtered.order("asc").paginate(args.paginationOpts);
76
+ return { ...result, page: result.page.map(view) };
77
+ },
78
+ });
79
+
80
+ /**
81
+ * Count the visible (non-deleted) comments on one `resourceRef`. Reads the whole
82
+ * resource slice via the `by_resource` index and tallies the open/resolved rows —
83
+ * a small per-resource scan, not a global one. Soft-deleted comments are never
84
+ * counted.
85
+ */
86
+ export const count = query({
87
+ args: { resourceRef: v.string() },
88
+ returns: v.number(),
89
+ handler: async (ctx, args) => {
90
+ const all = await ctx.db
91
+ .query("comments")
92
+ .withIndex("by_resource", (q) => q.eq("resourceRef", args.resourceRef))
93
+ .collect();
94
+ return all.filter((c) => VISIBLE_STATUSES.has(c.status)).length;
95
+ },
96
+ });
@@ -0,0 +1,34 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { commentStatus, jsonValue } from "./validators";
4
+
5
+ /**
6
+ * Sandboxed table — the comment tree's own concern. A comment is attached to an
7
+ * opaque host `resourceRef` (the thing being commented on) and authored by an
8
+ * opaque `authorRef`; the host owns the meaning of both. `parentId` is the opaque
9
+ * id of the comment this one replies to (absent at the top level), so the tree is
10
+ * a self-referential thread. `body` is opaque host data (cleared on soft-delete);
11
+ * `status` tracks the lifecycle. `editedAt` records the last edit, distinct from
12
+ * `updatedAt` (any write).
13
+ *
14
+ * The three indexes serve: list/count one resource oldest-first (`by_resource`),
15
+ * walk one parent's direct replies (`by_resource_parent`), list one author's
16
+ * comments (`by_author`), and the retention sweep of soft-deleted rows
17
+ * (`by_status_updated`).
18
+ */
19
+ export default defineSchema({
20
+ comments: defineTable({
21
+ resourceRef: v.string(),
22
+ authorRef: v.string(),
23
+ parentId: v.optional(v.id("comments")),
24
+ body: v.optional(jsonValue),
25
+ status: commentStatus,
26
+ editedAt: v.optional(v.number()),
27
+ createdAt: v.number(),
28
+ updatedAt: v.number(),
29
+ })
30
+ .index("by_resource", ["resourceRef", "createdAt"])
31
+ .index("by_resource_parent", ["resourceRef", "parentId", "createdAt"])
32
+ .index("by_author", ["authorRef", "createdAt"])
33
+ .index("by_status_updated", ["status", "updatedAt"]),
34
+ });
@@ -0,0 +1,44 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Opaque host-owned comment body — plain text, a rich-block JSON document, or
5
+ * whatever shape the host's editor produces. The component never inspects it; it
6
+ * is last-resort arbitrary data, aliased here rather than left bare in a function
7
+ * signature. The host narrows it at the {@link Comments} client boundary via an
8
+ * optional `bodyValidator` parser.
9
+ *
10
+ * This is the single documented `v.any()` escape hatch in the component; the lint
11
+ * rule `convex-rules/no-bare-v-any` is satisfied by routing every arbitrary host
12
+ * body through this alias instead of a bare `v.any()`.
13
+ */
14
+ export const jsonValue = v.any();
15
+
16
+ /** The three lifecycle statuses a comment moves through. */
17
+ export const commentStatus = v.union(
18
+ v.literal("open"),
19
+ v.literal("resolved"),
20
+ v.literal("deleted"),
21
+ );
22
+
23
+ /**
24
+ * The visible (non-deleted) status subset a `list` filters on. A soft-deleted
25
+ * comment is excluded from a normal listing.
26
+ */
27
+ export const visibleStatus = v.union(v.literal("open"), v.literal("resolved"));
28
+
29
+ /**
30
+ * Public projection of a comment returned by {@link get} / {@link list}. `body`
31
+ * is opaque host data (`undefined` once soft-deleted — the body is cleared);
32
+ * `parentId` is the opaque id of the comment this one replies to, when threaded.
33
+ */
34
+ export const commentView = v.object({
35
+ commentId: v.string(),
36
+ resourceRef: v.string(),
37
+ authorRef: v.string(),
38
+ parentId: v.optional(v.string()),
39
+ body: v.optional(jsonValue),
40
+ status: commentStatus,
41
+ editedAt: v.optional(v.number()),
42
+ createdAt: v.number(),
43
+ updatedAt: v.number(),
44
+ });
package/src/shared.ts ADDED
@@ -0,0 +1,33 @@
1
+ /** Shared constants used by both `client/` and `component/`. */
2
+
3
+ export const COMPONENT_NAME = "comments";
4
+
5
+ /**
6
+ * The lifecycle statuses a comment moves through. `open` is the freshly-posted
7
+ * state; `resolve` toggles it to `resolved` and back; a soft `delete` moves it to
8
+ * the terminal `deleted` state (the row is kept for retention, its `body` cleared).
9
+ */
10
+ export const COMMENT_STATUSES = ["open", "resolved", "deleted"] as const;
11
+
12
+ /** A single comment lifecycle status. */
13
+ export type CommentStatus = (typeof COMMENT_STATUSES)[number];
14
+
15
+ /**
16
+ * The non-deleted statuses a `list` returns by default — a soft-deleted comment
17
+ * is excluded from a normal listing (the host opts in with `includeDeleted`).
18
+ */
19
+ export const VISIBLE_STATUSES: ReadonlySet<CommentStatus> = new Set([
20
+ "open",
21
+ "resolved",
22
+ ]);
23
+
24
+ /**
25
+ * Default retention (ms) for soft-deleted comments before the prune cron sweeps
26
+ * them: 30 days. Bounds unbounded growth of the `comments` table while leaving a
27
+ * window in which a deletion can still be audited. A host that wants a different
28
+ * window drives `prune` from its own scheduler with an explicit `before` cutoff.
29
+ */
30
+ export const DEFAULT_RETENTION_MS = 2_592_000_000;
31
+
32
+ /** Default page size for a `prune` pass before the sweep self-reschedules. */
33
+ export const DEFAULT_PRUNE_BATCH = 200;
package/src/test.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { TestConvex } from "convex-test";
2
+ import schema from "./component/schema";
3
+
4
+ const modules = import.meta.glob("./component/**/*.ts");
5
+
6
+ /**
7
+ * Register this component with a `convex-test` instance so consuming apps can
8
+ * test integration: `import { register } from "@vllnt/convex-comments/test"`.
9
+ */
10
+ export function register(
11
+ t: TestConvex<typeof schema>,
12
+ name = "comments",
13
+ ): void {
14
+ t.registerComponent(name, schema, modules);
15
+ }