@nuelink/nuelink-cli 1.4.1 → 1.4.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/package.json CHANGED
@@ -1,39 +1,39 @@
1
1
  {
2
2
  "name": "@nuelink/nuelink-cli",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
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
- "license": "MIT",
6
- "author": "Nuelink",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/Nuelink/nuelink-cli.git"
10
- },
11
- "homepage": "https://github.com/Nuelink/nuelink-cli#readme",
12
- "bugs": {
13
- "url": "https://github.com/Nuelink/nuelink-cli/issues"
14
- },
5
+ "license": "MIT",
6
+ "author": "Nuelink",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Nuelink/nuelink-cli.git"
10
+ },
11
+ "homepage": "https://github.com/Nuelink/nuelink-cli#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Nuelink/nuelink-cli/issues"
14
+ },
15
15
  "type": "module",
16
16
  "main": "./src/cli.js",
17
17
  "scripts": {
18
- "test": "node --test test/cli.test.mjs",
19
- "smoke:auth": "node src/cli.js auth:status",
20
- "check:pack": "npm pack --dry-run",
21
- "check:pack:installed": "node scripts/check-packed-package.mjs"
18
+ "test": "node --test test/cli.test.mjs",
19
+ "smoke:auth": "node src/cli.js auth:status",
20
+ "check:pack": "npm pack --dry-run",
21
+ "check:pack:installed": "node scripts/check-packed-package.mjs"
22
22
  },
23
23
  "engines": {
24
24
  "node": ">=18.17"
25
25
  },
26
- "files": [
27
- "src",
28
- "test",
29
- "CHANGELOG.md",
30
- "README.md",
31
- "SECURITY.md",
32
- "LICENSE"
33
- ],
34
- "publishConfig": {
35
- "access": "public"
36
- },
26
+ "files": [
27
+ "src",
28
+ "test",
29
+ "CHANGELOG.md",
30
+ "README.md",
31
+ "SECURITY.md",
32
+ "LICENSE"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
37
  "keywords": [
38
38
  "nuelink",
39
39
  "cli",
@@ -41,10 +41,11 @@
41
41
  "automation"
42
42
  ],
43
43
  "dependencies": {
44
+ "@nuelink/nuelink-cli": "^1.4.1",
44
45
  "chalk": "^5.6.2",
45
46
  "commander": "^13.1.0"
46
47
  },
47
- "bin": {
48
- "nuelink-cli": "src/cli.js"
49
- }
50
- }
48
+ "bin": {
49
+ "nuelink-cli": "src/cli.js"
50
+ }
51
+ }
package/src/commands.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { readFile, stat } from "node:fs/promises";
2
2
  import readline from "node:readline";
3
3
  import path from "node:path";
4
- import chalk from "chalk";
5
-
6
- import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey, saveApiKey } from "./config.js";
7
- import { CliError, printCliError } from "./errors.js";
4
+ import chalk from "chalk";
5
+
6
+ import { clearApiKey, maskToken, readConfig, resolveApiKey, CONFIG_FILE, decryptApiKey, saveApiKey } from "./config.js";
7
+ import { CliError, printCliError } from "./errors.js";
8
8
  import { brandPath, collectionPath, nuelinkRequest } from "./http.js";
9
9
  import { buildPostPayload, parseCsv, validateRawPostPayload, VALID_PUBLISH_MODES } from "./postPayload.js";
10
10
  import {
@@ -20,10 +20,10 @@ import {
20
20
  parsePositiveInteger,
21
21
  splitCsv,
22
22
  validateHttpUrl,
23
- validateMediaFile,
24
- validateQueueSlots,
25
- validateRequiredString,
26
- } from "./validation.js";
23
+ validateMediaFile,
24
+ validateQueueSlots,
25
+ validateRequiredString,
26
+ } from "./validation.js";
27
27
 
28
28
  function extractApiKeyArg(args) {
29
29
  const sanitizedArgs = [];
@@ -180,19 +180,19 @@ async function executeRequest(program, runtimeApiKey, request) {
180
180
  });
181
181
  }
182
182
 
183
- function withCommandErrorHandling(program, handler) {
184
- return async (...args) => {
185
- try {
186
- await handler(...args);
187
- } catch (error) {
188
- printCliError(error, {
189
- json: Boolean(program.opts().json),
190
- fallbackCode: "VALIDATION_ERROR",
191
- });
192
- process.exitCode = 1;
193
- }
194
- };
195
- }
183
+ function withCommandErrorHandling(program, handler) {
184
+ return async (...args) => {
185
+ try {
186
+ await handler(...args);
187
+ } catch (error) {
188
+ printCliError(error, {
189
+ json: Boolean(program.opts().json),
190
+ fallbackCode: "VALIDATION_ERROR",
191
+ });
192
+ process.exitCode = 1;
193
+ }
194
+ };
195
+ }
196
196
 
