@nuelink/nuelink-cli 1.3.9 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/errors.js ADDED
@@ -0,0 +1,47 @@
1
+ import chalk from "chalk";
2
+
3
+ class CliError extends Error {
4
+ constructor(code, message, { httpStatus = null, details = {} } = {}) {
5
+ super(message);
6
+ this.name = "CliError";
7
+ this.code = code;
8
+ this.httpStatus = httpStatus;
9
+ this.details = details;
10
+ }
11
+ }
12
+
13
+ function normalizeCliError(error, fallbackCode = "CLI_ERROR") {
14
+ if (error instanceof CliError) {
15
+ return error;
16
+ }
17
+
18
+ return new CliError(fallbackCode, error?.message || "Unexpected CLI error.");
19
+ }
20
+
21
+ function printCliError(error, { json = false, fallbackCode } = {}) {
22
+ const normalized = normalizeCliError(error, fallbackCode);
23
+
24
+ if (json) {
25
+ process.stdout.write(`${JSON.stringify({
26
+ success: false,
27
+ error: {
28
+ code: normalized.code,
29
+ message: normalized.message,
30
+ httpStatus: normalized.httpStatus,
31
+ details: normalized.details,
32
+ },
33
+ })}\n`);
34
+ return;
35
+ }
36
+
37
+ console.error(chalk.red(normalized.message));
38
+ if (normalized.details && Object.keys(normalized.details).length > 0) {
39
+ console.error(chalk.red(JSON.stringify(normalized.details, null, 2)));
40
+ }
41
+ }
42
+
43
+ export {
44
+ CliError,
45
+ normalizeCliError,
46
+ printCliError,
47
+ };
package/src/http.js CHANGED
@@ -1,15 +1,39 @@
1
- import { createRequire } from "node:module";
2
- import chalk from "chalk";
3
- import { printApiResponse } from "./output.js";
1
+ import { createRequire } from "node:module";
2
+ import chalk from "chalk";
3
+ import { CliError } from "./errors.js";
4
+ import { printApiResponse } from "./output.js";
4
5
 
5
6
  const require = createRequire(import.meta.url);
6
7
  const { version: cliVersion } = require("../package.json");
7
8
 
