itd-api 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +715 -90
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +515 -46
  8. package/dist/index.d.ts +515 -46
  9. package/dist/index.js +707 -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-FaXfdle0.d.cts → events-Bip3qvCc.d.cts} +42 -63
  26. package/dist/shared/{events-9215JDDd.d.ts → events-DF1elRzZ.d.ts} +2 -23
  27. package/dist/shared/{events-_iYo8EP5.js → events-DRbBDq9p.js} +30 -40
  28. package/dist/shared/events-DRbBDq9p.js.map +1 -0
  29. package/dist/shared/{events-BKyxZQNw.cjs → events-DcxmyPTX.cjs} +30 -40
  30. package/dist/shared/events-DcxmyPTX.cjs.map +1 -0
  31. package/dist/shared/{key-value-store-COZaNHZS.d.ts → key-value-store-BGoSgLze.d.cts} +1 -4
  32. package/dist/shared/{key-value-store-w1Dn5Pjb.js → key-value-store-BwXlaoD4.js} +3 -4
  33. package/dist/shared/{key-value-store-w1Dn5Pjb.js.map → key-value-store-BwXlaoD4.js.map} +1 -1
  34. package/dist/shared/{key-value-store-DYSPsqwq.cjs → key-value-store-CmnIjuE4.cjs} +3 -4
  35. package/dist/shared/{key-value-store-DYSPsqwq.cjs.map → key-value-store-CmnIjuE4.cjs.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-LkljOSzA.d.ts → multi-storage-DQiERirK.d.ts} +3 -6
  38. package/dist/shared/{multi-storage-DiBSx64p.js → multi-storage-DffEAzdc.js} +6 -7
  39. package/dist/shared/{multi-storage-DiBSx64p.js.map → multi-storage-DffEAzdc.js.map} +1 -1
  40. package/dist/shared/{multi-storage-7Y3KCseI.cjs → multi-storage-Dp5x6OOl.cjs} +6 -7
  41. package/dist/shared/multi-storage-Dp5x6OOl.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-DLlaETn_.js → options-Ddyc5qec.js} +8 -12
  44. package/dist/shared/{options-DLlaETn_.js.map → options-Ddyc5qec.js.map} +1 -1
  45. package/dist/shared/{options-D5ttspWk.cjs → options-DsmQRyx4.cjs} +8 -12
  46. package/dist/shared/{options-D5ttspWk.cjs.map → options-DsmQRyx4.cjs.map} +1 -1
  47. package/dist/shared/{redact-DSfdmeY7.js → redact-BCmucE19.js} +16 -16
  48. package/dist/shared/redact-BCmucE19.js.map +1 -0
  49. package/dist/shared/{redact-BbhtA9o-.cjs → redact-BuXRKC1G.cjs} +16 -16
  50. package/dist/shared/redact-BuXRKC1G.cjs.map +1 -0
  51. package/dist/shared/{render-BS09ygcy.d.ts → render-Bvv1V5Tp.d.ts} +154 -102
  52. package/dist/shared/{render-BQvC5UxF.cjs → render-C1lmsu1i.cjs} +204 -109
  53. package/dist/shared/render-C1lmsu1i.cjs.map +1 -0
  54. package/dist/shared/{render-X2JCo1JS.d.cts → render-D83t9ckd.d.cts} +152 -251
  55. package/dist/shared/{render-CFoF2WaH.js → render-DJKZqv9O.js} +181 -110
  56. package/dist/shared/render-DJKZqv9O.js.map +1 -0
  57. package/dist/shared/{storage-86wiHeXD.js → storage-Bc4lWtSj.js} +4 -5
  58. package/dist/shared/{storage-86wiHeXD.js.map → storage-Bc4lWtSj.js.map} +1 -1
  59. package/dist/shared/{storage-CTRGT5wF.d.ts → storage-C_ZujAZt.d.ts} +2 -5
  60. package/dist/shared/{storage-BQrtKon9.d.cts → storage-FtS4NIC7.d.cts} +2 -5
  61. package/dist/shared/{storage-CIjejZDt.cjs → storage-e2xYL6ro.cjs} +4 -5
  62. package/dist/shared/{storage-CIjejZDt.cjs.map → storage-e2xYL6ro.cjs.map} +1 -1
  63. package/dist/shared/{url-ioIaywDi.cjs → url-CXRaoR_w.cjs} +263 -91
  64. package/dist/shared/url-CXRaoR_w.cjs.map +1 -0
  65. package/dist/shared/{url-_R0oJ7gE.d.cts → url-V4bCae35.d.ts} +222 -78
  66. package/dist/shared/{url-CdT4lMxQ.js → url-aw_NZdVY.js} +263 -91
  67. package/dist/shared/url-aw_NZdVY.js.map +1 -0
  68. package/dist/shared/{url-_R0oJ7gE.d.ts → url-n_h2pvHA.d.cts} +1915 -1620
  69. package/dist/shared/{validate-CFx2dISs.cjs → validate-BHKy_YMv.cjs} +8 -7
  70. package/dist/shared/validate-BHKy_YMv.cjs.map +1 -0
  71. package/dist/shared/{validate-D7_kq3g5.js → validate-BQzL_oJ4.js} +8 -7
  72. package/dist/shared/validate-BQzL_oJ4.js.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-BKyxZQNw.cjs.map +0 -1
  81. package/dist/shared/events-_iYo8EP5.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-BQvC5UxF.cjs.map +0 -1
  86. package/dist/shared/render-CFoF2WaH.js.map +0 -1
  87. package/dist/shared/url-CdT4lMxQ.js.map +0 -1
  88. package/dist/shared/url-ioIaywDi.cjs.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-ioIaywDi.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-BQvC5UxF.cjs");
