@hubex/mcp 0.12.20261119 → 0.14.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/dist/auth.js CHANGED
@@ -6,7 +6,98 @@
6
6
  * - "service": a long-lived service token -> JWT via AUTHZ/AccessTokens.
7
7
  * Afterwards all three refresh the same way.
8
8
  */
9
+ import { SET_TOKEN_TOOL } from "./token-prompt.js";
9
10
  export const SELECT_TENANT_TOOL = "hubex_select_tenant";
11
+ /**
12
+ * Limit for each AUTHN/AUTHZ request. Together with HUBEX_REQUEST_TIMEOUT_MS it keeps
13
+ * a refresh plus the API call under the MCP client's default 60 s request timeout.
14
+ */
15
+ const AUTH_REQUEST_TIMEOUT_MS = 10_000;
16
+ /** How many times an auth request rejected with InvalidTenantMember is sent, same data each time. */
17
+ const TENANT_MEMBERSHIP_ATTEMPTS = 3;
18
+ const TENANT_MEMBERSHIP_RETRY_DELAY_MS = 1_000;
19
+ /** Refresh token lifetime asked of AUTHZ/RefreshTokens, the same year as in the HubEx web app. */
20
+ const REFRESH_TOKEN_VALIDITY = "365.00:00:00";
21
+ function waitForAuthentication(operation, signal) {
22
+ if (!signal)
23
+ return operation;
24
+ return new Promise((resolve, reject) => {
25
+ const onAbort = () => reject(signal.reason);
26
+ if (signal.aborted)
27
+ onAbort();
28
+ else
29
+ signal.addEventListener("abort", onAbort, { once: true });
30
+ void operation.finally(() => signal.removeEventListener("abort", onAbort)).then(resolve, reject);
31
+ });
32
+ }
33
+ class AuthHttpError extends Error {
34
+ status;
35
+ constructor(status, message) {
36
+ super(message);
37
+ this.status = status;
38
+ this.name = "AuthHttpError";
39
+ }
40
+ }
41
+ /** No complete response: a network failure, a timeout or a body cut off mid-transfer. */
42
+ class AuthTransportError extends Error {
43
+ constructor(message, options) {
44
+ super(message, options);
45
+ this.name = "AuthTransportError";
46
+ }
47
+ }
48
+ function readTenantMembershipFailure(body) {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(body);
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ const failures = Array.isArray(parsed) ? parsed : [parsed];
57
+ return failures.find((failure) => typeof failure === "object" && failure !== null &&
58
+ "code" in failure && failure.code === "InvalidTenantMember");
59
+ }
60
+ function diagnosticId(value) {
61
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
62
+ return String(value);
63
+ return typeof value === "string" && /^\d{1,24}$/.test(value) ? value : undefined;
64
+ }
65
+ class TenantMembershipError extends AuthHttpError {
66
+ constructor(failure, config, request, options) {
67
+ const reason = failure.message === "Закончен период членства в тенанте"
68
+ ? "Закончился период членства пользователя в тенанте"
69
+ : "Членство пользователя в тенанте недействительно";
70
+ const recovery = config.authMode === "token"
71
+ ? `После восстановления доступа переподключи MCP для ввода свежего токена или передай его через ${SET_TOKEN_TOOL}.`
72
+ : "После восстановления доступа повтори вызов.";
73
+ const claims = typeof options.accessToken === "string" ? decodeJwt(options.accessToken) : undefined;
74
+ const selectedTenant = diagnosticId(options.tenantMember?.tenantID);
75
+ const requestTenant = selectedTenant ?? diagnosticId(claims?.TenantID);
76
+ const configuredTenant = diagnosticId(config.tenantId);
77
+ const tenant = configuredTenant && requestTenant && configuredTenant !== requestTenant
78
+ ? `Тенант ${selectedTenant ? "в запросе" : "в токене"} ${requestTenant}, в настройках ${configuredTenant}.`
79
+ : `Тенант ${requestTenant ?? configuredTenant ?? "не определён"}.`;
80
+ const identity = Object.entries({
81
+ accountId: diagnosticId(claims?.AccountID),
82
+ tenantMemberId: diagnosticId(options.tenantMember?.tenantMemberID ?? claims?.TenantMemberID),
83
+ userId: diagnosticId(options.tenantMember?.userID ?? claims?.UserID) ?? diagnosticId(config.userId),
84
+ }).flatMap(([label, value]) => value === undefined ? [] : [`${label} ${value}`]).join(", ");
85
+ const traceIdentifier = failure.traceIdentifier;
86
+ const trace = typeof traceIdentifier === "string" && /^[a-zA-Z0-9:_-]{1,128}$/.test(traceIdentifier)
87
+ ? `Идентификатор трассировки ${traceIdentifier}.`
88
+ : undefined;
89
+ super(401, [
90
+ `HubEx отклонил авторизацию. ${reason} (HTTP 401, ${failure.code}).`,
91
+ `Окружение ${config.env}, режим ${config.authMode}, applicationId ${config.applicationId}.`,
92
+ tenant,
93
+ identity ? `${identity}.` : undefined,
94
+ `Запрос ${request}.`,
95
+ trace,
96
+ `Обратись к администратору HubEx, чтобы проверить членство. ${recovery}`,
97
+ ].filter(Boolean).join("\n"));
98
+ this.name = "TenantMembershipError";
99
+ }
100
+ }
10
101
  /** Decode a JWT payload without verifying the signature (we only read claims). */
