@nuelink/nuelink-cli 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@nuelink/nuelink-cli",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "The official Nuelink CLI for automating social media workflows from your terminal. Schedule posts, upload media, manage brands, and integrate Nuelink into scripts, CI/CD pipelines, and AI agents.",
5
5
  "license": "MIT",
6
6
  "author": "Nuelink",
7
7
  "type": "module",
8
- "main": "./src/main.js",
8
+ "main": "./src/cli.js",
9
9
  "scripts": {
10
10
  "test": "node --test test/cli.test.mjs",
11
- "smoke:auth": "node src/main.js auth:status",
11
+ "smoke:auth": "node src/cli.js auth:status",
12
12
  "check:pack": "npm pack --dry-run"
13
13
  },
14
14
  "engines": {
@@ -28,6 +28,6 @@
28
28
  "commander": "^15.0.0"
29
29
  },
30
30
  "bin": {
31
- "nuelink-cli": "./src/main.js"
31
+ "nuelink-cli": "./src/cli.js"
32
32
  }
33
33
  }
package/src/cli.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from "commander";
4
+ import { saveApiKey } from "./config.js";
5
+ import { extractAuthArg, registerCommands } from "./commands.js";
6
+
7
+ const parsedAuth = extractAuthArg(process.argv.slice(2));
8
+ const runtimeApiKey = parsedAuth.apiKey;
9
+ const parseArgv = [process.argv[0], process.argv[1], ...parsedAuth.sanitizedArgs];
10
+
11
+ if (runtimeApiKey) {
12
+ await saveApiKey(runtimeApiKey);
13
+ }
14
+
15
+ registerCommands(program, runtimeApiKey);
16
+
17
+ const argvHasCommand = parsedAuth.sanitizedArgs.some((arg) => !arg.startsWith("-"));
18
+ const hasHelpFlag = parsedAuth.sanitizedArgs.includes("--help") || parsedAuth.sanitizedArgs.includes("-h");
19
+
20
+ if (!argvHasCommand && runtimeApiKey && !hasHelpFlag) {
21
+ console.log("API key saved and ready to use.");
22
+ process.exit(0);
23
+ }
24
+
25
+ if (!argvHasCommand && !runtimeApiKey && !hasHelpFlag) {
26
+ program.outputHelp();
27
+ process.exit(0);
28
+ }
29
+
30
+ await program.parseAsync(parseArgv);
@@ -0,0 +1,339 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import chalk from "chalk";
4
+
5
+ import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey } from "./config.js";
6
+ import { brandPath, collectionPath, nuelinkRequest } from "./http.js";
7
+ import { buildPostPayload, parseCsv } from "./postPayload.js";
8
+
9
+ function extractAuthArg(args) {
10
+ const sanitizedArgs = [];
11
+ let apiKey;
12
+
13
+ for (let index = 0; index < args.length; index += 1) {
14
+ const arg = args[index];
15
+
16
+ if (arg === "--auth" || arg === "-a") {
17
+ const next = args[index + 1];
18
+ if (next && !next.startsWith("-")) {
19
+ apiKey = next;
20
+ index += 1;
21
+ continue;
22
+ }
23
+ }
24
+
25
+ if (arg.startsWith("--auth=")) {
26
+ apiKey = arg.slice("--auth=".length);
27
+ continue;
28
+ }
29
+
30
+ sanitizedArgs.push(arg);
31
+ }
32
+
33
+ return { apiKey, sanitizedArgs };
34
+ }
35
+
36
+ function withCommandErrorHandling(handler) {
37
+ return async (...args) => {
38
+ try {
39
+ await handler(...args);
40
+ } catch (error) {
41
+ console.error(chalk.red(error.message));
42
+ process.exitCode = 1;
43
+ }
44
+ };
45
+ }
46
+
47
+ function registerCommands(program, runtimeApiKey) {
48
+ program
49
+ .name("nuelink-cli")
50
+ .version("1.0.0")
51
+ .description("Nuelink CLI for the Public API")
52
+ .option("-a, --auth <apiKey>", "Set and use API key");
53
+
54
+ program
55
+ .command("auth:clear")
56
+ .description("Remove the saved API key")
57
+ .action(withCommandErrorHandling(async () => {
58
+ await clearApiKey();
59
+ console.log(chalk.yellow("Saved API key removed."));
60
+ }));
61
+
62
+ program
63
+ .command("auth:status")
64
+ .description("Show where auth is currently resolved from")
65
+ .action(withCommandErrorHandling(async () => {
66
+ if (runtimeApiKey) {
67
+ console.log(chalk.green(`Auth source: CLI flag (${maskToken(runtimeApiKey)})`));
68
+ return;
69
+ }
70
+
71
+ if (process.env.NUELINK_API_KEY) {
72
+ console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
73
+ return;
74
+ }
75
+
76
+ const config = await readConfig();
77
+ const storedApiKey = decryptApiKey(config);
78
+ if (storedApiKey) {
79
+ console.log(chalk.green(`Auth source: saved config (${maskToken(storedApiKey)})`));
80
+
81
+ try {
82
+ const fileStat = await stat(CONFIG_FILE);
83
+ console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
84
+ console.log(chalk.blue(`Last updated: ${fileStat.mtime.toISOString()}`));
85
+ } catch {
86
+ // Ignore non-critical stat failure.
87
+ }
88
+
89
+ return;
90
+ }
91
+
92
+ console.log(chalk.yellow("No API key configured. Set one with --auth <api_key>."));
93
+ }));
94
+
95
+ program
96
+ .command("me")
97
+ .description("Get current profile")
98
+ .action(withCommandErrorHandling(async () => {
99
+ const apiKey = await resolveApiKey(runtimeApiKey);
100
+ await nuelinkRequest({ apiKey, endpoint: "/me" });
101
+ }));
102
+
103
+ program
104
+ .command("brands")
105
+ .description("List brands")
106
+ .option("--per-page <number>", "Items per page", "25")
107
+ .option("--page <number>", "Page number", "1")
108
+ .action(withCommandErrorHandling(async (options) => {
109
+ const apiKey = await resolveApiKey(runtimeApiKey);
110
+ await nuelinkRequest({
111
+ apiKey,
112
+ endpoint: "/brands",
113
+ query: {
114
+ per_page: options.perPage,
115
+ page: options.page,
116
+ },
117
+ });
118
+ }));
119
+
120
+ program
121
+ .command("collections")
122
+ .description("List collections for a brand")
123
+ .requiredOption("--brand-id <id>", "Brand ID")
124
+ .option("--per-page <number>", "Items per page", "25")
125
+ .option("--page <number>", "Page number", "1")
126
+ .action(withCommandErrorHandling(async (options) => {
127
+ const apiKey = await resolveApiKey(runtimeApiKey);
128
+ await nuelinkRequest({
129
+ apiKey,
130
+ endpoint: `${brandPath(options.brandId)}/collections`,
131
+ query: {
132
+ per_page: options.perPage,
133
+ page: options.page,
134
+ },
135
+ });
136
+ }));
137
+
138
+ program
139
+ .command("collections:create")
140
+ .description("Create a collection")
141
+ .requiredOption("--brand-id <id>", "Brand ID")
142
+ .requiredOption("--title <title>", "Collection title")
143
+ .option("--description <text>", "Collection description", "")
144
+ .option("--max-republish <number>", "Max republish")
145
+ .option("--channels <ids>", "Comma-separated channel IDs")
146
+ .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
147
+ .action(withCommandErrorHandling(async (options) => {
148
+ const apiKey = await resolveApiKey(runtimeApiKey);
149
+ await nuelinkRequest({
150
+ apiKey,
151
+ method: "POST",
152
+ endpoint: `${brandPath(options.brandId)}/collections`,
153
+ body: {
154
+ title: options.title,
155
+ description: options.description,
156
+ maxRepublish: options.maxRepublish ? Number(options.maxRepublish) : undefined,
157
+ channels: parseCsv(options.channels).map((id) => Number(id)),
158
+ queues: parseCsv(options.queues),
159
+ },
160
+ });
161
+ }));
162
+
163
+ program
164
+ .command("automations")
165
+ .description("List automations for a brand")
166
+ .requiredOption("--brand-id <id>", "Brand ID")
167
+ .action(withCommandErrorHandling(async (options) => {
168
+ const apiKey = await resolveApiKey(runtimeApiKey);
169
+ await nuelinkRequest({
170
+ apiKey,
171
+ endpoint: `${brandPath(options.brandId)}/automations`,
172
+ });
173
+ }));
174
+
175
+ program
176
+ .command("automations:create")
177
+ .description("Create an automation")
178
+ .requiredOption("--brand-id <id>", "Brand ID")
179
+ .requiredOption("--collection-id <id>", "Collection ID")
180
+ .requiredOption("--feed-url <url>", "Feed URL")
181
+ .requiredOption("--import-as-type <type>", "Import type, e.g. IMAGE")
182
+ .requiredOption("--sub-type <type>", "Sub type, e.g. RSS")
183
+ .requiredOption("--title <title>", "Automation title")
184
+ .option("--type <type>", "Automation type", "FEED")
185
+ .option("--dynamic-title <text>", "Dynamic title", "{{title}}")
186
+ .option("--dynamic-body <text>", "Dynamic body", "{title} {link}")
187
+ .option("--description <text>", "Automation description")
188
+ .action(withCommandErrorHandling(async (options) => {
189
+ const apiKey = await resolveApiKey(runtimeApiKey);
190
+ await nuelinkRequest({
191
+ apiKey,
192
+ method: "POST",
193
+ endpoint: `${brandPath(options.brandId)}/automations`,
194
+ body: {
195
+ collectionId: Number(options.collectionId),
196
+ feedUrl: options.feedUrl,
197
+ importAsType: options.importAsType,
198
+ subType: options.subType,
199
+ title: options.title,
200
+ type: options.type,
201
+ dynamicTitle: options.dynamicTitle,
202
+ dynamicBody: options.dynamicBody,
203
+ description: options.description,
204
+ },
205
+ });
206
+ }));
207
+
208
+ program
209
+ .command("channels")
210
+ .description("List channels for a brand")
211
+ .requiredOption("--brand-id <id>", "Brand ID")
212
+ .option("--per-page <number>", "Items per page", "25")
213
+ .option("--page <number>", "Page number", "1")
214
+ .action(withCommandErrorHandling(async (options) => {
215
+ const apiKey = await resolveApiKey(runtimeApiKey);
216
+ await nuelinkRequest({
217
+ apiKey,
218
+ endpoint: `${brandPath(options.brandId)}/channels`,
219
+ query: {
220
+ per_page: options.perPage,
221
+ page: options.page,
222
+ },
223
+ });
224
+ }));
225
+
226
+ program
227
+ .command("media")
228
+ .description("List media for a brand")
229
+ .requiredOption("--brand-id <id>", "Brand ID")
230
+ .action(withCommandErrorHandling(async (options) => {
231
+ const apiKey = await resolveApiKey(runtimeApiKey);
232
+ await nuelinkRequest({
233
+ apiKey,
234
+ endpoint: `${brandPath(options.brandId)}/media`,
235
+ });
236
+ }));
237
+
238
+ program
239
+ .command("media:upload")
240
+ .description("Upload a media file")
241
+ .requiredOption("--brand-id <id>", "Brand ID")
242
+ .requiredOption("--file <path>", "Path to local file")
243
+ .action(withCommandErrorHandling(async (options) => {
244
+ const apiKey = await resolveApiKey(runtimeApiKey);
245
+
246
+ const fileBuffer = await readFile(options.file);
247
+ const formData = new FormData();
248
+ formData.append("media", new Blob([fileBuffer]), path.basename(options.file));
249
+
250
+ await nuelinkRequest({
251
+ apiKey,
252
+ method: "POST",
253
+ endpoint: `${brandPath(options.brandId)}/media`,
254
+ multipart: formData,
255
+ });
256
+ }));
257
+
258
+ program
259
+ .command("posts")
260
+ .description("List posts in a collection")
261
+ .requiredOption("--brand-id <id>", "Brand ID")
262
+ .requiredOption("--collection-id <id>", "Collection ID")
263
+ .action(withCommandErrorHandling(async (options) => {
264
+ const apiKey = await resolveApiKey(runtimeApiKey);
265
+ await nuelinkRequest({
266
+ apiKey,
267
+ endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
268
+ });
269
+ }));
270
+
271
+ program
272
+ .command("posts:add-json")
273
+ .description("Create a post using a JSON payload file")
274
+ .requiredOption("--brand-id <id>", "Brand ID")
275
+ .requiredOption("--collection-id <id>", "Collection ID")
276
+ .requiredOption("--payload <file>", "Path to JSON payload file")
277
+ .action(withCommandErrorHandling(async (options) => {
278
+ const apiKey = await resolveApiKey(runtimeApiKey);
279
+ const payloadText = await readFile(options.payload, "utf8");
280
+ const payload = JSON.parse(payloadText);
281
+
282
+ await nuelinkRequest({
283
+ apiKey,
284
+ method: "POST",
285
+ endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
286
+ body: payload,
287
+ });
288
+ }));
289
+
290
+ program
291
+ .command("posts:create")
292
+ .description("Create a post using CLI options")
293
+ .requiredOption("--brand-id <id>", "Brand ID")
294
+ .requiredOption("--collection-id <id>", "Collection ID")
295
+ .option("--title <text>", "Post title")
296
+ .option("--caption <text>", "Post caption/body")
297
+ .option("--alt <text>", "Alt text")
298
+ .option("--link <url>", "Post link")
299
+ .option("--publish-mode <mode>", "Publish mode (e.g. DRAFT, NOW, SCHEDULE)", "DRAFT")
300
+ .option("--publish-at <value>", "Publish datetime (YYYY-MM-DD HH:mm:ss or ISO) or null")
301
+ .option("--post-as-story <boolean>", "Post as story: true/false")
302
+ .option("--post-type <type>", "Post type override")
303
+ .option("--comment <text>", "First comment")
304
+ .option("--comment-delay <seconds>", "First comment delay seconds")
305
+ .option("--media-ids <ids>", "Comma-separated media IDs")
306
+ .option("--media-urls <urls>", "Comma-separated media URLs")
307
+ .option("--poll-question <text>", "Poll question")
308
+ .option("--poll-options <items>", "Comma-separated poll options")
309
+ .option("--poll-period <value>", "Poll period (e.g. 3d)")
310
+ .option("--poll-correct-option-index <number>", "Poll correct option index")
311
+ .option("--poll-explanation <text>", "Poll explanation")
312
+ .option("--instagram-collab <username>", "Instagram collab username")
313
+ .option("--instagram-location-id <id>", "Instagram location ID")
314
+ .option("--instagram-location-name <name>", "Instagram location name")
315
+ .option("--instagram-trial-reel <mode>", "Instagram trial reel mode")
316
+ .option("--instagram-share-to-feed <boolean>", "Instagram share to feed true/false")
317
+ .option("--facebook-collab <username>", "Facebook collab username")
318
+ .option("--facebook-location-id <id>", "Facebook location ID")
319
+ .option("--facebook-location-name <name>", "Facebook location name")
320
+ .option("--tiktok-send-to-inbox <boolean>", "TikTok send to inbox true/false")
321
+ .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
322
+ .option("--youtube-playlists <json>", "YouTube playlists JSON string")
323
+ .action(withCommandErrorHandling(async (options) => {
324
+ const apiKey = await resolveApiKey(runtimeApiKey);
325
+ const payload = buildPostPayload(options);
326
+
327
+ await nuelinkRequest({
328
+ apiKey,
329
+ method: "POST",
330
+ endpoint: `${collectionPath(options.brandId, options.collectionId)}/posts`,
331
+ body: payload,
332
+ });
333
+ }));
334
+ }
335
+
336
+ export {
337
+ extractAuthArg,
338
+ registerCommands,
339
+ };
package/src/config.js ADDED
@@ -0,0 +1,116 @@
1
+ import crypto from "node:crypto";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
5
+
6
+ const CONFIG_DIR = path.join(os.homedir(), ".nuelink-cli");
7
+ const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
8
+ const CONFIG_ENCRYPTION_SALT = "nuelink-cli-config-salt-v1";
9
+ const CONFIG_ENCRYPTION_PASSPHRASE = "nuelink-cli::config::v1::auth";
10
+
11
+ async function readConfig() {
12
+ try {
13
+ const content = await readFile(CONFIG_FILE, "utf8");
14
+ return JSON.parse(content);
15
+ } catch {
16
+ return {};
17
+ }
18
+ }
19
+
20
+ function getConfigCipherKey() {
21
+ return crypto.scryptSync(CONFIG_ENCRYPTION_PASSPHRASE, CONFIG_ENCRYPTION_SALT, 32);
22
+ }
23
+
24
+ function encryptApiKey(apiKey) {
25
+ const iv = crypto.randomBytes(12);
26
+ const cipher = crypto.createCipheriv("aes-256-gcm", getConfigCipherKey(), iv);
27
+ const encrypted = Buffer.concat([cipher.update(apiKey, "utf8"), cipher.final()]);
28
+ const authTag = cipher.getAuthTag();
29
+
30
+ return {
31
+ version: 1,
32
+ encryptedApiKey: encrypted.toString("base64"),
33
+ iv: iv.toString("base64"),
34
+ authTag: authTag.toString("base64"),
35
+ };
36
+ }
37
+
38
+ function decryptApiKey(config) {
39
+ if (config?.encryptedApiKey && config?.iv && config?.authTag) {
40
+ const decipher = crypto.createDecipheriv(
41
+ "aes-256-gcm",
42
+ getConfigCipherKey(),
43
+ Buffer.from(config.iv, "base64"),
44
+ );
45
+ decipher.setAuthTag(Buffer.from(config.authTag, "base64"));
46
+
47
+ const decrypted = Buffer.concat([
48
+ decipher.update(Buffer.from(config.encryptedApiKey, "base64")),
49
+ decipher.final(),
50
+ ]);
51
+
52
+ return decrypted.toString("utf8");
53
+ }
54
+
55
+ if (config?.apiKey) {
56
+ return config.apiKey;
57
+ }
58
+
59
+ return undefined;
60
+ }
61
+
62
+ async function writeConfig(config) {
63
+ await mkdir(CONFIG_DIR, { recursive: true });
64
+ await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf8");
65
+
66
+ try {
67
+ await chmod(CONFIG_FILE, 0o600);
68
+ } catch {
69
+ // Ignore on platforms where chmod permissions are not meaningful.
70
+ }
71
+ }
72
+
73
+ async function saveApiKey(apiKey) {
74
+ await writeConfig(encryptApiKey(apiKey));
75
+ }
76
+
77
+ async function clearApiKey() {
78
+ await writeConfig({});
79
+ }
80
+
81
+ async function resolveApiKey(runtimeApiKey) {
82
+ if (runtimeApiKey) {
83
+ return runtimeApiKey;
84
+ }
85
+
86
+ if (process.env.NUELINK_API_KEY) {
87
+ return process.env.NUELINK_API_KEY;
88
+ }
89
+
90
+ const config = await readConfig();
91
+ const storedApiKey = decryptApiKey(config);
92
+
93
+ if (storedApiKey && config.apiKey) {
94
+ await saveApiKey(storedApiKey);
95
+ }
96
+
97
+ return storedApiKey;
98
+ }
99
+
100
+ function maskToken(token) {
101
+ if (!token || token.length < 8) {
102
+ return "(set)";
103
+ }
104
+
105
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
106
+ }
107
+
108
+ export {
109
+ CONFIG_FILE,
110
+ clearApiKey,
111
+ decryptApiKey,
112
+ maskToken,
113
+ readConfig,
114
+ resolveApiKey,
115
+ saveApiKey,
116
+ };
package/src/http.js ADDED
@@ -0,0 +1,103 @@
1
+ import chalk from "chalk";
2
+
3
+ const API_BASE_URL = "https://nuelink.com/api/public/v1";
4
+ const REQUEST_TIMEOUT_MS = Number(process.env.NUELINK_TIMEOUT_MS || 30000);
5
+
6
+ function pathParam(value, label) {
7
+ const stringValue = String(value ?? "").trim();
8
+
9
+ if (!stringValue) {
10
+ throw new Error(`Missing required ${label}.`);
11
+ }
12
+
13
+ return encodeURIComponent(stringValue);
14
+ }
15
+
16
+ function brandPath(brandId) {
17
+ return `/brands/${pathParam(brandId, "brand-id")}`;
18
+ }
19
+
20
+ function collectionPath(brandId, collectionId) {
21
+ return `${brandPath(brandId)}/collections/${pathParam(collectionId, "collection-id")}`;
22
+ }
23
+
24
+ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart }) {
25
+ if (!apiKey) {
26
+ console.error(chalk.red("Missing API key. Use --auth <api_key> to set it."));
27
+ process.exitCode = 1;
28
+ return null;
29
+ }
30
+
31
+ const url = new URL(`${API_BASE_URL}${endpoint}`);
32
+
33
+ if (query) {
34
+ Object.entries(query).forEach(([key, value]) => {
35
+ if (value !== undefined && value !== null && value !== "") {
36
+ url.searchParams.set(key, String(value));
37
+ }
38
+ });
39
+ }
40
+
41
+ const headers = {
42
+ Authorization: `Bearer ${apiKey}`,
43
+ Accept: "application/json",
44
+ "User-Agent": "nuelink-cli/1.0.0",
45
+ };
46
+
47
+ const init = {
48
+ method,
49
+ headers,
50
+ };
51
+
52
+ if (multipart) {
53
+ init.body = multipart;
54
+ } else if (body !== undefined) {
55
+ headers["Content-Type"] = "application/json";
56
+ init.body = JSON.stringify(body);
57
+ }
58
+
59
+ try {
60
+ const response = await fetch(url, {
61
+ ...init,
62
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
63
+ });
64
+ const text = await response.text();
65
+ let data = {};
66
+
67
+ if (text) {
68
+ try {
69
+ data = JSON.parse(text);
70
+ } catch {
71
+ data = { raw: text };
72
+ }
73
+ }
74
+
75
+ if (!response.ok) {
76
+ console.error(chalk.red(`Request failed (${response.status} ${response.statusText})`));
77
+ console.error(chalk.red(JSON.stringify(data, null, 2)));
78
+ process.exitCode = 1;
79
+ return null;
80
+ }
81
+
82
+ console.log(chalk.green(`OK ${method} ${url.pathname}`));
83
+ console.log(JSON.stringify(data, null, 2));
84
+ return data;
85
+ } catch (error) {
86
+ if (error?.name === "TimeoutError") {
87
+ console.error(chalk.red(`Request timed out after ${REQUEST_TIMEOUT_MS}ms.`));
88
+ process.exitCode = 1;
89
+ return null;
90
+ }
91
+
92
+ console.error(chalk.red("Request error:"), error.message);
93
+ process.exitCode = 1;
94
+ return null;
95
+ }
96
+ }
97
+
98
+ export {
99
+ brandPath,
100
+ collectionPath,
101
+ nuelinkRequest,
102
+ pathParam,
103
+ };
@@ -0,0 +1,144 @@
1
+ function parseCsv(value) {
2
+ if (!value) {
3
+ return [];
4
+ }
5
+
6
+ return value
7
+ .split(",")
8
+ .map((item) => item.trim())
9
+ .filter(Boolean);
10
+ }
11
+
12
+ function parseBoolean(value) {
13
+ if (value === undefined || value === null || value === "") {
14
+ return undefined;
15
+ }
16
+
17
+ const normalized = String(value).trim().toLowerCase();
18
+
19
+ if (["true", "1", "yes", "y"].includes(normalized)) {
20
+ return true;
21
+ }
22
+
23
+ if (["false", "0", "no", "n"].includes(normalized)) {
24
+ return false;
25
+ }
26
+
27
+ return undefined;
28
+ }
29
+
30
+ function parseNumber(value) {
31
+ if (value === undefined || value === null || value === "") {
32
+ return undefined;
33
+ }
34
+
35
+ const parsed = Number(value);
36
+ return Number.isNaN(parsed) ? undefined : parsed;
37
+ }
38
+
39
+ function mergeMedia(idsCsv, urlsCsv) {
40
+ const idMedia = parseCsv(idsCsv).map((id) => ({ id }));
41
+ const urlMedia = parseCsv(urlsCsv).map((url) => ({ url }));
42
+ return [...idMedia, ...urlMedia];
43
+ }
44
+
45
+ function buildPostPayload(options) {
46
+ const media = mergeMedia(options.mediaIds, options.mediaUrls);
47
+
48
+ const poll = {
49
+ ...(options.pollQuestion ? { question: options.pollQuestion } : {}),
50
+ ...(options.pollOptions ? { options: parseCsv(options.pollOptions) } : {}),
51
+ ...(options.pollPeriod ? { period: options.pollPeriod } : {}),
52
+ ...(parseNumber(options.pollCorrectOptionIndex) !== undefined
53
+ ? { correctOptionIndex: parseNumber(options.pollCorrectOptionIndex) }
54
+ : {}),
55
+ ...(options.pollExplanation ? { explanation: options.pollExplanation } : {}),
56
+ };
57
+
58
+ const instagram = {
59
+ ...(options.instagramCollab ? { collab: options.instagramCollab } : {}),
60
+ ...(options.instagramLocationId || options.instagramLocationName
61
+ ? {
62
+ location: {
63
+ ...(options.instagramLocationId ? { id: options.instagramLocationId } : {}),
64
+ ...(options.instagramLocationName ? { name: options.instagramLocationName } : {}),
65
+ },
66
+ }
67
+ : {}),
68
+ ...(options.instagramTrialReel ? { trialReel: options.instagramTrialReel } : {}),
69
+ ...(parseBoolean(options.instagramShareToFeed) !== undefined
70
+ ? { shareToFeed: parseBoolean(options.instagramShareToFeed) }
71
+ : {}),
72
+ };
73
+
74
+ const facebook = {
75
+ ...(options.facebookCollab ? { collab: options.facebookCollab } : {}),
76
+ ...(options.facebookLocationId || options.facebookLocationName
77
+ ? {
78
+ location: {
79
+ ...(options.facebookLocationId ? { id: options.facebookLocationId } : {}),
80
+ ...(options.facebookLocationName ? { name: options.facebookLocationName } : {}),
81
+ },
82
+ }
83
+ : {}),
84
+ };
85
+
86
+ const tiktok = {
87
+ ...(parseBoolean(options.tiktokSendToInbox) !== undefined
88
+ ? { sendToInbox: parseBoolean(options.tiktokSendToInbox) }
89
+ : {}),
90
+ };
91
+
92
+ let youtubePlaylists;
93
+ if (options.youtubePlaylists) {
94
+ youtubePlaylists = JSON.parse(options.youtubePlaylists);
95
+ }
96
+
97
+ const youtube = {
98
+ ...(options.youtubeTags ? { tags: parseCsv(options.youtubeTags) } : {}),
99
+ ...(youtubePlaylists ? { playlists: youtubePlaylists } : {}),
100
+ };
101
+
102
+ return {
103
+ ...(options.title ? { title: options.title } : {}),
104
+ ...(options.caption ? { caption: options.caption } : {}),
105
+ ...(options.alt ? { alt: options.alt } : {}),
106
+ ...(options.link ? { link: options.link } : {}),
107
+ ...(options.postType ? { postType: options.postType } : {}),
108
+ publishMode: options.publishMode,
109
+ ...(options.publishAt && options.publishAt !== "null" ? { publishAt: options.publishAt } : { publishAt: null }),
110
+ ...(parseBoolean(options.postAsStory) !== undefined
111
+ ? { postAsStory: parseBoolean(options.postAsStory) }
112
+ : {}),
113
+ ...(options.comment
114
+ ? {
115
+ comment: {
116
+ comment: options.comment,
117
+ ...(parseNumber(options.commentDelay) !== undefined
118
+ ? { delay: parseNumber(options.commentDelay) }
119
+ : {}),
120
+ },
121
+ }
122
+ : {}),
123
+ ...(media.length > 0 ? { media } : {}),
124
+ ...(Object.keys(poll).length > 0 ? { poll } : {}),
125
+ ...(Object.keys(instagram).length > 0 || Object.keys(facebook).length > 0 || Object.keys(tiktok).length > 0 || Object.keys(youtube).length > 0
126
+ ? {
127
+ platforms: {
128
+ ...(Object.keys(instagram).length > 0 ? { instagram } : {}),
129
+ ...(Object.keys(facebook).length > 0 ? { facebook } : {}),
130
+ ...(Object.keys(tiktok).length > 0 ? { tiktok } : {}),
131
+ ...(Object.keys(youtube).length > 0 ? { youtube } : {}),
132
+ },
133
+ }
134
+ : {}),
135
+ };
136
+ }
137
+
138
+ export {
139
+ buildPostPayload,
140
+ mergeMedia,
141
+ parseBoolean,
142
+ parseCsv,
143
+ parseNumber,
144
+ };
package/src/main.js DELETED
@@ -1,617 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { program } from "commander";
4
- import chalk from "chalk";
5
- import os from "node:os";
6
- import path from "node:path";
7
- import { readFile, writeFile, mkdir, chmod, stat } from "node:fs/promises";
8
-
9
- const API_BASE_URL = "https://nuelink.com/api/public/v1";
10
- const CONFIG_DIR = path.join(os.homedir(), ".nuelink-cli");
11
- const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
12
- const REQUEST_TIMEOUT_MS = Number(process.env.NUELINK_TIMEOUT_MS || 30000);
13
-
14
- async function readConfig() {
15
- try {
16
- const content = await readFile(CONFIG_FILE, "utf8");
17
- return JSON.parse(content);
18
- } catch {
19
- return {};
20
- }
21
- }
22
-
23
- async function writeConfig(config) {
24
- await mkdir(CONFIG_DIR, { recursive: true });
25
- await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), "utf8");
26
-
27
- // Best effort to keep token readable only by the current user on POSIX systems.
28
- try {
29
- await chmod(CONFIG_FILE, 0o600);
30
- } catch {
31
- // Ignore on platforms where chmod permissions are not meaningful.
32
- }
33
- }
34
-
35
- async function saveApiKey(apiKey) {
36
- const config = await readConfig();
37
- config.apiKey = apiKey;
38
- await writeConfig(config);
39
- }
40
-
41
- async function clearApiKey() {
42
- const config = await readConfig();
43
- delete config.apiKey;
44
- await writeConfig(config);
45
- }
46
-
47
- function maskToken(token) {
48
- if (!token || token.length < 8) {
49
- return "(set)";
50
- }
51
-
52
- return `${token.slice(0, 4)}...${token.slice(-4)}`;
53
- }
54
-
55
- async function resolveApiKey(runtimeApiKey) {
56
- if (runtimeApiKey) {
57
- return runtimeApiKey;
58
- }
59
-
60
- if (process.env.NUELINK_API_KEY) {
61
- return process.env.NUELINK_API_KEY;
62
- }
63
-
64
- const config = await readConfig();
65
- return config.apiKey;
66
- }
67
-
68
- function extractAuthArg(args) {
69
- const sanitizedArgs = [];
70
- let apiKey;
71
-
72
- for (let index = 0; index < args.length; index += 1) {
73
- const arg = args[index];
74
-
75
- if (arg === "--auth" || arg === "-a") {
76
- const next = args[index + 1];
77
- if (next && !next.startsWith("-")) {
78
- apiKey = next;
79
- index += 1;
80
- continue;
81
- }
82
- }
83
-
84
- if (arg.startsWith("--auth=")) {
85
- apiKey = arg.slice("--auth=".length);
86
- continue;
87
- }
88
-
89
- sanitizedArgs.push(arg);
90
- }
91
-
92
- return { apiKey, sanitizedArgs };
93
- }
94
-
95
- function parseCsv(value) {
96
- if (!value) {
97
- return [];
98
- }
99
-
100
- return value
101
- .split(",")
102
- .map((item) => item.trim())
103
- .filter(Boolean);
104
- }
105
-
106
- function parseBoolean(value) {
107
- if (value === undefined || value === null || value === "") {
108
- return undefined;
109
- }
110
-
111
- const normalized = String(value).trim().toLowerCase();
112
-
113
- if (["true", "1", "yes", "y"].includes(normalized)) {
114
- return true;
115
- }
116
-
117
- if (["false", "0", "no", "n"].includes(normalized)) {
118
- return false;
119
- }
120
-
121
- return undefined;
122
- }
123
-
124
- function parseNumber(value) {
125
- if (value === undefined || value === null || value === "") {
126
- return undefined;
127
- }
128
-
129
- const parsed = Number(value);
130
- return Number.isNaN(parsed) ? undefined : parsed;
131
- }
132
-
133
- function mergeMedia(idsCsv, urlsCsv) {
134
- const idMedia = parseCsv(idsCsv).map((id) => ({ id }));
135
- const urlMedia = parseCsv(urlsCsv).map((url) => ({ url }));
136
- return [...idMedia, ...urlMedia];
137
- }
138
-
139
- async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart }) {
140
- if (!apiKey) {
141
- console.error(chalk.red("Missing API key. Use --auth <api_key> to set it."));
142
- process.exitCode = 1;
143
- return null;
144
- }
145
-
146
- const url = new URL(`${API_BASE_URL}${endpoint}`);
147
-
148
- if (query) {
149
- Object.entries(query).forEach(([key, value]) => {
150
- if (value !== undefined && value !== null && value !== "") {
151
- url.searchParams.set(key, String(value));
152
- }
153
- });
154
- }
155
-
156
- const headers = {
157
- Authorization: `Bearer ${apiKey}`,
158
- Accept: "application/json",
159
- "User-Agent": "nuelink-cli/1.0.0",
160
- };
161
-
162
- const init = {
163
- method,
164
- headers,
165
- };
166
-
167
- if (multipart) {
168
- init.body = multipart;
169
- } else if (body !== undefined) {
170
- headers["Content-Type"] = "application/json";
171
- init.body = JSON.stringify(body);
172
- }
173
-
174
- try {
175
- const response = await fetch(url, {
176
- ...init,
177
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
178
- });
179
- const text = await response.text();
180
- let data = {};
181
-
182
- if (text) {
183
- try {
184
- data = JSON.parse(text);
185
- } catch {
186
- data = { raw: text };
187
- }
188
- }
189
-
190
- if (!response.ok) {
191
- console.error(chalk.red(`Request failed (${response.status} ${response.statusText})`));
192
- console.error(chalk.red(JSON.stringify(data, null, 2)));
193
- process.exitCode = 1;
194
- return null;
195
- }
196
-
197
- console.log(chalk.green(`OK ${method} ${url.pathname}`));
198
- console.log(JSON.stringify(data, null, 2));
199
- return data;
200
- } catch (error) {
201
- if (error?.name === "TimeoutError") {
202
- console.error(chalk.red(`Request timed out after ${REQUEST_TIMEOUT_MS}ms.`));
203
- process.exitCode = 1;
204
- return null;
205
- }
206
-
207
- console.error(chalk.red("Request error:"), error.message);
208
- process.exitCode = 1;
209
- return null;
210
- }
211
- }
212
-
213
- const parsedAuth = extractAuthArg(process.argv.slice(2));
214
- const runtimeApiKey = parsedAuth.apiKey;
215
- const parseArgv = [process.argv[0], process.argv[1], ...parsedAuth.sanitizedArgs];
216
-
217
- if (runtimeApiKey) {
218
- await saveApiKey(runtimeApiKey);
219
- }
220
-
221
- program
222
- .name("nuelink-cli")
223
- .version("1.0.0")
224
- .description("Nuelink CLI for the Public API")
225
- .option("-a, --auth <apiKey>", "Set and use API key");
226
-
227
- program
228
- .command("auth:clear")
229
- .description("Remove the saved API key")
230
- .action(async () => {
231
- await clearApiKey();
232
- console.log(chalk.yellow("Saved API key removed."));
233
- });
234
-
235
- program
236
- .command("auth:status")
237
- .description("Show where auth is currently resolved from")
238
- .action(async () => {
239
- if (runtimeApiKey) {
240
- console.log(chalk.green(`Auth source: CLI flag (${maskToken(runtimeApiKey)})`));
241
- return;
242
- }
243
-
244
- if (process.env.NUELINK_API_KEY) {
245
- console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
246
- return;
247
- }
248
-
249
- const config = await readConfig();
250
- if (config.apiKey) {
251
- console.log(chalk.green(`Auth source: saved config (${maskToken(config.apiKey)})`));
252
-
253
- try {
254
- const fileStat = await stat(CONFIG_FILE);
255
- console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
256
- console.log(chalk.blue(`Last updated: ${fileStat.mtime.toISOString()}`));
257
- } catch {
258
- // Ignore non-critical stat failure.
259
- }
260
-
261
- return;
262
- }
263
-
264
- console.log(chalk.yellow("No API key configured. Set one with --auth <api_key>."));
265
- });
266
-
267
- program
268
- .command("me")
269
- .description("Get current profile")
270
- .action(async () => {
271
- const apiKey = await resolveApiKey(runtimeApiKey);
272
- await nuelinkRequest({ apiKey, endpoint: "/me" });
273
- });
274
-
275
- program
276
- .command("brands")
277
- .description("List brands")
278
- .option("--per-page <number>", "Items per page", "25")
279
- .option("--page <number>", "Page number", "1")
280
- .action(async (options) => {
281
- const apiKey = await resolveApiKey(runtimeApiKey);
282
- await nuelinkRequest({
283
- apiKey,
284
- endpoint: "/brands",
285
- query: {
286
- per_page: options.perPage,
287
- page: options.page,
288
- },
289
- });
290
- });
291
-
292
- program
293
- .command("collections")
294
- .description("List collections for a brand")
295
- .requiredOption("--brand-id <id>", "Brand ID")
296
- .option("--per-page <number>", "Items per page", "25")
297
- .option("--page <number>", "Page number", "1")
298
- .action(async (options) => {
299
- const apiKey = await resolveApiKey(runtimeApiKey);
300
- await nuelinkRequest({
301
- apiKey,
302
- endpoint: `/brands/${options.brandId}/collections`,
303
- query: {
304
- per_page: options.perPage,
305
- page: options.page,
306
- },
307
- });
308
- });
309
-
310
- program
311
- .command("collections:create")
312
- .description("Create a collection")
313
- .requiredOption("--brand-id <id>", "Brand ID")
314
- .requiredOption("--title <title>", "Collection title")
315
- .option("--description <text>", "Collection description", "")
316
- .option("--max-republish <number>", "Max republish")
317
- .option("--channels <ids>", "Comma-separated channel IDs")
318
- .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
319
- .action(async (options) => {
320
- const apiKey = await resolveApiKey(runtimeApiKey);
321
- await nuelinkRequest({
322
- apiKey,
323
- method: "POST",
324
- endpoint: `/brands/${options.brandId}/collections`,
325
- body: {
326
- title: options.title,
327
- description: options.description,
328
- maxRepublish: options.maxRepublish ? Number(options.maxRepublish) : undefined,
329
- channels: parseCsv(options.channels).map((id) => Number(id)),
330
- queues: parseCsv(options.queues),
331
- },
332
- });
333
- });
334
-
335
- program
336
- .command("automations")
337
- .description("List automations for a brand")
338
- .requiredOption("--brand-id <id>", "Brand ID")
339
- .action(async (options) => {
340
- const apiKey = await resolveApiKey(runtimeApiKey);
341
- await nuelinkRequest({
342
- apiKey,
343
- endpoint: `/brands/${options.brandId}/automations`,
344
- });
345
- });
346
-
347
- program
348
- .command("automations:create")
349
- .description("Create an automation")
350
- .requiredOption("--brand-id <id>", "Brand ID")
351
- .requiredOption("--collection-id <id>", "Collection ID")
352
- .requiredOption("--feed-url <url>", "Feed URL")
353
- .requiredOption("--import-as-type <type>", "Import type, e.g. IMAGE")
354
- .requiredOption("--sub-type <type>", "Sub type, e.g. RSS")
355
- .requiredOption("--title <title>", "Automation title")
356
- .option("--type <type>", "Automation type", "FEED")
357
- .option("--dynamic-title <text>", "Dynamic title", "{{title}}")
358
- .option("--dynamic-body <text>", "Dynamic body", "{title} {link}")
359
- .option("--description <text>", "Automation description")
360
- .action(async (options) => {
361
- const apiKey = await resolveApiKey(runtimeApiKey);
362
- await nuelinkRequest({
363
- apiKey,
364
- method: "POST",
365
- endpoint: `/brands/${options.brandId}/automations`,
366
- body: {
367
- collectionId: Number(options.collectionId),
368
- feedUrl: options.feedUrl,
369
- importAsType: options.importAsType,
370
- subType: options.subType,
371
- title: options.title,
372
- type: options.type,
373
- dynamicTitle: options.dynamicTitle,
374
- dynamicBody: options.dynamicBody,
375
- description: options.description,
376
- },
377
- });
378
- });
379
-
380
- program
381
- .command("channels")
382
- .description("List channels for a brand")
383
- .requiredOption("--brand-id <id>", "Brand ID")
384
- .option("--per-page <number>", "Items per page", "25")
385
- .option("--page <number>", "Page number", "1")
386
- .action(async (options) => {
387
- const apiKey = await resolveApiKey(runtimeApiKey);
388
- await nuelinkRequest({
389
- apiKey,
390
- endpoint: `/brands/${options.brandId}/channels`,
391
- query: {
392
- per_page: options.perPage,
393
- page: options.page,
394
- },
395
- });
396
- });
397
-
398
- program
399
- .command("media")
400
- .description("List media for a brand")
401
- .requiredOption("--brand-id <id>", "Brand ID")
402
- .action(async (options) => {
403
- const apiKey = await resolveApiKey(runtimeApiKey);
404
- await nuelinkRequest({
405
- apiKey,
406
- endpoint: `/brands/${options.brandId}/media`,
407
- });
408
- });
409
-
410
- program
411
- .command("media:upload")
412
- .description("Upload a media file")
413
- .requiredOption("--brand-id <id>", "Brand ID")
414
- .requiredOption("--file <path>", "Path to local file")
415
- .action(async (options) => {
416
- const apiKey = await resolveApiKey(runtimeApiKey);
417
-
418
- const fileBuffer = await readFile(options.file);
419
- const formData = new FormData();
420
- formData.append("media", new Blob([fileBuffer]), path.basename(options.file));
421
-
422
- await nuelinkRequest({
423
- apiKey,
424
- method: "POST",
425
- endpoint: `/brands/${options.brandId}/media`,
426
- multipart: formData,
427
- });
428
- });
429
-
430
- program
431
- .command("posts")
432
- .description("List posts in a collection")
433
- .requiredOption("--brand-id <id>", "Brand ID")
434
- .requiredOption("--collection-id <id>", "Collection ID")
435
- .action(async (options) => {
436
- const apiKey = await resolveApiKey(runtimeApiKey);
437
- await nuelinkRequest({
438
- apiKey,
439
- endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
440
- });
441
- });
442
-
443
- program
444
- .command("posts:add-json")
445
- .description("Create a post using a JSON payload file")
446
- .requiredOption("--brand-id <id>", "Brand ID")
447
- .requiredOption("--collection-id <id>", "Collection ID")
448
- .requiredOption("--payload <file>", "Path to JSON payload file")
449
- .action(async (options) => {
450
- const apiKey = await resolveApiKey(runtimeApiKey);
451
- const payloadText = await readFile(options.payload, "utf8");
452
- const payload = JSON.parse(payloadText);
453
-
454
- await nuelinkRequest({
455
- apiKey,
456
- method: "POST",
457
- endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
458
- body: payload,
459
- });
460
- });
461
-
462
- program
463
- .command("posts:create")
464
- .description("Create a post using CLI options")
465
- .requiredOption("--brand-id <id>", "Brand ID")
466
- .requiredOption("--collection-id <id>", "Collection ID")
467
- .option("--title <text>", "Post title")
468
- .option("--caption <text>", "Post caption/body")
469
- .option("--alt <text>", "Alt text")
470
- .option("--link <url>", "Post link")
471
- .option("--publish-mode <mode>", "Publish mode (e.g. DRAFT, NOW, SCHEDULE)", "DRAFT")
472
- .option("--publish-at <value>", "Publish datetime (YYYY-MM-DD HH:mm:ss or ISO) or null")
473
- .option("--post-as-story <boolean>", "Post as story: true/false")
474
- .option("--post-type <type>", "Post type override")
475
- .option("--comment <text>", "First comment")
476
- .option("--comment-delay <seconds>", "First comment delay seconds")
477
- .option("--media-ids <ids>", "Comma-separated media IDs")
478
- .option("--media-urls <urls>", "Comma-separated media URLs")
479
- .option("--poll-question <text>", "Poll question")
480
- .option("--poll-options <items>", "Comma-separated poll options")
481
- .option("--poll-period <value>", "Poll period (e.g. 3d)")
482
- .option("--poll-correct-option-index <number>", "Poll correct option index")
483
- .option("--poll-explanation <text>", "Poll explanation")
484
- .option("--instagram-collab <username>", "Instagram collab username")
485
- .option("--instagram-location-id <id>", "Instagram location ID")
486
- .option("--instagram-location-name <name>", "Instagram location name")
487
- .option("--instagram-trial-reel <mode>", "Instagram trial reel mode")
488
- .option("--instagram-share-to-feed <boolean>", "Instagram share to feed true/false")
489
- .option("--facebook-collab <username>", "Facebook collab username")
490
- .option("--facebook-location-id <id>", "Facebook location ID")
491
- .option("--facebook-location-name <name>", "Facebook location name")
492
- .option("--tiktok-send-to-inbox <boolean>", "TikTok send to inbox true/false")
493
- .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
494
- .option("--youtube-playlists <json>", "YouTube playlists JSON string")
495
- .action(async (options) => {
496
- const apiKey = await resolveApiKey(runtimeApiKey);
497
-
498
- const media = mergeMedia(options.mediaIds, options.mediaUrls);
499
-
500
- const poll = {
501
- ...(options.pollQuestion ? { question: options.pollQuestion } : {}),
502
- ...(options.pollOptions ? { options: parseCsv(options.pollOptions) } : {}),
503
- ...(options.pollPeriod ? { period: options.pollPeriod } : {}),
504
- ...(parseNumber(options.pollCorrectOptionIndex) !== undefined
505
- ? { correctOptionIndex: parseNumber(options.pollCorrectOptionIndex) }
506
- : {}),
507
- ...(options.pollExplanation ? { explanation: options.pollExplanation } : {}),
508
- };
509
-
510
- const instagram = {
511
- ...(options.instagramCollab ? { collab: options.instagramCollab } : {}),
512
- ...(options.instagramLocationId || options.instagramLocationName
513
- ? {
514
- location: {
515
- ...(options.instagramLocationId ? { id: options.instagramLocationId } : {}),
516
- ...(options.instagramLocationName ? { name: options.instagramLocationName } : {}),
517
- },
518
- }
519
- : {}),
520
- ...(options.instagramTrialReel ? { trialReel: options.instagramTrialReel } : {}),
521
- ...(parseBoolean(options.instagramShareToFeed) !== undefined
522
- ? { shareToFeed: parseBoolean(options.instagramShareToFeed) }
523
- : {}),
524
- };
525
-
526
- const facebook = {
527
- ...(options.facebookCollab ? { collab: options.facebookCollab } : {}),
528
- ...(options.facebookLocationId || options.facebookLocationName
529
- ? {
530
- location: {
531
- ...(options.facebookLocationId ? { id: options.facebookLocationId } : {}),
532
- ...(options.facebookLocationName ? { name: options.facebookLocationName } : {}),
533
- },
534
- }
535
- : {}),
536
- };
537
-
538
-
539
- const tiktok = {
540
- ...(parseBoolean(options.tiktokSendToInbox) !== undefined
541
- ? { sendToInbox: parseBoolean(options.tiktokSendToInbox) }
542
- : {}),
543
- };
544
-
545
- let youtubePlaylists;
546
- if (options.youtubePlaylists) {
547
- try {
548
- youtubePlaylists = JSON.parse(options.youtubePlaylists);
549
- } catch {
550
- console.error(chalk.red("Invalid --youtube-playlists JSON."));
551
- process.exitCode = 1;
552
- return;
553
- }
554
- }
555
-
556
- const youtube = {
557
- ...(options.youtubeTags ? { tags: parseCsv(options.youtubeTags) } : {}),
558
- ...(youtubePlaylists ? { playlists: youtubePlaylists } : {}),
559
- };
560
-
561
- const payload = {
562
- ...(options.title ? { title: options.title } : {}),
563
- ...(options.caption ? { caption: options.caption } : {}),
564
- ...(options.alt ? { alt: options.alt } : {}),
565
- ...(options.link ? { link: options.link } : {}),
566
- ...(options.postType ? { postType: options.postType } : {}),
567
- publishMode: options.publishMode,
568
- ...(options.publishAt && options.publishAt !== "null" ? { publishAt: options.publishAt } : { publishAt: null }),
569
- ...(parseBoolean(options.postAsStory) !== undefined
570
- ? { postAsStory: parseBoolean(options.postAsStory) }
571
- : {}),
572
- ...(options.comment
573
- ? {
574
- comment: {
575
- comment: options.comment,
576
- ...(parseNumber(options.commentDelay) !== undefined
577
- ? { delay: parseNumber(options.commentDelay) }
578
- : {}),
579
- },
580
- }
581
- : {}),
582
- ...(media.length > 0 ? { media } : {}),
583
- ...(Object.keys(poll).length > 0 ? { poll } : {}),
584
- ...(Object.keys(instagram).length > 0 || Object.keys(facebook).length > 0 || Object.keys(tiktok).length > 0 || Object.keys(youtube).length > 0
585
- ? {
586
- platforms: {
587
- ...(Object.keys(instagram).length > 0 ? { instagram } : {}),
588
- ...(Object.keys(facebook).length > 0 ? { facebook } : {}),
589
- ...(Object.keys(tiktok).length > 0 ? { tiktok } : {}),
590
- ...(Object.keys(youtube).length > 0 ? { youtube } : {}),
591
- },
592
- }
593
- : {}),
594
- };
595
-
596
- await nuelinkRequest({
597
- apiKey,
598
- method: "POST",
599
- endpoint: `/brands/${options.brandId}/collections/${options.collectionId}/posts`,
600
- body: payload,
601
- });
602
- });
603
-
604
- const argvHasCommand = parsedAuth.sanitizedArgs.some((arg) => !arg.startsWith("-"));
605
- const hasHelpFlag = parsedAuth.sanitizedArgs.includes("--help") || parsedAuth.sanitizedArgs.includes("-h");
606
-
607
- if (!argvHasCommand && runtimeApiKey && !hasHelpFlag) {
608
- console.log(chalk.green("API key saved and ready to use."));
609
- process.exit(0);
610
- }
611
-
612
- if (!argvHasCommand && !runtimeApiKey && !hasHelpFlag) {
613
- program.outputHelp();
614
- process.exit(0);
615
- }
616
-
617
- await program.parseAsync(parseArgv);