@nuelink/nuelink-cli 1.2.0 → 1.3.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/src/output.js ADDED
@@ -0,0 +1,183 @@
1
+ function toTitleCase(value) {
2
+ return String(value)
3
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
4
+ .replace(/[_-]+/g, " ")
5
+ .replace(/\s+/g, " ")
6
+ .trim()
7
+ .replace(/^./, (char) => char.toUpperCase());
8
+ }
9
+
10
+ function formatCell(value, maxLength = 42) {
11
+ if (value === undefined || value === null) {
12
+ return "";
13
+ }
14
+
15
+ let text;
16
+
17
+ if (typeof value === "string") {
18
+ text = value;
19
+ } else if (typeof value === "number" || typeof value === "boolean") {
20
+ text = String(value);
21
+ } else if (Array.isArray(value)) {
22
+ text = `[${value.map((item) => formatCell(item, 18)).join(", ")}]`;
23
+ } else {
24
+ text = JSON.stringify(value);
25
+ }
26
+
27
+ text = text.replace(/\s+/g, " ").trim();
28
+
29
+ if (text.length > maxLength) {
30
+ return `${text.slice(0, maxLength - 1)}…`;
31
+ }
32
+
33
+ return text;
34
+ }
35
+
36
+ function pickColumns(items) {
37
+ const preferredKeys = [
38
+ "id",
39
+ "title",
40
+ "name",
41
+ "description",
42
+ "status",
43
+ "type",
44
+ "subType",
45
+ "timezone",
46
+ "collectionId",
47
+ "postType",
48
+ "postingType",
49
+ "postDate",
50
+ "feedUrl",
51
+ "size",
52
+ "createdAt",
53
+ "updatedAt",
54
+ ];
55
+ const excludedKeys = new Set(["body", "caption", "media", "poll", "platforms", "queues", "channels"]);
56
+ const presentKeys = new Set(items.flatMap((item) => Object.keys(item)));
57
+
58
+ const columns = preferredKeys.filter((key) => presentKeys.has(key) && !excludedKeys.has(key));
59
+
60
+ for (const item of items) {
61
+ for (const key of Object.keys(item)) {
62
+ if (!excludedKeys.has(key) && !columns.includes(key)) {
63
+ columns.push(key);
64
+ }
65
+
66
+ if (columns.length >= 7) {
67
+ break;
68
+ }
69
+ }
70
+
71
+ if (columns.length >= 7) {
72
+ break;
73
+ }
74
+ }
75
+
76
+ return columns.slice(0, 7);
77
+ }
78
+
79
+ function renderTable(items) {
80
+ const columns = pickColumns(items);
81
+
82
+ if (columns.length === 0) {
83
+ return [];
84
+ }
85
+
86
+ const rows = items.map((item) => columns.map((column) => formatCell(item[column])));
87
+ const headers = columns.map((column) => toTitleCase(column));
88
+ const widths = headers.map((header, index) => {
89
+ const cellWidths = rows.map((row) => row[index].length);
90
+ return Math.max(header.length, 0, ...cellWidths);
91
+ });
92
+
93
+ const divider = `+${widths.map((width) => "-".repeat(width + 2)).join("+")}+`;
94
+ const renderRow = (values) => `| ${values.map((value, index) => value.padEnd(widths[index])).join(" | ")} |`;
95
+
96
+ return [
97
+ divider,
98
+ renderRow(headers),
99
+ divider,
100
+ ...rows.map(renderRow),
101
+ divider,
102
+ ];
103
+ }
104
+
105
+ function renderPagination(pagination) {
106
+ if (!pagination) {
107
+ return null;
108
+ }
109
+
110
+ const parts = [];
111
+
112
+ if (pagination.currentPage !== undefined && pagination.lastPage !== undefined) {
113
+ parts.push(`Page ${pagination.currentPage} of ${pagination.lastPage}`);
114
+ } else if (pagination.currentPage !== undefined) {
115
+ parts.push(`Page ${pagination.currentPage}`);
116
+ }
117
+
118
+ if (pagination.perPage !== undefined) {
119
+ parts.push(`${pagination.perPage} per page`);
120
+ }
121
+
122
+ if (pagination.total !== undefined) {
123
+ parts.push(`${pagination.total} total`);
124
+ }
125
+
126
+ if (pagination.nextPageUrl) {
127
+ try {
128
+ const nextPage = new URL(pagination.nextPageUrl).searchParams.get("page");
129
+ parts.push(nextPage ? `next page ${nextPage}` : "next page available");
130
+ } catch {
131
+ parts.push("next page available");
132
+ }
133
+ }
134
+
135
+ if (pagination.prevPageUrl) {
136
+ try {
137
+ const prevPage = new URL(pagination.prevPageUrl).searchParams.get("page");
138
+ parts.push(prevPage ? `prev page ${prevPage}` : "prev page available");
139
+ } catch {
140
+ parts.push("prev page available");
141
+ }
142
+ }
143
+
144
+ return parts.length > 0 ? `Pagination: ${parts.join(" | ")}` : null;
145
+ }
146
+
147
+ function printApiResponse(response, { outputMode = "json" } = {}) {
148
+ if (outputMode !== "table" || !response || !Array.isArray(response.data)) {
149
+ console.log(JSON.stringify(response, null, 2));
150
+ return;
151
+ }
152
+
153
+ const items = response.data;
154
+
155
+ if (items.length === 0) {
156
+ console.log("No results.");
157
+ const paginationLine = renderPagination(response.pagination);
158
+ if (paginationLine) {
159
+ console.log(paginationLine);
160
+ }
161
+ return;
162
+ }
163
+
164
+ const lines = renderTable(items);
165
+
166
+ if (lines.length === 0) {
167
+ console.log(JSON.stringify(response, null, 2));
168
+ return;
169
+ }
170
+
171
+ lines.forEach((line) => console.log(line));
172
+
173
+ const paginationLine = renderPagination(response.pagination);
174
+ if (paginationLine) {
175
+ console.log(paginationLine);
176
+ }
177
+ }
178
+
179
+ export {
180
+ printApiResponse,
181
+ renderPagination,
182
+ renderTable,
183
+ };
@@ -1,12 +1,17 @@
1
- function parseCsv(value) {
2
- if (!value) {
3
- return [];
4
- }
1
+ import {
2
+ parseBooleanStrict,
3
+ parseJsonString,
4
+ parseOptionalPositiveInteger,
5
+ splitCsv,
6
+ validateHttpUrl,
7
+ validatePollOptions,
8
+ validatePublishAt,
9
+ } from "./validation.js";
10
+
11
+ const VALID_PUBLISH_MODES = ["DRAFT", "QUEUE", "SCHEDULE", "IMMEDIATE"];
5
12
 
6
- return value
7
- .split(",")
8
- .map((item) => item.trim())
9
- .filter(Boolean);
13
+ function parseCsv(value) {
14
+ return splitCsv(value);
10
15
  }
11
16
 
12
17
  function parseBoolean(value) {
@@ -38,19 +43,43 @@ function parseNumber(value) {
38
43
 
39
44
  function mergeMedia(idsCsv, urlsCsv) {
40
45
  const idMedia = parseCsv(idsCsv).map((id) => ({ id }));
41
- const urlMedia = parseCsv(urlsCsv).map((url) => ({ url }));
46
+ const urlMedia = parseCsv(urlsCsv).map((url) => ({ url: validateHttpUrl(url, "media-url") }));
42
47
  return [...idMedia, ...urlMedia];
43
48
  }
44
49
 
50
+ function normalizePublishMode(value) {
51
+ const normalized = String(value ?? "").trim().toUpperCase();
52
+
53
+ if (!VALID_PUBLISH_MODES.includes(normalized)) {
54
+ throw new Error(`Invalid publish mode \"${value}\". Expected one of: ${VALID_PUBLISH_MODES.join(", ")}.`);
55
+ }
56
+
57
+ return normalized;
58
+ }
59
+
45
60
  function buildPostPayload(options) {
46
61
  const media = mergeMedia(options.mediaIds, options.mediaUrls);
62
+ const publishMode = normalizePublishMode(options.publishMode);
63
+ const publishAt = validatePublishAt(options.publishAt);
64
+
65
+ if (publishMode === "SCHEDULE" && !publishAt) {
66
+ throw new Error("publishAt is required when publishMode is SCHEDULE.");
67
+ }
68
+
69
+ const pollOptions = options.pollOptions ? parseCsv(options.pollOptions) : [];
70
+ const pollCorrectOptionIndex = parseOptionalPositiveInteger(options.pollCorrectOptionIndex, "poll-correct-option-index");
71
+ const zeroBasedCorrectOptionIndex = pollCorrectOptionIndex !== undefined
72
+ ? pollCorrectOptionIndex - 1
73
+ : undefined;
74
+
75
+ validatePollOptions(pollOptions, zeroBasedCorrectOptionIndex);
47
76
 
48
77
  const poll = {
49
78
  ...(options.pollQuestion ? { question: options.pollQuestion } : {}),
50
- ...(options.pollOptions ? { options: parseCsv(options.pollOptions) } : {}),
79
+ ...(pollOptions.length > 0 ? { options: pollOptions } : {}),
51
80
  ...(options.pollPeriod ? { period: options.pollPeriod } : {}),
52
- ...(parseNumber(options.pollCorrectOptionIndex) !== undefined
53
- ? { correctOptionIndex: parseNumber(options.pollCorrectOptionIndex) }
81
+ ...(zeroBasedCorrectOptionIndex !== undefined
82
+ ? { correctOptionIndex: zeroBasedCorrectOptionIndex }
54
83
  : {}),
55
84
  ...(options.pollExplanation ? { explanation: options.pollExplanation } : {}),
56
85
  };
@@ -66,8 +95,8 @@ function buildPostPayload(options) {
66
95
  }
67
96
  : {}),
68
97
  ...(options.instagramTrialReel ? { trialReel: options.instagramTrialReel } : {}),
69
- ...(parseBoolean(options.instagramShareToFeed) !== undefined
70
- ? { shareToFeed: parseBoolean(options.instagramShareToFeed) }
98
+ ...(parseBooleanStrict(options.instagramShareToFeed, "instagram-share-to-feed") !== undefined
99
+ ? { shareToFeed: parseBooleanStrict(options.instagramShareToFeed, "instagram-share-to-feed") }
71
100
  : {}),
72
101
  };
73
102
 
@@ -84,14 +113,14 @@ function buildPostPayload(options) {
84
113
  };
85
114
 
86
115
  const tiktok = {
87
- ...(parseBoolean(options.tiktokSendToInbox) !== undefined
88
- ? { sendToInbox: parseBoolean(options.tiktokSendToInbox) }
116
+ ...(parseBooleanStrict(options.tiktokSendToInbox, "tiktok-send-to-inbox") !== undefined
117
+ ? { sendToInbox: parseBooleanStrict(options.tiktokSendToInbox, "tiktok-send-to-inbox") }
89
118
  : {}),
90
119
  };
91
120
 
92
121
  let youtubePlaylists;
93
122
  if (options.youtubePlaylists) {
94
- youtubePlaylists = JSON.parse(options.youtubePlaylists);
123
+ youtubePlaylists = parseJsonString(options.youtubePlaylists, "youtube-playlists");
95
124
  }
96
125
 
97
126
  const youtube = {
@@ -103,19 +132,19 @@ function buildPostPayload(options) {
103
132
  ...(options.title ? { title: options.title } : {}),
104
133
  ...(options.caption ? { caption: options.caption } : {}),
105
134
  ...(options.alt ? { alt: options.alt } : {}),
106
- ...(options.link ? { link: options.link } : {}),
135
+ ...(options.link ? { link: validateHttpUrl(options.link, "link") } : {}),
107
136
  ...(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) }
137
+ publishMode,
138
+ publishAt,
139
+ ...(parseBooleanStrict(options.postAsStory, "post-as-story") !== undefined
140
+ ? { postAsStory: parseBooleanStrict(options.postAsStory, "post-as-story") }
112
141
  : {}),
113
142
  ...(options.comment
114
143
  ? {
115
144
  comment: {
116
145
  comment: options.comment,
117
- ...(parseNumber(options.commentDelay) !== undefined
118
- ? { delay: parseNumber(options.commentDelay) }
146
+ ...(parseOptionalPositiveInteger(options.commentDelay, "comment-delay") !== undefined
147
+ ? { delay: parseOptionalPositiveInteger(options.commentDelay, "comment-delay") }
119
148
  : {}),
120
149
  },
121
150
  }
@@ -141,4 +170,5 @@ export {
141
170
  parseBoolean,
142
171
  parseCsv,
143
172
  parseNumber,
173
+ VALID_PUBLISH_MODES,
144
174
  };
@@ -0,0 +1,186 @@
1
+ import path from "node:path";
2
+
3
+ const VALID_AUTOMATION_TYPES = ["FEED"];
4
+ const VALID_AUTOMATION_SUB_TYPES = ["RSS"];
5
+ const VALID_IMPORT_AS_TYPES = ["IMAGE", "VIDEO", "CAROUSEL", "TEXT"];
6
+ const SUPPORTED_MEDIA_TYPES = new Map([
7
+ [".jpg", "image/jpeg"],
8
+ [".jpeg", "image/jpeg"],
9
+ [".png", "image/png"],
10
+ [".gif", "image/gif"],
11
+ [".webp", "image/webp"],
12
+ [".mp4", "video/mp4"],
13
+ [".mov", "video/quicktime"],
14
+ ]);
15
+ const DEFAULT_MAX_MEDIA_SIZE_BYTES = Number(process.env.NUELINK_MAX_MEDIA_SIZE_BYTES || 100 * 1024 * 1024);
16
+ const QUEUE_SLOT_PATTERN = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s\d{2}:\d{2}$/;
17
+ const SQL_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
18
+
19
+ function splitCsv(value) {
20
+ if (!value) {
21
+ return [];
22
+ }
23
+
24
+ return value
25
+ .split(",")
26
+ .map((item) => item.trim())
27
+ .filter(Boolean);
28
+ }
29
+
30
+ function normalizeEnum(value, label, allowedValues) {
31
+ const normalized = String(value ?? "").trim().toUpperCase();
32
+
33
+ if (!allowedValues.includes(normalized)) {
34
+ throw new Error(`Invalid ${label} \"${value}\". Expected one of: ${allowedValues.join(", ")}.`);
35
+ }
36
+
37
+ return normalized;
38
+ }
39
+
40
+ function parsePositiveInteger(value, label) {
41
+ const normalized = String(value ?? "").trim();
42
+
43
+ if (!/^\d+$/.test(normalized)) {
44
+ throw new Error(`Invalid ${label}. Expected a positive integer.`);
45
+ }
46
+
47
+ const parsed = Number(normalized);
48
+
49
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
50
+ throw new Error(`Invalid ${label}. Expected a positive integer.`);
51
+ }
52
+
53
+ return parsed;
54
+ }
55
+
56
+ function parseOptionalPositiveInteger(value, label) {
57
+ if (value === undefined || value === null || value === "") {
58
+ return undefined;
59
+ }
60
+
61
+ return parsePositiveInteger(value, label);
62
+ }
63
+
64
+ function parseBooleanStrict(value, label) {
65
+ if (value === undefined || value === null || value === "") {
66
+ return undefined;
67
+ }
68
+
69
+ const normalized = String(value).trim().toLowerCase();
70
+
71
+ if (["true", "1", "yes", "y"].includes(normalized)) {
72
+ return true;
73
+ }
74
+
75
+ if (["false", "0", "no", "n"].includes(normalized)) {
76
+ return false;
77
+ }
78
+
79
+ throw new Error(`Invalid ${label}. Expected true or false.`);
80
+ }
81
+
82
+ function validateHttpUrl(value, label) {
83
+ const normalized = String(value ?? "").trim();
84
+
85
+ let parsedUrl;
86
+ try {
87
+ parsedUrl = new URL(normalized);
88
+ } catch {
89
+ throw new Error(`Invalid ${label}. Expected an absolute http or https URL.`);
90
+ }
91
+
92
+ if (!["http:", "https:"].includes(parsedUrl.protocol)) {
93
+ throw new Error(`Invalid ${label}. Expected an absolute http or https URL.`);
94
+ }
95
+
96
+ return parsedUrl.toString();
97
+ }
98
+
99
+ function validateQueueSlots(queueSlots) {
100
+ queueSlots.forEach((slot) => {
101
+ if (!QUEUE_SLOT_PATTERN.test(slot)) {
102
+ throw new Error(`Invalid queue slot \"${slot}\". Expected values like Mon 10:10.`);
103
+ }
104
+ });
105
+
106
+ return queueSlots;
107
+ }
108
+
109
+ function validatePublishAt(value) {
110
+ if (value === undefined || value === null || value === "" || value === "null") {
111
+ return null;
112
+ }
113
+
114
+ const normalized = String(value).trim();
115
+
116
+ if (SQL_DATETIME_PATTERN.test(normalized)) {
117
+ return normalized;
118
+ }
119
+
120
+ if (Number.isNaN(Date.parse(normalized))) {
121
+ throw new Error("Invalid publish-at. Expected YYYY-MM-DD HH:mm:ss or an ISO 8601 datetime.");
122
+ }
123
+
124
+ return normalized;
125
+ }
126
+
127
+ function validatePollOptions(options, correctOptionIndex) {
128
+ if (options.length === 1) {
129
+ throw new Error("Polls require at least two options.");
130
+ }
131
+
132
+ if (correctOptionIndex !== undefined && (correctOptionIndex < 0 || correctOptionIndex >= options.length)) {
133
+ throw new Error("poll-correct-option-index must point to an existing poll option.");
134
+ }
135
+ }
136
+
137
+ function parseJsonString(value, label) {
138
+ try {
139
+ return JSON.parse(value);
140
+ } catch {
141
+ throw new Error(`Invalid ${label}. Expected valid JSON.`);
142
+ }
143
+ }
144
+
145
+ function validateMediaFile(filePath, fileStat) {
146
+ if (!fileStat.isFile()) {
147
+ throw new Error("Invalid file. Expected a regular file path.");
148
+ }
149
+
150
+ if (fileStat.size <= 0) {
151
+ throw new Error("Invalid file. File must not be empty.");
152
+ }
153
+
154
+ if (fileStat.size > DEFAULT_MAX_MEDIA_SIZE_BYTES) {
155
+ throw new Error(`Invalid file. File exceeds ${DEFAULT_MAX_MEDIA_SIZE_BYTES} bytes.`);
156
+ }
157
+
158
+ const extension = path.extname(filePath).toLowerCase();
159
+ const mediaType = SUPPORTED_MEDIA_TYPES.get(extension);
160
+
161
+ if (!mediaType) {
162
+ throw new Error(`Unsupported file type \"${extension || "(none)"}\".`);
163
+ }
164
+
165
+ return {
166
+ mediaType,
167
+ size: fileStat.size,
168
+ };
169
+ }
170
+
171
+ export {
172
+ VALID_AUTOMATION_SUB_TYPES,
173
+ VALID_AUTOMATION_TYPES,
174
+ VALID_IMPORT_AS_TYPES,
175
+ parseBooleanStrict,
176
+ parseJsonString,
177
+ parseOptionalPositiveInteger,
178
+ parsePositiveInteger,
179
+ splitCsv,
180
+ validateHttpUrl,
181
+ validateMediaFile,
182
+ validatePollOptions,
183
+ validatePublishAt,
184
+ validateQueueSlots,
185
+ normalizeEnum,
186
+ };