@respectify/astro 1.0.2 → 1.2.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 +101 -9
- package/components/CommentForm.astro +21 -3
- package/dist/cli/bin.js +13 -0
- package/dist/cli/cli.js +98 -0
- package/dist/cli/init.js +225 -0
- package/dist/cli/project-files.js +38 -0
- package/dist/cli/templates.js +142 -0
- package/dist/cli/terminal.js +35 -0
- package/dist/cli/types.js +2 -0
- package/package.json +10 -4
- package/src/actions.ts +75 -10
- package/src/cli/bin.ts +15 -0
- package/src/cli/cli.ts +120 -0
- package/src/cli/init.ts +311 -0
- package/src/cli/project-files.ts +47 -0
- package/src/cli/templates.ts +158 -0
- package/src/cli/terminal.ts +39 -0
- package/src/cli/types.ts +89 -0
- package/src/define-runtime.ts +1 -1
- package/src/index.ts +8 -2
- package/src/lib/messages.ts +2 -0
- package/src/lib/service.ts +76 -1
- package/src/options.ts +7 -1
- package/src/runtime.ts +2 -0
- package/src/types.ts +72 -2
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Where `init` puts each file, relative to the project root. */
|
|
2
|
+
export const SCAFFOLD_PATHS = {
|
|
3
|
+
runtime: 'src/respectify.runtime.ts',
|
|
4
|
+
config: 'respectify.config.json',
|
|
5
|
+
actions: 'src/actions/index.ts',
|
|
6
|
+
schema: 'src/db/schema.ts',
|
|
7
|
+
drizzleConfig: 'drizzle.config.ts',
|
|
8
|
+
};
|
|
9
|
+
/** The package subpath that exports the comment table and store for each database. */
|
|
10
|
+
const ADAPTER_ENTRY = {
|
|
11
|
+
postgres: '@respectify/astro/postgres',
|
|
12
|
+
sqlite: '@respectify/astro/sqlite',
|
|
13
|
+
};
|
|
14
|
+
/** The line a Drizzle schema needs so drizzle-kit creates the comment table. */
|
|
15
|
+
export function schemaExportLine(database) {
|
|
16
|
+
return `export { respectifyComments } from '${ADAPTER_ENTRY[database]}';`;
|
|
17
|
+
}
|
|
18
|
+
/** A new Drizzle schema file holding only the comment table. */
|
|
19
|
+
export function schemaTemplate(database) {
|
|
20
|
+
return `// The table Respectify comments are stored in. Add your own tables to this file too.
|
|
21
|
+
${schemaExportLine(database)}
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
const POSTGRES_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
|
|
25
|
+
import { createPostgresCommentStore } from '@respectify/astro/postgres';
|
|
26
|
+
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
27
|
+
import { Pool } from 'pg';
|
|
28
|
+
import { getSecret } from 'astro:env/server';
|
|
29
|
+
|
|
30
|
+
const connectionString = getSecret('DATABASE_URL');
|
|
31
|
+
if (!connectionString) {
|
|
32
|
+
throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// If your site already creates a Drizzle database, import it here and delete these lines.
|
|
36
|
+
const db = drizzle({ client: new Pool({ connectionString }) });
|
|
37
|
+
|
|
38
|
+
export default defineRespectifyRuntime({
|
|
39
|
+
store: createPostgresCommentStore(db),
|
|
40
|
+
// Optional: the public URL of a post, which Respectify reads for topic context
|
|
41
|
+
// getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
|
|
42
|
+
});
|
|
43
|
+
`;
|
|
44
|
+
const SQLITE_RUNTIME = `import { defineRespectifyRuntime } from '@respectify/astro/runtime';
|
|
45
|
+
import { createSqliteCommentStore } from '@respectify/astro/sqlite';
|
|
46
|
+
import { drizzle } from 'drizzle-orm/libsql';
|
|
47
|
+
import { createClient } from '@libsql/client';
|
|
48
|
+
import { getSecret } from 'astro:env/server';
|
|
49
|
+
|
|
50
|
+
const url = getSecret('DATABASE_URL');
|
|
51
|
+
if (!url) {
|
|
52
|
+
throw new Error('DATABASE_URL is not set. Respectify comments need it to reach your database.');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Only a hosted database such as Turso needs a token; an empty one counts as none
|
|
56
|
+
const authToken = getSecret('DATABASE_AUTH_TOKEN') || undefined;
|
|
57
|
+
|
|
58
|
+
// If your site already creates a Drizzle database, import it here and delete these lines.
|
|
59
|
+
const db = drizzle({ client: createClient({ url, authToken }) });
|
|
60
|
+
|
|
61
|
+
export default defineRespectifyRuntime({
|
|
62
|
+
store: createSqliteCommentStore(db),
|
|
63
|
+
// Optional: the public URL of a post, which Respectify reads for topic context
|
|
64
|
+
// getPostUrl: (slug, site) => \`\${site}/blog/\${slug}/\`,
|
|
65
|
+
});
|
|
66
|
+
`;
|
|
67
|
+
/** The runtime module: it builds the comment store from the site's database connection. */
|
|
68
|
+
export function runtimeTemplate(database) {
|
|
69
|
+
return database === 'postgres' ? POSTGRES_RUNTIME : SQLITE_RUNTIME;
|
|
70
|
+
}
|
|
71
|
+
/** The lines an existing actions file needs. */
|
|
72
|
+
export const ACTIONS_MANUAL_INSTRUCTIONS = `Add the comment actions to your existing actions:
|
|
73
|
+
|
|
74
|
+
import { respectifyCommentActions } from '@respectify/astro/actions';
|
|
75
|
+
|
|
76
|
+
export const server = {
|
|
77
|
+
// ...your actions
|
|
78
|
+
comments: respectifyCommentActions,
|
|
79
|
+
};`;
|
|
80
|
+
/** A new Astro Actions file exposing the comment actions. */
|
|
81
|
+
export function actionsTemplate() {
|
|
82
|
+
return `import { respectifyCommentActions } from '@respectify/astro/actions';
|
|
83
|
+
|
|
84
|
+
export const server = {
|
|
85
|
+
comments: respectifyCommentActions,
|
|
86
|
+
};
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
const DRIZZLE_CONFIG_HEAD = `import { existsSync } from 'node:fs';
|
|
90
|
+
import { defineConfig } from 'drizzle-kit';
|
|
91
|
+
|
|
92
|
+
// drizzle-kit does not read .env by itself
|
|
93
|
+
if (existsSync('.env')) process.loadEnvFile('.env');
|
|
94
|
+
|
|
95
|
+
const url = process.env.DATABASE_URL;
|
|
96
|
+
if (!url) {
|
|
97
|
+
throw new Error('Set DATABASE_URL before running drizzle-kit.');
|
|
98
|
+
}
|
|
99
|
+
`;
|
|
100
|
+
/** A new drizzle-kit config pointing at the schema file `init` writes. */
|
|
101
|
+
export function drizzleConfigTemplate(database) {
|
|
102
|
+
const dialect = database === 'postgres' ? 'postgresql' : 'turso';
|
|
103
|
+
// drizzle-kit rejects an empty token, so an empty DATABASE_AUTH_TOKEN counts as none
|
|
104
|
+
const credentials = database === 'postgres' ? '{ url }' : '{ url, authToken: process.env.DATABASE_AUTH_TOKEN || undefined }';
|
|
105
|
+
return `${DRIZZLE_CONFIG_HEAD}
|
|
106
|
+
export default defineConfig({
|
|
107
|
+
dialect: '${dialect}',
|
|
108
|
+
schema: './${SCAFFOLD_PATHS.schema}',
|
|
109
|
+
out: './drizzle',
|
|
110
|
+
dbCredentials: ${credentials},
|
|
111
|
+
});
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
/** The packages each database needs beside `@respectify/astro` itself. */
|
|
115
|
+
export const REQUIRED_PACKAGES = {
|
|
116
|
+
postgres: { runtime: ['@respectify/client', 'drizzle-orm', 'pg'], dev: ['drizzle-kit', '@types/pg'] },
|
|
117
|
+
sqlite: { runtime: ['@respectify/client', 'drizzle-orm', '@libsql/client'], dev: ['drizzle-kit'] },
|
|
118
|
+
};
|
|
119
|
+
/** The lines shown for the environment variables each database's runtime module reads, with sample values. */
|
|
120
|
+
export const ENVIRONMENT_VARIABLES = {
|
|
121
|
+
postgres: [
|
|
122
|
+
'RESPECTIFY_EMAIL=you@example.com',
|
|
123
|
+
'RESPECTIFY_API_KEY=your-api-key',
|
|
124
|
+
'DATABASE_URL=postgres://user:password@host:5432/database',
|
|
125
|
+
],
|
|
126
|
+
sqlite: [
|
|
127
|
+
'RESPECTIFY_EMAIL=you@example.com',
|
|
128
|
+
'RESPECTIFY_API_KEY=your-api-key',
|
|
129
|
+
'DATABASE_URL=file:local.db',
|
|
130
|
+
'',
|
|
131
|
+
'For a hosted database such as Turso, use its URL and token instead:',
|
|
132
|
+
'',
|
|
133
|
+
'DATABASE_URL=libsql://your-database.turso.io',
|
|
134
|
+
'DATABASE_AUTH_TOKEN=your-database-token',
|
|
135
|
+
],
|
|
136
|
+
};
|
|
137
|
+
/** The snippet that puts comments on a page. */
|
|
138
|
+
export const COMPONENT_SNIPPET = `---
|
|
139
|
+
import CommentSection from '@respectify/astro/components/CommentSection.astro';
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
<CommentSection postSlug={post.id} />`;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline/promises';
|
|
2
|
+
/** Writes messages to the terminal: information to stdout, warnings and errors to stderr. */
|
|
3
|
+
export class TerminalLogger {
|
|
4
|
+
info(message) {
|
|
5
|
+
process.stdout.write(`${message}\n`);
|
|
6
|
+
}
|
|
7
|
+
warn(message) {
|
|
8
|
+
process.stderr.write(`Warning: ${message}\n`);
|
|
9
|
+
}
|
|
10
|
+
error(message) {
|
|
11
|
+
process.stderr.write(`Error: ${message}\n`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Asks questions on the terminal, when there is one. */
|
|
15
|
+
export class TerminalPrompter {
|
|
16
|
+
get interactive() {
|
|
17
|
+
return process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
18
|
+
}
|
|
19
|
+
async choose(question, choices) {
|
|
20
|
+
const readline = createInterface({ input: process.stdin, output: process.stdout });
|
|
21
|
+
try {
|
|
22
|
+
const menu = choices.map((choice, index) => ` ${index + 1}. ${choice.label}`).join('\n');
|
|
23
|
+
for (;;) {
|
|
24
|
+
const answer = (await readline.question(`${question}\n${menu}\n> `)).trim().toLowerCase();
|
|
25
|
+
const picked = choices[Number(answer) - 1] ?? choices.find((choice) => choice.value === answer);
|
|
26
|
+
if (picked !== undefined)
|
|
27
|
+
return picked.value;
|
|
28
|
+
process.stdout.write(`Enter a number from 1 to ${choices.length}.\n`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
readline.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@respectify/astro",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Respectify-powered commenting for Astro \u2014 AI moderation, spam filtering, and beautiful UX out of the box.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -41,10 +41,14 @@
|
|
|
41
41
|
"./sqlite": "./src/adapters/sqlite/index.ts",
|
|
42
42
|
"./testing": "./src/testing/index.ts"
|
|
43
43
|
},
|
|
44
|
+
"bin": {
|
|
45
|
+
"respectify-astro": "./dist/cli/bin.js"
|
|
46
|
+
},
|
|
44
47
|
"files": [
|
|
45
48
|
"src",
|
|
46
49
|
"components",
|
|
47
50
|
"client",
|
|
51
|
+
"dist",
|
|
48
52
|
"migrations",
|
|
49
53
|
"drizzle",
|
|
50
54
|
"default-respectify.config.json",
|
|
@@ -53,7 +57,7 @@
|
|
|
53
57
|
],
|
|
54
58
|
"peerDependencies": {
|
|
55
59
|
"@libsql/client": ">=0.10.0",
|
|
56
|
-
"@respectify/client": "^0.
|
|
60
|
+
"@respectify/client": "^0.8.0",
|
|
57
61
|
"astro": "^5.0.0 || ^6.0.0 || ^7.0.0",
|
|
58
62
|
"drizzle-orm": "^0.45.0",
|
|
59
63
|
"pg": "^8.0.0",
|
|
@@ -77,14 +81,16 @@
|
|
|
77
81
|
"zod": "^4.6.6"
|
|
78
82
|
},
|
|
79
83
|
"scripts": {
|
|
80
|
-
"typecheck": "tsc --noEmit",
|
|
84
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.cli.json --noEmit",
|
|
85
|
+
"build:cli": "tsc -p tsconfig.cli.json",
|
|
86
|
+
"prepack": "npm run build:cli",
|
|
81
87
|
"test": "vitest run",
|
|
82
88
|
"migrations:generate": "drizzle-kit generate --config drizzle/postgres.config.ts && drizzle-kit generate --config drizzle/sqlite.config.ts"
|
|
83
89
|
},
|
|
84
90
|
"devDependencies": {
|
|
85
91
|
"@electric-sql/pglite": "0.5.8",
|
|
86
92
|
"@libsql/client": "^0.18.0",
|
|
87
|
-
"@respectify/client": "^0.
|
|
93
|
+
"@respectify/client": "^0.8.0",
|
|
88
94
|
"astro": "^6.0.4",
|
|
89
95
|
"drizzle-kit": "^0.31.11",
|
|
90
96
|
"drizzle-orm": "^0.45.4",
|
package/src/actions.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { defineAction, ActionError, type ActionAPIContext } from 'astro:actions';
|
|
2
2
|
import { z } from 'astro/zod';
|
|
3
3
|
import { analyzeComment } from './lib/service';
|
|
4
|
+
import { logger } from './lib/logger';
|
|
5
|
+
import { HELD_FOR_REVIEW_MESSAGE } from './lib/messages';
|
|
4
6
|
import { checkRateLimit } from './lib/rate-limit';
|
|
5
7
|
import { getIntegrationOptions } from './runtime-config';
|
|
6
8
|
import { getRespectifyRuntime } from './runtime';
|
|
7
9
|
import { COMMENT_LIMITS } from './store/limits';
|
|
8
10
|
import { CommentValidationError } from './store/schemas';
|
|
11
|
+
import type { CommentRecord, NewComment } from './store/types';
|
|
12
|
+
import type { AnalyzeCommentOptions } from './types';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A revision token as the API issues it: URL-safe base64 characters. The pattern keeps
|
|
16
|
+
* anything else out of the request header the token is sent back in.
|
|
17
|
+
*/
|
|
18
|
+
const REVISION_TOKEN_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
9
19
|
|
|
10
20
|
/** Input to `comments.submit`. Uses Astro's Zod (3 on Astro 5, 4 on Astro 6+), so only API both share. */
|
|
11
21
|
export const submitCommentInput = z.object({
|
|
@@ -14,6 +24,8 @@ export const submitCommentInput = z.object({
|
|
|
14
24
|
email: z.string().email().max(COMMENT_LIMITS.emailMax).optional(),
|
|
15
25
|
content: z.string().min(1).max(COMMENT_LIMITS.contentMax),
|
|
16
26
|
parentId: z.number().int().positive().optional(),
|
|
27
|
+
/** The token a previous, unpublished submission of this comment returned (see `SubmitCommentResult`) */
|
|
28
|
+
revisionToken: z.string().regex(REVISION_TOKEN_PATTERN).optional(),
|
|
17
29
|
});
|
|
18
30
|
|
|
19
31
|
/** Input to `comments.delete`. */
|
|
@@ -26,19 +38,41 @@ export type DeleteCommentInput = z.infer<typeof deleteCommentInput>;
|
|
|
26
38
|
|
|
27
39
|
export type SubmitCommentResult =
|
|
28
40
|
| {
|
|
41
|
+
/** Not published: the commenter can revise and resubmit */
|
|
29
42
|
success: false;
|
|
30
43
|
approved: false;
|
|
44
|
+
heldForReview: false;
|
|
31
45
|
feedback: string;
|
|
32
46
|
suggestion: string | undefined;
|
|
33
47
|
suspectedSpam: boolean;
|
|
34
48
|
score: number;
|
|
49
|
+
/**
|
|
50
|
+
* On the free plan, send this back as `revisionToken` when the commenter resubmits the
|
|
51
|
+
* revised comment, so the revision is not counted as a new comment. Keep it with the
|
|
52
|
+
* form; it belongs to this comment only. Absent for paid accounts.
|
|
53
|
+
*/
|
|
54
|
+
revisionToken?: string;
|
|
35
55
|
}
|
|
36
56
|
| {
|
|
57
|
+
/** Stored for the site owner to review, neither published nor rejected */
|
|
58
|
+
success: true;
|
|
59
|
+
approved: false;
|
|
60
|
+
heldForReview: true;
|
|
61
|
+
message: string;
|
|
62
|
+
}
|
|
63
|
+
| {
|
|
64
|
+
/** Published */
|
|
37
65
|
success: true;
|
|
38
66
|
approved: true;
|
|
67
|
+
heldForReview: false;
|
|
39
68
|
feedback: string;
|
|
40
69
|
score: number;
|
|
41
70
|
message: string;
|
|
71
|
+
/**
|
|
72
|
+
* True when Respectify did not assess this comment because the account's free plan is
|
|
73
|
+
* used up. The comment is published all the same; a site can style it differently.
|
|
74
|
+
*/
|
|
75
|
+
unmoderated: boolean;
|
|
42
76
|
};
|
|
43
77
|
|
|
44
78
|
/** The client's address, or a shared bucket when the adapter or rendering mode does not expose one. */
|
|
@@ -67,7 +101,7 @@ async function loadReplyTarget(parentId: number, postSlug: string): Promise<stri
|
|
|
67
101
|
* @throws ActionError TOO_MANY_REQUESTS, or BAD_REQUEST for an invalid parent or comment
|
|
68
102
|
*/
|
|
69
103
|
export async function submitComment(
|
|
70
|
-
{ postSlug, author, email, content, parentId }: SubmitCommentInput,
|
|
104
|
+
{ postSlug, author, email, content, parentId, revisionToken }: SubmitCommentInput,
|
|
71
105
|
context: Pick<ActionAPIContext, 'clientAddress'>,
|
|
72
106
|
): Promise<SubmitCommentResult> {
|
|
73
107
|
const { rateLimit } = getIntegrationOptions();
|
|
@@ -79,37 +113,68 @@ export async function submitComment(
|
|
|
79
113
|
}
|
|
80
114
|
|
|
81
115
|
const replyToComment = parentId === undefined ? undefined : await loadReplyTarget(parentId, postSlug);
|
|
82
|
-
const
|
|
116
|
+
const analyzeOptions: AnalyzeCommentOptions = { replyToComment };
|
|
117
|
+
if (revisionToken !== undefined) analyzeOptions.revisionToken = revisionToken;
|
|
118
|
+
const analysis = await analyzeComment(content, postSlug, analyzeOptions);
|
|
119
|
+
|
|
120
|
+
if (analysis.heldForReview) {
|
|
121
|
+
const comment = await storeComment({ postSlug, author, email, content, parentId, approved: false });
|
|
122
|
+
await notifyHeldForReview(comment);
|
|
123
|
+
return { success: true, approved: false, heldForReview: true, message: HELD_FOR_REVIEW_MESSAGE };
|
|
124
|
+
}
|
|
83
125
|
|
|
84
126
|
if (!analysis.approved) {
|
|
85
127
|
return {
|
|
86
128
|
success: false,
|
|
87
129
|
approved: false,
|
|
130
|
+
heldForReview: false,
|
|
88
131
|
feedback: analysis.feedback,
|
|
89
132
|
suggestion: analysis.suggestion,
|
|
90
133
|
suspectedSpam: analysis.suspectedSpam === true,
|
|
91
134
|
score: analysis.score,
|
|
135
|
+
...(analysis.revisionToken === undefined ? {} : { revisionToken: analysis.revisionToken }),
|
|
92
136
|
};
|
|
93
137
|
}
|
|
94
138
|
|
|
95
|
-
|
|
96
|
-
await getRespectifyRuntime().store.create({ postSlug, author, email, content, parentId, approved: true });
|
|
97
|
-
} catch (error) {
|
|
98
|
-
if (error instanceof CommentValidationError) {
|
|
99
|
-
throw new ActionError({ code: 'BAD_REQUEST', message: error.message });
|
|
100
|
-
}
|
|
101
|
-
throw error;
|
|
102
|
-
}
|
|
139
|
+
await storeComment({ postSlug, author, email, content, parentId, approved: true });
|
|
103
140
|
|
|
104
141
|
return {
|
|
105
142
|
success: true,
|
|
106
143
|
approved: true,
|
|
144
|
+
heldForReview: false,
|
|
107
145
|
feedback: analysis.feedback,
|
|
108
146
|
score: analysis.score,
|
|
109
147
|
message: 'Comment published successfully!',
|
|
148
|
+
unmoderated: analysis.moderationSkipped !== undefined,
|
|
110
149
|
};
|
|
111
150
|
}
|
|
112
151
|
|
|
152
|
+
/**
|
|
153
|
+
* Store a comment through the runtime's store.
|
|
154
|
+
* @throws ActionError BAD_REQUEST when the store rejects the comment
|
|
155
|
+
*/
|
|
156
|
+
async function storeComment(comment: NewComment): Promise<CommentRecord> {
|
|
157
|
+
try {
|
|
158
|
+
return await getRespectifyRuntime().store.create(comment);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error instanceof CommentValidationError) {
|
|
161
|
+
throw new ActionError({ code: 'BAD_REQUEST', message: error.message });
|
|
162
|
+
}
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Tell the site owner a comment awaits their review, when the runtime asks to be told. */
|
|
168
|
+
async function notifyHeldForReview(comment: CommentRecord): Promise<void> {
|
|
169
|
+
const { onHeldForReview } = getRespectifyRuntime();
|
|
170
|
+
if (!onHeldForReview) return;
|
|
171
|
+
try {
|
|
172
|
+
await onHeldForReview({ reason: 'revision_limit_reached', comment });
|
|
173
|
+
} catch (error) {
|
|
174
|
+
logger.error('onHeldForReview failed', { commentId: comment.id, error });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
113
178
|
/**
|
|
114
179
|
* Delete a comment. Only for an authenticated admin.
|
|
115
180
|
* @throws ActionError UNAUTHORIZED when not logged in, NOT_FOUND when there is no such comment
|
package/src/cli/bin.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { runCli } from './cli.js';
|
|
4
|
+
import { NodeProjectFiles } from './project-files.js';
|
|
5
|
+
import { TerminalLogger, TerminalPrompter } from './terminal.js';
|
|
6
|
+
|
|
7
|
+
// The package root is two folders up from both src/cli and the compiled dist/cli
|
|
8
|
+
const defaultConfigJson = readFileSync(new URL('../../default-respectify.config.json', import.meta.url), 'utf8');
|
|
9
|
+
|
|
10
|
+
process.exitCode = await runCli(process.argv.slice(2), {
|
|
11
|
+
logger: new TerminalLogger(),
|
|
12
|
+
prompter: new TerminalPrompter(),
|
|
13
|
+
openProject: (folder) => new NodeProjectFiles(folder),
|
|
14
|
+
defaultConfigJson,
|
|
15
|
+
});
|
package/src/cli/cli.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { InitError, runInit } from './init.js';
|
|
4
|
+
import { DATABASE_KINDS } from './types.js';
|
|
5
|
+
import type { ICliLogger, IPrompter, IProjectFiles, InitResult, InitStep, InitStepStatus } from './types.js';
|
|
6
|
+
|
|
7
|
+
export const USAGE = `Usage: npx @respectify/astro init [options]
|
|
8
|
+
|
|
9
|
+
Sets up Respectify comments in an Astro project: writes the runtime module, the config
|
|
10
|
+
file and the comment actions, and adds the comment table to your Drizzle schema.
|
|
11
|
+
Files that already exist are never overwritten.
|
|
12
|
+
|
|
13
|
+
Options:
|
|
14
|
+
--database <postgres|sqlite> The database your comments go in. Read from drizzle.config
|
|
15
|
+
when there is one, otherwise you are asked.
|
|
16
|
+
--cwd <folder> The project folder (default: the current folder)
|
|
17
|
+
-h, --help Show this help`;
|
|
18
|
+
|
|
19
|
+
const cliArgumentsSchema = z.object({
|
|
20
|
+
command: z.literal('init', { error: 'Unknown command. The only command is "init".' }),
|
|
21
|
+
database: z
|
|
22
|
+
.enum(DATABASE_KINDS, { error: `--database must be one of: ${DATABASE_KINDS.join(', ')}` })
|
|
23
|
+
.optional(),
|
|
24
|
+
cwd: z.string().min(1).default('.'),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** What the command needs from the outside world. */
|
|
28
|
+
export interface CliDependencies {
|
|
29
|
+
logger: ICliLogger;
|
|
30
|
+
prompter: IPrompter;
|
|
31
|
+
/** Opens the project in a folder. */
|
|
32
|
+
openProject: (folder: string) => IProjectFiles;
|
|
33
|
+
/** The text of the package's default-respectify.config.json. */
|
|
34
|
+
defaultConfigJson: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const STEP_LABELS: Record<InitStepStatus, string> = {
|
|
38
|
+
created: 'Created ',
|
|
39
|
+
updated: 'Updated ',
|
|
40
|
+
unchanged: 'Kept ',
|
|
41
|
+
manual: 'By hand ',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
function describeStep(step: InitStep): string {
|
|
45
|
+
const line = ` ${STEP_LABELS[step.status]} ${step.path}`;
|
|
46
|
+
return step.status === 'unchanged' ? `${line} (already there)` : line;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Say what was done, then what is left to do. */
|
|
50
|
+
function report(result: InitResult, logger: ICliLogger): void {
|
|
51
|
+
logger.info(`Respectify comments, stored in ${result.database === 'postgres' ? 'Postgres' : 'SQLite'}:\n`);
|
|
52
|
+
for (const step of result.steps) logger.info(describeStep(step));
|
|
53
|
+
|
|
54
|
+
const manualSteps = result.steps.flatMap((step) => (step.instructions === undefined ? [] : [step.instructions]));
|
|
55
|
+
const remaining = [...manualSteps, ...result.nextSteps];
|
|
56
|
+
logger.info('\nWhat is left to do:');
|
|
57
|
+
remaining.forEach((step, index) => {
|
|
58
|
+
logger.info(`\n${index + 1}. ${step}`);
|
|
59
|
+
});
|
|
60
|
+
logger.info('\nDocs: https://docs.respectify.ai/docs/astro');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Run the command line.
|
|
65
|
+
* @param argv the arguments after the program name
|
|
66
|
+
* @returns the process exit code
|
|
67
|
+
*/
|
|
68
|
+
export async function runCli(argv: readonly string[], dependencies: CliDependencies): Promise<number> {
|
|
69
|
+
const { logger, prompter, openProject, defaultConfigJson } = dependencies;
|
|
70
|
+
|
|
71
|
+
let parsed: ReturnType<typeof parseCommandLine>;
|
|
72
|
+
try {
|
|
73
|
+
parsed = parseCommandLine(argv);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
logger.error(error instanceof Error ? error.message : String(error));
|
|
76
|
+
logger.info(`\n${USAGE}`);
|
|
77
|
+
return 1;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (parsed.values.help === true || parsed.positionals.length === 0) {
|
|
81
|
+
logger.info(USAGE);
|
|
82
|
+
return parsed.values.help === true ? 0 : 1;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const validated = cliArgumentsSchema.safeParse({
|
|
86
|
+
command: parsed.positionals[0],
|
|
87
|
+
database: parsed.values.database,
|
|
88
|
+
cwd: parsed.values.cwd,
|
|
89
|
+
});
|
|
90
|
+
if (!validated.success) {
|
|
91
|
+
logger.error(validated.error.issues.map((issue) => issue.message).join('; '));
|
|
92
|
+
logger.info(`\n${USAGE}`);
|
|
93
|
+
return 1;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const result = await runInit(
|
|
98
|
+
{ database: validated.data.database },
|
|
99
|
+
{ files: openProject(validated.data.cwd), prompter, defaultConfigJson },
|
|
100
|
+
);
|
|
101
|
+
report(result, logger);
|
|
102
|
+
return 0;
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (!(error instanceof InitError)) throw error;
|
|
105
|
+
logger.error(error.message);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function parseCommandLine(argv: readonly string[]) {
|
|
111
|
+
return parseArgs({
|
|
112
|
+
args: [...argv],
|
|
113
|
+
allowPositionals: true,
|
|
114
|
+
options: {
|
|
115
|
+
database: { type: 'string' },
|
|
116
|
+
cwd: { type: 'string' },
|
|
117
|
+
help: { type: 'boolean', short: 'h' },
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
}
|