8
- const API_BASE_URL = process.env.NUELINK_BASE_URL || "https://nuelink.com/api/public/v1";
9
- const REQUEST_TIMEOUT_MS = Number(process.env.NUELINK_TIMEOUT_MS || 30000);
10
- const MAX_GET_RETRIES = Number(process.env.NUELINK_GET_RETRIES || 2);
11
- const RETRY_BASE_DELAY_MS = Number(process.env.NUELINK_RETRY_BASE_MS || 500);
12
- const RETRY_MAX_DELAY_MS = Number(process.env.NUELINK_RETRY_MAX_MS || 2000);
9
+ const DEFAULT_API_BASE_URL = "https://app.nuelink.com/api/public/v1";
10
+
11
+ function readIntegerEnvironment(name, fallback, { minimum = 0, maximum = 600000 } = {}) {
12
+ const raw = process.env[name];
13
+ if (raw === undefined || raw === "") return fallback;
14
+
15
+ const normalized = String(raw).trim();
16
+ if (!/^\d+$/.test(normalized)) {
17
+ throw new CliError("CONFIG_INVALID", `${name} must be an integer from ${minimum} to ${maximum}.`);
18
+ }
19
+
20
+ const parsed = Number(normalized);
21
+ if (!Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {
22
+ throw new CliError("CONFIG_INVALID", `${name} must be an integer from ${minimum} to ${maximum}.`);
23
+ }
24
+
25
+ return parsed;
26
+ }
27
+
28
+ function getRequestConfiguration() {
29
+ return {
30
+ apiBaseUrl: process.env.NUELINK_BASE_URL || DEFAULT_API_BASE_URL,
31
+ requestTimeoutMs: readIntegerEnvironment("NUELINK_TIMEOUT_MS", 30000, { minimum: 1 }),
32
+ maxGetRetries: readIntegerEnvironment("NUELINK_GET_RETRIES", 2, { maximum: 10 }),
33
+ retryBaseDelayMs: readIntegerEnvironment("NUELINK_RETRY_BASE_MS", 500),
34
+ retryMaxDelayMs: readIntegerEnvironment("NUELINK_RETRY_MAX_MS", 2000),
35
+ };
36
+ }
13
37
 
14
38
  function pathParam(value, label) {
15
39
  const stringValue = String(value ?? "").trim();
@@ -29,32 +53,36 @@ function collectionPath(brandId, collectionId) {
29
53
  return `${brandPath(brandId)}/collections/${pathParam(collectionId, "collection-id")}`;
30
54
  }
31
55
 
32
- function buildApiUrl(endpoint) {
33
- return new URL(endpoint.replace(/^\//, ""), `${API_BASE_URL.replace(/\/?$/, "/")}`);
34
- }
35
-
36
- function shouldRetryRequest(method, statusCode, attempt) {
37
- return method === "GET" && attempt < MAX_GET_RETRIES && (statusCode === 429 || statusCode >= 500);
38
- }
39
-
40
- function parseRetryAfterMs(headers, attempt) {
56
+ function buildApiUrl(endpoint, apiBaseUrl) {
57
+ try {
58
+ return new URL(endpoint.replace(/^\//, ""), `${apiBaseUrl.replace(/\/?$/, "/")}`);
59
+ } catch {
60
+ throw new CliError("CONFIG_INVALID", "NUELINK_BASE_URL must be a valid absolute URL.");
61
+ }
62
+ }
63
+
64
+ function shouldRetryRequest(method, statusCode, attempt, maxGetRetries) {
65
+ return method === "GET" && attempt < maxGetRetries && (statusCode === 429 || statusCode >= 500);
66
+ }
67
+
68
+ function parseRetryAfterMs(headers, attempt, retryBaseDelayMs, retryMaxDelayMs) {
41
69
  const retryAfter = headers.get("retry-after");
42
70
 
43
71
  if (retryAfter) {
44
72
  const seconds = Number(retryAfter);
45
73
 
46
74
  if (!Number.isNaN(seconds)) {
47
- return Math.max(seconds * 1000, 0);
75
+ return Math.max(seconds * 1000, 0);
48
76
  }
49
77
 
50
78
  const dateDelay = Date.parse(retryAfter) - Date.now();
51
79
  if (!Number.isNaN(dateDelay)) {
52
- return Math.max(dateDelay, 0);
80
+ return Math.max(dateDelay, 0);
53
81
  }
54
82
  }
55
83
 
56
- const exponentialDelay = Math.min(RETRY_BASE_DELAY_MS * (2 ** attempt), RETRY_MAX_DELAY_MS);
57
- return Math.floor(Math.random() * (exponentialDelay + 1));
84
+ const exponentialDelay = Math.min(retryBaseDelayMs * (2 ** attempt), retryMaxDelayMs);
85
+ return Math.floor(Math.random() * (exponentialDelay + 1));
58
86
  }
59
87
 
60
88
  async function sleep(ms) {
@@ -76,8 +104,9 @@ function printDryRun({ method, url, query, body, multipart, dryRunBody }) {
76
104
  }, null, 2));
77
105
  }
78
106
 
79
- async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart, outputMode = "json", quiet = false, dryRun = false, dryRunBody }) {
80
- const url = buildApiUrl(endpoint);
107
+ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, multipart, outputMode = "json", quiet = false, dryRun = false, dryRunBody }) {
108
+ const configuration = getRequestConfiguration();
109
+ const url = buildApiUrl(endpoint, configuration.apiBaseUrl);
81
110
 
82
111
  if (query) {
83
112
  Object.entries(query).forEach(([key, value]) => {
@@ -92,10 +121,11 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
92
121
  return { dryRun: true };
93
122
  }
94
123
 
95
- if (!apiKey) {
96
- console.error(chalk.red("Missing API key. Use --api-key <api_key> for a single command or auth:login to save one."));
97
- process.exitCode = 1;
98
- return null;
124
+ if (!apiKey) {
125
+ throw new CliError(
126
+ "AUTH_MISSING",
127
+ "Missing API key. Use --api-key <api_key> for a single command or auth:login to save one.",
128
+ );
99
129
  }
100
130
 
101
131
  const headers = {
@@ -121,15 +151,20 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
121
151
 
122
152
  for (let attempt = 0; ; attempt += 1) {
123
153
  response = await fetch(url, {
124
- ...init,
125
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
126
- });
127
-
128
- if (!shouldRetryRequest(method, response.status, attempt)) {
129
- break;
130
- }
131
-
132
- await sleep(parseRetryAfterMs(response.headers, attempt));
154
+ ...init,
155
+ signal: AbortSignal.timeout(configuration.requestTimeoutMs),
156
+ });
157
+
158
+ if (!shouldRetryRequest(method, response.status, attempt, configuration.maxGetRetries)) {
159
+ break;
160
+ }
161
+
162
+ await sleep(parseRetryAfterMs(
163
+ response.headers,
164
+ attempt,
165
+ configuration.retryBaseDelayMs,
166
+ configuration.retryMaxDelayMs,
167
+ ));
133
168
  }
134
169
 
135
170
  const text = await response.text();
@@ -137,20 +172,25 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
137
172
 
138
173
  if (text) {
139
174
  try {
140
- data = JSON.parse(text);
175
+ data = JSON.parse(text);
141
176
  } catch {
142
177
  if (response.ok) {
143
- throw new Error(`Protocol error: expected a JSON response (HTTP ${response.status}).`);
144
- }
145
- data = { raw: text };
178
+ throw new CliError(
179
+ "PROTOCOL_ERROR",
180
+ `Protocol error: expected a JSON response (HTTP ${response.status}).`,
181
+ { httpStatus: response.status },
182
+ );
183
+ }
184
+ data = { raw: text };
146
185
  }
147
186
  }
148
187
 
149
- if (!response.ok) {
150
- console.error(chalk.red(`Request failed (${response.status} ${response.statusText})`));
151
- console.error(chalk.red(JSON.stringify(data, null, 2)));
152
- process.exitCode = 1;
153
- return null;
188
+ if (!response.ok) {
189
+ throw new CliError(
190
+ "HTTP_ERROR",
191
+ `Request failed (${response.status} ${response.statusText})`,
192
+ { httpStatus: response.status, details: data },
193
+ );
154
194
  }
155
195
 
156
196
  if (outputMode !== "json" && !quiet) {
@@ -159,18 +199,19 @@ async function nuelinkRequest({ apiKey, method = "GET", endpoint, query, body, m
159
199
 
160
200
  printApiResponse(data, { outputMode });
161
201
  return data;
162
- } catch (error) {
163
- if (error?.name === "TimeoutError") {
164
- console.error(chalk.red(`Request timed out after ${REQUEST_TIMEOUT_MS}ms.`));
165
- process.exitCode = 1;
166
- return null;
167
- }
168
-
169
- console.error(chalk.red("Request error:"), error.message);
170
- process.exitCode = 1;
171
- return null;
172
- }
173
- }
202
+ } catch (error) {
203
+ if (error instanceof CliError) throw error;
204
+
205
+ if (error?.name === "TimeoutError") {
206
+ throw new CliError(
207
+ "TIMEOUT",
208
+ `Request timed out after ${configuration.requestTimeoutMs}ms.`,
209
+ );
210
+ }
211
+
212
+ throw new CliError("NETWORK_ERROR", `Request error: ${error.message}`);
213
+ }
214
+ }
174
215
 
175
216
  export {
176
217
  brandPath,