@5y/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -2
- package/bin/5y.mjs +12 -0
- package/lib/args.mjs +97 -0
- package/lib/callback.mjs +72 -0
- package/lib/commands.mjs +915 -0
- package/lib/config.mjs +139 -0
- package/lib/http.mjs +493 -0
- package/lib/output.mjs +105 -0
- package/lib/version.mjs +6 -0
- package/package.json +36 -4
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// 生产 nginx 只把 /api/ 转给后端 ⇒ 基址必须带 /api(CLI 会在其后拼 /open/v1)
|
|
6
|
+
export const DEFAULT_BASE_URL = 'https://5y.com.cn/api';
|
|
7
|
+
|
|
8
|
+
const KNOWN_KEYS = new Set(['api_key', 'base_url', 'callback_secret']);
|
|
9
|
+
|
|
10
|
+
export function normalizeBaseUrl(value) {
|
|
11
|
+
const raw = String(value == null ? '' : value).trim();
|
|
12
|
+
if (!raw) return DEFAULT_BASE_URL;
|
|
13
|
+
return raw.replace(/\/+$/, '');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function configFilePath() {
|
|
17
|
+
const home = process.env.HOME || os.homedir();
|
|
18
|
+
return path.join(home, '.config', '5y', 'config.toml');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function findClosingQuote(text, quote) {
|
|
22
|
+
for (let i = 1; i < text.length; i += 1) {
|
|
23
|
+
if (text[i] === '\\') {
|
|
24
|
+
i += 1;
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (text[i] === quote) return i;
|
|
28
|
+
}
|
|
29
|
+
return -1;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function parseValue(raw) {
|
|
33
|
+
const value = raw.trim();
|
|
34
|
+
if (value.startsWith('"')) {
|
|
35
|
+
const end = findClosingQuote(value, '"');
|
|
36
|
+
if (end !== -1) {
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(value.slice(0, end + 1));
|
|
39
|
+
} catch {
|
|
40
|
+
return value.slice(1, end);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return value.slice(1);
|
|
44
|
+
}
|
|
45
|
+
if (value.startsWith("'")) {
|
|
46
|
+
const end = value.indexOf("'", 1);
|
|
47
|
+
return end !== -1 ? value.slice(1, end) : value.slice(1);
|
|
48
|
+
}
|
|
49
|
+
const hash = value.indexOf('#');
|
|
50
|
+
return (hash !== -1 ? value.slice(0, hash) : value).trim();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Extreme-minimal TOML reader for the three keys this CLI owns. */
|
|
54
|
+
export function readConfigFile(file = configFilePath()) {
|
|
55
|
+
let text;
|
|
56
|
+
try {
|
|
57
|
+
text = fs.readFileSync(file, 'utf8');
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (err.code === 'ENOENT') return {};
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const config = {};
|
|
64
|
+
for (const line of text.split(/\r?\n/)) {
|
|
65
|
+
const trimmed = line.trim();
|
|
66
|
+
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('[')) continue;
|
|
67
|
+
const match = trimmed.match(/^([A-Za-z0-9_]+)\s*=\s*(.*)$/);
|
|
68
|
+
if (!match) continue;
|
|
69
|
+
const key = match[1];
|
|
70
|
+
if (!KNOWN_KEYS.has(key)) continue;
|
|
71
|
+
config[key] = parseValue(match[2]);
|
|
72
|
+
}
|
|
73
|
+
return config;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Merge-update known keys, preserving any unknown lines the user added. */
|
|
77
|
+
export function saveConfig(updates, file = configFilePath()) {
|
|
78
|
+
const dir = path.dirname(file);
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
80
|
+
try {
|
|
81
|
+
fs.chmodSync(dir, 0o700);
|
|
82
|
+
} catch {
|
|
83
|
+
// Directory permissions are best-effort on platforms that ignore chmod.
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let lines = [];
|
|
87
|
+
try {
|
|
88
|
+
lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
|
|
89
|
+
} catch (err) {
|
|
90
|
+
if (err.code !== 'ENOENT') throw err;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const pending = { ...updates };
|
|
94
|
+
const out = [];
|
|
95
|
+
for (const line of lines) {
|
|
96
|
+
const match = line.match(/^\s*([A-Za-z0-9_]+)\s*=/);
|
|
97
|
+
if (match && Object.prototype.hasOwnProperty.call(pending, match[1])) {
|
|
98
|
+
out.push(`${match[1]} = ${JSON.stringify(String(pending[match[1]]))}`);
|
|
99
|
+
delete pending[match[1]];
|
|
100
|
+
} else {
|
|
101
|
+
out.push(line);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
while (out.length && out[out.length - 1] === '') out.pop();
|
|
106
|
+
for (const [key, value] of Object.entries(pending)) {
|
|
107
|
+
out.push(`${key} = ${JSON.stringify(String(value))}`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fs.writeFileSync(file, `${out.join('\n')}\n`, { mode: 0o600 });
|
|
111
|
+
try {
|
|
112
|
+
fs.chmodSync(file, 0o600);
|
|
113
|
+
} catch {
|
|
114
|
+
// Best-effort; Windows does not support POSIX modes.
|
|
115
|
+
}
|
|
116
|
+
return file;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function loadRuntimeConfig(flags = {}) {
|
|
120
|
+
const file = configFilePath();
|
|
121
|
+
const stored = readConfigFile(file);
|
|
122
|
+
|
|
123
|
+
const apiKey = String(process.env['5Y_API_KEY'] || stored.api_key || '').trim();
|
|
124
|
+
const baseUrl = normalizeBaseUrl(
|
|
125
|
+
flags['base-url'] || process.env['5Y_BASE_URL'] || stored.base_url || DEFAULT_BASE_URL,
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
apiKey,
|
|
130
|
+
baseUrl,
|
|
131
|
+
callbackSecret: String(stored.callback_secret || ''),
|
|
132
|
+
configPath: file,
|
|
133
|
+
stored,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function keyPrefix(apiKey) {
|
|
138
|
+
return String(apiKey || '').slice(0, 8);
|
|
139
|
+
}
|
package/lib/http.mjs
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import https from 'node:https';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Readable } from 'node:stream';
|
|
7
|
+
import { pipeline } from 'node:stream/promises';
|
|
8
|
+
|
|
9
|
+
import { VERSION } from './version.mjs';
|
|
10
|
+
import {
|
|
11
|
+
CliError,
|
|
12
|
+
EXIT,
|
|
13
|
+
defaultErrorCode,
|
|
14
|
+
exitCodeForStatus,
|
|
15
|
+
log,
|
|
16
|
+
retryDelay,
|
|
17
|
+
sleep,
|
|
18
|
+
} from './output.mjs';
|
|
19
|
+
|
|
20
|
+
const API_PREFIX = '/open/v1';
|
|
21
|
+
|
|
22
|
+
const MIME_BY_EXT = {
|
|
23
|
+
'.png': 'image/png',
|
|
24
|
+
'.jpg': 'image/jpeg',
|
|
25
|
+
'.jpeg': 'image/jpeg',
|
|
26
|
+
'.webp': 'image/webp',
|
|
27
|
+
'.gif': 'image/gif',
|
|
28
|
+
'.mp4': 'video/mp4',
|
|
29
|
+
'.mov': 'video/quicktime',
|
|
30
|
+
'.webm': 'video/webm',
|
|
31
|
+
'.mp3': 'audio/mpeg',
|
|
32
|
+
'.wav': 'audio/wav',
|
|
33
|
+
'.m4a': 'audio/mp4',
|
|
34
|
+
'.txt': 'text/plain',
|
|
35
|
+
'.json': 'application/json',
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const EXT_BY_CONTENT_TYPE = {
|
|
39
|
+
'image/png': 'png',
|
|
40
|
+
'image/jpeg': 'jpg',
|
|
41
|
+
'image/webp': 'webp',
|
|
42
|
+
'image/gif': 'gif',
|
|
43
|
+
'video/mp4': 'mp4',
|
|
44
|
+
'video/quicktime': 'mov',
|
|
45
|
+
'video/webm': 'webm',
|
|
46
|
+
'audio/mpeg': 'mp3',
|
|
47
|
+
'audio/wav': 'wav',
|
|
48
|
+
'audio/mp4': 'm4a',
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
function transportFor(urlObject) {
|
|
52
|
+
return urlObject.protocol === 'https:' ? https : http;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function networkError(err) {
|
|
56
|
+
return new CliError({
|
|
57
|
+
code: 'NETWORK_ERROR',
|
|
58
|
+
message: `network error: ${err && err.message ? err.message : String(err)}`,
|
|
59
|
+
retryable: true,
|
|
60
|
+
exitCode: EXIT.UPSTREAM,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function toCliError(err) {
|
|
65
|
+
return err instanceof CliError ? err : networkError(err);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function guessMime(filePath) {
|
|
69
|
+
return MIME_BY_EXT[path.extname(filePath).toLowerCase()] || 'application/octet-stream';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function extensionForContentType(contentType) {
|
|
73
|
+
const bare = String(contentType || '').split(';')[0].trim().toLowerCase();
|
|
74
|
+
return EXT_BY_CONTENT_TYPE[bare] || '';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Strip userinfo before a URL is printed to logs / output. */
|
|
78
|
+
export function redactUrl(url) {
|
|
79
|
+
try {
|
|
80
|
+
const parsed = new URL(url);
|
|
81
|
+
if (parsed.username || parsed.password) {
|
|
82
|
+
parsed.username = '';
|
|
83
|
+
parsed.password = '';
|
|
84
|
+
}
|
|
85
|
+
return parsed.toString();
|
|
86
|
+
} catch {
|
|
87
|
+
return '[invalid url]';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function buildApiUrl(baseUrl, apiPath, query) {
|
|
92
|
+
const base = String(baseUrl || '').replace(/\/+$/, '');
|
|
93
|
+
const prefix = base.endsWith(API_PREFIX) ? '' : API_PREFIX;
|
|
94
|
+
let url = `${base}${prefix}${apiPath}`;
|
|
95
|
+
const search = new URLSearchParams();
|
|
96
|
+
for (const [key, value] of Object.entries(query || {})) {
|
|
97
|
+
if (value === undefined || value === null || value === '') continue;
|
|
98
|
+
search.append(key, String(value));
|
|
99
|
+
}
|
|
100
|
+
const qs = search.toString();
|
|
101
|
+
if (qs) url += `?${qs}`;
|
|
102
|
+
return url;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* One HTTP request. Collects the response body (except requestStream).
|
|
107
|
+
* `stream` must be fresh per attempt; callers use a factory for retries.
|
|
108
|
+
*/
|
|
109
|
+
export function request(urlString, options = {}) {
|
|
110
|
+
const {
|
|
111
|
+
method = 'GET',
|
|
112
|
+
headers = {},
|
|
113
|
+
body = null,
|
|
114
|
+
stream = null,
|
|
115
|
+
contentLength = null,
|
|
116
|
+
timeoutMs = 10000,
|
|
117
|
+
} = options;
|
|
118
|
+
|
|
119
|
+
return new Promise((resolve, reject) => {
|
|
120
|
+
let urlObject;
|
|
121
|
+
try {
|
|
122
|
+
urlObject = new URL(urlString);
|
|
123
|
+
} catch {
|
|
124
|
+
reject(
|
|
125
|
+
new CliError({
|
|
126
|
+
code: 'INVALID_URL',
|
|
127
|
+
message: 'invalid URL',
|
|
128
|
+
retryable: false,
|
|
129
|
+
exitCode: EXIT.USAGE,
|
|
130
|
+
}),
|
|
131
|
+
);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const req = transportFor(urlObject).request(urlObject, { method, headers }, (res) => {
|
|
136
|
+
const chunks = [];
|
|
137
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
138
|
+
res.on('end', () => {
|
|
139
|
+
resolve({
|
|
140
|
+
status: res.statusCode,
|
|
141
|
+
headers: res.headers,
|
|
142
|
+
body: Buffer.concat(chunks),
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
res.on('error', (err) => reject(toCliError(err)));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
if (timeoutMs > 0) {
|
|
149
|
+
req.setTimeout(timeoutMs, () => {
|
|
150
|
+
req.destroy(
|
|
151
|
+
new CliError({
|
|
152
|
+
code: 'TIMEOUT',
|
|
153
|
+
message: `request timed out after ${timeoutMs}ms`,
|
|
154
|
+
retryable: true,
|
|
155
|
+
exitCode: EXIT.UPSTREAM,
|
|
156
|
+
}),
|
|
157
|
+
);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
req.on('error', (err) => {
|
|
162
|
+
if (stream && !stream.destroyed) stream.destroy();
|
|
163
|
+
reject(toCliError(err));
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
if (contentLength !== null) req.setHeader('Content-Length', String(contentLength));
|
|
167
|
+
|
|
168
|
+
if (stream) {
|
|
169
|
+
stream.on('error', (err) => req.destroy(err));
|
|
170
|
+
stream.pipe(req);
|
|
171
|
+
} else {
|
|
172
|
+
if (body !== null) req.write(body);
|
|
173
|
+
req.end();
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function requestStream(urlString, options = {}) {
|
|
179
|
+
const { method = 'GET', headers = {}, timeoutMs = 60000 } = options;
|
|
180
|
+
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
let urlObject;
|
|
183
|
+
try {
|
|
184
|
+
urlObject = new URL(urlString);
|
|
185
|
+
} catch {
|
|
186
|
+
reject(
|
|
187
|
+
new CliError({
|
|
188
|
+
code: 'INVALID_URL',
|
|
189
|
+
message: 'invalid URL',
|
|
190
|
+
retryable: false,
|
|
191
|
+
exitCode: EXIT.USAGE,
|
|
192
|
+
}),
|
|
193
|
+
);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const req = transportFor(urlObject).request(urlObject, { method, headers }, (res) => {
|
|
198
|
+
resolve({ res, req });
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
if (timeoutMs > 0) {
|
|
202
|
+
req.setTimeout(timeoutMs, () => {
|
|
203
|
+
req.destroy(
|
|
204
|
+
new CliError({
|
|
205
|
+
code: 'TIMEOUT',
|
|
206
|
+
message: `request timed out after ${timeoutMs}ms`,
|
|
207
|
+
retryable: true,
|
|
208
|
+
exitCode: EXIT.UPSTREAM,
|
|
209
|
+
}),
|
|
210
|
+
);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
req.on('error', (err) => reject(toCliError(err)));
|
|
215
|
+
req.end();
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Generic retry wrapper. Retries network errors and 429/5xx up to maxRetries
|
|
221
|
+
* (default 3 -> 4 attempts total, waits 1s / 2s / 4s).
|
|
222
|
+
*/
|
|
223
|
+
export async function requestWithRetry(urlString, makeOptions, options = {}) {
|
|
224
|
+
const { maxRetries = 3, timeoutMs = 10000, label = 'request' } = options;
|
|
225
|
+
|
|
226
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
227
|
+
try {
|
|
228
|
+
const requestOptions = typeof makeOptions === 'function' ? makeOptions(attempt) : makeOptions;
|
|
229
|
+
const res = await request(urlString, { timeoutMs, ...requestOptions });
|
|
230
|
+
|
|
231
|
+
if ((res.status === 429 || res.status >= 500) && attempt < maxRetries) {
|
|
232
|
+
const wait = retryDelay(attempt, res.headers['retry-after']);
|
|
233
|
+
log(`${label}: HTTP ${res.status}, retrying in ${wait}ms (${attempt + 1}/${maxRetries})`);
|
|
234
|
+
await sleep(wait);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
return res;
|
|
238
|
+
} catch (err) {
|
|
239
|
+
const cliError = toCliError(err);
|
|
240
|
+
if (!cliError.retryable || attempt >= maxRetries) throw cliError;
|
|
241
|
+
const wait = retryDelay(attempt);
|
|
242
|
+
log(`${label}: ${cliError.code}, retrying in ${wait}ms (${attempt + 1}/${maxRetries})`);
|
|
243
|
+
await sleep(wait);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function parseBody(res) {
|
|
249
|
+
if (!res.body || res.body.length === 0) return null;
|
|
250
|
+
const text = res.body.toString('utf8');
|
|
251
|
+
const contentType = String(res.headers['content-type'] || '');
|
|
252
|
+
const looksJson = contentType.includes('json') || text.trim().startsWith('{') || text.trim().startsWith('[');
|
|
253
|
+
if (looksJson) {
|
|
254
|
+
try {
|
|
255
|
+
return JSON.parse(text);
|
|
256
|
+
} catch {
|
|
257
|
+
// fall through to { raw }
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return { raw: text };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function errorFromResponse(res) {
|
|
264
|
+
const parsed = parseBody(res);
|
|
265
|
+
const status = Number(res.status) || 0;
|
|
266
|
+
const source =
|
|
267
|
+
parsed && typeof parsed === 'object' && parsed.error && typeof parsed.error === 'object'
|
|
268
|
+
? parsed.error
|
|
269
|
+
: parsed;
|
|
270
|
+
|
|
271
|
+
let message = null;
|
|
272
|
+
if (source && typeof source === 'object') {
|
|
273
|
+
if (typeof source.message === 'string') message = source.message;
|
|
274
|
+
else if (typeof source.detail === 'string') message = source.detail;
|
|
275
|
+
else if (source.detail !== undefined) message = JSON.stringify(source.detail);
|
|
276
|
+
} else if (typeof source === 'string') {
|
|
277
|
+
message = source;
|
|
278
|
+
} else if (parsed && typeof parsed === 'object' && typeof parsed.error === 'string') {
|
|
279
|
+
message = parsed.error;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const code =
|
|
283
|
+
source && typeof source === 'object' && typeof source.code === 'string'
|
|
284
|
+
? source.code
|
|
285
|
+
: defaultErrorCode(status);
|
|
286
|
+
|
|
287
|
+
const retryable =
|
|
288
|
+
source && typeof source === 'object' && typeof source.retryable === 'boolean'
|
|
289
|
+
? source.retryable
|
|
290
|
+
: status === 429 || status >= 500;
|
|
291
|
+
|
|
292
|
+
const requestId =
|
|
293
|
+
(source && typeof source === 'object' && source.request_id) ||
|
|
294
|
+
(res.headers && res.headers['x-request-id']) ||
|
|
295
|
+
null;
|
|
296
|
+
|
|
297
|
+
return new CliError({
|
|
298
|
+
code,
|
|
299
|
+
message: message || `HTTP ${status}`,
|
|
300
|
+
retryable,
|
|
301
|
+
requestId,
|
|
302
|
+
exitCode: exitCodeForStatus(status),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Call /open/v1/*. Adds auth, retries retryable failures, and maps HTTP errors
|
|
308
|
+
* onto CliError with the spec exit codes.
|
|
309
|
+
*/
|
|
310
|
+
export async function openApi(cfg, options = {}) {
|
|
311
|
+
const {
|
|
312
|
+
method = 'GET',
|
|
313
|
+
path: apiPath,
|
|
314
|
+
query,
|
|
315
|
+
json,
|
|
316
|
+
multipart,
|
|
317
|
+
headers = {},
|
|
318
|
+
timeoutMs = 10000,
|
|
319
|
+
maxRetries = 3,
|
|
320
|
+
label,
|
|
321
|
+
} = options;
|
|
322
|
+
|
|
323
|
+
const url = buildApiUrl(cfg.baseUrl, apiPath, query);
|
|
324
|
+
const baseHeaders = {
|
|
325
|
+
Accept: 'application/json',
|
|
326
|
+
'User-Agent': `@5y/cli/${VERSION}`,
|
|
327
|
+
...(cfg.apiKey ? { Authorization: `Bearer ${cfg.apiKey}` } : {}),
|
|
328
|
+
...headers,
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
let makeOptions;
|
|
332
|
+
if (multipart) {
|
|
333
|
+
makeOptions = () => {
|
|
334
|
+
const spec = multipart.build();
|
|
335
|
+
return {
|
|
336
|
+
method,
|
|
337
|
+
headers: { ...baseHeaders, ...spec.headers },
|
|
338
|
+
stream: spec.stream,
|
|
339
|
+
contentLength: spec.contentLength,
|
|
340
|
+
};
|
|
341
|
+
};
|
|
342
|
+
} else if (json !== undefined) {
|
|
343
|
+
const body = Buffer.from(JSON.stringify(json));
|
|
344
|
+
baseHeaders['Content-Type'] = 'application/json';
|
|
345
|
+
makeOptions = () => ({ method, headers: baseHeaders, body, contentLength: body.length });
|
|
346
|
+
} else {
|
|
347
|
+
makeOptions = () => ({ method, headers: baseHeaders });
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const res = await requestWithRetry(url, makeOptions, {
|
|
351
|
+
maxRetries,
|
|
352
|
+
timeoutMs,
|
|
353
|
+
label: label || `${method} ${apiPath}`,
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
if (res.status < 200 || res.status >= 300) throw errorFromResponse(res);
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
data: parseBody(res),
|
|
360
|
+
status: res.status,
|
|
361
|
+
headers: res.headers,
|
|
362
|
+
requestId: res.headers['x-request-id'] || null,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function escapeFormField(value) {
|
|
367
|
+
return String(value).replace(/"/g, '%22').replace(/[\r\n]/g, ' ');
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Build a replayable multipart/form-data body without dependencies.
|
|
372
|
+
* `build()` is called once per HTTP attempt so retries get a fresh file stream.
|
|
373
|
+
*/
|
|
374
|
+
export function makeMultipart(filePath, options = {}) {
|
|
375
|
+
const {
|
|
376
|
+
fieldName = 'file',
|
|
377
|
+
filename = path.basename(filePath),
|
|
378
|
+
contentType = guessMime(filePath),
|
|
379
|
+
fields = {},
|
|
380
|
+
} = options;
|
|
381
|
+
|
|
382
|
+
const stat = fs.statSync(filePath);
|
|
383
|
+
const boundary = `----5y${crypto.randomBytes(16).toString('hex')}`;
|
|
384
|
+
const pieces = [];
|
|
385
|
+
|
|
386
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
387
|
+
if (value === undefined || value === null) continue;
|
|
388
|
+
pieces.push(
|
|
389
|
+
Buffer.from(
|
|
390
|
+
`--${boundary}\r\nContent-Disposition: form-data; name="${escapeFormField(key)}"\r\n\r\n${value}\r\n`,
|
|
391
|
+
),
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const head = Buffer.from(
|
|
396
|
+
`--${boundary}\r\nContent-Disposition: form-data; name="${escapeFormField(
|
|
397
|
+
fieldName,
|
|
398
|
+
)}"; filename="${escapeFormField(filename)}"\r\nContent-Type: ${contentType}\r\n\r\n`,
|
|
399
|
+
);
|
|
400
|
+
const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
|
|
401
|
+
const contentLength =
|
|
402
|
+
pieces.reduce((sum, piece) => sum + piece.length, 0) + head.length + stat.size + tail.length;
|
|
403
|
+
|
|
404
|
+
return {
|
|
405
|
+
build() {
|
|
406
|
+
const stream = Readable.from(
|
|
407
|
+
(async function* generate() {
|
|
408
|
+
for (const piece of pieces) yield piece;
|
|
409
|
+
yield head;
|
|
410
|
+
const fileStream = fs.createReadStream(filePath);
|
|
411
|
+
for await (const chunk of fileStream) yield chunk;
|
|
412
|
+
yield tail;
|
|
413
|
+
})(),
|
|
414
|
+
);
|
|
415
|
+
return {
|
|
416
|
+
headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
|
|
417
|
+
stream,
|
|
418
|
+
contentLength,
|
|
419
|
+
};
|
|
420
|
+
},
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async function downloadOnce(url, destPath, options) {
|
|
425
|
+
const { timeoutMs = 60000, maxRedirects = 5 } = options;
|
|
426
|
+
let current = url;
|
|
427
|
+
|
|
428
|
+
for (let hop = 0; hop <= maxRedirects; hop += 1) {
|
|
429
|
+
const { res } = await requestStream(current, { timeoutMs });
|
|
430
|
+
|
|
431
|
+
if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
|
|
432
|
+
res.resume();
|
|
433
|
+
current = new URL(res.headers.location, current).toString();
|
|
434
|
+
continue;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
438
|
+
const chunks = [];
|
|
439
|
+
for await (const chunk of res) chunks.push(chunk);
|
|
440
|
+
throw errorFromResponse({
|
|
441
|
+
status: res.statusCode,
|
|
442
|
+
headers: res.headers,
|
|
443
|
+
body: Buffer.concat(chunks),
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const contentType = String(res.headers['content-type'] || '');
|
|
448
|
+
try {
|
|
449
|
+
await pipeline(res, fs.createWriteStream(destPath));
|
|
450
|
+
} catch (err) {
|
|
451
|
+
try {
|
|
452
|
+
fs.rmSync(destPath, { force: true });
|
|
453
|
+
} catch {
|
|
454
|
+
// ignore
|
|
455
|
+
}
|
|
456
|
+
if (err instanceof CliError) throw err;
|
|
457
|
+
const retryableCodes = ['ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN'];
|
|
458
|
+
if (retryableCodes.includes(err.code)) throw networkError(err);
|
|
459
|
+
throw new CliError({
|
|
460
|
+
code: 'DOWNLOAD_FAILED',
|
|
461
|
+
message: err.message,
|
|
462
|
+
retryable: false,
|
|
463
|
+
exitCode: EXIT.BUSINESS,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
return { bytes: fs.statSync(destPath).size, contentType, finalUrl: current };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
throw new CliError({
|
|
471
|
+
code: 'TOO_MANY_REDIRECTS',
|
|
472
|
+
message: 'too many redirects',
|
|
473
|
+
retryable: false,
|
|
474
|
+
exitCode: EXIT.BUSINESS,
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Download with redirects and up to 3 retries on network / 429 / 5xx. */
|
|
479
|
+
export async function downloadToFile(url, destPath, options = {}) {
|
|
480
|
+
const { maxRetries = 3, timeoutMs = 60000, maxRedirects = 5 } = options;
|
|
481
|
+
|
|
482
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
483
|
+
try {
|
|
484
|
+
return await downloadOnce(url, destPath, { timeoutMs, maxRedirects });
|
|
485
|
+
} catch (err) {
|
|
486
|
+
const cliError = toCliError(err);
|
|
487
|
+
if (!cliError.retryable || attempt >= maxRetries) throw cliError;
|
|
488
|
+
const wait = retryDelay(attempt);
|
|
489
|
+
log(`download: ${cliError.code}, retrying in ${wait}ms (${attempt + 1}/${maxRetries})`);
|
|
490
|
+
await sleep(wait);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|