@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.
@@ -0,0 +1,197 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { CommentValidationError } from '../store/schemas';
3
+ import type { ICommentStore, NewComment } from '../store/types';
4
+
5
+ /** A store on an empty comment table, and how to release it after the test. */
6
+ export interface CommentStoreFixture {
7
+ store: ICommentStore;
8
+ dispose?: () => Promise<void> | void;
9
+ }
10
+
11
+ /**
12
+ * The contract every `ICommentStore` must meet, as a Vitest suite. Call it from a test file
13
+ * with a factory that returns a store on a new, empty, migrated table each time:
14
+ *
15
+ * ```ts
16
+ * import { describeCommentStoreContract } from '@respectify/astro/testing';
17
+ * describeCommentStoreContract('my store', async () => ({ store: createMyStore(await freshDb()) }));
18
+ * ```
19
+ */
20
+ export function describeCommentStoreContract(name: string, createFixture: () => Promise<CommentStoreFixture>): void {
21
+ describe(`ICommentStore contract: ${name}`, () => {
22
+ let fixture: CommentStoreFixture;
23
+ let store: ICommentStore;
24
+
25
+ beforeEach(async () => {
26
+ fixture = await createFixture();
27
+ store = fixture.store;
28
+ });
29
+
30
+ afterEach(async () => {
31
+ await fixture.dispose?.();
32
+ });
33
+
34
+ function comment(overrides: Partial<NewComment> = {}): NewComment {
35
+ return { postSlug: 'a-post', author: 'Ada', content: 'A comment.', approved: true, ...overrides };
36
+ }
37
+
38
+ describe('create', () => {
39
+ it('returns the stored comment with an id and a creation time', async () => {
40
+ const before = Date.now();
41
+ const created = await store.create(comment({ email: 'ada@example.com' }));
42
+
43
+ expect(created).toEqual({
44
+ id: expect.any(Number),
45
+ postSlug: 'a-post',
46
+ author: 'Ada',
47
+ email: 'ada@example.com',
48
+ content: 'A comment.',
49
+ createdAt: expect.any(Date),
50
+ approved: true,
51
+ parentId: null,
52
+ });
53
+ // Some databases keep whole seconds only
54
+ expect(created.createdAt.getTime()).toBeGreaterThanOrEqual(Math.floor(before / 1000) * 1000);
55
+ expect(created.createdAt.getTime()).toBeLessThanOrEqual(Date.now() + 1000);
56
+ });
57
+
58
+ it('stores a missing email and parent as null', async () => {
59
+ const created = await store.create(comment());
60
+
61
+ expect(created.email).toBeNull();
62
+ expect(created.parentId).toBeNull();
63
+ });
64
+
65
+ it('stores an unapproved comment as unapproved', async () => {
66
+ const created = await store.create(comment({ approved: false }));
67
+
68
+ expect(created.approved).toBe(false);
69
+ });
70
+
71
+ it('stores the parent of a reply', async () => {
72
+ const parent = await store.create(comment());
73
+ const reply = await store.create(comment({ parentId: parent.id }));
74
+
75
+ expect(reply.parentId).toBe(parent.id);
76
+ });
77
+
78
+ it('gives each comment a different id', async () => {
79
+ const first = await store.create(comment());
80
+ const second = await store.create(comment());
81
+
82
+ expect(second.id).not.toBe(first.id);
83
+ });
84
+
85
+ it('keeps quotes, backslashes, SQL and non-Latin text exactly as given', async () => {
86
+ const content = `It's "quoted" \\ back; DROP TABLE comments; -- 你好 🎉`;
87
+ const created = await store.create(comment({ content, author: `O'Brien` }));
88
+
89
+ const found = await store.findById(created.id);
90
+ expect(found?.content).toBe(content);
91
+ expect(found?.author).toBe(`O'Brien`);
92
+ });
93
+
94
+ it.each<[string, Partial<NewComment>]>([
95
+ ['an empty author', { author: '' }],
96
+ ['an empty comment', { content: '' }],
97
+ ['an empty post slug', { postSlug: '' }],
98
+ ['a comment over the length limit', { content: 'x'.repeat(5001) }],
99
+ ['an author over the length limit', { author: 'x'.repeat(101) }],
100
+ ['an invalid email', { email: 'not-an-email' }],
101
+ ['a parent id that is not a positive integer', { parentId: 0 }],
102
+ ])('rejects %s and stores nothing', async (_label, overrides) => {
103
+ await expect(store.create(comment(overrides))).rejects.toBeInstanceOf(CommentValidationError);
104
+
105
+ expect(await store.listApproved(overrides.postSlug ?? 'a-post')).toEqual([]);
106
+ });
107
+ });
108
+
109
+ describe('findById', () => {
110
+ it('returns the comment with that id, email included', async () => {
111
+ const created = await store.create(comment({ email: 'ada@example.com', approved: false }));
112
+
113
+ expect(await store.findById(created.id)).toEqual(created);
114
+ });
115
+
116
+ it('returns undefined when there is no comment with that id', async () => {
117
+ expect(await store.findById(987_654)).toBeUndefined();
118
+ });
119
+
120
+ it('returns undefined for an id that is not a positive integer', async () => {
121
+ expect(await store.findById(-1)).toBeUndefined();
122
+ expect(await store.findById(1.5)).toBeUndefined();
123
+ });
124
+ });
125
+
126
+ describe('listApproved', () => {
127
+ it("returns only the post's approved comments", async () => {
128
+ const approved = await store.create(comment({ content: 'Approved.' }));
129
+ await store.create(comment({ content: 'Held back.', approved: false }));
130
+ await store.create(comment({ postSlug: 'another-post', content: 'Elsewhere.' }));
131
+
132
+ const listed = await store.listApproved('a-post');
133
+
134
+ expect(listed.map((c) => c.id)).toEqual([approved.id]);
135
+ });
136
+
137
+ it('returns the public fields only, never the email', async () => {
138
+ const parent = await store.create(comment({ email: 'ada@example.com' }));
139
+ const reply = await store.create(comment({ email: 'bob@example.com', author: 'Bob', parentId: parent.id }));
140
+
141
+ const listed = await store.listApproved('a-post');
142
+
143
+ expect(listed).toEqual([
144
+ { id: parent.id, author: 'Ada', content: 'A comment.', createdAt: parent.createdAt, parentId: null },
145
+ { id: reply.id, author: 'Bob', content: 'A comment.', createdAt: reply.createdAt, parentId: parent.id },
146
+ ]);
147
+ });
148
+
149
+ it('lists oldest first, breaking ties by id', async () => {
150
+ const created = [];
151
+ for (const content of ['First.', 'Second.', 'Third.']) {
152
+ created.push(await store.create(comment({ content })));
153
+ }
154
+
155
+ const listed = await store.listApproved('a-post');
156
+
157
+ expect(listed.map((c) => c.content)).toEqual(['First.', 'Second.', 'Third.']);
158
+ });
159
+
160
+ it('returns an empty list for a post with no comments', async () => {
161
+ expect(await store.listApproved('no-such-post')).toEqual([]);
162
+ });
163
+ });
164
+
165
+ describe('delete', () => {
166
+ it('deletes the comment and returns true', async () => {
167
+ const created = await store.create(comment());
168
+
169
+ expect(await store.delete(created.id)).toBe(true);
170
+ expect(await store.findById(created.id)).toBeUndefined();
171
+ expect(await store.listApproved('a-post')).toEqual([]);
172
+ });
173
+
174
+ it('returns false when there is no comment with that id', async () => {
175
+ expect(await store.delete(987_654)).toBe(false);
176
+ });
177
+
178
+ it('leaves the other comments alone', async () => {
179
+ const kept = await store.create(comment({ content: 'Kept.' }));
180
+ const removed = await store.create(comment({ content: 'Removed.' }));
181
+
182
+ await store.delete(removed.id);
183
+
184
+ expect((await store.listApproved('a-post')).map((c) => c.id)).toEqual([kept.id]);
185
+ });
186
+
187
+ it('keeps the replies of a deleted comment, with no parent', async () => {
188
+ const parent = await store.create(comment());
189
+ const reply = await store.create(comment({ parentId: parent.id }));
190
+
191
+ await store.delete(parent.id);
192
+
193
+ expect(await store.findById(reply.id)).toEqual({ ...reply, parentId: null });
194
+ });
195
+ });
196
+ });
197
+ }
@@ -0,0 +1 @@
1
+ export { describeCommentStoreContract, type CommentStoreFixture } from './comment-store-contract';
package/src/types.ts CHANGED
@@ -4,6 +4,7 @@ import type {
4
4
  ModerationTolerances,
5
5
  RespectifyClientOptions,
6
6
  } from '@respectify/client';
