@hasna/microservices 0.0.7 → 0.0.9

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.
Files changed (23) hide show
  1. package/microservices/microservice-social/package.json +2 -1
  2. package/microservices/microservice-social/src/cli/index.ts +906 -12
  3. package/microservices/microservice-social/src/db/migrations.ts +72 -0
  4. package/microservices/microservice-social/src/db/social.ts +33 -3
  5. package/microservices/microservice-social/src/lib/audience.ts +353 -0
  6. package/microservices/microservice-social/src/lib/content-ai.ts +278 -0
  7. package/microservices/microservice-social/src/lib/media.ts +311 -0
  8. package/microservices/microservice-social/src/lib/mentions.ts +434 -0
  9. package/microservices/microservice-social/src/lib/metrics-sync.ts +264 -0
  10. package/microservices/microservice-social/src/lib/publisher.ts +377 -0
  11. package/microservices/microservice-social/src/lib/scheduler.ts +229 -0
  12. package/microservices/microservice-social/src/lib/sentiment.ts +256 -0
  13. package/microservices/microservice-social/src/lib/threads.ts +291 -0
  14. package/microservices/microservice-social/src/mcp/index.ts +776 -6
  15. package/microservices/microservice-social/src/server/index.ts +441 -0
  16. package/microservices/microservice-transcriber/src/cli/index.ts +247 -1
  17. package/microservices/microservice-transcriber/src/db/comments.ts +166 -0
  18. package/microservices/microservice-transcriber/src/db/migrations.ts +46 -0
  19. package/microservices/microservice-transcriber/src/db/proofread.ts +119 -0
  20. package/microservices/microservice-transcriber/src/lib/downloader.ts +68 -0
  21. package/microservices/microservice-transcriber/src/lib/proofread.ts +296 -0
  22. package/microservices/microservice-transcriber/src/mcp/index.ts +263 -3
  23. package/package.json +1 -1
@@ -38,6 +38,61 @@ import {
38
38
  type PostStatus,
39
39
  type Recurrence,
40
40
  } from "../db/social.js";
41
+ import {
42
+ startScheduler,
43
+ stopScheduler,
44
+ getSchedulerStatus,
45
+ } from "../lib/scheduler.js";
46
+ import {
47
+ syncAllMetrics,
48
+ syncAccountMetrics,
49
+ startMetricsSync,
50
+ stopMetricsSync,
51
+ getMetricsSyncStatus,
52
+ getSyncReport,
53
+ } from "../lib/metrics-sync.js";
54
+ import {
55
+ validateMedia,
56
+ getSupportedFormats,
57
+ uploadMedia,
58
+ } from "../lib/media.js";
59
+ import {
60
+ listMentions,
61
+ getMention,
62
+ markRead,
63
+ markAllRead,
64
+ getMentionStats,
65
+ replyToMention,
66
+ pollMentions,
67
+ stopPolling,
68
+ type MentionType,
69
+ } from "../lib/mentions.js";
70
+ import {
71
+ createThread,
72
+ getThread,
73
+ publishThread,
74
+ deleteThread,
75
+ createCarousel,
76
+ } from "../lib/threads.js";
77
+ import {
78
+ generatePost as aiGeneratePost,
79
+ suggestHashtags as aiSuggestHashtags,
80
+ optimizePost as aiOptimizePost,
81
+ generateThread as aiGenerateThread,
82
+ repurposePost as aiRepurposePost,
83
+ type Tone,
84
+ } from "../lib/content-ai.js";
85
+ import {
86
+ syncFollowers,
87
+ getAudienceInsights,
88
+ getFollowerGrowthChart,
89
+ getTopFollowers,
90
+ } from "../lib/audience.js";
91
+ import {
92
+ analyzeSentiment,
93
+ getSentimentReport,
94
+ autoAnalyzeMention,
95
+ } from "../lib/sentiment.js";
41
96
 
42
97
  const program = new Command();
43
98
 
@@ -181,21 +236,34 @@ postCmd
181
236
 
182
237
  postCmd
183
238
  .command("publish")
184
- .description("Mark a post as published")
239
+ .description("Publish a post — sends to the platform API if --live, otherwise marks as published locally")
185
240
  .argument("<id>", "Post ID")
186
- .option("--platform-id <id>", "Platform post ID")
241
+ .option("--platform-id <id>", "Platform post ID (for manual/local publish)")
242
+ .option("--live", "Publish via platform API (X, Meta)", false)
187
243
  .option("--json", "Output as JSON", false)