6
- const require_options = require("./shared/options-D5ttspWk.cjs");
7
- const require_events = require("./shared/events-BKyxZQNw.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-CXRaoR_w.cjs");
3
+ const require_validate = require("./shared/validate-BHKy_YMv.cjs");
4
+ const require_render = require("./shared/render-C1lmsu1i.cjs");
5
+ const require_events = require("./shared/events-DcxmyPTX.cjs");
6
+ const require_redact = require("./shared/redact-BuXRKC1G.cjs");
7
+ const require_storage = require("./shared/storage-e2xYL6ro.cjs");
8
+ const require_multi_storage = require("./shared/multi-storage-Dp5x6OOl.cjs");
9
+ const require_options = require("./shared/options-DsmQRyx4.cjs");
10
+ const require_key_value_store = require("./shared/key-value-store-CmnIjuE4.cjs");
11
+ // src/notifications-api.ts
12
12
  var ClientNotifications = class extends require_render.NotificationsResource {
13
13
  #createEvents;
14
14
  #events;
@@ -25,8 +25,397 @@ 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
+ return http.execute(operation, {
42
+ ...options,
43
+ path: `/api/v1/auth${path}`,
44
+ body
45
+ });
46
+ }
47
+ // src/resources/account/changes.ts
48
+ /** Завершение смены номера или почты и управление отложенными заявками. */
49
+ var AccountChangesResource = class extends require_render.BaseResource {
50
+ /**
51
+ * Запрашивает код на привязанный номер или почту.
52
+ *
53
+ * Возьмите `changeToken` и способ доставки из результата `verifyChange()` или
54
+ * `phone.reverseChangeComplete()`. Полученный код передайте в {@link confirm}.
55
+ */
56
+ requestProof(input, options = {}) {
57
+ return requestAccount(this.http, ACCOUNT_CHANGES_REQUEST_PROOF, "/change/proof", input, options);
58
+ }
59
+ /**
60
+ * Завершает смену номера или почты.
61
+ *
62
+ * Передайте `changeToken` и код из {@link requestProof} либо облачный
63
+ * пароль, если сервер предложил такой способ подтверждения.
64
+ */
65
+ confirm(input, options = {}) {
66
+ return requestAccount(this.http, ACCOUNT_CHANGES_CONFIRM, "/change/confirm", input, options);
67
+ }
68
+ /**
69
+ * Создаёт отложенную заявку на смену номера или почты.
70
+ *
71
+ * @returns время применения заявки. До этого её можно отменить через {@link cancelPending}
72
+ */
73
+ wait(changeToken, options = {}) {
74
+ return requestAccount(this.http, ACCOUNT_CHANGES_WAIT, "/change/wait", { changeToken }, options);
75
+ }
76
+ /** Возвращает отложенные заявки текущего аккаунта. */
77
+ pending(options = {}) {
78
+ return requestAccount(this.http, ACCOUNT_CHANGES_PENDING, "/change/pending", void 0, options);
79
+ }
80
+ /**
81
+ * Отменяет отложенную смену.
82
+ *
83
+ * @param requestId идентификатор заявки из {@link pending}
84
+ */
85
+ cancelPending(requestId, options = {}) {
86
+ return requestAccount(this.http, ACCOUNT_CHANGES_CANCEL_PENDING, `/change/pending/${require_redact.encodePathSegment(requestId, "requestId")}`, void 0, options);
87
+ }
88
+ };
89
+ // src/operations/account/email.ts
90
+ /** Извлекает токен для подтверждения адреса почты. */
91
+ function readEmailFlow(body) {
92
+ const flowToken = require_url.pickString(body, "flowToken");
93
+ if (!flowToken) throw new require_validate.ItdConfigError("Сервер не вернул flowToken для подтверждения почты");
94
+ return flowToken;
95
+ }
96
+ const ACCOUNT_EMAIL_ATTACH = require_url.defineBuiltInOperation("account.email.attach", readEmailFlow);
97
+ const ACCOUNT_EMAIL_START_CHANGE = require_url.defineBuiltInOperation("account.email.startChange", readEmailFlow);
98
+ const ACCOUNT_EMAIL_RESEND_OTP = require_url.voidOperation("account.email.resendOtp");
99
+ // src/models/phone-auth.ts
100
+ /** Назначение контекста согласия телефонного входа. @internal */
101
+ const PHONE_CONSENT_FLOW = "phone_entry";
102
+ /** Назначение ответа общего endpoint подтверждения кода. */
103
+ const AuthVerificationMode = Object.freeze({
104
+ SignIn: "signin",
105
+ Change: "change"
106
+ });
107
+ /** Серверные каналы доставки кода. */
108
+ const PhoneDeliveryChannel = Object.freeze({
109
+ MissedCall: "missed_call",
110
+ VoiceCall: "voice_call",
111
+ Sms: "sms",
112
+ Push: "push"
113
+ });
114
+ /** Подтверждение входящим кодом либо исходящим звонком пользователя. */
115
+ const PhoneVerificationMethod = Object.freeze({
116
+ Direct: "direct",
117
+ Reverse: "reverse"
118
+ });
119
+ /** Продолжение телефонного входа, ещё не выдавшее access token. */
120
+ const PhoneLoginStep = Object.freeze({ Password: "password" });
121
+ /** Состояния подтверждения номера исходящим звонком. */
122
+ const PhoneReverseState = Object.freeze({
123
+ NotStarted: "not_started",
124
+ Preparing: "preparing",
125
+ Waiting: "waiting",
126
+ Confirmed: "confirmed",
127
+ Expired: "expired",
128
+ Failed: "failed"
129
+ });
130
+ // src/operations/account/verification.ts
131
+ /** Отделяет ответ смены контакта от результата входа на общем маршруте подтверждения. */
132
+ function readContactChange(body) {
133
+ const changeToken = require_url.pickString(body, "changeToken");
134
+ if (!require_validate.isRecord(body) || body.mode !== void 0 && body.mode !== AuthVerificationMode.Change || !changeToken) throw new require_validate.ItdConfigError("Сервер не вернул подтверждение смены контакта");
135
+ return {
136
+ changeToken,
137
+ proofs: require_url.pickArray(body, "proofs"),
138
+ ...typeof body.waitDays === "number" ? { waitDays: body.waitDays } : {}
139
+ };
140
+ }
141
+ const ACCOUNT_VERIFY_ATTACH = require_url.passthroughOperation("account.verifyAttach");
142
+ const ACCOUNT_VERIFY_CHANGE = require_url.defineBuiltInOperation("account.verifyChange", (body) => {
143
+ if (!require_validate.isRecord(body) || body.mode !== AuthVerificationMode.Change) throw new require_validate.ItdConfigError("Сервер не вернул режим смены контакта");
144
+ return readContactChange(body);
145
+ });
146
+ const ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE = require_url.passthroughOperation("account.phone.reverseAttachComplete");
147
+ const ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE = require_url.defineBuiltInOperation("account.phone.reverseChangeComplete", readContactChange);
148
+ // src/resources/account/email.ts
149
+ /** Привязка и смена почты текущего аккаунта. */
150
+ var AccountEmailResource = class extends require_render.BaseResource {
151
+ /**
152
+ * Отправляет код на почту для привязки.
153
+ *
154
+ * @returns значение `flowToken` для {@link verifyAttach} или {@link resendOtp}
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * const flowToken = await itd.account.email.attach(email);
159
+ * await itd.account.email.verifyAttach({ email, flowToken, otp: await getOtp() });
160
+ * ```
161
+ */
162
+ attach(email, options = {}) {
163
+ return requestAccount(this.http, ACCOUNT_EMAIL_ATTACH, "/email/attach", { email }, options);
164
+ }
165
+ /**
166
+ * Отправляет код на новый адрес почты.
167
+ *
168
+ * @returns значение `flowToken` для {@link verifyChange} или {@link resendOtp}
169
+ */
170
+ startChange(email, options = {}) {
171
+ return requestAccount(this.http, ACCOUNT_EMAIL_START_CHANGE, "/email/change", { email }, options);
172
+ }
173
+ /**
174
+ * Завершает привязку почты кодом.
175
+ *
176
+ * Передайте тот же адрес и `flowToken` из {@link attach}.
177
+ */
178
+ verifyAttach(input, options = {}) {
179
+ return requestAccount(this.http, ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
180
+ }
181
+ /**
182
+ * Подтверждает код новой почты, запрошенный через {@link startChange}.
183
+ *
184
+ * @returns `changeToken` и способы завершить смену через `itd.account.changes`
185
+ */
186
+ verifyChange(input, options = {}) {
187
+ return requestAccount(this.http, ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
188
+ }
189
+ /** Повторно отправляет код на тот же адрес. Передайте `flowToken` из первого запроса. */
190
+ resendOtp(input, options = {}) {
191
+ return requestAccount(this.http, ACCOUNT_EMAIL_RESEND_OTP, "/resend-otp", input, options);
192
+ }
193
+ };
194
+ // src/resources/account/password.ts
195
+ /** Облачный пароль текущего аккаунта. */
196
+ var AccountPasswordResource = class extends require_render.BaseResource {
197
+ /**
198
+ * Создаёт облачный пароль для аккаунта без пароля.
199
+ *
200
+ * Наличие пароля можно проверить через `itd.account.getInfo()`.
201
+ */
202
+ set(password, options = {}) {
203
+ return requestAccount(this.http, ACCOUNT_PASSWORD_SET, "/set-password", { password }, options);
204
+ }
205
+ /**
206
+ * Меняет облачный пароль в действующей сессии.
207
+ *
208
+ * При неверном текущем пароле сервер возвращает `ACCOUNT_CURRENT_PASSWORD_INCORRECT`.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * await itd.account.password.change({ currentPassword, newPassword });
213
+ * ```
214
+ */
215
+ change({ currentPassword, newPassword }, options = {}) {
216
+ return this.voidOperation(ACCOUNT_PASSWORD_CHANGE, {
217
+ path: "/api/v1/auth/change-password",
218
+ body: {
219
+ currentPassword,
220
+ newPassword
221
+ },
222
+ ...options
223
+ });
224
+ }
225
+ };
226
+ // src/operations/phone-flow.ts
227
+ /** Приводит вложенные и плоские параметры доставки к одному результату. */
228
+ function readPhoneDelivery(body) {
229
+ const response = body;
230
+ const next = response.next ?? response.nextChannel;
231
+ return {
232
+ channel: response.delivery?.type ?? response.channel,
233
+ codeLength: response.delivery?.codeLength ?? response.codeLength,
234
+ retryIn: response.retryIn,
235
+ ...response.reverseOnly === true ? { reverseOnly: true } : {},
236
+ nextChannel: next ?? null
237
+ };
238
+ }
239
+ /** Извлекает `flowToken` и параметры доставки после запуска проверки номера. */
240
+ function readPhoneStart(body) {
241
+ const flowToken = require_url.pickString(body, "flowToken");
242
+ if (!flowToken) throw new require_validate.ItdConfigError("Сервер не вернул flowToken для проверки номера");
243
+ return {
244
+ ...readPhoneDelivery(body),
245
+ flowToken
246
+ };
247
+ }
248
+ // src/operations/account/phone.ts
249
+ const ACCOUNT_PHONE_ATTACH = require_url.defineBuiltInOperation("account.phone.attach", readPhoneStart);
250
+ const ACCOUNT_PHONE_START_CHANGE = require_url.defineBuiltInOperation("account.phone.startChange", readPhoneStart);
251
+ const ACCOUNT_PHONE_RESEND_OTP = require_url.defineBuiltInOperation("account.phone.resendOtp", readPhoneDelivery);
252
+ const ACCOUNT_PHONE_SYNC = require_url.passthroughOperation("account.phone.sync");
253
+ const ACCOUNT_PHONE_REVERSE_OPTIONS = require_url.passthroughOperation("account.phone.reverseOptions");
254
+ const ACCOUNT_PHONE_REVERSE_START = require_url.passthroughOperation("account.phone.reverseStart");
255
+ const ACCOUNT_PHONE_REVERSE_STATUS = require_url.passthroughOperation("account.phone.reverseStatus");
256
+ // src/resources/account/phone.ts
257
+ /** Привязка и смена номера текущего аккаунта. */
258
+ var AccountPhoneResource = class extends require_render.BaseResource {
259
+ #auth;
260
+ constructor(http, auth) {
261
+ super(http);
262
+ this.#auth = auth;
263
+ }
264
+ /**
265
+ * Запрашивает подтверждение номера для привязки.
266
+ *
267
+ * Передайте номер в международном формате с `+`. Если токен капчи не передан
268
+ * в вызов, SDK использует настроенный источник капчи.
269
+ * Для исходящего звонка передайте `method: PhoneVerificationMethod.Reverse`.
270
+ *
271
+ * @returns параметры доставки и `flowToken` для {@link verifyAttach}
272
+ *
273
+ * @example
274
+ * ```ts
275
+ * const { flowToken } = await itd.account.phone.attach({ phone });
276
+ * await itd.account.phone.verifyAttach({ phone, flowToken, otp: await getOtp() });
277
+ * ```
278
+ */
279
+ attach(input, options = {}) {
280
+ return this.#start(ACCOUNT_PHONE_ATTACH, "/phone/attach", input, options);
281
+ }
282
+ /**
283
+ * Запрашивает подтверждение нового номера для смены.
284
+ *
285
+ * Формат номера, источник капчи и выбор способа подтверждения такие же, как у {@link attach}.
286
+ *
287
+ * @returns параметры доставки и `flowToken` для {@link verifyChange}
288
+ */
289
+ startChange(input, options = {}) {
290
+ return this.#start(ACCOUNT_PHONE_START_CHANGE, "/phone/change", input, options);
291
+ }
292
+ /**
293
+ * Завершает привязку номера кодом.
294
+ *
295
+ * Передайте номер и `flowToken` из {@link attach}.
296
+ */
297
+ verifyAttach(input, options = {}) {
298
+ return this.#request(ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
299
+ }
300
+ /**
301
+ * Подтверждает код нового номера, запрошенный через {@link startChange}.
302
+ *
303
+ * @returns `changeToken` и способы завершить смену через `itd.account.changes`
304
+ */
305
+ verifyChange(input, options = {}) {
306
+ return this.#request(ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
307
+ }
308
+ /**
309
+ * Повторно запрашивает код для того же номера. Передайте `flowToken` из первого запроса.
310
+ *
311
+ * @returns актуальные канал, длину кода и паузу до повтора в секундах
312
+ */
313
+ resendOtp(input, options = {}) {
314
+ return this.#request(ACCOUNT_PHONE_RESEND_OTP, "/resend-otp", input, options);
315
+ }
316
+ /** Синхронизирует привязанный номер с профилем. */
317
+ sync(options = {}) {
318
+ return requestAccount(this.http, ACCOUNT_PHONE_SYNC, "/phone/sync", {}, options);
319
+ }
320
+ /** Возвращает доступность исходящего звонка для привязки или смены номера. */
321
+ reverseOptions(input, options = {}) {
322
+ return this.#request(ACCOUNT_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
323
+ }
324
+ /**
325
+ * Подготавливает номер, на который должен позвонить пользователь.
326
+ *
327
+ * @returns состояние попытки, номер для звонка и срок действия в секундах
328
+ */
329
+ reverseStart(input, options = {}) {
330
+ return this.#request(ACCOUNT_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
331
+ }
332
+ /**
333
+ * Читает состояние исходящего звонка.
334
+ *
335
+ * После подтверждения вызовите {@link reverseAttachComplete} при привязке
336
+ * или {@link reverseChangeComplete} при смене номера.
337
+ */
338
+ reverseStatus(input, options = {}) {
339
+ return this.#request(ACCOUNT_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
340
+ }
341
+ /** Завершает привязку номера после исходящего звонка. */
342
+ reverseAttachComplete(input, options = {}) {
343
+ return this.#request(ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE, "/phone/reverse/complete", input, options);
344
+ }
345
+ /** Подтверждает новый номер звонком и возвращает варианты завершения смены. */
346
+ reverseChangeComplete(input, options = {}) {
347
+ return this.#request(ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE, "/phone/reverse/complete", input, options);
348
+ }
349
+ /** Запускает проверку номера, если за время получения капчи сессия не сменилась. */
350
+ async #start(operation, path, { phone, captcha, method }, options) {
351
+ const revision = this.#auth.revision();
352
+ const proof = await this.#auth.captchaToken(captcha);
353
+ if (this.#auth.revision() !== revision) throw new require_validate.ItdStateError("Сессия сменилась во время получения капчи. Начните проверку номера заново.");
354
+ return this.#request(operation, path, {
355
+ phone,
356
+ captcha: proof ? {
357
+ provider: proof.type,
358
+ token: proof.token
359
+ } : void 0
360
+ }, {
361
+ ...options,
362
+ headers: {
363
+ ...options.headers,
364
+ ...method === PhoneVerificationMethod.Reverse ? { "X-ITD-Phone-Method": PhoneVerificationMethod.Reverse } : {}
365
+ }
366
+ });
367
+ }
368
+ /** Объявляет поддержку исходящего звонка и срока действия проверки номера. */
369
+ #request(operation, path, body, options) {
370
+ return requestAccount(this.http, operation, path, body, {
371
+ ...options,
372
+ headers: {
373
+ ...options.headers,
374
+ "X-ITD-Phone-Reverse": "1",
375
+ "X-ITD-Flow-Expiry": "1",
376
+ ...path.startsWith("/phone/reverse/") ? { "X-ITD-Reverse-Attempts": "1" } : {}
377
+ }
378
+ });
379
+ }
380
+ };
381
+ // src/resources/account.ts
382
+ /**
383
+ * Настройки текущего аккаунта. Доступен как `itd.account`.
384
+ *
385
+ * Здесь можно менять номер, почту и облачный пароль, управлять отложенными
386
+ * заявками, деактивировать и восстановить аккаунт.
387
+ */
388
+ var AccountResource = class extends require_render.AccountLifecycleResource {
389
+ /** Привязка и смена номера. */
390
+ phone;
391
+ /** Привязка и смена почты. */
392
+ email;
393
+ /** Настройка облачного пароля. */
394
+ password;
395
+ /** Завершение смены номера или почты и отложенные заявки. */
396
+ changes;
397
+ constructor(http, auth) {
398
+ super(http);
399
+ this.phone = new AccountPhoneResource(http, auth);
400
+ this.email = new AccountEmailResource(http);
401
+ this.password = new AccountPasswordResource(http);
402
+ this.changes = new AccountChangesResource(http);
403
+ }
404
+ /**
405
+ * Получает сведения о доступе к текущему аккаунту.
406
+ *
407
+ * @returns привязанные номер и почту и признак наличия облачного пароля
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * const { email, phone, hasPassword } = await itd.account.getInfo();
412
+ * ```
413
+ */
414
+ getInfo(options = {}) {
415
+ return requestAccount(this.http, ACCOUNT_GET_INFO, "/methods", void 0, options);
416
+ }
417
+ };
418
+ // src/operations/auth.ts
30
419
  /** Чем закончился запрос входа. */
