@vettly/supabase 0.1.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 ADDED
@@ -0,0 +1,266 @@
1
+ # @vettly/supabase
2
+
3
+ Vettly content moderation for Supabase Edge Functions. Deno-compatible, fetch-based client.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @vettly/supabase
9
+ ```
10
+
11
+ Or with Deno in your Edge Function:
12
+
13
+ ```typescript
14
+ import { moderate } from 'npm:@vettly/supabase'
15
+ ```
16
+
17
+ ## Quick Start
18
+
19
+ ### One-liner Edge Function
20
+
21
+ ```typescript
22
+ import { createModerationHandler } from '@vettly/supabase'
23
+
24
+ // Moderate all incoming content
25
+ Deno.serve(createModerationHandler({
26
+ policyId: 'default',
27
+ onBlock: (result) => new Response(JSON.stringify({
28
+ error: 'Content blocked',
29
+ reason: result.categories.filter(c => c.flagged)
30
+ }), { status: 403, headers: { 'Content-Type': 'application/json' } })
31
+ }))
32
+ ```
33
+
34
+ ### Manual Control
35
+
36
+ ```typescript
37
+ import { moderate } from '@vettly/supabase'
38
+
39
+ Deno.serve(async (req) => {
40
+ const { content, userId } = await req.json()
41
+
42
+ // Moderate content first
43
+ const result = await moderate(content, { policyId: 'strict' })
44
+
45
+ if (result.action === 'block') {
46
+ return new Response('Content blocked', { status: 403 })
47
+ }
48
+
49
+ // Content is safe, continue with your logic
50
+ // await supabase.from('posts').insert({ content, userId })
51
+
52
+ return new Response(JSON.stringify({ success: true }), {
53
+ headers: { 'Content-Type': 'application/json' }
54
+ })
55
+ })
56
+ ```
57
+
58
+ ### Middleware Pattern
59
+
60
+ ```typescript
61
+ import { withModeration } from '@vettly/supabase'
62
+
63
+ const handler = withModeration(
64
+ async (req, moderationResult) => {
65
+ // Content already passed moderation
66
+ const { content, userId } = await req.json()
67
+
68
+ // Insert into database...
69
+ // await supabase.from('posts').insert({ content, userId })
70
+
71
+ return new Response(JSON.stringify({
72
+ success: true,
73
+ moderation: {
74
+ decisionId: moderationResult.decisionId,
75
+ safe: moderationResult.safe
76
+ }
77
+ }), { headers: { 'Content-Type': 'application/json' } })
78
+ },
79
+ { policyId: 'user-content' }
80
+ )
81
+
82
+ Deno.serve(handler)
83
+ ```
84
+
85
+ ## Configuration
86
+
87
+ ### Environment Variable
88
+
89
+ Set `VETTLY_API_KEY` in your Supabase project secrets:
90
+
91
+ ```bash
92
+ supabase secrets set VETTLY_API_KEY=your_api_key
93
+ ```
94
+
95
+ ### Programmatic Configuration
96
+
97
+ ```typescript
98
+ import { createClient } from '@vettly/supabase'
99
+
100
+ const vettly = createClient({
101
+ apiKey: Deno.env.get('VETTLY_API_KEY')!,
102
+ apiUrl: 'https://api.vettly.dev', // optional
103
+ timeout: 30000 // optional, in ms
104
+ })
105
+
106
+ const result = await vettly.check('Hello world', { policyId: 'default' })
107
+ ```
108
+
109
+ ## API Reference
110
+
111
+ ### `moderate(content, options?)`
112
+
113
+ Moderate text content using the default client.
114
+
115
+ ```typescript
116
+ const result = await moderate('User generated content', {
117
+ policyId: 'strict', // Policy to use (default: 'default')
118
+ contentType: 'text', // 'text' | 'image' | 'video'
119
+ language: 'en', // ISO 639-1 language code
120
+ metadata: { userId: '123' }
121
+ })
122
+
123
+ // Result:
124
+ // {
125
+ // decisionId: 'dec_123',
126
+ // safe: true,
127
+ // flagged: false,
128
+ // action: 'allow',
129
+ // categories: [{ category: 'hate_speech', score: 0.01, flagged: false }],
130
+ // provider: 'openai',
131
+ // latency: 150,
132
+ // cost: 0.0001
133
+ // }
134
+ ```
135
+
136
+ ### `moderateImage(imageUrl, options?)`
137
+
138
+ Moderate an image by URL.
139
+
140
+ ```typescript
141
+ const result = await moderateImage('https://example.com/image.jpg', {
142
+ policyId: 'images'
143
+ })
144
+ ```
145
+
146
+ ### `createModerationHandler(config)`
147
+
148
+ Create an Edge Function handler that moderates incoming requests.
149
+
150
+ ```typescript
151
+ import { createModerationHandler } from '@vettly/supabase'
152
+
153
+ Deno.serve(createModerationHandler({
154
+ apiKey: Deno.env.get('VETTLY_API_KEY'), // Optional, uses env var by default
155
+ policyId: 'default',
156
+
157
+ // Custom content extraction (default: reads req.json().content)
158
+ getContent: async (req) => {
159
+ const { message } = await req.json()
160
+ return message
161
+ },
162
+
163
+ // Handle blocked content
164
+ onBlock: (result, req) => {
165
+ return new Response(JSON.stringify({ blocked: true }), { status: 403 })
166
+ },
167
+
168
+ // Handle flagged content (logged but allowed)
169
+ onFlag: (result, req) => {
170
+ console.log('Flagged content:', result.decisionId)
171
+ },
172
+
173
+ // Handle warnings
174
+ onWarn: (result, req) => {
175
+ console.log('Warning:', result.categories)
176
+ },
177
+
178
+ // Handle allowed content
179
+ onAllow: (result, req) => {
180
+ return new Response(JSON.stringify({ success: true }))
181
+ },
182
+
183
+ // Handle errors
184
+ onError: (error, req) => {
185
+ console.error('Moderation error:', error)
186
+ return new Response('Error', { status: 500 })
187
+ }
188
+ }))
189
+ ```
190
+
191
+ ### `withModeration(handler, config)`
192
+
193
+ Middleware-style handler that moderates content before passing to your handler.
194
+
195
+ ```typescript
196
+ import { withModeration } from '@vettly/supabase'
197
+
198
+ const handler = withModeration(
199
+ async (req, moderationResult) => {
200
+ // Your handler receives the moderation result
201
+ console.log('Decision ID:', moderationResult.decisionId)
202
+ console.log('Safe:', moderationResult.safe)
203
+
204
+ // Process the request...
205
+ return new Response(JSON.stringify({ success: true }))
206
+ },
207
+ { policyId: 'user-content' }
208
+ )
209
+
210
+ Deno.serve(handler)
211
+ ```
212
+
213
+ ### `createClient(config)`
214
+
215
+ Create a configured Vettly client for more control.
216
+
217
+ ```typescript
218
+ const client = createClient({
219
+ apiKey: 'vettly_...',
220
+ apiUrl: 'https://api.vettly.dev',
221
+ timeout: 30000
222
+ })
223
+
224
+ // Text moderation
225
+ const textResult = await client.check('Hello world', { policyId: 'default' })
226
+
227
+ // Image moderation
228
+ const imageResult = await client.checkImage('https://...', { policyId: 'images' })
229
+ ```
230
+
231
+ ## Error Handling
232
+
233
+ ```typescript
234
+ import { moderate, VettlyError, VettlyAuthError, VettlyRateLimitError } from '@vettly/supabase'
235
+
236
+ try {
237
+ const result = await moderate('content')
238
+ } catch (error) {
239
+ if (error instanceof VettlyAuthError) {
240
+ console.error('Invalid API key')
241
+ } else if (error instanceof VettlyRateLimitError) {
242
+ console.error('Rate limited, retry after:', error.retryAfter)
243
+ } else if (error instanceof VettlyError) {
244
+ console.error('Vettly error:', error.code, error.message)
245
+ }
246
+ }
247
+ ```
248
+
249
+ ## TypeScript Types
250
+
251
+ ```typescript
252
+ import type {
253
+ ModerationResult,
254
+ ModerationOptions,
255
+ Action,
256
+ Category,
257
+ CategoryScore,
258
+ VettlyConfig,
259
+ EdgeHandlerOptions,
260
+ ModerationHandlerConfig
261
+ } from '@vettly/supabase'
262
+ ```
263
+
264
+ ## License
265
+
266
+ MIT
@@ -0,0 +1,368 @@
1
+ // src/types.ts
2
+ var VettlyError = class extends Error {
3
+ code;
4
+ statusCode;
5
+ responseBody;
6
+ constructor(message, code, statusCode, responseBody) {
7
+ super(message);
8
+ this.name = "VettlyError";
9
+ this.code = code;
10
+ this.statusCode = statusCode;
11
+ this.responseBody = responseBody;
12
+ }
13
+ };
14
+ var VettlyAuthError = class extends VettlyError {
15
+ constructor(message = "Invalid API key") {
16
+ super(message, "AUTH_ERROR", 401);
17
+ this.name = "VettlyAuthError";
18
+ }
19
+ };
20
+ var VettlyRateLimitError = class extends VettlyError {
21
+ retryAfter;
22
+ constructor(message = "Rate limit exceeded", retryAfter) {
23
+ super(message, "RATE_LIMIT", 429);
24
+ this.name = "VettlyRateLimitError";
25
+ this.retryAfter = retryAfter;
26
+ }
27
+ };
28
+ var VettlyValidationError = class extends VettlyError {
29
+ errors;
30
+ constructor(message, errors) {
31
+ super(message, "VALIDATION_ERROR", 422);
32
+ this.name = "VettlyValidationError";
33
+ this.errors = errors;
34
+ }
35
+ };
36
+
37
+ // src/client.ts
38
+ var DEFAULT_API_URL = "https://api.vettly.dev";
39
+ var DEFAULT_TIMEOUT = 3e4;
40
+ var SDK_VERSION = "0.1.0";
41
+ function createClient(config) {
42
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
43
+ const timeout = config.timeout ?? DEFAULT_TIMEOUT;
44
+ const apiKey = config.apiKey;
45
+ if (!apiKey) {
46
+ throw new VettlyError(
47
+ "API key is required",
48
+ "CONFIG_ERROR",
49
+ 500
50
+ );
51
+ }
52
+ async function request(method, path, body) {
53
+ const controller = new AbortController();
54
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
55
+ try {
56
+ const response = await fetch(`${apiUrl}${path}`, {
57
+ method,
58
+ headers: {
59
+ "Content-Type": "application/json",
60
+ Authorization: `Bearer ${apiKey}`,
61
+ "User-Agent": `@vettly/supabase/${SDK_VERSION}`,
62
+ "X-Vettly-SDK-Version": SDK_VERSION
63
+ },
64
+ body: body ? JSON.stringify(body) : void 0,
65
+ signal: controller.signal
66
+ });
67
+ clearTimeout(timeoutId);
68
+ if (!response.ok) {
69
+ const errorBody = await response.json().catch(() => ({}));
70
+ switch (response.status) {
71
+ case 401:
72
+ throw new VettlyAuthError(errorBody.error || "Invalid API key");
73
+ case 429: {
74
+ const retryAfter = response.headers.get("Retry-After");
75
+ throw new VettlyRateLimitError(
76
+ errorBody.error || "Rate limit exceeded",
77
+ retryAfter ? parseInt(retryAfter, 10) : void 0
78
+ );
79
+ }
80
+ case 422:
81
+ throw new VettlyValidationError(
82
+ errorBody.error || "Validation error",
83
+ Array.isArray(errorBody.details) ? errorBody.details : []
84
+ );
85
+ default:
86
+ throw new VettlyError(
87
+ errorBody.error || `Request failed with status ${response.status}`,
88
+ errorBody.code || "API_ERROR",
89
+ response.status,
90
+ errorBody
91
+ );
92
+ }
93
+ }
94
+ return response.json();
95
+ } catch (error) {
96
+ clearTimeout(timeoutId);
97
+ if (error instanceof VettlyError) {
98
+ throw error;
99
+ }
100
+ if (error instanceof Error && error.name === "AbortError") {
101
+ throw new VettlyError(
102
+ `Request timed out after ${timeout}ms`,
103
+ "TIMEOUT",
104
+ 408
105
+ );
106
+ }
107
+ throw new VettlyError(
108
+ error instanceof Error ? error.message : "Unknown error",
109
+ "NETWORK_ERROR",
110
+ 500
111
+ );
112
+ }
113
+ }
114
+ return {
115
+ /**
116
+ * Moderate text content
117
+ */
118
+ async check(content, options = {}) {
119
+ return request("POST", "/v1/moderate", {
120
+ content,
121
+ policyId: options.policyId ?? "default",
122
+ contentType: options.contentType ?? "text",
123
+ language: options.language,
124
+ metadata: options.metadata,
125
+ requestId: options.requestId
126
+ });
127
+ },
128
+ /**
129
+ * Moderate an image
130
+ */
131
+ async checkImage(imageUrl, options = {}) {
132
+ return request("POST", "/v1/moderate", {
133
+ content: imageUrl,
134
+ policyId: options.policyId ?? "default",
135
+ contentType: "image",
136
+ metadata: options.metadata,
137
+ requestId: options.requestId
138
+ });
139
+ }
140
+ };
141
+ }
142
+ var defaultClient = null;
143
+ function getDefaultClient() {
144
+ if (defaultClient) {
145
+ return defaultClient;
146
+ }
147
+ const apiKey = typeof Deno !== "undefined" ? Deno.env.get("VETTLY_API_KEY") : typeof process !== "undefined" ? process.env.VETTLY_API_KEY : void 0;
148
+ if (!apiKey) {
149
+ throw new VettlyError(
150
+ "VETTLY_API_KEY environment variable is not set",
151
+ "CONFIG_ERROR",
152
+ 500
153
+ );
154
+ }
155
+ defaultClient = createClient({ apiKey });
156
+ return defaultClient;
157
+ }
158
+ async function moderate(content, options = {}) {
159
+ return getDefaultClient().check(content, options);
160
+ }
161
+ async function moderateImage(imageUrl, options = {}) {
162
+ return getDefaultClient().checkImage(imageUrl, options);
163
+ }
164
+
165
+ // src/edge.ts
166
+ async function defaultGetContent(req) {
167
+ try {
168
+ const body = await req.json();
169
+ return typeof body.content === "string" ? body.content : null;
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+ function createModerationHandler(config = {}) {
175
+ const {
176
+ apiKey,
177
+ policyId = "default",
178
+ getContent = defaultGetContent,
179
+ onBlock,
180
+ onFlag,
181
+ onWarn,
182
+ onAllow,
183
+ onError
184
+ } = config;
185
+ const resolvedApiKey = apiKey ?? (typeof Deno !== "undefined" ? Deno.env.get("VETTLY_API_KEY") : typeof process !== "undefined" ? process.env.VETTLY_API_KEY : void 0);
186
+ if (!resolvedApiKey) {
187
+ throw new VettlyError(
188
+ "API key is required. Set VETTLY_API_KEY env var or pass apiKey in config.",
189
+ "CONFIG_ERROR",
190
+ 500
191
+ );
192
+ }
193
+ const client = createClient({ apiKey: resolvedApiKey });
194
+ return async (req) => {
195
+ if (req.method === "OPTIONS") {
196
+ return new Response(null, {
197
+ status: 204,
198
+ headers: {
199
+ "Access-Control-Allow-Origin": "*",
200
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
201
+ "Access-Control-Allow-Headers": "Content-Type, Authorization"
202
+ }
203
+ });
204
+ }
205
+ if (req.method !== "POST") {
206
+ return new Response(
207
+ JSON.stringify({ error: "Method not allowed" }),
208
+ {
209
+ status: 405,
210
+ headers: { "Content-Type": "application/json" }
211
+ }
212
+ );
213
+ }
214
+ try {
215
+ const content = await getContent(req);
216
+ if (!content) {
217
+ return new Response(
218
+ JSON.stringify({ error: "No content to moderate" }),
219
+ {
220
+ status: 400,
221
+ headers: { "Content-Type": "application/json" }
222
+ }
223
+ );
224
+ }
225
+ const result = await client.check(content, { policyId });
226
+ if (result.action === "block") {
227
+ if (onBlock) {
228
+ return onBlock(result, req);
229
+ }
230
+ return new Response(
231
+ JSON.stringify({
232
+ error: "Content blocked",
233
+ categories: result.categories.filter((c) => c.flagged)
234
+ }),
235
+ {
236
+ status: 403,
237
+ headers: { "Content-Type": "application/json" }
238
+ }
239
+ );
240
+ }
241
+ if (result.action === "flag" && onFlag) {
242
+ await onFlag(result, req);
243
+ }
244
+ if (result.action === "warn" && onWarn) {
245
+ await onWarn(result, req);
246
+ }
247
+ if (onAllow) {
248
+ return onAllow(result, req);
249
+ }
250
+ return new Response(
251
+ JSON.stringify({
252
+ success: true,
253
+ moderation: {
254
+ safe: result.safe,
255
+ action: result.action,
256
+ decisionId: result.decisionId
257
+ }
258
+ }),
259
+ {
260
+ status: 200,
261
+ headers: { "Content-Type": "application/json" }
262
+ }
263
+ );
264
+ } catch (error) {
265
+ if (onError) {
266
+ return onError(error instanceof Error ? error : new Error(String(error)), req);
267
+ }
268
+ console.error("[Vettly] Moderation error:", error);
269
+ return new Response(
270
+ JSON.stringify({
271
+ error: "Moderation service error",
272
+ message: error instanceof Error ? error.message : "Unknown error"
273
+ }),
274
+ {
275
+ status: 500,
276
+ headers: { "Content-Type": "application/json" }
277
+ }
278
+ );
279
+ }
280
+ };
281
+ }
282
+ function withModeration(handler, config = {}) {
283
+ const {
284
+ apiKey,
285
+ policyId = "default",
286
+ getContent = defaultGetContent,
287
+ onBlock,
288
+ onError
289
+ } = config;
290
+ const resolvedApiKey = apiKey ?? (typeof Deno !== "undefined" ? Deno.env.get("VETTLY_API_KEY") : typeof process !== "undefined" ? process.env.VETTLY_API_KEY : void 0);
291
+ if (!resolvedApiKey) {
292
+ throw new VettlyError(
293
+ "API key is required. Set VETTLY_API_KEY env var or pass apiKey in config.",
294
+ "CONFIG_ERROR",
295
+ 500
296
+ );
297
+ }
298
+ const client = createClient({ apiKey: resolvedApiKey });
299
+ return async (req) => {
300
+ if (req.method === "OPTIONS") {
301
+ return new Response(null, {
302
+ status: 204,
303
+ headers: {
304
+ "Access-Control-Allow-Origin": "*",
305
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
306
+ "Access-Control-Allow-Headers": "Content-Type, Authorization"
307
+ }
308
+ });
309
+ }
310
+ try {
311
+ const clonedReq = req.clone();
312
+ const content = await getContent(clonedReq);
313
+ if (!content) {
314
+ return new Response(
315
+ JSON.stringify({ error: "No content to moderate" }),
316
+ {
317
+ status: 400,
318
+ headers: { "Content-Type": "application/json" }
319
+ }
320
+ );
321
+ }
322
+ const result = await client.check(content, { policyId });
323
+ if (result.action === "block") {
324
+ if (onBlock) {
325
+ return onBlock(result, req);
326
+ }
327
+ return new Response(
328
+ JSON.stringify({
329
+ error: "Content blocked",
330
+ categories: result.categories.filter((c) => c.flagged)
331
+ }),
332
+ {
333
+ status: 403,
334
+ headers: { "Content-Type": "application/json" }
335
+ }
336
+ );
337
+ }
338
+ return handler(req, result);
339
+ } catch (error) {
340
+ if (onError) {
341
+ return onError(error instanceof Error ? error : new Error(String(error)), req);
342
+ }
343
+ console.error("[Vettly] Moderation error:", error);
344
+ return new Response(
345
+ JSON.stringify({
346
+ error: "Moderation service error",
347
+ message: error instanceof Error ? error.message : "Unknown error"
348
+ }),
349
+ {
350
+ status: 500,
351
+ headers: { "Content-Type": "application/json" }
352
+ }
353
+ );
354
+ }
355
+ };
356
+ }
357
+
358
+ export {
359
+ VettlyError,
360
+ VettlyAuthError,
361
+ VettlyRateLimitError,
362
+ VettlyValidationError,
363
+ createClient,
364
+ moderate,
365
+ moderateImage,
366
+ createModerationHandler,
367
+ withModeration
368
+ };