188
- .action((id, opts) => {
189
- const post = publishPost(id, opts.platformId);
190
- if (!post) {
191
- console.error(`Post '${id}' not found.`);
192
- process.exit(1);
193
- }
244
+ .action(async (id, opts) => {
245
+ try {
246
+ let post;
247
+ if (opts.live) {
248
+ const { publishToApi } = await import("../lib/publisher.js");
249
+ post = await publishToApi(id);
250
+ } else {
251
+ post = publishPost(id, opts.platformId);
252
+ }
194
253
 
195
- if (opts.json) {
196
- console.log(JSON.stringify(post, null, 2));
197
- } else {
198
- console.log(`Published post ${post.id} at ${post.published_at}`);
254
+ if (!post) {
255
+ console.error(`Post '${id}' not found.`);
256
+ process.exit(1);
257
+ }
258
+
259
+ if (opts.json) {
260
+ console.log(JSON.stringify(post, null, 2));
261
+ } else {
262
+ console.log(`Published post ${post.id} at ${post.published_at}${post.platform_post_id ? ` (platform ID: ${post.platform_post_id})` : ""}`);
263
+ }
264
+ } catch (err) {
265
+ console.error(err instanceof Error ? err.message : String(err));
266
+ process.exit(1);
199
267
  }
200
268
  });
201
269
 
@@ -365,6 +433,124 @@ postCmd
365
433
  }
366
434
  });
367
435
 
436
+ postCmd
437
+ .command("create-thread")
438
+ .description("Create a thread of multiple posts")
439
+ .requiredOption("--content <texts...>", "Content for each post in the thread")
440
+ .requiredOption("--account <id>", "Account ID")
441
+ .option("--schedule <datetime>", "Schedule date/time")
442
+ .option("--tags <tags>", "Comma-separated tags")
443
+ .option("--json", "Output as JSON", false)
444
+ .action((opts) => {
445
+ try {
446
+ const result = createThread(opts.content, opts.account, {
447
+ scheduledAt: opts.schedule,
448
+ tags: opts.tags ? opts.tags.split(",").map((t: string) => t.trim()) : undefined,
449
+ });
450
+
451
+ if (opts.json) {
452
+ console.log(JSON.stringify(result, null, 2));
453
+ } else {
454
+ console.log(`Created thread ${result.threadId} with ${result.posts.length} post(s)`);
455
+ for (const post of result.posts) {
456
+ const preview = post.content.substring(0, 60) + (post.content.length > 60 ? "..." : "");
457
+ console.log(` [${post.thread_position}] ${preview}`);
458
+ }
459
+ }
460
+ } catch (err) {
461
+ console.error(err instanceof Error ? err.message : String(err));
462
+ process.exit(1);
463
+ }
464
+ });
465
+
466
+ postCmd
467
+ .command("get-thread")
468
+ .description("Get all posts in a thread")
469
+ .argument("<thread-id>", "Thread ID")
470
+ .option("--json", "Output as JSON", false)
471
+ .action((threadId, opts) => {
472
+ try {
473
+ const posts = getThread(threadId);
474
+
475
+ if (opts.json) {
476
+ console.log(JSON.stringify({ threadId, posts, count: posts.length }, null, 2));
477
+ } else {
478
+ console.log(`Thread ${threadId} (${posts.length} post(s)):`);
479
+ for (const post of posts) {
480
+ const preview = post.content.substring(0, 60) + (post.content.length > 60 ? "..." : "");
481
+ console.log(` [${post.thread_position}] [${post.status}] ${preview}`);
482
+ }
483
+ }
484
+ } catch (err) {
485
+ console.error(err instanceof Error ? err.message : String(err));
486
+ process.exit(1);
487
+ }
488
+ });
489
+
490
+ postCmd
491
+ .command("publish-thread")
492
+ .description("Publish a thread to the platform API")
493
+ .argument("<thread-id>", "Thread ID")
494
+ .option("--live", "Publish via platform API", false)
495
+ .option("--json", "Output as JSON", false)
496
+ .action(async (threadId, opts) => {
497
+ try {
498
+ if (opts.live) {
499
+ const result = await publishThread(threadId);
500
+
501
+ if (opts.json) {
502
+ console.log(JSON.stringify(result, null, 2));
503
+ } else {
504
+ console.log(`Published thread ${result.threadId} (${result.posts.length} post(s))`);
505
+ for (const post of result.posts) {
506
+ console.log(` [${post.thread_position}] platform ID: ${post.platform_post_id}`);
507
+ }
508
+ }
509
+ } else {
510
+ // Local publish — mark all posts as published
511
+ const posts = getThread(threadId);
512
+ for (const post of posts) {
513
+ publishPost(post.id);
514
+ }
515
+ if (opts.json) {
516
+ const updated = getThread(threadId);
517
+ console.log(JSON.stringify({ threadId, posts: updated }, null, 2));
518
+ } else {
519
+ console.log(`Locally published thread ${threadId} (${posts.length} post(s))`);
520
+ }
521
+ }
522
+ } catch (err) {
523
+ console.error(err instanceof Error ? err.message : String(err));
524
+ process.exit(1);
525
+ }
526
+ });
527
+
528
+ postCmd
529
+ .command("create-carousel")
530
+ .description("Create a carousel post with multiple images")
531
+ .requiredOption("--images <urls>", "Comma-separated image URLs")
532
+ .requiredOption("--account <id>", "Account ID")
533
+ .option("--captions <texts>", "Comma-separated captions")
534
+ .option("--json", "Output as JSON", false)
535
+ .action((opts) => {
536
+ try {
537
+ const images = opts.images.split(",").map((u: string) => u.trim());
538
+ const captions = opts.captions ? opts.captions.split(",").map((c: string) => c.trim()) : [];
539
+ const post = createCarousel(images, captions, opts.account);
540
+
541
+ if (opts.json) {
542
+ console.log(JSON.stringify(post, null, 2));
543
+ } else {
544
+ console.log(`Created carousel post: ${post.id}`);
545
+ console.log(` Images: ${post.media_urls.length}`);
546
+ if (post.content) console.log(` Content: ${post.content.substring(0, 80)}${post.content.length > 80 ? "..." : ""}`);
547
+ }
548
+ } catch (err) {
549
+ console.error(err instanceof Error ? err.message : String(err));
550
+ process.exit(1);
551
+ }
552
+ });
553
+
368
554
  // --- Accounts ---