31
420
  const SignInStatus = Object.freeze({
32
421
  Authenticated: "authenticated",
@@ -62,8 +451,8 @@ function requireString(body, key, message) {
62
451
  return value;
63
452
  }
64
453
  const AUTH_CHECK = require_url.passthroughOperation("auth.check");
65
- require_url.passthroughOperation("auth.captchaProvider");
66
- require_url.passthroughOperation("auth.captchaPage");
454
+ const AUTH_CAPTCHA_PROVIDER = require_url.passthroughOperation("auth.captchaProvider");
455
+ const AUTH_CAPTCHA_PAGE = require_url.passthroughOperation("auth.captchaPage");
67
456
  const AUTH_SIGN_UP = require_url.defineBuiltInOperation("auth.signUp", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при регистрации"));
68
457
  const AUTH_SIGN_IN = require_url.defineBuiltInOperation("auth.signIn", (body) => {
69
458
  const accessToken = require_url.pickString(body, "accessToken");
@@ -81,7 +470,6 @@ const AUTH_RESEND_OTP = require_url.voidOperation("auth.resendOtp");
81
470
  const AUTH_LOGOUT = require_url.voidOperation("auth.logout");
82
471
  const AUTH_FORGOT_PASSWORD = require_url.defineBuiltInOperation("auth.forgotPassword", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при запросе сброса пароля"));
83
472
  const AUTH_RESET_PASSWORD = require_url.voidOperation("auth.resetPassword");
84
- const AUTH_CHANGE_PASSWORD = require_url.voidOperation("auth.changePassword");
85
473
  const AUTH_SESSIONS = require_url.defineBuiltInOperation("auth.sessions", (body) => require_url.pickArray(body, "sessions"));
86
474
  const AUTH_REVOKE_SESSION = require_url.voidOperation("auth.revokeSession");
87
475
  const AUTH_REVOKE_OTHER_SESSIONS = require_url.voidOperation("auth.revokeOtherSessions");
@@ -90,8 +478,7 @@ const AUTH_QR_CLAIM = require_url.passthroughOperation("auth.qrClaim");
90
478
  const AUTH_QR_SCAN = require_url.passthroughOperation("auth.qrScan");
91
479
  const AUTH_QR_APPROVE = require_url.voidOperation("auth.qrApprove");
92
480
  const AUTH_QR_REJECT = require_url.voidOperation("auth.qrReject");
93
- //#endregion
94
- //#region src/session/captcha.ts
481
+ // src/session/captcha.ts
95
482
  function requireCaptchaText(value, field) {
96
483
  if (value !== void 0 && (typeof value !== "string" || value.trim() === "")) throw new require_validate.ItdConfigError(`${field} должен быть непустой строкой`);
97
484
  }
@@ -127,6 +514,17 @@ function validateCaptchaToken(captcha, path) {
127
514
  if (typeof type !== "string" || type.trim() === "") throw new require_validate.ItdConfigError(`${path}.type должен быть непустой строкой`);
128
515
  requireCaptchaText(field, `${path}.field`);
129
516
  }
517
+ /** Разбирает ответ `GET /api/v1/auth/captcha/provider` для автоматического входа. */
518
+ function readCaptchaProvider(body) {
519
+ const config = require_validate.isRecord(body) ? body : void 0;
520
+ const provider = config?.provider;
521
+ const field = config?.field;
522
+ if (typeof provider !== "string" || provider.trim() === "" || typeof field !== "string" || field.trim() === "") throw new require_validate.ItdConfigError("Сервер вернул неподдерживаемую конфигурацию капчи");
523
+ return {
524
+ provider,
525
+ field
526
+ };
527
+ }
130
528
  /** Куда класть токен: настройка, иначе умолчание провайдера. */
131
529
  function resolveField(type, configured) {
132
530
  const field = configured ?? CAPTCHA_FIELDS[type];
@@ -139,37 +537,30 @@ async function requireSolvedToken(solver, type, context) {
139
537
  if (typeof token === "string" && token.trim() !== "") return token;
140
538
  throw new require_validate.ItdConfigError(`Источник капчи не вернул токен для провайдера «${type}». Проверьте captcha.getToken.`);
141
539
  }
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) {
540
+ /** Сохраняет провайдера и токен для API, принимающих доказательство капчи объектом. */
541
+ async function solveCaptchaToken(solver, askProvider, context) {
153
542
  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) };
543
+ const { provider, field } = choice === require_url.CaptchaChoice.Auto ? await askProvider() : {
544
+ provider: choice,
545
+ field: solver.field
546
+ };
547
+ return {
548
+ type: provider,
549
+ field,
550
+ token: await requireSolvedToken(solver, provider, context)
551
+ };
159
552
  }
160
553
  /**
161
554
  * Готовит фрагмент тела из готового токена.
162
555
  *
163
556
  * Поле берётся из самого токена либо из умолчания провайдера; запроса к серверу нет.
164
557
  *
165
- * @throws {ItdConfigError} если токен или его тип не указаны
558
+ * @throws {ItdConfigError} если для провайдера не определено поле запроса
166
559
  */
167
560
  function captchaBody(captcha) {
168
- validateCaptchaToken(captcha, "captcha");
169
561
  return { [resolveField(captcha.type, captcha.field)]: captcha.token };
170
562
  }
171
- //#endregion
172
- //#region src/session/jwt.ts
563
+ // src/session/jwt.ts
173
564
  /**
174
565
  * Разбирает строку base64url.
175
566
  *
@@ -208,8 +599,7 @@ function readTokenMetadata(token) {
208
599
  ...expiresAt !== void 0 && Number.isFinite(expiresAt) ? { expiresAt } : {}
209
600
  };
210
601
  }
211
- //#endregion
212
- //#region src/session/auth.ts
602
+ // src/session/auth.ts
213
603
  /** Запас до истечения токена на очередь и выполнение запроса. */
214
604
  const ACCESS_TOKEN_REFRESH_LEEWAY_MS = 3e4;
215
605
  /**
@@ -301,7 +691,6 @@ const AUTH_PATHS = {
301
691
  logout: "/api/v1/auth/logout",
302
692
  forgotPassword: "/api/v1/auth/forgot-password",
303
693
  resetPassword: "/api/v1/auth/reset-password",
304
- changePassword: "/api/v1/auth/change-password",
305
694
  sessions: "/api/v1/auth/sessions",
306
695
  qrStart: "/api/v1/auth/qr/start",
307
696
  qrClaim: "/api/v1/auth/qr/claim",
@@ -993,13 +1382,20 @@ var AuthManager = class {
993
1382
  * @throws {ItdConfigError} если токен неполный или источник его не вернул
994
1383
  */
995
1384
  async captchaBody(explicit) {
996
- if (explicit) return captchaBody(explicit);
1385
+ const token = await this.captchaToken(explicit);
1386
+ return token ? captchaBody(token) : {};
1387
+ }
1388
+ /** Доказательство капчи с провайдером для телефонного API. @internal */
1389
+ async captchaToken(explicit) {
1390
+ if (explicit) {
1391
+ validateCaptchaToken(explicit, "captcha");
1392
+ return explicit;
1393
+ }
997
1394
  const configured = this.#takeConfiguredCaptcha();
998
- if (configured) return captchaBody(configured);
1395
+ if (configured) return configured;
999
1396
  const solver = this.#config.captcha;
1000
- if (solver) return solveCaptchaBody(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
1397
+ if (solver) return solveCaptchaToken(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
1001
1398
  this.#config.logger?.debug("Запрос уходит без токена капчи: не передан аргумент captcha и не задана опция captcha");
1002
- return {};
1003
1399
  }
1004
1400
  /** Отдаёт разовый токен из `auth.captcha`, помечая его потраченным. */
1005
1401
  #takeConfiguredCaptcha() {
@@ -1012,10 +1408,22 @@ var AuthManager = class {
1012
1408
  }
1013
1409
  /** Спрашивает у сервера активного провайдера и поле, в котором он ждёт токен. */
1014
1410
  async #resolveCaptchaProvider() {
1015
- return {
1016
- provider: require_url.CaptchaType.Cloudflare,
1017
- field: require_url.CaptchaField.Cloudflare
1018
- };
1411
+ try {
1412
+ return readCaptchaProvider(await this.#http.execute(AUTH_CAPTCHA_PROVIDER, {
1413
+ path: AUTH_PATHS.captchaProvider,
1414
+ skipAuth: true,
1415
+ skipAuthRefresh: true
1416
+ }));
1417
+ } catch (error) {
1418
+ if (require_validate.isItdApiError(error) && error.status === 404 && error.code === require_url.ItdErrorCode.NOT_FOUND) {
1419
+ this.#config.logger?.warn("Сервер отключил определение провайдера капчи; используется Cloudflare Turnstile");
1420
+ return {
1421
+ provider: require_url.CaptchaType.Cloudflare,
1422
+ field: require_url.CaptchaField.Cloudflare
1423
+ };
1424
+ }
1425
+ throw error;
1426
+ }
1019
1427
  }
1020
1428
  async #performSignIn(credentials, revision) {
1021
1429
  const captcha = await this.captchaBody();
@@ -1054,8 +1462,7 @@ var AuthManager = class {
1054
1462
  return userId ? `: пользователь ${userId}` : "";
1055
1463
  }
1056
1464
  };
1057
- //#endregion
1058
- //#region src/session/qr-stream.ts
1465
+ // src/session/qr-stream.ts
1059
1466
  const QR_STREAM_STATUSES = new Set(Object.values(QrLoginStreamStatus));
1060
1467
  function readQrLoginStreamEvent(data) {
1061
1468
  let value;
@@ -1171,8 +1578,214 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
1171
1578
  abort.cleanup();
1172
1579
  }
1173
1580
  }
1174
- //#endregion
1175
- //#region src/resources/auth.ts
1581
+ // src/operations/auth/phone.ts
1582
+ /** Отклоняет неизвестный контракт до принятия результата входа. */
1583
+ function invalidResponse() {
1584
+ throw new require_validate.ItdConfigError("Сервер вернул неподдерживаемый ответ телефонного входа");
1585
+ }
1586
+ /** Требует непустой секрет для продолжения телефонного потока. */
1587
+ function readFlowToken(body) {
1588
+ const value = require_url.pickString(body, "flowToken");
1589
+ if (!value) return invalidResponse();
1590
+ return value;
1591
+ }
1592
+ /** Разделяет access token и шаг пароля; режимы привязки/смены контакта не принимает. */
1593
+ function readLoginResult(body) {
1594
+ if (!require_validate.isRecord(body)) return invalidResponse();
1595
+ if (body.mode !== void 0 && body.mode !== AuthVerificationMode.SignIn) return invalidResponse();
1596
+ const accessToken = require_url.pickString(body, "accessToken");
1597
+ if (accessToken) return { accessToken };
1598
+ if (body.step === PhoneLoginStep.Password) return {
1599
+ step: PhoneLoginStep.Password,
1600
+ flowToken: readFlowToken(body)
1601
+ };
1602
+ return invalidResponse();
1603
+ }
1604
+ /** Для завершения по паролю промежуточный шаг вместо access token недопустим. */
1605
+ function readAccessToken(body) {
1606
+ const result = readLoginResult(body);
1607
+ if (!("accessToken" in result)) return invalidResponse();
1608
+ return result.accessToken;
1609
+ }
1610
+ const AUTH_PHONE_CONFIG = require_url.passthroughOperation("auth.phone.config");
1611
+ const AUTH_PHONE_CONSENT = require_url.passthroughOperation("auth.phone.consent");
1612
+ const AUTH_PHONE_START = require_url.defineBuiltInOperation("auth.phone.start", readPhoneStart);
1613
+ const AUTH_PHONE_RESUME = require_url.defineBuiltInOperation("auth.phone.resume", (body) => ({
1614
+ ...readPhoneDelivery(body),
1615
+ expiresIn: body.expiresIn
1616
+ }));
1617
+ const AUTH_PHONE_VERIFY = require_url.defineBuiltInOperation("auth.phone.verify", readLoginResult);
1618
+ const AUTH_PHONE_PASSWORD = require_url.defineBuiltInOperation("auth.phone.password", readAccessToken);
1619
+ const AUTH_PHONE_RESET_PASSWORD = require_url.defineBuiltInOperation("auth.phone.resetPassword", readAccessToken);
1620
+ const AUTH_PHONE_RESEND = require_url.defineBuiltInOperation("auth.phone.resend", readPhoneDelivery);
1621
+ const AUTH_PHONE_REVERSE_OPTIONS = require_url.passthroughOperation("auth.phone.reverseOptions");
1622
+ const AUTH_PHONE_REVERSE_START = require_url.passthroughOperation("auth.phone.reverseStart");
1623
+ const AUTH_PHONE_REVERSE_STATUS = require_url.passthroughOperation("auth.phone.reverseStatus");
1624
+ const AUTH_PHONE_REVERSE_COMPLETE = require_url.defineBuiltInOperation("auth.phone.reverseComplete", readLoginResult);
1625
+ // src/resources/auth/phone.ts
1626
+ /** Телефонный вход и регистрация. Доступен как `itd.auth.phone`. */
1627
+ var PhoneAuthResource = class extends require_render.BaseResource {
1628
+ #auth;
1629
+ constructor(http, deps) {
1630
+ super(http);
1631
+ this.#auth = deps.auth;
1632
+ }
1633
+ /** Разрешённые регионы, примеры номеров и доступные способы подтверждения. */
1634
+ config(options = {}) {
1635
+ return this.#request(AUTH_PHONE_CONFIG, "/phone/config", void 0, options);
1636
+ }
1637
+ /**
1638
+ * Загружает контекст phone_entry вместе с текстом и редакциями документов.
1639
+ *
1640
+ * До start() покажите документы пользователю. Истёкший контекст и новые редакции
1641
+ * библиотека не заменяет автоматически.
1642
+ */
1643
+ consent(options = {}) {
1644
+ return this.#request(AUTH_PHONE_CONSENT, `/consent?flow=${PHONE_CONSENT_FLOW}`, void 0, options);
1645
+ }
1646
+ /**
1647
+ * Запрашивает подтверждение номера для входа или регистрации.
1648
+ *
1649
+ * Токен капчи отправляется объектом { provider, token }.
1650
+ *
1651
+ * @returns `flowToken` для продолжения входа, канал доставки, длина кода и пауза повтора в секундах
1652
+ */
1653
+ async start(input, options = {}) {
1654
+ const captcha = await this.#auth.captchaToken(input.captcha);
1655
+ return this.#request(AUTH_PHONE_START, "/phone/start", {
1656
+ phone: input.phone,
1657
+ captcha: captcha ? {
1658
+ provider: captcha.type,
1659
+ token: captcha.token
1660
+ } : void 0,
1661
+ legal: {
1662
+ protocolVersion: input.consent.protocolVersion,
1663
+ contextToken: input.consent.contextToken
1664
+ }
1665
+ }, {
1666
+ ...options,
1667
+ headers: {
1668
+ ...options.headers,
1669
+ ...input.method === PhoneVerificationMethod.Reverse ? { "X-ITD-Phone-Method": PhoneVerificationMethod.Reverse } : {}
1670
+ }
1671
+ });
1672
+ }
1673
+ /**
1674
+ * Возобновляет незавершённую проверку номера.
1675
+ *
1676
+ * Передайте номер и `flowToken` из {@link start}. Для следующих шагов используйте тот же
1677
+ * токен и параметры доставки из ответа.
1678
+ */
1679
+ resume({ phone, flowToken }, options = {}) {
1680
+ return this.http.execute(AUTH_PHONE_RESUME, {
1681
+ ...options,
1682
+ path: "/api/v1/auth/phone/resume",
1683
+ body: {
1684
+ phone,
1685
+ flowToken
1686
+ },
1687
+ redirect: "error",
1688
+ skipAuth: true,
1689
+ skipAuthRefresh: true,
1690
+ headers: {
1691
+ ...options.headers,
1692
+ "X-ITD-Phone-Resume": "1"
1693
+ }
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Подтверждает код без email и пароля.
1698
+ *
1699
+ * При accessToken сохраняет новую сессию; при step: 'password' возвращает секрет
1700
+ * для password().
1701
+ */
1702
+ verify(input, options = {}) {
1703
+ return this.#complete(AUTH_PHONE_VERIFY, "/verify-otp", input, options);
1704
+ }
1705
+ /**
1706
+ * Запрашивает повторную доставку без изменения авторизации.
1707
+ *
1708
+ * Используйте новый channel/codeLength из результата: способ доставки может измениться.
1709
+ * retryIn — секунды до следующего запроса.
1710
+ */
1711
+ resend(input, options = {}) {
1712
+ return this.#request(AUTH_PHONE_RESEND, "/resend-otp", input, options);
1713
+ }
1714
+ /**
1715
+ * Завершает вход облачным паролем после step: 'password'.
1716
+ *
1717
+ * Передайте flowToken из этого шага. Полученный access token и cookies сохраняются
1718
+ * автоматически, если владелец сессии не сменился во время запроса.
1719
+ */
1720
+ password(input, options = {}) {
1721
+ return this.#authenticate(AUTH_PHONE_PASSWORD, "/phone/password", input, options);
1722
+ }
1723
+ /** Устанавливает новый пароль после подтверждения номера и сохраняет сессию. */
1724
+ resetPassword(input, options = {}) {
1725
+ return this.#authenticate(AUTH_PHONE_RESET_PASSWORD, "/phone/reset-password", input, options);
1726
+ }
1727
+ /** Проверяет, доступен ли исходящий звонок для подтверждения номера. */
1728
+ reverseOptions(input, options = {}) {
1729
+ return this.#request(AUTH_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
1730
+ }
1731
+ /**
1732
+ * Подготавливает номер, на который пользователь должен позвонить.
1733
+ *
1734
+ * Может выделить новую попытку; не повторяется после сетевых ошибок и 5xx. Номер и срок
1735
+ * его действия возвращаются в phone и expiresIn.
1736
+ */
1737
+ reverseStart(input, options = {}) {
1738
+ return this.#request(AUTH_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
1739
+ }
1740
+ /** Читает состояние звонка через POST, без завершения входа и смены сессии. */
1741
+ reverseStatus(input, options = {}) {
1742
+ return this.#request(AUTH_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
1743
+ }
1744
+ /** Завершает подтверждённый звонок; сервер может потребовать облачный пароль. */
1745
+ reverseComplete(input, options = {}) {
1746
+ return this.#complete(AUTH_PHONE_REVERSE_COMPLETE, "/phone/reverse/complete", input, options);
1747
+ }
1748
+ /** Применяет cookies промежуточного шага либо атомарно сохраняет завершённый вход. */
1749
+ async #complete(operation, path, input, options) {
1750
+ const revision = this.#auth.revision();
1751
+ const cookies = this.#auth.createCookieFlow();
1752
+ const result = await this.#request(operation, path, input, options, cookies);
1753
+ if ("accessToken" in result) await this.#auth.commitAuthFlow(result.accessToken, cookies, revision);
1754
+ else this.#auth.commitCookieFlow(cookies, revision);
1755
+ return result;
1756
+ }
1757
+ /** Сохраняет результат пароля, не позволяя запоздалому ответу сменить нового владельца. */
1758
+ async #authenticate(operation, path, input, options) {
1759
+ const revision = this.#auth.revision();
1760
+ const cookies = this.#auth.createCookieFlow();
1761
+ const token = await this.#request(operation, path, input, options, cookies);
1762
+ await this.#auth.commitAuthFlow(token, cookies, revision);
1763
+ return token;
1764
+ }
1765
+ /**
1766
+ * Выполняет телефонный запрос без Bearer/refresh через общий pipeline.
1767
+ * X-ITD-Phone-Reverse объявляет поддержку исходящего звонка, в том числе при запросе кода.
1768
+ */
1769
+ #request(operation, path, body, options, cookies) {
1770
+ return this.http.execute(operation, {
1771
+ ...options,
1772
+ path: `/api/v1/auth${path}`,
1773
+ body,
1774
+ ...cookies ? { cookieJar: cookies } : {},
1775
+ skipAuth: true,
1776
+ skipAuthRefresh: true,
1777
+ headers: {
1778
+ ...options.headers,
1779
+ ...operation.method === "POST" ? {
1780
+ "X-ITD-Phone-Reverse": "1",
1781
+ "X-ITD-Flow-Expiry": "1"
1782
+ } : {},
1783
+ ...path.startsWith("/phone/reverse/") ? { "X-ITD-Reverse-Attempts": "1" } : {}
1784
+ }
1785
+ });
1786
+ }
1787
+ };
1788
+ // src/resources/auth.ts
1176
1789
  /**
1177
1790
  * Результат входа.
1178
1791
  *
@@ -1185,6 +1798,8 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
1185
1798
  * Доступна как `itd.auth`.
1186
1799
  */
