itd-api 0.10.4 → 0.12.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/README.md +2 -1
- package/dist/events/index.cjs +27 -25
- package/dist/events/index.d.cts +3 -3
- package/dist/events/index.d.ts +3 -3
- package/dist/events/index.js +5 -5
- package/dist/index.cjs +155 -155
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -20
- package/dist/index.d.ts +35 -20
- package/dist/index.js +65 -72
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +13 -13
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +7 -8
- package/dist/node/index.d.ts +7 -8
- package/dist/node/index.js +5 -5
- package/dist/node/index.js.map +1 -1
- package/dist/rest/index.cjs +46 -40
- package/dist/rest/index.cjs.map +1 -1
- package/dist/rest/index.d.cts +5 -5
- package/dist/rest/index.d.ts +5 -5
- package/dist/rest/index.js +6 -6
- package/dist/rest/index.js.map +1 -1
- package/dist/shared/{events-CK3zHntT.d.cts → events-9L0Fonak.d.cts} +2 -2
- package/dist/shared/{events-DGdU8q1X.d.ts → events-BpLAIiMj.d.ts} +2 -2
- package/dist/shared/{events-B8cjz_Ed.cjs → events-C2DJZyI0.cjs} +306 -112
- package/dist/shared/events-C2DJZyI0.cjs.map +1 -0
- package/dist/shared/{events-D2n7Yu1P.js → events-D1BfefBT.js} +262 -68
- package/dist/shared/events-D1BfefBT.js.map +1 -0
- package/dist/shared/{key-value-store-B5GYVEYZ.cjs → key-value-store-DYSPsqwq.cjs} +11 -14
- package/dist/shared/key-value-store-DYSPsqwq.cjs.map +1 -0
- package/dist/shared/{key-value-store-Bt2PSMxY.js → key-value-store-w1Dn5Pjb.js} +5 -8
- package/dist/shared/key-value-store-w1Dn5Pjb.js.map +1 -0
- package/dist/shared/{multi-storage-s-fPtjoy.cjs → multi-storage-7Y3KCseI.cjs} +8 -8
- package/dist/shared/multi-storage-7Y3KCseI.cjs.map +1 -0
- package/dist/shared/{multi-storage-C3Ngtop1.js → multi-storage-DiBSx64p.js} +6 -6
- package/dist/shared/multi-storage-DiBSx64p.js.map +1 -0
- package/dist/shared/{options-DjEtbVaf.cjs → options-D5ttspWk.cjs} +13 -13
- package/dist/shared/{options-DjEtbVaf.cjs.map → options-D5ttspWk.cjs.map} +1 -1
- package/dist/shared/{options-i4LrKfqx.js → options-DLlaETn_.js} +3 -3
- package/dist/shared/{options-i4LrKfqx.js.map → options-DLlaETn_.js.map} +1 -1
- package/dist/shared/{redact-lAmck1Z6.cjs → redact-BbhtA9o-.cjs} +121 -26
- package/dist/shared/redact-BbhtA9o-.cjs.map +1 -0
- package/dist/shared/{redact-DJV0XM3n.js → redact-DSfdmeY7.js} +91 -20
- package/dist/shared/redact-DSfdmeY7.js.map +1 -0
- package/dist/shared/{render-BrrZOSV5.cjs → render-CrGXcj6L.cjs} +346 -284
- package/dist/shared/render-CrGXcj6L.cjs.map +1 -0
- package/dist/shared/{render-C6CJ343E.js → render-D3vSEbLL.js} +240 -178
- package/dist/shared/render-D3vSEbLL.js.map +1 -0
- package/dist/shared/{render-9F_kR6sq.d.cts → render-Dzw3KeN5.d.cts} +236 -278
- package/dist/shared/{render-UsOGMRzS.d.ts → render-UsQ1hb2U.d.ts} +236 -278
- package/dist/shared/{storage-DiDe0PZM.js → storage-86wiHeXD.js} +3 -3
- package/dist/shared/storage-86wiHeXD.js.map +1 -0
- package/dist/shared/{storage-CZJZoaz9.cjs → storage-CIjejZDt.cjs} +4 -4
- package/dist/shared/storage-CIjejZDt.cjs.map +1 -0
- package/dist/shared/{url-BNTKqBMB.cjs → url-B21Bdmw_.cjs} +869 -717
- package/dist/shared/url-B21Bdmw_.cjs.map +1 -0
- package/dist/shared/{url-yB6T_H_-.d.cts → url-C9YADYNg.d.cts} +221 -103
- package/dist/shared/{url-yB6T_H_-.d.ts → url-C9YADYNg.d.ts} +221 -103
- package/dist/shared/{url-Dc7wLikf.js → url-Dg1u29cu.js} +744 -598
- package/dist/shared/url-Dg1u29cu.js.map +1 -0
- package/dist/shared/{errors-BmP3TKoW.cjs → validate-CFx2dISs.cjs} +84 -5
- package/dist/shared/validate-CFx2dISs.cjs.map +1 -0
- package/dist/shared/{errors-GI10kZxk.js → validate-D7_kq3g5.js} +55 -6
- package/dist/shared/validate-D7_kq3g5.js.map +1 -0
- package/dist/web/index.cjs +4 -4
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +4 -5
- package/dist/web/index.d.ts +4 -5
- package/dist/web/index.js +3 -3
- package/dist/web/index.js.map +1 -1
- package/package.json +11 -11
- package/dist/shared/errors-BmP3TKoW.cjs.map +0 -1
- package/dist/shared/errors-GI10kZxk.js.map +0 -1
- package/dist/shared/events-B8cjz_Ed.cjs.map +0 -1
- package/dist/shared/events-D2n7Yu1P.js.map +0 -1
- package/dist/shared/key-value-store-B5GYVEYZ.cjs.map +0 -1
- package/dist/shared/key-value-store-Bt2PSMxY.js.map +0 -1
- package/dist/shared/multi-storage-C3Ngtop1.js.map +0 -1
- package/dist/shared/multi-storage-s-fPtjoy.cjs.map +0 -1
- package/dist/shared/redact-DJV0XM3n.js.map +0 -1
- package/dist/shared/redact-lAmck1Z6.cjs.map +0 -1
- package/dist/shared/render-BrrZOSV5.cjs.map +0 -1
- package/dist/shared/render-C6CJ343E.js.map +0 -1
- package/dist/shared/storage-CZJZoaz9.cjs.map +0 -1
- package/dist/shared/storage-DiDe0PZM.js.map +0 -1
- package/dist/shared/url-BNTKqBMB.cjs.map +0 -1
- package/dist/shared/url-Dc7wLikf.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_url = require("./shared/url-
|
|
3
|
-
const
|
|
4
|
-
const require_redact = require("./shared/redact-
|
|
5
|
-
const require_render = require("./shared/render-
|
|
6
|
-
const require_options = require("./shared/options-
|
|
7
|
-
const require_events = require("./shared/events-
|
|
8
|
-
const require_key_value_store = require("./shared/key-value-store-
|
|
9
|
-
const require_storage = require("./shared/storage-
|
|
10
|
-
const require_multi_storage = require("./shared/multi-storage-
|
|
2
|
+
const require_url = require("./shared/url-B21Bdmw_.cjs");
|
|
3
|
+
const require_validate = require("./shared/validate-CFx2dISs.cjs");
|
|
4
|
+
const require_redact = require("./shared/redact-BbhtA9o-.cjs");
|
|
5
|
+
const require_render = require("./shared/render-CrGXcj6L.cjs");
|
|
6
|
+
const require_options = require("./shared/options-D5ttspWk.cjs");
|
|
7
|
+
const require_events = require("./shared/events-C2DJZyI0.cjs");
|
|
8
|
+
const require_key_value_store = require("./shared/key-value-store-DYSPsqwq.cjs");
|
|
9
|
+
const require_storage = require("./shared/storage-CIjejZDt.cjs");
|
|
10
|
+
const require_multi_storage = require("./shared/multi-storage-7Y3KCseI.cjs");
|
|
11
11
|
//#region src/notifications-api.ts
|
|
12
12
|
var ClientNotifications = class extends require_render.NotificationsResource {
|
|
13
13
|
#createEvents;
|
|
@@ -58,12 +58,12 @@ const QrLoginStreamStatus = Object.freeze({
|
|
|
58
58
|
});
|
|
59
59
|
function requireString(body, key, message) {
|
|
60
60
|
const value = require_url.pickString(body, key);
|
|
61
|
-
if (!value) throw new
|
|
61
|
+
if (!value) throw new require_validate.ItdConfigError(message);
|
|
62
62
|
return value;
|
|
63
63
|
}
|
|
64
64
|
const AUTH_CHECK = require_url.passthroughOperation("auth.check");
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
require_url.passthroughOperation("auth.captchaProvider");
|
|
66
|
+
require_url.passthroughOperation("auth.captchaPage");
|
|
67
67
|
const AUTH_SIGN_UP = require_url.defineBuiltInOperation("auth.signUp", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при регистрации"));
|
|
68
68
|
const AUTH_SIGN_IN = require_url.defineBuiltInOperation("auth.signIn", (body) => {
|
|
69
69
|
const accessToken = require_url.pickString(body, "accessToken");
|
|
@@ -93,7 +93,7 @@ const AUTH_QR_REJECT = require_url.voidOperation("auth.qrReject");
|
|
|
93
93
|
//#endregion
|
|
94
94
|
//#region src/session/captcha.ts
|
|
95
95
|
function requireCaptchaText(value, field) {
|
|
96
|
-
if (value !== void 0 && (typeof value !== "string" || value.trim() === "")) throw new
|
|
96
|
+
if (value !== void 0 && (typeof value !== "string" || value.trim() === "")) throw new require_validate.ItdConfigError(`${field} должен быть непустой строкой`);
|
|
97
97
|
}
|
|
98
98
|
/**
|
|
99
99
|
* Проверяет форму источника токена и приводит его к объекту.
|
|
@@ -106,9 +106,9 @@ function requireCaptchaText(value, field) {
|
|
|
106
106
|
function resolveCaptchaSolver(captcha) {
|
|
107
107
|
if (captcha === void 0) return void 0;
|
|
108
108
|
if (typeof captcha === "function") return { getToken: captcha };
|
|
109
|
-
if (!
|
|
109
|
+
if (!require_validate.isRecord(captcha)) throw new require_validate.ItdConfigError("captcha должен быть функцией либо объектом с getToken");
|
|
110
110
|
const { getToken, type, field } = captcha;
|
|
111
|
-
if (typeof getToken !== "function") throw new
|
|
111
|
+
if (typeof getToken !== "function") throw new require_validate.ItdConfigError("captcha.getToken должен быть функцией");
|
|
112
112
|
requireCaptchaText(type, "captcha.type");
|
|
113
113
|
requireCaptchaText(field, "captcha.field");
|
|
114
114
|
return captcha;
|
|
@@ -121,34 +121,23 @@ function resolveCaptchaSolver(captcha) {
|
|
|
121
121
|
*/
|
|
122
122
|
function validateCaptchaToken(captcha, path) {
|
|
123
123
|
if (captcha === void 0) return;
|
|
124
|
-
if (!
|
|
124
|
+
if (!require_validate.isRecord(captcha)) throw new require_validate.ItdConfigError(`${path} должен быть объектом { type, token }`);
|
|
125
125
|
const { type, token, field } = captcha;
|
|
126
|
-
if (typeof token !== "string" || token.trim() === "") throw new
|
|
127
|
-
if (typeof type !== "string" || type.trim() === "") throw new
|
|
126
|
+
if (typeof token !== "string" || token.trim() === "") throw new require_validate.ItdConfigError(`${path}.token должен быть непустой строкой`);
|
|
127
|
+
if (typeof type !== "string" || type.trim() === "") throw new require_validate.ItdConfigError(`${path}.type должен быть непустой строкой`);
|
|
128
128
|
requireCaptchaText(field, `${path}.field`);
|
|
129
129
|
}
|
|
130
|
-
/** Разбирает ответ `GET /api/v1/auth/captcha/provider` для автоматического входа. */
|
|
131
|
-
function readCaptchaProvider(body) {
|
|
132
|
-
const config = require_url.isRecord$1(body) ? body : void 0;
|
|
133
|
-
const provider = config?.provider;
|
|
134
|
-
const field = config?.field;
|
|
135
|
-
if (typeof provider !== "string" || provider.trim() === "" || typeof field !== "string" || field.trim() === "") throw new require_errors.ItdConfigError("Сервер вернул неподдерживаемую конфигурацию капчи");
|
|
136
|
-
return {
|
|
137
|
-
provider,
|
|
138
|
-
field
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
130
|
/** Куда класть токен: настройка, иначе умолчание провайдера. */
|
|
142
131
|
function resolveField(type, configured) {
|
|
143
132
|
const field = configured ?? CAPTCHA_FIELDS[type];
|
|
144
133
|
if (field) return field;
|
|
145
|
-
throw new
|
|
134
|
+
throw new require_validate.ItdConfigError(`Неизвестно, в каком поле сервер ждёт токен капчи «${type}». Передайте captcha.field либо оставьте captcha.type = ${require_url.CaptchaChoice.Auto}, чтобы поле назвал сервер.`);
|
|
146
135
|
}
|
|
147
136
|
/** Спрашивает токен у источника и убеждается, что он непустой. */
|
|
148
|
-
async function requireSolvedToken(solver, type) {
|
|
149
|
-
const token = await solver.getToken(type);
|
|
137
|
+
async function requireSolvedToken(solver, type, context) {
|
|
138
|
+
const token = await solver.getToken(type, context);
|
|
150
139
|
if (typeof token === "string" && token.trim() !== "") return token;
|
|
151
|
-
throw new
|
|
140
|
+
throw new require_validate.ItdConfigError(`Источник капчи не вернул токен для провайдера «${type}». Проверьте captcha.getToken.`);
|
|
152
141
|
}
|
|
153
142
|
/**
|
|
154
143
|
* Готовит фрагмент тела запроса, взяв токен у источника.
|
|
@@ -157,15 +146,16 @@ async function requireSolvedToken(solver, type) {
|
|
|
157
146
|
* и имя поля приходят оттуда. Явно названный тип обходится без этого запроса.
|
|
158
147
|
*
|
|
159
148
|
* @param askProvider как спросить активного провайдера; вызывается, только если это нужно
|
|
149
|
+
* @param context что источник получает вместе с типом капчи
|
|
160
150
|
* @throws {ItdConfigError} если токен получить не удалось
|
|
161
151
|
*/
|
|
162
|
-
async function solveCaptchaBody(solver, askProvider) {
|
|
152
|
+
async function solveCaptchaBody(solver, askProvider, context) {
|
|
163
153
|
const choice = solver.type ?? require_url.CaptchaChoice.Auto;
|
|
164
154
|
if (choice === require_url.CaptchaChoice.Auto) {
|
|
165
155
|
const { provider, field } = await askProvider();
|
|
166
|
-
return { [field]: await requireSolvedToken(solver, provider) };
|
|
156
|
+
return { [field]: await requireSolvedToken(solver, provider, context) };
|
|
167
157
|
}
|
|
168
|
-
return { [resolveField(choice, solver.field)]: await requireSolvedToken(solver, choice) };
|
|
158
|
+
return { [resolveField(choice, solver.field)]: await requireSolvedToken(solver, choice, context) };
|
|
169
159
|
}
|
|
170
160
|
/**
|
|
171
161
|
* Готовит фрагмент тела из готового токена.
|
|
@@ -231,41 +221,41 @@ const ACCESS_TOKEN_REFRESH_LEEWAY_MS = 3e4;
|
|
|
231
221
|
function validateAuth(auth) {
|
|
232
222
|
if (auth === void 0) return void 0;
|
|
233
223
|
if (typeof auth === "string") {
|
|
234
|
-
if (auth.trim() === "") throw new
|
|
224
|
+
if (auth.trim() === "") throw new require_validate.ItdConfigError("auth: передана пустая строка вместо accessToken");
|
|
235
225
|
return auth;
|
|
236
226
|
}
|
|
237
|
-
if (typeof auth !== "object" || auth === null) throw new
|
|
227
|
+
if (typeof auth !== "object" || auth === null) throw new require_validate.ItdConfigError(`auth должен быть строкой с токеном или объектом, получено: ${typeof auth}`);
|
|
238
228
|
if ([
|
|
239
229
|
"getToken" in auth,
|
|
240
230
|
"accessToken" in auth || "refreshToken" in auth,
|
|
241
231
|
"email" in auth || "password" in auth
|
|
242
|
-
].filter(Boolean).length > 1) throw new
|
|
232
|
+
].filter(Boolean).length > 1) throw new require_validate.ItdConfigError("auth должен описывать ровно один способ авторизации: getToken, accessToken или email/password");
|
|
243
233
|
if ("getToken" in auth) {
|
|
244
|
-
if (typeof auth.getToken !== "function") throw new
|
|
234
|
+
if (typeof auth.getToken !== "function") throw new require_validate.ItdConfigError("auth.getToken должен быть функцией");
|
|
245
235
|
return { ...auth };
|
|
246
236
|
}
|
|
247
237
|
if ("accessToken" in auth) {
|
|
248
|
-
if (typeof auth.accessToken !== "string" || auth.accessToken.trim() === "") throw new
|
|
249
|
-
if (auth.refreshToken !== void 0 && (typeof auth.refreshToken !== "string" || auth.refreshToken.trim() === "")) throw new
|
|
238
|
+
if (typeof auth.accessToken !== "string" || auth.accessToken.trim() === "") throw new require_validate.ItdConfigError("auth.accessToken должен быть непустой строкой");
|
|
239
|
+
if (auth.refreshToken !== void 0 && (typeof auth.refreshToken !== "string" || auth.refreshToken.trim() === "")) throw new require_validate.ItdConfigError("auth.refreshToken должен быть непустой строкой");
|
|
250
240
|
return { ...auth };
|
|
251
241
|
}
|
|
252
242
|
if ("email" in auth || "password" in auth) {
|
|
253
243
|
const { email, password, captcha } = auth;
|
|
254
|
-
if (typeof email !== "string" || email.trim() === "") throw new
|
|
255
|
-
if (typeof password !== "string" || password === "") throw new
|
|
244
|
+
if (typeof email !== "string" || email.trim() === "") throw new require_validate.ItdConfigError("auth.email должен быть непустой строкой");
|
|
245
|
+
if (typeof password !== "string" || password === "") throw new require_validate.ItdConfigError("auth.password должен быть непустой строкой");
|
|
256
246
|
validateCaptchaToken(captcha, "auth.captcha");
|
|
257
247
|
return { ...auth };
|
|
258
248
|
}
|
|
259
|
-
throw new
|
|
249
|
+
throw new require_validate.ItdConfigError("auth не распознан. Ожидается строка с accessToken либо объект { accessToken }, { email, password } или { getToken }");
|
|
260
250
|
}
|
|
261
251
|
function resolveStorage(storage) {
|
|
262
252
|
if (storage === void 0) return new require_storage.MemoryTokenStorage();
|
|
263
|
-
if (!
|
|
253
|
+
if (!require_validate.isObjectLike(storage)) throw new require_validate.ItdConfigError("storage должен быть объектом TokenStorage");
|
|
264
254
|
for (const method of [
|
|
265
255
|
"get",
|
|
266
256
|
"set",
|
|
267
257
|
"clear"
|
|
268
|
-
]) if (typeof storage[method] !== "function") throw new
|
|
258
|
+
]) if (typeof storage[method] !== "function") throw new require_validate.ItdConfigError(`storage.${method} должен быть функцией`);
|
|
269
259
|
return storage;
|
|
270
260
|
}
|
|
271
261
|
/**
|
|
@@ -275,10 +265,10 @@ function resolveStorage(storage) {
|
|
|
275
265
|
* @throws {ItdConfigError} при некорректных значениях
|
|
276
266
|
*/
|
|
277
267
|
function resolveSessionConfig(options, runtime) {
|
|
278
|
-
if (!
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (options.deviceId !== void 0 && (typeof options.deviceId !== "string" || options.deviceId.trim() === "")) throw new
|
|
268
|
+
if (!require_validate.isObjectLike(options)) throw new require_validate.ItdConfigError("опции клиента должны быть объектом");
|
|
269
|
+
require_validate.requireOptionalBoolean(options.autoRefresh, "autoRefresh");
|
|
270
|
+
require_validate.requireOptionalBoolean(options.reloginOnRefreshFailure, "reloginOnRefreshFailure");
|
|
271
|
+
if (options.deviceId !== void 0 && (typeof options.deviceId !== "string" || options.deviceId.trim() === "")) throw new require_validate.ItdConfigError("deviceId должен быть непустой строкой");
|
|
282
272
|
return {
|
|
283
273
|
...runtime,
|
|
284
274
|
auth: validateAuth(options.auth),
|
|
@@ -349,12 +339,12 @@ function withoutLegacyUserId(session) {
|
|
|
349
339
|
}
|
|
350
340
|
function normalizeSessionValue(value, source, mode = "strict", logger) {
|
|
351
341
|
const tolerant = mode === "stored";
|
|
352
|
-
if (!
|
|
342
|
+
if (!require_validate.isRecord(value)) {
|
|
353
343
|
if (tolerant) {
|
|
354
344
|
logger?.warn(`${source} вернула не объект сессии; сохранённая запись пропущена`);
|
|
355
345
|
return null;
|
|
356
346
|
}
|
|
357
|
-
throw new
|
|
347
|
+
throw new require_validate.ItdConfigError(`${source} должна быть объектом сессии`);
|
|
358
348
|
}
|
|
359
349
|
const record = value;
|
|
360
350
|
const normalized = { ...record };
|
|
@@ -371,7 +361,7 @@ function normalizeSessionValue(value, source, mode = "strict", logger) {
|
|
|
371
361
|
delete normalized[field];
|
|
372
362
|
return;
|
|
373
363
|
}
|
|
374
|
-
throw new
|
|
364
|
+
throw new require_validate.ItdConfigError(`${source}.${field} должна быть непустой строкой`);
|
|
375
365
|
}
|
|
376
366
|
normalized[field] = item;
|
|
377
367
|
};
|
|
@@ -380,7 +370,7 @@ function normalizeSessionValue(value, source, mode = "strict", logger) {
|
|
|
380
370
|
normalizeString("deviceId");
|
|
381
371
|
if (record.obtainedAt === void 0) delete normalized.obtainedAt;
|
|
382
372
|
else if (typeof record.obtainedAt !== "number" || !Number.isFinite(record.obtainedAt)) {
|
|
383
|
-
if (!tolerant) throw new
|
|
373
|
+
if (!tolerant) throw new require_validate.ItdConfigError(`${source}.obtainedAt должна быть конечным числом`);
|
|
384
374
|
else {
|
|
385
375
|
logger?.warn(`${source}.obtainedAt повреждена; поле сохранённой сессии пропущено`);
|
|
386
376
|
delete normalized.obtainedAt;
|
|
@@ -391,7 +381,7 @@ function normalizeSessionValue(value, source, mode = "strict", logger) {
|
|
|
391
381
|
if (tolerant) {
|
|
392
382
|
logger?.warn(`${source}.cookies повреждена; поле сохранённой сессии пропущено`);
|
|
393
383
|
delete normalized.cookies;
|
|
394
|
-
} else throw new
|
|
384
|
+
} else throw new require_validate.ItdConfigError(`${source}.cookies должна быть массивом`);
|
|
395
385
|
} else {
|
|
396
386
|
const valid = record.cookies.filter((cookie) => typeof cookie === "string" && require_redact.isSerializedCookieEntry(cookie));
|
|
397
387
|
if (valid.length > 0) normalized.cookies = valid;
|
|
@@ -401,7 +391,7 @@ function normalizeSessionValue(value, source, mode = "strict", logger) {
|
|
|
401
391
|
}
|
|
402
392
|
function normalizeSession(value, source) {
|
|
403
393
|
const normalized = normalizeSessionValue(value, source);
|
|
404
|
-
if (!normalized) throw new
|
|
394
|
+
if (!normalized) throw new require_validate.ItdConfigError(`${source} должна быть объектом сессии`);
|
|
405
395
|
return normalized;
|
|
406
396
|
}
|
|
407
397
|
let authScopeSequence = 0;
|
|
@@ -544,7 +534,7 @@ var AuthManager = class {
|
|
|
544
534
|
return true;
|
|
545
535
|
}
|
|
546
536
|
#assertActive() {
|
|
547
|
-
if (this.#disposed) throw new
|
|
537
|
+
if (this.#disposed) throw new require_validate.ItdStateError("Менеджер авторизации уже освобождён");
|
|
548
538
|
}
|
|
549
539
|
#currentAccessToken() {
|
|
550
540
|
return this.#session?.accessToken ?? null;
|
|
@@ -732,7 +722,7 @@ var AuthManager = class {
|
|
|
732
722
|
* `SESSION_NOT_FOUND`, `SESSION_REVOKED` — разные поводы и разные действия).
|
|
733
723
|
*/
|
|
734
724
|
#noRefreshSessionError() {
|
|
735
|
-
return new
|
|
725
|
+
return new require_validate.ItdAuthError({
|
|
736
726
|
status: 401,
|
|
737
727
|
code: "SESSION_EXPIRED",
|
|
738
728
|
message: "Не удалось обновить сессию: нет ни cookie is_auth, ни refresh-токена. Войдите заново либо передайте refreshToken в auth.",
|
|
@@ -764,7 +754,7 @@ var AuthManager = class {
|
|
|
764
754
|
}
|
|
765
755
|
async #storeAccessToken(accessToken, expectedRevision, cookies, replaceSession) {
|
|
766
756
|
this.#assertActive();
|
|
767
|
-
if (typeof accessToken !== "string" || accessToken.trim() === "") throw new
|
|
757
|
+
if (typeof accessToken !== "string" || accessToken.trim() === "") throw new require_validate.ItdConfigError("accessToken должен быть непустой строкой");
|
|
768
758
|
await this.#loadSession();
|
|
769
759
|
this.#assertActive();
|
|
770
760
|
if (this.#authEpoch !== expectedRevision) return false;
|
|
@@ -777,6 +767,7 @@ var AuthManager = class {
|
|
|
777
767
|
obtainedAt: this.#config.clock.now()
|
|
778
768
|
});
|
|
779
769
|
this.#emitter.emit("tokens", { accessToken });
|
|
770
|
+
this.#config.logger?.info(`${replaceSession ? "вход выполнен" : "принят токен доступа"}${this.#describeUser(accessToken)}`);
|
|
780
771
|
await saved;
|
|
781
772
|
return true;
|
|
782
773
|
}
|
|
@@ -828,6 +819,7 @@ var AuthManager = class {
|
|
|
828
819
|
const retained = this.#deviceId ? { deviceId: this.#deviceId } : null;
|
|
829
820
|
this.#session = retained;
|
|
830
821
|
this.#emitter.emit("signOut", void 0);
|
|
822
|
+
this.#config.logger?.info("сессия очищена");
|
|
831
823
|
await this.#enqueuePersistence(async () => {
|
|
832
824
|
await this.#config.storage.clear();
|
|
833
825
|
if (retained) await this.#config.storage.set(require_storage.copySession(retained));
|
|
@@ -845,6 +837,7 @@ var AuthManager = class {
|
|
|
845
837
|
this.#assertActive();
|
|
846
838
|
const stored = loaded === null ? null : normalizeSessionValue(loaded, "storage.get()", "stored", this.#config.logger);
|
|
847
839
|
if (stored?.cookies) this.#jar.deserialize(stored.cookies);
|
|
840
|
+
if (stored?.accessToken) this.#config.logger?.info(`сессия восстановлена из хранилища${this.#describeUser(stored.accessToken)}`);
|
|
848
841
|
const fromConfig = this.#sessionFromConfig(this.#config.auth);
|
|
849
842
|
this.#session = stored && fromConfig ? {
|
|
850
843
|
...stored,
|
|
@@ -941,12 +934,14 @@ var AuthManager = class {
|
|
|
941
934
|
obtainedAt: this.#config.clock.now()
|
|
942
935
|
});
|
|
943
936
|
this.#emitter.emit("tokens", { accessToken });
|
|
937
|
+
this.#config.logger?.info("токен доступа обновлён");
|
|
944
938
|
await saved;
|
|
945
939
|
if (this.#authEpoch !== expectation.epoch) return this.#currentAccessToken();
|
|
946
940
|
return accessToken;
|
|
947
941
|
} catch (error) {
|
|
948
942
|
if (this.#authEpoch !== expectation.epoch) return this.#currentAccessToken();
|
|
949
|
-
if (error instanceof
|
|
943
|
+
if (error instanceof require_validate.ItdAuthError) {
|
|
944
|
+
this.#config.logger?.warn(`обновить сессию не удалось (${error.message}); сохранённая сессия удалена`);
|
|
950
945
|
this.#invalidateInFlight();
|
|
951
946
|
const clearedRevision = this.#authEpoch;
|
|
952
947
|
this.#transitionAuth(void 0);
|
|
@@ -1002,7 +997,7 @@ var AuthManager = class {
|
|
|
1002
997
|
const configured = this.#takeConfiguredCaptcha();
|
|
1003
998
|
if (configured) return captchaBody(configured);
|
|
1004
999
|
const solver = this.#config.captcha;
|
|
1005
|
-
if (solver) return solveCaptchaBody(solver, () => this.#resolveCaptchaProvider());
|
|
1000
|
+
if (solver) return solveCaptchaBody(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
|
|
1006
1001
|
this.#config.logger?.debug("Запрос уходит без токена капчи: не передан аргумент captcha и не задана опция captcha");
|
|
1007
1002
|
return {};
|
|
1008
1003
|
}
|
|
@@ -1010,29 +1005,17 @@ var AuthManager = class {
|
|
|
1010
1005
|
#takeConfiguredCaptcha() {
|
|
1011
1006
|
if (this.#configCaptchaSpent) return void 0;
|
|
1012
1007
|
const auth = this.#config.auth;
|
|
1013
|
-
const captcha =
|
|
1008
|
+
const captcha = typeof auth === "object" && auth !== null && "email" in auth ? auth.captcha : void 0;
|
|
1014
1009
|
if (!captcha) return void 0;
|
|
1015
1010
|
this.#configCaptchaSpent = true;
|
|
1016
1011
|
return captcha;
|
|
1017
1012
|
}
|
|
1018
1013
|
/** Спрашивает у сервера активного провайдера и поле, в котором он ждёт токен. */
|
|
1019
1014
|
async #resolveCaptchaProvider() {
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
skipAuthRefresh: true
|
|
1025
|
-
}));
|
|
1026
|
-
} catch (error) {
|
|
1027
|
-
if (require_errors.isItdApiError(error) && error.status === 404 && error.code === require_url.ItdErrorCode.NOT_FOUND) {
|
|
1028
|
-
this.#config.logger?.warn("Сервер отключил определение провайдера капчи; используется Cloudflare Turnstile");
|
|
1029
|
-
return {
|
|
1030
|
-
provider: require_url.CaptchaType.Cloudflare,
|
|
1031
|
-
field: require_url.CaptchaField.Cloudflare
|
|
1032
|
-
};
|
|
1033
|
-
}
|
|
1034
|
-
throw error;
|
|
1035
|
-
}
|
|
1015
|
+
return {
|
|
1016
|
+
provider: require_url.CaptchaType.Cloudflare,
|
|
1017
|
+
field: require_url.CaptchaField.Cloudflare
|
|
1018
|
+
};
|
|
1036
1019
|
}
|
|
1037
1020
|
async #performSignIn(credentials, revision) {
|
|
1038
1021
|
const captcha = await this.captchaBody();
|
|
@@ -1048,7 +1031,7 @@ var AuthManager = class {
|
|
|
1048
1031
|
skipAuthRefresh: true,
|
|
1049
1032
|
cookieJar: flowCookies
|
|
1050
1033
|
});
|
|
1051
|
-
if (result.status !== SignInStatus.Authenticated) throw new
|
|
1034
|
+
if (result.status !== SignInStatus.Authenticated) throw new require_validate.ItdConfigError("Вход по email и паролю требует подтверждения кодом из письма. Автоматический вход невозможен: воспользуйтесь itd.auth.signInWithOtp() и передайте полученный accessToken в конфигурацию клиента.");
|
|
1052
1035
|
const accessToken = result.accessToken;
|
|
1053
1036
|
this.#assertActive();
|
|
1054
1037
|
if (this.#authEpoch !== revision) return this.#session?.accessToken ?? null;
|
|
@@ -1061,9 +1044,15 @@ var AuthManager = class {
|
|
|
1061
1044
|
});
|
|
1062
1045
|
this.#emitter.emit("tokens", { accessToken });
|
|
1063
1046
|
this.#emitter.emit("signIn", { accessToken });
|
|
1047
|
+
this.#config.logger?.info(`вход по email и паролю выполнен${this.#describeUser(accessToken)}`);
|
|
1064
1048
|
await saved;
|
|
1065
1049
|
return accessToken;
|
|
1066
1050
|
}
|
|
1051
|
+
/** Хвост сообщения журнала с идентификатором пользователя, если токен его содержит. */
|
|
1052
|
+
#describeUser(accessToken) {
|
|
1053
|
+
const userId = this.#identityForToken(accessToken).userId;
|
|
1054
|
+
return userId ? `: пользователь ${userId}` : "";
|
|
1055
|
+
}
|
|
1067
1056
|
};
|
|
1068
1057
|
//#endregion
|
|
1069
1058
|
//#region src/session/qr-stream.ts
|
|
@@ -1075,7 +1064,7 @@ function readQrLoginStreamEvent(data) {
|
|
|
1075
1064
|
} catch {
|
|
1076
1065
|
return;
|
|
1077
1066
|
}
|
|
1078
|
-
if (!
|
|
1067
|
+
if (!require_validate.isRecord(value)) return void 0;
|
|
1079
1068
|
const event = value;
|
|
1080
1069
|
if (typeof event.status !== "string" || !QR_STREAM_STATUSES.has(event.status)) return;
|
|
1081
1070
|
return {
|
|
@@ -1121,7 +1110,7 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
|
|
|
1121
1110
|
const path = AUTH_PATHS.qrStream;
|
|
1122
1111
|
const method = "POST";
|
|
1123
1112
|
const url = require_redact.joinUrl(connection.baseUrl, path);
|
|
1124
|
-
const abort = require_url.createRequestAbortScope(signal, connection.signal,
|
|
1113
|
+
const abort = require_url.createRequestAbortScope(signal, connection.signal, connection.clock);
|
|
1125
1114
|
try {
|
|
1126
1115
|
const headers = await connection.baseHeaders(url);
|
|
1127
1116
|
headers.delete("Authorization");
|
|
@@ -1140,13 +1129,12 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
|
|
|
1140
1129
|
signal: abort.signal
|
|
1141
1130
|
});
|
|
1142
1131
|
} catch (error) {
|
|
1143
|
-
const failure = new
|
|
1132
|
+
const failure = new require_validate.ItdNetworkError(`Не удалось открыть QR-поток: ${String(error)}`, {
|
|
1144
1133
|
method,
|
|
1145
1134
|
path,
|
|
1146
1135
|
cause: error
|
|
1147
1136
|
});
|
|
1148
1137
|
throw require_url.requestAbortError(abort, {
|
|
1149
|
-
timeout: 0,
|
|
1150
1138
|
method,
|
|
1151
1139
|
path
|
|
1152
1140
|
}, failure);
|
|
@@ -1169,14 +1157,13 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
|
|
|
1169
1157
|
now: connection.clock.now()
|
|
1170
1158
|
});
|
|
1171
1159
|
}
|
|
1172
|
-
if (!response.body) throw new
|
|
1160
|
+
if (!response.body) throw new require_validate.ItdNetworkError("Сервер не вернул тело QR-потока", {
|
|
1173
1161
|
method,
|
|
1174
1162
|
path
|
|
1175
1163
|
});
|
|
1176
1164
|
await consumeQrLoginStream(response.body, onEvent, abort.signal);
|
|
1177
1165
|
} catch (error) {
|
|
1178
1166
|
throw require_url.requestAbortError(abort, {
|
|
1179
|
-
timeout: 0,
|
|
1180
1167
|
method,
|
|
1181
1168
|
path
|
|
1182
1169
|
}, error);
|
|
@@ -1228,7 +1215,7 @@ var AuthResource = class extends require_render.BaseResource {
|
|
|
1228
1215
|
flow.expiresAt = flow.expiresAt === void 0 ? expiresAt : Math.min(flow.expiresAt, expiresAt);
|
|
1229
1216
|
}
|
|
1230
1217
|
#forgetTerminalQrError(qrId, error) {
|
|
1231
|
-
if (
|
|
1218
|
+
if (require_validate.isItdApiError(error) && error.hasCode("QR_EXPIRED", "QR_ALREADY_USED", "QR_TOKEN_MISMATCH")) this.#qrFlows.delete(qrId);
|
|
1232
1219
|
}
|
|
1233
1220
|
/**
|
|
1234
1221
|
* Проверяет состояние авторизации и возвращает текущего пользователя.
|
|
@@ -1246,13 +1233,13 @@ var AuthResource = class extends require_render.BaseResource {
|
|
|
1246
1233
|
*
|
|
1247
1234
|
* Сервер может переключить провайдера или переименовать поле без выпуска новой версии SDK.
|
|
1248
1235
|
* Автоматическому входу этот вызов не нужен — клиент делает его сам.
|
|
1236
|
+
*
|
|
1237
|
+
* @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile.
|
|
1249
1238
|
*/
|
|
1250
|
-
captchaProvider(
|
|
1251
|
-
return
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
skipAuthRefresh: true,
|
|
1255
|
-
...options
|
|
1239
|
+
captchaProvider(_options = {}) {
|
|
1240
|
+
return Promise.resolve({
|
|
1241
|
+
provider: require_url.CaptchaType.Cloudflare,
|
|
1242
|
+
field: CAPTCHA_FIELDS[require_url.CaptchaType.Cloudflare]
|
|
1256
1243
|
});
|
|
1257
1244
|
}
|
|
1258
1245
|
/**
|
|
@@ -1261,14 +1248,14 @@ var AuthResource = class extends require_render.BaseResource {
|
|
|
1261
1248
|
* То же, что {@link captchaProvider}, плюс `url` — готовая страница на домене итд.com,
|
|
1262
1249
|
* где ключ виджета действителен. Пригодится встроенному браузеру: открыть её и забрать
|
|
1263
1250
|
* токен, ничего не собирая самому.
|
|
1251
|
+
*
|
|
1252
|
+
* @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile на домене итд.com.
|
|
1264
1253
|
*/
|
|
1265
|
-
captchaPage(options = {}) {
|
|
1266
|
-
return
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
...options
|
|
1271
|
-
});
|
|
1254
|
+
async captchaPage(options = {}) {
|
|
1255
|
+
return {
|
|
1256
|
+
...await this.captchaProvider(options),
|
|
1257
|
+
url: require_url.DEFAULT_BASE_URL
|
|
1258
|
+
};
|
|
1272
1259
|
}
|
|
1273
1260
|
/** Создаёт короткоживущую сессию QR-входа. */
|
|
1274
1261
|
async startQrLogin(options = {}) {
|
|
@@ -1334,7 +1321,7 @@ var AuthResource = class extends require_render.BaseResource {
|
|
|
1334
1321
|
* {@link claimQrLogin}, чтобы получить и сохранить access token.
|
|
1335
1322
|
*/
|
|
1336
1323
|
async streamQrLogin(input, onEvent, options = {}) {
|
|
1337
|
-
if (typeof onEvent !== "function") throw new
|
|
1324
|
+
if (typeof onEvent !== "function") throw new require_validate.ItdConfigError("onEvent QR-потока должен быть функцией");
|
|
1338
1325
|
const flow = this.#qrFlow(input.qrId);
|
|
1339
1326
|
try {
|
|
1340
1327
|
await openQrLoginStream(this.#connection, flow.cookies, input, async (event) => {
|
|
@@ -1491,7 +1478,7 @@ var AuthResource = class extends require_render.BaseResource {
|
|
|
1491
1478
|
const { getOtp, ...credentials } = input;
|
|
1492
1479
|
const result = await this.signIn(credentials, options);
|
|
1493
1480
|
if (result.status === SignInStatus.Authenticated) return result.accessToken;
|
|
1494
|
-
if (!result.flowToken) throw new
|
|
1481
|
+
if (!result.flowToken) throw new require_validate.ItdConfigError("Сервер запросил код подтверждения, но не вернул flowToken — продолжить вход невозможно");
|
|
1495
1482
|
const otp = await getOtp();
|
|
1496
1483
|
return this.verifyOtp({
|
|
1497
1484
|
email: credentials.email,
|
|
@@ -1660,7 +1647,7 @@ const CLIENT_PLUGIN_REGISTRIES = /* @__PURE__ */ new WeakMap();
|
|
|
1660
1647
|
const DISPOSED_CLIENTS = /* @__PURE__ */ new WeakSet();
|
|
1661
1648
|
function assertClientActive(client, action) {
|
|
1662
1649
|
if (!DISPOSED_CLIENTS.has(client)) return;
|
|
1663
|
-
throw new
|
|
1650
|
+
throw new require_validate.ItdStateError(`ItdClient уже окончательно освобождён через dispose(); нельзя ${action}. Создайте новый клиент`);
|
|
1664
1651
|
}
|
|
1665
1652
|
/** Проверяет возможность подключить плагин к клиенту без вызова `install()`. @internal */
|
|
1666
1653
|
function assertClientCanUsePlugin(client, plugin) {
|
|
@@ -1904,9 +1891,9 @@ var ItdClient = class ItdClient {
|
|
|
1904
1891
|
*/
|
|
1905
1892
|
withFeature(key, feature) {
|
|
1906
1893
|
assertClientActive(this, "установить feature");
|
|
1907
|
-
if (typeof key !== "string" || key.trim() === "" || key !== key.trim()) throw new
|
|
1908
|
-
if (key === "then" || key in this) throw new
|
|
1909
|
-
if (!Object.isExtensible(this)) throw new
|
|
1894
|
+
if (typeof key !== "string" || key.trim() === "" || key !== key.trim()) throw new require_validate.ItdConfigError("Свойство feature должно иметь непустое имя без краевых пробелов");
|
|
1895
|
+
if (key === "then" || key in this) throw new require_validate.ItdConfigError(`Свойство клиента «${key}» уже занято или зарезервировано`);
|
|
1896
|
+
if (!Object.isExtensible(this)) throw new require_validate.ItdConfigError("Нельзя опубликовать feature на нерасширяемом клиенте");
|
|
1910
1897
|
const api = this.install(feature);
|
|
1911
1898
|
Object.defineProperty(this, key, {
|
|
1912
1899
|
value: api,
|
|
@@ -2172,20 +2159,27 @@ function createClient(options = {}) {
|
|
|
2172
2159
|
}
|
|
2173
2160
|
//#endregion
|
|
2174
2161
|
//#region src/accounts.ts
|
|
2162
|
+
/** Как аккаунты делят между собой очередь запросов. */
|
|
2163
|
+
const RateLimitScope = Object.freeze({
|
|
2164
|
+
/** У каждого аккаунта своя очередь. */
|
|
2165
|
+
Account: "account",
|
|
2166
|
+
/** Одна очередь на всех — умолчание. */
|
|
2167
|
+
Shared: "shared"
|
|
2168
|
+
});
|
|
2175
2169
|
/** Проверяет имя до создания клиента или частичного восстановления контейнера. */
|
|
2176
2170
|
function validateAccountName(name) {
|
|
2177
|
-
if (typeof name !== "string" || name.trim() === "") throw new
|
|
2171
|
+
if (typeof name !== "string" || name.trim() === "") throw new require_validate.ItdConfigError("имя аккаунта должно быть непустой строкой");
|
|
2178
2172
|
}
|
|
2179
2173
|
/** Проверяет фабрики до создания первого аккаунта. */
|
|
2180
2174
|
function resolveAccountFeatures(features) {
|
|
2181
2175
|
if (features === void 0) return [];
|
|
2182
|
-
if (!Array.isArray(features)) throw new
|
|
2176
|
+
if (!Array.isArray(features)) throw new require_validate.ItdConfigError("features должен быть массивом фабрик подключаемых модулей");
|
|
2183
2177
|
const keys = /* @__PURE__ */ new Set();
|
|
2184
2178
|
return features.map((feature, index) => {
|
|
2185
|
-
if (typeof feature !== "object" || feature === null || typeof feature.create !== "function") throw new
|
|
2179
|
+
if (typeof feature !== "object" || feature === null || typeof feature.create !== "function") throw new require_validate.ItdConfigError(`features[${index}] должен предоставлять create()`);
|
|
2186
2180
|
if (feature.key !== void 0) {
|
|
2187
|
-
if (typeof feature.key !== "string" || feature.key.trim() === "" || feature.key !== feature.key.trim()) throw new
|
|
2188
|
-
if (keys.has(feature.key)) throw new
|
|
2181
|
+
if (typeof feature.key !== "string" || feature.key.trim() === "" || feature.key !== feature.key.trim()) throw new require_validate.ItdConfigError(`features[${index}].key должен быть непустой строкой без пробелов`);
|
|
2182
|
+
if (keys.has(feature.key)) throw new require_validate.ItdConfigError(`Свойство подключаемого модуля «${feature.key}» объявлено повторно`);
|
|
2189
2183
|
keys.add(feature.key);
|
|
2190
2184
|
}
|
|
2191
2185
|
const create = feature.create.bind(feature);
|
|
@@ -2198,7 +2192,7 @@ function resolveAccountFeatures(features) {
|
|
|
2198
2192
|
const DISPOSED_ACCOUNTS = /* @__PURE__ */ new WeakSet();
|
|
2199
2193
|
function assertAccountsActive(accounts, action) {
|
|
2200
2194
|
if (!DISPOSED_ACCOUNTS.has(accounts)) return;
|
|
2201
|
-
throw new
|
|
2195
|
+
throw new require_validate.ItdStateError(`ItdAccounts уже окончательно освобождён через dispose(); нельзя ${action}. Создайте новый контейнер`);
|
|
2202
2196
|
}
|
|
2203
2197
|
/**
|
|
2204
2198
|
* Несколько аккаунтов итд.com в одном месте.
|
|
@@ -2261,15 +2255,16 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2261
2255
|
#disposePromise;
|
|
2262
2256
|
constructor(options = {}) {
|
|
2263
2257
|
const { storage, plugins, features, rateLimitScope, ...base } = options;
|
|
2264
|
-
|
|
2258
|
+
const scopes = Object.values(RateLimitScope);
|
|
2259
|
+
if (rateLimitScope !== void 0 && !scopes.includes(rateLimitScope)) throw new require_validate.ItdConfigError(`rateLimitScope должен быть одним из ${scopes.join(", ")}`);
|
|
2265
2260
|
this.#base = base;
|
|
2266
2261
|
this.#storage = storage ?? new require_multi_storage.MemoryMultiTokenStorage();
|
|
2267
2262
|
this.#plugins = require_url.orderPluginDefinitions(plugins ?? []);
|
|
2268
2263
|
this.#features = resolveAccountFeatures(features);
|
|
2269
|
-
this.#rateLimitScope = rateLimitScope ??
|
|
2270
|
-
const rateLimit = this.#rateLimitScope ===
|
|
2264
|
+
this.#rateLimitScope = rateLimitScope ?? RateLimitScope.Shared;
|
|
2265
|
+
const rateLimit = this.#rateLimitScope === RateLimitScope.Shared ? require_url.resolveRateLimit(base.rateLimit, require_url.ITD_CATALOG) : void 0;
|
|
2271
2266
|
this.#queues = rateLimit ? new require_url.RequestQueuePool(rateLimit, base.clock ?? require_url.systemClock) : void 0;
|
|
2272
|
-
const logger =
|
|
2267
|
+
const logger = require_redact.resolveLogger(base.logger);
|
|
2273
2268
|
this.#logger = logger;
|
|
2274
2269
|
this.#emitter = new require_events.Emitter((error) => require_events.reportListenerError(logger, "аккаунтов", error));
|
|
2275
2270
|
}
|
|
@@ -2310,9 +2305,9 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2310
2305
|
addAccount(name, options = {}) {
|
|
2311
2306
|
assertAccountsActive(this, "добавить аккаунт");
|
|
2312
2307
|
validateAccountName(name);
|
|
2313
|
-
if (this.#clients.has(name)) throw new
|
|
2314
|
-
if (this.#removing.has(name)) throw new
|
|
2315
|
-
if (this.#rateLimitScope ===
|
|
2308
|
+
if (this.#clients.has(name)) throw new require_validate.ItdConfigError(`аккаунт «${name}» уже добавлен. Возьмите его через accounts.account('${name}')`);
|
|
2309
|
+
if (this.#removing.has(name)) throw new require_validate.ItdConfigError(`аккаунт «${name}» ещё удаляется. Дождитесь завершения removeAccount() перед повторным добавлением`);
|
|
2310
|
+
if (this.#rateLimitScope === RateLimitScope.Shared && options.rateLimit !== void 0 && options.rateLimit !== false) throw new require_validate.ItdConfigError("при rateLimitScope: 'shared' настройки rateLimit задаются контейнеру; аккаунту можно передать только rateLimit: false");
|
|
2316
2311
|
const storageControl = require_multi_storage.controlledTokenStorage(this.#storage, name);
|
|
2317
2312
|
let client;
|
|
2318
2313
|
try {
|
|
@@ -2351,7 +2346,7 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2351
2346
|
const client = this.#clients.get(name);
|
|
2352
2347
|
if (!client) {
|
|
2353
2348
|
const known = this.names();
|
|
2354
|
-
throw new
|
|
2349
|
+
throw new require_validate.ItdConfigError(`аккаунт «${name}» не заведён. ` + (known.length > 0 ? `Известны: ${known.join(", ")}` : "Ни одного аккаунта нет — добавьте его через addAccount() или restore()"));
|
|
2355
2350
|
}
|
|
2356
2351
|
return client;
|
|
2357
2352
|
}
|
|
@@ -2438,7 +2433,7 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2438
2433
|
*/
|
|
2439
2434
|
use(plugin) {
|
|
2440
2435
|
assertAccountsActive(this, "подключить плагин");
|
|
2441
|
-
if (this.#removingPlugins.has(plugin?.name)) throw new
|
|
2436
|
+
if (this.#removingPlugins.has(plugin?.name)) throw new require_validate.ItdConfigError(`плагин «${plugin.name}» ещё отключается; дождитесь завершения accounts.unuse()`);
|
|
2442
2437
|
const ordered = require_url.orderPluginDefinitions([...this.#plugins, plugin]);
|
|
2443
2438
|
const clients = [...this.#clients.values()];
|
|
2444
2439
|
for (const client of clients) assertClientCanUsePlugin(client, plugin);
|
|
@@ -2603,9 +2598,7 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2603
2598
|
}
|
|
2604
2599
|
/** Не теряет ошибку фонового освобождения ресурсов, которого синхронный API не ждёт. */
|
|
2605
2600
|
#reportCleanup(scope, error) {
|
|
2606
|
-
|
|
2607
|
-
if (this.#logger) this.#logger.error(message, error);
|
|
2608
|
-
else console.error(`[itd-api] ${message}`, error);
|
|
2601
|
+
(this.#logger ?? require_redact.fallbackLogger).error(`Не удалось освободить ресурсы после ${scope}`, error);
|
|
2609
2602
|
}
|
|
2610
2603
|
/** Ретранслирует события клиента наружу, добавляя к ним имя аккаунта. */
|
|
2611
2604
|
#forwardEvents(account, client) {
|
|
@@ -2656,34 +2649,37 @@ exports.FileTransferMode = require_options.FileTransferMode;
|
|
|
2656
2649
|
exports.IMAGE_MIME_TYPES = require_render.IMAGE_MIME_TYPES;
|
|
2657
2650
|
exports.IncidentKind = require_url.IncidentKind;
|
|
2658
2651
|
exports.InteractionType = require_url.InteractionType;
|
|
2659
|
-
exports.ItdAbortError =
|
|
2652
|
+
exports.ItdAbortError = require_validate.ItdAbortError;
|
|
2660
2653
|
exports.ItdAccounts = ItdAccounts;
|
|
2661
|
-
exports.ItdApiError =
|
|
2662
|
-
exports.ItdApiErrorKind =
|
|
2663
|
-
exports.ItdAuthError =
|
|
2654
|
+
exports.ItdApiError = require_validate.ItdApiError;
|
|
2655
|
+
exports.ItdApiErrorKind = require_validate.ItdApiErrorKind;
|
|
2656
|
+
exports.ItdAuthError = require_validate.ItdAuthError;
|
|
2664
2657
|
exports.ItdClient = ItdClient;
|
|
2665
|
-
exports.ItdConfigError =
|
|
2666
|
-
exports.ItdConflictError =
|
|
2667
|
-
exports.ItdError =
|
|
2658
|
+
exports.ItdConfigError = require_validate.ItdConfigError;
|
|
2659
|
+
exports.ItdConflictError = require_validate.ItdConflictError;
|
|
2660
|
+
exports.ItdError = require_validate.ItdError;
|
|
2668
2661
|
exports.ItdErrorCode = require_url.ItdErrorCode;
|
|
2669
|
-
exports.ItdErrorKind =
|
|
2670
|
-
exports.ItdFileError =
|
|
2671
|
-
exports.ItdFileErrorReason =
|
|
2672
|
-
exports.ItdForbiddenError =
|
|
2673
|
-
exports.ItdNetworkError =
|
|
2674
|
-
exports.ItdNotFoundError =
|
|
2675
|
-
exports.ItdPhoneVerificationError =
|
|
2676
|
-
exports.ItdRateLimitError =
|
|
2677
|
-
exports.ItdServerError =
|
|
2678
|
-
exports.ItdStateError =
|
|
2679
|
-
exports.ItdTimeoutError =
|
|
2680
|
-
exports.ItdValidationError =
|
|
2662
|
+
exports.ItdErrorKind = require_validate.ItdErrorKind;
|
|
2663
|
+
exports.ItdFileError = require_validate.ItdFileError;
|
|
2664
|
+
exports.ItdFileErrorReason = require_validate.ItdFileErrorReason;
|
|
2665
|
+
exports.ItdForbiddenError = require_validate.ItdForbiddenError;
|
|
2666
|
+
exports.ItdNetworkError = require_validate.ItdNetworkError;
|
|
2667
|
+
exports.ItdNotFoundError = require_validate.ItdNotFoundError;
|
|
2668
|
+
exports.ItdPhoneVerificationError = require_validate.ItdPhoneVerificationError;
|
|
2669
|
+
exports.ItdRateLimitError = require_validate.ItdRateLimitError;
|
|
2670
|
+
exports.ItdServerError = require_validate.ItdServerError;
|
|
2671
|
+
exports.ItdStateError = require_validate.ItdStateError;
|
|
2672
|
+
exports.ItdTimeoutError = require_validate.ItdTimeoutError;
|
|
2673
|
+
exports.ItdValidationError = require_validate.ItdValidationError;
|
|
2681
2674
|
exports.LIBRARY_VERSION = require_url.LIBRARY_VERSION;
|
|
2675
|
+
exports.LastSeenUnit = require_url.LastSeenUnit;
|
|
2682
2676
|
exports.LikesVisibility = require_url.LikesVisibility;
|
|
2677
|
+
exports.LogLevel = require_redact.LogLevel;
|
|
2683
2678
|
exports.MemoryKeyValueStore = require_key_value_store.MemoryKeyValueStore;
|
|
2684
2679
|
exports.MemoryMultiTokenStorage = require_multi_storage.MemoryMultiTokenStorage;
|
|
2685
2680
|
exports.MemoryShopOrderAccessStorage = require_render.MemoryShopOrderAccessStorage;
|
|
2686
2681
|
exports.MemoryTokenStorage = require_storage.MemoryTokenStorage;
|
|
2682
|
+
exports.MessageAccess = require_url.MessageAccess;
|
|
2687
2683
|
exports.NotificationEvents = require_events.NotificationEvents;
|
|
2688
2684
|
exports.NotificationEventsClient = require_events.NotificationEventsClient;
|
|
2689
2685
|
exports.NotificationEventsTransport = require_events.NotificationEventsTransport;
|
|
@@ -2691,12 +2687,14 @@ exports.NotificationType = require_url.NotificationType;
|
|
|
2691
2687
|
exports.NotificationUpdateOrigin = require_events.NotificationUpdateOrigin;
|
|
2692
2688
|
exports.NotificationUpdateType = require_events.NotificationUpdateType;
|
|
2693
2689
|
exports.OPERATIONS = require_url.OPERATIONS;
|
|
2690
|
+
exports.OperationMethod = require_url.OperationMethod;
|
|
2694
2691
|
exports.PaginationMode = require_render.PaginationMode;
|
|
2695
2692
|
exports.Paginator = require_render.Paginator;
|
|
2696
2693
|
exports.QrLocationPrecision = require_url.QrLocationPrecision;
|
|
2697
2694
|
exports.QrLoginStatus = QrLoginStatus;
|
|
2698
2695
|
exports.QrLoginStreamStatus = QrLoginStreamStatus;
|
|
2699
2696
|
exports.RateLimitPacing = require_url.RateLimitPacing;
|
|
2697
|
+
exports.RateLimitScope = RateLimitScope;
|
|
2700
2698
|
exports.ReportReason = require_url.ReportReason;
|
|
2701
2699
|
exports.ReportTargetType = require_url.ReportTargetType;
|
|
2702
2700
|
exports.RetrySafety = require_url.RetrySafety;
|
|
@@ -2711,7 +2709,9 @@ exports.SignInStatus = SignInStatus;
|
|
|
2711
2709
|
exports.SpanRenderFormat = require_render.SpanRenderFormat;
|
|
2712
2710
|
exports.SpanType = require_url.SpanType;
|
|
2713
2711
|
exports.TURNSTILE_SITE_KEY = TURNSTILE_SITE_KEY;
|
|
2712
|
+
exports.TimeoutBudget = require_validate.TimeoutBudget;
|
|
2714
2713
|
exports.UnauthorizedStreamError = require_events.UnauthorizedStreamError;
|
|
2714
|
+
exports.UsernameUnavailableReason = require_url.UsernameUnavailableReason;
|
|
2715
2715
|
exports.VIDEO_MIME_TYPES = require_render.VIDEO_MIME_TYPES;
|
|
2716
2716
|
exports.ViewReason = require_url.ViewReason;
|
|
2717
2717
|
exports.ViewSource = require_url.ViewSource;
|
|
@@ -2735,18 +2735,18 @@ exports.fromUrl = require_render.fromUrl;
|
|
|
2735
2735
|
exports.isBuilder = require_render.isBuilder;
|
|
2736
2736
|
exports.isBuiltInOperationId = require_url.isBuiltInOperationId;
|
|
2737
2737
|
exports.isEnumerableKeyValueStore = require_key_value_store.isEnumerableKeyValueStore;
|
|
2738
|
-
exports.isItdApiError =
|
|
2739
|
-
exports.isItdAuthError =
|
|
2740
|
-
exports.isItdConflictError =
|
|
2741
|
-
exports.isItdError =
|
|
2742
|
-
exports.isItdFileError =
|
|
2743
|
-
exports.isItdForbiddenError =
|
|
2744
|
-
exports.isItdNotFoundError =
|
|
2745
|
-
exports.isItdPhoneVerificationError =
|
|
2746
|
-
exports.isItdRateLimitError =
|
|
2747
|
-
exports.isItdServerError =
|
|
2748
|
-
exports.isItdStateError =
|
|
2749
|
-
exports.isItdValidationError =
|
|
2738
|
+
exports.isItdApiError = require_validate.isItdApiError;
|
|
2739
|
+
exports.isItdAuthError = require_validate.isItdAuthError;
|
|
2740
|
+
exports.isItdConflictError = require_validate.isItdConflictError;
|
|
2741
|
+
exports.isItdError = require_validate.isItdError;
|
|
2742
|
+
exports.isItdFileError = require_validate.isItdFileError;
|
|
2743
|
+
exports.isItdForbiddenError = require_validate.isItdForbiddenError;
|
|
2744
|
+
exports.isItdNotFoundError = require_validate.isItdNotFoundError;
|
|
2745
|
+
exports.isItdPhoneVerificationError = require_validate.isItdPhoneVerificationError;
|
|
2746
|
+
exports.isItdRateLimitError = require_validate.isItdRateLimitError;
|
|
2747
|
+
exports.isItdServerError = require_validate.isItdServerError;
|
|
2748
|
+
exports.isItdStateError = require_validate.isItdStateError;
|
|
2749
|
+
exports.isItdValidationError = require_validate.isItdValidationError;
|
|
2750
2750
|
exports.isKnownNotificationType = require_url.isKnownNotificationType;
|
|
2751
2751
|
exports.isMyProfile = require_render.isMyProfile;
|
|
2752
2752
|
exports.mapPage = require_render.mapPage;
|