@chaouidz/postpilot 1.1.1 → 1.1.2
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 +56 -103
- package/bin/postpilot.mjs +309 -292
- package/package.json +27 -27
- package/src/bootstrap.mjs +53 -0
- package/src/client.mjs +168 -168
- package/src/plan.mjs +333 -331
package/src/plan.mjs
CHANGED
|
@@ -1,331 +1,333 @@
|
|
|
1
|
-
import { readFile, stat, writeFile, rename } from "node:fs/promises";
|
|
2
|
-
import { createReadStream } from "node:fs";
|
|
3
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
-
import { dirname, basename, resolve, extname } from "node:path";
|
|
5
|
-
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
-
import { CliError } from "./client.mjs";
|
|
7
|
-
|
|
8
|
-
export async function retryUpload(upload, { wait = sleep, maxRetries = 5 } = {}) {
|
|
9
|
-
for (let attempt = 0; ; attempt++) {
|
|
10
|
-
try {
|
|
11
|
-
return await upload();
|
|
12
|
-
} catch (error) {
|
|
13
|
-
if (!(error instanceof CliError) || error.code !== "RATE_LIMITED" || attempt >= maxRetries)
|
|
14
|
-
throw error;
|
|
15
|
-
const raw = error.details.retryAfter;
|
|
16
|
-
const seconds =
|
|
17
|
-
raw !== null && raw !== undefined && /^\d+(?:\.\d+)?$/.test(String(raw))
|
|
18
|
-
? Number(raw)
|
|
19
|
-
: Number.isFinite(Date.parse(raw))
|
|
20
|
-
? Math.max(0, (Date.parse(raw) - Date.now()) / 1000)
|
|
21
|
-
: 5 * (attempt + 1);
|
|
22
|
-
if (seconds > 300)
|
|
23
|
-
throw new CliError(
|
|
24
|
-
"Upload rate limit requires a longer wait. Retry this same plan after Retry-After.",
|
|
25
|
-
"RATE_LIMITED",
|
|
26
|
-
error.details
|
|
27
|
-
);
|
|
28
|
-
await wait(Math.max(0, seconds * 1000));
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
function chooseAccount(accounts, selector, index) {
|
|
33
|
-
if (typeof selector !== "string" || !selector)
|
|
34
|
-
throw new CliError(`Plan item ${index}: choose an account or supply --account.`);
|
|
35
|
-
const exact = accounts.filter((account) => account.id === selector);
|
|
36
|
-
const matches = exact.length
|
|
37
|
-
? exact
|
|
38
|
-
: accounts.filter(
|
|
39
|
-
(account) =>
|
|
40
|
-
String(account.platformUsername || account.name || "").toLowerCase() ===
|
|
41
|
-
selector.toLowerCase()
|
|
42
|
-
);
|
|
43
|
-
if (matches.length !== 1)
|
|
44
|
-
throw new CliError(`Plan item ${index}: account must be an exact ID or unique account name.`);
|
|
45
|
-
if (matches[0].status && matches[0].status !== "CONNECTED")
|
|
46
|
-
throw new CliError(`Plan item ${index}: account needs reconnection.`);
|
|
47
|
-
return matches[0];
|
|
48
|
-
}
|
|
49
|
-
export async function schedulePlan(client, file, options = {}) {
|
|
50
|
-
if (options.yes && options["dry-run"]) throw new CliError("Choose --yes or --dry-run, not both.");
|
|
51
|
-
const location = resolve(file);
|
|
52
|
-
if ((await stat(location)).size > 1024 * 1024)
|
|
53
|
-
throw new CliError("Plan JSON must be at most 1 MiB.");
|
|
54
|
-
let raw;
|
|
55
|
-
try {
|
|
56
|
-
raw = JSON.parse((await readFile(location, "utf8")).replace(/^\uFEFF/, ""));
|
|
57
|
-
} catch {
|
|
58
|
-
throw new CliError("Plan must be valid JSON.");
|
|
59
|
-
}
|
|
60
|
-
const items = Array.isArray(raw) ? raw : raw?.posts;
|
|
61
|
-
if (!Array.isArray(items) || !items.length || items.length > 100)
|
|
62
|
-
throw new CliError("Plan must contain 1-100 posts.");
|
|
63
|
-
const listed = await client.tool("accounts_list");
|
|
64
|
-
const accounts = Array.isArray(listed) ? listed : listed.items || listed.accounts || [];
|
|
65
|
-
const prepared = [];
|
|
66
|
-
const allowedKeys = new Set([
|
|
67
|
-
"video",
|
|
68
|
-
"videoPath",
|
|
69
|
-
"title",
|
|
70
|
-
"description",
|
|
71
|
-
"tags",
|
|
72
|
-
"scheduledAt",
|
|
73
|
-
"account",
|
|
74
|
-
"privacy",
|
|
75
|
-
"tiktokSettings",
|
|
76
|
-
"pinterestSettings",
|
|
77
|
-
"facebookSettings",
|
|
78
|
-
"instagramPostType",
|
|
79
|
-
"instagramCaption",
|
|
80
|
-
]);
|
|
81
|
-
for (const [offset, item] of items.entries()) {
|
|
82
|
-
const index = offset + 1;
|
|
83
|
-
if (
|
|
84
|
-
!item ||
|
|
85
|
-
typeof item !== "object" ||
|
|
86
|
-
Array.isArray(item) ||
|
|
87
|
-
Object.keys(item).some((key) => !allowedKeys.has(key))
|
|
88
|
-
)
|
|
89
|
-
throw new CliError(`Plan item ${index}: invalid or unknown fields.`);
|
|
90
|
-
if (typeof item.title !== "string" || !item.title.trim() || item.title.length > 100)
|
|
91
|
-
throw new CliError(`Plan item ${index}: title must be 1-100 characters.`);
|
|
92
|
-
if (
|
|
93
|
-
item.description !== undefined &&
|
|
94
|
-
(typeof item.description !== "string" || item.description.length > 5000)
|
|
95
|
-
)
|
|
96
|
-
throw new CliError(`Plan item ${index}: description must be at most 5000 characters.`);
|
|
97
|
-
if (
|
|
98
|
-
!Array.isArray(item.tags || []) ||
|
|
99
|
-
(item.tags || []).some((tag) => typeof tag !== "string" || !tag.trim() || tag.length > 80) ||
|
|
100
|
-
(item.tags || []).length > 30 ||
|
|
101
|
-
(item.tags || []).join(",").length > 400
|
|
102
|
-
)
|
|
103
|
-
throw new CliError(
|
|
104
|
-
`Plan item ${index}: use up to 30 tags, 80 characters each and 400 characters total.`
|
|
105
|
-
);
|
|
106
|
-
if (
|
|
107
|
-
typeof item.scheduledAt !== "string" ||
|
|
108
|
-
!/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(item.scheduledAt) ||
|
|
109
|
-
!Number.isFinite(Date.parse(item.scheduledAt)) ||
|
|
110
|
-
Date.parse(item.scheduledAt) <= Date.now()
|
|
111
|
-
)
|
|
112
|
-
throw new CliError(
|
|
113
|
-
`Plan item ${index}: scheduledAt must be a future ISO timestamp with an offset.`
|
|
114
|
-
);
|
|
115
|
-
const path = item.video || item.videoPath;
|
|
116
|
-
if (
|
|
117
|
-
typeof path !== "string" ||
|
|
118
|
-
!path ||
|
|
119
|
-
(item.video && item.videoPath && item.video !== item.videoPath)
|
|
120
|
-
)
|
|
121
|
-
throw new CliError(`Plan item ${index}: specify one video path.`);
|
|
122
|
-
const video = resolve(dirname(location), path);
|
|
123
|
-
const info = await stat(video).catch(() => null);
|
|
124
|
-
if (
|
|
125
|
-
!info?.isFile() ||
|
|
126
|
-
info.size < 1 ||
|
|
127
|
-
info.size > 90 * 1024 * 1024 ||
|
|
128
|
-
extname(video).toLowerCase() !== ".mp4"
|
|
129
|
-
)
|
|
130
|
-
throw new CliError(
|
|
131
|
-
`Plan item ${index}: choose an existing MP4 up to 90 MiB. Use prepare-video for other formats.`
|
|
132
|
-
);
|
|
133
|
-
const account = chooseAccount(accounts, item.account || options.account, index);
|
|
134
|
-
const privacy = item.privacy || options.privacy || "private";
|
|
135
|
-
if (!["private", "public", "unlisted"].includes(privacy))
|
|
136
|
-
throw new CliError(`Plan item ${index}: invalid YouTube privacy.`);
|
|
137
|
-
if (
|
|
138
|
-
account.platform === "TIKTOK" &&
|
|
139
|
-
(!item.tiktokSettings ||
|
|
140
|
-
typeof item.tiktokSettings.privacy !== "string" ||
|
|
141
|
-
["allowComments", "allowDuet", "allowStitch"].some(
|
|
142
|
-
(key) => typeof item.tiktokSettings[key] !== "boolean"
|
|
143
|
-
))
|
|
144
|
-
)
|
|
145
|
-
throw new CliError(
|
|
146
|
-
`Plan item ${index}: TikTok needs explicit tiktokSettings (privacy, allowComments, allowDuet, allowStitch), reviewed against creator settings.`
|
|
147
|
-
);
|
|
148
|
-
if (account.platform === "PINTEREST" && !item.pinterestSettings?.boardIds?.[account.id])
|
|
149
|
-
throw new CliError(
|
|
150
|
-
`Plan item ${index}: choose the Pinterest board in pinterestSettings.boardIds.`
|
|
151
|
-
);
|
|
152
|
-
const tags = (item.tags || []).map((tag) => tag.trim());
|
|
153
|
-
const description = item.description || "";
|
|
154
|
-
const content =
|
|
155
|
-
account.platform === "YOUTUBE"
|
|
156
|
-
? description
|
|
157
|
-
: [
|
|
158
|
-
description,
|
|
159
|
-
tags.map((tag) => `#${tag.replace(/^#/, "").replace(/\s+/g, "")}`).join(" "),
|
|
160
|
-
]
|
|
161
|
-
.filter(Boolean)
|
|
162
|
-
.join("\n\n");
|
|
163
|
-
const max = { TWITTER: 280, BLUESKY: 300, THREADS: 500 }[account.platform] || 5000;
|
|
164
|
-
if ([...content].length > max)
|
|
165
|
-
throw new CliError(
|
|
166
|
-
`Plan item ${index}: description and tags exceed ${account.platform}'s ${max}-character local limit.`
|
|
167
|
-
);
|
|
168
|
-
prepared.push({
|
|
169
|
-
video,
|
|
170
|
-
title: item.title,
|
|
171
|
-
description,
|
|
172
|
-
tags,
|
|
173
|
-
scheduledAt: item.scheduledAt,
|
|
174
|
-
accountId: account.id,
|
|
175
|
-
platform: account.platform,
|
|
176
|
-
privacy,
|
|
177
|
-
content,
|
|
178
|
-
settings: Object.fromEntries(
|
|
179
|
-
[
|
|
180
|
-
"tiktokSettings",
|
|
181
|
-
"pinterestSettings",
|
|
182
|
-
"facebookSettings",
|
|
183
|
-
"instagramPostType",
|
|
184
|
-
"instagramCaption",
|
|
185
|
-
]
|
|
186
|
-
.filter((key) => item[key] !== undefined)
|
|
187
|
-
.map((key) => [key, item[key]])
|
|
188
|
-
),
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
const hashed = [];
|
|
192
|
-
for (const item of prepared) {
|
|
193
|
-
const hash = createHash("sha256");
|
|
194
|
-
for await (const chunk of createReadStream(item.video)) hash.update(chunk);
|
|
195
|
-
hashed.push({ ...item, sha256: hash.digest("hex") });
|
|
196
|
-
}
|
|
197
|
-
const digest = createHash("sha256").update(JSON.stringify(hashed)).digest("hex");
|
|
198
|
-
const root = options["idempotency-key"] || `plan-${digest}`;
|
|
199
|
-
if (!/^[\w.:-]{8,150}$/.test(root))
|
|
200
|
-
throw new CliError("Plan idempotency key must be 8-150 safe characters.");
|
|
201
|
-
const journal = resolve(
|
|
202
|
-
dirname(location),
|
|
203
|
-
`${basename(location)}.postpilot-${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`
|
|
204
|
-
);
|
|
205
|
-
let state = { planId: root, digest, preparedPosts: [] };
|
|
206
|
-
try {
|
|
207
|
-
state = JSON.parse(await readFile(journal, "utf8"));
|
|
208
|
-
} catch (error) {
|
|
209
|
-
if (error.code !== "ENOENT")
|
|
210
|
-
throw new CliError("Plan checkpoint cannot be read. Inspect it before retrying.");
|
|
211
|
-
}
|
|
212
|
-
if (
|
|
213
|
-
state.planId !== root ||
|
|
214
|
-
state.digest !== digest ||
|
|
215
|
-
!Array.isArray(state.preparedPosts) ||
|
|
216
|
-
state.preparedPosts.some(
|
|
217
|
-
(post, i) =>
|
|
218
|
-
!post.postId ||
|
|
219
|
-
post.accountId !== prepared[i]?.accountId ||
|
|
220
|
-
post.scheduledAt !== prepared[i]?.scheduledAt
|
|
221
|
-
)
|
|
222
|
-
)
|
|
223
|
-
throw new CliError(
|
|
224
|
-
"This plan key or checkpoint belongs to different arguments. Choose a new key only for an intentionally new plan."
|
|
225
|
-
);
|
|
226
|
-
const drafts = [...state.preparedPosts];
|
|
227
|
-
async function saveState() {
|
|
228
|
-
const temporary = `${journal}.${randomUUID()}.tmp`;
|
|
229
|
-
await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
|
|
230
|
-
await rename(temporary, journal);
|
|
231
|
-
}
|
|
232
|
-
if (state.approvalId) {
|
|
233
|
-
const status = await client.tool("approval_status", { approvalId: state.approvalId });
|
|
234
|
-
if (["EXPIRED", "FAILED", "PARTIALLY_FAILED", "CANCELED"].includes(status.status))
|
|
235
|
-
throw new CliError(
|
|
236
|
-
"This batch ended or expired. Inspect per-post results before preparing only the intended retries with a new plan key.",
|
|
237
|
-
"CONFLICT",
|
|
238
|
-
{ approvalId: state.approvalId, result: status }
|
|
239
|
-
);
|
|
240
|
-
return {
|
|
241
|
-
...status,
|
|
242
|
-
approvalUrl: state.approvalUrl,
|
|
243
|
-
alreadyPrepared: true,
|
|
244
|
-
planId: root,
|
|
245
|
-
preparedPosts: drafts,
|
|
246
|
-
dryRun: !options.yes,
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
const capacity = await client.tool("plan_validate", {
|
|
250
|
-
items: prepared.map((item, i) => ({
|
|
251
|
-
accountId: item.accountId,
|
|
252
|
-
scheduledAt: item.scheduledAt,
|
|
253
|
-
title: item.title,
|
|
254
|
-
...(drafts[i] ? { postId: drafts[i].postId } : {}),
|
|
255
|
-
})),
|
|
256
|
-
});
|
|
257
|
-
if (capacity.allowed === false || capacity.validated !== true)
|
|
258
|
-
throw new CliError("The server did not validate this plan. No uploads or drafts were created.");
|
|
259
|
-
if (!options.yes)
|
|
260
|
-
return {
|
|
261
|
-
dryRun: true,
|
|
262
|
-
validated: true,
|
|
263
|
-
requiresYes: true,
|
|
264
|
-
planId: root,
|
|
265
|
-
message:
|
|
266
|
-
"No uploads, drafts or schedules created. Add --yes to
|
|
267
|
-
items: prepared.map(({ video, title, accountId, scheduledAt }) => ({
|
|
268
|
-
video,
|
|
269
|
-
title,
|
|
270
|
-
accountId,
|
|
271
|
-
scheduledAt,
|
|
272
|
-
})),
|
|
273
|
-
capacity,
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
try {
|
|
277
|
-
for (const [index, item] of hashed.entries()) {
|
|
278
|
-
if (drafts[index]) continue;
|
|
279
|
-
const upload = await retryUpload(() => client.upload(item.video, `${root}.upload.${index}`));
|
|
280
|
-
if (upload.sha256 && upload.sha256 !== item.sha256)
|
|
281
|
-
throw new CliError(
|
|
282
|
-
`Plan item ${index + 1}: video changed after plan validation. Review the file before retrying.`
|
|
283
|
-
);
|
|
284
|
-
const assetId = upload.uploadSessionId || upload.sessionId || upload.id;
|
|
285
|
-
if (!assetId)
|
|
286
|
-
throw new CliError(
|
|
287
|
-
`Plan item ${index + 1}: upload did not return an asset ID.`,
|
|
288
|
-
"INTERNAL_FAILURE"
|
|
289
|
-
);
|
|
290
|
-
const draft = await client.tool("post_create_draft", {
|
|
291
|
-
post: {
|
|
292
|
-
content: item.content,
|
|
293
|
-
videoTitle: item.title,
|
|
294
|
-
videoDescription: item.description,
|
|
295
|
-
videoTags: item.tags,
|
|
296
|
-
youtubePrivacyStatus: item.privacy,
|
|
297
|
-
platformTargets: [item.platform],
|
|
298
|
-
selectedAccountIds: [item.accountId],
|
|
299
|
-
uploadSessionId: assetId,
|
|
300
|
-
mediaType: "VIDEO",
|
|
301
|
-
...item.settings,
|
|
302
|
-
},
|
|
303
|
-
idempotencyKey: `${root}.draft.${index}`,
|
|
304
|
-
});
|
|
305
|
-
if (!draft.id || draft.status !== "DRAFT")
|
|
306
|
-
throw new CliError(
|
|
307
|
-
`Plan item ${index + 1}: draft creation is incomplete. Inspect the operation before retrying.`,
|
|
308
|
-
"INTERNAL_FAILURE"
|
|
309
|
-
);
|
|
310
|
-
drafts.push({ postId: draft.id, accountId: item.accountId, scheduledAt: item.scheduledAt });
|
|
311
|
-
state.preparedPosts = drafts;
|
|
312
|
-
await saveState();
|
|
313
|
-
}
|
|
314
|
-
const approval = await client.tool("post_schedule_batch", {
|
|
315
|
-
items: drafts,
|
|
316
|
-
idempotencyKey: `${root}.approval`,
|
|
317
|
-
});
|
|
318
|
-
if (!approval.approvalId || !approval.approvalUrl)
|
|
319
|
-
throw new CliError(
|
|
320
|
-
"Batch did not return a
|
|
321
|
-
"INTERNAL_FAILURE"
|
|
322
|
-
);
|
|
323
|
-
Object.assign(state, { approvalId: approval.approvalId, approvalUrl: approval.approvalUrl });
|
|
324
|
-
await saveState();
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
1
|
+
import { readFile, stat, writeFile, rename } from "node:fs/promises";
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { dirname, basename, resolve, extname } from "node:path";
|
|
5
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
6
|
+
import { CliError } from "./client.mjs";
|
|
7
|
+
|
|
8
|
+
export async function retryUpload(upload, { wait = sleep, maxRetries = 5 } = {}) {
|
|
9
|
+
for (let attempt = 0; ; attempt++) {
|
|
10
|
+
try {
|
|
11
|
+
return await upload();
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (!(error instanceof CliError) || error.code !== "RATE_LIMITED" || attempt >= maxRetries)
|
|
14
|
+
throw error;
|
|
15
|
+
const raw = error.details.retryAfter;
|
|
16
|
+
const seconds =
|
|
17
|
+
raw !== null && raw !== undefined && /^\d+(?:\.\d+)?$/.test(String(raw))
|
|
18
|
+
? Number(raw)
|
|
19
|
+
: Number.isFinite(Date.parse(raw))
|
|
20
|
+
? Math.max(0, (Date.parse(raw) - Date.now()) / 1000)
|
|
21
|
+
: 5 * (attempt + 1);
|
|
22
|
+
if (seconds > 300)
|
|
23
|
+
throw new CliError(
|
|
24
|
+
"Upload rate limit requires a longer wait. Retry this same plan after Retry-After.",
|
|
25
|
+
"RATE_LIMITED",
|
|
26
|
+
error.details
|
|
27
|
+
);
|
|
28
|
+
await wait(Math.max(0, seconds * 1000));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function chooseAccount(accounts, selector, index) {
|
|
33
|
+
if (typeof selector !== "string" || !selector)
|
|
34
|
+
throw new CliError(`Plan item ${index}: choose an account or supply --account.`);
|
|
35
|
+
const exact = accounts.filter((account) => account.id === selector);
|
|
36
|
+
const matches = exact.length
|
|
37
|
+
? exact
|
|
38
|
+
: accounts.filter(
|
|
39
|
+
(account) =>
|
|
40
|
+
String(account.platformUsername || account.name || "").toLowerCase() ===
|
|
41
|
+
selector.toLowerCase()
|
|
42
|
+
);
|
|
43
|
+
if (matches.length !== 1)
|
|
44
|
+
throw new CliError(`Plan item ${index}: account must be an exact ID or unique account name.`);
|
|
45
|
+
if (matches[0].status && matches[0].status !== "CONNECTED")
|
|
46
|
+
throw new CliError(`Plan item ${index}: account needs reconnection.`);
|
|
47
|
+
return matches[0];
|
|
48
|
+
}
|
|
49
|
+
export async function schedulePlan(client, file, options = {}) {
|
|
50
|
+
if (options.yes && options["dry-run"]) throw new CliError("Choose --yes or --dry-run, not both.");
|
|
51
|
+
const location = resolve(file);
|
|
52
|
+
if ((await stat(location)).size > 1024 * 1024)
|
|
53
|
+
throw new CliError("Plan JSON must be at most 1 MiB.");
|
|
54
|
+
let raw;
|
|
55
|
+
try {
|
|
56
|
+
raw = JSON.parse((await readFile(location, "utf8")).replace(/^\uFEFF/, ""));
|
|
57
|
+
} catch {
|
|
58
|
+
throw new CliError("Plan must be valid JSON.");
|
|
59
|
+
}
|
|
60
|
+
const items = Array.isArray(raw) ? raw : raw?.posts;
|
|
61
|
+
if (!Array.isArray(items) || !items.length || items.length > 100)
|
|
62
|
+
throw new CliError("Plan must contain 1-100 posts.");
|
|
63
|
+
const listed = await client.tool("accounts_list");
|
|
64
|
+
const accounts = Array.isArray(listed) ? listed : listed.items || listed.accounts || [];
|
|
65
|
+
const prepared = [];
|
|
66
|
+
const allowedKeys = new Set([
|
|
67
|
+
"video",
|
|
68
|
+
"videoPath",
|
|
69
|
+
"title",
|
|
70
|
+
"description",
|
|
71
|
+
"tags",
|
|
72
|
+
"scheduledAt",
|
|
73
|
+
"account",
|
|
74
|
+
"privacy",
|
|
75
|
+
"tiktokSettings",
|
|
76
|
+
"pinterestSettings",
|
|
77
|
+
"facebookSettings",
|
|
78
|
+
"instagramPostType",
|
|
79
|
+
"instagramCaption",
|
|
80
|
+
]);
|
|
81
|
+
for (const [offset, item] of items.entries()) {
|
|
82
|
+
const index = offset + 1;
|
|
83
|
+
if (
|
|
84
|
+
!item ||
|
|
85
|
+
typeof item !== "object" ||
|
|
86
|
+
Array.isArray(item) ||
|
|
87
|
+
Object.keys(item).some((key) => !allowedKeys.has(key))
|
|
88
|
+
)
|
|
89
|
+
throw new CliError(`Plan item ${index}: invalid or unknown fields.`);
|
|
90
|
+
if (typeof item.title !== "string" || !item.title.trim() || item.title.length > 100)
|
|
91
|
+
throw new CliError(`Plan item ${index}: title must be 1-100 characters.`);
|
|
92
|
+
if (
|
|
93
|
+
item.description !== undefined &&
|
|
94
|
+
(typeof item.description !== "string" || item.description.length > 5000)
|
|
95
|
+
)
|
|
96
|
+
throw new CliError(`Plan item ${index}: description must be at most 5000 characters.`);
|
|
97
|
+
if (
|
|
98
|
+
!Array.isArray(item.tags || []) ||
|
|
99
|
+
(item.tags || []).some((tag) => typeof tag !== "string" || !tag.trim() || tag.length > 80) ||
|
|
100
|
+
(item.tags || []).length > 30 ||
|
|
101
|
+
(item.tags || []).join(",").length > 400
|
|
102
|
+
)
|
|
103
|
+
throw new CliError(
|
|
104
|
+
`Plan item ${index}: use up to 30 tags, 80 characters each and 400 characters total.`
|
|
105
|
+
);
|
|
106
|
+
if (
|
|
107
|
+
typeof item.scheduledAt !== "string" ||
|
|
108
|
+
!/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(item.scheduledAt) ||
|
|
109
|
+
!Number.isFinite(Date.parse(item.scheduledAt)) ||
|
|
110
|
+
Date.parse(item.scheduledAt) <= Date.now()
|
|
111
|
+
)
|
|
112
|
+
throw new CliError(
|
|
113
|
+
`Plan item ${index}: scheduledAt must be a future ISO timestamp with an offset.`
|
|
114
|
+
);
|
|
115
|
+
const path = item.video || item.videoPath;
|
|
116
|
+
if (
|
|
117
|
+
typeof path !== "string" ||
|
|
118
|
+
!path ||
|
|
119
|
+
(item.video && item.videoPath && item.video !== item.videoPath)
|
|
120
|
+
)
|
|
121
|
+
throw new CliError(`Plan item ${index}: specify one video path.`);
|
|
122
|
+
const video = resolve(dirname(location), path);
|
|
123
|
+
const info = await stat(video).catch(() => null);
|
|
124
|
+
if (
|
|
125
|
+
!info?.isFile() ||
|
|
126
|
+
info.size < 1 ||
|
|
127
|
+
info.size > 90 * 1024 * 1024 ||
|
|
128
|
+
extname(video).toLowerCase() !== ".mp4"
|
|
129
|
+
)
|
|
130
|
+
throw new CliError(
|
|
131
|
+
`Plan item ${index}: choose an existing MP4 up to 90 MiB. Use prepare-video for other formats.`
|
|
132
|
+
);
|
|
133
|
+
const account = chooseAccount(accounts, item.account || options.account, index);
|
|
134
|
+
const privacy = item.privacy || options.privacy || "private";
|
|
135
|
+
if (!["private", "public", "unlisted"].includes(privacy))
|
|
136
|
+
throw new CliError(`Plan item ${index}: invalid YouTube privacy.`);
|
|
137
|
+
if (
|
|
138
|
+
account.platform === "TIKTOK" &&
|
|
139
|
+
(!item.tiktokSettings ||
|
|
140
|
+
typeof item.tiktokSettings.privacy !== "string" ||
|
|
141
|
+
["allowComments", "allowDuet", "allowStitch"].some(
|
|
142
|
+
(key) => typeof item.tiktokSettings[key] !== "boolean"
|
|
143
|
+
))
|
|
144
|
+
)
|
|
145
|
+
throw new CliError(
|
|
146
|
+
`Plan item ${index}: TikTok needs explicit tiktokSettings (privacy, allowComments, allowDuet, allowStitch), reviewed against creator settings.`
|
|
147
|
+
);
|
|
148
|
+
if (account.platform === "PINTEREST" && !item.pinterestSettings?.boardIds?.[account.id])
|
|
149
|
+
throw new CliError(
|
|
150
|
+
`Plan item ${index}: choose the Pinterest board in pinterestSettings.boardIds.`
|
|
151
|
+
);
|
|
152
|
+
const tags = (item.tags || []).map((tag) => tag.trim());
|
|
153
|
+
const description = item.description || "";
|
|
154
|
+
const content =
|
|
155
|
+
account.platform === "YOUTUBE"
|
|
156
|
+
? description
|
|
157
|
+
: [
|
|
158
|
+
description,
|
|
159
|
+
tags.map((tag) => `#${tag.replace(/^#/, "").replace(/\s+/g, "")}`).join(" "),
|
|
160
|
+
]
|
|
161
|
+
.filter(Boolean)
|
|
162
|
+
.join("\n\n");
|
|
163
|
+
const max = { TWITTER: 280, BLUESKY: 300, THREADS: 500 }[account.platform] || 5000;
|
|
164
|
+
if ([...content].length > max)
|
|
165
|
+
throw new CliError(
|
|
166
|
+
`Plan item ${index}: description and tags exceed ${account.platform}'s ${max}-character local limit.`
|
|
167
|
+
);
|
|
168
|
+
prepared.push({
|
|
169
|
+
video,
|
|
170
|
+
title: item.title,
|
|
171
|
+
description,
|
|
172
|
+
tags,
|
|
173
|
+
scheduledAt: item.scheduledAt,
|
|
174
|
+
accountId: account.id,
|
|
175
|
+
platform: account.platform,
|
|
176
|
+
privacy,
|
|
177
|
+
content,
|
|
178
|
+
settings: Object.fromEntries(
|
|
179
|
+
[
|
|
180
|
+
"tiktokSettings",
|
|
181
|
+
"pinterestSettings",
|
|
182
|
+
"facebookSettings",
|
|
183
|
+
"instagramPostType",
|
|
184
|
+
"instagramCaption",
|
|
185
|
+
]
|
|
186
|
+
.filter((key) => item[key] !== undefined)
|
|
187
|
+
.map((key) => [key, item[key]])
|
|
188
|
+
),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const hashed = [];
|
|
192
|
+
for (const item of prepared) {
|
|
193
|
+
const hash = createHash("sha256");
|
|
194
|
+
for await (const chunk of createReadStream(item.video)) hash.update(chunk);
|
|
195
|
+
hashed.push({ ...item, sha256: hash.digest("hex") });
|
|
196
|
+
}
|
|
197
|
+
const digest = createHash("sha256").update(JSON.stringify(hashed)).digest("hex");
|
|
198
|
+
const root = options["idempotency-key"] || `plan-${digest}`;
|
|
199
|
+
if (!/^[\w.:-]{8,150}$/.test(root))
|
|
200
|
+
throw new CliError("Plan idempotency key must be 8-150 safe characters.");
|
|
201
|
+
const journal = resolve(
|
|
202
|
+
dirname(location),
|
|
203
|
+
`${basename(location)}.postpilot-${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`
|
|
204
|
+
);
|
|
205
|
+
let state = { planId: root, digest, preparedPosts: [] };
|
|
206
|
+
try {
|
|
207
|
+
state = JSON.parse(await readFile(journal, "utf8"));
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (error.code !== "ENOENT")
|
|
210
|
+
throw new CliError("Plan checkpoint cannot be read. Inspect it before retrying.");
|
|
211
|
+
}
|
|
212
|
+
if (
|
|
213
|
+
state.planId !== root ||
|
|
214
|
+
state.digest !== digest ||
|
|
215
|
+
!Array.isArray(state.preparedPosts) ||
|
|
216
|
+
state.preparedPosts.some(
|
|
217
|
+
(post, i) =>
|
|
218
|
+
!post.postId ||
|
|
219
|
+
post.accountId !== prepared[i]?.accountId ||
|
|
220
|
+
post.scheduledAt !== prepared[i]?.scheduledAt
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
throw new CliError(
|
|
224
|
+
"This plan key or checkpoint belongs to different arguments. Choose a new key only for an intentionally new plan."
|
|
225
|
+
);
|
|
226
|
+
const drafts = [...state.preparedPosts];
|
|
227
|
+
async function saveState() {
|
|
228
|
+
const temporary = `${journal}.${randomUUID()}.tmp`;
|
|
229
|
+
await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
|
|
230
|
+
await rename(temporary, journal);
|
|
231
|
+
}
|
|
232
|
+
if (state.approvalId) {
|
|
233
|
+
const status = await client.tool("approval_status", { approvalId: state.approvalId });
|
|
234
|
+
if (["EXPIRED", "FAILED", "PARTIALLY_FAILED", "CANCELED"].includes(status.status))
|
|
235
|
+
throw new CliError(
|
|
236
|
+
"This batch ended or expired. Inspect per-post results before preparing only the intended retries with a new plan key.",
|
|
237
|
+
"CONFLICT",
|
|
238
|
+
{ approvalId: state.approvalId, result: status }
|
|
239
|
+
);
|
|
240
|
+
return {
|
|
241
|
+
...status,
|
|
242
|
+
approvalUrl: state.approvalUrl,
|
|
243
|
+
alreadyPrepared: true,
|
|
244
|
+
planId: root,
|
|
245
|
+
preparedPosts: drafts,
|
|
246
|
+
dryRun: !options.yes,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
const capacity = await client.tool("plan_validate", {
|
|
250
|
+
items: prepared.map((item, i) => ({
|
|
251
|
+
accountId: item.accountId,
|
|
252
|
+
scheduledAt: item.scheduledAt,
|
|
253
|
+
title: item.title,
|
|
254
|
+
...(drafts[i] ? { postId: drafts[i].postId } : {}),
|
|
255
|
+
})),
|
|
256
|
+
});
|
|
257
|
+
if (capacity.allowed === false || capacity.validated !== true)
|
|
258
|
+
throw new CliError("The server did not validate this plan. No uploads or drafts were created.");
|
|
259
|
+
if (!options.yes)
|
|
260
|
+
return {
|
|
261
|
+
dryRun: true,
|
|
262
|
+
validated: true,
|
|
263
|
+
requiresYes: true,
|
|
264
|
+
planId: root,
|
|
265
|
+
message:
|
|
266
|
+
"No uploads, drafts or schedules created. Add --yes to upload, create drafts and schedule this plan.",
|
|
267
|
+
items: prepared.map(({ video, title, accountId, scheduledAt }) => ({
|
|
268
|
+
video,
|
|
269
|
+
title,
|
|
270
|
+
accountId,
|
|
271
|
+
scheduledAt,
|
|
272
|
+
})),
|
|
273
|
+
capacity,
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
for (const [index, item] of hashed.entries()) {
|
|
278
|
+
if (drafts[index]) continue;
|
|
279
|
+
const upload = await retryUpload(() => client.upload(item.video, `${root}.upload.${index}`));
|
|
280
|
+
if (upload.sha256 && upload.sha256 !== item.sha256)
|
|
281
|
+
throw new CliError(
|
|
282
|
+
`Plan item ${index + 1}: video changed after plan validation. Review the file before retrying.`
|
|
283
|
+
);
|
|
284
|
+
const assetId = upload.uploadSessionId || upload.sessionId || upload.id;
|
|
285
|
+
if (!assetId)
|
|
286
|
+
throw new CliError(
|
|
287
|
+
`Plan item ${index + 1}: upload did not return an asset ID.`,
|
|
288
|
+
"INTERNAL_FAILURE"
|
|
289
|
+
);
|
|
290
|
+
const draft = await client.tool("post_create_draft", {
|
|
291
|
+
post: {
|
|
292
|
+
content: item.content,
|
|
293
|
+
videoTitle: item.title,
|
|
294
|
+
videoDescription: item.description,
|
|
295
|
+
videoTags: item.tags,
|
|
296
|
+
youtubePrivacyStatus: item.privacy,
|
|
297
|
+
platformTargets: [item.platform],
|
|
298
|
+
selectedAccountIds: [item.accountId],
|
|
299
|
+
uploadSessionId: assetId,
|
|
300
|
+
mediaType: "VIDEO",
|
|
301
|
+
...item.settings,
|
|
302
|
+
},
|
|
303
|
+
idempotencyKey: `${root}.draft.${index}`,
|
|
304
|
+
});
|
|
305
|
+
if (!draft.id || draft.status !== "DRAFT")
|
|
306
|
+
throw new CliError(
|
|
307
|
+
`Plan item ${index + 1}: draft creation is incomplete. Inspect the operation before retrying.`,
|
|
308
|
+
"INTERNAL_FAILURE"
|
|
309
|
+
);
|
|
310
|
+
drafts.push({ postId: draft.id, accountId: item.accountId, scheduledAt: item.scheduledAt });
|
|
311
|
+
state.preparedPosts = drafts;
|
|
312
|
+
await saveState();
|
|
313
|
+
}
|
|
314
|
+
const approval = await client.tool("post_schedule_batch", {
|
|
315
|
+
items: drafts,
|
|
316
|
+
idempotencyKey: `${root}.approval`,
|
|
317
|
+
});
|
|
318
|
+
if (!approval.approvalId || !["SUCCEEDED", "PENDING_APPROVAL", "PARTIALLY_FAILED", "FAILED"].includes(approval.status) || (approval.status === "PENDING_APPROVAL" && !approval.approvalUrl))
|
|
319
|
+
throw new CliError(
|
|
320
|
+
"Batch did not return a completed operation or optional review link. Inspect the operation before retrying.",
|
|
321
|
+
"INTERNAL_FAILURE"
|
|
322
|
+
);
|
|
323
|
+
Object.assign(state, { approvalId: approval.approvalId, approvalUrl: approval.approvalUrl });
|
|
324
|
+
await saveState();
|
|
325
|
+
if (["PARTIALLY_FAILED", "FAILED"].includes(approval.status))
|
|
326
|
+
throw new CliError("Some plan items failed. Inspect results before retrying failed destinations only.", "CONFLICT", { result: approval });
|
|
327
|
+
return { ...approval, planId: root, preparedPosts: drafts };
|
|
328
|
+
} catch (error) {
|
|
329
|
+
if (error instanceof CliError)
|
|
330
|
+
Object.assign(error.details, { planId: root, preparedPosts: drafts });
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
}
|