11
102
  export function decodeJwt(token) {
12
103
  const parts = token.split(".");
@@ -73,6 +164,7 @@ class RefreshingAuth {
73
164
  accessRejected = false;
74
165
  refreshToken;
75
166
  refreshExp; // seconds since epoch
167
+ tenantMembershipError;
76
168
  tenantId;
77
169
  inflight;
78
170
  constructor(config) {
@@ -88,9 +180,10 @@ class RefreshingAuth {
88
180
  setTenantChooser(choose) {
89
181
  this.chooser = choose;
90
182
  }
91
- async selectTenantMember(tenantID, userID) {
183
+ async selectTenantMember(tenantID, userID, signal) {
92
184
  if (this.inflight)
93
- await this.inflight.catch(() => undefined);
185
+ await waitForAuthentication(this.inflight.catch(() => undefined), signal);
186
+ signal?.throwIfAborted();
94
187
  const previous = this.chosen;
95
188
  this.chosen = { tenantID, userID };
96
189
  // Tokens of the previous user must not be reused or refreshed.
@@ -111,6 +204,8 @@ class RefreshingAuth {
111
204
  async acceptToken(token) {
112
205
  const trimmed = token.trim();
113
206
  assertUsableJwt(trimmed);
207
+ // A rejection of the previous token must not outlive it.
208
+ this.tenantMembershipError = undefined;
114
209
  this.refreshToken = undefined;
115
210
  this.refreshExp = undefined;
116
211
  this.absorb({ access_token: trimmed });
@@ -120,32 +215,55 @@ class RefreshingAuth {
120
215
  if (token === this.accessToken)
121
216
  this.accessRejected = true;
122
217
  }
123
- async getAccessToken() {
124
- if (this.accessToken && !this.accessRejected && !isExpired(this.accessExp)) {
125
- return this.accessToken;
126
- }
218
+ async getAccessToken(signal) {
219
+ signal?.throwIfAborted();
220
+ if (this.tenantMembershipError)
221
+ throw this.tenantMembershipError;
222
+ const current = this.usableAccessToken();
223
+ if (current)
224
+ return current;
127
225
  // De-duplicate concurrent acquisitions.
128
226
  if (!this.inflight) {
129
227
  this.inflight = this.acquire().finally(() => {
130
228
  this.inflight = undefined;
131
229
  });
132
230
  }
133
- return this.inflight;
231
+ return waitForAuthentication(this.inflight, signal);
232
+ }
233
+ usableAccessToken() {
234
+ if (this.accessToken && !this.accessRejected && !isExpired(this.accessExp))
235
+ return this.accessToken;
236
+ return undefined;
134
237
  }
135
238
  async acquire() {
136
- if (this.refreshToken && !isExpired(this.refreshExp)) {
239
+ const { refreshToken, accessToken } = this;
240
+ if (refreshToken && !isExpired(this.refreshExp)) {
241
+ let renewed;
242
+ let failure;
137
243
  try {
138
- return await this.renew();
244
+ renewed = await this.renew(refreshToken, accessToken);
245
+ }
246
+ catch (error) {
247
+ failure = error;
248
+ }
249
+ // A manually supplied token takes precedence over an older refresh response.
250
+ if (this.refreshToken !== refreshToken || this.accessToken !== accessToken) {
251
+ const current = this.usableAccessToken();
252
+ if (current)
253
+ return current;
254
+ throw new Error("Токен HubEx изменился во время обновления. Повтори вызов.");
139
255
  }
140
- catch (err) {
141
- // Not fatal: fall back to a full authentication exactly once.
142
- console.error(`[hubex-mcp] token refresh failed, re-authenticating: ${err.message}`);
143
- this.refreshToken = undefined;
144
- this.refreshExp = undefined;
256
+ if (renewed) {
257
+ this.absorb(renewed);
258
+ return renewed.access_token;
145
259
  }
260
+ if (failure instanceof TenantMembershipError)
261
+ this.rejectTenantMembership(failure);
262
+ if (!this.reauthenticatesAfterRefresh(failure))
263
+ throw failure;
264
+ console.error(`[hubex-mcp] token refresh failed, re-authenticating: ${failure.message}`);
146
265
  }
147
- else if (this.refreshToken) {
148
- // Протух — выбрасываем, иначе новый не будет запрошен после аутентификации.
266
+ if (refreshToken) {
149
267
  this.refreshToken = undefined;
150
268
  this.refreshExp = undefined;
151
269
  }
@@ -160,17 +278,37 @@ class RefreshingAuth {
160
278
  * the issuer options, and without it the new token silently gets the default
161
279
  * (shorter) lifetime. The refresh token itself is not rotated.
162
280
  */
163
- async renew() {
281
+ async renew(refreshToken, accessToken) {
164
282
  const result = await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHZ/AccessTokens`, {
165
283
  method: "POST",
166
284
  headers: this.authHeaders({ "Content-Type": "application/json" }),
167
- body: JSON.stringify({ refreshJwt: this.refreshToken, accessJwt: this.accessToken }),
168
- });
169
- const token = this.absorb(result);
170
- if (!token) {
285
+ body: JSON.stringify({ refreshJwt: refreshToken, accessJwt: accessToken }),
286
+ }, { accessToken });
287
+ if (typeof result.access_token !== "string" || !result.access_token) {
171
288
  throw new Error("Refresh succeeded but no access_token was returned.");
172
289
  }
173
- return token;
290
+ if (result.refresh_token && typeof result.refresh_token !== "string") {
291
+ throw new Error("Refresh returned an invalid refresh_token.");
292
+ }
293
+ return result;
294
+ }
295
+ /**
296
+ * Whether a failed refresh drops the refresh token for a full authentication.
297
+ * AUTHZ/AccessTokens documents 400 and 401 as a rejection of the credentials sent.
298
+ * Anything else keeps it in "token" mode, where a full authentication means asking
299
+ * the user. Login and service tokens need nobody, so there it is kept only through
300
+ * an outage that a full authentication would hit as well; otherwise a refresh that
301
+ * keeps failing (403, a response without access_token) would block every call
302
+ * until the refresh token expires.
303
+ */
304
+ reauthenticatesAfterRefresh(failure) {
305
+ if (failure instanceof AuthHttpError && [400, 401].includes(failure.status))
306
+ return true;
307
+ if (this.config.authMode === "token")
308
+ return false;
309
+ const outage = failure instanceof AuthTransportError ||
310
+ (failure instanceof AuthHttpError && failure.status >= 500);
311
+ return !outage;
174
312
  }
175
313
  /** Full authentication: credentials from config, or a token from the user. */
176
314
  async authenticate() {
@@ -212,8 +350,10 @@ class RefreshingAuth {
212
350
  */
213
351
  async loginByPassword() {
214
352
  const basic = Buffer.from(`${encodeURIComponent(this.config.username)}:${encodeURIComponent(this.config.password)}`).toString("base64");
215
- const account = (await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHN/Accounts/login`, { method: "POST", headers: this.authHeaders({ Authorization: `Basic ${basic}` }) }, `Проверь HUBEX_USERNAME и HUBEX_PASSWORD: учётная запись должна существовать в окружении ` +
216
- `HUBEX_ENV=${this.config.env}.`));
353
+ const account = (await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHN/Accounts/login`, { method: "POST", headers: this.authHeaders({ Authorization: `Basic ${basic}` }) }, {
354
+ rejectHint: `Проверь HUBEX_USERNAME и HUBEX_PASSWORD: учётная запись должна существовать в окружении ` +
355
+ `HUBEX_ENV=${this.config.env}.`,
356
+ }));
217
357
  const member = await this.pickTenantMember(account.tenantEntities ?? []);
218
358
  // The chosen tenant, even when switching users: absorb() keeps a known tenant.
219
359
  this.tenantId = String(member.tenantID);
@@ -224,7 +364,7 @@ class RefreshingAuth {
224
364
  "Content-Type": "application/json",
225
365
  }),
226
366
  body: JSON.stringify({ tenantID: member.tenantID, tenantMemberID: member.tenantMemberID }),
227
- });
367
+ }, { accessToken: account.access_token, tenantMember: member });
228
368
  }
229
369
  /**
230
370
  * Narrows the account's tenant users by HUBEX_TENANT_ID / HUBEX_USER_ID. One
@@ -279,22 +419,42 @@ class RefreshingAuth {
279
419
  * against the server, so this request is the only thing that can catch a
280
420
  * token issued for the wrong environment (dev/stg/prod) — swallowing it
281
421
  * would report success on a token that doesn't actually work.
422
+ * POST, as in the HubEx web and mobile apps: GET returns a refresh token that is
423
+ * missing from ADM.TenantMemberToken, and AUTHZ/AccessTokens rejects it with
424
+ * 401 InvalidTenantMember ("Закончен период членства в тенанте").
282
425
  */
283
426
  async acquireRefreshToken() {
427
+ const accessToken = this.accessToken;
284
428
  try {
285
429
  const result = await this.fetchJwt(`${this.config.apiBaseUrl}/AUTHZ/RefreshTokens`, {
286
- method: "GET",
287
- headers: this.authHeaders({ Authorization: `Bearer ${this.accessToken}` }),
288
- });
289
- this.absorb(result);
430
+ method: "POST",
431
+ headers: this.authHeaders({ Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" }),
432
+ body: JSON.stringify({ validity: REFRESH_TOKEN_VALIDITY }),
433
+ }, { accessToken });
434
+ if (this.accessToken === accessToken)
435
+ this.absorb(result);
290
436
  }
291
437
  catch (err) {
438
+ if (err instanceof TenantMembershipError) {
439
+ if (this.accessToken === accessToken)
440
+ this.rejectTenantMembership(err);
441
+ throw err;
442
+ }
292
443
  if (this.config.authMode === "token")
293
444
  throw err;
294
445
  console.error("[hubex-mcp] could not obtain a refresh token; will re-authenticate on expiry: " +
295
446
  `${err.message}`);
296
447
  }
297
448
  }
449
+ rejectTenantMembership(error) {
450
+ this.accessRejected = true;
451
+ this.refreshToken = undefined;
452
+ this.refreshExp = undefined;
453
+ if (this.config.authMode === "token")
454
+ this.tenantMembershipError = error;
455
+ console.error(`[hubex-mcp] ${error.message}`);
456
+ throw error;
457
+ }
298
458
  authHeaders(extra) {
299
459
  return {
300
460
  "X-Application-ID": this.config.applicationId,
@@ -302,12 +462,50 @@ class RefreshingAuth {
302
462
  ...extra,
303
463
  };
304
464
  }
305
- /** `rejectHint` replaces the default wrong-environment hint on 401/403/409. */
306
- async fetchJwt(url, init, rejectHint) {
307
- const res = await fetch(url, init);
465
+ /** Repeats the request unchanged while HubEx answers InvalidTenantMember, up to the attempt limit. */
466
+ async fetchJwt(url, init, options = {}) {
467
+ for (let attempt = 1;; attempt += 1) {
468
+ try {
469
+ return await this.fetchJwtOnce(url, init, options);
470
+ }
471
+ catch (error) {
472
+ if (!(error instanceof TenantMembershipError) || attempt >= TENANT_MEMBERSHIP_ATTEMPTS)
473
+ throw error;
474
+ console.error(`[hubex-mcp] ${init.method ?? "GET"} ${url}: InvalidTenantMember, ` +
475
+ `попытка ${attempt + 1} из ${TENANT_MEMBERSHIP_ATTEMPTS} через ${TENANT_MEMBERSHIP_RETRY_DELAY_MS} мс`);
476
+ await new Promise((resolve) => setTimeout(resolve, TENANT_MEMBERSHIP_RETRY_DELAY_MS));
477
+ }
478
+ }
479
+ }
480
+ async fetchJwtOnce(url, init, options) {
481
+ const request = `${init.method ?? "GET"} ${url}`;
482
+ const controller = new AbortController();
483
+ const timeout = setTimeout(() => controller.abort(), AUTH_REQUEST_TIMEOUT_MS);
484
+ let res;
485
+ let body;
486
+ try {
487
+ res = await fetch(url, { ...init, signal: controller.signal });
488
+ body = await res.text();
489
+ }
490
+ catch (error) {
491
+ const reason = controller.signal.aborted
492
+ ? `HubEx не ответил за ${AUTH_REQUEST_TIMEOUT_MS / 1000} с`
493
+ : res
494
+ ? `ответ HTTP ${res.status} оборван: ${error.message}`
495
+ : `запрос не дошёл до HubEx: ${error.message}`;
496
+ throw new AuthTransportError(`${request}: ${reason}.`, { cause: error });
497
+ }
498
+ finally {
499
+ clearTimeout(timeout);
500
+ }
308
501
  if (!res.ok) {
309
- const body = await res.text().catch(() => "");
310
- let message = `${init.method ?? "GET"} ${url} failed (HTTP ${res.status}): ${body.slice(0, 500)}`;
502
+ if (res.status === 401) {
503
+ const membershipFailure = readTenantMembershipFailure(body);
504
+ if (membershipFailure)
505
+ throw new TenantMembershipError(membershipFailure, this.config, request, options);
506
+ }
507
+ const { rejectHint } = options;
508
+ let message = `${request} failed (HTTP ${res.status}): ${body.slice(0, 500)}`;
311
509
  if (rejectHint && [401, 403, 409].includes(res.status)) {
312
510
  message += ` ${rejectHint}`;
313
511
  }
@@ -316,9 +514,14 @@ class RefreshingAuth {
316
514
  ` Сейчас выбрано окружение HUBEX_ENV=${this.config.env}. Если токен получен в другом ` +
317
515
  `окружении (dev/stg/prod), авторизация не пройдёт — проверь, что токен именно из ${this.config.env}.`;
318
516
  }
319
- throw new Error(message);
517
+ throw new AuthHttpError(res.status, message);
518
+ }
519
+ try {
520
+ return JSON.parse(body);
521
+ }
522
+ catch {
523
+ throw new Error(`${request}: HubEx вернул не JSON (HTTP ${res.status}).`);
320
524
  }
321
- return (await res.json());
322
525
  }
323
526
  /** Stores whatever the response carried; returns its access token, if any. */
324
527
  absorb(result) {
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Чтение и проверка элементов пакета: массив `items` из вызова инструмента или
3
+ * JSON/JSONL-файл `itemsFile`. Проверка идёт до отправки первого запроса:
4
+ * ошибка здесь не должна оставлять половину пакета выполненной.
5
+ */
6
+ import { readFile, stat } from "node:fs/promises";
7
+ import { extname, isAbsolute } from "node:path";
8
+ import { RESERVED_HEADERS } from "../http.js";
9
+ export const MAX_BATCH_ITEMS = 1000;
10
+ export const MAX_ITEMS_FILE_BYTES = 20 * 1024 * 1024;
11
+ const ITEM_KEYS = ["pathParams", "query", "body", "headers"];
12
+ function isPlainObject(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function checkItemCount(items) {
16
+ if (items.length === 0) {
17
+ throw new Error("Пакет пустой: передай хотя бы один элемент.");
18
+ }
19
+ if (items.length > MAX_BATCH_ITEMS) {
20
+ throw new Error(`В пакете ${items.length} элементов, максимум ${MAX_BATCH_ITEMS}. ` +
21
+ `Раздели данные на несколько пакетов и запусти их по очереди.`);
22
+ }
23
+ }
24
+ async function readItemsFile(itemsFile) {
25
+ if (typeof itemsFile !== "string" || !isAbsolute(itemsFile)) {
26
+ throw new Error(`itemsFile должен быть строкой — абсолютный путь к файлу (получено: ${JSON.stringify(itemsFile)}). ` +
27
+ `Относительные пути не поддерживаются: укажи полный путь.`);
28
+ }
29
+ const extension = extname(itemsFile).toLowerCase();
30
+ if (extension !== ".json" && extension !== ".jsonl") {
31
+ throw new Error(`Файл ${itemsFile} должен иметь расширение .json или .jsonl ` +
32
+ `(.json — массив элементов, .jsonl — один элемент в строке).`);
33
+ }
34
+ let size;
35
+ try {
36
+ const info = await stat(itemsFile);
37
+ if (!info.isFile())
38
+ throw new Error(`${itemsFile} — не файл.`);
39
+ size = info.size;
40
+ }
41
+ catch (e) {
42
+ if (e.code === "ENOENT") {
43
+ throw new Error(`Файл ${itemsFile} не найден. Проверь путь: он должен быть абсолютным и существовать.`);
44
+ }
45
+ throw e;
46
+ }
47
+ if (size > MAX_ITEMS_FILE_BYTES) {
48
+ throw new Error(`Файл ${itemsFile} занимает ${Math.ceil(size / 1024 / 1024)} МБ, максимум ` +
49
+ `${MAX_ITEMS_FILE_BYTES / 1024 / 1024} МБ. Раздели данные на несколько файлов.`);
50
+ }
51
+ // BOM в начале файла (Excel, Блокнот Windows) ломает JSON.parse первой строки.
52
+ const text = (await readFile(itemsFile, "utf8")).replace(/^\uFEFF/, "");
53
+ if (extension === ".json") {
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(text);
57
+ }
58
+ catch (e) {
59
+ throw new Error(`Файл ${itemsFile} — некорректный JSON: ${e.message}`);
60
+ }
61
+ if (!Array.isArray(parsed)) {
62
+ throw new Error(`Файл ${itemsFile} должен содержать массив элементов пакета, а не ${isPlainObject(parsed) ? "объект" : "одиночное значение"}. ` +
63
+ `Для элемента на строку используй расширение .jsonl.`);
64
+ }
65
+ return parsed;
66
+ }
67
+ const items = [];
68
+ text.split("\n").forEach((line, i) => {
69
+ if (line.trim() === "")
70
+ return;
71
+ try {
72
+ items.push(JSON.parse(line));
73
+ }
74
+ catch (e) {
75
+ throw new Error(`Файл ${itemsFile}, строка ${i + 1}: некорректный JSON (${e.message}). ` +
76
+ `В .jsonl на каждой строке должен быть один JSON-элемент.`);
77
+ }
78
+ });
79
+ return items;
80
+ }
81
+ /** Элементы пакета из `items` или `itemsFile` (ровно одно из двух). */
82
+ export async function readBatchItems(args) {
83
+ const hasItems = args.items !== undefined && args.items !== null;
84
+ const hasFile = args.itemsFile !== undefined && args.itemsFile !== null;
85
+ if (hasItems === hasFile) {
86
+ throw new Error("Передай либо items, либо itemsFile — ровно одно из двух: items — массив элементов, " +
87
+ "itemsFile — абсолютный путь к .json/.jsonl.");
88
+ }
89
+ if (hasItems) {
90
+ if (!Array.isArray(args.items)) {
91
+ throw new Error("items должен быть массивом элементов вида { pathParams?, query?, body?, headers? }.");
92
+ }
93
+ checkItemCount(args.items);
94
+ return { items: args.items };
95
+ }
96
+ const items = await readItemsFile(args.itemsFile);
97
+ checkItemCount(items);
98
+ return { items, itemsFile: args.itemsFile };
99
+ }
100
+ /** Элемент пакета как вход запроса; ошибка называет индекс элемента (с нуля). */
101
+ export function toRequestInput(raw, index) {
102
+ const label = `Элемент ${index}`;
103
+ if (!isPlainObject(raw)) {
104
+ throw new Error(`${label}: ожидается объект { pathParams?, query?, body?, headers? }, получено ${raw === null ? "null" : Array.isArray(raw) ? "массив" : typeof raw}.`);
105
+ }
106
+ const keys = Object.keys(raw);
107
+ const unknown = keys.filter((k) => !ITEM_KEYS.includes(k));
108
+ if (unknown.length > 0) {
109
+ if (unknown.length === keys.length) {
110
+ throw new Error(`${label}: похоже на голое тело запроса (ключи: ${unknown.join(", ")}). ` +
111
+ `Оберни его в поле body: { "body": { ... } }. ` +
112
+ `Допустимые ключи элемента: ${ITEM_KEYS.join(", ")}.`);
113
+ }
114
+ throw new Error(`${label}: неизвестные ключи: ${unknown.join(", ")}. ` +
115
+ `Допустимые ключи элемента: ${ITEM_KEYS.join(", ")}. ` +
116
+ `Поля тела запроса клади внутрь body.`);
117
+ }
118
+ // null — то же, что отсутствие поля (как `args.pathParams ?? {}` в hubex_request_*).
119
+ const fields = Object.fromEntries(Object.entries(raw).filter(([, v]) => v !== null));
120
+ for (const key of ["pathParams", "query", "headers"]) {
121
+ if (fields[key] !== undefined && !isPlainObject(fields[key])) {
122
+ throw new Error(`${label}: поле ${key} должно быть объектом.`);
123
+ }
124
+ }
125
+ if (isPlainObject(fields.headers)) {
126
+ const bad = Object.entries(fields.headers)
127
+ .filter(([, v]) => typeof v !== "string")
128
+ .map(([k]) => k);
129
+ if (bad.length > 0) {
130
+ throw new Error(`${label}: значения headers должны быть строками, исправь: ${bad.join(", ")}.`);
131
+ }
132
+ // HubexClient отклонил бы такой заголовок уже при отправке — элемент упал бы
133
+ // посреди пакета, а не при проверке до старта.
134
+ const reserved = Object.keys(fields.headers).filter((name) => RESERVED_HEADERS.has(name.toLowerCase()));
135
+ if (reserved.length > 0) {
136
+ throw new Error(`${label}: заголовки ${reserved.join(", ")} подставляет сам сервер, переопределить их нельзя. ` +
137
+ `Убери их из headers.`);
138
+ }
139
+ }
140
+ return fields;
141
+ }