@respectify/astro 0.1.7 → 0.1.9
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 +57 -2
- package/components/CommentSection.astro +7 -4
- package/package.json +3 -1
- package/respectify.config.sample.jsonc +151 -0
- package/src/actions.ts +26 -2
- package/src/credentials.ts +1 -0
- package/src/index.ts +7 -1
- package/src/lib/config.ts +56 -0
- package/src/lib/rate-limit.ts +24 -0
- package/src/lib/service.ts +125 -52
- package/src/runtime-config.ts +17 -5
- package/src/types.ts +40 -0
package/README.md
CHANGED
|
@@ -60,12 +60,18 @@ export default defineConfig({
|
|
|
60
60
|
|
|
61
61
|
### 3. Configure Respectify
|
|
62
62
|
|
|
63
|
-
Copy
|
|
63
|
+
Copy a starter config to your project root:
|
|
64
64
|
|
|
65
65
|
```bash
|
|
66
|
+
# Minimal defaults
|
|
66
67
|
cp node_modules/@respectify/astro/default-respectify.config.json ./respectify.config.json
|
|
68
|
+
|
|
69
|
+
# Or the fully commented sample (strip comments — JSON does not allow them)
|
|
70
|
+
cp node_modules/@respectify/astro/respectify.config.sample.jsonc ./respectify.config.json
|
|
67
71
|
```
|
|
68
72
|
|
|
73
|
+
See [`respectify.config.sample.jsonc`](./respectify.config.sample.jsonc) for every field and how it maps to `@respectify/client`.
|
|
74
|
+
|
|
69
75
|
Add environment variables:
|
|
70
76
|
|
|
71
77
|
```env
|
|
@@ -166,16 +172,65 @@ Override on `.rf-comments`:
|
|
|
166
172
|
|
|
167
173
|
### Integration options
|
|
168
174
|
|
|
175
|
+
Any `@respectify/client` option can be set via `client` and `megacall`. Values in `astro.config` override the same keys in `respectify.config.json`.
|
|
176
|
+
|
|
169
177
|
```ts
|
|
170
178
|
respectify({
|
|
171
179
|
configPath: './respectify.config.json',
|
|
172
180
|
commentsApiPath: '/api/respectify/comments',
|
|
173
181
|
showBranding: true,
|
|
174
182
|
getPostUrl: (slug, site) => `${site}/posts/${slug}/`,
|
|
183
|
+
|
|
184
|
+
// Alternative to getPostUrl: hand Respectify the post body directly instead of
|
|
185
|
+
// having it fetch getPostUrl. Useful for staged/preview/auth-gated content, or
|
|
186
|
+
// when the URL isn't live yet right after deploy. Takes priority over getPostUrl.
|
|
187
|
+
// getPostContent: async (slug) => loadPostBody(slug),
|
|
188
|
+
|
|
189
|
+
// Per-IP submission limit, enforced in the `comments.submit` action.
|
|
190
|
+
// In-memory per server process — not shared across multiple instances/regions.
|
|
175
191
|
rateLimit: { windowMs: 300_000, maxRequests: 10 },
|
|
192
|
+
|
|
193
|
+
// Forwarded to RespectifyClient (email/apiKey still default from env)
|
|
194
|
+
client: {
|
|
195
|
+
baseUrl: 'https://app.respectify.ai',
|
|
196
|
+
timeout: 30_000,
|
|
197
|
+
version: '0.2',
|
|
198
|
+
website: 'yoursite.com',
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
// Forwarded to every megacall (comment + articleId are set automatically)
|
|
202
|
+
megacall: {
|
|
203
|
+
includeSpam: true,
|
|
204
|
+
includeCommentScore: true,
|
|
205
|
+
includeRelevance: true,
|
|
206
|
+
includeDogwhistle: true,
|
|
207
|
+
bannedTopics: ['spam-topics'],
|
|
208
|
+
sensitiveTopics: [],
|
|
209
|
+
dogwhistleExamples: [],
|
|
210
|
+
},
|
|
176
211
|
});
|
|
177
212
|
```
|
|
178
213
|
|
|
214
|
+
`showBranding` and `commentsApiPath` set here become the defaults for `<CommentSection>` — you can still override either per-instance via props.
|
|
215
|
+
|
|
216
|
+
### Checking Respectify credentials
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
import { verifyRespectifyCredentials } from '@respectify/astro/credentials';
|
|
220
|
+
|
|
221
|
+
const isConnected = await verifyRespectifyCredentials();
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Useful for an admin health-check page — returns `true` when `RESPECTIFY_EMAIL`/`RESPECTIFY_API_KEY` (or `client.email`/`client.apiKey`) are valid and the subscription is active.
|
|
225
|
+
|
|
226
|
+
### `respectify.config.json`
|
|
227
|
+
|
|
228
|
+
Moderation policy lives in the JSON file. You can also put `client` / `megacall` there (same shapes as above). Integration options win on conflicts.
|
|
229
|
+
|
|
230
|
+
For a field-by-field walkthrough with comments, see [`respectify.config.sample.jsonc`](./respectify.config.sample.jsonc).
|
|
231
|
+
|
|
232
|
+
Replies automatically pass the parent comment text as `replyToComment` to Respectify.
|
|
233
|
+
|
|
179
234
|
### Admin delete (optional)
|
|
180
235
|
|
|
181
236
|
Set `enableDelete` on `CommentSection` and implement auth so `context.locals.isAuthenticated` is true. See the [Nick-Blog](https://github.com/NickHodges/Nick-Blog) repo for a full admin auth example.
|
|
@@ -185,7 +240,7 @@ Set `enableDelete` on `CommentSection` and implement auth so `context.locals.isA
|
|
|
185
240
|
```text
|
|
186
241
|
Visitor submits comment
|
|
187
242
|
→ Astro Action (comments.submit)
|
|
188
|
-
→ Respectify megacall (spam
|
|
243
|
+
→ Respectify megacall (configured checks: spam, score, relevance, dogwhistle, …)
|
|
189
244
|
→ If approved: save to Astro DB
|
|
190
245
|
→ Client refreshes comment list via GET /api/respectify/comments
|
|
191
246
|
```
|
|
@@ -3,13 +3,14 @@ import '@respectify/astro/styles.css';
|
|
|
3
3
|
import PoweredByRespectify from './PoweredByRespectify.astro';
|
|
4
4
|
import CommentList from './CommentList.astro';
|
|
5
5
|
import CommentForm from './CommentForm.astro';
|
|
6
|
+
import { getIntegrationOptions } from '../src/runtime-config';
|
|
6
7
|
|
|
7
8
|
interface Props {
|
|
8
9
|
/** Unique identifier for the page/post (e.g. blog slug) */
|
|
9
10
|
postSlug: string;
|
|
10
|
-
/** API path
|
|
11
|
+
/** API path (default: the integration's `commentsApiPath` option) */
|
|
11
12
|
apiPath?: string;
|
|
12
|
-
/** Show Powered by Respectify branding (default:
|
|
13
|
+
/** Show Powered by Respectify branding (default: the integration's `showBranding` option) */
|
|
13
14
|
showBranding?: boolean;
|
|
14
15
|
/** Enable admin delete controls when authenticated (default: false) */
|
|
15
16
|
enableDelete?: boolean;
|
|
@@ -19,10 +20,12 @@ interface Props {
|
|
|
19
20
|
style?: string;
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
const integrationOptions = getIntegrationOptions();
|
|
24
|
+
|
|
22
25
|
const {
|
|
23
26
|
postSlug,
|
|
24
|
-
apiPath =
|
|
25
|
-
showBranding =
|
|
27
|
+
apiPath = integrationOptions.commentsApiPath,
|
|
28
|
+
showBranding = integrationOptions.showBranding,
|
|
26
29
|
enableDelete = false,
|
|
27
30
|
class: className,
|
|
28
31
|
style,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@respectify/astro",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "Respectify-powered commenting for Astro — AI moderation, spam filtering, and beautiful UX out of the box.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"exports": {
|
|
31
31
|
".": "./src/index.ts",
|
|
32
32
|
"./actions": "./src/actions.ts",
|
|
33
|
+
"./credentials": "./src/credentials.ts",
|
|
33
34
|
"./schema": "./src/schema.ts",
|
|
34
35
|
"./routes/comments": "./src/routes/comments.ts",
|
|
35
36
|
"./components/CommentSection.astro": "./components/CommentSection.astro",
|
|
@@ -42,6 +43,7 @@
|
|
|
42
43
|
"components",
|
|
43
44
|
"client",
|
|
44
45
|
"default-respectify.config.json",
|
|
46
|
+
"respectify.config.sample.jsonc",
|
|
45
47
|
"README.md"
|
|
46
48
|
],
|
|
47
49
|
"peerDependencies": {
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// Respectify Astro — sample config
|
|
3
|
+
// =============================================================================
|
|
4
|
+
//
|
|
5
|
+
// Copy this file to your project root as `respectify.config.json` and trim
|
|
6
|
+
// comments (JSON does not allow comments). Or keep a `.jsonc` copy for
|
|
7
|
+
// reference and point the integration at a plain JSON file via `configPath`.
|
|
8
|
+
//
|
|
9
|
+
// cp node_modules/@respectify/astro/respectify.config.sample.jsonc \
|
|
10
|
+
// ./respectify.config.json
|
|
11
|
+
//
|
|
12
|
+
// Values here merge with options passed to `respectify({ ... })` in
|
|
13
|
+
// astro.config. Integration options win on conflicts for `client` / `megacall`.
|
|
14
|
+
//
|
|
15
|
+
// Credentials still come from env by default:
|
|
16
|
+
// RESPECTIFY_EMAIL
|
|
17
|
+
// RESPECTIFY_API_KEY
|
|
18
|
+
//
|
|
19
|
+
// Astro-only options (not in this file) go in astro.config:
|
|
20
|
+
// respectify({
|
|
21
|
+
// configPath: './respectify.config.json',
|
|
22
|
+
// commentsApiPath: '/api/respectify/comments',
|
|
23
|
+
// showBranding: true,
|
|
24
|
+
// getPostUrl: (slug, site) => `${site}/posts/${slug}/`,
|
|
25
|
+
// rateLimit: { windowMs: 300_000, maxRequests: 10 },
|
|
26
|
+
// client: { /* same shape as "client" below */ },
|
|
27
|
+
// megacall: { /* same shape as "megacall" below */ },
|
|
28
|
+
// })
|
|
29
|
+
//
|
|
30
|
+
// =============================================================================
|
|
31
|
+
|
|
32
|
+
{
|
|
33
|
+
// Master switch. When false, comments skip the Respectify API and are
|
|
34
|
+
// auto-approved with `feedback.approved`.
|
|
35
|
+
"enabled": true,
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// client — forwarded to RespectifyClient
|
|
39
|
+
// See: https://www.npmjs.com/package/@respectify/client
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
"client": {
|
|
42
|
+
// API base URL (default: https://app.respectify.ai)
|
|
43
|
+
"baseUrl": "https://app.respectify.ai",
|
|
44
|
+
|
|
45
|
+
// API version path segment (default: "0.2")
|
|
46
|
+
"version": "0.2",
|
|
47
|
+
|
|
48
|
+
// Request timeout in milliseconds (default: 30000)
|
|
49
|
+
"timeout": 30000,
|
|
50
|
+
|
|
51
|
+
// Optional website domain for license / usage tracking
|
|
52
|
+
"website": "yoursite.com"
|
|
53
|
+
|
|
54
|
+
// Optional credential overrides (prefer env vars in production):
|
|
55
|
+
// "email": "you@example.com",
|
|
56
|
+
// "apiKey": "your-api-key"
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// megacall — forwarded to every Respectify megacall
|
|
61
|
+
// `comment` and `articleId` are set automatically by the integration.
|
|
62
|
+
// Replies also set `replyToComment` from the parent comment text.
|
|
63
|
+
// Relevance / comment score / dogwhistle require a topic (articleId); if
|
|
64
|
+
// topic init fails, those flags are dropped and only spam (if enabled) runs.
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
"megacall": {
|
|
67
|
+
// Spam detection (default: true)
|
|
68
|
+
"includeSpam": true,
|
|
69
|
+
|
|
70
|
+
// Toxicity / quality / fallacy scoring (default: true when a topic exists)
|
|
71
|
+
"includeCommentScore": true,
|
|
72
|
+
|
|
73
|
+
// On-topic + banned-topic analysis (requires topic / articleId)
|
|
74
|
+
"includeRelevance": false,
|
|
75
|
+
|
|
76
|
+
// Dogwhistle / coded-language detection (requires topic / articleId)
|
|
77
|
+
"includeDogwhistle": false,
|
|
78
|
+
|
|
79
|
+
// Topics that should fail the relevance check when discussed
|
|
80
|
+
"bannedTopics": [],
|
|
81
|
+
|
|
82
|
+
// Sensitive topics used to focus dogwhistle detection
|
|
83
|
+
"sensitiveTopics": [],
|
|
84
|
+
|
|
85
|
+
// Example dogwhistle phrases to help the model
|
|
86
|
+
"dogwhistleExamples": []
|
|
87
|
+
|
|
88
|
+
// Normally set per-request for replies — only set here if you want a fixed value:
|
|
89
|
+
// "replyToComment": "Parent comment text"
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// moderation — how megacall results become approve / reject decisions
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
"moderation": {
|
|
96
|
+
// Block comments whose respectfulness score is below `thresholds.block`
|
|
97
|
+
"blockDisrespectful": true,
|
|
98
|
+
|
|
99
|
+
// Mid-band scores (between block and autoApprove): allow through with
|
|
100
|
+
// `feedback.warning` when true; otherwise treat like a soft reject path
|
|
101
|
+
"allowOverride": false,
|
|
102
|
+
|
|
103
|
+
// Include revision suggestions (toxicity explanation, fallacies, etc.)
|
|
104
|
+
// in the action response (default: true)
|
|
105
|
+
"showFeedbackToUser": true,
|
|
106
|
+
|
|
107
|
+
// When megacall.includeRelevance is true, reject off-topic comments or
|
|
108
|
+
// those matching bannedTopics (default: true)
|
|
109
|
+
"blockOffTopic": true,
|
|
110
|
+
|
|
111
|
+
// When megacall.includeDogwhistle is true, reject detected dogwhistles
|
|
112
|
+
// (default: true)
|
|
113
|
+
"blockDogwhistles": true
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// thresholds — respectfulness score bands (0.0–1.0)
|
|
118
|
+
// Score is derived as `1 - toxicity_score` from comment_score when available.
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
"thresholds": {
|
|
121
|
+
// Score >= this → approve with `feedback.approved`
|
|
122
|
+
"autoApprove": 0.7,
|
|
123
|
+
|
|
124
|
+
// Reserved mid band (kept for compatibility; decisions use autoApprove/block)
|
|
125
|
+
"warn": 0.5,
|
|
126
|
+
|
|
127
|
+
// Score < this + blockDisrespectful → reject with `feedback.blocked`
|
|
128
|
+
"block": 0.3
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// feedback — user-facing messages returned by the submit action
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
"feedback": {
|
|
135
|
+
"approved": "Thank you for your respectful comment!",
|
|
136
|
+
"warning": "Your comment may contain disrespectful language. Please consider revising it.",
|
|
137
|
+
"blocked": "Your comment does not meet our respectfulness standards. Please revise and try again.",
|
|
138
|
+
|
|
139
|
+
// Used when blockOffTopic rejects a comment (optional)
|
|
140
|
+
"offTopic": "This comment appears to be off-topic.",
|
|
141
|
+
|
|
142
|
+
// Used when blockDogwhistles rejects a comment (optional)
|
|
143
|
+
"dogwhistle": "This comment was blocked due to policy violations."
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// Legacy (optional)
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
// Deprecated: use client.baseUrl instead. Still accepted and mapped to baseUrl.
|
|
150
|
+
// "apiEndpoint": "https://app.respectify.ai"
|
|
151
|
+
}
|
package/src/actions.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { defineAction, ActionError } from 'astro:actions';
|
|
|
2
2
|
import { z } from 'astro/zod';
|
|
3
3
|
import { db, Comment, eq } from 'astro:db';
|
|
4
4
|
import { analyzeComment } from './lib/service';
|
|
5
|
+
import { checkRateLimit } from './lib/rate-limit';
|
|
6
|
+
import { getIntegrationOptions } from './runtime-config';
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* Merge into your src/actions/index.ts:
|
|
@@ -25,8 +27,30 @@ export const respectifyCommentActions = {
|
|
|
25
27
|
content: z.string().min(1).max(5000),
|
|
26
28
|
parentId: z.number().optional(),
|
|
27
29
|
}),
|
|
28
|
-
handler: async ({ postSlug, author, email, content, parentId }) => {
|
|
29
|
-
const
|
|
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 });
|
|
30
54
|
|
|
31
55
|
if (!analysis.approved) {
|
|
32
56
|
return {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { verifyRespectifyCredentials } from './lib/service';
|
package/src/index.ts
CHANGED
|
@@ -31,4 +31,10 @@ export default function respectify(userOptions: RespectifyIntegrationOptions = {
|
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
export type {
|
|
34
|
+
export type {
|
|
35
|
+
RespectifyIntegrationOptions,
|
|
36
|
+
RespectifyAnalysisResult,
|
|
37
|
+
RespectifyClientConfig,
|
|
38
|
+
RespectifyMegacallConfig,
|
|
39
|
+
AnalyzeCommentOptions,
|
|
40
|
+
} from './types';
|
package/src/lib/config.ts
CHANGED
|
@@ -2,9 +2,35 @@ import { z } from 'zod';
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { getIntegrationOptions } from '../runtime-config';
|
|
5
|
+
import type { RespectifyClientConfig, RespectifyMegacallConfig } from '../types';
|
|
6
|
+
|
|
7
|
+
const MegacallConfigSchema = z
|
|
8
|
+
.object({
|
|
9
|
+
includeSpam: z.boolean().optional(),
|
|
10
|
+
includeRelevance: z.boolean().optional(),
|
|
11
|
+
includeCommentScore: z.boolean().optional(),
|
|
12
|
+
includeDogwhistle: z.boolean().optional(),
|
|
13
|
+
bannedTopics: z.array(z.string()).optional(),
|
|
14
|
+
sensitiveTopics: z.array(z.string()).optional(),
|
|
15
|
+
dogwhistleExamples: z.array(z.string()).optional(),
|
|
16
|
+
replyToComment: z.string().optional(),
|
|
17
|
+
})
|
|
18
|
+
.optional();
|
|
19
|
+
|
|
20
|
+
const ClientConfigSchema = z
|
|
21
|
+
.object({
|
|
22
|
+
baseUrl: z.string().url().optional(),
|
|
23
|
+
version: z.string().optional(),
|
|
24
|
+
timeout: z.number().positive().optional(),
|
|
25
|
+
website: z.string().optional(),
|
|
26
|
+
email: z.string().email().optional(),
|
|
27
|
+
apiKey: z.string().optional(),
|
|
28
|
+
})
|
|
29
|
+
.optional();
|
|
5
30
|
|
|
6
31
|
const RespectifyConfigSchema = z.object({
|
|
7
32
|
enabled: z.boolean(),
|
|
33
|
+
/** @deprecated Prefer `client.baseUrl` — still accepted and mapped to the client base URL */
|
|
8
34
|
apiEndpoint: z.string().url().optional(),
|
|
9
35
|
requiresAuth: z.boolean().optional(),
|
|
10
36
|
autoPublish: z
|
|
@@ -17,6 +43,10 @@ const RespectifyConfigSchema = z.object({
|
|
|
17
43
|
blockDisrespectful: z.boolean(),
|
|
18
44
|
showFeedbackToUser: z.boolean().optional(),
|
|
19
45
|
allowOverride: z.boolean(),
|
|
46
|
+
/** Reject comments that fail relevance / banned-topic checks (default: true when relevance is enabled) */
|
|
47
|
+
blockOffTopic: z.boolean().optional(),
|
|
48
|
+
/** Reject comments when dogwhistles are detected (default: true when dogwhistle is enabled) */
|
|
49
|
+
blockDogwhistles: z.boolean().optional(),
|
|
20
50
|
}),
|
|
21
51
|
thresholds: z.object({
|
|
22
52
|
autoApprove: z.number().min(0).max(1),
|
|
@@ -27,7 +57,13 @@ const RespectifyConfigSchema = z.object({
|
|
|
27
57
|
approved: z.string(),
|
|
28
58
|
warning: z.string(),
|
|
29
59
|
blocked: z.string(),
|
|
60
|
+
offTopic: z.string().optional(),
|
|
61
|
+
dogwhistle: z.string().optional(),
|
|
30
62
|
}),
|
|
63
|
+
/** Options forwarded to RespectifyClient (merged with integration `client` options) */
|
|
64
|
+
client: ClientConfigSchema,
|
|
65
|
+
/** Options forwarded to megacall (merged with integration `megacall` options) */
|
|
66
|
+
megacall: MegacallConfigSchema,
|
|
31
67
|
});
|
|
32
68
|
|
|
33
69
|
export type RespectifyConfig = z.infer<typeof RespectifyConfigSchema>;
|
|
@@ -54,6 +90,26 @@ export function loadRespectifyConfig(): RespectifyConfig {
|
|
|
54
90
|
}
|
|
55
91
|
}
|
|
56
92
|
|
|
93
|
+
/** Merge JSON + integration client options. Integration options win. */
|
|
94
|
+
export function resolveClientConfig(config: RespectifyConfig): RespectifyClientConfig {
|
|
95
|
+
const { client: integrationClient } = getIntegrationOptions();
|
|
96
|
+
const fromJson: RespectifyClientConfig = {
|
|
97
|
+
...(config.apiEndpoint ? { baseUrl: config.apiEndpoint } : {}),
|
|
98
|
+
...config.client,
|
|
99
|
+
};
|
|
100
|
+
return { ...fromJson, ...integrationClient };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Merge JSON + integration megacall options. Integration options win. */
|
|
104
|
+
export function resolveMegacallConfig(config: RespectifyConfig): RespectifyMegacallConfig {
|
|
105
|
+
const { megacall: integrationMegacall } = getIntegrationOptions();
|
|
106
|
+
return {
|
|
107
|
+
includeSpam: true,
|
|
108
|
+
...config.megacall,
|
|
109
|
+
...integrationMegacall,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
57
113
|
export function getDefaultConfig(): RespectifyConfig {
|
|
58
114
|
return {
|
|
59
115
|
enabled: true,
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
interface Bucket {
|
|
2
|
+
count: number;
|
|
3
|
+
resetAt: number;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
const buckets = new Map<string, Bucket>();
|
|
7
|
+
|
|
8
|
+
/** Simple in-memory fixed-window rate limiter, keyed per process (not shared across instances/regions). */
|
|
9
|
+
export function checkRateLimit(key: string, windowMs: number, maxRequests: number): boolean {
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
const bucket = buckets.get(key);
|
|
12
|
+
|
|
13
|
+
if (!bucket || now >= bucket.resetAt) {
|
|
14
|
+
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (bucket.count >= maxRequests) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
bucket.count += 1;
|
|
23
|
+
return true;
|
|
24
|
+
}
|
package/src/lib/service.ts
CHANGED
|
@@ -1,57 +1,83 @@
|
|
|
1
1
|
import type { RespectifyConfig } from './config';
|
|
2
|
-
import { loadRespectifyConfig } from './config';
|
|
2
|
+
import { loadRespectifyConfig, resolveClientConfig, resolveMegacallConfig } from './config';
|
|
3
3
|
import { RESPECTIFY_API_KEY, RESPECTIFY_EMAIL } from 'astro:env/server';
|
|
4
4
|
import {
|
|
5
5
|
RespectifyClient,
|
|
6
6
|
AuthenticationError,
|
|
7
7
|
PaymentRequiredError,
|
|
8
8
|
RespectifyError,
|
|
9
|
+
type MegacallOptions,
|
|
10
|
+
type MegaCallResult,
|
|
9
11
|
} from '@respectify/client';
|
|
10
12
|
import { getIntegrationOptions } from '../runtime-config';
|
|
11
13
|
import { logger } from './logger';
|
|
12
|
-
import type { RespectifyAnalysisResult } from '../types';
|
|
14
|
+
import type { AnalyzeCommentOptions, RespectifyAnalysisResult } from '../types';
|
|
13
15
|
|
|
14
16
|
let client: RespectifyClient | null = null;
|
|
17
|
+
let clientFingerprint: string | null = null;
|
|
15
18
|
const articleIdCache = new Map<string, string>();
|
|
16
19
|
|
|
17
|
-
function getRespectifyClient(): RespectifyClient {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
function getRespectifyClient(config: RespectifyConfig): RespectifyClient {
|
|
21
|
+
const clientConfig = resolveClientConfig(config);
|
|
22
|
+
const email = clientConfig.email ?? RESPECTIFY_EMAIL;
|
|
23
|
+
const apiKey = clientConfig.apiKey ?? RESPECTIFY_API_KEY;
|
|
24
|
+
|
|
25
|
+
if (!email || !apiKey) {
|
|
26
|
+
throw new Error('Respectify credentials not configured. Set RESPECTIFY_EMAIL and RESPECTIFY_API_KEY.');
|
|
27
|
+
}
|
|
22
28
|
|
|
29
|
+
const fingerprint = JSON.stringify({
|
|
30
|
+
email,
|
|
31
|
+
apiKey,
|
|
32
|
+
baseUrl: clientConfig.baseUrl,
|
|
33
|
+
version: clientConfig.version,
|
|
34
|
+
timeout: clientConfig.timeout,
|
|
35
|
+
website: clientConfig.website,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
if (!client || clientFingerprint !== fingerprint) {
|
|
23
39
|
client = new RespectifyClient({
|
|
24
|
-
email
|
|
25
|
-
apiKey
|
|
40
|
+
email,
|
|
41
|
+
apiKey,
|
|
42
|
+
...(clientConfig.baseUrl !== undefined ? { baseUrl: clientConfig.baseUrl } : {}),
|
|
43
|
+
...(clientConfig.version !== undefined ? { version: clientConfig.version } : {}),
|
|
44
|
+
...(clientConfig.timeout !== undefined ? { timeout: clientConfig.timeout } : {}),
|
|
45
|
+
...(clientConfig.website !== undefined ? { website: clientConfig.website } : {}),
|
|
26
46
|
});
|
|
47
|
+
clientFingerprint = fingerprint;
|
|
27
48
|
}
|
|
28
49
|
|
|
29
50
|
return client;
|
|
30
51
|
}
|
|
31
52
|
|
|
32
|
-
async function getOrInitializeArticleId(postSlug: string): Promise<string> {
|
|
53
|
+
async function getOrInitializeArticleId(postSlug: string, config: RespectifyConfig): Promise<string> {
|
|
33
54
|
const cached = articleIdCache.get(postSlug);
|
|
34
55
|
if (cached) return cached;
|
|
35
56
|
|
|
36
|
-
const { getPostUrl } = getIntegrationOptions();
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
throw new Error('import.meta.env.SITE must be set in astro.config.ts for Respectify topic initialization.');
|
|
40
|
-
}
|
|
57
|
+
const { getPostUrl, getPostContent } = getIntegrationOptions();
|
|
58
|
+
const respectifyClient = getRespectifyClient(config);
|
|
59
|
+
const topicDescription = `Post: ${postSlug}`;
|
|
41
60
|
|
|
42
|
-
const
|
|
43
|
-
|
|
61
|
+
const result = await (getPostContent
|
|
62
|
+
? respectifyClient.initTopicFromText(await getPostContent(postSlug), topicDescription)
|
|
63
|
+
: (() => {
|
|
64
|
+
const site = import.meta.env.SITE;
|
|
65
|
+
if (!site) {
|
|
66
|
+
throw new Error('import.meta.env.SITE must be set in astro.config.ts for Respectify topic initialization.');
|
|
67
|
+
}
|
|
68
|
+
return respectifyClient.initTopicFromUrl(getPostUrl!(postSlug, site), topicDescription);
|
|
69
|
+
})());
|
|
44
70
|
|
|
45
|
-
const result = await respectifyClient.initTopicFromUrl(postUrl, `Post: ${postSlug}`);
|
|
46
71
|
articleIdCache.set(postSlug, result.article_id);
|
|
47
|
-
logger.info('Initialized Respectify topic', { postSlug });
|
|
72
|
+
logger.info('Initialized Respectify topic', { postSlug, source: getPostContent ? 'text' : 'url' });
|
|
48
73
|
|
|
49
74
|
return result.article_id;
|
|
50
75
|
}
|
|
51
76
|
|
|
52
77
|
export async function verifyRespectifyCredentials(): Promise<boolean> {
|
|
53
78
|
try {
|
|
54
|
-
const
|
|
79
|
+
const config = loadRespectifyConfig();
|
|
80
|
+
const respectifyClient = getRespectifyClient(config);
|
|
55
81
|
const result = await respectifyClient.checkUserCredentials();
|
|
56
82
|
return result.active;
|
|
57
83
|
} catch (error) {
|
|
@@ -60,7 +86,41 @@ export async function verifyRespectifyCredentials(): Promise<boolean> {
|
|
|
60
86
|
}
|
|
61
87
|
}
|
|
62
88
|
|
|
63
|
-
|
|
89
|
+
function buildSuggestion(result: MegaCallResult, showFeedback: boolean): string | undefined {
|
|
90
|
+
if (!showFeedback || !result.comment_score) return undefined;
|
|
91
|
+
|
|
92
|
+
const suggestions: string[] = [];
|
|
93
|
+
|
|
94
|
+
if (result.comment_score.toxicity_explanation) {
|
|
95
|
+
suggestions.push(result.comment_score.toxicity_explanation);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (result.comment_score.logical_fallacies.length > 0) {
|
|
99
|
+
suggestions.push(
|
|
100
|
+
`Logical fallacies detected: ${result.comment_score.logical_fallacies.map((f) => f.fallacy_name).join(', ')}`,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (result.comment_score.objectionable_phrases.length > 0) {
|
|
105
|
+
suggestions.push(`Objectionable phrases found: ${result.comment_score.objectionable_phrases.length} issue(s)`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (result.relevance_check && !result.relevance_check.on_topic.on_topic) {
|
|
109
|
+
suggestions.push(result.relevance_check.on_topic.reasoning);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (result.dogwhistle_check?.detection.dogwhistles_detected && result.dogwhistle_check.detection.reasoning) {
|
|
113
|
+
suggestions.push(result.dogwhistle_check.detection.reasoning);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return suggestions.length > 0 ? suggestions.join(' ') : undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function analyzeComment(
|
|
120
|
+
text: string,
|
|
121
|
+
postSlug?: string,
|
|
122
|
+
options: AnalyzeCommentOptions = {},
|
|
123
|
+
): Promise<RespectifyAnalysisResult> {
|
|
64
124
|
const config: RespectifyConfig = loadRespectifyConfig();
|
|
65
125
|
|
|
66
126
|
if (!config.enabled) {
|
|
@@ -72,12 +132,12 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
72
132
|
}
|
|
73
133
|
|
|
74
134
|
try {
|
|
75
|
-
const respectifyClient = getRespectifyClient();
|
|
135
|
+
const respectifyClient = getRespectifyClient(config);
|
|
76
136
|
let respectifyArticleId: string | undefined;
|
|
77
137
|
|
|
78
138
|
if (postSlug) {
|
|
79
139
|
try {
|
|
80
|
-
respectifyArticleId = await getOrInitializeArticleId(postSlug);
|
|
140
|
+
respectifyArticleId = await getOrInitializeArticleId(postSlug, config);
|
|
81
141
|
} catch (error) {
|
|
82
142
|
logger.warn('Could not initialize Respectify article ID; falling back to spam-only check', {
|
|
83
143
|
postSlug,
|
|
@@ -86,22 +146,31 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
86
146
|
}
|
|
87
147
|
}
|
|
88
148
|
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
includeSpam: boolean;
|
|
93
|
-
includeCommentScore?: boolean;
|
|
94
|
-
} = {
|
|
149
|
+
const megacallDefaults = resolveMegacallConfig(config);
|
|
150
|
+
const megacallOptions: MegacallOptions = {
|
|
151
|
+
...megacallDefaults,
|
|
95
152
|
comment: text,
|
|
96
|
-
includeSpam: true,
|
|
97
153
|
};
|
|
98
154
|
|
|
99
155
|
if (respectifyArticleId) {
|
|
100
156
|
megacallOptions.articleId = respectifyArticleId;
|
|
101
|
-
|
|
157
|
+
// Score requires an article; enable by default when topic context exists unless explicitly disabled
|
|
158
|
+
if (megacallOptions.includeCommentScore === undefined) {
|
|
159
|
+
megacallOptions.includeCommentScore = true;
|
|
160
|
+
}
|
|
161
|
+
} else {
|
|
162
|
+
// Relevance / comment score / dogwhistle require articleId — drop them without context
|
|
163
|
+
delete megacallOptions.includeRelevance;
|
|
164
|
+
delete megacallOptions.includeCommentScore;
|
|
165
|
+
delete megacallOptions.includeDogwhistle;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (options.replyToComment !== undefined) {
|
|
169
|
+
megacallOptions.replyToComment = options.replyToComment;
|
|
102
170
|
}
|
|
103
171
|
|
|
104
172
|
const result = await respectifyClient.megacall(megacallOptions);
|
|
173
|
+
const showFeedback = config.moderation.showFeedbackToUser !== false;
|
|
105
174
|
|
|
106
175
|
if (result.spam_check?.is_spam) {
|
|
107
176
|
return {
|
|
@@ -113,6 +182,30 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
113
182
|
};
|
|
114
183
|
}
|
|
115
184
|
|
|
185
|
+
const blockOffTopic = config.moderation.blockOffTopic !== false;
|
|
186
|
+
if (blockOffTopic && result.relevance_check) {
|
|
187
|
+
const { on_topic, banned_topics } = result.relevance_check;
|
|
188
|
+
const hasBannedTopics = banned_topics.banned_topics.length > 0 && banned_topics.quantity_on_banned_topics > 0;
|
|
189
|
+
if (!on_topic.on_topic || hasBannedTopics) {
|
|
190
|
+
return {
|
|
191
|
+
score: 0,
|
|
192
|
+
approved: false,
|
|
193
|
+
feedback: config.feedback.offTopic ?? 'This comment appears to be off-topic.',
|
|
194
|
+
suggestion: showFeedback ? on_topic.reasoning || banned_topics.reasoning : undefined,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const blockDogwhistles = config.moderation.blockDogwhistles !== false;
|
|
200
|
+
if (blockDogwhistles && result.dogwhistle_check?.detection.dogwhistles_detected) {
|
|
201
|
+
return {
|
|
202
|
+
score: 0,
|
|
203
|
+
approved: false,
|
|
204
|
+
feedback: config.feedback.dogwhistle ?? 'This comment was blocked due to policy violations.',
|
|
205
|
+
suggestion: showFeedback ? result.dogwhistle_check.detection.reasoning : undefined,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
116
209
|
let respectfulnessScore = config.thresholds.autoApprove;
|
|
117
210
|
|
|
118
211
|
if (result.comment_score) {
|
|
@@ -134,33 +227,13 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
134
227
|
feedback = config.feedback.warning;
|
|
135
228
|
}
|
|
136
229
|
|
|
137
|
-
let suggestion: string | undefined;
|
|
138
|
-
if (result.comment_score) {
|
|
139
|
-
const suggestions: string[] = [];
|
|
140
|
-
|
|
141
|
-
if (result.comment_score.toxicity_explanation) {
|
|
142
|
-
suggestions.push(result.comment_score.toxicity_explanation);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
if (result.comment_score.logical_fallacies.length > 0) {
|
|
146
|
-
suggestions.push(
|
|
147
|
-
`Logical fallacies detected: ${result.comment_score.logical_fallacies.map((f) => f.fallacy_name).join(', ')}`,
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
if (result.comment_score.objectionable_phrases.length > 0) {
|
|
152
|
-
suggestions.push(`Objectionable phrases found: ${result.comment_score.objectionable_phrases.length} issue(s)`);
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
if (suggestions.length > 0) suggestion = suggestions.join(' ');
|
|
156
|
-
}
|
|
157
|
-
|
|
158
230
|
const analysisResult: RespectifyAnalysisResult = {
|
|
159
231
|
score: respectfulnessScore,
|
|
160
232
|
approved,
|
|
161
233
|
feedback,
|
|
162
234
|
};
|
|
163
235
|
|
|
236
|
+
const suggestion = buildSuggestion(result, showFeedback);
|
|
164
237
|
if (suggestion) analysisResult.suggestion = suggestion;
|
|
165
238
|
|
|
166
239
|
return analysisResult;
|
package/src/runtime-config.ts
CHANGED
|
@@ -1,25 +1,37 @@
|
|
|
1
|
-
import type { RespectifyIntegrationOptions } from './types';
|
|
1
|
+
import type { RespectifyIntegrationOptions, RespectifyClientConfig, RespectifyMegacallConfig } from './types';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
Pick<RespectifyIntegrationOptions, '
|
|
3
|
+
export type ResolvedIntegrationOptions = Required<
|
|
4
|
+
Pick<RespectifyIntegrationOptions, 'configPath' | 'commentsApiPath' | 'showBranding'>
|
|
5
|
+
> &
|
|
6
|
+
Pick<RespectifyIntegrationOptions, 'getPostUrl' | 'getPostContent' | 'rateLimit' | 'client' | 'megacall'>;
|
|
7
|
+
|
|
8
|
+
const defaults: ResolvedIntegrationOptions = {
|
|
5
9
|
configPath: './respectify.config.json',
|
|
6
10
|
commentsApiPath: '/api/respectify/comments',
|
|
7
11
|
showBranding: true,
|
|
8
12
|
getPostUrl: (slug, site) => `${site.replace(/\/$/, '')}/posts/${slug}/`,
|
|
13
|
+
getPostContent: undefined,
|
|
9
14
|
rateLimit: { windowMs: 5 * 60 * 1000, maxRequests: 10 },
|
|
15
|
+
client: undefined,
|
|
16
|
+
megacall: undefined,
|
|
10
17
|
};
|
|
11
18
|
|
|
12
|
-
let options:
|
|
19
|
+
let options: ResolvedIntegrationOptions = { ...defaults };
|
|
13
20
|
|
|
14
21
|
export function setIntegrationOptions(userOptions: RespectifyIntegrationOptions = {}): void {
|
|
15
22
|
options = {
|
|
16
23
|
...defaults,
|
|
17
24
|
...userOptions,
|
|
18
25
|
getPostUrl: userOptions.getPostUrl ?? defaults.getPostUrl,
|
|
26
|
+
getPostContent: userOptions.getPostContent,
|
|
19
27
|
rateLimit: userOptions.rateLimit ?? defaults.rateLimit,
|
|
28
|
+
client: userOptions.client,
|
|
29
|
+
megacall: userOptions.megacall,
|
|
20
30
|
};
|
|
21
31
|
}
|
|
22
32
|
|
|
23
|
-
export function getIntegrationOptions():
|
|
33
|
+
export function getIntegrationOptions(): ResolvedIntegrationOptions {
|
|
24
34
|
return options;
|
|
25
35
|
}
|
|
36
|
+
|
|
37
|
+
export type { RespectifyClientConfig, RespectifyMegacallConfig };
|
package/src/types.ts
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
import type { MegacallOptions, RespectifyClientOptions } from '@respectify/client';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Options forwarded to `RespectifyClient`.
|
|
5
|
+
* Email and API key default to `RESPECTIFY_EMAIL` / `RESPECTIFY_API_KEY` env vars.
|
|
6
|
+
*/
|
|
7
|
+
export type RespectifyClientConfig = Partial<RespectifyClientOptions>;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Options forwarded to every `megacall`.
|
|
11
|
+
* `comment` and `articleId` are set automatically by the integration.
|
|
12
|
+
*/
|
|
13
|
+
export type RespectifyMegacallConfig = Omit<MegacallOptions, 'comment' | 'articleId'>;
|
|
14
|
+
|
|
1
15
|
export interface RespectifyIntegrationOptions {
|
|
2
16
|
/** Path to respectify.config.json (default: ./respectify.config.json) */
|
|
3
17
|
configPath?: string;
|
|
@@ -5,6 +19,14 @@ export interface RespectifyIntegrationOptions {
|
|
|
5
19
|
/** Build the canonical URL for a post — used to initialize Respectify topics */
|
|
6
20
|
getPostUrl?: (slug: string, site: string) => string;
|
|
7
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Provide a post's raw text content directly instead of having Respectify fetch
|
|
24
|
+
* `getPostUrl`. Useful when the URL isn't publicly fetchable (staged/preview content,
|
|
25
|
+
* auth-gated pages, or timing issues right after deploy). Takes priority over
|
|
26
|
+
* `getPostUrl` for topic initialization when provided.
|
|
27
|
+
*/
|
|
28
|
+
getPostContent?: (slug: string) => string | Promise<string>;
|
|
29
|
+
|
|
8
30
|
/** API route path for fetching comments (default: /api/respectify/comments) */
|
|
9
31
|
commentsApiPath?: string;
|
|
10
32
|
|
|
@@ -16,6 +38,24 @@ export interface RespectifyIntegrationOptions {
|
|
|
16
38
|
windowMs: number;
|
|
17
39
|
maxRequests: number;
|
|
18
40
|
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Options forwarded to the Respectify API client
|
|
44
|
+
* (`baseUrl`, `timeout`, `version`, `website`, optional credential overrides).
|
|
45
|
+
*/
|
|
46
|
+
client?: RespectifyClientConfig;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Options forwarded to every Respectify megacall
|
|
50
|
+
* (`includeSpam`, `includeRelevance`, `includeCommentScore`, `includeDogwhistle`,
|
|
51
|
+
* `bannedTopics`, `sensitiveTopics`, `dogwhistleExamples`, `replyToComment`).
|
|
52
|
+
*/
|
|
53
|
+
megacall?: RespectifyMegacallConfig;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface AnalyzeCommentOptions {
|
|
57
|
+
/** Parent comment text when submitting a reply */
|
|
58
|
+
replyToComment?: string;
|
|
19
59
|
}
|
|
20
60
|
|
|
21
61
|
export interface RespectifyAnalysisResult {
|