@respectify/astro 0.1.7 → 0.1.8
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 +37 -2
- package/package.json +2 -1
- package/respectify.config.sample.jsonc +151 -0
- package/src/actions.ts +7 -1
- package/src/index.ts +7 -1
- package/src/lib/config.ts +56 -0
- package/src/lib/service.ts +113 -44
- package/src/runtime-config.ts +15 -5
- package/src/types.ts +32 -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,6 +172,8 @@ 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',
|
|
@@ -173,9 +181,36 @@ respectify({
|
|
|
173
181
|
showBranding: true,
|
|
174
182
|
getPostUrl: (slug, site) => `${site}/posts/${slug}/`,
|
|
175
183
|
rateLimit: { windowMs: 300_000, maxRequests: 10 },
|
|
184
|
+
|
|
185
|
+
// Forwarded to RespectifyClient (email/apiKey still default from env)
|
|
186
|
+
client: {
|
|
187
|
+
baseUrl: 'https://app.respectify.ai',
|
|
188
|
+
timeout: 30_000,
|
|
189
|
+
version: '0.2',
|
|
190
|
+
website: 'yoursite.com',
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
// Forwarded to every megacall (comment + articleId are set automatically)
|
|
194
|
+
megacall: {
|
|
195
|
+
includeSpam: true,
|
|
196
|
+
includeCommentScore: true,
|
|
197
|
+
includeRelevance: true,
|
|
198
|
+
includeDogwhistle: true,
|
|
199
|
+
bannedTopics: ['spam-topics'],
|
|
200
|
+
sensitiveTopics: [],
|
|
201
|
+
dogwhistleExamples: [],
|
|
202
|
+
},
|
|
176
203
|
});
|
|
177
204
|
```
|
|
178
205
|
|
|
206
|
+
### `respectify.config.json`
|
|
207
|
+
|
|
208
|
+
Moderation policy lives in the JSON file. You can also put `client` / `megacall` there (same shapes as above). Integration options win on conflicts.
|
|
209
|
+
|
|
210
|
+
For a field-by-field walkthrough with comments, see [`respectify.config.sample.jsonc`](./respectify.config.sample.jsonc).
|
|
211
|
+
|
|
212
|
+
Replies automatically pass the parent comment text as `replyToComment` to Respectify.
|
|
213
|
+
|
|
179
214
|
### Admin delete (optional)
|
|
180
215
|
|
|
181
216
|
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 +220,7 @@ Set `enableDelete` on `CommentSection` and implement auth so `context.locals.isA
|
|
|
185
220
|
```text
|
|
186
221
|
Visitor submits comment
|
|
187
222
|
→ Astro Action (comments.submit)
|
|
188
|
-
→ Respectify megacall (spam
|
|
223
|
+
→ Respectify megacall (configured checks: spam, score, relevance, dogwhistle, …)
|
|
189
224
|
→ If approved: save to Astro DB
|
|
190
225
|
→ Client refreshes comment list via GET /api/respectify/comments
|
|
191
226
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@respectify/astro",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
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",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
"components",
|
|
43
43
|
"client",
|
|
44
44
|
"default-respectify.config.json",
|
|
45
|
+
"respectify.config.sample.jsonc",
|
|
45
46
|
"README.md"
|
|
46
47
|
],
|
|
47
48
|
"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
|
@@ -26,7 +26,13 @@ export const respectifyCommentActions = {
|
|
|
26
26
|
parentId: z.number().optional(),
|
|
27
27
|
}),
|
|
28
28
|
handler: async ({ postSlug, author, email, content, parentId }) => {
|
|
29
|
-
|
|
29
|
+
let replyToComment: string | undefined;
|
|
30
|
+
if (parentId !== undefined) {
|
|
31
|
+
const [parent] = await db.select().from(Comment).where(eq(Comment.id, parentId)).limit(1);
|
|
32
|
+
replyToComment = parent?.content;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const analysis = await analyzeComment(content, postSlug, { replyToComment });
|
|
30
36
|
|
|
31
37
|
if (!analysis.approved) {
|
|
32
38
|
return {
|
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,
|
package/src/lib/service.ts
CHANGED
|
@@ -1,35 +1,56 @@
|
|
|
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
|
|
|
@@ -40,7 +61,7 @@ async function getOrInitializeArticleId(postSlug: string): Promise<string> {
|
|
|
40
61
|
}
|
|
41
62
|
|
|
42
63
|
const postUrl = getPostUrl!(postSlug, site);
|
|
43
|
-
const respectifyClient = getRespectifyClient();
|
|
64
|
+
const respectifyClient = getRespectifyClient(config);
|
|
44
65
|
|
|
45
66
|
const result = await respectifyClient.initTopicFromUrl(postUrl, `Post: ${postSlug}`);
|
|
46
67
|
articleIdCache.set(postSlug, result.article_id);
|
|
@@ -51,7 +72,8 @@ async function getOrInitializeArticleId(postSlug: string): Promise<string> {
|
|
|
51
72
|
|
|
52
73
|
export async function verifyRespectifyCredentials(): Promise<boolean> {
|
|
53
74
|
try {
|
|
54
|
-
const
|
|
75
|
+
const config = loadRespectifyConfig();
|
|
76
|
+
const respectifyClient = getRespectifyClient(config);
|
|
55
77
|
const result = await respectifyClient.checkUserCredentials();
|
|
56
78
|
return result.active;
|
|
57
79
|
} catch (error) {
|
|
@@ -60,7 +82,41 @@ export async function verifyRespectifyCredentials(): Promise<boolean> {
|
|
|
60
82
|
}
|
|
61
83
|
}
|
|
62
84
|
|
|
63
|
-
|
|
85
|
+
function buildSuggestion(result: MegaCallResult, showFeedback: boolean): string | undefined {
|
|
86
|
+
if (!showFeedback || !result.comment_score) return undefined;
|
|
87
|
+
|
|
88
|
+
const suggestions: string[] = [];
|
|
89
|
+
|
|
90
|
+
if (result.comment_score.toxicity_explanation) {
|
|
91
|
+
suggestions.push(result.comment_score.toxicity_explanation);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (result.comment_score.logical_fallacies.length > 0) {
|
|
95
|
+
suggestions.push(
|
|
96
|
+
`Logical fallacies detected: ${result.comment_score.logical_fallacies.map((f) => f.fallacy_name).join(', ')}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (result.comment_score.objectionable_phrases.length > 0) {
|
|
101
|
+
suggestions.push(`Objectionable phrases found: ${result.comment_score.objectionable_phrases.length} issue(s)`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (result.relevance_check && !result.relevance_check.on_topic.on_topic) {
|
|
105
|
+
suggestions.push(result.relevance_check.on_topic.reasoning);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (result.dogwhistle_check?.detection.dogwhistles_detected && result.dogwhistle_check.detection.reasoning) {
|
|
109
|
+
suggestions.push(result.dogwhistle_check.detection.reasoning);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return suggestions.length > 0 ? suggestions.join(' ') : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function analyzeComment(
|
|
116
|
+
text: string,
|
|
117
|
+
postSlug?: string,
|
|
118
|
+
options: AnalyzeCommentOptions = {},
|
|
119
|
+
): Promise<RespectifyAnalysisResult> {
|
|
64
120
|
const config: RespectifyConfig = loadRespectifyConfig();
|
|
65
121
|
|
|
66
122
|
if (!config.enabled) {
|
|
@@ -72,12 +128,12 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
72
128
|
}
|
|
73
129
|
|
|
74
130
|
try {
|
|
75
|
-
const respectifyClient = getRespectifyClient();
|
|
131
|
+
const respectifyClient = getRespectifyClient(config);
|
|
76
132
|
let respectifyArticleId: string | undefined;
|
|
77
133
|
|
|
78
134
|
if (postSlug) {
|
|
79
135
|
try {
|
|
80
|
-
respectifyArticleId = await getOrInitializeArticleId(postSlug);
|
|
136
|
+
respectifyArticleId = await getOrInitializeArticleId(postSlug, config);
|
|
81
137
|
} catch (error) {
|
|
82
138
|
logger.warn('Could not initialize Respectify article ID; falling back to spam-only check', {
|
|
83
139
|
postSlug,
|
|
@@ -86,22 +142,31 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
86
142
|
}
|
|
87
143
|
}
|
|
88
144
|
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
includeSpam: boolean;
|
|
93
|
-
includeCommentScore?: boolean;
|
|
94
|
-
} = {
|
|
145
|
+
const megacallDefaults = resolveMegacallConfig(config);
|
|
146
|
+
const megacallOptions: MegacallOptions = {
|
|
147
|
+
...megacallDefaults,
|
|
95
148
|
comment: text,
|
|
96
|
-
includeSpam: true,
|
|
97
149
|
};
|
|
98
150
|
|
|
99
151
|
if (respectifyArticleId) {
|
|
100
152
|
megacallOptions.articleId = respectifyArticleId;
|
|
101
|
-
|
|
153
|
+
// Score requires an article; enable by default when topic context exists unless explicitly disabled
|
|
154
|
+
if (megacallOptions.includeCommentScore === undefined) {
|
|
155
|
+
megacallOptions.includeCommentScore = true;
|
|
156
|
+
}
|
|
157
|
+
} else {
|
|
158
|
+
// Relevance / comment score / dogwhistle require articleId — drop them without context
|
|
159
|
+
delete megacallOptions.includeRelevance;
|
|
160
|
+
delete megacallOptions.includeCommentScore;
|
|
161
|
+
delete megacallOptions.includeDogwhistle;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (options.replyToComment !== undefined) {
|
|
165
|
+
megacallOptions.replyToComment = options.replyToComment;
|
|
102
166
|
}
|
|
103
167
|
|
|
104
168
|
const result = await respectifyClient.megacall(megacallOptions);
|
|
169
|
+
const showFeedback = config.moderation.showFeedbackToUser !== false;
|
|
105
170
|
|
|
106
171
|
if (result.spam_check?.is_spam) {
|
|
107
172
|
return {
|
|
@@ -113,6 +178,30 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
113
178
|
};
|
|
114
179
|
}
|
|
115
180
|
|
|
181
|
+
const blockOffTopic = config.moderation.blockOffTopic !== false;
|
|
182
|
+
if (blockOffTopic && result.relevance_check) {
|
|
183
|
+
const { on_topic, banned_topics } = result.relevance_check;
|
|
184
|
+
const hasBannedTopics = banned_topics.banned_topics.length > 0 && banned_topics.quantity_on_banned_topics > 0;
|
|
185
|
+
if (!on_topic.on_topic || hasBannedTopics) {
|
|
186
|
+
return {
|
|
187
|
+
score: 0,
|
|
188
|
+
approved: false,
|
|
189
|
+
feedback: config.feedback.offTopic ?? 'This comment appears to be off-topic.',
|
|
190
|
+
suggestion: showFeedback ? on_topic.reasoning || banned_topics.reasoning : undefined,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const blockDogwhistles = config.moderation.blockDogwhistles !== false;
|
|
196
|
+
if (blockDogwhistles && result.dogwhistle_check?.detection.dogwhistles_detected) {
|
|
197
|
+
return {
|
|
198
|
+
score: 0,
|
|
199
|
+
approved: false,
|
|
200
|
+
feedback: config.feedback.dogwhistle ?? 'This comment was blocked due to policy violations.',
|
|
201
|
+
suggestion: showFeedback ? result.dogwhistle_check.detection.reasoning : undefined,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
116
205
|
let respectfulnessScore = config.thresholds.autoApprove;
|
|
117
206
|
|
|
118
207
|
if (result.comment_score) {
|
|
@@ -134,33 +223,13 @@ export async function analyzeComment(text: string, postSlug?: string): Promise<R
|
|
|
134
223
|
feedback = config.feedback.warning;
|
|
135
224
|
}
|
|
136
225
|
|
|
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
226
|
const analysisResult: RespectifyAnalysisResult = {
|
|
159
227
|
score: respectfulnessScore,
|
|
160
228
|
approved,
|
|
161
229
|
feedback,
|
|
162
230
|
};
|
|
163
231
|
|
|
232
|
+
const suggestion = buildSuggestion(result, showFeedback);
|
|
164
233
|
if (suggestion) analysisResult.suggestion = suggestion;
|
|
165
234
|
|
|
166
235
|
return analysisResult;
|
package/src/runtime-config.ts
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
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' | '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}/`,
|
|
9
13
|
rateLimit: { windowMs: 5 * 60 * 1000, maxRequests: 10 },
|
|
14
|
+
client: undefined,
|
|
15
|
+
megacall: undefined,
|
|
10
16
|
};
|
|
11
17
|
|
|
12
|
-
let options:
|
|
18
|
+
let options: ResolvedIntegrationOptions = { ...defaults };
|
|
13
19
|
|
|
14
20
|
export function setIntegrationOptions(userOptions: RespectifyIntegrationOptions = {}): void {
|
|
15
21
|
options = {
|
|
@@ -17,9 +23,13 @@ export function setIntegrationOptions(userOptions: RespectifyIntegrationOptions
|
|
|
17
23
|
...userOptions,
|
|
18
24
|
getPostUrl: userOptions.getPostUrl ?? defaults.getPostUrl,
|
|
19
25
|
rateLimit: userOptions.rateLimit ?? defaults.rateLimit,
|
|
26
|
+
client: userOptions.client,
|
|
27
|
+
megacall: userOptions.megacall,
|
|
20
28
|
};
|
|
21
29
|
}
|
|
22
30
|
|
|
23
|
-
export function getIntegrationOptions():
|
|
31
|
+
export function getIntegrationOptions(): ResolvedIntegrationOptions {
|
|
24
32
|
return options;
|
|
25
33
|
}
|
|
34
|
+
|
|
35
|
+
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;
|
|
@@ -16,6 +30,24 @@ export interface RespectifyIntegrationOptions {
|
|
|
16
30
|
windowMs: number;
|
|
17
31
|
maxRequests: number;
|
|
18
32
|
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Options forwarded to the Respectify API client
|
|
36
|
+
* (`baseUrl`, `timeout`, `version`, `website`, optional credential overrides).
|
|
37
|
+
*/
|
|
38
|
+
client?: RespectifyClientConfig;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Options forwarded to every Respectify megacall
|
|
42
|
+
* (`includeSpam`, `includeRelevance`, `includeCommentScore`, `includeDogwhistle`,
|
|
43
|
+
* `bannedTopics`, `sensitiveTopics`, `dogwhistleExamples`, `replyToComment`).
|
|
44
|
+
*/
|
|
45
|
+
megacall?: RespectifyMegacallConfig;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface AnalyzeCommentOptions {
|
|
49
|
+
/** Parent comment text when submitting a reply */
|
|
50
|
+
replyToComment?: string;
|
|
19
51
|
}
|
|
20
52
|
|
|
21
53
|
export interface RespectifyAnalysisResult {
|