ampost-cli 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +214 -2
- package/dist/bin.js +9 -0
- package/dist/cli.js +214 -0
- package/dist/commands/accounts.js +92 -0
- package/dist/commands/analytics.js +110 -0
- package/dist/commands/auth.js +106 -0
- package/dist/commands/import-csv.js +67 -0
- package/dist/commands/index.js +43 -0
- package/dist/commands/posts.js +432 -0
- package/dist/commands/shared.js +104 -0
- package/dist/commands/webhooks.js +201 -0
- package/dist/config.js +76 -0
- package/dist/errors.js +144 -0
- package/dist/format.js +78 -0
- package/dist/io.js +50 -0
- package/package.json +55 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { Ampost, AuthenticationError, PermissionDeniedError } from "ampost";
|
|
2
|
+
import { configPath, deleteConfig, maskKey, readConfig, resolveCredentials, writeConfig } from "../config.js";
|
|
3
|
+
import { CliError, EXIT, UsageError } from "../errors.js";
|
|
4
|
+
import { fields } from "../format.js";
|
|
5
|
+
import { flag } from "./shared.js";
|
|
6
|
+
export const login = {
|
|
7
|
+
name: "login",
|
|
8
|
+
summary: "Save an API key in your config directory",
|
|
9
|
+
options: {
|
|
10
|
+
"no-verify": { type: "boolean", help: "Save the key without checking it against the API" },
|
|
11
|
+
},
|
|
12
|
+
help: `Reads the key from a hidden prompt, or from stdin when stdin is not a terminal:
|
|
13
|
+
|
|
14
|
+
ampost login
|
|
15
|
+
printf '%s' "$AMPOST_API_KEY" | ampost login
|
|
16
|
+
|
|
17
|
+
Create a key at https://ampost.io/app/settings/api-keys?ref=cli. The key is stored, readable by
|
|
18
|
+
you only, in config.json in the ampost config directory (~/.config/ampost on Linux, ~/Library/Application
|
|
19
|
+
Support/ampost on macOS, %APPDATA%\\ampost on Windows; AMPOST_CONFIG_DIR overrides it).
|
|
20
|
+
AMPOST_API_KEY, when set, is used instead of the stored key.`,
|
|
21
|
+
async run(ctx, input) {
|
|
22
|
+
const { io, env } = ctx.deps;
|
|
23
|
+
const raw = io.stdinIsTTY ? await io.promptSecret("Ampost API key: ") : await io.readStdin();
|
|
24
|
+
const apiKey = raw.trim();
|
|
25
|
+
if (!apiKey)
|
|
26
|
+
throw new UsageError("No API key given");
|
|
27
|
+
if (/\s/.test(apiKey))
|
|
28
|
+
throw new UsageError("The API key contains spaces: paste only the key");
|
|
29
|
+
const baseUrl = env.AMPOST_BASE_URL || undefined;
|
|
30
|
+
let verified = false;
|
|
31
|
+
let warning;
|
|
32
|
+
if (!flag(input, "no-verify")) {
|
|
33
|
+
const client = new Ampost({
|
|
34
|
+
apiKey,
|
|
35
|
+
...(baseUrl && { baseUrl }),
|
|
36
|
+
...(ctx.deps.fetch && { fetch: ctx.deps.fetch }),
|
|
37
|
+
});
|
|
38
|
+
try {
|
|
39
|
+
// Any key may call it unless its scopes leave out posts:read; a 403 still proves the key is real.
|
|
40
|
+
await client.platforms.list({ limit: 1 });
|
|
41
|
+
verified = true;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error instanceof AuthenticationError) {
|
|
45
|
+
throw new CliError("The API refused this key: it is wrong or revoked. Nothing was saved.", EXIT.AUTH, error.code);
|
|
46
|
+
}
|
|
47
|
+
if (!(error instanceof PermissionDeniedError))
|
|
48
|
+
throw error;
|
|
49
|
+
verified = true;
|
|
50
|
+
warning = "The key is valid but lacks the posts:read scope; some commands will fail with exit code 4.";
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const path = await writeConfig(env, { apiKey, ...(baseUrl && { baseUrl }) });
|
|
54
|
+
const lines = [`Saved ${maskKey(apiKey)} to ${path}`];
|
|
55
|
+
if (warning)
|
|
56
|
+
lines.push(warning);
|
|
57
|
+
if (env.AMPOST_API_KEY && env.AMPOST_API_KEY !== apiKey) {
|
|
58
|
+
lines.push("Note: AMPOST_API_KEY is set in this shell and is used instead of the saved key.");
|
|
59
|
+
}
|
|
60
|
+
return { data: { saved: true, verified, path, key: maskKey(apiKey), ...(baseUrl && { baseUrl }) }, text: lines.join("\n") };
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
export const logout = {
|
|
64
|
+
name: "logout",
|
|
65
|
+
summary: "Delete the saved API key",
|
|
66
|
+
async run(ctx) {
|
|
67
|
+
const { env } = ctx.deps;
|
|
68
|
+
const removed = await deleteConfig(env);
|
|
69
|
+
const lines = [removed ? `Deleted the key saved in ${configPath(env)}` : "No key was saved."];
|
|
70
|
+
if (env.AMPOST_API_KEY)
|
|
71
|
+
lines.push("AMPOST_API_KEY is still set in this shell.");
|
|
72
|
+
return { data: { removed, path: configPath(env) }, text: lines.join("\n") };
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
export const status = {
|
|
76
|
+
name: "status",
|
|
77
|
+
summary: "Show which API key is used, without calling the API",
|
|
78
|
+
async run(ctx) {
|
|
79
|
+
const { env } = ctx.deps;
|
|
80
|
+
const credentials = await resolveCredentials(env);
|
|
81
|
+
const saved = await readConfig(env);
|
|
82
|
+
const data = {
|
|
83
|
+
authenticated: Boolean(credentials),
|
|
84
|
+
source: credentials?.source ?? null,
|
|
85
|
+
key: credentials ? maskKey(credentials.apiKey) : null,
|
|
86
|
+
baseUrl: credentials?.baseUrl ?? "https://api.ampost.io",
|
|
87
|
+
configPath: configPath(env),
|
|
88
|
+
savedKey: saved.apiKey ? maskKey(saved.apiKey) : null,
|
|
89
|
+
};
|
|
90
|
+
if (!credentials) {
|
|
91
|
+
return {
|
|
92
|
+
data,
|
|
93
|
+
text: "Not logged in. Run `ampost login`, or set AMPOST_API_KEY.",
|
|
94
|
+
exitCode: EXIT.AUTH,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
data,
|
|
99
|
+
text: fields([
|
|
100
|
+
["Key", data.key],
|
|
101
|
+
["From", credentials.source === "env" ? "AMPOST_API_KEY" : data.configPath],
|
|
102
|
+
["API", data.baseUrl],
|
|
103
|
+
]),
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { EXIT, UsageError } from "../errors.js";
|
|
3
|
+
import { date, table } from "../format.js";
|
|
4
|
+
import { flag, string } from "./shared.js";
|
|
5
|
+
export const importCsv = {
|
|
6
|
+
name: "import-csv",
|
|
7
|
+
summary: "Create many posts from a CSV file (one post per row)",
|
|
8
|
+
args: "<file.csv | ->",
|
|
9
|
+
positionals: { min: 1, max: 1 },
|
|
10
|
+
options: {
|
|
11
|
+
"dry-run": { type: "boolean", help: "Check every row; create nothing" },
|
|
12
|
+
"idempotency-key": { type: "string", value: "KEY", help: "Run the same import again with the same key: no duplicates" },
|
|
13
|
+
},
|
|
14
|
+
help: `Columns: text, platforms (space-separated) or accountIds, platformSetId, scheduledFor or useQueue
|
|
15
|
+
(neither: a draft), linkUrl, firstComment, media (space-separated https URLs), altText,
|
|
16
|
+
text_<platform> and tiktok_<option>. The dashboard's CSV export imports again as it is.
|
|
17
|
+
Column reference: https://ampost.io/docs?ref=cli#posts
|
|
18
|
+
|
|
19
|
+
A bad row does not stop the others. Exit code 6 when any row has an error.
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
ampost import-csv week.csv --dry-run
|
|
23
|
+
ampost import-csv week.csv --idempotency-key "week-48"`,
|
|
24
|
+
async run(ctx, input) {
|
|
25
|
+
const [path] = input.positionals;
|
|
26
|
+
let csv;
|
|
27
|
+
if (path === "-") {
|
|
28
|
+
if (ctx.deps.io.stdinIsTTY)
|
|
29
|
+
throw new UsageError("Reading the CSV from stdin, but stdin is a terminal: pipe the file in");
|
|
30
|
+
csv = await ctx.deps.io.readStdin();
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
try {
|
|
34
|
+
csv = await readFile(path, "utf8");
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
throw new UsageError(`Cannot read ${path}: ${error.code ?? error.message}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (!csv.trim())
|
|
41
|
+
throw new UsageError(`${path === "-" ? "stdin" : path} is empty`);
|
|
42
|
+
const client = await ctx.client();
|
|
43
|
+
const key = string(input, "idempotency-key");
|
|
44
|
+
const result = await client.posts.importCsv({ csv, dryRun: flag(input, "dry-run") }, key ? { idempotencyKey: key } : {});
|
|
45
|
+
return { data: result, text: importText(result), exitCode: result.summary.errors > 0 ? EXIT.INVALID : EXIT.OK };
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
function importText(result) {
|
|
49
|
+
const { summary } = result;
|
|
50
|
+
const lines = [
|
|
51
|
+
result.dryRun
|
|
52
|
+
? `Dry run: ${summary.rows} rows, ${summary.valid} valid, ${summary.errors} with errors. Nothing was created.`
|
|
53
|
+
: `Imported: ${summary.rows} rows, ${summary.created} posts created, ${summary.errors} with errors.`,
|
|
54
|
+
];
|
|
55
|
+
for (const warning of result.warnings)
|
|
56
|
+
lines.push(`warning: ${warning.column}: ${warning.message}`);
|
|
57
|
+
const failed = result.rows.filter((row) => row.status === "error");
|
|
58
|
+
if (failed.length) {
|
|
59
|
+
const rows = failed.flatMap((row) => row.errors.map((error) => [row.row, error.column ?? "", `${error.message} (${error.code})`]));
|
|
60
|
+
lines.push("", table(["row", "column", "error"], rows));
|
|
61
|
+
}
|
|
62
|
+
const created = result.rows.filter((row) => row.status === "created");
|
|
63
|
+
if (created.length) {
|
|
64
|
+
lines.push("", table(["row", "post", "scheduled"], created.map((row) => [row.row, row.postId, date(row.scheduledFor)])));
|
|
65
|
+
}
|
|
66
|
+
return lines.join("\n");
|
|
67
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { accountsDisconnect, accountsGet, accountsList, platformSetsList } from "./accounts.js";
|
|
2
|
+
import { analyticsFollowers, analyticsOverview, analyticsPosts } from "./analytics.js";
|
|
3
|
+
import { login, logout, status } from "./auth.js";
|
|
4
|
+
import { importCsv } from "./import-csv.js";
|
|
5
|
+
import { post, postsDelete, postsEditPublished, postsGet, postsList, postsPublish, postsRetry, postsUnpublish } from "./posts.js";
|
|
6
|
+
import { webhooksCreate, webhooksDeliveries, webhooksDelete, webhooksGet, webhooksList, webhooksTest, webhooksUpdate, } from "./webhooks.js";
|
|
7
|
+
/** In the order `ampost --help` lists them. */
|
|
8
|
+
export const COMMANDS = [
|
|
9
|
+
login,
|
|
10
|
+
logout,
|
|
11
|
+
status,
|
|
12
|
+
accountsList,
|
|
13
|
+
accountsGet,
|
|
14
|
+
accountsDisconnect,
|
|
15
|
+
platformSetsList,
|
|
16
|
+
post,
|
|
17
|
+
postsList,
|
|
18
|
+
postsGet,
|
|
19
|
+
postsPublish,
|
|
20
|
+
postsRetry,
|
|
21
|
+
postsDelete,
|
|
22
|
+
postsUnpublish,
|
|
23
|
+
postsEditPublished,
|
|
24
|
+
importCsv,
|
|
25
|
+
analyticsOverview,
|
|
26
|
+
analyticsPosts,
|
|
27
|
+
analyticsFollowers,
|
|
28
|
+
webhooksList,
|
|
29
|
+
webhooksGet,
|
|
30
|
+
webhooksCreate,
|
|
31
|
+
webhooksUpdate,
|
|
32
|
+
webhooksDelete,
|
|
33
|
+
webhooksTest,
|
|
34
|
+
webhooksDeliveries,
|
|
35
|
+
];
|
|
36
|
+
/** Command groups: `ampost <group>` alone prints the group's help. */
|
|
37
|
+
export const GROUPS = {
|
|
38
|
+
accounts: "connected social accounts",
|
|
39
|
+
"platform-sets": "platform sets (one account per platform each)",
|
|
40
|
+
posts: "list, read, publish, retry, discard, unpublish and edit published posts (create them with `ampost post`)",
|
|
41
|
+
analytics: "post metrics, account totals and followers",
|
|
42
|
+
webhooks: "send post and account events to your URL",
|
|
43
|
+
};
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { EXIT, UsageError } from "../errors.js";
|
|
4
|
+
import { date, fields, oneLine, pageNote, table } from "../format.js";
|
|
5
|
+
import { checkPlatform, fetchList, flag, id, integer, LIST_OPTIONS, list, oneOf, pageQuery, platform, repeated, string, } from "./shared.js";
|
|
6
|
+
const VIDEO_EXTENSIONS = ["mp4", "m4v", "mov", "webm"];
|
|
7
|
+
const POST_STATUSES = ["draft", "scheduled", "queued", "posting", "published", "partial", "failed", "discarded", "deleted"];
|
|
8
|
+
/** While a post is `posting` (or `queued`, about to post), `--wait` keeps checking. */
|
|
9
|
+
const WAIT_INTERVAL_MS = 3_000;
|
|
10
|
+
export const post = {
|
|
11
|
+
name: "post",
|
|
12
|
+
summary: "Create a post: publish now, schedule, queue or save a draft",
|
|
13
|
+
args: "[text]",
|
|
14
|
+
positionals: { min: 0, max: 1 },
|
|
15
|
+
options: {
|
|
16
|
+
platforms: { type: "string", short: "p", multiple: true, value: "LIST", help: "Platforms, comma-separated: bluesky,threads,x,..." },
|
|
17
|
+
"platform-set": { type: "string", multiple: true, value: "ID", help: "Platform set to post from (default: your default set)" },
|
|
18
|
+
"text-file": { type: "string", value: "PATH", help: "Read the text from a file, or - for stdin" },
|
|
19
|
+
media: { type: "string", short: "m", multiple: true, value: "PATH|URL", help: "Image or video: a local file (uploaded) or a public https URL" },
|
|
20
|
+
"alt-text": { type: "string", multiple: true, value: "TEXT", help: "Alt text for the media, in --media order" },
|
|
21
|
+
link: { type: "string", value: "URL", help: "Link to attach" },
|
|
22
|
+
"first-comment": { type: "string", value: "TEXT", help: "Comment posted right after the post (replies on X, Threads, Bluesky)" },
|
|
23
|
+
schedule: { type: "string", short: "s", value: "TIME", help: "Publish at this time, ISO 8601: 2026-12-01T09:00:00Z" },
|
|
24
|
+
queue: { type: "boolean", short: "q", help: "Schedule in the next free slot of the platform set's queue" },
|
|
25
|
+
draft: { type: "boolean", help: "Save as a draft; nothing publishes" },
|
|
26
|
+
"dry-run": { type: "boolean", help: "Check the post with the API's validator; create nothing" },
|
|
27
|
+
wait: { type: "boolean", short: "w", help: "When publishing now: wait for the result (exit 10 if a platform failed)" },
|
|
28
|
+
"wait-timeout": { type: "string", value: "SECONDS", help: "How long --wait waits (default 600)" },
|
|
29
|
+
metadata: { type: "string", value: "JSON", help: "Your own JSON object, returned on the post and in webhooks" },
|
|
30
|
+
"idempotency-key": { type: "string", value: "KEY", help: "Run the same command again with the same key: no duplicate post" },
|
|
31
|
+
},
|
|
32
|
+
help: `Without --schedule, --queue or --draft the post is published now.
|
|
33
|
+
|
|
34
|
+
Examples:
|
|
35
|
+
ampost post "Hello from the terminal" -p bluesky,threads
|
|
36
|
+
ampost post "Launch day" -p instagram,threads -m ./photo.jpg --alt-text "Our team" --schedule 2026-12-01T09:00:00Z
|
|
37
|
+
ampost post --text-file notes.md -p threads --queue
|
|
38
|
+
echo "Built by a script" | ampost post --text-file - -p bluesky --wait --json
|
|
39
|
+
ampost post "Check me" -p x,bluesky --dry-run
|
|
40
|
+
|
|
41
|
+
Local --media files are uploaded first, also with --dry-run, so the check covers them.
|
|
42
|
+
Platform rules (lengths, media types, first comments): https://ampost.io/docs?ref=cli#platforms`,
|
|
43
|
+
async run(ctx, input) {
|
|
44
|
+
const body = await buildPost(ctx, input);
|
|
45
|
+
const client = await ctx.client();
|
|
46
|
+
if (flag(input, "dry-run")) {
|
|
47
|
+
const validation = await client.posts.validate(body);
|
|
48
|
+
return { data: validation, text: validationText(validation), exitCode: validation.valid ? EXIT.OK : EXIT.INVALID };
|
|
49
|
+
}
|
|
50
|
+
const key = string(input, "idempotency-key");
|
|
51
|
+
const created = await client.posts.create(body, key ? { idempotencyKey: key } : {});
|
|
52
|
+
if (!flag(input, "wait"))
|
|
53
|
+
return { data: created, text: postText(created, "Created") };
|
|
54
|
+
return waitForPost(ctx, client, created, waitTimeout(input));
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
/** The `posts.create` body from the command line. Uploads local media. Exported for tests. */
|
|
58
|
+
export async function buildPost(ctx, input) {
|
|
59
|
+
const text = await readText(ctx, input, input.positionals[0], "an argument");
|
|
60
|
+
const platforms = list(input, "platforms").map(checkPlatform);
|
|
61
|
+
if (platforms.length === 0)
|
|
62
|
+
throw new UsageError("Choose platforms with -p, e.g. -p bluesky,threads");
|
|
63
|
+
const when = [flag(input, "draft") && "--draft", string(input, "schedule") !== undefined && "--schedule", flag(input, "queue") && "--queue"].filter(Boolean);
|
|
64
|
+
if (when.length > 1)
|
|
65
|
+
throw new UsageError(`Use only one of ${when.join(", ")}`);
|
|
66
|
+
if (flag(input, "wait") && when.length > 0)
|
|
67
|
+
throw new UsageError(`--wait works only when publishing now, not with ${when[0]}`);
|
|
68
|
+
if (flag(input, "wait") && flag(input, "dry-run"))
|
|
69
|
+
throw new UsageError("--wait does not work with --dry-run");
|
|
70
|
+
if (string(input, "wait-timeout") !== undefined && !flag(input, "wait"))
|
|
71
|
+
throw new UsageError("--wait-timeout needs --wait");
|
|
72
|
+
const sets = list(input, "platform-set").map((s) => id(s, "--platform-set"));
|
|
73
|
+
const targets = sets.length ? sets.map((platformSetId) => ({ platformSetId, platforms })) : [{ platforms }];
|
|
74
|
+
if (flag(input, "queue") && targets.length > 1)
|
|
75
|
+
throw new UsageError("--queue takes one --platform-set: each set has its own queue");
|
|
76
|
+
const sources = repeated(input, "media");
|
|
77
|
+
const altTexts = repeated(input, "alt-text");
|
|
78
|
+
if (altTexts.length > sources.length)
|
|
79
|
+
throw new UsageError(`${altTexts.length} --alt-text for ${sources.length} --media`);
|
|
80
|
+
if (!text && sources.length === 0)
|
|
81
|
+
throw new UsageError("Give the post text, --text-file or --media");
|
|
82
|
+
const link = string(input, "link");
|
|
83
|
+
if (link !== undefined && !/^https?:\/\//i.test(link))
|
|
84
|
+
throw new UsageError(`--link must be an http(s) URL, got ${JSON.stringify(link)}`);
|
|
85
|
+
const media = await resolveMedia(ctx, sources, altTexts);
|
|
86
|
+
const firstComment = string(input, "first-comment");
|
|
87
|
+
const metadata = parseMetadata(string(input, "metadata"));
|
|
88
|
+
return {
|
|
89
|
+
text,
|
|
90
|
+
targets,
|
|
91
|
+
...(media.length && { media }),
|
|
92
|
+
...(link !== undefined && { linkUrl: link }),
|
|
93
|
+
...(firstComment !== undefined && { firstComment }),
|
|
94
|
+
...(metadata && { metadata }),
|
|
95
|
+
...scheduleFields(input),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/** The text from `given` (the argument, or `--text`), `--text-file`, or stdin for `-`. */
|
|
99
|
+
async function readText(ctx, input, given, givenAs) {
|
|
100
|
+
const positional = given;
|
|
101
|
+
const file = string(input, "text-file");
|
|
102
|
+
if (positional !== undefined && file !== undefined)
|
|
103
|
+
throw new UsageError(`Give the text as ${givenAs} or with --text-file, not both`);
|
|
104
|
+
if (positional === "-" || file === "-") {
|
|
105
|
+
if (ctx.deps.io.stdinIsTTY)
|
|
106
|
+
throw new UsageError("Reading the text from stdin, but stdin is a terminal: pipe the text in");
|
|
107
|
+
return trimEnd(await ctx.deps.io.readStdin());
|
|
108
|
+
}
|
|
109
|
+
if (file !== undefined) {
|
|
110
|
+
try {
|
|
111
|
+
return trimEnd(await readFile(file, "utf8"));
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw new UsageError(`Cannot read --text-file ${file}: ${error.code ?? error.message}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return positional ?? "";
|
|
118
|
+
}
|
|
119
|
+
/** A file's or a pipe's final newline is not part of the post. */
|
|
120
|
+
function trimEnd(text) {
|
|
121
|
+
return text.replace(/\s+$/, "");
|
|
122
|
+
}
|
|
123
|
+
function scheduleFields(input) {
|
|
124
|
+
const schedule = string(input, "schedule");
|
|
125
|
+
if (schedule !== undefined) {
|
|
126
|
+
const at = parseTime(schedule);
|
|
127
|
+
return { scheduledFor: at };
|
|
128
|
+
}
|
|
129
|
+
if (flag(input, "queue"))
|
|
130
|
+
return { useQueue: true };
|
|
131
|
+
if (flag(input, "draft"))
|
|
132
|
+
return {};
|
|
133
|
+
return { publishNow: true };
|
|
134
|
+
}
|
|
135
|
+
/** ISO 8601. Without an offset the time is the machine's local time, as `new Date()` reads it. */
|
|
136
|
+
export function parseTime(value) {
|
|
137
|
+
if (!/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/i.test(value.trim())) {
|
|
138
|
+
throw new UsageError(`--schedule must be an ISO 8601 time like 2026-12-01T09:00:00Z, got ${JSON.stringify(value)}`);
|
|
139
|
+
}
|
|
140
|
+
const normalized = value.trim().replace(" ", "T");
|
|
141
|
+
// A date alone would be read as UTC midnight; ask for a time instead of guessing.
|
|
142
|
+
if (!normalized.includes("T"))
|
|
143
|
+
throw new UsageError(`--schedule needs a time too, e.g. ${normalized}T09:00:00Z`);
|
|
144
|
+
const at = new Date(normalized);
|
|
145
|
+
if (Number.isNaN(at.getTime()))
|
|
146
|
+
throw new UsageError(`--schedule is not a valid time: ${JSON.stringify(value)}`);
|
|
147
|
+
return at.toISOString();
|
|
148
|
+
}
|
|
149
|
+
function parseMetadata(value) {
|
|
150
|
+
if (value === undefined)
|
|
151
|
+
return undefined;
|
|
152
|
+
let parsed;
|
|
153
|
+
try {
|
|
154
|
+
parsed = JSON.parse(value);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
throw new UsageError("--metadata must be a JSON object, e.g. '{\"source\":\"cron\"}'");
|
|
158
|
+
}
|
|
159
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
160
|
+
throw new UsageError("--metadata must be a JSON object");
|
|
161
|
+
return parsed;
|
|
162
|
+
}
|
|
163
|
+
async function resolveMedia(ctx, sources, altTexts) {
|
|
164
|
+
// Check every local file before uploading any.
|
|
165
|
+
const kinds = await Promise.all(sources.map((source) => mediaKind(source)));
|
|
166
|
+
const media = [];
|
|
167
|
+
for (const [i, source] of sources.entries()) {
|
|
168
|
+
const altText = altTexts[i] ? { altText: altTexts[i] } : {};
|
|
169
|
+
if (kinds[i] === "url") {
|
|
170
|
+
media.push({ url: source, type: guessType(source), ...altText });
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
ctx.progress(`Uploading ${source} ...`);
|
|
174
|
+
const client = await ctx.client();
|
|
175
|
+
const uploaded = await client.media.upload(resolve(source));
|
|
176
|
+
media.push({ ...uploaded, ...altText });
|
|
177
|
+
}
|
|
178
|
+
return media;
|
|
179
|
+
}
|
|
180
|
+
async function mediaKind(source) {
|
|
181
|
+
if (/^https:\/\//i.test(source))
|
|
182
|
+
return "url";
|
|
183
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(source))
|
|
184
|
+
throw new UsageError(`--media URLs must be https: ${source}`);
|
|
185
|
+
try {
|
|
186
|
+
const info = await stat(source);
|
|
187
|
+
if (!info.isFile())
|
|
188
|
+
throw new UsageError(`--media ${source} is not a file`);
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error instanceof UsageError)
|
|
192
|
+
throw error;
|
|
193
|
+
throw new UsageError(`--media ${source}: no such file`);
|
|
194
|
+
}
|
|
195
|
+
return "file";
|
|
196
|
+
}
|
|
197
|
+
/** The CSV import's rule: these extensions are videos, the rest images. */
|
|
198
|
+
export function guessType(url) {
|
|
199
|
+
const path = url.split(/[?#]/)[0] ?? "";
|
|
200
|
+
const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase();
|
|
201
|
+
return extension && VIDEO_EXTENSIONS.includes(extension) ? "video" : "image";
|
|
202
|
+
}
|
|
203
|
+
function waitTimeout(input) {
|
|
204
|
+
return (integer(input, "wait-timeout", 1, 86_400) ?? 600) * 1000;
|
|
205
|
+
}
|
|
206
|
+
/** Polls the post until it is no longer `posting`. Exit 0 when published, 10 when it failed anywhere. */
|
|
207
|
+
async function waitForPost(ctx, client, first, timeoutMs) {
|
|
208
|
+
let current = first;
|
|
209
|
+
const deadline = Date.now() + timeoutMs;
|
|
210
|
+
ctx.progress(`Created ${first.id}; waiting for the platforms ...`);
|
|
211
|
+
while (current.status === "posting" || current.status === "queued") {
|
|
212
|
+
if (Date.now() + WAIT_INTERVAL_MS > deadline) {
|
|
213
|
+
ctx.progress(`Still ${current.status} after ${Math.round(timeoutMs / 1000)} s: check later with \`ampost posts get ${current.id}\``);
|
|
214
|
+
return { data: current, text: postText(current, "Still publishing"), exitCode: EXIT.ERROR };
|
|
215
|
+
}
|
|
216
|
+
await ctx.deps.sleep(WAIT_INTERVAL_MS);
|
|
217
|
+
current = await client.posts.get(current.id);
|
|
218
|
+
}
|
|
219
|
+
return { data: current, text: postText(current), exitCode: postExitCode(current) };
|
|
220
|
+
}
|
|
221
|
+
function postExitCode(p) {
|
|
222
|
+
return p.status === "failed" || p.status === "partial" ? EXIT.POST_FAILED : EXIT.OK;
|
|
223
|
+
}
|
|
224
|
+
/** `refused` names what a notice means for the account (default: it is still in its status). */
|
|
225
|
+
export function postText(p, heading, refused) {
|
|
226
|
+
const head = fields([
|
|
227
|
+
["Post", heading ? `${p.id} (${heading.toLowerCase()})` : p.id],
|
|
228
|
+
["Status", p.status],
|
|
229
|
+
["Scheduled", p.scheduledFor ? date(p.scheduledFor) : undefined],
|
|
230
|
+
["Created", date(p.createdAt)],
|
|
231
|
+
["Text", oneLine(p.text, 72)],
|
|
232
|
+
["Media", p.media.length ? `${p.media.length} file${p.media.length === 1 ? "" : "s"}` : undefined],
|
|
233
|
+
["Link", p.linkUrl],
|
|
234
|
+
["First comment", p.firstComment ? oneLine(p.firstComment, 60) : undefined],
|
|
235
|
+
]);
|
|
236
|
+
if (p.platformPosts.length === 0)
|
|
237
|
+
return head;
|
|
238
|
+
const rows = p.platformPosts.map((pp) => [
|
|
239
|
+
pp.platform,
|
|
240
|
+
pp.status,
|
|
241
|
+
pp.publishedUrl ?? (pp.error ? `${pp.error.code}: ${oneLine(pp.error.message, 60)}` : pp.nextAttemptAt ? `next try ${date(pp.nextAttemptAt)}` : ""),
|
|
242
|
+
pp.accountId,
|
|
243
|
+
]);
|
|
244
|
+
const notices = p.platformPosts
|
|
245
|
+
.filter((pp) => pp.notice)
|
|
246
|
+
.map((pp) => `${pp.platform}: ${refused ?? `still ${pp.status}`}. ${pp.notice.message} (${pp.notice.code})`);
|
|
247
|
+
return [`${head}\n\n${table(["platform", "status", "url or error", "account"], rows)}`, ...(notices.length ? ["", ...notices] : [])].join("\n");
|
|
248
|
+
}
|
|
249
|
+
function validationText(v) {
|
|
250
|
+
const lines = [v.valid ? "Valid: the post would be created." : "Invalid: the post would be refused."];
|
|
251
|
+
for (const e of v.errors)
|
|
252
|
+
lines.push(` error: ${e.message} (${e.code})`);
|
|
253
|
+
for (const w of v.warnings)
|
|
254
|
+
lines.push(` warning: ${w.message} (${w.code})`);
|
|
255
|
+
if (v.targets.length) {
|
|
256
|
+
const rows = v.targets.map((t) => [
|
|
257
|
+
t.platform,
|
|
258
|
+
t.valid ? "ok" : "invalid",
|
|
259
|
+
[...t.errors.map((e) => `error: ${e.message}`), ...t.warnings.map((w) => `warning: ${w.message}`)].join("; ") || "",
|
|
260
|
+
]);
|
|
261
|
+
lines.push("", table(["platform", "check", "issues"], rows));
|
|
262
|
+
}
|
|
263
|
+
if (v.scheduledFor)
|
|
264
|
+
lines.push("", `Would publish at ${date(v.scheduledFor)}`);
|
|
265
|
+
return lines.join("\n");
|
|
266
|
+
}
|
|
267
|
+
export const postsList = {
|
|
268
|
+
name: "posts list",
|
|
269
|
+
summary: "List posts, newest first",
|
|
270
|
+
options: {
|
|
271
|
+
status: { type: "string", value: "STATUS", help: POST_STATUSES.join(", ") },
|
|
272
|
+
platform: { type: "string", value: "NAME", help: "Only posts to this platform" },
|
|
273
|
+
"platform-set": { type: "string", value: "ID", help: "Only posts from this platform set" },
|
|
274
|
+
search: { type: "string", value: "TEXT", help: "Only posts whose text contains this" },
|
|
275
|
+
...LIST_OPTIONS,
|
|
276
|
+
},
|
|
277
|
+
help: `Examples:
|
|
278
|
+
ampost posts list --status failed
|
|
279
|
+
ampost posts list --all --json | jq -r '.data[] | select(.status == "scheduled") | .id'`,
|
|
280
|
+
async run(ctx, input) {
|
|
281
|
+
const setId = string(input, "platform-set");
|
|
282
|
+
const query = {
|
|
283
|
+
...pageQuery(input),
|
|
284
|
+
status: oneOf(input, "status", POST_STATUSES),
|
|
285
|
+
platform: platform(input),
|
|
286
|
+
platformSetId: setId === undefined ? undefined : id(setId, "--platform-set"),
|
|
287
|
+
search: string(input, "search"),
|
|
288
|
+
};
|
|
289
|
+
const client = await ctx.client();
|
|
290
|
+
const result = await fetchList(client.posts.list(query), input);
|
|
291
|
+
if (result.data.length === 0)
|
|
292
|
+
return { data: result, text: "No posts." };
|
|
293
|
+
const rows = result.data.map((p) => [
|
|
294
|
+
p.id,
|
|
295
|
+
p.status,
|
|
296
|
+
date(p.scheduledFor ?? p.createdAt),
|
|
297
|
+
p.platformPosts.map((pp) => `${pp.platform}:${pp.status}`).join(" ") || p.platforms.join(" "),
|
|
298
|
+
oneLine(p.text, 40),
|
|
299
|
+
]);
|
|
300
|
+
return {
|
|
301
|
+
data: result,
|
|
302
|
+
text: `${table(["id", "status", "scheduled/created", "platforms", "text"], rows)}\n\n${pageNote(result.pagination, result.data.length, "post")}`,
|
|
303
|
+
};
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
export const postsGet = {
|
|
307
|
+
name: "posts get",
|
|
308
|
+
summary: "Show a post and its status on each platform",
|
|
309
|
+
args: "<post-id>",
|
|
310
|
+
positionals: { min: 1, max: 1 },
|
|
311
|
+
async run(ctx, input) {
|
|
312
|
+
const client = await ctx.client();
|
|
313
|
+
const p = await client.posts.get(id(input.positionals[0], "The post id"));
|
|
314
|
+
return { data: p, text: postText(p), exitCode: EXIT.OK };
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
export const postsPublish = {
|
|
318
|
+
name: "posts publish",
|
|
319
|
+
summary: "Publish a draft or scheduled post now",
|
|
320
|
+
args: "<post-id>",
|
|
321
|
+
positionals: { min: 1, max: 1 },
|
|
322
|
+
options: {
|
|
323
|
+
wait: { type: "boolean", short: "w", help: "Wait for the result (exit 10 if a platform failed)" },
|
|
324
|
+
"wait-timeout": { type: "string", value: "SECONDS", help: "How long --wait waits (default 600)" },
|
|
325
|
+
"idempotency-key": { type: "string", value: "KEY", help: "Repeat the command safely with the same key" },
|
|
326
|
+
},
|
|
327
|
+
async run(ctx, input) {
|
|
328
|
+
const postId = id(input.positionals[0], "The post id");
|
|
329
|
+
if (string(input, "wait-timeout") !== undefined && !flag(input, "wait"))
|
|
330
|
+
throw new UsageError("--wait-timeout needs --wait");
|
|
331
|
+
const client = await ctx.client();
|
|
332
|
+
const key = string(input, "idempotency-key");
|
|
333
|
+
const published = await client.posts.publish(postId, key ? { idempotencyKey: key } : {});
|
|
334
|
+
if (!flag(input, "wait"))
|
|
335
|
+
return { data: published, text: postText(published, "Publishing") };
|
|
336
|
+
return waitForPost(ctx, client, published, waitTimeout(input));
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
export const postsRetry = {
|
|
340
|
+
name: "posts retry",
|
|
341
|
+
summary: "Publish again to the accounts that failed",
|
|
342
|
+
args: "<post-id>",
|
|
343
|
+
positionals: { min: 1, max: 1 },
|
|
344
|
+
options: {
|
|
345
|
+
account: { type: "string", multiple: true, value: "ID", help: "Retry only this account (default: every failed one)" },
|
|
346
|
+
wait: { type: "boolean", short: "w", help: "Wait for the result (exit 10 if a platform failed again)" },
|
|
347
|
+
"wait-timeout": { type: "string", value: "SECONDS", help: "How long --wait waits (default 600)" },
|
|
348
|
+
"idempotency-key": { type: "string", value: "KEY", help: "Repeat the command safely with the same key" },
|
|
349
|
+
},
|
|
350
|
+
async run(ctx, input) {
|
|
351
|
+
const postId = id(input.positionals[0], "The post id");
|
|
352
|
+
const accountIds = list(input, "account").map((a) => id(a, "--account"));
|
|
353
|
+
if (string(input, "wait-timeout") !== undefined && !flag(input, "wait"))
|
|
354
|
+
throw new UsageError("--wait-timeout needs --wait");
|
|
355
|
+
const client = await ctx.client();
|
|
356
|
+
const key = string(input, "idempotency-key");
|
|
357
|
+
const retried = await client.posts.retry(postId, accountIds.length ? { accountIds } : {}, key ? { idempotencyKey: key } : {});
|
|
358
|
+
if (!flag(input, "wait"))
|
|
359
|
+
return { data: retried, text: postText(retried, "Retrying") };
|
|
360
|
+
return waitForPost(ctx, client, retried, waitTimeout(input));
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
export const postsDelete = {
|
|
364
|
+
name: "posts delete",
|
|
365
|
+
summary: "Discard a post before it publishes: a draft, scheduled, queued or failed post",
|
|
366
|
+
args: "<post-id>",
|
|
367
|
+
positionals: { min: 1, max: 1 },
|
|
368
|
+
help: "The post stays readable with status `discarded`, and its uploaded media is deleted. A partly\npublished post stops retrying; what went out stays. A published post cannot be discarded (exit 7):\ntake it down with `ampost posts unpublish`.",
|
|
369
|
+
async run(ctx, input) {
|
|
370
|
+
const client = await ctx.client();
|
|
371
|
+
const discarded = await client.posts.delete(id(input.positionals[0], "The post id"));
|
|
372
|
+
return { data: discarded, text: postText(discarded, "Discarded") };
|
|
373
|
+
},
|
|
374
|
+
};
|
|
375
|
+
export const postsUnpublish = {
|
|
376
|
+
name: "posts unpublish",
|
|
377
|
+
summary: "Delete a published post from the platforms",
|
|
378
|
+
args: "<post-id>",
|
|
379
|
+
positionals: { min: 1, max: 1 },
|
|
380
|
+
options: {
|
|
381
|
+
account: { type: "string", multiple: true, value: "ID", help: "Only this account (default: every account where it is published)" },
|
|
382
|
+
},
|
|
383
|
+
help: `Each account ends up \`deleted\`, or still \`published\` with a notice saying why: Instagram and
|
|
384
|
+
TikTok have no delete API (delete it in their app), or the platform refused (for example Telegram's
|
|
385
|
+
48-hour limit for bots). The post stays readable in Ampost; it becomes \`deleted\` once no account has it.
|
|
386
|
+
Exit 10 if any account still has it. YouTube deletes count in the channel's daily budget of edits and deletes.
|
|
387
|
+
|
|
388
|
+
Examples:
|
|
389
|
+
ampost posts unpublish <post-id>
|
|
390
|
+
ampost posts unpublish <post-id> --account <account-id> --json`,
|
|
391
|
+
async run(ctx, input) {
|
|
392
|
+
const postId = id(input.positionals[0], "The post id");
|
|
393
|
+
const accountIds = list(input, "account").map((a) => id(a, "--account"));
|
|
394
|
+
const client = await ctx.client();
|
|
395
|
+
const p = await client.posts.unpublish(postId, accountIds.length ? { accountIds } : {});
|
|
396
|
+
const targeted = p.platformPosts.filter((pp) => !accountIds.length || accountIds.includes(pp.accountId));
|
|
397
|
+
const left = targeted.some((pp) => pp.status === "published");
|
|
398
|
+
return { data: p, text: postText(p, "Unpublished"), exitCode: left ? EXIT.POST_FAILED : EXIT.OK };
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
export const postsEditPublished = {
|
|
402
|
+
name: "posts edit-published",
|
|
403
|
+
summary: "Replace the text of a published post on the platforms",
|
|
404
|
+
args: "<post-id>",
|
|
405
|
+
positionals: { min: 1, max: 1 },
|
|
406
|
+
options: {
|
|
407
|
+
text: { type: "string", value: "TEXT", help: "The new text" },
|
|
408
|
+
"text-file": { type: "string", value: "PATH", help: "Read the new text from a file, or - for stdin" },
|
|
409
|
+
account: { type: "string", multiple: true, value: "ID", help: "Only this account (default: every account where it is published)" },
|
|
410
|
+
},
|
|
411
|
+
help: `Text only: media and links stay. Each account's new text is in \`platformPosts[].text\`. An account
|
|
412
|
+
the platform refused keeps its text, with a notice saying why: Instagram, Threads, TikTok, Bluesky and
|
|
413
|
+
X have no edit API (EDIT_NOT_SUPPORTED), nor do Facebook stories, and Facebook edits only posts Ampost
|
|
414
|
+
published. Exit 10 if any account did not take the new text. YouTube edits count in the channel's
|
|
415
|
+
daily budget of edits and deletes. To change a draft or scheduled post, create it again or use the API.
|
|
416
|
+
|
|
417
|
+
Examples:
|
|
418
|
+
ampost posts edit-published <post-id> --text "Fixed the typo"
|
|
419
|
+
ampost posts edit-published <post-id> --text-file new.md --account <account-id> --json`,
|
|
420
|
+
async run(ctx, input) {
|
|
421
|
+
const postId = id(input.positionals[0], "The post id");
|
|
422
|
+
const accountIds = list(input, "account").map((a) => id(a, "--account"));
|
|
423
|
+
const text = await readText(ctx, input, string(input, "text"), "--text");
|
|
424
|
+
if (!text.trim())
|
|
425
|
+
throw new UsageError("Give the new text with --text or --text-file");
|
|
426
|
+
const client = await ctx.client();
|
|
427
|
+
const p = await client.posts.editPublished(postId, { text, ...(accountIds.length && { accountIds }) });
|
|
428
|
+
const targeted = p.platformPosts.filter((pp) => pp.status === "published" && (!accountIds.length || accountIds.includes(pp.accountId)));
|
|
429
|
+
const refused = targeted.some((pp) => pp.notice || pp.text !== text);
|
|
430
|
+
return { data: p, text: postText(p, "Edited", "not edited"), exitCode: refused ? EXIT.POST_FAILED : EXIT.OK };
|
|
431
|
+
},
|
|
432
|
+
};
|