itd-api 0.0.5 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -1
- package/dist/{chunk-RUPF4X5L.js → chunk-CCRQI3ON.js} +182 -7
- package/dist/chunk-CCRQI3ON.js.map +1 -0
- package/dist/{chunk-YM2YUO4D.cjs → chunk-K7NBFQEE.cjs} +182 -6
- package/dist/chunk-K7NBFQEE.cjs.map +1 -0
- package/dist/{index-Dv0LXpMf.d.cts → index-CDGXKy8r.d.cts} +178 -7
- package/dist/{index-Dv0LXpMf.d.ts → index-CDGXKy8r.d.ts} +178 -7
- package/dist/index.cjs +88 -84
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/node.cjs +87 -83
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/node.js +2 -2
- package/package.json +5 -4
- package/dist/chunk-RUPF4X5L.js.map +0 -1
- package/dist/chunk-YM2YUO4D.cjs.map +0 -1
|
@@ -97,6 +97,39 @@ declare const AttachmentType: Readonly<{
|
|
|
97
97
|
readonly Audio: "audio";
|
|
98
98
|
}>;
|
|
99
99
|
type AttachmentType = (typeof AttachmentType)[keyof typeof AttachmentType];
|
|
100
|
+
/**
|
|
101
|
+
* Тип фрагмента разметки в тексте поста или комментария.
|
|
102
|
+
*
|
|
103
|
+
* Первые два сервер расставляет сам при разборе текста, остальные приходят от редактора.
|
|
104
|
+
* Тип открытый: набор может пополниться.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* await itd.posts.update(postId, {
|
|
109
|
+
* content: 'жирное слово',
|
|
110
|
+
* spans: [{ type: SpanType.Bold, offset: 0, length: 6 }],
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
declare const SpanType: Readonly<{
|
|
115
|
+
/** Хэштег. Название без решётки лежит в `tag`. */
|
|
116
|
+
readonly Hashtag: "hashtag";
|
|
117
|
+
/** Упоминание. Имя пользователя лежит в `tag`. */
|
|
118
|
+
readonly Mention: "mention";
|
|
119
|
+
/** Ссылка. Адрес лежит в `url`, а не в `tag`. */
|
|
120
|
+
readonly Link: "link";
|
|
121
|
+
readonly Bold: "bold";
|
|
122
|
+
readonly Italic: "italic";
|
|
123
|
+
readonly Underline: "underline";
|
|
124
|
+
/** Зачёркнутый. */
|
|
125
|
+
readonly Strike: "strike";
|
|
126
|
+
/** Спойлер: текст скрыт до нажатия. */
|
|
127
|
+
readonly Spoiler: "spoiler";
|
|
128
|
+
/** Моноширинный. */
|
|
129
|
+
readonly Monospace: "monospace";
|
|
130
|
+
readonly Quote: "quote";
|
|
131
|
+
}>;
|
|
132
|
+
type SpanType = Loose<(typeof SpanType)[keyof typeof SpanType]>;
|
|
100
133
|
/** На что подаётся жалоба. */
|
|
101
134
|
declare const ReportTargetType: Readonly<{
|
|
102
135
|
readonly Post: "post";
|
|
@@ -264,14 +297,16 @@ type UserRef = string;
|
|
|
264
297
|
* поэтому при работе с эмодзи проверяйте результат.
|
|
265
298
|
*/
|
|
266
299
|
interface Span {
|
|
267
|
-
/** Тип
|
|
268
|
-
type:
|
|
300
|
+
/** Тип фрагмента — см. {@link SpanType}. */
|
|
301
|
+
type: SpanType;
|
|
269
302
|
/** Смещение от начала текста. */
|
|
270
303
|
offset: number;
|
|
271
304
|
/** Длина фрагмента. */
|
|
272
305
|
length: number;
|
|
273
|
-
/**
|
|
306
|
+
/** Имя хэштега без решётки либо имя пользователя. */
|
|
274
307
|
tag?: string;
|
|
308
|
+
/** Адрес ссылки. Только у `link`: у него вместо `tag` отдельное поле. */
|
|
309
|
+
url?: string;
|
|
275
310
|
}
|
|
276
311
|
/**
|
|
277
312
|
* Значок-«пин» в профиле — награда или отметка платформы.
|
|
@@ -1439,7 +1474,7 @@ declare const DEFAULT_TIMEOUT = 30000;
|
|
|
1439
1474
|
/**
|
|
1440
1475
|
* Версия библиотеки — попадает в `User-Agent`.
|
|
1441
1476
|
*/
|
|
1442
|
-
declare const LIBRARY_VERSION = "0.0.
|
|
1477
|
+
declare const LIBRARY_VERSION = "0.0.6";
|
|
1443
1478
|
/**
|
|
1444
1479
|
* `User-Agent` по умолчанию.
|
|
1445
1480
|
*
|
|
@@ -1450,7 +1485,7 @@ declare const LIBRARY_VERSION = "0.0.5";
|
|
|
1450
1485
|
* В браузере заголовок не выставляется — `User-Agent` там запрещён к изменению, и среда
|
|
1451
1486
|
* молча его игнорирует.
|
|
1452
1487
|
*/
|
|
1453
|
-
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.0.
|
|
1488
|
+
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.0.6; +https://github.com/KiowDev/itd-api)";
|
|
1454
1489
|
/**
|
|
1455
1490
|
* Настройки повторов со всеми значениями по умолчанию.
|
|
1456
1491
|
*
|
|
@@ -1610,6 +1645,108 @@ declare class Emitter<Events> {
|
|
|
1610
1645
|
removeAllListeners(): void;
|
|
1611
1646
|
}
|
|
1612
1647
|
|
|
1648
|
+
/**
|
|
1649
|
+
* Обёртка вокруг запроса.
|
|
1650
|
+
*
|
|
1651
|
+
* Получает описание запроса и продолжение цепочки. Может изменить запрос перед отправкой,
|
|
1652
|
+
* посмотреть и подменить разобранный ответ или вовсе не вызывать `next` и вернуть своё.
|
|
1653
|
+
*
|
|
1654
|
+
* @param request что уходит на сервер; изменять сам объект не нужно — передайте копию в `next`
|
|
1655
|
+
* @param next продолжение: либо следующая обёртка, либо настоящий запрос
|
|
1656
|
+
* @returns тело ответа в том виде, в каком его получит вызывающий код
|
|
1657
|
+
*
|
|
1658
|
+
* @example Дописать заголовок ко всем запросам
|
|
1659
|
+
* ```ts
|
|
1660
|
+
* const transformer: Transformer = (request, next) =>
|
|
1661
|
+
* next({ ...request, headers: { ...request.headers, 'X-Trace': trace() } });
|
|
1662
|
+
* ```
|
|
1663
|
+
*/
|
|
1664
|
+
type Transformer = (request: RawRequestOptions, next: (request: RawRequestOptions) => Promise<unknown>) => Promise<unknown>;
|
|
1665
|
+
/** Что плагин получает при подключении. */
|
|
1666
|
+
interface PluginContext {
|
|
1667
|
+
/** Базовый URL клиента — например чтобы разобрать абсолютные ссылки из ответа. */
|
|
1668
|
+
baseUrl: string;
|
|
1669
|
+
/** Отладочный вывод клиента, если он включён. */
|
|
1670
|
+
logger: Logger | undefined;
|
|
1671
|
+
/** Добавляет обёртку запроса. Подключённые раньше оказываются снаружи. */
|
|
1672
|
+
use(transformer: Transformer): void;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Плагин клиента.
|
|
1676
|
+
*
|
|
1677
|
+
* Подключается через `itd.use(plugin)` и работает на уровне транспорта: видит запрос
|
|
1678
|
+
* до отправки и разобранный ответ. Библиотека не знает, что именно делает плагин, —
|
|
1679
|
+
* ей достаточно списка обёрток и имён опций, которые он читает.
|
|
1680
|
+
*
|
|
1681
|
+
* @example
|
|
1682
|
+
* ```ts
|
|
1683
|
+
* const logging: ItdPlugin = {
|
|
1684
|
+
* name: 'logging',
|
|
1685
|
+
* install({ use, logger }) {
|
|
1686
|
+
* use(async (request, next) => {
|
|
1687
|
+
* logger?.info(`${request.method} ${request.path}`);
|
|
1688
|
+
* return next(request);
|
|
1689
|
+
* });
|
|
1690
|
+
* },
|
|
1691
|
+
* };
|
|
1692
|
+
*
|
|
1693
|
+
* itd.use(logging);
|
|
1694
|
+
* ```
|
|
1695
|
+
*/
|
|
1696
|
+
interface ItdPlugin {
|
|
1697
|
+
/** Имя плагина. Должно быть уникальным: повторное подключение — ошибка. */
|
|
1698
|
+
name: string;
|
|
1699
|
+
/**
|
|
1700
|
+
* Имена опций запроса, которые плагин читает у методов ресурсов.
|
|
1701
|
+
*
|
|
1702
|
+
* Библиотека этих опций не понимает и ничего с ними не делает — только доносит
|
|
1703
|
+
* от вызова метода до обёртки нетронутыми. Без такого списка чужие поля отсеиваются,
|
|
1704
|
+
* чтобы случайная опечатка в параметрах не уезжала на сервер.
|
|
1705
|
+
*
|
|
1706
|
+
* Имена полей самого запроса (`path`, `body`, `headers`, `signal` и прочие из
|
|
1707
|
+
* `RawRequestOptions`) заявить нельзя: подключение такого плагина завершится ошибкой.
|
|
1708
|
+
*
|
|
1709
|
+
* Типы для них плагин объявляет сам, дополняя `RequestOptions`:
|
|
1710
|
+
* ```ts
|
|
1711
|
+
* declare module 'itd-api' {
|
|
1712
|
+
* interface RequestOptions { encrypt?: string | undefined }
|
|
1713
|
+
* }
|
|
1714
|
+
* ```
|
|
1715
|
+
*/
|
|
1716
|
+
optionKeys?: readonly string[];
|
|
1717
|
+
/** Вызывается один раз при подключении. */
|
|
1718
|
+
install(context: PluginContext): void;
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Список подключённых плагинов и собранная из них цепочка обёрток.
|
|
1722
|
+
*
|
|
1723
|
+
* Живёт в клиенте, а работает в транспорте: {@link HttpClient} прогоняет через `run`
|
|
1724
|
+
* каждый запрос, если плагины есть.
|
|
1725
|
+
*/
|
|
1726
|
+
declare class PluginRegistry {
|
|
1727
|
+
#private;
|
|
1728
|
+
/** Сколько обёрток подключено. Ноль означает, что запрос идёт прежним путём. */
|
|
1729
|
+
get size(): number;
|
|
1730
|
+
/** Имена опций запроса, заявленные плагинами. */
|
|
1731
|
+
get optionKeys(): ReadonlySet<string>;
|
|
1732
|
+
/**
|
|
1733
|
+
* Подключает плагин.
|
|
1734
|
+
*
|
|
1735
|
+
* @throws {ItdConfigError} если плагин задан неверно, уже подключён или заявил занятое
|
|
1736
|
+
* имя опции
|
|
1737
|
+
*/
|
|
1738
|
+
add(plugin: ItdPlugin, context: Omit<PluginContext, 'use'>): void;
|
|
1739
|
+
/**
|
|
1740
|
+
* Прогоняет запрос через цепочку обёрток.
|
|
1741
|
+
*
|
|
1742
|
+
* Цепочка собирается на каждый запрос заново: плагин можно подключить в любой момент,
|
|
1743
|
+
* а обёрток единицы — экономить тут не на чем.
|
|
1744
|
+
*
|
|
1745
|
+
* @param execute настоящий запрос, вызывается самой внутренней обёрткой
|
|
1746
|
+
*/
|
|
1747
|
+
run(request: RawRequestOptions, execute: (request: RawRequestOptions) => Promise<unknown>): Promise<unknown>;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1613
1750
|
/**
|
|
1614
1751
|
* Подключаемые части конвейера.
|
|
1615
1752
|
*
|
|
@@ -1666,6 +1803,15 @@ declare class HttpClient {
|
|
|
1666
1803
|
constructor(config: ResolvedConfig, collaborators?: HttpCollaborators);
|
|
1667
1804
|
/** Базовый URL, к которому обращается клиент. */
|
|
1668
1805
|
get baseUrl(): string;
|
|
1806
|
+
/**
|
|
1807
|
+
* Имена опций запроса, заявленные плагинами.
|
|
1808
|
+
*
|
|
1809
|
+
* Читается ресурсами: они переносят в транспорт только известные поля, а чужие,
|
|
1810
|
+
* если их никто не заявил, отсеивают.
|
|
1811
|
+
*/
|
|
1812
|
+
get pluginOptionKeys(): ReadonlySet<string>;
|
|
1813
|
+
/** Подключает список плагинов. Реестр общий с клиентом и пополняется через `itd.use()`. */
|
|
1814
|
+
usePlugins(plugins: PluginRegistry): void;
|
|
1669
1815
|
/**
|
|
1670
1816
|
* Подключает недостающие части конвейера.
|
|
1671
1817
|
*
|
|
@@ -2196,7 +2342,14 @@ declare class BaseResource {
|
|
|
2196
2342
|
/** @internal */
|
|
2197
2343
|
protected readonly http: HttpClient;
|
|
2198
2344
|
constructor(http: HttpClient);
|
|
2199
|
-
/**
|
|
2345
|
+
/**
|
|
2346
|
+
* Переносит общие поля опций запроса в параметры транспорта.
|
|
2347
|
+
*
|
|
2348
|
+
* Поля перечислены поимённо, а не скопированы целиком: параметры методов наследуют
|
|
2349
|
+
* {@link RequestOptions} и приносят с собой `limit`, `cursor` и прочее, чему в описании
|
|
2350
|
+
* запроса делать нечего. Исключение — опции, заявленные плагинами: их библиотека
|
|
2351
|
+
* не понимает, но обязана донести до обёрток нетронутыми.
|
|
2352
|
+
*/
|
|
2200
2353
|
protected requestOptions(options: RequestOptions | undefined): Partial<RequestOptions>;
|
|
2201
2354
|
/**
|
|
2202
2355
|
* Собирает перебор страниц.
|
|
@@ -3181,6 +3334,24 @@ declare class ItdClient {
|
|
|
3181
3334
|
* ```
|
|
3182
3335
|
*/
|
|
3183
3336
|
request<T = unknown>(options: RawRequestOptions): Promise<T>;
|
|
3337
|
+
/**
|
|
3338
|
+
* Подключает плагин.
|
|
3339
|
+
*
|
|
3340
|
+
* Плагин работает на уровне транспорта: видит запрос до отправки и разобранный ответ,
|
|
3341
|
+
* поэтому одна обёртка охватывает сразу все методы клиента. Подключать можно в любой
|
|
3342
|
+
* момент, но обычно это делают сразу после создания клиента.
|
|
3343
|
+
*
|
|
3344
|
+
* @throws {ItdConfigError} если плагин задан неверно или уже подключён
|
|
3345
|
+
*
|
|
3346
|
+
* @example
|
|
3347
|
+
* ```ts
|
|
3348
|
+
* import { crypt } from 'itd-api-crypto';
|
|
3349
|
+
*
|
|
3350
|
+
* itd.use(crypt());
|
|
3351
|
+
* await itd.posts.create({ content: 'секрет' }, { encrypt: 'invis' });
|
|
3352
|
+
* ```
|
|
3353
|
+
*/
|
|
3354
|
+
use(plugin: ItdPlugin): this;
|
|
3184
3355
|
/**
|
|
3185
3356
|
* Подписывается на события авторизации.
|
|
3186
3357
|
*
|
|
@@ -3611,4 +3782,4 @@ interface SseTransportOptions {
|
|
|
3611
3782
|
idleTimeout?: number;
|
|
3612
3783
|
}
|
|
3613
3784
|
|
|
3614
|
-
export { IMAGE_MIME_TYPES as $, ALLOWED_MIME_TYPES as A, type BuilderInput as B, type CaptchaCredentials as C, type CreatePollInput as D, type CreatePostInput as E, type FileReader as F, type CreateReportInput as G, type Credentials as H, type ItdSession as I, type CredentialsAuth as J, DEFAULT_BASE_URL as K, DEFAULT_TIMEOUT as L, DEFAULT_USER_AGENT as M, DEVICE_ID_HEADER as N, DetectedRuntime as O, type DwellEntry as P, type ErrorContextHook as Q, type FeedParams as R, FeedTab as S, type TokenStorage as T, type FileInput as U, FilesResource as V, type FollowResult as W, type ForgotPasswordInput as X, type Hashtag as Y, type HashtagPostsParams as Z, HashtagsResource as _, ItdClient as a,
|
|
3785
|
+
export { IMAGE_MIME_TYPES as $, ALLOWED_MIME_TYPES as A, type BuilderInput as B, type CaptchaCredentials as C, type CreatePollInput as D, type CreatePostInput as E, type FileReader as F, type CreateReportInput as G, type Credentials as H, type ItdSession as I, type CredentialsAuth as J, DEFAULT_BASE_URL as K, DEFAULT_TIMEOUT as L, DEFAULT_USER_AGENT as M, DEVICE_ID_HEADER as N, DetectedRuntime as O, type DwellEntry as P, type ErrorContextHook as Q, type FeedParams as R, FeedTab as S, type TokenStorage as T, type FileInput as U, FilesResource as V, type FollowResult as W, type ForgotPasswordInput as X, type Hashtag as Y, type HashtagPostsParams as Z, HashtagsResource as _, ItdClient as a, PostsResource as a$, type ImageMimeType as a0, type InteractionEntry as a1, type IsoDate as a2, ItdAbortError as a3, ItdApiError as a4, type ItdApiErrorInit as a5, ItdApiErrorKind as a6, ItdAuthError as a7, type ItdBuilder as a8, ItdConfigError as a9, type Notification as aA, type NotificationEvent as aB, type NotificationListParams as aC, type NotificationSettings as aD, NotificationType as aE, NotificationsResource as aF, OAuthProvider as aG, type Page as aH, type PageState as aI, PaginationMode as aJ, Paginator as aK, type PaymentMethod as aL, type Pin as aM, type PinPostResult as aN, type PinsResult as aO, PlatformResource as aP, type PluginContext as aQ, type Poll as aR, PollBuilder as aS, type PollInput as aT, type PollOption as aU, type PollTransportOptions as aV, type Portal as aW, type Post as aX, PostBuilder as aY, type PostInput as aZ, type PostStats as a_, ItdConflictError as aa, ItdError as ab, ItdErrorCode as ac, ItdErrorKind as ad, type ItdFieldErrors as ae, ItdForbiddenError as af, ItdNetworkError as ag, ItdNotFoundError as ah, ItdPhoneVerificationError as ai, type ItdPlugin as aj, ItdRateLimitError as ak, ItdRealtime as al, ItdServerError as am, ItdTimeoutError as an, ItdValidationError as ao, LIBRARY_VERSION as ap, type LikeResult as aq, LikesVisibility as ar, type Listener as as, LocalStorageTokenStorage as at, type Logger as au, type Loose as av, MAX_RECONNECT_ATTEMPTS as aw, MemoryTokenStorage as ax, type MyProfile as ay, NOTIFICATION_TYPE_ALIASES as az, type ItdClientOptions as b, WallAccess as b$, type PrivacySettings as b0, type Profile as b1, type PublicProfile as b2, RECONNECT_BACKOFF as b3, RECONNECT_JITTER as b4, REFRESH_COOKIE as b5, REFRESH_COOKIE_PATH as b6, type RateLimitOptions as b7, type RawRequestOptions as b8, type RealtimeEvents as b9, SpanType as bA, type SseTransportOptions as bB, type Subscription as bC, SubscriptionResource as bD, type SubscriptionState as bE, TURNSTILE_SITE_KEY as bF, TelemetryResource as bG, type Transformer as bH, type TransportContext as bI, type TransportEvent as bJ, UnauthorizedStreamError as bK, type Unsubscribe as bL, type UpdateNotificationSettingsInput as bM, type UpdatePrivacyInput as bN, type UpdateProfileInput as bO, type UploadOptions as bP, type UploadedFile as bQ, type UserId as bR, type UserListParams as bS, type UserPostsParams as bT, type UserRef as bU, type UserSummary as bV, UsersResource as bW, VIDEO_MIME_TYPES as bX, VerificationResource as bY, type VerificationStatus as bZ, type VideoMimeType as b_, type RealtimeOptions as ba, RealtimeStatus as bb, type RealtimeTransport as bc, RealtimeTransportKind as bd, type ReconnectOptions as be, type RepliesParams as bf, type Report as bg, ReportBuilder as bh, type ReportInput as bi, ReportReason as bj, ReportTargetType as bk, ReportsResource as bl, type RequestContext as bm, type RequestOptions as bn, type ResetPasswordInput as bo, type ResponseContext as bp, type RetryContext as bq, type RetryOptions as br, RuntimeMode as bs, STREAM_PATH as bt, SearchResource as bu, type SearchResult as bv, type Session as bw, type SignInResult as bx, SignInStatus as by, type Span as bz, AUDIO_MIME_TYPES as c, canonicalNotificationType as c0, comment as c1, createTokenStorage as c2, formatNotificationText as c3, isBuilder as c4, isItdApiError as c5, isItdAuthError as c6, isItdConflictError as c7, isItdError as c8, isItdForbiddenError as c9, isItdNotFoundError as ca, isItdPhoneVerificationError as cb, isItdRateLimitError as cc, isItdServerError as cd, isItdValidationError as ce, isKnownNotificationType as cf, isMyProfile as cg, normalizeNotification as ch, poll as ci, post as cj, readNotificationEvent as ck, readUnreadCountEvent as cl, report as cm, resolveNotificationUrl as cn, toDate as co, createClient as cp, AUTH_FLAG_COOKIE as d, AUTH_PATHS as e, type Actor as f, type AllowedMimeType as g, type Announcement as h, type AnnouncementButton as i, type Attachment as j, AttachmentType as k, type AudioMimeType as l, type AuthInput as m, AuthResource as n, type Author as o, type ChangelogEntry as p, type Clan as q, type ClientHooks as r, type Comment as s, CommentBuilder as t, type CommentInput as u, type CommentReplyTo as v, CommentSort as w, type CommentsParams as x, CommentsResource as y, type CreateCommentInput as z };
|
|
@@ -97,6 +97,39 @@ declare const AttachmentType: Readonly<{
|
|
|
97
97
|
readonly Audio: "audio";
|
|
98
98
|
}>;
|
|
99
99
|
type AttachmentType = (typeof AttachmentType)[keyof typeof AttachmentType];
|
|
100
|
+
/**
|
|
101
|
+
* Тип фрагмента разметки в тексте поста или комментария.
|
|
102
|
+
*
|
|
103
|
+
* Первые два сервер расставляет сам при разборе текста, остальные приходят от редактора.
|
|
104
|
+
* Тип открытый: набор может пополниться.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* await itd.posts.update(postId, {
|
|
109
|
+
* content: 'жирное слово',
|
|
110
|
+
* spans: [{ type: SpanType.Bold, offset: 0, length: 6 }],
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
declare const SpanType: Readonly<{
|
|
115
|
+
/** Хэштег. Название без решётки лежит в `tag`. */
|
|
116
|
+
readonly Hashtag: "hashtag";
|
|
117
|
+
/** Упоминание. Имя пользователя лежит в `tag`. */
|
|
118
|
+
readonly Mention: "mention";
|
|
119
|
+
/** Ссылка. Адрес лежит в `url`, а не в `tag`. */
|
|
120
|
+
readonly Link: "link";
|
|
121
|
+
readonly Bold: "bold";
|
|
122
|
+
readonly Italic: "italic";
|
|
123
|
+
readonly Underline: "underline";
|
|
124
|
+
/** Зачёркнутый. */
|
|
125
|
+
readonly Strike: "strike";
|
|
126
|
+
/** Спойлер: текст скрыт до нажатия. */
|
|
127
|
+
readonly Spoiler: "spoiler";
|
|
128
|
+
/** Моноширинный. */
|
|
129
|
+
readonly Monospace: "monospace";
|
|
130
|
+
readonly Quote: "quote";
|
|
131
|
+
}>;
|
|
132
|
+
type SpanType = Loose<(typeof SpanType)[keyof typeof SpanType]>;
|
|
100
133
|
/** На что подаётся жалоба. */
|
|
101
134
|
declare const ReportTargetType: Readonly<{
|
|
102
135
|
readonly Post: "post";
|
|
@@ -264,14 +297,16 @@ type UserRef = string;
|
|
|
264
297
|
* поэтому при работе с эмодзи проверяйте результат.
|
|
265
298
|
*/
|
|
266
299
|
interface Span {
|
|
267
|
-
/** Тип
|
|
268
|
-
type:
|
|
300
|
+
/** Тип фрагмента — см. {@link SpanType}. */
|
|
301
|
+
type: SpanType;
|
|
269
302
|
/** Смещение от начала текста. */
|
|
270
303
|
offset: number;
|
|
271
304
|
/** Длина фрагмента. */
|
|
272
305
|
length: number;
|
|
273
|
-
/**
|
|
306
|
+
/** Имя хэштега без решётки либо имя пользователя. */
|
|
274
307
|
tag?: string;
|
|
308
|
+
/** Адрес ссылки. Только у `link`: у него вместо `tag` отдельное поле. */
|
|
309
|
+
url?: string;
|
|
275
310
|
}
|
|
276
311
|
/**
|
|
277
312
|
* Значок-«пин» в профиле — награда или отметка платформы.
|
|
@@ -1439,7 +1474,7 @@ declare const DEFAULT_TIMEOUT = 30000;
|
|
|
1439
1474
|
/**
|
|
1440
1475
|
* Версия библиотеки — попадает в `User-Agent`.
|
|
1441
1476
|
*/
|
|
1442
|
-
declare const LIBRARY_VERSION = "0.0.
|
|
1477
|
+
declare const LIBRARY_VERSION = "0.0.6";
|
|
1443
1478
|
/**
|
|
1444
1479
|
* `User-Agent` по умолчанию.
|
|
1445
1480
|
*
|
|
@@ -1450,7 +1485,7 @@ declare const LIBRARY_VERSION = "0.0.5";
|
|
|
1450
1485
|
* В браузере заголовок не выставляется — `User-Agent` там запрещён к изменению, и среда
|
|
1451
1486
|
* молча его игнорирует.
|
|
1452
1487
|
*/
|
|
1453
|
-
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.0.
|
|
1488
|
+
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.0.6; +https://github.com/KiowDev/itd-api)";
|
|
1454
1489
|
/**
|
|
1455
1490
|
* Настройки повторов со всеми значениями по умолчанию.
|
|
1456
1491
|
*
|
|
@@ -1610,6 +1645,108 @@ declare class Emitter<Events> {
|
|
|
1610
1645
|
removeAllListeners(): void;
|
|
1611
1646
|
}
|
|
1612
1647
|
|
|
1648
|
+
/**
|
|
1649
|
+
* Обёртка вокруг запроса.
|
|
1650
|
+
*
|
|
1651
|
+
* Получает описание запроса и продолжение цепочки. Может изменить запрос перед отправкой,
|
|
1652
|
+
* посмотреть и подменить разобранный ответ или вовсе не вызывать `next` и вернуть своё.
|
|
1653
|
+
*
|
|
1654
|
+
* @param request что уходит на сервер; изменять сам объект не нужно — передайте копию в `next`
|
|
1655
|
+
* @param next продолжение: либо следующая обёртка, либо настоящий запрос
|
|
1656
|
+
* @returns тело ответа в том виде, в каком его получит вызывающий код
|
|
1657
|
+
*
|
|
1658
|
+
* @example Дописать заголовок ко всем запросам
|
|
1659
|
+
* ```ts
|
|
1660
|
+
* const transformer: Transformer = (request, next) =>
|
|
1661
|
+
* next({ ...request, headers: { ...request.headers, 'X-Trace': trace() } });
|
|
1662
|
+
* ```
|
|
1663
|
+
*/
|
|
1664
|
+
type Transformer = (request: RawRequestOptions, next: (request: RawRequestOptions) => Promise<unknown>) => Promise<unknown>;
|
|
1665
|
+
/** Что плагин получает при подключении. */
|
|
1666
|
+
interface PluginContext {
|
|
1667
|
+
/** Базовый URL клиента — например чтобы разобрать абсолютные ссылки из ответа. */
|
|
1668
|
+
baseUrl: string;
|
|
1669
|
+
/** Отладочный вывод клиента, если он включён. */
|
|
1670
|
+
logger: Logger | undefined;
|
|
1671
|
+
/** Добавляет обёртку запроса. Подключённые раньше оказываются снаружи. */
|
|
1672
|
+
use(transformer: Transformer): void;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Плагин клиента.
|
|
1676
|
+
*
|
|
1677
|
+
* Подключается через `itd.use(plugin)` и работает на уровне транспорта: видит запрос
|
|
1678
|
+
* до отправки и разобранный ответ. Библиотека не знает, что именно делает плагин, —
|
|
1679
|
+
* ей достаточно списка обёрток и имён опций, которые он читает.
|
|
1680
|
+
*
|
|
1681
|
+
* @example
|
|
1682
|
+
* ```ts
|
|
1683
|
+
* const logging: ItdPlugin = {
|
|
1684
|
+
* name: 'logging',
|
|
1685
|
+
* install({ use, logger }) {
|
|
1686
|
+
* use(async (request, next) => {
|
|
1687
|
+
* logger?.info(`${request.method} ${request.path}`);
|
|
1688
|
+
* return next(request);
|
|
1689
|
+
* });
|
|
1690
|
+
* },
|
|
1691
|
+
* };
|
|
1692
|
+
*
|
|
1693
|
+
* itd.use(logging);
|
|
1694
|
+
* ```
|
|
1695
|
+
*/
|
|
1696
|
+
interface ItdPlugin {
|
|
1697
|
+
/** Имя плагина. Должно быть уникальным: повторное подключение — ошибка. */
|
|
1698
|
+
name: string;
|
|
1699
|
+
/**
|
|
1700
|
+
* Имена опций запроса, которые плагин читает у методов ресурсов.
|
|
1701
|
+
*
|
|
1702
|
+
* Библиотека этих опций не понимает и ничего с ними не делает — только доносит
|
|
1703
|
+
* от вызова метода до обёртки нетронутыми. Без такого списка чужие поля отсеиваются,
|
|
1704
|
+
* чтобы случайная опечатка в параметрах не уезжала на сервер.
|
|
1705
|
+
*
|
|
1706
|
+
* Имена полей самого запроса (`path`, `body`, `headers`, `signal` и прочие из
|
|
1707
|
+
* `RawRequestOptions`) заявить нельзя: подключение такого плагина завершится ошибкой.
|
|
1708
|
+
*
|
|
1709
|
+
* Типы для них плагин объявляет сам, дополняя `RequestOptions`:
|
|
1710
|
+
* ```ts
|
|
1711
|
+
* declare module 'itd-api' {
|
|
1712
|
+
* interface RequestOptions { encrypt?: string | undefined }
|
|
1713
|
+
* }
|
|
1714
|
+
* ```
|
|
1715
|
+
*/
|
|
1716
|
+
optionKeys?: readonly string[];
|
|
1717
|
+
/** Вызывается один раз при подключении. */
|
|
1718
|
+
install(context: PluginContext): void;
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Список подключённых плагинов и собранная из них цепочка обёрток.
|
|
1722
|
+
*
|
|
1723
|
+
* Живёт в клиенте, а работает в транспорте: {@link HttpClient} прогоняет через `run`
|
|
1724
|
+
* каждый запрос, если плагины есть.
|
|
1725
|
+
*/
|
|
1726
|
+
declare class PluginRegistry {
|
|
1727
|
+
#private;
|
|
1728
|
+
/** Сколько обёрток подключено. Ноль означает, что запрос идёт прежним путём. */
|
|
1729
|
+
get size(): number;
|
|
1730
|
+
/** Имена опций запроса, заявленные плагинами. */
|
|
1731
|
+
get optionKeys(): ReadonlySet<string>;
|
|
1732
|
+
/**
|
|
1733
|
+
* Подключает плагин.
|
|
1734
|
+
*
|
|
1735
|
+
* @throws {ItdConfigError} если плагин задан неверно, уже подключён или заявил занятое
|
|
1736
|
+
* имя опции
|
|
1737
|
+
*/
|
|
1738
|
+
add(plugin: ItdPlugin, context: Omit<PluginContext, 'use'>): void;
|
|
1739
|
+
/**
|
|
1740
|
+
* Прогоняет запрос через цепочку обёрток.
|
|
1741
|
+
*
|
|
1742
|
+
* Цепочка собирается на каждый запрос заново: плагин можно подключить в любой момент,
|
|
1743
|
+
* а обёрток единицы — экономить тут не на чем.
|
|
1744
|
+
*
|
|
1745
|
+
* @param execute настоящий запрос, вызывается самой внутренней обёрткой
|
|
1746
|
+
*/
|
|
1747
|
+
run(request: RawRequestOptions, execute: (request: RawRequestOptions) => Promise<unknown>): Promise<unknown>;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1613
1750
|
/**
|
|
1614
1751
|
* Подключаемые части конвейера.
|
|
1615
1752
|
*
|
|
@@ -1666,6 +1803,15 @@ declare class HttpClient {
|
|
|
1666
1803
|
constructor(config: ResolvedConfig, collaborators?: HttpCollaborators);
|
|
1667
1804
|
/** Базовый URL, к которому обращается клиент. */
|
|
1668
1805
|
get baseUrl(): string;
|
|
1806
|
+
/**
|
|
1807
|
+
* Имена опций запроса, заявленные плагинами.
|
|
1808
|
+
*
|
|
1809
|
+
* Читается ресурсами: они переносят в транспорт только известные поля, а чужие,
|
|
1810
|
+
* если их никто не заявил, отсеивают.
|
|
1811
|
+
*/
|
|
1812
|
+
get pluginOptionKeys(): ReadonlySet<string>;
|
|
1813
|
+
/** Подключает список плагинов. Реестр общий с клиентом и пополняется через `itd.use()`. */
|
|
1814
|
+
usePlugins(plugins: PluginRegistry): void;
|
|
1669
1815
|
/**
|
|
1670
1816
|
* Подключает недостающие части конвейера.
|
|
1671
1817
|
*
|
|
@@ -2196,7 +2342,14 @@ declare class BaseResource {
|
|
|
2196
2342
|
/** @internal */
|
|
2197
2343
|
protected readonly http: HttpClient;
|
|
2198
2344
|
constructor(http: HttpClient);
|
|
2199
|
-
/**
|
|
2345
|
+
/**
|
|
2346
|
+
* Переносит общие поля опций запроса в параметры транспорта.
|
|
2347
|
+
*
|
|
2348
|
+
* Поля перечислены поимённо, а не скопированы целиком: параметры методов наследуют
|
|
2349
|
+
* {@link RequestOptions} и приносят с собой `limit`, `cursor` и прочее, чему в описании
|
|
2350
|
+
* запроса делать нечего. Исключение — опции, заявленные плагинами: их библиотека
|
|
2351
|
+
* не понимает, но обязана донести до обёрток нетронутыми.
|
|
2352
|
+
*/
|
|
2200
2353
|
protected requestOptions(options: RequestOptions | undefined): Partial<RequestOptions>;
|
|
2201
2354
|
/**
|
|
2202
2355
|
* Собирает перебор страниц.
|
|
@@ -3181,6 +3334,24 @@ declare class ItdClient {
|
|
|
3181
3334
|
* ```
|
|
3182
3335
|
*/
|
|
3183
3336
|
request<T = unknown>(options: RawRequestOptions): Promise<T>;
|
|
3337
|
+
/**
|
|
3338
|
+
* Подключает плагин.
|
|
3339
|
+
*
|
|
3340
|
+
* Плагин работает на уровне транспорта: видит запрос до отправки и разобранный ответ,
|
|
3341
|
+
* поэтому одна обёртка охватывает сразу все методы клиента. Подключать можно в любой
|
|
3342
|
+
* момент, но обычно это делают сразу после создания клиента.
|
|
3343
|
+
*
|
|
3344
|
+
* @throws {ItdConfigError} если плагин задан неверно или уже подключён
|
|
3345
|
+
*
|
|
3346
|
+
* @example
|
|
3347
|
+
* ```ts
|
|
3348
|
+
* import { crypt } from 'itd-api-crypto';
|
|
3349
|
+
*
|
|
3350
|
+
* itd.use(crypt());
|
|
3351
|
+
* await itd.posts.create({ content: 'секрет' }, { encrypt: 'invis' });
|
|
3352
|
+
* ```
|
|
3353
|
+
*/
|
|
3354
|
+
use(plugin: ItdPlugin): this;
|
|
3184
3355
|
/**
|
|
3185
3356
|
* Подписывается на события авторизации.
|
|
3186
3357
|
*
|
|
@@ -3611,4 +3782,4 @@ interface SseTransportOptions {
|
|
|
3611
3782
|
idleTimeout?: number;
|
|
3612
3783
|
}
|
|
3613
3784
|
|
|
3614
|
-
export { IMAGE_MIME_TYPES as $, ALLOWED_MIME_TYPES as A, type BuilderInput as B, type CaptchaCredentials as C, type CreatePollInput as D, type CreatePostInput as E, type FileReader as F, type CreateReportInput as G, type Credentials as H, type ItdSession as I, type CredentialsAuth as J, DEFAULT_BASE_URL as K, DEFAULT_TIMEOUT as L, DEFAULT_USER_AGENT as M, DEVICE_ID_HEADER as N, DetectedRuntime as O, type DwellEntry as P, type ErrorContextHook as Q, type FeedParams as R, FeedTab as S, type TokenStorage as T, type FileInput as U, FilesResource as V, type FollowResult as W, type ForgotPasswordInput as X, type Hashtag as Y, type HashtagPostsParams as Z, HashtagsResource as _, ItdClient as a,
|
|
3785
|
+
export { IMAGE_MIME_TYPES as $, ALLOWED_MIME_TYPES as A, type BuilderInput as B, type CaptchaCredentials as C, type CreatePollInput as D, type CreatePostInput as E, type FileReader as F, type CreateReportInput as G, type Credentials as H, type ItdSession as I, type CredentialsAuth as J, DEFAULT_BASE_URL as K, DEFAULT_TIMEOUT as L, DEFAULT_USER_AGENT as M, DEVICE_ID_HEADER as N, DetectedRuntime as O, type DwellEntry as P, type ErrorContextHook as Q, type FeedParams as R, FeedTab as S, type TokenStorage as T, type FileInput as U, FilesResource as V, type FollowResult as W, type ForgotPasswordInput as X, type Hashtag as Y, type HashtagPostsParams as Z, HashtagsResource as _, ItdClient as a, PostsResource as a$, type ImageMimeType as a0, type InteractionEntry as a1, type IsoDate as a2, ItdAbortError as a3, ItdApiError as a4, type ItdApiErrorInit as a5, ItdApiErrorKind as a6, ItdAuthError as a7, type ItdBuilder as a8, ItdConfigError as a9, type Notification as aA, type NotificationEvent as aB, type NotificationListParams as aC, type NotificationSettings as aD, NotificationType as aE, NotificationsResource as aF, OAuthProvider as aG, type Page as aH, type PageState as aI, PaginationMode as aJ, Paginator as aK, type PaymentMethod as aL, type Pin as aM, type PinPostResult as aN, type PinsResult as aO, PlatformResource as aP, type PluginContext as aQ, type Poll as aR, PollBuilder as aS, type PollInput as aT, type PollOption as aU, type PollTransportOptions as aV, type Portal as aW, type Post as aX, PostBuilder as aY, type PostInput as aZ, type PostStats as a_, ItdConflictError as aa, ItdError as ab, ItdErrorCode as ac, ItdErrorKind as ad, type ItdFieldErrors as ae, ItdForbiddenError as af, ItdNetworkError as ag, ItdNotFoundError as ah, ItdPhoneVerificationError as ai, type ItdPlugin as aj, ItdRateLimitError as ak, ItdRealtime as al, ItdServerError as am, ItdTimeoutError as an, ItdValidationError as ao, LIBRARY_VERSION as ap, type LikeResult as aq, LikesVisibility as ar, type Listener as as, LocalStorageTokenStorage as at, type Logger as au, type Loose as av, MAX_RECONNECT_ATTEMPTS as aw, MemoryTokenStorage as ax, type MyProfile as ay, NOTIFICATION_TYPE_ALIASES as az, type ItdClientOptions as b, WallAccess as b$, type PrivacySettings as b0, type Profile as b1, type PublicProfile as b2, RECONNECT_BACKOFF as b3, RECONNECT_JITTER as b4, REFRESH_COOKIE as b5, REFRESH_COOKIE_PATH as b6, type RateLimitOptions as b7, type RawRequestOptions as b8, type RealtimeEvents as b9, SpanType as bA, type SseTransportOptions as bB, type Subscription as bC, SubscriptionResource as bD, type SubscriptionState as bE, TURNSTILE_SITE_KEY as bF, TelemetryResource as bG, type Transformer as bH, type TransportContext as bI, type TransportEvent as bJ, UnauthorizedStreamError as bK, type Unsubscribe as bL, type UpdateNotificationSettingsInput as bM, type UpdatePrivacyInput as bN, type UpdateProfileInput as bO, type UploadOptions as bP, type UploadedFile as bQ, type UserId as bR, type UserListParams as bS, type UserPostsParams as bT, type UserRef as bU, type UserSummary as bV, UsersResource as bW, VIDEO_MIME_TYPES as bX, VerificationResource as bY, type VerificationStatus as bZ, type VideoMimeType as b_, type RealtimeOptions as ba, RealtimeStatus as bb, type RealtimeTransport as bc, RealtimeTransportKind as bd, type ReconnectOptions as be, type RepliesParams as bf, type Report as bg, ReportBuilder as bh, type ReportInput as bi, ReportReason as bj, ReportTargetType as bk, ReportsResource as bl, type RequestContext as bm, type RequestOptions as bn, type ResetPasswordInput as bo, type ResponseContext as bp, type RetryContext as bq, type RetryOptions as br, RuntimeMode as bs, STREAM_PATH as bt, SearchResource as bu, type SearchResult as bv, type Session as bw, type SignInResult as bx, SignInStatus as by, type Span as bz, AUDIO_MIME_TYPES as c, canonicalNotificationType as c0, comment as c1, createTokenStorage as c2, formatNotificationText as c3, isBuilder as c4, isItdApiError as c5, isItdAuthError as c6, isItdConflictError as c7, isItdError as c8, isItdForbiddenError as c9, isItdNotFoundError as ca, isItdPhoneVerificationError as cb, isItdRateLimitError as cc, isItdServerError as cd, isItdValidationError as ce, isKnownNotificationType as cf, isMyProfile as cg, normalizeNotification as ch, poll as ci, post as cj, readNotificationEvent as ck, readUnreadCountEvent as cl, report as cm, resolveNotificationUrl as cn, toDate as co, createClient as cp, AUTH_FLAG_COOKIE as d, AUTH_PATHS as e, type Actor as f, type AllowedMimeType as g, type Announcement as h, type AnnouncementButton as i, type Attachment as j, AttachmentType as k, type AudioMimeType as l, type AuthInput as m, AuthResource as n, type Author as o, type ChangelogEntry as p, type Clan as q, type ClientHooks as r, type Comment as s, CommentBuilder as t, type CommentInput as u, type CommentReplyTo as v, CommentSort as w, type CommentsParams as x, CommentsResource as y, type CreateCommentInput as z };
|