itd-api 0.12.0 → 0.13.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.
Files changed (90) hide show
  1. package/dist/events/index.cjs +4 -4
  2. package/dist/events/index.d.cts +7 -2
  3. package/dist/events/index.d.ts +7 -2
  4. package/dist/events/index.js +4 -4
  5. package/dist/index.cjs +672 -90
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +497 -46
  8. package/dist/index.d.ts +497 -46
  9. package/dist/index.js +664 -91
  10. package/dist/index.js.map +1 -1
  11. package/dist/node/index.cjs +6 -7
  12. package/dist/node/index.cjs.map +1 -1
  13. package/dist/node/index.d.cts +24 -7
  14. package/dist/node/index.d.ts +24 -7
  15. package/dist/node/index.js +6 -7
  16. package/dist/node/index.js.map +1 -1
  17. package/dist/rest/index.cjs +19 -7
  18. package/dist/rest/index.cjs.map +1 -1
  19. package/dist/rest/index.d.cts +28 -7
  20. package/dist/rest/index.d.ts +28 -7
  21. package/dist/rest/index.js +17 -8
  22. package/dist/rest/index.js.map +1 -1
  23. package/dist/shared/{contracts-BoT7msmq.d.ts → contracts-DEbkC0cB.d.cts} +1 -4
  24. package/dist/shared/{contracts-BoT7msmq.d.cts → contracts-pxnDIsQP.d.ts} +1 -4
  25. package/dist/shared/{events-9L0Fonak.d.cts → events-B6uqXOSs.d.cts} +42 -63
  26. package/dist/shared/{events-D1BfefBT.js → events-C_MgYlXR.js} +30 -40
  27. package/dist/shared/events-C_MgYlXR.js.map +1 -0
  28. package/dist/shared/{events-C2DJZyI0.cjs → events-DV1i1t6J.cjs} +30 -40
  29. package/dist/shared/events-DV1i1t6J.cjs.map +1 -0
  30. package/dist/shared/{events-BpLAIiMj.d.ts → events-D_aMNrPd.d.ts} +2 -23
  31. package/dist/shared/{key-value-store-DYSPsqwq.cjs → key-value-store-6DHm_iNW.cjs} +3 -4
  32. package/dist/shared/{key-value-store-DYSPsqwq.cjs.map → key-value-store-6DHm_iNW.cjs.map} +1 -1
  33. package/dist/shared/{key-value-store-COZaNHZS.d.ts → key-value-store-BGoSgLze.d.cts} +1 -4
  34. package/dist/shared/{key-value-store-w1Dn5Pjb.js → key-value-store-PnZE_DFC.js} +3 -4
  35. package/dist/shared/{key-value-store-w1Dn5Pjb.js.map → key-value-store-PnZE_DFC.js.map} +1 -1
  36. package/dist/shared/{key-value-store-COZaNHZS.d.cts → key-value-store-WUQBeTAr.d.ts} +1 -4
  37. package/dist/shared/{multi-storage-DiBSx64p.js → multi-storage-DM0skcSO.js} +6 -7
  38. package/dist/shared/{multi-storage-DiBSx64p.js.map → multi-storage-DM0skcSO.js.map} +1 -1
  39. package/dist/shared/{multi-storage-LkljOSzA.d.ts → multi-storage-DQiERirK.d.ts} +3 -6
  40. package/dist/shared/{multi-storage-7Y3KCseI.cjs → multi-storage-DnonVBfO.cjs} +6 -7
  41. package/dist/shared/multi-storage-DnonVBfO.cjs.map +1 -0
  42. package/dist/shared/{multi-storage-BEL7tcKn.d.cts → multi-storage-OGWNMK3x.d.cts} +3 -6
  43. package/dist/shared/{options-D5ttspWk.cjs → options-SvAWOaqT.cjs} +8 -12
  44. package/dist/shared/{options-D5ttspWk.cjs.map → options-SvAWOaqT.cjs.map} +1 -1
  45. package/dist/shared/{options-DLlaETn_.js → options-bS27r_gR.js} +8 -12
  46. package/dist/shared/{options-DLlaETn_.js.map → options-bS27r_gR.js.map} +1 -1
  47. package/dist/shared/{redact-DSfdmeY7.js → redact-C4b2NzdB.js} +16 -16
  48. package/dist/shared/redact-C4b2NzdB.js.map +1 -0
  49. package/dist/shared/{redact-BbhtA9o-.cjs → redact-DDGkv8KF.cjs} +16 -16
  50. package/dist/shared/redact-DDGkv8KF.cjs.map +1 -0
  51. package/dist/shared/{render-CrGXcj6L.cjs → render-0-JJPOwb.cjs} +222 -111
  52. package/dist/shared/render-0-JJPOwb.cjs.map +1 -0
  53. package/dist/shared/{render-D3vSEbLL.js → render-CF49aBO8.js} +199 -112
  54. package/dist/shared/render-CF49aBO8.js.map +1 -0
  55. package/dist/shared/{render-Dzw3KeN5.d.cts → render-CYVOc_IW.d.cts} +191 -308
  56. package/dist/shared/{render-UsQ1hb2U.d.ts → render-eOxYgdoA.d.ts} +191 -159
  57. package/dist/shared/{storage-86wiHeXD.js → storage-B6OkSi38.js} +4 -5
  58. package/dist/shared/{storage-86wiHeXD.js.map → storage-B6OkSi38.js.map} +1 -1
  59. package/dist/shared/{storage-CTRGT5wF.d.ts → storage-C_ZujAZt.d.ts} +2 -5
  60. package/dist/shared/{storage-CIjejZDt.cjs → storage-CezF2Mvz.cjs} +4 -5
  61. package/dist/shared/{storage-CIjejZDt.cjs.map → storage-CezF2Mvz.cjs.map} +1 -1
  62. package/dist/shared/{storage-BQrtKon9.d.cts → storage-FtS4NIC7.d.cts} +2 -5
  63. package/dist/shared/{url-Dg1u29cu.js → url-CPKhcxf1.js} +250 -91
  64. package/dist/shared/url-CPKhcxf1.js.map +1 -0
  65. package/dist/shared/{url-C9YADYNg.d.cts → url-DCqxoxGX.d.cts} +1909 -1634
  66. package/dist/shared/{url-C9YADYNg.d.ts → url-DL5Mip4L.d.ts} +230 -104
  67. package/dist/shared/{url-B21Bdmw_.cjs → url-DOfjru6L.cjs} +250 -91
  68. package/dist/shared/url-DOfjru6L.cjs.map +1 -0
  69. package/dist/shared/{validate-D7_kq3g5.js → validate-B5l_vLKD.js} +5 -7
  70. package/dist/shared/validate-B5l_vLKD.js.map +1 -0
  71. package/dist/shared/{validate-CFx2dISs.cjs → validate-CfxCK1BC.cjs} +5 -7
  72. package/dist/shared/validate-CfxCK1BC.cjs.map +1 -0
  73. package/dist/web/index.cjs +4 -5
  74. package/dist/web/index.cjs.map +1 -1
  75. package/dist/web/index.d.cts +22 -5
  76. package/dist/web/index.d.ts +22 -5
  77. package/dist/web/index.js +4 -5
  78. package/dist/web/index.js.map +1 -1
  79. package/package.json +6 -6
  80. package/dist/shared/events-C2DJZyI0.cjs.map +0 -1
  81. package/dist/shared/events-D1BfefBT.js.map +0 -1
  82. package/dist/shared/multi-storage-7Y3KCseI.cjs.map +0 -1
  83. package/dist/shared/redact-BbhtA9o-.cjs.map +0 -1
  84. package/dist/shared/redact-DSfdmeY7.js.map +0 -1
  85. package/dist/shared/render-CrGXcj6L.cjs.map +0 -1
  86. package/dist/shared/render-D3vSEbLL.js.map +0 -1
  87. package/dist/shared/url-B21Bdmw_.cjs.map +0 -1
  88. package/dist/shared/url-Dg1u29cu.js.map +0 -1
  89. package/dist/shared/validate-CFx2dISs.cjs.map +0 -1
  90. package/dist/shared/validate-D7_kq3g5.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,14 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
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
- //#region src/notifications-api.ts
2
+ const require_url = require("./shared/url-DOfjru6L.cjs");
3
+ const require_validate = require("./shared/validate-CfxCK1BC.cjs");
4
+ const require_render = require("./shared/render-0-JJPOwb.cjs");
5
+ const require_events = require("./shared/events-DV1i1t6J.cjs");
6
+ const require_redact = require("./shared/redact-DDGkv8KF.cjs");
7
+ const require_storage = require("./shared/storage-CezF2Mvz.cjs");
8
+ const require_multi_storage = require("./shared/multi-storage-DnonVBfO.cjs");
9
+ const require_options = require("./shared/options-SvAWOaqT.cjs");
10
+ const require_key_value_store = require("./shared/key-value-store-6DHm_iNW.cjs");
11
+ // src/notifications-api.ts
12
12
  var ClientNotifications = class extends require_render.NotificationsResource {
13
13
  #createEvents;
14
14
  #events;
@@ -25,8 +25,384 @@ var ClientNotifications = class extends require_render.NotificationsResource {
25
25
  function createNotificationsApi(http, createEvents) {
26
26
  return new ClientNotifications(http, createEvents);
27
27
  }
28
- //#endregion
29
- //#region src/operations/auth.ts
28
+ // src/operations/account.ts
29
+ const ACCOUNT_GET_INFO = require_url.passthroughOperation("account.getInfo");
30
+ const ACCOUNT_PASSWORD_SET = require_url.voidOperation("account.password.set");
31
+ const ACCOUNT_PASSWORD_CHANGE = require_url.voidOperation("account.password.change");
32
+ // src/operations/account/changes.ts
33
+ const ACCOUNT_CHANGES_REQUEST_PROOF = require_url.passthroughOperation("account.changes.requestProof");
34
+ const ACCOUNT_CHANGES_CONFIRM = require_url.voidOperation("account.changes.confirm");
35
+ const ACCOUNT_CHANGES_WAIT = require_url.passthroughOperation("account.changes.wait");
36
+ const ACCOUNT_CHANGES_PENDING = require_url.defineBuiltInOperation("account.changes.pending", (body) => require_url.pickArray(body, "requests"));
37
+ const ACCOUNT_CHANGES_CANCEL_PENDING = require_url.voidOperation("account.changes.cancelPending");
38
+ // src/resources/account/request.ts
39
+ /** Выполняет запрос настройки способов входа с текущей авторизацией. */
40
+ function requestAccount(http, operation, path, body, options) {
41
+ const reverse = path.startsWith("/phone/reverse/");
42
+ return http.execute(operation, {
43
+ ...options,
44
+ path: `/api/v1/auth${path}`,
45
+ body,
46
+ headers: {
47
+ ...options.headers,
48
+ ...operation.method === "POST" ? { "X-ITD-Phone-Reverse": "1" } : {},
49
+ ...reverse ? { "X-ITD-Reverse-Attempts": "1" } : {}
50
+ }
51
+ });
52
+ }
53
+ // src/resources/account/changes.ts
54
+ /** Завершение смены номера или почты и управление отложенными заявками. */
55
+ var AccountChangesResource = class extends require_render.BaseResource {
56
+ /**
57
+ * Запрашивает код на привязанный номер или почту.
58
+ *
59
+ * Возьмите `changeToken` и способ доставки из результата `verifyChange()` или
60
+ * `phone.reverseChangeComplete()`. Полученный код передайте в {@link confirm}.
61
+ */
62
+ requestProof(input, options = {}) {
63
+ return requestAccount(this.http, ACCOUNT_CHANGES_REQUEST_PROOF, "/change/proof", input, options);
64
+ }
65
+ /**
66
+ * Завершает смену номера или почты.
67
+ *
68
+ * Передайте `changeToken` и код из {@link requestProof} либо облачный
69
+ * пароль, если сервер предложил такой способ подтверждения.
70
+ */
71
+ confirm(input, options = {}) {
72
+ return requestAccount(this.http, ACCOUNT_CHANGES_CONFIRM, "/change/confirm", input, options);
73
+ }
74
+ /**
75
+ * Создаёт отложенную заявку на смену номера или почты.
76
+ *
77
+ * @returns время применения заявки. До этого её можно отменить через {@link cancelPending}
78
+ */
79
+ wait(changeToken, options = {}) {
80
+ return requestAccount(this.http, ACCOUNT_CHANGES_WAIT, "/change/wait", { changeToken }, options);
81
+ }
82
+ /** Возвращает отложенные заявки текущего аккаунта. */
83
+ pending(options = {}) {
84
+ return requestAccount(this.http, ACCOUNT_CHANGES_PENDING, "/change/pending", void 0, options);
85
+ }
86
+ /**
87
+ * Отменяет отложенную смену.
88
+ *
89
+ * @param requestId идентификатор заявки из {@link pending}
90
+ */
91
+ cancelPending(requestId, options = {}) {
92
+ return requestAccount(this.http, ACCOUNT_CHANGES_CANCEL_PENDING, `/change/pending/${require_redact.encodePathSegment(requestId, "requestId")}`, void 0, options);
93
+ }
94
+ };
95
+ // src/operations/account/email.ts
96
+ /** Извлекает токен для подтверждения адреса почты. */
97
+ function readEmailFlow(body) {
98
+ const flowToken = require_url.pickString(body, "flowToken");
99
+ if (!flowToken) throw new require_validate.ItdConfigError("Сервер не вернул flowToken для подтверждения почты");
100
+ return flowToken;
101
+ }
102
+ const ACCOUNT_EMAIL_ATTACH = require_url.defineBuiltInOperation("account.email.attach", readEmailFlow);
103
+ const ACCOUNT_EMAIL_START_CHANGE = require_url.defineBuiltInOperation("account.email.startChange", readEmailFlow);
104
+ const ACCOUNT_EMAIL_RESEND_OTP = require_url.voidOperation("account.email.resendOtp");
105
+ // src/models/phone-auth.ts
106
+ /** Назначение контекста согласия телефонного входа. @internal */
107
+ const PHONE_CONSENT_FLOW = "phone_entry";
108
+ /** Назначение ответа общего endpoint подтверждения кода. */
109
+ const AuthVerificationMode = Object.freeze({
110
+ SignIn: "signin",
111
+ Change: "change"
112
+ });
113
+ /** Серверные каналы доставки кода. */
114
+ const PhoneDeliveryChannel = Object.freeze({
115
+ MissedCall: "missed_call",
116
+ VoiceCall: "voice_call",
117
+ Sms: "sms",
118
+ Push: "push"
119
+ });
120
+ /** Подтверждение входящим кодом либо исходящим звонком пользователя. */
121
+ const PhoneVerificationMethod = Object.freeze({
122
+ Direct: "direct",
123
+ Reverse: "reverse"
124
+ });
125
+ /** Продолжение телефонного входа, ещё не выдавшее access token. */
126
+ const PhoneLoginStep = Object.freeze({ Password: "password" });
127
+ /** Состояния подтверждения номера исходящим звонком. */
128
+ const PhoneReverseState = Object.freeze({
129
+ NotStarted: "not_started",
130
+ Preparing: "preparing",
131
+ Waiting: "waiting",
132
+ Confirmed: "confirmed",
133
+ Expired: "expired",
134
+ Failed: "failed"
135
+ });
136
+ // src/operations/account/verification.ts
137
+ /** Отделяет ответ смены контакта от результата входа на общем маршруте подтверждения. */
138
+ function readContactChange(body) {
139
+ const changeToken = require_url.pickString(body, "changeToken");
140
+ if (!require_validate.isRecord(body) || body.mode !== void 0 && body.mode !== AuthVerificationMode.Change || !changeToken) throw new require_validate.ItdConfigError("Сервер не вернул подтверждение смены контакта");
141
+ return {
142
+ changeToken,
143
+ proofs: require_url.pickArray(body, "proofs"),
144
+ ...typeof body.waitDays === "number" ? { waitDays: body.waitDays } : {}
145
+ };
146
+ }
147
+ const ACCOUNT_VERIFY_ATTACH = require_url.passthroughOperation("account.verifyAttach");
148
+ const ACCOUNT_VERIFY_CHANGE = require_url.defineBuiltInOperation("account.verifyChange", (body) => {
149
+ if (!require_validate.isRecord(body) || body.mode !== AuthVerificationMode.Change) throw new require_validate.ItdConfigError("Сервер не вернул режим смены контакта");
150
+ return readContactChange(body);
151
+ });
152
+ const ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE = require_url.passthroughOperation("account.phone.reverseAttachComplete");
153
+ const ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE = require_url.defineBuiltInOperation("account.phone.reverseChangeComplete", readContactChange);
154
+ // src/resources/account/email.ts
155
+ /** Привязка и смена почты текущего аккаунта. */
156
+ var AccountEmailResource = class extends require_render.BaseResource {
157
+ /**
158
+ * Отправляет код на почту для привязки.
159
+ *
160
+ * @returns значение `flowToken` для {@link verifyAttach} или {@link resendOtp}
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * const flowToken = await itd.account.email.attach(email);
165
+ * await itd.account.email.verifyAttach({ email, flowToken, otp: await getOtp() });
166
+ * ```
167
+ */
168
+ attach(email, options = {}) {
169
+ return requestAccount(this.http, ACCOUNT_EMAIL_ATTACH, "/email/attach", { email }, options);
170
+ }
171
+ /**
172
+ * Отправляет код на новый адрес почты.
173
+ *
174
+ * @returns значение `flowToken` для {@link verifyChange} или {@link resendOtp}
175
+ */
176
+ startChange(email, options = {}) {
177
+ return requestAccount(this.http, ACCOUNT_EMAIL_START_CHANGE, "/email/change", { email }, options);
178
+ }
179
+ /**
180
+ * Завершает привязку почты кодом.
181
+ *
182
+ * Передайте тот же адрес и `flowToken` из {@link attach}.
183
+ */
184
+ verifyAttach(input, options = {}) {
185
+ return requestAccount(this.http, ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
186
+ }
187
+ /**
188
+ * Подтверждает код новой почты, запрошенный через {@link startChange}.
189
+ *
190
+ * @returns `changeToken` и способы завершить смену через `itd.account.changes`
191
+ */
192
+ verifyChange(input, options = {}) {
193
+ return requestAccount(this.http, ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
194
+ }
195
+ /** Повторно отправляет код на тот же адрес. Передайте `flowToken` из первого запроса. */
196
+ resendOtp(input, options = {}) {
197
+ return requestAccount(this.http, ACCOUNT_EMAIL_RESEND_OTP, "/resend-otp", input, options);
198
+ }
199
+ };
200
+ // src/resources/account/password.ts
201
+ /** Облачный пароль текущего аккаунта. */
202
+ var AccountPasswordResource = class extends require_render.BaseResource {
203
+ /**
204
+ * Создаёт облачный пароль для аккаунта без пароля.
205
+ *
206
+ * Наличие пароля можно проверить через `itd.account.getInfo()`.
207
+ */
208
+ set(password, options = {}) {
209
+ return requestAccount(this.http, ACCOUNT_PASSWORD_SET, "/set-password", { password }, options);
210
+ }
211
+ /**
212
+ * Меняет облачный пароль в действующей сессии.
213
+ *
214
+ * При неверном текущем пароле сервер возвращает `ACCOUNT_CURRENT_PASSWORD_INCORRECT`.
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * await itd.account.password.change({ currentPassword, newPassword });
219
+ * ```
220
+ */
221
+ change({ currentPassword, newPassword }, options = {}) {
222
+ return this.voidOperation(ACCOUNT_PASSWORD_CHANGE, {
223
+ path: "/api/v1/auth/change-password",
224
+ body: {
225
+ currentPassword,
226
+ newPassword
227
+ },
228
+ ...options
229
+ });
230
+ }
231
+ };
232
+ // src/operations/phone-flow.ts
233
+ /** Приводит вложенные и плоские параметры доставки к одному результату. */
234
+ function readPhoneDelivery(body) {
235
+ const response = body;
236
+ const next = response.next ?? response.nextChannel;
237
+ return {
238
+ channel: response.delivery?.type ?? response.channel,
239
+ codeLength: response.delivery?.codeLength ?? response.codeLength,
240
+ retryIn: response.retryIn,
241
+ ...response.reverseOnly === true ? { reverseOnly: true } : {},
242
+ nextChannel: next ?? null
243
+ };
244
+ }
245
+ /** Извлекает `flowToken` и параметры доставки после запуска проверки номера. */
246
+ function readPhoneStart(body) {
247
+ const flowToken = require_url.pickString(body, "flowToken");
248
+ if (!flowToken) throw new require_validate.ItdConfigError("Сервер не вернул flowToken для проверки номера");
249
+ return {
250
+ ...readPhoneDelivery(body),
251
+ flowToken
252
+ };
253
+ }
254
+ // src/operations/account/phone.ts
255
+ const ACCOUNT_PHONE_ATTACH = require_url.defineBuiltInOperation("account.phone.attach", readPhoneStart);
256
+ const ACCOUNT_PHONE_START_CHANGE = require_url.defineBuiltInOperation("account.phone.startChange", readPhoneStart);
257
+ const ACCOUNT_PHONE_RESEND_OTP = require_url.defineBuiltInOperation("account.phone.resendOtp", readPhoneDelivery);
258
+ const ACCOUNT_PHONE_SYNC = require_url.passthroughOperation("account.phone.sync");
259
+ const ACCOUNT_PHONE_REVERSE_OPTIONS = require_url.passthroughOperation("account.phone.reverseOptions");
260
+ const ACCOUNT_PHONE_REVERSE_START = require_url.passthroughOperation("account.phone.reverseStart");
261
+ const ACCOUNT_PHONE_REVERSE_STATUS = require_url.passthroughOperation("account.phone.reverseStatus");
262
+ // src/resources/account/phone.ts
263
+ /** Привязка и смена номера текущего аккаунта. */
264
+ var AccountPhoneResource = class extends require_render.BaseResource {
265
+ #auth;
266
+ constructor(http, auth) {
267
+ super(http);
268
+ this.#auth = auth;
269
+ }
270
+ /**
271
+ * Запрашивает подтверждение номера для привязки.
272
+ *
273
+ * Передайте номер в международном формате с `+`. Если токен капчи не передан
274
+ * в вызов, SDK использует настроенный источник капчи.
275
+ *
276
+ * @returns параметры доставки и `flowToken` для {@link verifyAttach}
277
+ *
278
+ * @example
279
+ * ```ts
280
+ * const { flowToken } = await itd.account.phone.attach({ phone });
281
+ * await itd.account.phone.verifyAttach({ phone, flowToken, otp: await getOtp() });
282
+ * ```
283
+ */
284
+ attach(input, options = {}) {
285
+ return this.#start(ACCOUNT_PHONE_ATTACH, "/phone/attach", input, options);
286
+ }
287
+ /**
288
+ * Запрашивает подтверждение нового номера для смены.
289
+ *
290
+ * Формат номера и источник капчи такие же, как у {@link attach}.
291
+ *
292
+ * @returns параметры доставки и `flowToken` для {@link verifyChange}
293
+ */
294
+ startChange(input, options = {}) {
295
+ return this.#start(ACCOUNT_PHONE_START_CHANGE, "/phone/change", input, options);
296
+ }
297
+ /**
298
+ * Завершает привязку номера кодом.
299
+ *
300
+ * Передайте номер и `flowToken` из {@link attach}.
301
+ */
302
+ verifyAttach(input, options = {}) {
303
+ return requestAccount(this.http, ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
304
+ }
305
+ /**
306
+ * Подтверждает код нового номера, запрошенный через {@link startChange}.
307
+ *
308
+ * @returns `changeToken` и способы завершить смену через `itd.account.changes`
309
+ */
310
+ verifyChange(input, options = {}) {
311
+ return requestAccount(this.http, ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
312
+ }
313
+ /**
314
+ * Повторно запрашивает код для того же номера. Передайте `flowToken` из первого запроса.
315
+ *
316
+ * @returns актуальные канал, длину кода и паузу до повтора в секундах
317
+ */
318
+ resendOtp(input, options = {}) {
319
+ return requestAccount(this.http, ACCOUNT_PHONE_RESEND_OTP, "/resend-otp", input, options);
320
+ }
321
+ /** Синхронизирует привязанный номер с профилем. */
322
+ sync(options = {}) {
323
+ return requestAccount(this.http, ACCOUNT_PHONE_SYNC, "/phone/sync", {}, options);
324
+ }
325
+ /** Возвращает доступность исходящего звонка для привязки или смены номера. */
326
+ reverseOptions(input, options = {}) {
327
+ return requestAccount(this.http, ACCOUNT_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
328
+ }
329
+ /**
330
+ * Подготавливает номер, на который должен позвонить пользователь.
331
+ *
332
+ * @returns состояние попытки, номер для звонка и срок действия в секундах
333
+ */
334
+ reverseStart(input, options = {}) {
335
+ return requestAccount(this.http, ACCOUNT_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
336
+ }
337
+ /**
338
+ * Читает состояние исходящего звонка.
339
+ *
340
+ * После подтверждения вызовите {@link reverseAttachComplete} при привязке
341
+ * или {@link reverseChangeComplete} при смене номера.
342
+ */
343
+ reverseStatus(input, options = {}) {
344
+ return requestAccount(this.http, ACCOUNT_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
345
+ }
346
+ /** Завершает привязку номера после исходящего звонка. */
347
+ reverseAttachComplete(input, options = {}) {
348
+ return requestAccount(this.http, ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE, "/phone/reverse/complete", input, options);
349
+ }
350
+ /** Подтверждает новый номер звонком и возвращает варианты завершения смены. */
351
+ reverseChangeComplete(input, options = {}) {
352
+ return requestAccount(this.http, ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE, "/phone/reverse/complete", input, options);
353
+ }
354
+ /** Запускает проверку номера, если за время получения капчи сессия не сменилась. */
355
+ async #start(operation, path, { phone, captcha }, options) {
356
+ const revision = this.#auth.revision();
357
+ const proof = await this.#auth.captchaToken(captcha);
358
+ if (this.#auth.revision() !== revision) throw new require_validate.ItdStateError("Сессия сменилась во время получения капчи. Начните проверку номера заново.");
359
+ return requestAccount(this.http, operation, path, {
360
+ phone,
361
+ captcha: proof ? {
362
+ provider: proof.type,
363
+ token: proof.token
364
+ } : void 0
365
+ }, options);
366
+ }
367
+ };
368
+ // src/resources/account.ts
369
+ /**
370
+ * Настройки текущего аккаунта. Доступен как `itd.account`.
371
+ *
372
+ * Здесь можно менять номер, почту и облачный пароль, управлять отложенными
373
+ * заявками, деактивировать и восстановить аккаунт.
374
+ */
375
+ var AccountResource = class extends require_render.AccountLifecycleResource {
376
+ /** Привязка и смена номера. */
377
+ phone;
378
+ /** Привязка и смена почты. */
379
+ email;
380
+ /** Настройка облачного пароля. */
381
+ password;
382
+ /** Завершение смены номера или почты и отложенные заявки. */
383
+ changes;
384
+ constructor(http, auth) {
385
+ super(http);
386
+ this.phone = new AccountPhoneResource(http, auth);
387
+ this.email = new AccountEmailResource(http);
388
+ this.password = new AccountPasswordResource(http);
389
+ this.changes = new AccountChangesResource(http);
390
+ }
391
+ /**
392
+ * Получает сведения о доступе к текущему аккаунту.
393
+ *
394
+ * @returns привязанные номер и почту и признак наличия облачного пароля
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * const { email, phone, hasPassword } = await itd.account.getInfo();
399
+ * ```
400
+ */
401
+ getInfo(options = {}) {
402
+ return requestAccount(this.http, ACCOUNT_GET_INFO, "/methods", void 0, options);
403
+ }
404
+ };
405
+ // src/operations/auth.ts
30
406
  /** Чем закончился запрос входа. */
31
407
  const SignInStatus = Object.freeze({
32
408
  Authenticated: "authenticated",
@@ -62,8 +438,8 @@ function requireString(body, key, message) {
62
438
  return value;
63
439
  }
64
440
  const AUTH_CHECK = require_url.passthroughOperation("auth.check");
65
- require_url.passthroughOperation("auth.captchaProvider");
66
- require_url.passthroughOperation("auth.captchaPage");
441
+ const AUTH_CAPTCHA_PROVIDER = require_url.passthroughOperation("auth.captchaProvider");
442
+ const AUTH_CAPTCHA_PAGE = require_url.passthroughOperation("auth.captchaPage");
67
443
  const AUTH_SIGN_UP = require_url.defineBuiltInOperation("auth.signUp", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при регистрации"));
68
444
  const AUTH_SIGN_IN = require_url.defineBuiltInOperation("auth.signIn", (body) => {
69
445
  const accessToken = require_url.pickString(body, "accessToken");
@@ -81,7 +457,6 @@ const AUTH_RESEND_OTP = require_url.voidOperation("auth.resendOtp");
81
457
  const AUTH_LOGOUT = require_url.voidOperation("auth.logout");
82
458
  const AUTH_FORGOT_PASSWORD = require_url.defineBuiltInOperation("auth.forgotPassword", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при запросе сброса пароля"));
83
459
  const AUTH_RESET_PASSWORD = require_url.voidOperation("auth.resetPassword");
84
- const AUTH_CHANGE_PASSWORD = require_url.voidOperation("auth.changePassword");
85
460
  const AUTH_SESSIONS = require_url.defineBuiltInOperation("auth.sessions", (body) => require_url.pickArray(body, "sessions"));
86
461
  const AUTH_REVOKE_SESSION = require_url.voidOperation("auth.revokeSession");
87
462
  const AUTH_REVOKE_OTHER_SESSIONS = require_url.voidOperation("auth.revokeOtherSessions");
@@ -90,8 +465,7 @@ const AUTH_QR_CLAIM = require_url.passthroughOperation("auth.qrClaim");
90
465
  const AUTH_QR_SCAN = require_url.passthroughOperation("auth.qrScan");
91
466
  const AUTH_QR_APPROVE = require_url.voidOperation("auth.qrApprove");
92
467
  const AUTH_QR_REJECT = require_url.voidOperation("auth.qrReject");
93
- //#endregion
94
- //#region src/session/captcha.ts
468
+ // src/session/captcha.ts
95
469
  function requireCaptchaText(value, field) {
96
470
  if (value !== void 0 && (typeof value !== "string" || value.trim() === "")) throw new require_validate.ItdConfigError(`${field} должен быть непустой строкой`);
97
471
  }
@@ -127,6 +501,17 @@ function validateCaptchaToken(captcha, path) {
127
501
  if (typeof type !== "string" || type.trim() === "") throw new require_validate.ItdConfigError(`${path}.type должен быть непустой строкой`);
128
502
  requireCaptchaText(field, `${path}.field`);
129
503
  }
504
+ /** Разбирает ответ `GET /api/v1/auth/captcha/provider` для автоматического входа. */
505
+ function readCaptchaProvider(body) {
506
+ const config = require_validate.isRecord(body) ? body : void 0;
507
+ const provider = config?.provider;
508
+ const field = config?.field;
509
+ if (typeof provider !== "string" || provider.trim() === "" || typeof field !== "string" || field.trim() === "") throw new require_validate.ItdConfigError("Сервер вернул неподдерживаемую конфигурацию капчи");
510
+ return {
511
+ provider,
512
+ field
513
+ };
514
+ }
130
515
  /** Куда класть токен: настройка, иначе умолчание провайдера. */
131
516
  function resolveField(type, configured) {
132
517
  const field = configured ?? CAPTCHA_FIELDS[type];
@@ -139,37 +524,30 @@ async function requireSolvedToken(solver, type, context) {
139
524
  if (typeof token === "string" && token.trim() !== "") return token;
140
525
  throw new require_validate.ItdConfigError(`Источник капчи не вернул токен для провайдера «${type}». Проверьте captcha.getToken.`);
141
526
  }
142
- /**
143
- * Готовит фрагмент тела запроса, взяв токен у источника.
144
- *
145
- * При `CaptchaChoice.Auto` провайдер спрашивается у сервера — тогда и тип виджета,
146
- * и имя поля приходят оттуда. Явно названный тип обходится без этого запроса.
147
- *
148
- * @param askProvider как спросить активного провайдера; вызывается, только если это нужно
149
- * @param context что источник получает вместе с типом капчи
150
- * @throws {ItdConfigError} если токен получить не удалось
151
- */
152
- async function solveCaptchaBody(solver, askProvider, context) {
527
+ /** Сохраняет провайдера и токен для API, принимающих доказательство капчи объектом. */
528
+ async function solveCaptchaToken(solver, askProvider, context) {
153
529
  const choice = solver.type ?? require_url.CaptchaChoice.Auto;
154
- if (choice === require_url.CaptchaChoice.Auto) {
155
- const { provider, field } = await askProvider();
156
- return { [field]: await requireSolvedToken(solver, provider, context) };
157
- }
158
- return { [resolveField(choice, solver.field)]: await requireSolvedToken(solver, choice, context) };
530
+ const { provider, field } = choice === require_url.CaptchaChoice.Auto ? await askProvider() : {
531
+ provider: choice,
532
+ field: solver.field
533
+ };
534
+ return {
535
+ type: provider,
536
+ field,
537
+ token: await requireSolvedToken(solver, provider, context)
538
+ };
159
539
  }
160
540
  /**
161
541
  * Готовит фрагмент тела из готового токена.
162
542
  *
163
543
  * Поле берётся из самого токена либо из умолчания провайдера; запроса к серверу нет.
164
544
  *
165
- * @throws {ItdConfigError} если токен или его тип не указаны
545
+ * @throws {ItdConfigError} если для провайдера не определено поле запроса
166
546
  */
167
547
  function captchaBody(captcha) {
168
- validateCaptchaToken(captcha, "captcha");
169
548
  return { [resolveField(captcha.type, captcha.field)]: captcha.token };
170
549
  }
171
- //#endregion
172
- //#region src/session/jwt.ts
550
+ // src/session/jwt.ts
173
551
  /**
174
552
  * Разбирает строку base64url.
175
553
  *
@@ -208,8 +586,7 @@ function readTokenMetadata(token) {
208
586
  ...expiresAt !== void 0 && Number.isFinite(expiresAt) ? { expiresAt } : {}
209
587
  };
210
588
  }
211
- //#endregion
212
- //#region src/session/auth.ts
589
+ // src/session/auth.ts
213
590
  /** Запас до истечения токена на очередь и выполнение запроса. */
214
591
  const ACCESS_TOKEN_REFRESH_LEEWAY_MS = 3e4;
215
592
  /**
@@ -301,7 +678,6 @@ const AUTH_PATHS = {
301
678
  logout: "/api/v1/auth/logout",
302
679
  forgotPassword: "/api/v1/auth/forgot-password",
303
680
  resetPassword: "/api/v1/auth/reset-password",
304
- changePassword: "/api/v1/auth/change-password",
305
681
  sessions: "/api/v1/auth/sessions",
306
682
  qrStart: "/api/v1/auth/qr/start",
307
683
  qrClaim: "/api/v1/auth/qr/claim",
@@ -993,13 +1369,20 @@ var AuthManager = class {
993
1369
  * @throws {ItdConfigError} если токен неполный или источник его не вернул
994
1370
  */
995
1371
  async captchaBody(explicit) {
996
- if (explicit) return captchaBody(explicit);
1372
+ const token = await this.captchaToken(explicit);
1373
+ return token ? captchaBody(token) : {};
1374
+ }
1375
+ /** Доказательство капчи с провайдером для телефонного API. @internal */
1376
+ async captchaToken(explicit) {
1377
+ if (explicit) {
1378
+ validateCaptchaToken(explicit, "captcha");
1379
+ return explicit;
1380
+ }
997
1381
  const configured = this.#takeConfiguredCaptcha();
998
- if (configured) return captchaBody(configured);
1382
+ if (configured) return configured;
999
1383
  const solver = this.#config.captcha;
1000
- if (solver) return solveCaptchaBody(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
1384
+ if (solver) return solveCaptchaToken(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
1001
1385
  this.#config.logger?.debug("Запрос уходит без токена капчи: не передан аргумент captcha и не задана опция captcha");
1002
- return {};
1003
1386
  }
1004
1387
  /** Отдаёт разовый токен из `auth.captcha`, помечая его потраченным. */
1005
1388
  #takeConfiguredCaptcha() {
@@ -1012,10 +1395,22 @@ var AuthManager = class {
1012
1395
  }
1013
1396
  /** Спрашивает у сервера активного провайдера и поле, в котором он ждёт токен. */
1014
1397
  async #resolveCaptchaProvider() {
1015
- return {
1016
- provider: require_url.CaptchaType.Cloudflare,
1017
- field: require_url.CaptchaField.Cloudflare
1018
- };
1398
+ try {
1399
+ return readCaptchaProvider(await this.#http.execute(AUTH_CAPTCHA_PROVIDER, {
1400
+ path: AUTH_PATHS.captchaProvider,
1401
+ skipAuth: true,
1402
+ skipAuthRefresh: true
1403
+ }));
1404
+ } catch (error) {
1405
+ if (require_validate.isItdApiError(error) && error.status === 404 && error.code === require_url.ItdErrorCode.NOT_FOUND) {
1406
+ this.#config.logger?.warn("Сервер отключил определение провайдера капчи; используется Cloudflare Turnstile");
1407
+ return {
1408
+ provider: require_url.CaptchaType.Cloudflare,
1409
+ field: require_url.CaptchaField.Cloudflare
1410
+ };
1411
+ }
1412
+ throw error;
1413
+ }
1019
1414
  }
1020
1415
  async #performSignIn(credentials, revision) {
1021
1416
  const captcha = await this.captchaBody();
@@ -1054,8 +1449,7 @@ var AuthManager = class {
1054
1449
  return userId ? `: пользователь ${userId}` : "";
1055
1450
  }
1056
1451
  };
1057
- //#endregion
1058
- //#region src/session/qr-stream.ts
1452
+ // src/session/qr-stream.ts
1059
1453
  const QR_STREAM_STATUSES = new Set(Object.values(QrLoginStreamStatus));
1060
1454
  function readQrLoginStreamEvent(data) {
1061
1455
  let value;
@@ -1171,8 +1565,184 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
1171
1565
  abort.cleanup();
1172
1566
  }
1173
1567
  }
1174
- //#endregion
1175
- //#region src/resources/auth.ts
1568
+ // src/operations/auth/phone.ts
1569
+ /** Отклоняет неизвестный контракт до принятия результата входа. */
1570
+ function invalidResponse() {
1571
+ throw new require_validate.ItdConfigError("Сервер вернул неподдерживаемый ответ телефонного входа");
1572
+ }
1573
+ /** Требует непустой секрет для продолжения телефонного потока. */
1574
+ function readFlowToken(body) {
1575
+ const value = require_url.pickString(body, "flowToken");
1576
+ if (!value) return invalidResponse();
1577
+ return value;
1578
+ }
1579
+ /** Разделяет access token и шаг пароля; режимы привязки/смены контакта не принимает. */
1580
+ function readLoginResult(body) {
1581
+ if (!require_validate.isRecord(body)) return invalidResponse();
1582
+ if (body.mode !== void 0 && body.mode !== AuthVerificationMode.SignIn) return invalidResponse();
1583
+ const accessToken = require_url.pickString(body, "accessToken");
1584
+ if (accessToken) return { accessToken };
1585
+ if (body.step === PhoneLoginStep.Password) return {
1586
+ step: PhoneLoginStep.Password,
1587
+ flowToken: readFlowToken(body)
1588
+ };
1589
+ return invalidResponse();
1590
+ }
1591
+ /** Для завершения по паролю промежуточный шаг вместо access token недопустим. */
1592
+ function readAccessToken(body) {
1593
+ const result = readLoginResult(body);
1594
+ if (!("accessToken" in result)) return invalidResponse();
1595
+ return result.accessToken;
1596
+ }
1597
+ const AUTH_PHONE_CONFIG = require_url.passthroughOperation("auth.phone.config");
1598
+ const AUTH_PHONE_CONSENT = require_url.passthroughOperation("auth.phone.consent");
1599
+ const AUTH_PHONE_START = require_url.defineBuiltInOperation("auth.phone.start", readPhoneStart);
1600
+ const AUTH_PHONE_VERIFY = require_url.defineBuiltInOperation("auth.phone.verify", readLoginResult);
1601
+ const AUTH_PHONE_PASSWORD = require_url.defineBuiltInOperation("auth.phone.password", readAccessToken);
1602
+ const AUTH_PHONE_RESET_PASSWORD = require_url.defineBuiltInOperation("auth.phone.resetPassword", readAccessToken);
1603
+ const AUTH_PHONE_RESEND = require_url.defineBuiltInOperation("auth.phone.resend", readPhoneDelivery);
1604
+ const AUTH_PHONE_REVERSE_OPTIONS = require_url.passthroughOperation("auth.phone.reverseOptions");
1605
+ const AUTH_PHONE_REVERSE_START = require_url.passthroughOperation("auth.phone.reverseStart");
1606
+ const AUTH_PHONE_REVERSE_STATUS = require_url.passthroughOperation("auth.phone.reverseStatus");
1607
+ const AUTH_PHONE_REVERSE_COMPLETE = require_url.defineBuiltInOperation("auth.phone.reverseComplete", readLoginResult);
1608
+ // src/resources/auth/phone.ts
1609
+ /** Телефонный вход и регистрация. Доступен как `itd.auth.phone`. */
1610
+ var PhoneAuthResource = class extends require_render.BaseResource {
1611
+ #auth;
1612
+ constructor(http, deps) {
1613
+ super(http);
1614
+ this.#auth = deps.auth;
1615
+ }
1616
+ /** Разрешённые регионы и примеры номеров. */
1617
+ config(options = {}) {
1618
+ return this.#request(AUTH_PHONE_CONFIG, "/phone/config", void 0, options);
1619
+ }
1620
+ /**
1621
+ * Загружает контекст phone_entry вместе с текстом и редакциями документов.
1622
+ *
1623
+ * До start() покажите документы пользователю. Истёкший контекст и новые редакции
1624
+ * библиотека не заменяет автоматически.
1625
+ */
1626
+ consent(options = {}) {
1627
+ return this.#request(AUTH_PHONE_CONSENT, `/consent?flow=${PHONE_CONSENT_FLOW}`, void 0, options);
1628
+ }
1629
+ /**
1630
+ * Запрашивает подтверждение номера для входа или регистрации.
1631
+ *
1632
+ * Токен капчи отправляется объектом { provider, token }.
1633
+ *
1634
+ * @returns `flowToken` для продолжения входа, канал доставки, длина кода и пауза повтора в секундах
1635
+ */
1636
+ async start(input, options = {}) {
1637
+ const captcha = await this.#auth.captchaToken(input.captcha);
1638
+ return this.#request(AUTH_PHONE_START, "/phone/start", {
1639
+ phone: input.phone,
1640
+ captcha: captcha ? {
1641
+ provider: captcha.type,
1642
+ token: captcha.token
1643
+ } : void 0,
1644
+ legal: {
1645
+ protocolVersion: input.consent.protocolVersion,
1646
+ contextToken: input.consent.contextToken
1647
+ }
1648
+ }, {
1649
+ ...options,
1650
+ headers: {
1651
+ ...options.headers,
1652
+ ...input.method === PhoneVerificationMethod.Reverse ? { "X-ITD-Phone-Method": PhoneVerificationMethod.Reverse } : {}
1653
+ }
1654
+ });
1655
+ }
1656
+ /**
1657
+ * Подтверждает код без email и пароля.
1658
+ *
1659
+ * При accessToken сохраняет новую сессию; при step: 'password' возвращает секрет
1660
+ * для password().
1661
+ */
1662
+ verify(input, options = {}) {
1663
+ return this.#complete(AUTH_PHONE_VERIFY, "/verify-otp", input, options);
1664
+ }
1665
+ /**
1666
+ * Запрашивает повторную доставку без изменения авторизации.
1667
+ *
1668
+ * Используйте новый channel/codeLength из результата: способ доставки может измениться.
1669
+ * retryIn — секунды до следующего запроса.
1670
+ */
1671
+ resend(input, options = {}) {
1672
+ return this.#request(AUTH_PHONE_RESEND, "/resend-otp", input, options);
1673
+ }
1674
+ /**
1675
+ * Завершает вход облачным паролем после step: 'password'.
1676
+ *
1677
+ * Передайте flowToken из этого шага. Полученный access token и cookies сохраняются
1678
+ * автоматически, если владелец сессии не сменился во время запроса.
1679
+ */
1680
+ password(input, options = {}) {
1681
+ return this.#authenticate(AUTH_PHONE_PASSWORD, "/phone/password", input, options);
1682
+ }
1683
+ /** Устанавливает новый пароль после подтверждения номера и сохраняет сессию. */
1684
+ resetPassword(input, options = {}) {
1685
+ return this.#authenticate(AUTH_PHONE_RESET_PASSWORD, "/phone/reset-password", input, options);
1686
+ }
1687
+ /** Проверяет, доступен ли исходящий звонок для подтверждения номера. */
1688
+ reverseOptions(input, options = {}) {
1689
+ return this.#request(AUTH_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
1690
+ }
1691
+ /**
1692
+ * Подготавливает номер, на который пользователь должен позвонить.
1693
+ *
1694
+ * Может выделить новую попытку; не повторяется после сетевых ошибок и 5xx. Номер и срок
1695
+ * его действия возвращаются в phone и expiresIn.
1696
+ */
1697
+ reverseStart(input, options = {}) {
1698
+ return this.#request(AUTH_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
1699
+ }
1700
+ /** Читает состояние звонка через POST, без завершения входа и смены сессии. */
1701
+ reverseStatus(input, options = {}) {
1702
+ return this.#request(AUTH_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
1703
+ }
1704
+ /** Завершает подтверждённый звонок; сервер может потребовать облачный пароль. */
1705
+ reverseComplete(input, options = {}) {
1706
+ return this.#complete(AUTH_PHONE_REVERSE_COMPLETE, "/phone/reverse/complete", input, options);
1707
+ }
1708
+ /** Применяет cookies промежуточного шага либо атомарно сохраняет завершённый вход. */
1709
+ async #complete(operation, path, input, options) {
1710
+ const revision = this.#auth.revision();
1711
+ const cookies = this.#auth.createCookieFlow();
1712
+ const result = await this.#request(operation, path, input, options, cookies);
1713
+ if ("accessToken" in result) await this.#auth.commitAuthFlow(result.accessToken, cookies, revision);
1714
+ else this.#auth.commitCookieFlow(cookies, revision);
1715
+ return result;
1716
+ }
1717
+ /** Сохраняет результат пароля, не позволяя запоздалому ответу сменить нового владельца. */
1718
+ async #authenticate(operation, path, input, options) {
1719
+ const revision = this.#auth.revision();
1720
+ const cookies = this.#auth.createCookieFlow();
1721
+ const token = await this.#request(operation, path, input, options, cookies);
1722
+ await this.#auth.commitAuthFlow(token, cookies, revision);
1723
+ return token;
1724
+ }
1725
+ /**
1726
+ * Выполняет телефонный запрос без Bearer/refresh через общий pipeline.
1727
+ * X-ITD-Phone-Reverse объявляет поддержку обратного звонка и требуется для reverse-операций.
1728
+ */
1729
+ #request(operation, path, body, options, cookies) {
1730
+ return this.http.execute(operation, {
1731
+ ...options,
1732
+ path: `/api/v1/auth${path}`,
1733
+ body,
1734
+ ...cookies ? { cookieJar: cookies } : {},
1735
+ skipAuth: true,
1736
+ skipAuthRefresh: true,
1737
+ headers: {
1738
+ ...options.headers,
1739
+ ...operation.method === "POST" ? { "X-ITD-Phone-Reverse": "1" } : {},
1740
+ ...path.startsWith("/phone/reverse/") ? { "X-ITD-Reverse-Attempts": "1" } : {}
1741
+ }
1742
+ });
1743
+ }
1744
+ };
1745
+ // src/resources/auth.ts
1176
1746
  /**
1177
1747
  * Результат входа.
1178
1748
  *
@@ -1185,6 +1755,8 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
1185
1755
  * Доступна как `itd.auth`.
1186
1756
  */
1187
1757
  var AuthResource = class extends require_render.BaseResource {
1758
+ /** Вход и регистрация по номеру телефона. */
1759
+ phone;
1188
1760
  #auth;
1189
1761
  #connection;
1190
1762
  #qrFlows = /* @__PURE__ */ new Map();
@@ -1192,6 +1764,7 @@ var AuthResource = class extends require_render.BaseResource {
1192
1764
  super(http);
1193
1765
  this.#auth = deps.auth;
1194
1766
  this.#connection = deps.connection;
1767
+ this.phone = new PhoneAuthResource(http, deps);
1195
1768
  }
1196
1769
  #pruneQrFlows() {
1197
1770
  const now = this.#connection.clock.now();
@@ -1233,13 +1806,13 @@ var AuthResource = class extends require_render.BaseResource {
1233
1806
  *
1234
1807
  * Сервер может переключить провайдера или переименовать поле без выпуска новой версии SDK.
1235
1808
  * Автоматическому входу этот вызов не нужен — клиент делает его сам.
1236
- *
1237
- * @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile.
1238
1809
  */
1239
- captchaProvider(_options = {}) {
1240
- return Promise.resolve({
1241
- provider: require_url.CaptchaType.Cloudflare,
1242
- field: CAPTCHA_FIELDS[require_url.CaptchaType.Cloudflare]
1810
+ captchaProvider(options = {}) {
1811
+ return this.http.execute(AUTH_CAPTCHA_PROVIDER, {
1812
+ path: AUTH_PATHS.captchaProvider,
1813
+ skipAuth: true,
1814
+ skipAuthRefresh: true,
1815
+ ...options
1243
1816
  });
1244
1817
  }
1245
1818
  /**
@@ -1248,14 +1821,14 @@ var AuthResource = class extends require_render.BaseResource {
1248
1821
  * То же, что {@link captchaProvider}, плюс `url` — готовая страница на домене итд.com,
1249
1822
  * где ключ виджета действителен. Пригодится встроенному браузеру: открыть её и забрать
1250
1823
  * токен, ничего не собирая самому.
1251
- *
1252
- * @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile на домене итд.com.
1253
1824
  */
1254
- async captchaPage(options = {}) {
1255
- return {
1256
- ...await this.captchaProvider(options),
1257
- url: require_url.DEFAULT_BASE_URL
1258
- };
1825
+ captchaPage(options = {}) {
1826
+ return this.http.execute(AUTH_CAPTCHA_PAGE, {
1827
+ path: AUTH_PATHS.captchaPage,
1828
+ skipAuth: true,
1829
+ skipAuthRefresh: true,
1830
+ ...options
1831
+ });
1259
1832
  }
1260
1833
  /** Создаёт короткоживущую сессию QR-входа. */
1261
1834
  async startQrLogin(options = {}) {
@@ -1383,6 +1956,7 @@ var AuthResource = class extends require_render.BaseResource {
1383
1956
  * Регистрирует аккаунт и запускает подтверждение по коду.
1384
1957
  *
1385
1958
  * @returns `flowToken`, который нужно передать в {@link verifyOtp}
1959
+ * @deprecated Регистрация по email отключена. Используйте auth.phone.start().
1386
1960
  */
1387
1961
  async signUp(credentials, options = {}) {
1388
1962
  const { captcha, ...rest } = credentials;
@@ -1599,26 +2173,6 @@ var AuthResource = class extends require_render.BaseResource {
1599
2173
  newPassword
1600
2174
  }, options);
1601
2175
  }
1602
- /**
1603
- * Меняет пароль. Требует действующей сессии.
1604
- *
1605
- * При неверном текущем пароле сервер отвечает `ACCOUNT_CURRENT_PASSWORD_INCORRECT`.
1606
- *
1607
- * @example
1608
- * ```ts
1609
- * await itd.auth.changePassword({ currentPassword, newPassword });
1610
- * ```
1611
- */
1612
- changePassword(input, options = {}) {
1613
- return this.voidOperation(AUTH_CHANGE_PASSWORD, {
1614
- path: AUTH_PATHS.changePassword,
1615
- body: {
1616
- currentPassword: input.currentPassword,
1617
- newPassword: input.newPassword
1618
- },
1619
- ...options
1620
- });
1621
- }
1622
2176
  /** Загружает список активных сессий. У текущей поле `isCurrent` равно `true`. */
1623
2177
  sessions(options = {}) {
1624
2178
  return this.http.execute(AUTH_SESSIONS, {
@@ -1641,8 +2195,7 @@ var AuthResource = class extends require_render.BaseResource {
1641
2195
  });
1642
2196
  }
1643
2197
  };
1644
- //#endregion
1645
- //#region src/client.ts
2198
+ // src/client.ts
1646
2199
  const CLIENT_PLUGIN_REGISTRIES = /* @__PURE__ */ new WeakMap();
1647
2200
  const DISPOSED_CLIENTS = /* @__PURE__ */ new WeakSet();
1648
2201
  function assertClientActive(client, action) {
@@ -1706,6 +2259,7 @@ var ItdClient = class ItdClient {
1706
2259
  #resources;
1707
2260
  /** Сессионный ресурс живёт у фасада: он управляет входом и продлением. */
1708
2261
  #auth;
2262
+ #account;
1709
2263
  /** Авторизация, сессии и пароли. */
1710
2264
  get auth() {
1711
2265
  this.#auth ??= new AuthResource(this.#runtime.http, {
@@ -1714,6 +2268,11 @@ var ItdClient = class ItdClient {
1714
2268
  });
1715
2269
  return this.#auth;
1716
2270
  }
2271
+ /** Настройки текущего аккаунта и управление его состоянием. */
2272
+ get account() {
2273
+ this.#account ??= new AccountResource(this.#runtime.http, this.#runtime.auth);
2274
+ return this.#account;
2275
+ }
1717
2276
  /** Профили, подписки, блокировки, приватность. */
1718
2277
  get users() {
1719
2278
  return this.#resources.users;
@@ -1754,6 +2313,10 @@ var ItdClient = class ItdClient {
1754
2313
  get subscription() {
1755
2314
  return this.#resources.subscription;
1756
2315
  }
2316
+ /** Публичные документы ИТД и история их редакций. */
2317
+ get legal() {
2318
+ return this.#resources.legal;
2319
+ }
1757
2320
  /** Сведения о платформе: версии приложений, изменения, анонсы, баннер события. */
1758
2321
  get platform() {
1759
2322
  return this.#resources.platform;
@@ -2157,8 +2720,7 @@ var ItdClient = class ItdClient {
2157
2720
  function createClient(options = {}) {
2158
2721
  return new ItdClient(options);
2159
2722
  }
2160
- //#endregion
2161
- //#region src/accounts.ts
2723
+ // src/accounts.ts
2162
2724
  /** Как аккаунты делят между собой очередь запросов. */
2163
2725
  const RateLimitScope = Object.freeze({
2164
2726
  /** У каждого аккаунта своя очередь. */
@@ -2627,17 +3189,31 @@ var ItdAccounts = class ItdAccounts {
2627
3189
  function createAccounts(options = {}) {
2628
3190
  return new ItdAccounts(options);
2629
3191
  }
2630
- //#endregion
3192
+ // src/models/account-access.ts
3193
+ /** Способ подтверждения смены номера или почты. */
3194
+ const ContactProofMethod = Object.freeze({
3195
+ Password: "password",
3196
+ EmailCode: "email_code",
3197
+ PhoneCode: "phone_code"
3198
+ });
3199
+ /** Что меняет отложенная заявка: номер или почту. */
3200
+ const ContactKind = Object.freeze({
3201
+ Email: "email",
3202
+ Phone: "phone"
3203
+ });
2631
3204
  exports.ALLOWED_MIME_TYPES = require_render.ALLOWED_MIME_TYPES;
2632
3205
  exports.AUDIO_MIME_TYPES = require_render.AUDIO_MIME_TYPES;
2633
3206
  exports.AccessType = require_url.AccessType;
2634
3207
  exports.AttachmentType = require_url.AttachmentType;
2635
3208
  exports.BUCKET_LIMITS = require_url.BUCKET_LIMITS;
3209
+ exports.BannerDrawingTool = require_render.BannerDrawingTool;
2636
3210
  exports.CAPTCHA_FIELDS = CAPTCHA_FIELDS;
2637
3211
  exports.CaptchaChoice = require_url.CaptchaChoice;
2638
3212
  exports.CaptchaField = require_url.CaptchaField;
2639
3213
  exports.CaptchaType = require_url.CaptchaType;
2640
3214
  exports.CommentSort = require_url.CommentSort;
3215
+ exports.ContactKind = ContactKind;
3216
+ exports.ContactProofMethod = ContactProofMethod;
2641
3217
  exports.DEFAULT_BASE_URL = require_url.DEFAULT_BASE_URL;
2642
3218
  exports.DEFAULT_RATE_LIMIT_BUCKET = require_url.DEFAULT_RATE_LIMIT_BUCKET;
2643
3219
  exports.EventChannel = require_events.EventChannel;
@@ -2673,6 +3249,8 @@ exports.ItdTimeoutError = require_validate.ItdTimeoutError;
2673
3249
  exports.ItdValidationError = require_validate.ItdValidationError;
2674
3250
  exports.LIBRARY_VERSION = require_url.LIBRARY_VERSION;
2675
3251
  exports.LastSeenUnit = require_url.LastSeenUnit;
3252
+ exports.LegalDocumentBlockType = require_render.LegalDocumentBlockType;
3253
+ exports.LegalDocumentScope = require_render.LegalDocumentScope;
2676
3254
  exports.LikesVisibility = require_url.LikesVisibility;
2677
3255
  exports.LogLevel = require_redact.LogLevel;
2678
3256
  exports.MemoryKeyValueStore = require_key_value_store.MemoryKeyValueStore;
@@ -2690,6 +3268,10 @@ exports.OPERATIONS = require_url.OPERATIONS;
2690
3268
  exports.OperationMethod = require_url.OperationMethod;
2691
3269
  exports.PaginationMode = require_render.PaginationMode;
2692
3270
  exports.Paginator = require_render.Paginator;
3271
+ exports.PhoneDeliveryChannel = PhoneDeliveryChannel;
3272
+ exports.PhoneLoginStep = PhoneLoginStep;
3273
+ exports.PhoneReverseState = PhoneReverseState;
3274
+ exports.PhoneVerificationMethod = PhoneVerificationMethod;
2693
3275
  exports.QrLocationPrecision = require_url.QrLocationPrecision;
2694
3276
  exports.QrLoginStatus = QrLoginStatus;
2695
3277
  exports.QrLoginStreamStatus = QrLoginStreamStatus;