@respectify/astro 0.1.9 → 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.
- package/README.md +213 -69
- package/client/comments.ts +2 -0
- package/default-respectify.config.json +1 -0
- package/drizzle/postgres.config.ts +8 -0
- package/drizzle/sqlite.config.ts +8 -0
- package/migrations/postgres/0000_respectify_comment.sql +14 -0
- package/migrations/postgres/meta/0000_snapshot.json +144 -0
- package/migrations/postgres/meta/_journal.json +13 -0
- package/migrations/sqlite/0000_respectify_comment.sql +13 -0
- package/migrations/sqlite/meta/0000_snapshot.json +101 -0
- package/migrations/sqlite/meta/_journal.json +13 -0
- package/package.json +35 -13
- package/respectify.config.sample.jsonc +47 -5
- package/src/actions.ts +133 -75
- package/src/adapters/postgres/index.ts +7 -0
- package/src/adapters/postgres/store.ts +83 -0
- package/src/adapters/postgres/table.ts +37 -0
- package/src/adapters/sqlite/index.ts +8 -0
- package/src/adapters/sqlite/store.ts +91 -0
- package/src/adapters/sqlite/table.ts +41 -0
- package/src/adapters/sqlite/text-date.ts +37 -0
- package/src/env.d.ts +11 -12
- package/src/index.ts +91 -7
- package/src/lib/config.ts +60 -0
- package/src/lib/service.ts +74 -23
- package/src/options.ts +135 -0
- package/src/routes/comments.ts +31 -33
- package/src/runtime-config.ts +9 -33
- package/src/runtime.ts +28 -0
- package/src/store/limits.ts +11 -0
- package/src/store/schemas.ts +41 -0
- package/src/store/types.ts +52 -0
- package/src/testing/comment-store-contract.ts +197 -0
- package/src/testing/index.ts +1 -0
- package/src/types.ts +87 -17
- package/src/schema.ts +0 -25
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "6",
|
|
3
|
+
"dialect": "sqlite",
|
|
4
|
+
"id": "9e37e666-2c7c-46b3-b761-c0ae5cc112e3",
|
|
5
|
+
"prevId": "00000000-0000-0000-0000-000000000000",
|
|
6
|
+
"tables": {
|
|
7
|
+
"Comment": {
|
|
8
|
+
"name": "Comment",
|
|
9
|
+
"columns": {
|
|
10
|
+
"id": {
|
|
11
|
+
"name": "id",
|
|
12
|
+
"type": "integer",
|
|
13
|
+
"primaryKey": true,
|
|
14
|
+
"notNull": true,
|
|
15
|
+
"autoincrement": false
|
|
16
|
+
},
|
|
17
|
+
"postSlug": {
|
|
18
|
+
"name": "postSlug",
|
|
19
|
+
"type": "text",
|
|
20
|
+
"primaryKey": false,
|
|
21
|
+
"notNull": true,
|
|
22
|
+
"autoincrement": false
|
|
23
|
+
},
|
|
24
|
+
"author": {
|
|
25
|
+
"name": "author",
|
|
26
|
+
"type": "text",
|
|
27
|
+
"primaryKey": false,
|
|
28
|
+
"notNull": true,
|
|
29
|
+
"autoincrement": false
|
|
30
|
+
},
|
|
31
|
+
"email": {
|
|
32
|
+
"name": "email",
|
|
33
|
+
"type": "text",
|
|
34
|
+
"primaryKey": false,
|
|
35
|
+
"notNull": false,
|
|
36
|
+
"autoincrement": false
|
|
37
|
+
},
|
|
38
|
+
"content": {
|
|
39
|
+
"name": "content",
|
|
40
|
+
"type": "text",
|
|
41
|
+
"primaryKey": false,
|
|
42
|
+
"notNull": true,
|
|
43
|
+
"autoincrement": false
|
|
44
|
+
},
|
|
45
|
+
"createdAt": {
|
|
46
|
+
"name": "createdAt",
|
|
47
|
+
"type": "text",
|
|
48
|
+
"primaryKey": false,
|
|
49
|
+
"notNull": true,
|
|
50
|
+
"autoincrement": false,
|
|
51
|
+
"default": "CURRENT_TIMESTAMP"
|
|
52
|
+
},
|
|
53
|
+
"approved": {
|
|
54
|
+
"name": "approved",
|
|
55
|
+
"type": "integer",
|
|
56
|
+
"primaryKey": false,
|
|
57
|
+
"notNull": true,
|
|
58
|
+
"autoincrement": false,
|
|
59
|
+
"default": false
|
|
60
|
+
},
|
|
61
|
+
"parentId": {
|
|
62
|
+
"name": "parentId",
|
|
63
|
+
"type": "integer",
|
|
64
|
+
"primaryKey": false,
|
|
65
|
+
"notNull": false,
|
|
66
|
+
"autoincrement": false
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"indexes": {
|
|
70
|
+
"Comment_postSlug_idx": {
|
|
71
|
+
"name": "Comment_postSlug_idx",
|
|
72
|
+
"columns": [
|
|
73
|
+
"postSlug"
|
|
74
|
+
],
|
|
75
|
+
"isUnique": false
|
|
76
|
+
},
|
|
77
|
+
"Comment_approved_idx": {
|
|
78
|
+
"name": "Comment_approved_idx",
|
|
79
|
+
"columns": [
|
|
80
|
+
"approved"
|
|
81
|
+
],
|
|
82
|
+
"isUnique": false
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"foreignKeys": {},
|
|
86
|
+
"compositePrimaryKeys": {},
|
|
87
|
+
"uniqueConstraints": {},
|
|
88
|
+
"checkConstraints": {}
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
"views": {},
|
|
92
|
+
"enums": {},
|
|
93
|
+
"_meta": {
|
|
94
|
+
"schemas": {},
|
|
95
|
+
"tables": {},
|
|
96
|
+
"columns": {}
|
|
97
|
+
},
|
|
98
|
+
"internal": {
|
|
99
|
+
"indexes": {}
|
|
100
|
+
}
|
|
101
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@respectify/astro",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Respectify-powered commenting for Astro
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Respectify-powered commenting for Astro \u2014 AI moderation, spam filtering, and beautiful UX out of the box.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Respectify",
|
|
@@ -31,42 +31,64 @@
|
|
|
31
31
|
".": "./src/index.ts",
|
|
32
32
|
"./actions": "./src/actions.ts",
|
|
33
33
|
"./credentials": "./src/credentials.ts",
|
|
34
|
-
"./schema": "./src/schema.ts",
|
|
35
34
|
"./routes/comments": "./src/routes/comments.ts",
|
|
36
35
|
"./components/CommentSection.astro": "./components/CommentSection.astro",
|
|
37
36
|
"./components/PoweredByRespectify.astro": "./components/PoweredByRespectify.astro",
|
|
38
37
|
"./client": "./client/comments.ts",
|
|
39
|
-
"./styles.css": "./components/respectify-comments.css"
|
|
38
|
+
"./styles.css": "./components/respectify-comments.css",
|
|
39
|
+
"./postgres": "./src/adapters/postgres/index.ts",
|
|
40
|
+
"./sqlite": "./src/adapters/sqlite/index.ts",
|
|
41
|
+
"./testing": "./src/testing/index.ts"
|
|
40
42
|
},
|
|
41
43
|
"files": [
|
|
42
44
|
"src",
|
|
43
45
|
"components",
|
|
44
46
|
"client",
|
|
47
|
+
"migrations",
|
|
48
|
+
"drizzle",
|
|
45
49
|
"default-respectify.config.json",
|
|
46
50
|
"respectify.config.sample.jsonc",
|
|
47
51
|
"README.md"
|
|
48
52
|
],
|
|
49
53
|
"peerDependencies": {
|
|
50
|
-
"@
|
|
51
|
-
"@respectify/client": "^0.
|
|
52
|
-
"astro": "^5.0.0 || ^6.0.0",
|
|
54
|
+
"@libsql/client": ">=0.10.0",
|
|
55
|
+
"@respectify/client": "^0.7.0",
|
|
56
|
+
"astro": "^5.0.0 || ^6.0.0 || ^7.0.0",
|
|
57
|
+
"drizzle-orm": "^0.45.0",
|
|
58
|
+
"pg": "^8.0.0",
|
|
59
|
+
"vitest": "^3.0.0",
|
|
53
60
|
"zod": "^3.0.0"
|
|
54
61
|
},
|
|
55
62
|
"peerDependenciesMeta": {
|
|
56
|
-
"@
|
|
57
|
-
"optional":
|
|
63
|
+
"@libsql/client": {
|
|
64
|
+
"optional": true
|
|
65
|
+
},
|
|
66
|
+
"drizzle-orm": {
|
|
67
|
+
"optional": true
|
|
68
|
+
},
|
|
69
|
+
"pg": {
|
|
70
|
+
"optional": true
|
|
71
|
+
},
|
|
72
|
+
"vitest": {
|
|
73
|
+
"optional": true
|
|
58
74
|
}
|
|
59
75
|
},
|
|
60
76
|
"dependencies": {
|
|
61
77
|
"zod": "^3.24.0"
|
|
62
78
|
},
|
|
63
79
|
"scripts": {
|
|
64
|
-
"typecheck": "tsc --noEmit"
|
|
80
|
+
"typecheck": "tsc --noEmit",
|
|
81
|
+
"test": "vitest run",
|
|
82
|
+
"migrations:generate": "drizzle-kit generate --config drizzle/postgres.config.ts && drizzle-kit generate --config drizzle/sqlite.config.ts"
|
|
65
83
|
},
|
|
66
84
|
"devDependencies": {
|
|
67
|
-
"@
|
|
68
|
-
"@
|
|
85
|
+
"@electric-sql/pglite": "0.5.8",
|
|
86
|
+
"@libsql/client": "^0.18.0",
|
|
87
|
+
"@respectify/client": "^0.7.0",
|
|
69
88
|
"astro": "^6.0.4",
|
|
70
|
-
"
|
|
89
|
+
"drizzle-kit": "^0.31.11",
|
|
90
|
+
"drizzle-orm": "^0.45.4",
|
|
91
|
+
"typescript": "^5.4.3",
|
|
92
|
+
"vitest": "^3.2.4"
|
|
71
93
|
}
|
|
72
94
|
}
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
// rateLimit: { windowMs: 300_000, maxRequests: 10 },
|
|
26
26
|
// client: { /* same shape as "client" below */ },
|
|
27
27
|
// megacall: { /* same shape as "megacall" below */ },
|
|
28
|
+
// tolerances: { /* same shape as "tolerances" below; wins per item */ },
|
|
28
29
|
// })
|
|
29
30
|
//
|
|
30
31
|
// =============================================================================
|
|
@@ -89,15 +90,52 @@
|
|
|
89
90
|
// "replyToComment": "Parent comment text"
|
|
90
91
|
},
|
|
91
92
|
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// tolerances — comment health: how much of each item this site accepts
|
|
95
|
+
// Ten items: the nine problem categories below, plus "quality". Items not
|
|
96
|
+
// named are "standard". Sent only when a comment score runs.
|
|
97
|
+
//
|
|
98
|
+
// Levels, loosest to strictest:
|
|
99
|
+
// "off" | "permissive" | "relaxed" | "standard" (default) | "strict" | "zero_tolerance"
|
|
100
|
+
// Problem categories, by their worst finding (minor, clear, severe, extreme):
|
|
101
|
+
// permissive filters only the very worst (fails extreme only), relaxed fails
|
|
102
|
+
// severe and extreme, standard fails clear and worse, strict and
|
|
103
|
+
// zero_tolerance fail any.
|
|
104
|
+
// Quality, the lowest 1-5 score accepted: permissive and relaxed 2,
|
|
105
|
+
// standard 3, strict 4, zero_tolerance 5. "off" leaves the item out of
|
|
106
|
+
// comment health entirely.
|
|
107
|
+
// threat, identity_attack, sexual_content and harassment are floored: they
|
|
108
|
+
// can be made stricter but never "permissive", "relaxed" or "off" (the config
|
|
109
|
+
// fails to load).
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
"tolerances": {
|
|
112
|
+
// Floored categories: "standard" | "strict" | "zero_tolerance"
|
|
113
|
+
// "threat": "zero_tolerance",
|
|
114
|
+
// "identity_attack": "strict",
|
|
115
|
+
// "sexual_content": "strict",
|
|
116
|
+
// "harassment": "strict",
|
|
117
|
+
|
|
118
|
+
// Tunable categories: any level, including "permissive", "relaxed" and "off"
|
|
119
|
+
// "insult": "relaxed",
|
|
120
|
+
// "profanity": "off",
|
|
121
|
+
// "dismissive_tone": "standard",
|
|
122
|
+
// "logical_fallacy": "relaxed",
|
|
123
|
+
// "low_effort": "strict",
|
|
124
|
+
|
|
125
|
+
// Quality: any level
|
|
126
|
+
// "quality": "strict"
|
|
127
|
+
},
|
|
128
|
+
|
|
92
129
|
// ---------------------------------------------------------------------------
|
|
93
130
|
// moderation — how megacall results become approve / reject decisions
|
|
94
131
|
// ---------------------------------------------------------------------------
|
|
95
132
|
"moderation": {
|
|
96
|
-
//
|
|
133
|
+
// When the comment score says exceeds_tolerance, block it if its
|
|
134
|
+
// respectfulness score is below `thresholds.block`
|
|
97
135
|
"blockDisrespectful": true,
|
|
98
136
|
|
|
99
|
-
//
|
|
100
|
-
// `feedback.warning
|
|
137
|
+
// A comment that exceeds tolerance but is not blocked gets
|
|
138
|
+
// `feedback.warning`; allow it through when true, reject when false
|
|
101
139
|
"allowOverride": false,
|
|
102
140
|
|
|
103
141
|
// Include revision suggestions (toxicity explanation, fallacies, etc.)
|
|
@@ -116,15 +154,19 @@
|
|
|
116
154
|
// ---------------------------------------------------------------------------
|
|
117
155
|
// thresholds — respectfulness score bands (0.0–1.0)
|
|
118
156
|
// Score is derived as `1 - toxicity_score` from comment_score when available.
|
|
157
|
+
// comment_score.exceeds_tolerance decides whether a comment has a problem:
|
|
158
|
+
// false → approve, whatever the score. true → the score picks warn or block.
|
|
119
159
|
// ---------------------------------------------------------------------------
|
|
120
160
|
"thresholds": {
|
|
121
|
-
//
|
|
161
|
+
// Only used when the API returns no exceeds_tolerance (older API):
|
|
162
|
+
// score >= this → approve with `feedback.approved`
|
|
122
163
|
"autoApprove": 0.7,
|
|
123
164
|
|
|
124
165
|
// Reserved mid band (kept for compatibility; decisions use autoApprove/block)
|
|
125
166
|
"warn": 0.5,
|
|
126
167
|
|
|
127
|
-
//
|
|
168
|
+
// exceeds_tolerance + score < this + blockDisrespectful → reject with
|
|
169
|
+
// `feedback.blocked`; exceeds_tolerance at or above this → `feedback.warning`
|
|
128
170
|
"block": 0.3
|
|
129
171
|
},
|
|
130
172
|
|
package/src/actions.ts
CHANGED
|
@@ -1,9 +1,136 @@
|
|
|
1
|
-
import { defineAction, ActionError } from 'astro:actions';
|
|
1
|
+
import { defineAction, ActionError, type ActionAPIContext } from 'astro:actions';
|
|
2
2
|
import { z } from 'astro/zod';
|
|
3
|
-
import { db, Comment, eq } from 'astro:db';
|
|
4
3
|
import { analyzeComment } from './lib/service';
|
|
5
4
|
import { checkRateLimit } from './lib/rate-limit';
|
|
6
5
|
import { getIntegrationOptions } from './runtime-config';
|
|
6
|
+
import { getRespectifyRuntime } from './runtime';
|
|
7
|
+
import { COMMENT_LIMITS } from './store/limits';
|
|
8
|
+
import { CommentValidationError } from './store/schemas';
|
|
9
|
+
|
|
10
|
+
/** Input to `comments.submit`. Uses Astro's Zod (3 on Astro 5, 4 on Astro 6+), so only API both share. */
|
|
11
|
+
export const submitCommentInput = z.object({
|
|
12
|
+
postSlug: z.string().min(1).max(COMMENT_LIMITS.postSlugMax),
|
|
13
|
+
author: z.string().min(1).max(COMMENT_LIMITS.authorMax),
|
|
14
|
+
email: z.string().email().max(COMMENT_LIMITS.emailMax).optional(),
|
|
15
|
+
content: z.string().min(1).max(COMMENT_LIMITS.contentMax),
|
|
16
|
+
parentId: z.number().int().positive().optional(),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
/** Input to `comments.delete`. */
|
|
20
|
+
export const deleteCommentInput = z.object({
|
|
21
|
+
commentId: z.number().int().positive(),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export type SubmitCommentInput = z.infer<typeof submitCommentInput>;
|
|
25
|
+
export type DeleteCommentInput = z.infer<typeof deleteCommentInput>;
|
|
26
|
+
|
|
27
|
+
export type SubmitCommentResult =
|
|
28
|
+
| {
|
|
29
|
+
success: false;
|
|
30
|
+
approved: false;
|
|
31
|
+
feedback: string;
|
|
32
|
+
suggestion: string | undefined;
|
|
33
|
+
suspectedSpam: boolean;
|
|
34
|
+
score: number;
|
|
35
|
+
}
|
|
36
|
+
| {
|
|
37
|
+
success: true;
|
|
38
|
+
approved: true;
|
|
39
|
+
feedback: string;
|
|
40
|
+
score: number;
|
|
41
|
+
message: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** The client's address, or a shared bucket when the adapter or rendering mode does not expose one. */
|
|
45
|
+
function clientAddressOf(context: Pick<ActionAPIContext, 'clientAddress'>): string {
|
|
46
|
+
try {
|
|
47
|
+
return context.clientAddress;
|
|
48
|
+
} catch {
|
|
49
|
+
return 'unknown';
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The text of the comment being replied to.
|
|
55
|
+
* @throws ActionError BAD_REQUEST when the parent does not exist, is on another post, or is not approved
|
|
56
|
+
*/
|
|
57
|
+
async function loadReplyTarget(parentId: number, postSlug: string): Promise<string> {
|
|
58
|
+
const parent = await getRespectifyRuntime().store.findById(parentId);
|
|
59
|
+
if (!parent || parent.postSlug !== postSlug || !parent.approved) {
|
|
60
|
+
throw new ActionError({ code: 'BAD_REQUEST', message: 'The comment you are replying to was not found.' });
|
|
61
|
+
}
|
|
62
|
+
return parent.content;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Rate-limit, moderate with Respectify, and store the comment when it is approved.
|
|
67
|
+
* @throws ActionError TOO_MANY_REQUESTS, or BAD_REQUEST for an invalid parent or comment
|
|
68
|
+
*/
|
|
69
|
+
export async function submitComment(
|
|
70
|
+
{ postSlug, author, email, content, parentId }: SubmitCommentInput,
|
|
71
|
+
context: Pick<ActionAPIContext, 'clientAddress'>,
|
|
72
|
+
): Promise<SubmitCommentResult> {
|
|
73
|
+
const { rateLimit } = getIntegrationOptions();
|
|
74
|
+
if (!checkRateLimit(clientAddressOf(context), rateLimit.windowMs, rateLimit.maxRequests)) {
|
|
75
|
+
throw new ActionError({
|
|
76
|
+
code: 'TOO_MANY_REQUESTS',
|
|
77
|
+
message: 'Too many comments submitted. Please wait a bit before trying again.',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const replyToComment = parentId === undefined ? undefined : await loadReplyTarget(parentId, postSlug);
|
|
82
|
+
const analysis = await analyzeComment(content, postSlug, { replyToComment });
|
|
83
|
+
|
|
84
|
+
if (!analysis.approved) {
|
|
85
|
+
return {
|
|
86
|
+
success: false,
|
|
87
|
+
approved: false,
|
|
88
|
+
feedback: analysis.feedback,
|
|
89
|
+
suggestion: analysis.suggestion,
|
|
90
|
+
suspectedSpam: analysis.suspectedSpam === true,
|
|
91
|
+
score: analysis.score,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
await getRespectifyRuntime().store.create({ postSlug, author, email, content, parentId, approved: true });
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error instanceof CommentValidationError) {
|
|
99
|
+
throw new ActionError({ code: 'BAD_REQUEST', message: error.message });
|
|
100
|
+
}
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
success: true,
|
|
106
|
+
approved: true,
|
|
107
|
+
feedback: analysis.feedback,
|
|
108
|
+
score: analysis.score,
|
|
109
|
+
message: 'Comment published successfully!',
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Delete a comment. Only for an authenticated admin.
|
|
115
|
+
* @throws ActionError UNAUTHORIZED when not logged in, NOT_FOUND when there is no such comment
|
|
116
|
+
*/
|
|
117
|
+
export async function deleteComment(
|
|
118
|
+
{ commentId }: DeleteCommentInput,
|
|
119
|
+
context: Pick<ActionAPIContext, 'locals'>,
|
|
120
|
+
): Promise<{ success: true }> {
|
|
121
|
+
if (!context.locals.isAuthenticated) {
|
|
122
|
+
throw new ActionError({
|
|
123
|
+
code: 'UNAUTHORIZED',
|
|
124
|
+
message: 'You must be logged in to delete comments',
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const deleted = await getRespectifyRuntime().store.delete(commentId);
|
|
129
|
+
if (!deleted) {
|
|
130
|
+
throw new ActionError({ code: 'NOT_FOUND', message: 'Comment not found' });
|
|
131
|
+
}
|
|
132
|
+
return { success: true };
|
|
133
|
+
}
|
|
7
134
|
|
|
8
135
|
/**
|
|
9
136
|
* Merge into your src/actions/index.ts:
|
|
@@ -20,82 +147,13 @@ import { getIntegrationOptions } from './runtime-config';
|
|
|
20
147
|
export const respectifyCommentActions = {
|
|
21
148
|
submit: defineAction({
|
|
22
149
|
accept: 'json',
|
|
23
|
-
input:
|
|
24
|
-
|
|
25
|
-
author: z.string().min(1).max(100),
|
|
26
|
-
email: z.string().email().optional(),
|
|
27
|
-
content: z.string().min(1).max(5000),
|
|
28
|
-
parentId: z.number().optional(),
|
|
29
|
-
}),
|
|
30
|
-
handler: async ({ postSlug, author, email, content, parentId }, context) => {
|
|
31
|
-
const { rateLimit } = getIntegrationOptions();
|
|
32
|
-
if (rateLimit) {
|
|
33
|
-
let key = 'unknown';
|
|
34
|
-
try {
|
|
35
|
-
key = context.clientAddress;
|
|
36
|
-
} catch {
|
|
37
|
-
// Some adapters/rendering modes don't expose a client address; fall back to a shared bucket.
|
|
38
|
-
}
|
|
39
|
-
if (!checkRateLimit(key, rateLimit.windowMs, rateLimit.maxRequests)) {
|
|
40
|
-
throw new ActionError({
|
|
41
|
-
code: 'TOO_MANY_REQUESTS',
|
|
42
|
-
message: 'Too many comments submitted. Please wait a bit before trying again.',
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
let replyToComment: string | undefined;
|
|
48
|
-
if (parentId !== undefined) {
|
|
49
|
-
const [parent] = await db.select().from(Comment).where(eq(Comment.id, parentId)).limit(1);
|
|
50
|
-
replyToComment = parent?.content;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const analysis = await analyzeComment(content, postSlug, { replyToComment });
|
|
54
|
-
|
|
55
|
-
if (!analysis.approved) {
|
|
56
|
-
return {
|
|
57
|
-
success: false as const,
|
|
58
|
-
approved: false as const,
|
|
59
|
-
feedback: analysis.feedback,
|
|
60
|
-
suggestion: analysis.suggestion,
|
|
61
|
-
score: analysis.score,
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
await db.insert(Comment).values({
|
|
66
|
-
postSlug,
|
|
67
|
-
author,
|
|
68
|
-
email,
|
|
69
|
-
content,
|
|
70
|
-
parentId,
|
|
71
|
-
approved: true,
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
return {
|
|
75
|
-
success: true as const,
|
|
76
|
-
approved: true as const,
|
|
77
|
-
feedback: analysis.feedback,
|
|
78
|
-
score: analysis.score,
|
|
79
|
-
message: 'Comment published successfully!',
|
|
80
|
-
};
|
|
81
|
-
},
|
|
150
|
+
input: submitCommentInput,
|
|
151
|
+
handler: submitComment,
|
|
82
152
|
}),
|
|
83
153
|
|
|
84
154
|
delete: defineAction({
|
|
85
155
|
accept: 'json',
|
|
86
|
-
input:
|
|
87
|
-
|
|
88
|
-
}),
|
|
89
|
-
handler: async ({ commentId }, context) => {
|
|
90
|
-
if (!context.locals.isAuthenticated) {
|
|
91
|
-
throw new ActionError({
|
|
92
|
-
code: 'UNAUTHORIZED',
|
|
93
|
-
message: 'You must be logged in to delete comments',
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
await db.delete(Comment).where(eq(Comment.id, commentId));
|
|
98
|
-
return { success: true as const };
|
|
99
|
-
},
|
|
156
|
+
input: deleteCommentInput,
|
|
157
|
+
handler: deleteComment,
|
|
100
158
|
}),
|
|
101
159
|
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { and, asc, eq } from 'drizzle-orm';
|
|
2
|
+
import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { commentIdSchema, parseNewComment } from '../../store/schemas';
|
|
4
|
+
import type { CommentRecord, ICommentStore, NewComment, PublicComment } from '../../store/types';
|
|
5
|
+
import { respectifyComments, type PostgresCommentTable } from './table';
|
|
6
|
+
|
|
7
|
+
export interface PostgresCommentStoreOptions {
|
|
8
|
+
/** The comment table, when it is not the default `respectify_comment` (see `createPostgresCommentTable`) */
|
|
9
|
+
table?: PostgresCommentTable;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A comment store on any Drizzle Postgres database: node-postgres, postgres.js, Neon, PGlite and others. */
|
|
13
|
+
class PostgresCommentStore<TQueryResult extends PgQueryResultHKT, TSchema extends Record<string, unknown>>
|
|
14
|
+
implements ICommentStore
|
|
15
|
+
{
|
|
16
|
+
readonly #db: PgDatabase<TQueryResult, TSchema>;
|
|
17
|
+
readonly #table: PostgresCommentTable;
|
|
18
|
+
|
|
19
|
+
constructor(db: PgDatabase<TQueryResult, TSchema>, table: PostgresCommentTable) {
|
|
20
|
+
this.#db = db;
|
|
21
|
+
this.#table = table;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async findById(id: number): Promise<CommentRecord | undefined> {
|
|
25
|
+
if (!commentIdSchema.safeParse(id).success) return undefined;
|
|
26
|
+
const [row] = await this.#db.select().from(this.#table).where(eq(this.#table.id, id)).limit(1);
|
|
27
|
+
return row;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async listApproved(postSlug: string): Promise<PublicComment[]> {
|
|
31
|
+
const table = this.#table;
|
|
32
|
+
return this.#db
|
|
33
|
+
.select({
|
|
34
|
+
id: table.id,
|
|
35
|
+
author: table.author,
|
|
36
|
+
content: table.content,
|
|
37
|
+
createdAt: table.createdAt,
|
|
38
|
+
parentId: table.parentId,
|
|
39
|
+
})
|
|
40
|
+
.from(table)
|
|
41
|
+
.where(and(eq(table.postSlug, postSlug), eq(table.approved, true)))
|
|
42
|
+
.orderBy(asc(table.createdAt), asc(table.id));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async create(input: NewComment): Promise<CommentRecord> {
|
|
46
|
+
const comment = parseNewComment(input);
|
|
47
|
+
const [row] = await this.#db
|
|
48
|
+
.insert(this.#table)
|
|
49
|
+
.values({
|
|
50
|
+
postSlug: comment.postSlug,
|
|
51
|
+
author: comment.author,
|
|
52
|
+
email: comment.email ?? null,
|
|
53
|
+
content: comment.content,
|
|
54
|
+
approved: comment.approved,
|
|
55
|
+
parentId: comment.parentId ?? null,
|
|
56
|
+
})
|
|
57
|
+
.returning();
|
|
58
|
+
if (!row) {
|
|
59
|
+
throw new Error('The comment was not stored: the database returned no row');
|
|
60
|
+
}
|
|
61
|
+
return row;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async delete(id: number): Promise<boolean> {
|
|
65
|
+
if (!commentIdSchema.safeParse(id).success) return false;
|
|
66
|
+
// The parent_id foreign key sets each reply's parent to null
|
|
67
|
+
const deleted = await this.#db.delete(this.#table).where(eq(this.#table.id, id)).returning({ id: this.#table.id });
|
|
68
|
+
return deleted.length > 0;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Store comments in Postgres through your own Drizzle database instance, so the integration
|
|
74
|
+
* uses your connection and never opens one. The table must already exist: add
|
|
75
|
+
* `respectifyComments` (or a table from `createPostgresCommentTable`) to your Drizzle schema
|
|
76
|
+
* and migrate with drizzle-kit.
|
|
77
|
+
*/
|
|
78
|
+
export function createPostgresCommentStore<
|
|
79
|
+
TQueryResult extends PgQueryResultHKT,
|
|
80
|
+
TSchema extends Record<string, unknown>,
|
|
81
|
+
>(db: PgDatabase<TQueryResult, TSchema>, options: PostgresCommentStoreOptions = {}): ICommentStore {
|
|
82
|
+
return new PostgresCommentStore(db, options.table ?? respectifyComments);
|
|
83
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { boolean, index, integer, pgTable, text, timestamp, type AnyPgColumn } from 'drizzle-orm/pg-core';
|
|
2
|
+
|
|
3
|
+
/** The default Postgres table name for Respectify comments. */
|
|
4
|
+
export const DEFAULT_POSTGRES_COMMENT_TABLE_NAME = 'respectify_comment';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Build the Drizzle definition of the comment table, named `name`. Put the result in your
|
|
8
|
+
* Drizzle schema so drizzle-kit can generate its migration; the store never creates it.
|
|
9
|
+
*
|
|
10
|
+
* Replies keep a foreign key to their parent, which is set to null when the parent is deleted.
|
|
11
|
+
*/
|
|
12
|
+
export function createPostgresCommentTable(name: string = DEFAULT_POSTGRES_COMMENT_TABLE_NAME) {
|
|
13
|
+
const table = pgTable(
|
|
14
|
+
name,
|
|
15
|
+
{
|
|
16
|
+
id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
|
|
17
|
+
postSlug: text('post_slug').notNull(),
|
|
18
|
+
author: text('author').notNull(),
|
|
19
|
+
email: text('email'),
|
|
20
|
+
content: text('content').notNull(),
|
|
21
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
22
|
+
approved: boolean('approved').notNull().default(false),
|
|
23
|
+
parentId: integer('parent_id').references((): AnyPgColumn => table.id, { onDelete: 'set null' }),
|
|
24
|
+
},
|
|
25
|
+
(columns) => [
|
|
26
|
+
index(`${name}_post_slug_created_at_idx`).on(columns.postSlug, columns.createdAt),
|
|
27
|
+
index(`${name}_parent_id_idx`).on(columns.parentId),
|
|
28
|
+
],
|
|
29
|
+
);
|
|
30
|
+
return table;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The Drizzle type of a Respectify comment table on Postgres. */
|
|
34
|
+
export type PostgresCommentTable = ReturnType<typeof createPostgresCommentTable>;
|
|
35
|
+
|
|
36
|
+
/** The comment table under its default name, ready to export from your Drizzle schema. */
|
|
37
|
+
export const respectifyComments: PostgresCommentTable = createPostgresCommentTable();
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createSqliteCommentStore, type SqliteCommentStoreOptions } from './store';
|
|
2
|
+
export {
|
|
3
|
+
createSqliteCommentTable,
|
|
4
|
+
respectifyComments,
|
|
5
|
+
DEFAULT_SQLITE_COMMENT_TABLE_NAME,
|
|
6
|
+
type SqliteCommentTable,
|
|
7
|
+
} from './table';
|
|
8
|
+
export { parseStoredDate } from './text-date';
|