@respectify/astro 0.2.0 → 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/src/index.ts CHANGED
@@ -1,33 +1,69 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import path from 'node:path';
1
3
  import type { AstroIntegration } from 'astro';
2
4
  import { envField } from 'astro/config';
3
- import { RespectifyError, validateModerationTolerances } from '@respectify/client';
4
- import { setIntegrationOptions } from './runtime-config';
5
- import type { RespectifyIntegrationOptions } from './types';
6
-
7
- /** Fail at setup, not on the first comment, when the integration's tolerances are invalid. */
8
- function assertValidTolerances(userOptions: RespectifyIntegrationOptions): void {
9
- if (userOptions.tolerances === undefined) return;
10
- try {
11
- validateModerationTolerances(userOptions.tolerances);
12
- } catch (error) {
13
- if (error instanceof RespectifyError) {
14
- throw new Error(`Invalid Respectify tolerances: ${error.message}`);
15
- }
16
- throw error;
5
+ import { parseIntegrationOptions, toResolvedIntegrationOptions } from './options';
6
+ import type { RespectifyIntegrationOptions, RespectifyRuntime } from './types';
7
+
8
+ const OPTIONS_MODULE_ID = 'virtual:@respectify/astro/options';
9
+ const RUNTIME_MODULE_ID = 'virtual:@respectify/astro/runtime';
10
+
11
+ /** A Vite plugin serving virtual modules, in the shape `vite.plugins` accepts. */
12
+ interface VirtualModulesPlugin {
13
+ name: string;
14
+ resolveId: (id: string) => string | undefined;
15
+ load: (id: string) => string | undefined;
16
+ }
17
+
18
+ /** Declarations for the virtual modules, injected into the site's generated types. */
19
+ const VIRTUAL_MODULE_TYPES = `declare module '${OPTIONS_MODULE_ID}' {
20
+ const options: import('@respectify/astro').ResolvedIntegrationOptions;
21
+ export default options;
22
+ }
23
+
24
+ declare module '${RUNTIME_MODULE_ID}' {
25
+ const runtime: import('@respectify/astro').RespectifyRuntime;
26
+ export default runtime;
27
+ }
28
+ `;
29
+
30
+ /**
31
+ * Where Vite should load the runtime module from. A relative path is resolved against the
32
+ * project root; an absolute path or a package specifier is left as given.
33
+ */
34
+ function resolveRuntimeSpecifier(runtime: string, root: URL): string {
35
+ if (runtime.startsWith('./') || runtime.startsWith('../')) {
36
+ return fileURLToPath(new URL(runtime, root));
17
37
  }
38
+ return path.isAbsolute(runtime) ? path.normalize(runtime) : runtime;
18
39
  }
19
40
 
20
- export default function respectify(userOptions: RespectifyIntegrationOptions = {}): AstroIntegration {
21
- assertValidTolerances(userOptions);
22
- setIntegrationOptions(userOptions);
41
+ /** Serve each virtual module's source, keyed by its public id, using Vite's `\0` resolved-id convention. */
42
+ function createVirtualModulesPlugin(modules: Record<string, string>): VirtualModulesPlugin {
43
+ const sources = new Map(Object.entries(modules).map(([id, source]) => [`\0${id}`, source]));
44
+ return {
45
+ name: '@respectify/astro:virtual-modules',
46
+ resolveId: (id) => (sources.has(`\0${id}`) ? `\0${id}` : undefined),
47
+ load: (id) => sources.get(id),
48
+ };
49
+ }
23
50
 
24
- const commentsApiPath = userOptions.commentsApiPath ?? '/api/respectify/comments';
25
- const routePattern = commentsApiPath.replace(/^\//, '');
51
+ /**
52
+ * The Respectify comments integration. Its options are serialized into the server bundle,
53
+ * so they must be plain data; the comment store and post functions live in the module
54
+ * named by `runtime`.
55
+ */
56
+ export default function respectify(userOptions: RespectifyIntegrationOptions): AstroIntegration {
57
+ const parsed = parseIntegrationOptions(userOptions);
58
+ const resolvedOptions = toResolvedIntegrationOptions(parsed);
59
+ const routePattern = resolvedOptions.commentsApiPath.replace(/^\//, '');
26
60
 
27
61
  return {
28
62
  name: '@respectify/astro',
29
63
  hooks: {
30
- 'astro:config:setup': ({ injectRoute, updateConfig }) => {
64
+ 'astro:config:setup': ({ config, injectRoute, updateConfig }) => {
65
+ const runtimeSpecifier = resolveRuntimeSpecifier(parsed.runtime, config.root);
66
+
31
67
  updateConfig({
32
68
  env: {
33
69
  schema: {
@@ -35,6 +71,14 @@ export default function respectify(userOptions: RespectifyIntegrationOptions = {
35
71
  RESPECTIFY_API_KEY: envField.string({ context: 'server', access: 'secret', optional: true }),
36
72
  },
37
73
  },
74
+ vite: {
75
+ plugins: [
76
+ createVirtualModulesPlugin({
77
+ [OPTIONS_MODULE_ID]: `export default ${JSON.stringify(resolvedOptions)};`,
78
+ [RUNTIME_MODULE_ID]: `export { default } from ${JSON.stringify(runtimeSpecifier)};`,
79
+ }),
80
+ ],
81
+ },
38
82
  });
39
83
 
40
84
  injectRoute({
@@ -42,14 +86,39 @@ export default function respectify(userOptions: RespectifyIntegrationOptions = {
42
86
  entrypoint: '@respectify/astro/routes/comments',
43
87
  });
44
88
  },
89
+ 'astro:config:done': ({ injectTypes }) => {
90
+ injectTypes({ filename: 'virtual-modules.d.ts', content: VIRTUAL_MODULE_TYPES });
91
+ },
45
92
  },
46
93
  };
47
94
  }
48
95
 
96
+ /**
97
+ * Define the runtime module named by `respectify({ runtime })`. Its default export must be
98
+ * the value this returns:
99
+ *
100
+ * ```ts
101
+ * // src/respectify.runtime.ts
102
+ * import { defineRespectifyRuntime } from '@respectify/astro';
103
+ * import { createSqliteCommentStore } from '@respectify/astro/sqlite';
104
+ *
105
+ * export default defineRespectifyRuntime({ store: createSqliteCommentStore(db) });
106
+ * ```
107
+ */
108
+ export function defineRespectifyRuntime(runtime: RespectifyRuntime): RespectifyRuntime {
109
+ return runtime;
110
+ }
111
+
49
112
  export type {
50
113
  RespectifyIntegrationOptions,
114
+ RespectifyIntegrationClientConfig,
115
+ ResolvedIntegrationOptions,
116
+ RespectifyRuntime,
51
117
  RespectifyAnalysisResult,
52
118
  RespectifyClientConfig,
53
119
  RespectifyMegacallConfig,
54
120
  AnalyzeCommentOptions,
55
121
  } from './types';
122
+ export type { ICommentStore, CommentRecord, NewComment, PublicComment } from './store/types';
123
+ export { CommentValidationError, newCommentSchema } from './store/schemas';
124
+ export { COMMENT_LIMITS } from './store/limits';
@@ -9,7 +9,7 @@ import {
9
9
  type MegacallOptions,
10
10
  type MegaCallResult,
11
11
  } from '@respectify/client';
12
- import { getIntegrationOptions } from '../runtime-config';
12
+ import { getRespectifyRuntime } from '../runtime';
13
13
  import { logger } from './logger';
14
14
  import type { AnalyzeCommentOptions, RespectifyAnalysisResult } from '../types';
15
15
 
@@ -54,7 +54,7 @@ async function getOrInitializeArticleId(postSlug: string, config: RespectifyConf
54
54
  const cached = articleIdCache.get(postSlug);
55
55
  if (cached) return cached;
56
56
 
57
- const { getPostUrl, getPostContent } = getIntegrationOptions();
57
+ const { getPostUrl, getPostContent } = getRespectifyRuntime();
58
58
  const respectifyClient = getRespectifyClient(config);
59
59
  const topicDescription = `Post: ${postSlug}`;
60
60
 
@@ -65,7 +65,7 @@ async function getOrInitializeArticleId(postSlug: string, config: RespectifyConf
65
65
  if (!site) {
66
66
  throw new Error('import.meta.env.SITE must be set in astro.config.ts for Respectify topic initialization.');
67
67
  }
68
- return respectifyClient.initTopicFromUrl(getPostUrl!(postSlug, site), topicDescription);
68
+ return respectifyClient.initTopicFromUrl(getPostUrl(postSlug, site), topicDescription);
69
69
  })());
70
70
 
71
71
  articleIdCache.set(postSlug, result.article_id);
package/src/options.ts ADDED
@@ -0,0 +1,135 @@
1
+ import { z } from 'zod';
2
+ import { RespectifyError, validateModerationTolerances } from '@respectify/client';
3
+ import type { ModerationTolerances } from '@respectify/client';
4
+ import type {
5
+ RespectifyIntegrationClientConfig,
6
+ RespectifyIntegrationOptions,
7
+ RespectifyMegacallConfig,
8
+ ResolvedIntegrationOptions,
9
+ } from './types';
10
+
11
+ /** The options the server bundle sees when `respectify()` is given only `runtime`. */
12
+ export const DEFAULT_INTEGRATION_OPTIONS: ResolvedIntegrationOptions = {
13
+ configPath: './respectify.config.json',
14
+ commentsApiPath: '/api/respectify/comments',
15
+ showBranding: true,
16
+ rateLimit: { windowMs: 5 * 60 * 1000, maxRequests: 10 },
17
+ };
18
+
19
+ /** Options that used to be accepted by `respectify()` and now belong in the runtime module. */
20
+ const RUNTIME_ONLY_OPTIONS = ['getPostUrl', 'getPostContent'] as const;
21
+
22
+ /** Credentials are never serialized into the server bundle. */
23
+ const CREDENTIAL_CLIENT_OPTIONS = ['email', 'apiKey'] as const;
24
+
25
+ const clientConfigSchema = z
26
+ .object({
27
+ baseUrl: z.string().url().optional(),
28
+ version: z.string().optional(),
29
+ timeout: z.number().positive().optional(),
30
+ website: z.string().optional(),
31
+ })
32
+ .strict() satisfies z.ZodType<RespectifyIntegrationClientConfig>;
33
+
34
+ const megacallConfigSchema = z
35
+ .object({
36
+ includeSpam: z.boolean().optional(),
37
+ includeRelevance: z.boolean().optional(),
38
+ includeCommentScore: z.boolean().optional(),
39
+ includeDogwhistle: z.boolean().optional(),
40
+ includePerspectiveAnalyzeComment: z.boolean().optional(),
41
+ bannedTopics: z.array(z.string()).optional(),
42
+ sensitiveTopics: z.array(z.string()).optional(),
43
+ dogwhistleExamples: z.array(z.string()).optional(),
44
+ replyToComment: z.string().optional(),
45
+ contextComments: z.array(z.string()).optional(),
46
+ })
47
+ .strict() satisfies z.ZodType<RespectifyMegacallConfig>;
48
+
49
+ /** Tolerances are checked by the Respectify client's own validator, so the wording matches the API. */
50
+ const tolerancesSchema = z.custom<ModerationTolerances>().superRefine((tolerances, ctx) => {
51
+ try {
52
+ validateModerationTolerances(tolerances);
53
+ } catch (error) {
54
+ if (!(error instanceof RespectifyError)) throw error;
55
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Invalid Respectify tolerances: ${error.message}` });
56
+ }
57
+ });
58
+
59
+ const integrationOptionsSchema = z
60
+ .object({
61
+ runtime: z.string().min(1, 'runtime must name the module that calls defineRespectifyRuntime()'),
62
+ configPath: z.string().min(1).default(DEFAULT_INTEGRATION_OPTIONS.configPath),
63
+ commentsApiPath: z
64
+ .string()
65
+ .startsWith('/', 'commentsApiPath must be a path starting with "/"')
66
+ .default(DEFAULT_INTEGRATION_OPTIONS.commentsApiPath),
67
+ showBranding: z.boolean().default(DEFAULT_INTEGRATION_OPTIONS.showBranding),
68
+ rateLimit: z
69
+ .object({
70
+ windowMs: z.number().int().positive(),
71
+ maxRequests: z.number().int().positive(),
72
+ })
73
+ .strict()
74
+ .default(DEFAULT_INTEGRATION_OPTIONS.rateLimit),
75
+ client: clientConfigSchema.optional(),
76
+ megacall: megacallConfigSchema.optional(),
77
+ tolerances: tolerancesSchema.optional(),
78
+ })
79
+ .strict();
80
+
81
+ /** The validated options: what the server bundle sees, plus the runtime module's specifier. */
82
+ export type ParsedIntegrationOptions = ResolvedIntegrationOptions & { runtime: string };
83
+
84
+ /** Throw a clear error for an option that cannot be serialized or must not be. */
85
+ function assertNoMisplacedOptions(userOptions: RespectifyIntegrationOptions): void {
86
+ for (const option of RUNTIME_ONLY_OPTIONS) {
87
+ if (option in userOptions) {
88
+ throw new Error(
89
+ `@respectify/astro: the "${option}" option moved out of astro.config. ` +
90
+ `Export it from your runtime module with defineRespectifyRuntime({ store, ${option} }) ` +
91
+ 'and point respectify({ runtime }) at that module. Functions cannot reach the server bundle.',
92
+ );
93
+ }
94
+ }
95
+
96
+ const client = userOptions.client;
97
+ if (client === undefined) return;
98
+ for (const option of CREDENTIAL_CLIENT_OPTIONS) {
99
+ if (option in client) {
100
+ throw new Error(
101
+ `@respectify/astro: "client.${option}" is not accepted in astro.config, because integration options ` +
102
+ 'are written into the server bundle. Set RESPECTIFY_EMAIL and RESPECTIFY_API_KEY instead.',
103
+ );
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Validate `respectify()`'s options and apply defaults. Runs at setup, so a bad option fails
110
+ * the build instead of the first comment.
111
+ * @throws Error naming every invalid option
112
+ */
113
+ export function parseIntegrationOptions(userOptions: RespectifyIntegrationOptions): ParsedIntegrationOptions {
114
+ assertNoMisplacedOptions(userOptions);
115
+
116
+ const result = integrationOptionsSchema.safeParse(userOptions);
117
+ if (!result.success) {
118
+ const issues = result.error.issues.map((issue) => `${issue.path.join('.') || 'options'}: ${issue.message}`);
119
+ throw new Error(`Invalid @respectify/astro options: ${issues.join('; ')}`);
120
+ }
121
+ return result.data;
122
+ }
123
+
124
+ /** Split the parsed options into the runtime specifier and what the server bundle sees. */
125
+ export function toResolvedIntegrationOptions(parsed: ParsedIntegrationOptions): ResolvedIntegrationOptions {
126
+ return {
127
+ configPath: parsed.configPath,
128
+ commentsApiPath: parsed.commentsApiPath,
129
+ showBranding: parsed.showBranding,
130
+ rateLimit: parsed.rateLimit,
131
+ client: parsed.client,
132
+ megacall: parsed.megacall,
133
+ tolerances: parsed.tolerances,
134
+ };
135
+ }
@@ -1,44 +1,42 @@
1
1
  import type { APIContext } from 'astro';
2
- import { db, Comment as CommentTable, eq, and, asc } from 'astro:db';
2
+ import { logger } from '../lib/logger';
3
+ import { getRespectifyRuntime } from '../runtime';
4
+ import { COMMENT_LIMITS } from '../store/limits';
5
+ import type { PublicComment } from '../store/types';
3
6
 
4
7
  export const prerender = false;
5
8
 
6
- export async function GET(context: APIContext): Promise<Response> {
9
+ function json(body: Record<string, string | PublicComment[]>, status: number): Response {
10
+ return new Response(JSON.stringify(body), {
11
+ status,
12
+ headers: {
13
+ 'Content-Type': 'application/json',
14
+ 'Cache-Control': 'no-store',
15
+ },
16
+ });
17
+ }
18
+
19
+ /** The approved comments on the post named by `?slug=`, oldest first. */
20
+ export async function GET(context: Pick<APIContext, 'url'>): Promise<Response> {
7
21
  const slug = context.url.searchParams.get('slug');
8
22
 
9
- if (!slug) {
10
- return new Response(JSON.stringify({ error: 'Missing slug parameter' }), {
11
- status: 400,
12
- headers: { 'Content-Type': 'application/json' },
13
- });
23
+ if (!slug || slug.length > COMMENT_LIMITS.postSlugMax) {
24
+ return json({ error: 'Missing or invalid slug parameter' }, 400);
14
25
  }
15
26
 
16
27
  try {
17
- const comments = await db
18
- .select({
19
- id: CommentTable.id,
20
- author: CommentTable.author,
21
- content: CommentTable.content,
22
- createdAt: CommentTable.createdAt,
23
- })
24
- .from(CommentTable)
25
- .where(and(eq(CommentTable.postSlug, slug), eq(CommentTable.approved, true)))
26
- .orderBy(asc(CommentTable.createdAt));
27
-
28
- return new Response(JSON.stringify({ comments }), {
29
- status: 200,
30
- headers: {
31
- 'Content-Type': 'application/json',
32
- 'Cache-Control': 'no-store',
33
- },
34
- });
35
- } catch {
36
- return new Response(JSON.stringify({ comments: [] }), {
37
- status: 200,
38
- headers: {
39
- 'Content-Type': 'application/json',
40
- 'Cache-Control': 'no-store',
41
- },
42
- });
28
+ const approved = await getRespectifyRuntime().store.listApproved(slug);
29
+ // Copy only the public fields, so a store that returns more can never leak them
30
+ const comments = approved.map(({ id, author, content, createdAt, parentId }) => ({
31
+ id,
32
+ author,
33
+ content,
34
+ createdAt,
35
+ parentId,
36
+ }));
37
+ return json({ comments }, 200);
38
+ } catch (error) {
39
+ logger.error('Could not load comments', { slug, error });
40
+ return json({ error: 'Could not load comments' }, 500);
43
41
  }
44
42
  }
@@ -1,39 +1,13 @@
1
- import type { RespectifyIntegrationOptions, RespectifyClientConfig, RespectifyMegacallConfig } from './types';
2
-
3
- export type ResolvedIntegrationOptions = Required<
4
- Pick<RespectifyIntegrationOptions, 'configPath' | 'commentsApiPath' | 'showBranding'>
5
- > &
6
- Pick<RespectifyIntegrationOptions, 'getPostUrl' | 'getPostContent' | 'rateLimit' | 'client' | 'megacall' | 'tolerances'>;
7
-
8
- const defaults: ResolvedIntegrationOptions = {
9
- configPath: './respectify.config.json',
10
- commentsApiPath: '/api/respectify/comments',
11
- showBranding: true,
12
- getPostUrl: (slug, site) => `${site.replace(/\/$/, '')}/posts/${slug}/`,
13
- getPostContent: undefined,
14
- rateLimit: { windowMs: 5 * 60 * 1000, maxRequests: 10 },
15
- client: undefined,
16
- megacall: undefined,
17
- tolerances: undefined,
18
- };
19
-
20
- let options: ResolvedIntegrationOptions = { ...defaults };
21
-
22
- export function setIntegrationOptions(userOptions: RespectifyIntegrationOptions = {}): void {
23
- options = {
24
- ...defaults,
25
- ...userOptions,
26
- getPostUrl: userOptions.getPostUrl ?? defaults.getPostUrl,
27
- getPostContent: userOptions.getPostContent,
28
- rateLimit: userOptions.rateLimit ?? defaults.rateLimit,
29
- client: userOptions.client,
30
- megacall: userOptions.megacall,
31
- tolerances: userOptions.tolerances,
32
- };
33
- }
34
-
1
+ import options from 'virtual:@respectify/astro/options';
2
+ import type { ResolvedIntegrationOptions } from './types';
3
+
4
+ /**
5
+ * The options given to `respectify()` in astro.config, with defaults applied. They reach the
6
+ * server bundle through the `virtual:@respectify/astro/options` module, which the integration
7
+ * writes at setup; module state set in astro.config would not.
8
+ */
35
9
  export function getIntegrationOptions(): ResolvedIntegrationOptions {
36
10
  return options;
37
11
  }
38
12
 
39
- export type { RespectifyClientConfig, RespectifyMegacallConfig };
13
+ export type { ResolvedIntegrationOptions };
package/src/runtime.ts ADDED
@@ -0,0 +1,28 @@
1
+ import runtime from 'virtual:@respectify/astro/runtime';
2
+ import type { RespectifyRuntime } from './types';
3
+
4
+ /** The site's runtime module, with the default `getPostUrl` applied. */
5
+ export type ResolvedRespectifyRuntime = RespectifyRuntime & Required<Pick<RespectifyRuntime, 'getPostUrl'>>;
6
+
7
+ /** The default canonical post URL: `${site}/posts/${slug}/`. */
8
+ function defaultGetPostUrl(slug: string, site: string): string {
9
+ return `${site.replace(/\/$/, '')}/posts/${slug}/`;
10
+ }
11
+
12
+ /**
13
+ * The comment store and post functions from the module named by `respectify({ runtime })`.
14
+ * Kept apart from the options so pages that only need options do not load the store.
15
+ * @throws Error when the runtime module's default export has no store
16
+ */
17
+ export function getRespectifyRuntime(): ResolvedRespectifyRuntime {
18
+ if (!runtime?.store) {
19
+ throw new Error(
20
+ '@respectify/astro: the runtime module has no store. Its default export must be defineRespectifyRuntime({ store }).',
21
+ );
22
+ }
23
+ return {
24
+ store: runtime.store,
25
+ getPostUrl: runtime.getPostUrl ?? defaultGetPostUrl,
26
+ getPostContent: runtime.getPostContent,
27
+ };
28
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Length limits for comment fields, shared by the store's input schema and the
3
+ * `comments.submit` action's schema (which uses Astro's own Zod, so it cannot share the
4
+ * schema object itself).
5
+ */
6
+ export const COMMENT_LIMITS = {
7
+ postSlugMax: 500,
8
+ authorMax: 100,
9
+ emailMax: 320,
10
+ contentMax: 5000,
11
+ } as const;
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import { COMMENT_LIMITS } from './limits';
3
+ import type { NewComment } from './types';
4
+
5
+ /** A comment id: a positive integer. */
6
+ export const commentIdSchema = z.number().int().positive();
7
+
8
+ /** What a store accepts in `create`. Every store validates its input against this. */
9
+ export const newCommentSchema = z
10
+ .object({
11
+ postSlug: z.string().min(1).max(COMMENT_LIMITS.postSlugMax),
12
+ author: z.string().min(1).max(COMMENT_LIMITS.authorMax),
13
+ email: z.string().email().max(COMMENT_LIMITS.emailMax).optional(),
14
+ content: z.string().min(1).max(COMMENT_LIMITS.contentMax),
15
+ approved: z.boolean(),
16
+ parentId: commentIdSchema.optional(),
17
+ })
18
+ .strict() satisfies z.ZodType<NewComment>;
19
+
20
+ /** Thrown by a store when `create` is given input that does not match `newCommentSchema`. */
21
+ export class CommentValidationError extends Error {
22
+ readonly issues: z.ZodIssue[];
23
+
24
+ constructor(issues: z.ZodIssue[]) {
25
+ super(`Invalid comment: ${issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ')}`);
26
+ this.name = 'CommentValidationError';
27
+ this.issues = issues;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Validate a new comment for a store.
33
+ * @throws CommentValidationError when it does not match `newCommentSchema`
34
+ */
35
+ export function parseNewComment(input: NewComment): NewComment {
36
+ const result = newCommentSchema.safeParse(input);
37
+ if (!result.success) {
38
+ throw new CommentValidationError(result.error.issues);
39
+ }
40
+ return result.data;
41
+ }
@@ -0,0 +1,52 @@
1
+ /** A stored comment, as every comment store returns it. */
2
+ export interface CommentRecord {
3
+ id: number;
4
+ postSlug: string;
5
+ author: string;
6
+ email: string | null;
7
+ content: string;
8
+ createdAt: Date;
9
+ approved: boolean;
10
+ /** The comment this one replies to, or null for a top-level comment (or one whose parent was deleted) */
11
+ parentId: number | null;
12
+ }
13
+
14
+ /** A comment to store. The store assigns `id` and `createdAt`. */
15
+ export interface NewComment {
16
+ postSlug: string;
17
+ author: string;
18
+ email?: string;
19
+ content: string;
20
+ approved: boolean;
21
+ parentId?: number;
22
+ }
23
+
24
+ /** The fields of an approved comment that are safe to show to anyone. Never includes `email`. */
25
+ export type PublicComment = Pick<CommentRecord, 'id' | 'author' | 'content' | 'createdAt' | 'parentId'>;
26
+
27
+ /**
28
+ * Where comments are kept. The integration's actions, API route and service depend only on
29
+ * this interface, never on a database.
30
+ *
31
+ * Every store must pass the shared contract suite in `@respectify/astro/testing`. Stores
32
+ * never create tables or run migrations: the schema is the site's to manage.
33
+ */
34
+ export interface ICommentStore {
35
+ /** The comment with this id, or undefined when there is none */
36
+ findById(id: number): Promise<CommentRecord | undefined>;
37
+
38
+ /** The approved comments on a post, oldest first (ties broken by id) */
39
+ listApproved(postSlug: string): Promise<PublicComment[]>;
40
+
41
+ /**
42
+ * Store a new comment and return it as stored.
43
+ * @throws CommentValidationError when the input does not match `newCommentSchema`
44
+ */
45
+ create(input: NewComment): Promise<CommentRecord>;
46
+
47
+ /**
48
+ * Delete a comment. Its replies are kept, with `parentId` set to null.
49
+ * @returns true when a comment was deleted, false when there was none with this id
50
+ */
51
+ delete(id: number): Promise<boolean>;
52
+ }