369
555
 
370
556
  const accountCmd = program
@@ -686,4 +872,712 @@ program
686
872
  }
687
873
  });
688
874
 
875
+ // --- Scheduler ---
876
+
877
+ const schedulerCmd = program
878
+ .command("scheduler")
879
+ .description("Scheduled post publishing worker");
880
+
881
+ schedulerCmd
882
+ .command("start")
883
+ .description("Start the scheduler to auto-publish due posts")
884
+ .option("--interval <ms>", "Check interval in milliseconds", "60000")
885
+ .action((opts) => {
886
+ try {
887
+ const interval = parseInt(opts.interval);
888
+ startScheduler(interval);
889
+ console.log(`Scheduler started (interval: ${interval}ms)`);
890
+ console.log("Press Ctrl+C to stop.");
891
+ // Keep process alive
892
+ process.on("SIGINT", () => {
893
+ stopScheduler();
894
+ console.log("\nScheduler stopped.");
895
+ process.exit(0);
896
+ });
897
+ } catch (err) {
898
+ console.error(err instanceof Error ? err.message : String(err));
899
+ process.exit(1);
900
+ }
901
+ });
902
+
903
+ schedulerCmd
904
+ .command("status")
905
+ .description("Show scheduler status")
906
+ .option("--json", "Output as JSON", false)
907
+ .action((opts) => {
908
+ const status = getSchedulerStatus();
909
+
910
+ if (opts.json) {
911
+ console.log(JSON.stringify(status, null, 2));
912
+ } else {
913
+ console.log("Scheduler Status:");
914
+ console.log(` Running: ${status.running}`);
915
+ console.log(` Last check: ${status.lastCheck || "never"}`);
916
+ console.log(` Posts processed: ${status.postsProcessed}`);
917
+ console.log(` Errors: ${status.errors}`);
918
+ }
919
+ });
920
+
921
+ schedulerCmd
922
+ .command("stop")
923
+ .description("Stop the scheduler")
924
+ .action(() => {
925
+ stopScheduler();
926
+ console.log("Scheduler stopped.");
927
+ });
928
+
929
+ // --- Media ---
930
+
931
+ const mediaCmd = program
932
+ .command("media")
933
+ .description("Media upload and validation");
934
+
935
+ mediaCmd
936
+ .command("upload")
937
+ .description("Upload a media file to a platform")
938
+ .argument("<file>", "Path to media file")
939
+ .requiredOption("--platform <platform>", "Target platform (x/linkedin/instagram/threads/bluesky)")
940
+ .option("--page-id <id>", "Page ID (required for Meta/LinkedIn)")
941
+ .option("--json", "Output as JSON", false)
942
+ .action(async (file, opts) => {
943
+ const platform = opts.platform as Platform;
944
+
945
+ // Validate first
946
+ const validation = validateMedia(file, platform);
947
+ if (!validation.valid) {
948
+ console.error("Validation errors:");
949
+ for (const err of validation.errors) {
950
+ console.error(` - ${err}`);
951
+ }
952
+ process.exit(1);
953
+ }
954
+
955
+ try {
956
+ const result = await uploadMedia(file, platform, opts.pageId);
957
+
958
+ if (opts.json) {
959
+ console.log(JSON.stringify(result, null, 2));
960
+ } else {
961
+ console.log(`Uploaded successfully. Media ID: ${result.mediaId}`);
962
+ if (result.url) console.log(` URL: ${result.url}`);
963
+ }
964
+ } catch (err) {
965
+ console.error(err instanceof Error ? err.message : String(err));
966
+ process.exit(1);
967
+ }
968
+ });
969
+
970
+ mediaCmd
971
+ .command("formats")
972
+ .description("Show supported media formats for a platform")
973
+ .requiredOption("--platform <platform>", "Platform (x/linkedin/instagram/threads/bluesky)")
974
+ .option("--json", "Output as JSON", false)
975
+ .action((opts) => {
976
+ const platform = opts.platform as Platform;
977
+ const formats = getSupportedFormats(platform);
978
+
979
+ if (opts.json) {
980
+ console.log(JSON.stringify({ platform, formats }, null, 2));
981
+ } else {
982
+ console.log(`Supported formats for ${platform}: ${formats.join(", ")}`);
983
+ }
984
+ });
985
+
986
+ mediaCmd
987
+ .command("validate")
988
+ .description("Validate a media file for a platform")
989
+ .argument("<file>", "Path to media file")
990
+ .requiredOption("--platform <platform>", "Target platform")
991
+ .option("--json", "Output as JSON", false)
992
+ .action((file, opts) => {
993
+ const platform = opts.platform as Platform;
994
+ const result = validateMedia(file, platform);
995
+
996
+ if (opts.json) {
997
+ console.log(JSON.stringify(result, null, 2));
998
+ } else {
999
+ if (result.valid) {
1000
+ console.log(`File '${file}' is valid for ${platform}.`);
1001
+ } else {
1002
+ console.error(`File '${file}' is NOT valid for ${platform}:`);
1003
+ for (const err of result.errors) {
1004
+ console.error(` - ${err}`);
1005
+ }
1006
+ process.exit(1);
1007
+ }
1008
+ }
1009
+ });
1010
+
1011
+ // --- Metrics Sync ---
1012
+
1013
+ const metricsCmd = program
1014
+ .command("metrics")
1015
+ .description("Metrics sync — pull engagement data from platform APIs");
1016
+
1017
+ metricsCmd
1018
+ .command("sync")
1019
+ .description("Sync metrics for recent published posts")
1020
+ .option("--watch", "Continuously sync on an interval", false)
1021
+ .option("--interval <ms>", "Sync interval in milliseconds (with --watch)", "300000")
1022
+ .option("--json", "Output as JSON", false)
1023
+ .action(async (opts) => {
1024
+ if (opts.watch) {
1025
+ const interval = parseInt(opts.interval);
1026
+ try {
1027
+ startMetricsSync(interval);
1028
+ console.log(`Metrics sync started (interval: ${interval}ms)`);
1029
+ console.log("Press Ctrl+C to stop.");
1030
+ process.on("SIGINT", () => {
1031
+ stopMetricsSync();
1032
+ const report = getSyncReport();
1033
+ console.log(`\nMetrics sync stopped. Posts synced: ${report.posts_synced}, Errors: ${report.errors.length}`);
1034
+ process.exit(0);
1035
+ });
1036
+ } catch (err) {
1037
+ console.error(err instanceof Error ? err.message : String(err));
1038
+ process.exit(1);
1039
+ }
1040
+ } else {
1041
+ try {
1042
+ const report = await syncAllMetrics();
1043
+
1044
+ if (opts.json) {
1045
+ console.log(JSON.stringify(report, null, 2));
1046
+ } else {
1047
+ console.log(`Metrics sync complete:`);
1048
+ console.log(` Posts synced: ${report.posts_synced}`);
1049
+ console.log(` Accounts synced: ${report.accounts_synced}`);
1050
+ if (report.errors.length > 0) {
1051
+ console.log(` Errors: ${report.errors.length}`);
1052
+ for (const err of report.errors) {
1053
+ console.log(` [${err.type}] ${err.id}: ${err.message}`);
1054
+ }
1055
+ }
1056
+ }
1057
+ } catch (err) {
1058
+ console.error(err instanceof Error ? err.message : String(err));
1059
+ process.exit(1);
1060
+ }
1061
+ }
1062
+ });
1063
+
1064
+ metricsCmd
1065
+ .command("status")
1066
+ .description("Show metrics sync status")
1067
+ .option("--json", "Output as JSON", false)
1068
+ .action((opts) => {
1069
+ const status = getMetricsSyncStatus();
1070
+
1071
+ if (opts.json) {
1072
+ console.log(JSON.stringify(status, null, 2));
1073
+ } else {
1074
+ console.log("Metrics Sync Status:");
1075
+ console.log(` Running: ${status.running}`);
1076
+ console.log(` Interval: ${status.interval_ms}ms`);
1077
+ console.log(` Last sync: ${status.last_sync || "never"}`);
1078
+ console.log(` Posts synced: ${status.posts_synced}`);
1079
+ console.log(` Accounts synced: ${status.accounts_synced}`);
1080
+ console.log(` Errors: ${status.errors}`);
1081
+ }
1082
+ });
1083
+
1084
+ // --- Mentions ---
1085
+
1086
+ const mentionsCmd = program
1087
+ .command("mentions")
1088
+ .description("Mention monitoring");
1089
+
1090
+ mentionsCmd
1091
+ .command("list")
1092
+ .description("List mentions")
1093
+ .option("--account <id>", "Filter by account ID")
1094
+ .option("--unread", "Show only unread mentions", false)
1095
+ .option("--type <type>", "Filter by type (mention/reply/quote/dm)")
1096
+ .option("--limit <n>", "Limit results")
1097
+ .option("--json", "Output as JSON", false)
1098
+ .action((opts) => {
1099
+ const mentions = listMentions(opts.account, {
1100
+ unread: opts.unread ? true : undefined,
1101
+ type: opts.type as MentionType | undefined,
1102
+ limit: opts.limit ? parseInt(opts.limit) : undefined,
1103
+ });
1104
+
1105
+ if (opts.json) {
1106
+ console.log(JSON.stringify(mentions, null, 2));
1107
+ } else {
1108
+ if (mentions.length === 0) {
1109
+ console.log("No mentions found.");
1110
+ return;
1111
+ }
1112
+ for (const m of mentions) {
1113
+ const readFlag = m.read ? " " : "*";
1114
+ const preview = m.content ? m.content.substring(0, 60) + (m.content.length > 60 ? "..." : "") : "(no content)";
1115
+ const author = m.author_handle ? `@${m.author_handle}` : m.author || "unknown";
1116
+ console.log(` ${readFlag} [${m.type || "?"}] ${author}: ${preview}`);
1117
+ }
1118
+ console.log(`\n${mentions.length} mention(s)`);
1119
+ }
1120
+ });
1121
+
1122
+ mentionsCmd
1123
+ .command("reply")
1124
+ .description("Reply to a mention")
1125
+ .argument("<id>", "Mention ID")
1126
+ .requiredOption("--content <text>", "Reply content")
1127
+ .option("--json", "Output as JSON", false)
1128
+ .action(async (id, opts) => {
1129
+ try {
1130
+ const result = await replyToMention(id, opts.content);
1131
+ if (opts.json) {
1132
+ console.log(JSON.stringify(result, null, 2));
1133
+ } else {
1134
+ console.log(`Reply sent. Platform reply ID: ${result.platformReplyId}`);
1135
+ }
1136
+ } catch (err) {
1137
+ console.error(err instanceof Error ? err.message : String(err));
1138
+ process.exit(1);
1139
+ }
1140
+ });
1141
+
1142
+ mentionsCmd
1143
+ .command("read")
1144
+ .description("Mark a mention as read")
1145
+ .argument("<id>", "Mention ID")
1146
+ .option("--json", "Output as JSON", false)
1147
+ .action((id, opts) => {
1148
+ const mention = markRead(id);
1149
+ if (!mention) {
1150
+ console.error(`Mention '${id}' not found.`);
1151
+ process.exit(1);
1152
+ }
1153
+ if (opts.json) {
1154
+ console.log(JSON.stringify(mention, null, 2));
1155
+ } else {
1156
+ console.log(`Marked mention ${id} as read.`);
1157
+ }
1158
+ });
1159
+
1160
+ mentionsCmd
1161
+ .command("read-all")
1162
+ .description("Mark all mentions for an account as read")
1163
+ .argument("<account-id>", "Account ID")
1164
+ .action((accountId) => {
1165
+ const count = markAllRead(accountId);
1166
+ console.log(`Marked ${count} mention(s) as read.`);
1167
+ });
1168
+
1169
+ mentionsCmd
1170
+ .command("watch")
1171
+ .description("Start polling for new mentions")
1172
+ .option("--interval <ms>", "Poll interval in milliseconds", "120000")
1173
+ .action((opts) => {
1174
+ const interval = parseInt(opts.interval);
1175
+ pollMentions(interval);
1176
+ console.log(`Mention poller started (interval: ${interval}ms)`);
1177
+ console.log("Press Ctrl+C to stop.");
1178
+ process.on("SIGINT", () => {
1179
+ stopPolling();
1180
+ console.log("\nMention poller stopped.");
1181
+ process.exit(0);
1182
+ });
1183
+ });
1184
+
1185
+ mentionsCmd
1186
+ .command("stats")
1187
+ .description("Get mention statistics for an account")
1188
+ .argument("<account-id>", "Account ID")
1189
+ .option("--json", "Output as JSON", false)
1190
+ .action((accountId, opts) => {
1191
+ const stats = getMentionStats(accountId);
1192
+ if (opts.json) {
1193
+ console.log(JSON.stringify(stats, null, 2));
1194
+ } else {
1195
+ console.log("Mention Stats:");
1196
+ console.log(` Total: ${stats.total}`);
1197
+ console.log(` Unread: ${stats.unread}`);
1198
+ if (Object.keys(stats.by_type).length) {
1199
+ console.log(" By type:");
1200
+ for (const [type, count] of Object.entries(stats.by_type)) {
1201
+ console.log(` ${type}: ${count}`);
1202
+ }
1203
+ }
1204
+ if (Object.keys(stats.by_sentiment).length) {
1205
+ console.log(" By sentiment:");
1206
+ for (const [sentiment, count] of Object.entries(stats.by_sentiment)) {
1207
+ console.log(` ${sentiment}: ${count}`);
1208
+ }
1209
+ }
1210
+ }
1211
+ });
1212
+
1213
+ // --- AI Content Generation ---
1214
+
1215
+ const aiCmd = program
1216
+ .command("ai")
1217
+ .description("AI-powered content generation");
1218
+
1219
+ aiCmd
1220
+ .command("generate")
1221
+ .description("Generate a post using AI")
1222
+ .requiredOption("--topic <topic>", "Topic to write about")
1223
+ .requiredOption("--platform <platform>", "Target platform (x/linkedin/instagram/threads/bluesky)")
1224
+ .option("--tone <tone>", "Tone: professional, casual, witty", "professional")
1225
+ .option("--no-hashtags", "Disable hashtags")
1226
+ .option("--emoji", "Include emojis", false)
1227
+ .option("--language <lang>", "Language", "English")
1228
+ .option("--json", "Output as JSON", false)
1229
+ .action(async (opts) => {
1230
+ try {
1231
+ const result = await aiGeneratePost(opts.topic, opts.platform as Platform, {
1232
+ tone: opts.tone as Tone,
1233
+ includeHashtags: opts.hashtags,
1234
+ includeEmoji: opts.emoji,
1235
+ language: opts.language,
1236
+ });
1237
+
1238
+ if (opts.json) {
1239
+ console.log(JSON.stringify(result, null, 2));
1240
+ } else {
1241
+ console.log("Generated Post:");
1242
+ console.log(` ${result.content}`);
1243
+ if (result.hashtags.length) {
1244
+ console.log(` Hashtags: ${result.hashtags.map((h: string) => "#" + h).join(" ")}`);
1245
+ }
1246
+ if (result.suggested_media_prompt) {
1247
+ console.log(` Media prompt: ${result.suggested_media_prompt}`);
1248
+ }
1249
+ }
1250
+ } catch (err) {
1251
+ console.error(err instanceof Error ? err.message : String(err));
1252
+ process.exit(1);
1253
+ }
1254
+ });
1255
+
1256
+ aiCmd
1257
+ .command("suggest-hashtags")
1258
+ .description("Suggest hashtags for content")
1259
+ .requiredOption("--content <text>", "Post content to analyze")
1260
+ .requiredOption("--platform <platform>", "Target platform")
1261
+ .option("--count <n>", "Number of hashtags", "5")
1262
+ .option("--json", "Output as JSON", false)
1263
+ .action(async (opts) => {
1264
+ try {
1265
+ const hashtags = await aiSuggestHashtags(opts.content, opts.platform as Platform, parseInt(opts.count));
1266
+
1267
+ if (opts.json) {
1268
+ console.log(JSON.stringify({ hashtags }, null, 2));
1269
+ } else {
1270
+ console.log("Suggested Hashtags:");
1271
+ for (const h of hashtags) {
1272
+ console.log(` #${h}`);
1273
+ }
1274
+ }
1275
+ } catch (err) {
1276
+ console.error(err instanceof Error ? err.message : String(err));
1277
+ process.exit(1);
1278
+ }
1279
+ });
1280
+
1281
+ aiCmd
1282
+ .command("optimize")
1283
+ .description("Optimize a post for better engagement")
1284
+ .argument("<post-id>", "Post ID to optimize")
1285
+ .option("--json", "Output as JSON", false)
1286
+ .action(async (postId, opts) => {
1287
+ try {
1288
+ const post = getPost(postId);
1289
+ if (!post) {
1290
+ console.error(`Post '${postId}' not found.`);
1291
+ process.exit(1);
1292
+ }
1293
+
1294
+ const account = getAccount(post.account_id);
1295
+ if (!account) {
1296
+ console.error(`Account '${post.account_id}' not found.`);
1297
+ process.exit(1);
1298
+ }
1299
+
1300
+ const result = await aiOptimizePost(post.content, account.platform);
1301
+
1302
+ if (opts.json) {
1303
+ console.log(JSON.stringify(result, null, 2));
1304
+ } else {
1305
+ console.log("Optimized Post:");
1306
+ console.log(` ${result.optimized_content}`);
1307
+ if (result.improvements.length) {
1308
+ console.log("\nImprovements:");
1309
+ for (const imp of result.improvements) {
1310
+ console.log(` - ${imp}`);
1311
+ }
1312
+ }
1313
+ }
1314
+ } catch (err) {
1315
+ console.error(err instanceof Error ? err.message : String(err));
1316
+ process.exit(1);
1317
+ }
1318
+ });
1319
+
1320
+ aiCmd
1321
+ .command("generate-thread")
1322
+ .description("Generate a multi-tweet thread using AI")
1323
+ .requiredOption("--topic <topic>", "Topic to write about")
1324
+ .option("--tweets <n>", "Number of tweets in thread", "5")
1325
+ .option("--json", "Output as JSON", false)
1326
+ .action(async (opts) => {
1327
+ try {
1328
+ const tweets = await aiGenerateThread(opts.topic, parseInt(opts.tweets));
1329
+
1330
+ if (opts.json) {
1331
+ console.log(JSON.stringify({ tweets }, null, 2));
1332
+ } else {
1333
+ console.log("Generated Thread:");
1334
+ for (let i = 0; i < tweets.length; i++) {
1335
+ console.log(`\n [${i + 1}/${tweets.length}] ${tweets[i]}`);
1336
+ }
1337
+ }
1338
+ } catch (err) {
1339
+ console.error(err instanceof Error ? err.message : String(err));
1340
+ process.exit(1);
1341
+ }
1342
+ });
1343
+
1344
+ aiCmd
1345
+ .command("repurpose")
1346
+ .description("Repurpose a post for a different platform")
1347
+ .argument("<post-id>", "Post ID to repurpose")
1348
+ .requiredOption("--to <platform>", "Target platform (x/linkedin/instagram/threads/bluesky)")
1349
+ .option("--json", "Output as JSON", false)
1350
+ .action(async (postId, opts) => {
1351
+ try {
1352
+ const post = getPost(postId);
1353
+ if (!post) {
1354
+ console.error(`Post '${postId}' not found.`);
1355
+ process.exit(1);
1356
+ }
1357
+
1358
+ const account = getAccount(post.account_id);
1359
+ if (!account) {
1360
+ console.error(`Account '${post.account_id}' not found.`);
1361
+ process.exit(1);
1362
+ }
1363
+
1364
+ const result = await aiRepurposePost(post.content, account.platform, opts.to as Platform);
1365
+
1366
+ if (opts.json) {
1367
+ console.log(JSON.stringify(result, null, 2));
1368
+ } else {
1369
+ console.log(`Repurposed for ${opts.to}:`);
1370
+ console.log(` ${result.content}`);
1371
+ }
1372
+ } catch (err) {
1373
+ console.error(err instanceof Error ? err.message : String(err));
1374
+ process.exit(1);
1375
+ }
1376
+ });
1377
+
1378
+ // --- Audience ---
1379
+
1380
+ const audienceCmd = program
1381
+ .command("audience")
1382
+ .description("Follower sync and audience insights");
1383
+
1384
+ audienceCmd
1385
+ .command("sync")
1386
+ .description("Sync followers from the platform API")
1387
+ .argument("<account-id>", "Account ID")
1388
+ .option("--json", "Output as JSON", false)
1389
+ .action((accountId, opts) => {
1390
+ const result = syncFollowers(accountId);
1391
+
1392
+ if (opts.json) {
1393
+ console.log(JSON.stringify(result, null, 2));
1394
+ } else {
1395
+ console.log(`Follower sync complete:`);
1396
+ console.log(` Synced: ${result.synced}`);
1397
+ console.log(` New: ${result.new_followers}`);
1398
+ console.log(` Unfollowed: ${result.unfollowed}`);
1399
+ if (result.message) console.log(` Note: ${result.message}`);
1400
+ }
1401
+ });
1402
+
1403
+ audienceCmd
1404
+ .command("insights")
1405
+ .description("Get audience insights for an account")
1406
+ .argument("<account-id>", "Account ID")
1407
+ .option("--json", "Output as JSON", false)
1408
+ .action((accountId, opts) => {
1409
+ const insights = getAudienceInsights(accountId);
1410
+
1411
+ if (opts.json) {
1412
+ console.log(JSON.stringify(insights, null, 2));
1413
+ } else {
1414
+ console.log("Audience Insights:");
1415
+ console.log(` Total followers: ${insights.total_followers}`);
1416
+ console.log(` Growth (7d): ${insights.growth_rate_7d}%`);
1417
+ console.log(` Growth (30d): ${insights.growth_rate_30d}%`);
1418
+ console.log(` New followers (7d): ${insights.new_followers_7d}`);
1419
+ console.log(` Lost followers (7d): ${insights.lost_followers_7d}`);
1420
+ if (insights.top_followers.length > 0) {
1421
+ console.log(" Top followers:");
1422
+ for (const f of insights.top_followers.slice(0, 5)) {
1423
+ console.log(` @${f.username || "?"} — ${f.follower_count} followers`);
1424
+ }
1425
+ }
1426
+ }
1427
+ });
1428
+
1429
+ audienceCmd
1430
+ .command("growth")
1431
+ .description("Show follower growth chart data")
1432
+ .argument("<account-id>", "Account ID")
1433
+ .option("--days <n>", "Number of days", "30")
1434
+ .option("--json", "Output as JSON", false)
1435
+ .action((accountId, opts) => {
1436
+ const days = parseInt(opts.days);
1437
+ const chart = getFollowerGrowthChart(accountId, days);
1438
+
1439
+ if (opts.json) {
1440
+ console.log(JSON.stringify(chart, null, 2));
1441
+ } else {
1442
+ if (chart.length === 0) {
1443
+ console.log("No snapshot data available.");
1444
+ return;
1445
+ }
1446
+ console.log(`Follower Growth (last ${days} days):`);
1447
+ for (const point of chart) {
1448
+ console.log(` ${point.date}: ${point.count}`);
1449
+ }
1450
+ }
1451
+ });
1452
+
1453
+ audienceCmd
1454
+ .command("top")
1455
+ .description("Show top followers by their follower count")
1456
+ .argument("<account-id>", "Account ID")
1457
+ .option("--limit <n>", "Number of results", "10")
1458
+ .option("--json", "Output as JSON", false)
1459
+ .action((accountId, opts) => {
1460
+ const limit = parseInt(opts.limit);
1461
+ const followers = getTopFollowers(accountId, limit);
1462
+
1463
+ if (opts.json) {
1464
+ console.log(JSON.stringify(followers, null, 2));
1465
+ } else {
1466
+ if (followers.length === 0) {
1467
+ console.log("No followers found.");
1468
+ return;
1469
+ }
1470
+ console.log("Top Followers:");
1471
+ for (const f of followers) {
1472
+ const name = f.display_name ? ` (${f.display_name})` : "";
1473
+ console.log(` @${f.username || "?"}${name} — ${f.follower_count} followers`);
1474
+ }
1475
+ }
1476
+ });
1477
+
1478
+ // --- Sentiment ---
1479
+
1480
+ const sentimentCmd = program
1481
+ .command("sentiment")
1482
+ .description("Sentiment analysis for mentions");
1483
+
1484
+ sentimentCmd
1485
+ .command("analyze")
1486
+ .description("Analyze sentiment of a text")
1487
+ .requiredOption("--text <text>", "Text to analyze")
1488
+ .option("--json", "Output as JSON", false)
1489
+ .action(async (opts) => {
1490
+ try {
1491
+ const result = await analyzeSentiment(opts.text);
1492
+ if (opts.json) {
1493
+ console.log(JSON.stringify(result, null, 2));
1494
+ } else {
1495
+ console.log(`Sentiment: ${result.sentiment}`);
1496
+ console.log(`Score: ${result.score}`);
1497
+ if (result.keywords.length) {
1498
+ console.log(`Keywords: ${result.keywords.join(", ")}`);
1499
+ }
1500
+ }
1501
+ } catch (err) {
1502
+ console.error(err instanceof Error ? err.message : String(err));
1503
+ process.exit(1);
1504
+ }
1505
+ });
1506
+
1507
+ sentimentCmd
1508
+ .command("report")
1509
+ .description("Get sentiment report for an account")
1510
+ .argument("<account-id>", "Account ID")
1511
+ .option("--days <n>", "Number of days to analyze", "30")
1512
+ .option("--json", "Output as JSON", false)
1513
+ .action((accountId, opts) => {
1514
+ const days = parseInt(opts.days);
1515
+ const report = getSentimentReport(accountId, days);
1516
+
1517
+ if (opts.json) {
1518
+ console.log(JSON.stringify(report, null, 2));
1519
+ } else {
1520
+ if (report.total_analyzed === 0) {
1521
+ console.log("No analyzed mentions found.");
1522
+ return;
1523
+ }
1524
+ console.log(`Sentiment Report (last ${days} days):`);
1525
+ console.log(` Total analyzed: ${report.total_analyzed}`);
1526
+ console.log(` Positive: ${report.positive_pct}%`);
1527
+ console.log(` Neutral: ${report.neutral_pct}%`);
1528
+ console.log(` Negative: ${report.negative_pct}%`);
1529
+ if (report.trending_keywords.length) {
1530
+ console.log(` Trending keywords: ${report.trending_keywords.join(", ")}`);
1531
+ }
1532
+ if (report.most_positive) {
1533
+ const preview = report.most_positive.content.substring(0, 60);
1534
+ console.log(` Most positive: ${preview}${report.most_positive.content.length > 60 ? "..." : ""}`);
1535
+ }
1536
+ if (report.most_negative) {
1537
+ const preview = report.most_negative.content.substring(0, 60);
1538
+ console.log(` Most negative: ${preview}${report.most_negative.content.length > 60 ? "..." : ""}`);
1539
+ }
1540
+ }
1541
+ });
1542
+
1543
+ sentimentCmd
1544
+ .command("auto")
1545
+ .description("Auto-analyze sentiment for a mention")
1546
+ .argument("<mention-id>", "Mention ID")
1547
+ .option("--json", "Output as JSON", false)
1548
+ .action(async (mentionId, opts) => {
1549
+ try {
1550
+ const result = await autoAnalyzeMention(mentionId);
1551
+ if (!result) {
1552
+ console.error("Analysis returned no result.");
1553
+ process.exit(1);
1554
+ }
1555
+
1556
+ if (opts.json) {
1557
+ console.log(JSON.stringify(result, null, 2));
1558
+ } else {
1559
+ console.log(`Analyzed mention ${mentionId}:`);
1560
+ console.log(` Sentiment: ${result.sentiment}`);
1561
+ console.log(` Score: ${result.score}`);
1562
+ if (result.keywords.length) {
1563
+ console.log(` Keywords: ${result.keywords.join(", ")}`);
1564
+ }
1565
+ }
1566
+ } catch (err) {
1567
+ console.error(err instanceof Error ? err.message : String(err));
1568
+ process.exit(1);
1569
+ }
1570
+ });
1571
+
1572
+ // --- Serve ---
1573
+
1574
+ program
1575
+ .command("serve")
1576
+ .description("Start REST API server with web dashboard")
1577
+ .option("--port <port>", "Port to listen on", "19650")
1578
+ .action(async (opts) => {
1579
+ process.env["PORT"] = opts.port;
1580
+ await import("../server/index.js");
1581
+ });
1582
+
689
1583
  program.parse(process.argv);