@hasna/microservices 0.0.7 → 0.0.8
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/microservices/microservice-social/package.json +2 -1
- package/microservices/microservice-social/src/cli/index.ts +906 -12
- package/microservices/microservice-social/src/db/migrations.ts +72 -0
- package/microservices/microservice-social/src/db/social.ts +33 -3
- package/microservices/microservice-social/src/lib/audience.ts +353 -0
- package/microservices/microservice-social/src/lib/content-ai.ts +278 -0
- package/microservices/microservice-social/src/lib/media.ts +311 -0
- package/microservices/microservice-social/src/lib/mentions.ts +434 -0
- package/microservices/microservice-social/src/lib/metrics-sync.ts +264 -0
- package/microservices/microservice-social/src/lib/publisher.ts +377 -0
- package/microservices/microservice-social/src/lib/scheduler.ts +229 -0
- package/microservices/microservice-social/src/lib/sentiment.ts +256 -0
- package/microservices/microservice-social/src/lib/threads.ts +291 -0
- package/microservices/microservice-social/src/mcp/index.ts +776 -6
- package/microservices/microservice-social/src/server/index.ts +441 -0
- package/package.json +1 -1
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sentiment analysis for social media mentions.
|
|
3
|
+
* Uses OpenAI (gpt-4o-mini) or Anthropic (claude-haiku) to classify text sentiment,
|
|
4
|
+
* extract emotional keywords, and generate aggregated sentiment reports.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { getDatabase } from "../db/database.js";
|
|
8
|
+
import { getMention, type Mention } from "./mentions.js";
|
|
9
|
+
import {
|
|
10
|
+
callOpenAI,
|
|
11
|
+
callAnthropic,
|
|
12
|
+
getDefaultAIProvider,
|
|
13
|
+
type AIProvider,
|
|
14
|
+
} from "./content-ai.js";
|
|
15
|
+
|
|
16
|
+
// ---- Types ----
|
|
17
|
+
|
|
18
|
+
export type SentimentLabel = "positive" | "neutral" | "negative";
|
|
19
|
+
|
|
20
|
+
export interface SentimentResult {
|
|
21
|
+
sentiment: SentimentLabel;
|
|
22
|
+
score: number;
|
|
23
|
+
keywords: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SentimentReport {
|
|
27
|
+
positive_pct: number;
|
|
28
|
+
neutral_pct: number;
|
|
29
|
+
negative_pct: number;
|
|
30
|
+
total_analyzed: number;
|
|
31
|
+
trending_keywords: string[];
|
|
32
|
+
most_positive: { id: string; content: string; sentiment: string } | null;
|
|
33
|
+
most_negative: { id: string; content: string; sentiment: string } | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---- Prompt Builders (exported for testing) ----
|
|
37
|
+
|
|
38
|
+
export function buildSentimentPrompt(text: string): string {
|
|
39
|
+
return `Analyze the sentiment of the following text.
|
|
40
|
+
|
|
41
|
+
Return ONLY valid JSON with these fields:
|
|
42
|
+
- "sentiment": one of "positive", "neutral", or "negative"
|
|
43
|
+
- "score": a number between 0 and 1 where 0 is most negative, 0.5 is neutral, 1 is most positive
|
|
44
|
+
- "keywords": array of key emotional or sentiment-bearing words from the text (max 5)
|
|
45
|
+
|
|
46
|
+
Text: ${text}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function buildBatchSentimentPrompt(texts: string[]): string {
|
|
50
|
+
const numbered = texts.map((t, i) => `${i + 1}. ${t}`).join("\n");
|
|
51
|
+
return `Analyze the sentiment of each of the following texts.
|
|
52
|
+
|
|
53
|
+
Return ONLY a valid JSON array where each element has:
|
|
54
|
+
- "sentiment": one of "positive", "neutral", or "negative"
|
|
55
|
+
- "score": a number between 0 and 1 where 0 is most negative, 0.5 is neutral, 1 is most positive
|
|
56
|
+
- "keywords": array of key emotional or sentiment-bearing words (max 5 per text)
|
|
57
|
+
|
|
58
|
+
The array must have exactly ${texts.length} elements, one per text, in order.
|
|
59
|
+
|
|
60
|
+
Texts:
|
|
61
|
+
${numbered}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---- JSON Parser ----
|
|
65
|
+
|
|
66
|
+
function parseJSON<T>(raw: string, fallback: T): T {
|
|
67
|
+
const cleaned = raw.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(cleaned) as T;
|
|
70
|
+
} catch {
|
|
71
|
+
return fallback;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function validateSentimentResult(result: SentimentResult): SentimentResult {
|
|
76
|
+
const validSentiments: SentimentLabel[] = ["positive", "neutral", "negative"];
|
|
77
|
+
if (!validSentiments.includes(result.sentiment)) {
|
|
78
|
+
result.sentiment = "neutral";
|
|
79
|
+
}
|
|
80
|
+
if (typeof result.score !== "number" || result.score < 0 || result.score > 1) {
|
|
81
|
+
result.score = 0.5;
|
|
82
|
+
}
|
|
83
|
+
if (!Array.isArray(result.keywords)) {
|
|
84
|
+
result.keywords = [];
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---- Core Functions ----
|
|
90
|
+
|
|
91
|
+
export async function analyzeSentiment(
|
|
92
|
+
text: string,
|
|
93
|
+
provider?: AIProvider
|
|
94
|
+
): Promise<SentimentResult> {
|
|
95
|
+
const resolved = provider ?? getDefaultAIProvider();
|
|
96
|
+
if (!resolved) {
|
|
97
|
+
throw new Error("No AI API key found. Set OPENAI_API_KEY or ANTHROPIC_API_KEY.");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const prompt = buildSentimentPrompt(text);
|
|
101
|
+
const raw = resolved === "openai"
|
|
102
|
+
? await callOpenAI(prompt, 200)
|
|
103
|
+
: await callAnthropic(prompt, 200);
|
|
104
|
+
|
|
105
|
+
const fallback: SentimentResult = { sentiment: "neutral", score: 0.5, keywords: [] };
|
|
106
|
+
const result = parseJSON<SentimentResult>(raw, fallback);
|
|
107
|
+
return validateSentimentResult(result);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function analyzeBatch(
|
|
111
|
+
texts: string[],
|
|
112
|
+
provider?: AIProvider
|
|
113
|
+
): Promise<SentimentResult[]> {
|
|
114
|
+
if (texts.length === 0) return [];
|
|
115
|
+
|
|
116
|
+
const resolved = provider ?? getDefaultAIProvider();
|
|
117
|
+
if (!resolved) {
|
|
118
|
+
throw new Error("No AI API key found. Set OPENAI_API_KEY or ANTHROPIC_API_KEY.");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const prompt = buildBatchSentimentPrompt(texts);
|
|
122
|
+
const maxTokens = Math.min(texts.length * 150, 4000);
|
|
123
|
+
const raw = resolved === "openai"
|
|
124
|
+
? await callOpenAI(prompt, maxTokens)
|
|
125
|
+
: await callAnthropic(prompt, maxTokens);
|
|
126
|
+
|
|
127
|
+
const fallback: SentimentResult[] = texts.map(() => ({
|
|
128
|
+
sentiment: "neutral" as SentimentLabel,
|
|
129
|
+
score: 0.5,
|
|
130
|
+
keywords: [],
|
|
131
|
+
}));
|
|
132
|
+
|
|
133
|
+
const results = parseJSON<SentimentResult[]>(raw, fallback);
|
|
134
|
+
if (!Array.isArray(results) || results.length !== texts.length) {
|
|
135
|
+
return fallback;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return results.map(validateSentimentResult);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function getSentimentReport(
|
|
142
|
+
accountId: string,
|
|
143
|
+
days?: number
|
|
144
|
+
): SentimentReport {
|
|
145
|
+
const db = getDatabase();
|
|
146
|
+
|
|
147
|
+
let dateFilter = "";
|
|
148
|
+
const params: unknown[] = [accountId];
|
|
149
|
+
|
|
150
|
+
if (days && days > 0) {
|
|
151
|
+
dateFilter = " AND fetched_at >= datetime('now', ?)";
|
|
152
|
+
params.push(`-${days} days`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Get all mentions with sentiment for this account
|
|
156
|
+
const rows = db
|
|
157
|
+
.prepare(
|
|
158
|
+
`SELECT id, content, sentiment FROM mentions
|
|
159
|
+
WHERE account_id = ? AND sentiment IS NOT NULL${dateFilter}
|
|
160
|
+
ORDER BY fetched_at DESC`
|
|
161
|
+
)
|
|
162
|
+
.all(...params) as { id: string; content: string | null; sentiment: string }[];
|
|
163
|
+
|
|
164
|
+
const total_analyzed = rows.length;
|
|
165
|
+
|
|
166
|
+
if (total_analyzed === 0) {
|
|
167
|
+
return {
|
|
168
|
+
positive_pct: 0,
|
|
169
|
+
neutral_pct: 0,
|
|
170
|
+
negative_pct: 0,
|
|
171
|
+
total_analyzed: 0,
|
|
172
|
+
trending_keywords: [],
|
|
173
|
+
most_positive: null,
|
|
174
|
+
most_negative: null,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
let positive = 0;
|
|
179
|
+
let neutral = 0;
|
|
180
|
+
let negative = 0;
|
|
181
|
+
let most_positive: { id: string; content: string; sentiment: string } | null = null;
|
|
182
|
+
let most_negative: { id: string; content: string; sentiment: string } | null = null;
|
|
183
|
+
|
|
184
|
+
for (const row of rows) {
|
|
185
|
+
const s = row.sentiment.toLowerCase();
|
|
186
|
+
if (s === "positive") {
|
|
187
|
+
positive++;
|
|
188
|
+
if (!most_positive) {
|
|
189
|
+
most_positive = { id: row.id, content: row.content || "", sentiment: row.sentiment };
|
|
190
|
+
}
|
|
191
|
+
} else if (s === "negative") {
|
|
192
|
+
negative++;
|
|
193
|
+
if (!most_negative) {
|
|
194
|
+
most_negative = { id: row.id, content: row.content || "", sentiment: row.sentiment };
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
neutral++;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Trending keywords: parse sentiment field for keywords if stored as JSON,
|
|
202
|
+
// otherwise just aggregate the sentiment labels
|
|
203
|
+
const keywordCounts: Record<string, number> = {};
|
|
204
|
+
for (const row of rows) {
|
|
205
|
+
// Try to parse sentiment as JSON (might contain keywords)
|
|
206
|
+
try {
|
|
207
|
+
const parsed = JSON.parse(row.sentiment);
|
|
208
|
+
if (parsed && Array.isArray(parsed.keywords)) {
|
|
209
|
+
for (const kw of parsed.keywords) {
|
|
210
|
+
const key = String(kw).toLowerCase();
|
|
211
|
+
keywordCounts[key] = (keywordCounts[key] || 0) + 1;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
} catch {
|
|
215
|
+
// sentiment is a plain string label, skip keyword extraction
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const trending_keywords = Object.entries(keywordCounts)
|
|
220
|
+
.sort((a, b) => b[1] - a[1])
|
|
221
|
+
.slice(0, 10)
|
|
222
|
+
.map(([kw]) => kw);
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
positive_pct: Math.round((positive / total_analyzed) * 100),
|
|
226
|
+
neutral_pct: Math.round((neutral / total_analyzed) * 100),
|
|
227
|
+
negative_pct: Math.round((negative / total_analyzed) * 100),
|
|
228
|
+
total_analyzed,
|
|
229
|
+
trending_keywords,
|
|
230
|
+
most_positive,
|
|
231
|
+
most_negative,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export async function autoAnalyzeMention(
|
|
236
|
+
mentionId: string,
|
|
237
|
+
provider?: AIProvider
|
|
238
|
+
): Promise<SentimentResult | null> {
|
|
239
|
+
const mention = getMention(mentionId);
|
|
240
|
+
if (!mention) {
|
|
241
|
+
throw new Error(`Mention '${mentionId}' not found.`);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (!mention.content) {
|
|
245
|
+
throw new Error(`Mention '${mentionId}' has no content to analyze.`);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const result = await analyzeSentiment(mention.content, provider);
|
|
249
|
+
|
|
250
|
+
// Store the sentiment result as JSON in the mention's sentiment field
|
|
251
|
+
const db = getDatabase();
|
|
252
|
+
const sentimentData = JSON.stringify(result);
|
|
253
|
+
db.prepare("UPDATE mentions SET sentiment = ? WHERE id = ?").run(sentimentData, mentionId);
|
|
254
|
+
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thread and carousel support for social media posts.
|
|
3
|
+
*
|
|
4
|
+
* Threads: multiple posts linked by thread_id, ordered by thread_position.
|
|
5
|
+
* Carousels: a single post with multiple media_urls (Instagram/LinkedIn format).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
createPost,
|
|
10
|
+
getAccount,
|
|
11
|
+
getPost,
|
|
12
|
+
updatePost,
|
|
13
|
+
getThreadPosts,
|
|
14
|
+
deleteThreadPosts,
|
|
15
|
+
checkPlatformLimit,
|
|
16
|
+
PLATFORM_LIMITS,
|
|
17
|
+
type Post,
|
|
18
|
+
type Platform,
|
|
19
|
+
} from "../db/social.js";
|
|
20
|
+
|
|
21
|
+
// ---- Types ----
|
|
22
|
+
|
|
23
|
+
export interface CreateThreadOptions {
|
|
24
|
+
scheduledAt?: string;
|
|
25
|
+
tags?: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ThreadResult {
|
|
29
|
+
threadId: string;
|
|
30
|
+
posts: Post[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PublishThreadResult {
|
|
34
|
+
threadId: string;
|
|
35
|
+
posts: Post[];
|
|
36
|
+
platformPostIds: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---- Thread Operations ----
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Create a thread of posts linked by a shared thread_id.
|
|
43
|
+
* Each post is validated against the platform's character limit.
|
|
44
|
+
*/
|
|
45
|
+
export function createThread(
|
|
46
|
+
contents: string[],
|
|
47
|
+
accountId: string,
|
|
48
|
+
options?: CreateThreadOptions
|
|
49
|
+
): ThreadResult {
|
|
50
|
+
if (contents.length === 0) {
|
|
51
|
+
throw new Error("Thread must have at least one post.");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const account = getAccount(accountId);
|
|
55
|
+
if (!account) {
|
|
56
|
+
throw new Error(`Account '${accountId}' not found.`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const limit = PLATFORM_LIMITS[account.platform];
|
|
60
|
+
for (let i = 0; i < contents.length; i++) {
|
|
61
|
+
if (contents[i].length > limit) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`Post ${i + 1} (${contents[i].length} chars) exceeds ${account.platform} limit (${limit} chars).`
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const threadId = crypto.randomUUID();
|
|
69
|
+
const posts: Post[] = [];
|
|
70
|
+
|
|
71
|
+
for (let i = 0; i < contents.length; i++) {
|
|
72
|
+
const post = createPost({
|
|
73
|
+
account_id: accountId,
|
|
74
|
+
content: contents[i],
|
|
75
|
+
status: options?.scheduledAt ? "scheduled" : "draft",
|
|
76
|
+
scheduled_at: options?.scheduledAt,
|
|
77
|
+
tags: options?.tags,
|
|
78
|
+
thread_id: threadId,
|
|
79
|
+
thread_position: i,
|
|
80
|
+
});
|
|
81
|
+
posts.push(post);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return { threadId, posts };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Get all posts in a thread, ordered by position.
|
|
89
|
+
*/
|
|
90
|
+
export function getThread(threadId: string): Post[] {
|
|
91
|
+
const posts = getThreadPosts(threadId);
|
|
92
|
+
if (posts.length === 0) {
|
|
93
|
+
throw new Error(`Thread '${threadId}' not found.`);
|
|
94
|
+
}
|
|
95
|
+
return posts;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Publish a thread sequentially via platform APIs.
|
|
100
|
+
*
|
|
101
|
+
* - X: POST /2/tweets chaining each reply to the previous tweet
|
|
102
|
+
* - Meta: POST /{page-id}/feed for first post, then POST /{post-id}/comments for rest
|
|
103
|
+
*
|
|
104
|
+
* Each post gets its platform_post_id stored.
|
|
105
|
+
*/
|
|
106
|
+
export async function publishThread(threadId: string): Promise<PublishThreadResult> {
|
|
107
|
+
const posts = getThreadPosts(threadId);
|
|
108
|
+
if (posts.length === 0) {
|
|
109
|
+
throw new Error(`Thread '${threadId}' not found.`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const firstPost = posts[0];
|
|
113
|
+
const account = getAccount(firstPost.account_id);
|
|
114
|
+
if (!account) {
|
|
115
|
+
throw new Error(`Account '${firstPost.account_id}' not found.`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const platformPostIds: string[] = [];
|
|
119
|
+
const updatedPosts: Post[] = [];
|
|
120
|
+
|
|
121
|
+
if (account.platform === "x") {
|
|
122
|
+
// X: chain tweets using reply.in_reply_to_tweet_id
|
|
123
|
+
const { XPublisher } = await import("./publisher.js");
|
|
124
|
+
const publisher = new XPublisher();
|
|
125
|
+
|
|
126
|
+
let previousTweetId: string | null = null;
|
|
127
|
+
|
|
128
|
+
for (const post of posts) {
|
|
129
|
+
const body: Record<string, unknown> = { text: post.content };
|
|
130
|
+
if (previousTweetId) {
|
|
131
|
+
body.reply = { in_reply_to_tweet_id: previousTweetId };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Use the publisher's publishPost for the first, then raw fetch for replies
|
|
135
|
+
const res = await fetch("https://api.twitter.com/2/tweets", {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers: {
|
|
138
|
+
Authorization: `Bearer ${process.env.X_BEARER_TOKEN || process.env.X_ACCESS_TOKEN || ""}`,
|
|
139
|
+
"Content-Type": "application/json",
|
|
140
|
+
},
|
|
141
|
+
body: JSON.stringify(body),
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
if (!res.ok) {
|
|
145
|
+
const text = await res.text();
|
|
146
|
+
// Mark remaining posts as failed
|
|
147
|
+
for (const remaining of posts.filter((p) => !platformPostIds.includes(p.platform_post_id || ""))) {
|
|
148
|
+
if (!platformPostIds.some((pid) => pid === remaining.platform_post_id)) {
|
|
149
|
+
updatePost(remaining.id, { status: "failed" });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
throw new Error(`X API error ${res.status}: ${text}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const data = (await res.json()) as { data: { id: string } };
|
|
156
|
+
const tweetId = data.data.id;
|
|
157
|
+
previousTweetId = tweetId;
|
|
158
|
+
platformPostIds.push(tweetId);
|
|
159
|
+
|
|
160
|
+
const updated = updatePost(post.id, {
|
|
161
|
+
status: "published",
|
|
162
|
+
published_at: new Date().toISOString().replace("T", " ").replace(/\.\d+Z$/, ""),
|
|
163
|
+
platform_post_id: tweetId,
|
|
164
|
+
});
|
|
165
|
+
updatedPosts.push(updated!);
|
|
166
|
+
}
|
|
167
|
+
} else if (account.platform === "instagram" || account.platform === "linkedin") {
|
|
168
|
+
// Meta-style: first post to feed, rest as comments
|
|
169
|
+
const accessToken = process.env.META_ACCESS_TOKEN || "";
|
|
170
|
+
const pageId = process.env.META_PAGE_ID || account.handle;
|
|
171
|
+
const baseUrl = "https://graph.facebook.com/v22.0";
|
|
172
|
+
|
|
173
|
+
// First post
|
|
174
|
+
const firstRes = await fetch(
|
|
175
|
+
`${baseUrl}/${pageId}/feed?access_token=${encodeURIComponent(accessToken)}`,
|
|
176
|
+
{
|
|
177
|
+
method: "POST",
|
|
178
|
+
headers: { "Content-Type": "application/json" },
|
|
179
|
+
body: JSON.stringify({ message: posts[0].content }),
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
if (!firstRes.ok) {
|
|
184
|
+
const text = await firstRes.text();
|
|
185
|
+
throw new Error(`Meta API error ${firstRes.status}: ${text}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const firstData = (await firstRes.json()) as { id: string };
|
|
189
|
+
platformPostIds.push(firstData.id);
|
|
190
|
+
const firstUpdated = updatePost(posts[0].id, {
|
|
191
|
+
status: "published",
|
|
192
|
+
published_at: new Date().toISOString().replace("T", " ").replace(/\.\d+Z$/, ""),
|
|
193
|
+
platform_post_id: firstData.id,
|
|
194
|
+
});
|
|
195
|
+
updatedPosts.push(firstUpdated!);
|
|
196
|
+
|
|
197
|
+
// Rest as comments on the first post
|
|
198
|
+
for (let i = 1; i < posts.length; i++) {
|
|
199
|
+
const commentRes = await fetch(
|
|
200
|
+
`${baseUrl}/${firstData.id}/comments?access_token=${encodeURIComponent(accessToken)}`,
|
|
201
|
+
{
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers: { "Content-Type": "application/json" },
|
|
204
|
+
body: JSON.stringify({ message: posts[i].content }),
|
|
205
|
+
}
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
if (!commentRes.ok) {
|
|
209
|
+
const text = await commentRes.text();
|
|
210
|
+
throw new Error(`Meta API error ${commentRes.status}: ${text}`);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const commentData = (await commentRes.json()) as { id: string };
|
|
214
|
+
platformPostIds.push(commentData.id);
|
|
215
|
+
|
|
216
|
+
const updated = updatePost(posts[i].id, {
|
|
217
|
+
status: "published",
|
|
218
|
+
published_at: new Date().toISOString().replace("T", " ").replace(/\.\d+Z$/, ""),
|
|
219
|
+
platform_post_id: commentData.id,
|
|
220
|
+
});
|
|
221
|
+
updatedPosts.push(updated!);
|
|
222
|
+
}
|
|
223
|
+
} else {
|
|
224
|
+
// For unsupported platforms, publish each post individually via the generic publisher
|
|
225
|
+
const { publishToApi } = await import("./publisher.js");
|
|
226
|
+
|
|
227
|
+
for (const post of posts) {
|
|
228
|
+
try {
|
|
229
|
+
const updated = await publishToApi(post.id);
|
|
230
|
+
platformPostIds.push(updated.platform_post_id || "");
|
|
231
|
+
updatedPosts.push(updated);
|
|
232
|
+
} catch (err) {
|
|
233
|
+
throw err;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return { threadId, posts: updatedPosts, platformPostIds };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Delete an entire thread and all its posts.
|
|
243
|
+
*/
|
|
244
|
+
export function deleteThread(threadId: string): number {
|
|
245
|
+
const posts = getThreadPosts(threadId);
|
|
246
|
+
if (posts.length === 0) {
|
|
247
|
+
throw new Error(`Thread '${threadId}' not found.`);
|
|
248
|
+
}
|
|
249
|
+
return deleteThreadPosts(threadId);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ---- Carousel ----
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Create a carousel post — a single post with multiple media_urls.
|
|
256
|
+
* Used for Instagram/LinkedIn carousel format.
|
|
257
|
+
*/
|
|
258
|
+
export function createCarousel(
|
|
259
|
+
images: string[],
|
|
260
|
+
captions: string[],
|
|
261
|
+
accountId: string
|
|
262
|
+
): Post {
|
|
263
|
+
if (images.length === 0) {
|
|
264
|
+
throw new Error("Carousel must have at least one image.");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const account = getAccount(accountId);
|
|
268
|
+
if (!account) {
|
|
269
|
+
throw new Error(`Account '${accountId}' not found.`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Use the first caption or combine all captions as the post content
|
|
273
|
+
const content = captions.length > 0 ? captions.join("\n\n") : "";
|
|
274
|
+
|
|
275
|
+
// Validate content length against platform limit
|
|
276
|
+
if (content.length > 0) {
|
|
277
|
+
const limit = PLATFORM_LIMITS[account.platform];
|
|
278
|
+
if (content.length > limit) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`Carousel caption (${content.length} chars) exceeds ${account.platform} limit (${limit} chars).`
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return createPost({
|
|
286
|
+
account_id: accountId,
|
|
287
|
+
content,
|
|
288
|
+
media_urls: images,
|
|
289
|
+
status: "draft",
|
|
290
|
+
});
|
|
291
|
+
}
|