1187
1800
  var AuthResource = class extends require_render.BaseResource {
1801
+ /** Вход и регистрация по номеру телефона. */
1802
+ phone;
1188
1803
  #auth;
1189
1804
  #connection;
1190
1805
  #qrFlows = /* @__PURE__ */ new Map();
@@ -1192,6 +1807,7 @@ var AuthResource = class extends require_render.BaseResource {
1192
1807
  super(http);
1193
1808
  this.#auth = deps.auth;
1194
1809
  this.#connection = deps.connection;
1810
+ this.phone = new PhoneAuthResource(http, deps);
1195
1811
  }
1196
1812
  #pruneQrFlows() {
1197
1813
  const now = this.#connection.clock.now();
@@ -1233,13 +1849,13 @@ var AuthResource = class extends require_render.BaseResource {
1233
1849
  *
1234
1850
  * Сервер может переключить провайдера или переименовать поле без выпуска новой версии SDK.
1235
1851
  * Автоматическому входу этот вызов не нужен — клиент делает его сам.
1236
- *
1237
- * @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile.
1238
1852
  */
1239
- captchaProvider(_options = {}) {
1240
- return Promise.resolve({
1241
- provider: require_url.CaptchaType.Cloudflare,
1242
- field: CAPTCHA_FIELDS[require_url.CaptchaType.Cloudflare]
1853
+ captchaProvider(options = {}) {
1854
+ return this.http.execute(AUTH_CAPTCHA_PROVIDER, {
1855
+ path: AUTH_PATHS.captchaProvider,
1856
+ skipAuth: true,
1857
+ skipAuthRefresh: true,
1858
+ ...options
1243
1859
  });
1244
1860
  }
1245
1861
  /**
@@ -1248,14 +1864,14 @@ var AuthResource = class extends require_render.BaseResource {
1248
1864
  * То же, что {@link captchaProvider}, плюс `url` — готовая страница на домене итд.com,
1249
1865
  * где ключ виджета действителен. Пригодится встроенному браузеру: открыть её и забрать
1250
1866
  * токен, ничего не собирая самому.
1251
- *
1252
- * @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile на домене итд.com.
1253
1867
  */
1254
- async captchaPage(options = {}) {
1255
- return {
1256
- ...await this.captchaProvider(options),
1257
- url: require_url.DEFAULT_BASE_URL
1258
- };
1868
+ captchaPage(options = {}) {
1869
+ return this.http.execute(AUTH_CAPTCHA_PAGE, {
1870
+ path: AUTH_PATHS.captchaPage,
1871
+ skipAuth: true,
1872
+ skipAuthRefresh: true,
1873
+ ...options
1874
+ });
1259
1875
  }
1260
1876
  /** Создаёт короткоживущую сессию QR-входа. */
1261
1877
  async startQrLogin(options = {}) {
@@ -1383,6 +1999,7 @@ var AuthResource = class extends require_render.BaseResource {
1383
1999
  * Регистрирует аккаунт и запускает подтверждение по коду.
1384
2000
  *
1385
2001
  * @returns `flowToken`, который нужно передать в {@link verifyOtp}
2002
+ * @deprecated Регистрация по email отключена. Используйте auth.phone.start().
1386
2003
  */
1387
2004
  async signUp(credentials, options = {}) {
1388
2005
  const { captcha, ...rest } = credentials;
@@ -1599,26 +2216,6 @@ var AuthResource = class extends require_render.BaseResource {
1599
2216
  newPassword
1600
2217
  }, options);
1601
2218
  }
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
2219
  /** Загружает список активных сессий. У текущей поле `isCurrent` равно `true`. */
1623
2220
  sessions(options = {}) {
1624
2221
  return this.http.execute(AUTH_SESSIONS, {
@@ -1641,8 +2238,7 @@ var AuthResource = class extends require_render.BaseResource {
1641
2238
  });
1642
2239
  }
1643
2240
  };
1644
- //#endregion
1645
- //#region src/client.ts
2241
+ // src/client.ts
1646
2242
  const CLIENT_PLUGIN_REGISTRIES = /* @__PURE__ */ new WeakMap();
1647
2243
  const DISPOSED_CLIENTS = /* @__PURE__ */ new WeakSet();
1648
2244
  function assertClientActive(client, action) {
@@ -1706,6 +2302,7 @@ var ItdClient = class ItdClient {
1706
2302
  #resources;
1707
2303
  /** Сессионный ресурс живёт у фасада: он управляет входом и продлением. */
1708
2304
  #auth;
2305
+ #account;
1709
2306
  /** Авторизация, сессии и пароли. */
1710
2307
  get auth() {
1711
2308
  this.#auth ??= new AuthResource(this.#runtime.http, {
@@ -1714,6 +2311,11 @@ var ItdClient = class ItdClient {
1714
2311
  });
1715
2312
  return this.#auth;
1716
2313
  }
2314
+ /** Настройки текущего аккаунта и управление его состоянием. */
2315
+ get account() {
2316
+ this.#account ??= new AccountResource(this.#runtime.http, this.#runtime.auth);
2317
+ return this.#account;
2318
+ }
1717
2319
  /** Профили, подписки, блокировки, приватность. */
1718
2320
  get users() {
1719
2321
  return this.#resources.users;
@@ -1754,6 +2356,10 @@ var ItdClient = class ItdClient {
1754
2356
  get subscription() {
1755
2357
  return this.#resources.subscription;
1756
2358
  }
2359
+ /** Публичные документы ИТД и история их редакций. */
2360
+ get legal() {
2361
+ return this.#resources.legal;
2362
+ }
1757
2363
  /** Сведения о платформе: версии приложений, изменения, анонсы, баннер события. */
1758
2364
  get platform() {
1759
2365
  return this.#resources.platform;
@@ -2157,8 +2763,7 @@ var ItdClient = class ItdClient {
2157
2763
  function createClient(options = {}) {
2158
2764
  return new ItdClient(options);
2159
2765
  }
2160
- //#endregion
2161
- //#region src/accounts.ts
2766
+ // src/accounts.ts
2162
2767
  /** Как аккаунты делят между собой очередь запросов. */
2163
2768
  const RateLimitScope = Object.freeze({
2164
2769
  /** У каждого аккаунта своя очередь. */
@@ -2627,17 +3232,31 @@ var ItdAccounts = class ItdAccounts {
2627
3232
  function createAccounts(options = {}) {
2628
3233
  return new ItdAccounts(options);
2629
3234
  }
2630
- //#endregion
3235
+ // src/models/account-access.ts
3236
+ /** Способ подтверждения смены номера или почты. */
3237
+ const ContactProofMethod = Object.freeze({
3238
+ Password: "password",
3239
+ EmailCode: "email_code",
3240
+ PhoneCode: "phone_code"
3241
+ });
3242
+ /** Что меняет отложенная заявка: номер или почту. */
3243
+ const ContactKind = Object.freeze({
3244
+ Email: "email",
3245
+ Phone: "phone"
3246
+ });
2631
3247
  exports.ALLOWED_MIME_TYPES = require_render.ALLOWED_MIME_TYPES;
2632
3248
  exports.AUDIO_MIME_TYPES = require_render.AUDIO_MIME_TYPES;
2633
3249
  exports.AccessType = require_url.AccessType;
2634
3250
  exports.AttachmentType = require_url.AttachmentType;
2635
3251
  exports.BUCKET_LIMITS = require_url.BUCKET_LIMITS;
3252
+ exports.BannerDrawingTool = require_render.BannerDrawingTool;
2636
3253
  exports.CAPTCHA_FIELDS = CAPTCHA_FIELDS;
2637
3254
  exports.CaptchaChoice = require_url.CaptchaChoice;
2638
3255
  exports.CaptchaField = require_url.CaptchaField;
2639
3256
  exports.CaptchaType = require_url.CaptchaType;
2640
3257
  exports.CommentSort = require_url.CommentSort;
3258
+ exports.ContactKind = ContactKind;
3259
+ exports.ContactProofMethod = ContactProofMethod;
2641
3260
  exports.DEFAULT_BASE_URL = require_url.DEFAULT_BASE_URL;
2642
3261
  exports.DEFAULT_RATE_LIMIT_BUCKET = require_url.DEFAULT_RATE_LIMIT_BUCKET;
2643
3262
  exports.EventChannel = require_events.EventChannel;
@@ -2673,6 +3292,8 @@ exports.ItdTimeoutError = require_validate.ItdTimeoutError;
2673
3292
  exports.ItdValidationError = require_validate.ItdValidationError;
2674
3293
  exports.LIBRARY_VERSION = require_url.LIBRARY_VERSION;
2675
3294
  exports.LastSeenUnit = require_url.LastSeenUnit;
3295
+ exports.LegalDocumentBlockType = require_render.LegalDocumentBlockType;
3296
+ exports.LegalDocumentScope = require_render.LegalDocumentScope;
2676
3297
  exports.LikesVisibility = require_url.LikesVisibility;
2677
3298
  exports.LogLevel = require_redact.LogLevel;
2678
3299
  exports.MemoryKeyValueStore = require_key_value_store.MemoryKeyValueStore;
@@ -2690,6 +3311,10 @@ exports.OPERATIONS = require_url.OPERATIONS;
2690
3311
  exports.OperationMethod = require_url.OperationMethod;
2691
3312
  exports.PaginationMode = require_render.PaginationMode;
2692
3313
  exports.Paginator = require_render.Paginator;
3314
+ exports.PhoneDeliveryChannel = PhoneDeliveryChannel;
3315
+ exports.PhoneLoginStep = PhoneLoginStep;
3316
+ exports.PhoneReverseState = PhoneReverseState;
3317
+ exports.PhoneVerificationMethod = PhoneVerificationMethod;
2693
3318
  exports.QrLocationPrecision = require_url.QrLocationPrecision;
2694
3319
  exports.QrLoginStatus = QrLoginStatus;
2695
3320
  exports.QrLoginStreamStatus = QrLoginStreamStatus;