197
197
  function registerCommands(program, runtimeApiKey, cliVersion) {
198
198
  program
@@ -202,7 +202,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
202
202
  .option("-a, --api-key <apiKey>", "Use API key for this invocation only")
203
203
  .option("--auth <apiKey>", "Deprecated alias for --api-key")
204
204
  .option("--dry-run", "Print the validated request without sending it")
205
- .option("--json", "Output machine-readable JSON for successes and failures")
205
+ .option("--json", "Output machine-readable JSON for successes and failures")
206
206
  .option("--quiet", "Suppress non-essential success banners");
207
207
 
208
208
  program
@@ -210,7 +210,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
210
210
  .description("Persist an API key to local config")
211
211
  .option("--api-key <apiKey>", "API key to save (prefer stdin or interactive prompt)")
212
212
  .option("--stdin", "Read API key from stdin")
213
- .action(withCommandErrorHandling(program, async (options) => {
213
+ .action(withCommandErrorHandling(program, async (options) => {
214
214
  const apiKey = await resolveLoginApiKey(options, runtimeApiKey);
215
215
 
216
216
  if (!apiKey) {
@@ -219,95 +219,95 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
219
219
 
220
220
  process.env.NUELINK_API_KEY = apiKey;
221
221
  await saveApiKey(apiKey);
222
- if (program.opts().json) {
223
- console.log(JSON.stringify({ success: true, source: "saved_config" }));
224
- } else {
225
- console.log(chalk.green("API key saved to local config."));
226
- }
227
- }));
222
+ if (program.opts().json) {
223
+ console.log(JSON.stringify({ success: true, source: "saved_config" }));
224
+ } else {
225
+ console.log(chalk.green("API key saved to local config."));
226
+ }
227
+ }));
228
228
 
229
229
  program
230
230
  .command("auth:clear")
231
231
  .description("Remove the saved API key")
232
- .action(withCommandErrorHandling(program, async () => {
233
- await clearApiKey();
234
- if (program.opts().json) {
235
- console.log(JSON.stringify({ success: true, cleared: true }));
236
- } else {
237
- console.log(chalk.yellow("Saved API key removed."));
238
- }
239
- }));
232
+ .action(withCommandErrorHandling(program, async () => {
233
+ await clearApiKey();
234
+ if (program.opts().json) {
235
+ console.log(JSON.stringify({ success: true, cleared: true }));
236
+ } else {
237
+ console.log(chalk.yellow("Saved API key removed."));
238
+ }
239
+ }));
240
240
 
241
241
  program
242
242
  .command("auth:status")
243
243
  .description("Show where auth is currently resolved from")
244
- .action(withCommandErrorHandling(program, async () => {
245
- if (runtimeApiKey) {
246
- if (program.opts().json) {
247
- console.log(JSON.stringify({ authenticated: true, source: "runtime_flag", token: maskToken(runtimeApiKey) }));
248
- } else {
249
- console.log(chalk.green(`Auth source: runtime CLI flag (${maskToken(runtimeApiKey)})`));
250
- }
251
- return;
252
- }
253
-
254
- if (process.env.NUELINK_API_KEY) {
255
- if (program.opts().json) {
256
- console.log(JSON.stringify({ authenticated: true, source: "environment", token: maskToken(process.env.NUELINK_API_KEY) }));
257
- } else {
258
- console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
259
- }
260
- return;
261
- }
244
+ .action(withCommandErrorHandling(program, async () => {
245
+ if (runtimeApiKey) {
246
+ if (program.opts().json) {
247
+ console.log(JSON.stringify({ authenticated: true, source: "runtime_flag", token: maskToken(runtimeApiKey) }));
248
+ } else {
249
+ console.log(chalk.green(`Auth source: runtime CLI flag (${maskToken(runtimeApiKey)})`));
250
+ }
251
+ return;
252
+ }
253
+
254
+ if (process.env.NUELINK_API_KEY) {
255
+ if (program.opts().json) {
256
+ console.log(JSON.stringify({ authenticated: true, source: "environment", token: maskToken(process.env.NUELINK_API_KEY) }));
257
+ } else {
258
+ console.log(chalk.green(`Auth source: NUELINK_API_KEY (${maskToken(process.env.NUELINK_API_KEY)})`));
259
+ }
260
+ return;
261
+ }
262
262
 
263
263
  const config = await readConfig();
264
- const storedApiKey = decryptApiKey(config);
265
- if (storedApiKey) {
266
- let lastUpdated;
267
-
268
- try {
269
- const fileStat = await stat(CONFIG_FILE);
270
- lastUpdated = fileStat.mtime.toISOString();
271
- } catch {
272
- // Ignore non-critical stat failure.
273
- }
274
-
275
- if (program.opts().json) {
276
- console.log(JSON.stringify({
277
- authenticated: true,
278
- source: "saved_config",
279
- token: maskToken(storedApiKey),
280
- configPath: CONFIG_FILE,
281
- lastUpdated: lastUpdated || null,
282
- }));
283
- } else {
284
- console.log(chalk.green(`Auth source: saved config (${maskToken(storedApiKey)})`));
285
- console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
286
- if (lastUpdated) console.log(chalk.blue(`Last updated: ${lastUpdated}`));
287
- }
288
-
289
- return;
290
- }
291
-
292
- throw new CliError(
293
- "AUTH_MISSING",
294
- "No API key configured. Use auth:login to save one, or pass --api-key for a single command.",
295
- );
296
- }));
297
-
298
- program
299
- .command("me")
300
- .description("Get current profile")
301
- .action(withCommandErrorHandling(program, async () => {
264
+ const storedApiKey = decryptApiKey(config);
265
+ if (storedApiKey) {
266
+ let lastUpdated;
267
+
268
+ try {
269
+ const fileStat = await stat(CONFIG_FILE);
270
+ lastUpdated = fileStat.mtime.toISOString();
271
+ } catch {
272
+ // Ignore non-critical stat failure.
273
+ }
274
+
275
+ if (program.opts().json) {
276
+ console.log(JSON.stringify({
277
+ authenticated: true,
278
+ source: "saved_config",
279
+ token: maskToken(storedApiKey),
280
+ configPath: CONFIG_FILE,
281
+ lastUpdated: lastUpdated || null,
282
+ }));
283
+ } else {
284
+ console.log(chalk.green(`Auth source: saved config (${maskToken(storedApiKey)})`));
285
+ console.log(chalk.blue(`Config path: ${CONFIG_FILE}`));
286
+ if (lastUpdated) console.log(chalk.blue(`Last updated: ${lastUpdated}`));
287
+ }
288
+
289
+ return;
290
+ }
291
+
292
+ throw new CliError(
293
+ "AUTH_MISSING",
294
+ "No API key configured. Use auth:login to save one, or pass --api-key for a single command.",
295
+ );
296
+ }));
297
+
298
+ program
299
+ .command("me")
300
+ .description("Get current profile")
301
+ .action(withCommandErrorHandling(program, async () => {
302
302
  await executeRequest(program, runtimeApiKey, { endpoint: "/me" });
303
303
  }));
304
304
 
305
- program
306
- .command("brands")
305
+ program
306
+ .command("brands")
307
307
  .description("List brands")
308
308
  .option("--per-page <number>", "Items per page", "25")
309
309
  .option("--page <number>", "Page number", "1")
310
- .action(withCommandErrorHandling(program, async (options) => {
310
+ .action(withCommandErrorHandling(program, async (options) => {
311
311
  await executeRequest(program, runtimeApiKey, {
312
312
  endpoint: "/brands",
313
313
  query: {
@@ -317,13 +317,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
317
317
  });
318
318
  }));
319
319
 
320
- program
321
- .command("collections")
320
+ program
321
+ .command("collections")
322
322
  .description("List collections for a brand")
323
323
  .requiredOption("--brand-id <id>", "Brand ID")
324
324
  .option("--per-page <number>", "Items per page", "25")
325
325
  .option("--page <number>", "Page number", "1")
326
- .action(withCommandErrorHandling(program, async (options) => {
326
+ .action(withCommandErrorHandling(program, async (options) => {
327
327
  await executeRequest(program, runtimeApiKey, {
328
328
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
329
329
  query: {
@@ -333,8 +333,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
333
333
  });
334
334
  }));
335
335
 
336
- program
337
- .command("collections:create")
336
+ program
337
+ .command("collections:create")
338
338
  .description("Create a collection")
339
339
  .requiredOption("--brand-id <id>", "Brand ID")
340
340
  .requiredOption("--title <title>", "Collection title")
@@ -342,7 +342,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
342
342
  .option("--max-republish <number>", "Max republish")
343
343
  .option("--channels <ids>", "Comma-separated channel IDs")
344
344
  .option("--queues <slots>", "Comma-separated queue slots (e.g. Mon 10:10,Mon 12:12)")
345
- .action(withCommandErrorHandling(program, async (options) => {
345
+ .action(withCommandErrorHandling(program, async (options) => {
346
346
  const channels = splitCsv(options.channels).map((id) => parsePositiveInteger(id, "channel-id"));
347
347
  const queues = validateQueueSlots(splitCsv(options.queues));
348
348
 
@@ -350,7 +350,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
350
350
  method: "POST",
351
351
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/collections`,
352
352
  body: {
353
- title: validateRequiredString(options.title, 255, "title"),
353
+ title: validateRequiredString(options.title, 255, "title"),
354
354
  description: validateMaxLength(options.description, 1000, "description"),
355
355
  maxRepublish: parseOptionalNonNegativeInteger(options.maxRepublish, "max-republish"),
356
356
  channels,
@@ -359,13 +359,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
359
359
  });
360
360
  }));
361
361
 
362
- program
363
- .command("automations")
362
+ program
363
+ .command("automations")
364
364
  .description("List automations for a brand")
365
365
  .requiredOption("--brand-id <id>", "Brand ID")
366
366
  .option("--per-page <number>", "Items per page", "25")
367
367
  .option("--page <number>", "Page number", "1")
368
- .action(withCommandErrorHandling(program, async (options) => {
368
+ .action(withCommandErrorHandling(program, async (options) => {
369
369
  await executeRequest(program, runtimeApiKey, {
370
370
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
371
371
  query: {
@@ -375,8 +375,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
375
375
  });
376
376
  }));
377
377
 
378
- program
379
- .command("automations:create")
378
+ program
379
+ .command("automations:create")
380
380
  .description("Create an automation")
381
381
  .requiredOption("--brand-id <id>", "Brand ID")
382
382
  .requiredOption("--collection-id <id>", "Collection ID")
@@ -391,7 +391,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
391
391
  .option("--load-old-posts <boolean>", "Import existing feed items: true/false")
392
392
  .option("--add-posts-as-draft <boolean>", "Create imported posts as drafts: true/false")
393
393
  .option("--refresh-rate <hours>", "Refresh interval (24, 12, 6, or 1 hours)")
394
- .action(withCommandErrorHandling(program, async (options) => {
394
+ .action(withCommandErrorHandling(program, async (options) => {
395
395
  await executeRequest(program, runtimeApiKey, {
396
396
  method: "POST",
397
397
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/automations`,
@@ -400,7 +400,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
400
400
  feedUrl: validateHttpUrl(options.feedUrl, "feed-url"),
401
401
  importAsType: normalizeEnum(options.importAsType, "import-as-type", VALID_IMPORT_AS_TYPES),
402
402
  subType: normalizeEnum(options.subType, "sub-type", VALID_AUTOMATION_SUB_TYPES),
403
- title: validateRequiredString(options.title, 255, "title"),
403
+ title: validateRequiredString(options.title, 255, "title"),
404
404
  type: normalizeEnum(options.type, "type", VALID_AUTOMATION_TYPES),
405
405
  dynamicTitle: validateMaxLength(options.dynamicTitle, 255, "dynamic-title"),
406
406
  dynamicBody: validateMaxLength(options.dynamicBody, 255, "dynamic-body"),
@@ -414,13 +414,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
414
414
  });
415
415
  }));
416
416
 
417
- program
418
- .command("channels")
417
+ program
418
+ .command("channels")
419
419
  .description("List channels for a brand")
420
420
  .requiredOption("--brand-id <id>", "Brand ID")
421
421
  .option("--per-page <number>", "Items per page", "25")
422
422
  .option("--page <number>", "Page number", "1")
423
- .action(withCommandErrorHandling(program, async (options) => {
423
+ .action(withCommandErrorHandling(program, async (options) => {
424
424
  await executeRequest(program, runtimeApiKey, {
425
425
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/channels`,
426
426
  query: {
@@ -430,14 +430,14 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
430
430
  });
431
431
  }));
432
432
 
433
- program
434
- .command("media")
433
+ program
434
+ .command("media")
435
435
  .description("List media for a brand")
436
436
  .requiredOption("--brand-id <id>", "Brand ID")
437
437
  .option("--type <type>", `Media type filter (${VALID_MEDIA_FILTER_TYPES.join(", ")})`)
438
438
  .option("--per-page <number>", "Items per page", "25")
439
439
  .option("--page <number>", "Page number", "1")
440
- .action(withCommandErrorHandling(program, async (options) => {
440
+ .action(withCommandErrorHandling(program, async (options) => {
441
441
  await executeRequest(program, runtimeApiKey, {
442
442
  endpoint: `${brandPath(parsePositiveInteger(options.brandId, "brand-id"))}/media`,
443
443
  query: {
@@ -450,29 +450,29 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
450
450
  });
451
451
  }));
452
452
 
453
- program
454
- .command("media:upload")
453
+ program
454
+ .command("media:upload")
455
455
  .description("Upload a media file")
456
456
  .requiredOption("--brand-id <id>", "Brand ID")
457
457
  .requiredOption("--file <path>", "Path to local file")
458
- .action(withCommandErrorHandling(program, async (options) => {
459
- const brandId = parsePositiveInteger(options.brandId, "brand-id");
460
- const fileStat = await stat(options.file);
461
- const { mediaType, size } = validateMediaFile(options.file, fileStat);
462
- let multipart = true;
463
-
464
- if (!program.opts().dryRun) {
465
- const formData = new FormData();
466
- const fileBuffer = await readFile(options.file);
467
- const fileBlob = new Blob([fileBuffer], { type: mediaType });
468
- formData.append("media", fileBlob, path.basename(options.file));
469
- multipart = formData;
470
- }
458
+ .action(withCommandErrorHandling(program, async (options) => {
459
+ const brandId = parsePositiveInteger(options.brandId, "brand-id");
460
+ const fileStat = await stat(options.file);
461
+ const { mediaType, size } = validateMediaFile(options.file, fileStat);
462
+ let multipart = true;
463
+
464
+ if (!program.opts().dryRun) {
465
+ const formData = new FormData();
466
+ const fileBuffer = await readFile(options.file);
467
+ const fileBlob = new Blob([fileBuffer], { type: mediaType });
468
+ formData.append("media", fileBlob, path.basename(options.file));
469
+ multipart = formData;
470
+ }
471
471
 
472
472
  await executeRequest(program, runtimeApiKey, {
473
473
  method: "POST",
474
474
  endpoint: `${brandPath(brandId)}/media`,
475
- multipart,
475
+ multipart,
476
476
  dryRunBody: {
477
477
  file: path.basename(options.file),
478
478
  size,
@@ -481,14 +481,14 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
481
481
  });
482
482
  }));
483
483
 
484
- program
485
- .command("posts")
484
+ program
485
+ .command("posts")
486
486
  .description("List posts in a collection")
487
487
  .requiredOption("--brand-id <id>", "Brand ID")
488
488
  .requiredOption("--collection-id <id>", "Collection ID")
489
489
  .option("--per-page <number>", "Items per page", "25")
490
490
  .option("--page <number>", "Page number", "1")
491
- .action(withCommandErrorHandling(program, async (options) => {
491
+ .action(withCommandErrorHandling(program, async (options) => {
492
492
  await executeRequest(program, runtimeApiKey, {
493
493
  endpoint: `${collectionPath(
494
494
  parsePositiveInteger(options.brandId, "brand-id"),
@@ -501,13 +501,13 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
501
501
  });
502
502
  }));
503
503
 
504
- program
505
- .command("posts:add-json")
504
+ program
505
+ .command("posts:add-json")
506
506
  .description("Create a post using a JSON payload file")
507
507
  .requiredOption("--brand-id <id>", "Brand ID")
508
508
  .requiredOption("--collection-id <id>", "Collection ID")
509
509
  .requiredOption("--payload <file>", "Path to JSON payload file")
510
- .action(withCommandErrorHandling(program, async (options) => {
510
+ .action(withCommandErrorHandling(program, async (options) => {
511
511
  const payloadText = options.payload === "-"
512
512
  ? await readStdinText()
513
513
  : await readFile(options.payload, "utf8");
@@ -523,8 +523,8 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
523
523
  });
524
524
  }));
525
525
 
526
- program
527
- .command("posts:create")
526
+ program
527
+ .command("posts:create")
528
528
  .description("Create a post using CLI options")
529
529
  .requiredOption("--brand-id <id>", "Brand ID")
530
530
  .requiredOption("--collection-id <id>", "Collection ID")
@@ -532,6 +532,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
532
532
  .option("--caption <text>", "Post caption/body")
533
533
  .option("--alt <text>", "Alt text")
534
534
  .option("--link <url>", "Post link")
535
+ .option("--auto-thread-text <boolean>", "Automatically thread text: true/false")
535
536
  .option("--publish-mode <mode>", `Publish mode (${VALID_PUBLISH_MODES.join(", ")})`, "DRAFT")
536
537
  .option("--scheduled-at <value>", "Publish datetime (YYYY-MM-DD HH:mm:ss) or null")
537
538
  .option("--post-as-story <boolean>", "Post as story: true/false")
@@ -556,7 +557,7 @@ function registerCommands(program, runtimeApiKey, cliVersion) {
556
557
  .option("--youtube-tags <tags>", "Comma-separated YouTube tags")
557
558
  .option("--youtube-playlists <json>", "YouTube playlists JSON string")
558
559
  .option("--googlemybusiness-upload-to-photos-section <boolean>", "Upload to Google Business Profile photos: true/false")
559
- .action(withCommandErrorHandling(program, async (options) => {
560
+ .action(withCommandErrorHandling(program, async (options) => {
560
561
  const payload = buildPostPayload(options);
561
562
 
562
563
  await executeRequest(program, runtimeApiKey, {
@@ -4,9 +4,9 @@ import {
4
4
  parseOptionalNonNegativeInteger,
5
5
  splitCsv,
6
6
  validateHttpUrl,
7
- validatePollOptions,
8
- validateRequiredString,
9
- validateScheduledAt,
7
+ validatePollOptions,
8
+ validateRequiredString,
9
+ validateScheduledAt,
10
10
  } from "./validation.js";
11
11
 
12
12
  const VALID_PUBLISH_MODES = ["DRAFT", "QUEUE", "SCHEDULE", "IMMEDIATE"];
@@ -80,16 +80,19 @@ function validateRawPostPayload(payload) {
80
80
  validateOptionalLength(payload.title, 255, "title");
81
81
  validateOptionalLength(payload.caption, 3000, "caption");
82
82
  validateOptionalLength(payload.alt, 255, "alt");
83
+ if (payload.autoThreadText !== undefined && payload.autoThreadText !== null && typeof payload.autoThreadText !== "boolean") {
84
+ throw new Error("Invalid autoThreadText. Expected a boolean or null.");
85
+ }
83
86
  if (payload.link !== undefined) {
84
87
  validateHttpUrl(payload.link, "link");
85
88
  }
86
89
 
87
- const poll = payload.poll;
88
- const caption = !poll
89
- ? validateRequiredString(payload.caption, 3000, "caption")
90
- : payload.caption === undefined
91
- ? undefined
92
- : String(payload.caption).trim();
90
+ const poll = payload.poll;
91
+ const caption = !poll
92
+ ? validateRequiredString(payload.caption, 3000, "caption")
93
+ : payload.caption === undefined
94
+ ? undefined
95
+ : String(payload.caption).trim();
93
96
  if (poll !== undefined) {
94
97
  if (!poll || typeof poll !== "object" || Array.isArray(poll)) {
95
98
  throw new Error("Invalid poll. Expected a JSON object.");
@@ -123,15 +126,15 @@ function validateRawPostPayload(payload) {
123
126
  });
124
127
  }
125
128
 
126
- return {
127
- ...payload,
128
- ...(payload.caption !== undefined ? { caption } : {}),
129
- publishMode,
129
+ return {
130
+ ...payload,
131
+ ...(payload.caption !== undefined ? { caption } : {}),
132
+ publishMode,
130
133
  ...(payload.scheduledAt !== undefined ? { scheduledAt } : {}),
131
134
  };
132
135
  }
133
136
 
134
- function buildPostPayload(options) {
137
+ function buildPostPayload(options) {
135
138
  const media = mergeMedia(options.mediaIds, options.mediaUrls);
136
139
  const publishMode = normalizePublishMode(options.publishMode);
137
140
  const scheduledAt = validateScheduledAt(options.scheduledAt);
@@ -256,11 +259,11 @@ function buildPostPayload(options) {
256
259
  };
257
260
 
258
261
  const hasPoll = Object.keys(poll).length > 0;
259
- const caption = !hasPoll
260
- ? validateRequiredString(options.caption, 3000, "caption")
261
- : options.caption === undefined
262
- ? undefined
263
- : String(options.caption).trim();
262
+ const caption = !hasPoll
263
+ ? validateRequiredString(options.caption, 3000, "caption")
264
+ : options.caption === undefined
265
+ ? undefined
266
+ : String(options.caption).trim();
264
267
  if (hasPoll && (!poll.question || poll.options?.length < 2 || !poll.period)) {
265
268
  throw new Error("poll requires question, 2 to 4 options, and period.");
266
269
  }
@@ -270,11 +273,14 @@ function buildPostPayload(options) {
270
273
 
271
274
  return {
272
275
  ...(options.title ? { title: options.title } : {}),
273
- ...(caption ? { caption } : {}),
276
+ ...(caption ? { caption } : {}),
274
277
  ...(options.alt ? { alt: options.alt } : {}),
275
278
  ...(options.link ? { link: validateHttpUrl(options.link, "link") } : {}),
276
279
  publishMode,
277
280
  scheduledAt,
281
+ ...(parseBooleanStrict(options.autoThreadText, "auto-thread-text") !== undefined
282
+ ? { autoThreadText: parseBooleanStrict(options.autoThreadText, "auto-thread-text") }
283
+ : {}),
278
284
  ...(parseBooleanStrict(options.postAsStory, "post-as-story") !== undefined
279
285
  ? { postAsStory: parseBooleanStrict(options.postAsStory, "post-as-story") }
280
286
  : {}),
package/test/cli.test.mjs CHANGED
@@ -2,7 +2,7 @@ import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
- import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
5
+ import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { pathToFileURL } from "node:url";
@@ -23,7 +23,7 @@ function currentApiKey() {
23
23
  return process.env.NUELINK_API_KEY || "test_api_key";
24
24
  }
25
25
 
26
- function runCli({ args, homeDir, capturePath, withMock = true, input, extraEnv = {} }) {
26
+ function runCli({ args, homeDir, capturePath, withMock = true, input, extraEnv = {} }) {
27
27
  const nodeArgs = withMock
28
28
  ? ["--require", mockCjsPath, mainPath, ...args]
29
29
  : [mainPath, ...args];
@@ -41,16 +41,16 @@ function runCli({ args, homeDir, capturePath, withMock = true, input, extraEnv =
41
41
  },
42
42
  input,
43
43
  });
44
- }
45
-
46
- function assertJsonError(result, code) {
47
- assert.equal(result.status, 1, result.stderr);
48
- assert.equal(result.stderr, "");
49
- const output = JSON.parse(result.stdout);
50
- assert.equal(output.success, false);
51
- assert.equal(output.error.code, code);
52
- return output.error;
53
- }
44
+ }
45
+
46
+ function assertJsonError(result, code) {
47
+ assert.equal(result.status, 1, result.stderr);
48
+ assert.equal(result.stderr, "");
49
+ const output = JSON.parse(result.stdout);
50
+ assert.equal(output.success, false);
51
+ assert.equal(output.error.code, code);
52
+ return output.error;
53
+ }
54
54
 
55
55
  test("brands command builds pagination query", async () => {
56
56
  const homeDir = await setupTempHome();
@@ -211,7 +211,7 @@ test("version flags print package version", async () => {
211
211
  });
212
212
 
213
213
  assert.equal(result.status, 0, result.stderr);
214
- assert.equal(result.stdout.trim(), "1.4.1");
214
+ assert.equal(result.stdout.trim(), "1.4.1");
215
215
  assert.equal(result.stderr, "");
216
216
  }
217
217
  });
@@ -298,7 +298,7 @@ test("automations:create works when boolean flags are omitted", async () => {
298
298
  assert.equal(capture.body.addPostsAsDraft, undefined);
299
299
  });
300
300
 
301
- test("auth:login stores token in isolated home config", async () => {
301
+ test("auth:login stores token in isolated home config", async () => {
302
302
  const homeDir = await setupTempHome();
303
303
  const result = runCli({
304
304
  args: ["auth:login", "--stdin"],
@@ -316,44 +316,44 @@ test("auth:login stores token in isolated home config", async () => {
316
316
  assert.equal(config.apiKey, undefined);
317
317
  assert.equal(typeof config.encryptedApiKey, "string");
318
318
  assert.equal(typeof config.iv, "string");
319
- assert.equal(typeof config.authTag, "string");
320
- assert.deepEqual(
321
- (await readdir(path.dirname(configPath))).filter((name) => name.endsWith(".tmp")),
322
- [],
323
- );
324
- });
325
-
326
- test("auth:clear atomically replaces an existing saved config", async () => {
327
- const homeDir = await setupTempHome();
328
- const capturePath = path.join(homeDir, "capture-auth-clear.json");
329
-
330
- const login = runCli({
331
- args: ["auth:login", "--stdin"],
332
- homeDir,
333
- capturePath,
334
- withMock: false,
335
- input: "saved_token\n",
336
- extraEnv: { NUELINK_API_KEY: "" },
337
- });
338
- assert.equal(login.status, 0, login.stderr);
339
-
340
- const clear = runCli({
341
- args: ["--json", "auth:clear"],
342
- homeDir,
343
- capturePath,
344
- withMock: false,
345
- extraEnv: { NUELINK_API_KEY: "" },
346
- });
347
- assert.equal(clear.status, 0, clear.stderr);
348
- assert.deepEqual(JSON.parse(clear.stdout), { success: true, cleared: true });
349
-
350
- const configPath = path.join(homeDir, ".nuelink-cli", "config.json");
351
- assert.deepEqual(JSON.parse(await readFile(configPath, "utf8")), {});
352
- assert.deepEqual(
353
- (await readdir(path.dirname(configPath))).filter((name) => name.endsWith(".tmp")),
354
- [],
355
- );
356
- });
319
+ assert.equal(typeof config.authTag, "string");
320
+ assert.deepEqual(
321
+ (await readdir(path.dirname(configPath))).filter((name) => name.endsWith(".tmp")),
322
+ [],
323
+ );
324
+ });
325
+
326
+ test("auth:clear atomically replaces an existing saved config", async () => {
327
+ const homeDir = await setupTempHome();
328
+ const capturePath = path.join(homeDir, "capture-auth-clear.json");
329
+
330
+ const login = runCli({
331
+ args: ["auth:login", "--stdin"],
332
+ homeDir,
333
+ capturePath,
334
+ withMock: false,
335
+ input: "saved_token\n",
336
+ extraEnv: { NUELINK_API_KEY: "" },
337
+ });
338
+ assert.equal(login.status, 0, login.stderr);
339
+
340
+ const clear = runCli({
341
+ args: ["--json", "auth:clear"],
342
+ homeDir,
343
+ capturePath,
344
+ withMock: false,
345
+ extraEnv: { NUELINK_API_KEY: "" },
346
+ });
347
+ assert.equal(clear.status, 0, clear.stderr);
348
+ assert.deepEqual(JSON.parse(clear.stdout), { success: true, cleared: true });
349
+
350
+ const configPath = path.join(homeDir, ".nuelink-cli", "config.json");
351
+ assert.deepEqual(JSON.parse(await readFile(configPath, "utf8")), {});
352
+ assert.deepEqual(
353
+ (await readdir(path.dirname(configPath))).filter((name) => name.endsWith(".tmp")),
354
+ [],
355
+ );
356
+ });
357
357
 
358
358
  test("runtime api key is exposed as a runtime auth source", async () => {
359
359
  const homeDir = await setupTempHome();
@@ -475,6 +475,7 @@ test("posts:add-json forwards payload file to API", async () => {
475
475
  title: "post title",
476
476
  caption: "post body",
477
477
  publishMode: "DRAFT",
478
+ autoThreadText: true,
478
479
  };
479
480
 
480
481
  await writeFile(payloadPath, JSON.stringify(payload, null, 2), "utf8");
@@ -560,6 +561,20 @@ test("posts:add-json validates calendar dates", async () => {
560
561
  assert.match(result.stderr, /Invalid scheduled-at/);
561
562
  });
562
563
 
564
+ test("posts:add-json rejects invalid autoThreadText values", async () => {
565
+ const homeDir = await setupTempHome();
566
+
567
+ const result = runCli({
568
+ args: ["posts:add-json", "--brand-id", "10", "--collection-id", "20", "--payload", "-"],
569
+ homeDir,
570
+ capturePath: path.join(homeDir, "capture-posts-invalid-auto-thread-text.json"),
571
+ input: JSON.stringify({ caption: "post", publishMode: "DRAFT", autoThreadText: "true" }),
572
+ });
573
+
574
+ assert.equal(result.status, 1);
575
+ assert.match(result.stderr, /Invalid autoThreadText/);
576
+ });
577
+
563
578
  test("dry-run prints validated request without sending", async () => {
564
579
  const homeDir = await setupTempHome();
565
580
  const capturePath = path.join(homeDir, "capture-dry-run.json");
@@ -612,6 +627,8 @@ test("posts:create builds full payload from options", async () => {
612
627
  "alt text",
613
628
  "--link",
614
629
  "https://nuelink.com",
630
+ "--auto-thread-text",
631
+ "true",
615
632
  "--publish-mode",
616
633
  "DRAFT",
617
634
  "--post-as-story",
@@ -669,6 +686,7 @@ test("posts:create builds full payload from options", async () => {
669
686
  assert.equal(capture.method, "POST");
670
687
  assert.equal(capture.body.title, "title here");
671
688
  assert.equal(capture.body.caption, "body here");
689
+ assert.equal(capture.body.autoThreadText, true);
672
690
  assert.equal(capture.body.postAsStory, true);
673
691
  assert.equal(capture.body.comment.delay, 30);
674
692
  assert.deepEqual(capture.body.media, [
@@ -992,7 +1010,7 @@ test("timeouts exit non-zero", async () => {
992
1010
  assert.match(result.stderr, /Request timed out/);
993
1011
  });
994
1012
 
995
- test("malformed JSON success responses fail as protocol errors", async () => {
1013
+ test("malformed JSON success responses fail as protocol errors", async () => {
996
1014
  const homeDir = await setupTempHome();
997
1015
 
998
1016
  const result = runCli({
@@ -1004,172 +1022,172 @@ test("malformed JSON success responses fail as protocol errors", async () => {
1004
1022
  },
1005
1023
  });
1006
1024
 
1007
- const error = assertJsonError(result, "PROTOCOL_ERROR");
1008
- assert.match(error.message, /Protocol error: expected a JSON response/);
1009
- assert.equal(error.httpStatus, 200);
1010
- });
1011
-
1012
- for (const fixture of [
1013
- {
1014
- name: "collection titles",
1015
- args: ["collections:create", "--brand-id", "1", "--title", " ", "--dry-run"],
1016
- },
1017
- {
1018
- name: "automation titles",
1019
- args: [
1020
- "automations:create", "--brand-id", "1", "--collection-id", "2",
1021
- "--feed-url", "https://example.com/feed.xml", "--import-as-type", "IMAGE",
1022
- "--sub-type", "RSS", "--title", " ", "--dry-run",
1023
- ],
1024
- },
1025
- {
1026
- name: "post captions",
1027
- args: ["posts:create", "--brand-id", "1", "--collection-id", "2", "--caption", " ", "--dry-run"],
1028
- },
1029
- ]) {
1030
- test(`rejects whitespace-only ${fixture.name}`, async () => {
1031
- const homeDir = await setupTempHome();
1032
- const result = runCli({
1033
- args: fixture.args,
1034
- homeDir,
1035
- capturePath: path.join(homeDir, `capture-blank-${fixture.name}.json`),
1036
- });
1037
-
1038
- assert.equal(result.status, 1);
1039
- assert.match(result.stderr, /must not be blank/);
1040
- });
1041
- }
1042
-
1043
- test("--json emits one structured object for missing authentication", async () => {
1044
- const homeDir = await setupTempHome();
1045
- const result = runCli({
1046
- args: ["--json", "brands"],
1047
- homeDir,
1048
- capturePath: path.join(homeDir, "capture-json-auth.json"),
1049
- extraEnv: { NUELINK_API_KEY: "" },
1050
- });
1051
-
1052
- assertJsonError(result, "AUTH_MISSING");
1053
- });
1054
-
1055
- test("--json emits one structured object for validation errors", async () => {
1056
- const homeDir = await setupTempHome();
1057
- const result = runCli({
1058
- args: ["--json", "collections:create", "--brand-id", "1", "--title", " ", "--dry-run"],
1059
- homeDir,
1060
- capturePath: path.join(homeDir, "capture-json-validation.json"),
1061
- });
1062
-
1063
- assertJsonError(result, "VALIDATION_ERROR");
1064
- });
1065
-
1066
- test("--json emits one structured object for command usage errors", async () => {
1067
- const homeDir = await setupTempHome();
1068
- const result = runCli({
1069
- args: ["--json", "collections"],
1070
- homeDir,
1071
- capturePath: path.join(homeDir, "capture-json-usage.json"),
1072
- });
1073
-
1074
- assertJsonError(result, "USAGE_ERROR");
1075
- });
1076
-
1077
- test("--json emits one structured object for HTTP errors", async () => {
1078
- const homeDir = await setupTempHome();
1079
- const result = runCli({
1080
- args: ["--json", "brands"],
1081
- homeDir,
1082
- capturePath: path.join(homeDir, "capture-json-http.json"),
1083
- extraEnv: {
1084
- NUELINK_MOCK_FAIL_COUNT: "1",
1085
- NUELINK_MOCK_FAIL_STATUS: "422",
1086
- NUELINK_MOCK_FAIL_PATH: "/brands",
1087
- NUELINK_GET_RETRIES: "0",
1088
- },
1089
- });
1090
-
1091
- const error = assertJsonError(result, "HTTP_ERROR");
1092
- assert.equal(error.httpStatus, 422);
1093
- });
1094
-
1095
- test("--json reports malformed config without silently ignoring it", async () => {
1096
- const homeDir = await setupTempHome();
1097
- const configDir = path.join(homeDir, ".nuelink-cli");
1098
- await mkdir(configDir, { recursive: true });
1099
- await writeFile(path.join(configDir, "config.json"), "{not-json}", "utf8");
1100
-
1101
- const result = runCli({
1102
- args: ["--json", "auth:status"],
1103
- homeDir,
1104
- capturePath: path.join(homeDir, "capture-json-config.json"),
1105
- withMock: false,
1106
- extraEnv: { NUELINK_API_KEY: "" },
1107
- });
1108
-
1109
- assertJsonError(result, "CONFIG_INVALID");
1110
- });
1111
-
1112
- test("--json reports corrupted saved credentials", async () => {
1113
- const homeDir = await setupTempHome();
1114
- const configDir = path.join(homeDir, ".nuelink-cli");
1115
- await mkdir(configDir, { recursive: true });
1116
- await writeFile(path.join(configDir, "config.json"), JSON.stringify({
1117
- version: 1,
1118
- encryptedApiKey: "invalid",
1119
- iv: "invalid",
1120
- authTag: "invalid",
1121
- }), "utf8");
1122
-
1123
- const result = runCli({
1124
- args: ["--json", "auth:status"],
1125
- homeDir,
1126
- capturePath: path.join(homeDir, "capture-json-corrupt-config.json"),
1127
- withMock: false,
1128
- extraEnv: { NUELINK_API_KEY: "" },
1129
- });
1130
-
1131
- assertJsonError(result, "CONFIG_INVALID");
1132
- });
1133
-
1134
- test("auth:login refuses an unsafe config directory path", async () => {
1135
- const homeDir = await setupTempHome();
1136
- await writeFile(path.join(homeDir, ".nuelink-cli"), "not-a-directory", "utf8");
1137
-
1138
- const result = runCli({
1139
- args: ["--json", "auth:login", "--stdin"],
1140
- homeDir,
1141
- capturePath: path.join(homeDir, "capture-unsafe-config.json"),
1142
- withMock: false,
1143
- input: "saved_token\n",
1144
- extraEnv: { NUELINK_API_KEY: "" },
1145
- });
1146
-
1147
- assertJsonError(result, "CONFIG_UNSAFE");
1148
- });
1149
-
1150
- test("--json emits one structured object for timeouts", async () => {
1151
- const homeDir = await setupTempHome();
1152
- const result = runCli({
1153
- args: ["--json", "brands"],
1154
- homeDir,
1155
- capturePath: path.join(homeDir, "capture-json-timeout.json"),
1156
- extraEnv: { NUELINK_MOCK_THROW_TIMEOUT: "1" },
1157
- });
1158
-
1159
- assertJsonError(result, "TIMEOUT");
1160
- });
1161
-
1162
- test("invalid timeout and retry environment values fail before a request", async () => {
1163
- const homeDir = await setupTempHome();
1164
- const result = runCli({
1165
- args: ["--json", "brands"],
1166
- homeDir,
1167
- capturePath: path.join(homeDir, "capture-invalid-timeout.json"),
1168
- extraEnv: { NUELINK_TIMEOUT_MS: "not-a-number" },
1169
- });
1170
-
1171
- assertJsonError(result, "CONFIG_INVALID");
1172
- });
1025
+ const error = assertJsonError(result, "PROTOCOL_ERROR");
1026
+ assert.match(error.message, /Protocol error: expected a JSON response/);
1027
+ assert.equal(error.httpStatus, 200);
1028
+ });
1029
+
1030
+ for (const fixture of [
1031
+ {
1032
+ name: "collection titles",
1033
+ args: ["collections:create", "--brand-id", "1", "--title", " ", "--dry-run"],
1034
+ },
1035
+ {
1036
+ name: "automation titles",
1037
+ args: [
1038
+ "automations:create", "--brand-id", "1", "--collection-id", "2",
1039
+ "--feed-url", "https://example.com/feed.xml", "--import-as-type", "IMAGE",
1040
+ "--sub-type", "RSS", "--title", " ", "--dry-run",
1041
+ ],
1042
+ },
1043
+ {
1044
+ name: "post captions",
1045
+ args: ["posts:create", "--brand-id", "1", "--collection-id", "2", "--caption", " ", "--dry-run"],
1046
+ },
1047
+ ]) {
1048
+ test(`rejects whitespace-only ${fixture.name}`, async () => {
1049
+ const homeDir = await setupTempHome();
1050
+ const result = runCli({
1051
+ args: fixture.args,
1052
+ homeDir,
1053
+ capturePath: path.join(homeDir, `capture-blank-${fixture.name}.json`),
1054
+ });
1055
+
1056
+ assert.equal(result.status, 1);
1057
+ assert.match(result.stderr, /must not be blank/);
1058
+ });
1059
+ }
1060
+
1061
+ test("--json emits one structured object for missing authentication", async () => {
1062
+ const homeDir = await setupTempHome();
1063
+ const result = runCli({
1064
+ args: ["--json", "brands"],
1065
+ homeDir,
1066
+ capturePath: path.join(homeDir, "capture-json-auth.json"),
1067
+ extraEnv: { NUELINK_API_KEY: "" },
1068
+ });
1069
+
1070
+ assertJsonError(result, "AUTH_MISSING");
1071
+ });
1072
+
1073
+ test("--json emits one structured object for validation errors", async () => {
1074
+ const homeDir = await setupTempHome();
1075
+ const result = runCli({
1076
+ args: ["--json", "collections:create", "--brand-id", "1", "--title", " ", "--dry-run"],
1077
+ homeDir,
1078
+ capturePath: path.join(homeDir, "capture-json-validation.json"),
1079
+ });
1080
+
1081
+ assertJsonError(result, "VALIDATION_ERROR");
1082
+ });
1083
+
1084
+ test("--json emits one structured object for command usage errors", async () => {
1085
+ const homeDir = await setupTempHome();
1086
+ const result = runCli({
1087
+ args: ["--json", "collections"],
1088
+ homeDir,
1089
+ capturePath: path.join(homeDir, "capture-json-usage.json"),
1090
+ });
1091
+
1092
+ assertJsonError(result, "USAGE_ERROR");
1093
+ });
1094
+
1095
+ test("--json emits one structured object for HTTP errors", async () => {
1096
+ const homeDir = await setupTempHome();
1097
+ const result = runCli({
1098
+ args: ["--json", "brands"],
1099
+ homeDir,
1100
+ capturePath: path.join(homeDir, "capture-json-http.json"),
1101
+ extraEnv: {
1102
+ NUELINK_MOCK_FAIL_COUNT: "1",
1103
+ NUELINK_MOCK_FAIL_STATUS: "422",
1104
+ NUELINK_MOCK_FAIL_PATH: "/brands",
1105
+ NUELINK_GET_RETRIES: "0",
1106
+ },
1107
+ });
1108
+
1109
+ const error = assertJsonError(result, "HTTP_ERROR");
1110
+ assert.equal(error.httpStatus, 422);
1111
+ });
1112
+
1113
+ test("--json reports malformed config without silently ignoring it", async () => {
1114
+ const homeDir = await setupTempHome();
1115
+ const configDir = path.join(homeDir, ".nuelink-cli");
1116
+ await mkdir(configDir, { recursive: true });
1117
+ await writeFile(path.join(configDir, "config.json"), "{not-json}", "utf8");
1118
+
1119
+ const result = runCli({
1120
+ args: ["--json", "auth:status"],
1121
+ homeDir,
1122
+ capturePath: path.join(homeDir, "capture-json-config.json"),
1123
+ withMock: false,
1124
+ extraEnv: { NUELINK_API_KEY: "" },
1125
+ });
1126
+
1127
+ assertJsonError(result, "CONFIG_INVALID");
1128
+ });
1129
+
1130
+ test("--json reports corrupted saved credentials", async () => {
1131
+ const homeDir = await setupTempHome();
1132
+ const configDir = path.join(homeDir, ".nuelink-cli");
1133
+ await mkdir(configDir, { recursive: true });
1134
+ await writeFile(path.join(configDir, "config.json"), JSON.stringify({
1135
+ version: 1,
1136
+ encryptedApiKey: "invalid",
1137
+ iv: "invalid",
1138
+ authTag: "invalid",
1139
+ }), "utf8");
1140
+
1141
+ const result = runCli({
1142
+ args: ["--json", "auth:status"],
1143
+ homeDir,
1144
+ capturePath: path.join(homeDir, "capture-json-corrupt-config.json"),
1145
+ withMock: false,
1146
+ extraEnv: { NUELINK_API_KEY: "" },
1147
+ });
1148
+
1149
+ assertJsonError(result, "CONFIG_INVALID");
1150
+ });
1151
+
1152
+ test("auth:login refuses an unsafe config directory path", async () => {
1153
+ const homeDir = await setupTempHome();
1154
+ await writeFile(path.join(homeDir, ".nuelink-cli"), "not-a-directory", "utf8");
1155
+
1156
+ const result = runCli({
1157
+ args: ["--json", "auth:login", "--stdin"],
1158
+ homeDir,
1159
+ capturePath: path.join(homeDir, "capture-unsafe-config.json"),
1160
+ withMock: false,
1161
+ input: "saved_token\n",
1162
+ extraEnv: { NUELINK_API_KEY: "" },
1163
+ });
1164
+
1165
+ assertJsonError(result, "CONFIG_UNSAFE");
1166
+ });
1167
+
1168
+ test("--json emits one structured object for timeouts", async () => {
1169
+ const homeDir = await setupTempHome();
1170
+ const result = runCli({
1171
+ args: ["--json", "brands"],
1172
+ homeDir,
1173
+ capturePath: path.join(homeDir, "capture-json-timeout.json"),
1174
+ extraEnv: { NUELINK_MOCK_THROW_TIMEOUT: "1" },
1175
+ });
1176
+
1177
+ assertJsonError(result, "TIMEOUT");
1178
+ });
1179
+
1180
+ test("invalid timeout and retry environment values fail before a request", async () => {
1181
+ const homeDir = await setupTempHome();
1182
+ const result = runCli({
1183
+ args: ["--json", "brands"],
1184
+ homeDir,
1185
+ capturePath: path.join(homeDir, "capture-invalid-timeout.json"),
1186
+ extraEnv: { NUELINK_TIMEOUT_MS: "not-a-number" },
1187
+ });
1188
+
1189
+ assertJsonError(result, "CONFIG_INVALID");
1190
+ });
1173
1191
 
1174
1192
  test("empty success bodies return an empty object", async () => {
1175
1193
  const homeDir = await setupTempHome();