7
+ import type { ICommentStore } from './store/types';
7
8
 
8
9
  /**
9
10
  * Options forwarded to `RespectifyClient`.
@@ -18,20 +19,27 @@ export type RespectifyClientConfig = Partial<RespectifyClientOptions>;
18
19
  */
19
20
  export type RespectifyMegacallConfig = Omit<MegacallOptions, 'comment' | 'articleId' | 'tolerances'>;
20
21
 
21
- export interface RespectifyIntegrationOptions {
22
- /** Path to respectify.config.json (default: ./respectify.config.json) */
23
- configPath?: string;
24
-
25
- /** Build the canonical URL for a post — used to initialize Respectify topics */
26
- getPostUrl?: (slug: string, site: string) => string;
22
+ /**
23
+ * Client options the integration accepts in astro.config. Credentials are not among them:
24
+ * options are serialized into the server bundle, so credentials come from the
25
+ * `RESPECTIFY_EMAIL` / `RESPECTIFY_API_KEY` env vars (or respectify.config.json) instead.
26
+ */
27
+ export type RespectifyIntegrationClientConfig = Omit<RespectifyClientConfig, 'email' | 'apiKey'>;
27
28
 
29
+ /**
30
+ * Options for `respectify()` in astro.config. Every option must be serializable: they are
31
+ * passed to the server bundle as JSON. Functions and the comment store belong in the
32
+ * runtime module (see `defineRespectifyRuntime`).
33
+ */
34
+ export interface RespectifyIntegrationOptions {
28
35
  /**
29
- * Provide a post's raw text content directly instead of having Respectify fetch
30
- * `getPostUrl`. Useful when the URL isn't publicly fetchable (staged/preview content,
31
- * auth-gated pages, or timing issues right after deploy). Takes priority over
32
- * `getPostUrl` for topic initialization when provided.
36
+ * The runtime module: a file whose default export is `defineRespectifyRuntime({ store, ... })`.
37
+ * A relative path is resolved against the project root; a package specifier is left to Vite.
33
38
  */
34
- getPostContent?: (slug: string) => string | Promise<string>;
39
+ runtime: string;
40
+
41
+ /** Path to respectify.config.json (default: ./respectify.config.json) */
42
+ configPath?: string;
35
43
 
36
44
  /** API route path for fetching comments (default: /api/respectify/comments) */
37
45
  commentsApiPath?: string;
@@ -46,10 +54,9 @@ export interface RespectifyIntegrationOptions {
46
54
  };
47
55
 
48
56
  /**
49
- * Options forwarded to the Respectify API client
50
- * (`baseUrl`, `timeout`, `version`, `website`, optional credential overrides).
57
+ * Options forwarded to the Respectify API client (`baseUrl`, `timeout`, `version`, `website`).
51
58
  */
52
- client?: RespectifyClientConfig;
59
+ client?: RespectifyIntegrationClientConfig;
53
60
 
54
61
  /**
55
62
  * Options forwarded to every Respectify megacall
@@ -67,6 +74,40 @@ export interface RespectifyIntegrationOptions {
67
74
  tolerances?: ModerationTolerances;
68
75
  }
69
76
 
77
+ /** The integration options as the server bundle sees them, with defaults applied. */
78
+ export interface ResolvedIntegrationOptions {
79
+ configPath: string;
80
+ commentsApiPath: string;
81
+ showBranding: boolean;
82
+ rateLimit: {
83
+ windowMs: number;
84
+ maxRequests: number;
85
+ };
86
+ client?: RespectifyIntegrationClientConfig;
87
+ megacall?: RespectifyMegacallConfig;
88
+ tolerances?: ModerationTolerances;
89
+ }
90
+
91
+ /**
92
+ * What the runtime module provides: the parts of the integration that are not serializable.
93
+ * It is loaded in the server bundle, so it may hold database clients and functions.
94
+ */
95
+ export interface RespectifyRuntime {
96
+ /** Where comments are kept */
97
+ store: ICommentStore;
98
+
99
+ /** Build the canonical URL for a post, used to initialize Respectify topics (default: `${site}/posts/${slug}/`) */
100
+ getPostUrl?: (slug: string, site: string) => string;
101
+
102
+ /**
103
+ * Provide a post's raw text content directly instead of having Respectify fetch
104
+ * `getPostUrl`. Useful when the URL isn't publicly fetchable (staged/preview content,
105
+ * auth-gated pages, or timing issues right after deploy). Takes priority over
106
+ * `getPostUrl` for topic initialization when provided.
107
+ */
108
+ getPostContent?: (slug: string) => string | Promise<string>;
109
+ }
110
+
70
111
  export interface AnalyzeCommentOptions {
71
112
  /** Parent comment text when submitting a reply */
72
113
  replyToComment?: string;
package/src/schema.ts DELETED
@@ -1,25 +0,0 @@
1
- import { defineTable, column, NOW } from 'astro:db';
2
- import type { TableConfig } from '@astrojs/db/types';
3
-
4
- const respectifyCommentColumns = {
5
- id: column.number({ primaryKey: true }),
6
- postSlug: column.text(),
7
- author: column.text(),
8
- email: column.text({ optional: true }),
9
- content: column.text(),
10
- createdAt: column.date({ default: NOW }),
11
- approved: column.boolean({ default: false }),
12
- parentId: column.number({ optional: true }),
13
- };
14
-
15
- /** Astro DB table definition for Respectify comments. Merge into your db/config.ts. */
16
- export const RespectifyComment: TableConfig<typeof respectifyCommentColumns> = defineTable({
17
- columns: respectifyCommentColumns,
18
- indexes: [
19
- { on: ['postSlug'], unique: false },
20
- { on: ['approved'], unique: false },
21
- ],
22
- });
23
-
24
- /** Alias for backwards compatibility with existing schemas */
25
- export const Comment = RespectifyComment;