itd-api 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.cjs +81 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -4
- package/dist/index.d.ts +22 -4
- package/dist/index.js +81 -8
- package/dist/index.js.map +1 -1
- package/dist/realtime/index.cjs +3 -3
- package/dist/realtime/index.d.cts +2 -2
- package/dist/realtime/index.d.ts +2 -2
- package/dist/realtime/index.js +3 -3
- package/dist/rest/index.cjs +70 -6
- package/dist/rest/index.cjs.map +1 -1
- package/dist/rest/index.d.cts +11 -3
- package/dist/rest/index.d.ts +11 -3
- package/dist/rest/index.js +70 -6
- package/dist/rest/index.js.map +1 -1
- package/dist/shared/{auth-provider-CTJkKfgy.cjs → auth-provider-CG8oCQ9F.cjs} +2 -2
- package/dist/shared/{auth-provider-CTJkKfgy.cjs.map → auth-provider-CG8oCQ9F.cjs.map} +1 -1
- package/dist/shared/{auth-provider-BfogACAb.js → auth-provider-mYqxsSVa.js} +2 -2
- package/dist/shared/{auth-provider-BfogACAb.js.map → auth-provider-mYqxsSVa.js.map} +1 -1
- package/dist/shared/{render-vtLixIiU.js → render-C6HRPs10.js} +353 -56
- package/dist/shared/render-C6HRPs10.js.map +1 -0
- package/dist/shared/{render-DZrxhC5_.d.ts → render-CgwKdOzu.d.ts} +101 -40
- package/dist/shared/{render-DMp_3Nzk.d.cts → render-DO0F5YSm.d.cts} +101 -40
- package/dist/shared/{render-DyeHJNBw.cjs → render-mcuELiYi.cjs} +369 -54
- package/dist/shared/render-mcuELiYi.cjs.map +1 -0
- package/dist/shared/{url-yjl2c8Ie.cjs → url-BaMCQpYH.cjs} +76 -24
- package/dist/shared/url-BaMCQpYH.cjs.map +1 -0
- package/dist/shared/{url-B6-bXHKt.d.ts → url-DTfZ2toq.d.cts} +6 -8
- package/dist/shared/{url-B6-bXHKt.d.cts → url-DTfZ2toq.d.ts} +6 -8
- package/dist/shared/{url-CYXgxqGx.js → url-IU0xN9wX.js} +65 -25
- package/dist/shared/url-IU0xN9wX.js.map +1 -0
- package/dist/shared/{websocket-CbzB1Leq.js → websocket-BLR8eVJV.js} +2 -2
- package/dist/shared/{websocket-CbzB1Leq.js.map → websocket-BLR8eVJV.js.map} +1 -1
- package/dist/shared/{websocket-sYlynrr0.cjs → websocket-C_eI4H2o.cjs} +2 -2
- package/dist/shared/{websocket-sYlynrr0.cjs.map → websocket-C_eI4H2o.cjs.map} +1 -1
- package/dist/shared/{websocket-D1p32SB2.d.cts → websocket-DF7XIMiX.d.cts} +2 -2
- package/dist/shared/{websocket-BMtihD56.d.ts → websocket-DYKBr8HF.d.ts} +2 -2
- package/package.json +1 -1
- package/dist/shared/render-DyeHJNBw.cjs.map +0 -1
- package/dist/shared/render-vtLixIiU.js.map +0 -1
- package/dist/shared/url-CYXgxqGx.js.map +0 -1
- package/dist/shared/url-yjl2c8Ie.cjs.map +0 -1
package/dist/realtime/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_url = require("../shared/url-
|
|
2
|
+
const require_url = require("../shared/url-BaMCQpYH.cjs");
|
|
3
3
|
const require_errors = require("../shared/errors-DfU8M5eS.cjs");
|
|
4
|
-
const require_websocket = require("../shared/websocket-
|
|
5
|
-
const require_auth_provider = require("../shared/auth-provider-
|
|
4
|
+
const require_websocket = require("../shared/websocket-C_eI4H2o.cjs");
|
|
5
|
+
const require_auth_provider = require("../shared/auth-provider-CG8oCQ9F.cjs");
|
|
6
6
|
//#region src/realtime/client.ts
|
|
7
7
|
/**
|
|
8
8
|
* Поток уведомлений с собственным конвейером запросов.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as Notification, C as ItdStateError, D as isItdAuthError, E as isItdApiError, Ft as Logger, I as isItdStateError, Mt as Unsubscribe, Nt as ClientHooks, P as isItdRateLimitError, R as NotificationEvent, S as ItdServerError, St as RealtimeStatus, T as ItdValidationError, V as NotificationSettings, Yt as RuntimeOptions, _ as ItdForbiddenError, a as ItdAbortError, at as DEFAULT_BASE_URL, bt as Loose, c as ItdApiErrorKind, en as RuntimeMode, et as AuthIdentity, f as ItdError, i as formatNotificationText, it as tokenProvider, jt as Listener, k as isItdError, l as ItdAuthError, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, p as ItdErrorKind, r as isKnownNotificationType, rt as bearerToken, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, v as ItdNetworkError, w as ItdTimeoutError, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, z as normalizeNotification } from "../shared/url-
|
|
2
|
-
import { A as NotificationOfType, B as RealtimeUpdateOfType, C as RealtimeMiddlewareObj, D as RealtimeTypeGuard, E as RealtimeSequentializer, F as RealtimeNotificationSelector, G as RealtimeTransport, H as RealtimeUpdateType, I as RealtimeNotificationUpdate, J as UnauthorizedStreamError, K as TransportContext, L as RealtimeUnknownUpdate, M as RealtimeContextBase, N as RealtimeNotificationContext, O as runRealtimeMiddleware, P as RealtimeNotificationFilter, R as RealtimeUnreadCountUpdate, S as RealtimeMiddleware, T as RealtimePredicate, U as RealtimeRequest, V as RealtimeUpdateOrigin, W as RealtimeRequestInput, _ as RealtimeOptions, a as WebSocketTransportOptions, b as ReconnectOptions, c as RealtimeErrorContext, d as RealtimeMiddlewareLike, f as RealtimeRouteTable, g as RealtimeEvents, h as ItdRealtime, i as WebSocketTransport, j as RealtimeContext, k as NotificationEventOfType, l as RealtimeFilter, m as RealtimeRouter, n as WebSocketLike, o as RealtimeComposer, p as RealtimeRouteSelector, q as TransportEvent, r as WebSocketOpenFailureClassifier, s as RealtimeErrorBoundary, t as WebSocketImplementationOptions, u as RealtimeMiddlewareGroup, v as RealtimeTransportKind, w as RealtimeNext, x as RealtimeHandler, y as RealtimeEngineEvents, z as RealtimeUpdate } from "../shared/websocket-
|
|
1
|
+
import { B as Notification, C as ItdStateError, D as isItdAuthError, E as isItdApiError, Ft as Logger, I as isItdStateError, Mt as Unsubscribe, Nt as ClientHooks, P as isItdRateLimitError, R as NotificationEvent, S as ItdServerError, St as RealtimeStatus, T as ItdValidationError, V as NotificationSettings, Yt as RuntimeOptions, _ as ItdForbiddenError, a as ItdAbortError, at as DEFAULT_BASE_URL, bt as Loose, c as ItdApiErrorKind, en as RuntimeMode, et as AuthIdentity, f as ItdError, i as formatNotificationText, it as tokenProvider, jt as Listener, k as isItdError, l as ItdAuthError, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, p as ItdErrorKind, r as isKnownNotificationType, rt as bearerToken, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, v as ItdNetworkError, w as ItdTimeoutError, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, z as normalizeNotification } from "../shared/url-DTfZ2toq.cjs";
|
|
2
|
+
import { A as NotificationOfType, B as RealtimeUpdateOfType, C as RealtimeMiddlewareObj, D as RealtimeTypeGuard, E as RealtimeSequentializer, F as RealtimeNotificationSelector, G as RealtimeTransport, H as RealtimeUpdateType, I as RealtimeNotificationUpdate, J as UnauthorizedStreamError, K as TransportContext, L as RealtimeUnknownUpdate, M as RealtimeContextBase, N as RealtimeNotificationContext, O as runRealtimeMiddleware, P as RealtimeNotificationFilter, R as RealtimeUnreadCountUpdate, S as RealtimeMiddleware, T as RealtimePredicate, U as RealtimeRequest, V as RealtimeUpdateOrigin, W as RealtimeRequestInput, _ as RealtimeOptions, a as WebSocketTransportOptions, b as ReconnectOptions, c as RealtimeErrorContext, d as RealtimeMiddlewareLike, f as RealtimeRouteTable, g as RealtimeEvents, h as ItdRealtime, i as WebSocketTransport, j as RealtimeContext, k as NotificationEventOfType, l as RealtimeFilter, m as RealtimeRouter, n as WebSocketLike, o as RealtimeComposer, p as RealtimeRouteSelector, q as TransportEvent, r as WebSocketOpenFailureClassifier, s as RealtimeErrorBoundary, t as WebSocketImplementationOptions, u as RealtimeMiddlewareGroup, v as RealtimeTransportKind, w as RealtimeNext, x as RealtimeHandler, y as RealtimeEngineEvents, z as RealtimeUpdate } from "../shared/websocket-DF7XIMiX.cjs";
|
|
3
3
|
//#region src/realtime/client.d.ts
|
|
4
4
|
/** Опции конструктора {@link ItdRealtimeClient}. */
|
|
5
5
|
interface RealtimeClientOptions<C extends RealtimeContext = RealtimeContext> extends RuntimeOptions, RealtimeOptions<C> {
|
package/dist/realtime/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as Notification, C as ItdStateError, D as isItdAuthError, E as isItdApiError, Ft as Logger, I as isItdStateError, Mt as Unsubscribe, Nt as ClientHooks, P as isItdRateLimitError, R as NotificationEvent, S as ItdServerError, St as RealtimeStatus, T as ItdValidationError, V as NotificationSettings, Yt as RuntimeOptions, _ as ItdForbiddenError, a as ItdAbortError, at as DEFAULT_BASE_URL, bt as Loose, c as ItdApiErrorKind, en as RuntimeMode, et as AuthIdentity, f as ItdError, i as formatNotificationText, it as tokenProvider, jt as Listener, k as isItdError, l as ItdAuthError, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, p as ItdErrorKind, r as isKnownNotificationType, rt as bearerToken, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, v as ItdNetworkError, w as ItdTimeoutError, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, z as normalizeNotification } from "../shared/url-
|
|
2
|
-
import { A as NotificationOfType, B as RealtimeUpdateOfType, C as RealtimeMiddlewareObj, D as RealtimeTypeGuard, E as RealtimeSequentializer, F as RealtimeNotificationSelector, G as RealtimeTransport, H as RealtimeUpdateType, I as RealtimeNotificationUpdate, J as UnauthorizedStreamError, K as TransportContext, L as RealtimeUnknownUpdate, M as RealtimeContextBase, N as RealtimeNotificationContext, O as runRealtimeMiddleware, P as RealtimeNotificationFilter, R as RealtimeUnreadCountUpdate, S as RealtimeMiddleware, T as RealtimePredicate, U as RealtimeRequest, V as RealtimeUpdateOrigin, W as RealtimeRequestInput, _ as RealtimeOptions, a as WebSocketTransportOptions, b as ReconnectOptions, c as RealtimeErrorContext, d as RealtimeMiddlewareLike, f as RealtimeRouteTable, g as RealtimeEvents, h as ItdRealtime, i as WebSocketTransport, j as RealtimeContext, k as NotificationEventOfType, l as RealtimeFilter, m as RealtimeRouter, n as WebSocketLike, o as RealtimeComposer, p as RealtimeRouteSelector, q as TransportEvent, r as WebSocketOpenFailureClassifier, s as RealtimeErrorBoundary, t as WebSocketImplementationOptions, u as RealtimeMiddlewareGroup, v as RealtimeTransportKind, w as RealtimeNext, x as RealtimeHandler, y as RealtimeEngineEvents, z as RealtimeUpdate } from "../shared/websocket-
|
|
1
|
+
import { B as Notification, C as ItdStateError, D as isItdAuthError, E as isItdApiError, Ft as Logger, I as isItdStateError, Mt as Unsubscribe, Nt as ClientHooks, P as isItdRateLimitError, R as NotificationEvent, S as ItdServerError, St as RealtimeStatus, T as ItdValidationError, V as NotificationSettings, Yt as RuntimeOptions, _ as ItdForbiddenError, a as ItdAbortError, at as DEFAULT_BASE_URL, bt as Loose, c as ItdApiErrorKind, en as RuntimeMode, et as AuthIdentity, f as ItdError, i as formatNotificationText, it as tokenProvider, jt as Listener, k as isItdError, l as ItdAuthError, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, p as ItdErrorKind, r as isKnownNotificationType, rt as bearerToken, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, v as ItdNetworkError, w as ItdTimeoutError, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, z as normalizeNotification } from "../shared/url-DTfZ2toq.js";
|
|
2
|
+
import { A as NotificationOfType, B as RealtimeUpdateOfType, C as RealtimeMiddlewareObj, D as RealtimeTypeGuard, E as RealtimeSequentializer, F as RealtimeNotificationSelector, G as RealtimeTransport, H as RealtimeUpdateType, I as RealtimeNotificationUpdate, J as UnauthorizedStreamError, K as TransportContext, L as RealtimeUnknownUpdate, M as RealtimeContextBase, N as RealtimeNotificationContext, O as runRealtimeMiddleware, P as RealtimeNotificationFilter, R as RealtimeUnreadCountUpdate, S as RealtimeMiddleware, T as RealtimePredicate, U as RealtimeRequest, V as RealtimeUpdateOrigin, W as RealtimeRequestInput, _ as RealtimeOptions, a as WebSocketTransportOptions, b as ReconnectOptions, c as RealtimeErrorContext, d as RealtimeMiddlewareLike, f as RealtimeRouteTable, g as RealtimeEvents, h as ItdRealtime, i as WebSocketTransport, j as RealtimeContext, k as NotificationEventOfType, l as RealtimeFilter, m as RealtimeRouter, n as WebSocketLike, o as RealtimeComposer, p as RealtimeRouteSelector, q as TransportEvent, r as WebSocketOpenFailureClassifier, s as RealtimeErrorBoundary, t as WebSocketImplementationOptions, u as RealtimeMiddlewareGroup, v as RealtimeTransportKind, w as RealtimeNext, x as RealtimeHandler, y as RealtimeEngineEvents, z as RealtimeUpdate } from "../shared/websocket-DYKBr8HF.js";
|
|
3
3
|
//#region src/realtime/client.d.ts
|
|
4
4
|
/** Опции конструктора {@link ItdRealtimeClient}. */
|
|
5
5
|
interface RealtimeClientOptions<C extends RealtimeContext = RealtimeContext> extends RuntimeOptions, RealtimeOptions<C> {
|
package/dist/realtime/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { L as pickNumber, N as createClientRuntime, T as ITD_CATALOG, Z as LIBRARY_VERSION, _ as RealtimeStatus, ct as installAsyncDisposeFallback, g as NotificationType, n as formatNotificationText, o as canonicalNotificationType, q as DEFAULT_BASE_URL, r as normalizeNotification, s as isKnownNotificationType, st as systemClock, t as resolveNotificationUrl, tt as RuntimeMode } from "../shared/url-IU0xN9wX.js";
|
|
2
2
|
import { A as isItdStateError, C as isItdError, O as isItdRateLimitError, _ as ItdStateError, a as ItdConfigError, b as isItdApiError, c as ItdErrorKind, d as ItdForbiddenError, f as ItdNetworkError, g as ItdServerError, h as ItdRateLimitError, i as ItdAuthError, n as ItdApiError, p as ItdNotFoundError, r as ItdApiErrorKind, s as ItdError, t as ItdAbortError, v as ItdTimeoutError, x as isItdAuthError, y as ItdValidationError } from "../shared/errors-Bhrd2fJd.js";
|
|
3
|
-
import { a as RealtimeTransportKind, c as RealtimeUpdateType, i as ItdRealtime, l as UnauthorizedStreamError, n as RealtimeComposer, o as setRealtimeConnectGuard, r as RealtimeRouter, s as RealtimeUpdateOrigin, t as WebSocketTransport, u as runRealtimeMiddleware } from "../shared/websocket-
|
|
4
|
-
import { n as bearerToken, r as tokenProvider, t as anonymousAuth } from "../shared/auth-provider-
|
|
3
|
+
import { a as RealtimeTransportKind, c as RealtimeUpdateType, i as ItdRealtime, l as UnauthorizedStreamError, n as RealtimeComposer, o as setRealtimeConnectGuard, r as RealtimeRouter, s as RealtimeUpdateOrigin, t as WebSocketTransport, u as runRealtimeMiddleware } from "../shared/websocket-BLR8eVJV.js";
|
|
4
|
+
import { n as bearerToken, r as tokenProvider, t as anonymousAuth } from "../shared/auth-provider-mYqxsSVa.js";
|
|
5
5
|
//#region src/realtime/client.ts
|
|
6
6
|
/**
|
|
7
7
|
* Поток уведомлений с собственным конвейером запросов.
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_url = require("../shared/url-
|
|
2
|
+
const require_url = require("../shared/url-BaMCQpYH.cjs");
|
|
3
3
|
const require_errors = require("../shared/errors-DfU8M5eS.cjs");
|
|
4
|
-
const require_render = require("../shared/render-
|
|
4
|
+
const require_render = require("../shared/render-mcuELiYi.cjs");
|
|
5
5
|
const require_options = require("../shared/options-Dg5N3r1V.cjs");
|
|
6
|
-
const require_auth_provider = require("../shared/auth-provider-
|
|
6
|
+
const require_auth_provider = require("../shared/auth-provider-CG8oCQ9F.cjs");
|
|
7
7
|
//#region src/rest/client.ts
|
|
8
8
|
/**
|
|
9
9
|
* Минимальный клиент REST API итд.com.
|
|
@@ -23,6 +23,7 @@ const require_auth_provider = require("../shared/auth-provider-CTJkKfgy.cjs");
|
|
|
23
23
|
*/
|
|
24
24
|
var ItdRestClient = class ItdRestClient {
|
|
25
25
|
#runtime;
|
|
26
|
+
#features;
|
|
26
27
|
#resources;
|
|
27
28
|
/** Общий результат терминальной очистки для идемпотентных повторных вызовов. */
|
|
28
29
|
#disposePromise;
|
|
@@ -77,14 +78,28 @@ var ItdRestClient = class ItdRestClient {
|
|
|
77
78
|
}
|
|
78
79
|
constructor(options = {}) {
|
|
79
80
|
const { auth, ...runtimeOptions } = options;
|
|
81
|
+
const catalog = new require_render.ExtensibleOperationCatalog(require_url.ITD_CATALOG);
|
|
80
82
|
this.#runtime = require_url.createClientRuntime(runtimeOptions, {
|
|
81
|
-
catalog
|
|
83
|
+
catalog,
|
|
82
84
|
assertActive: (action) => this.#assertActive(action),
|
|
83
85
|
auth: () => resolveAuthProvider(auth)
|
|
84
86
|
});
|
|
87
|
+
this.#features = new require_render.FeatureRegistry({
|
|
88
|
+
http: this.#runtime.http,
|
|
89
|
+
services: this.#runtime.services,
|
|
90
|
+
serviceOverrides: this.#runtime.config.services,
|
|
91
|
+
catalog,
|
|
92
|
+
baseUrl: this.#runtime.config.baseUrl,
|
|
93
|
+
clock: this.#runtime.config.clock,
|
|
94
|
+
logger: this.#runtime.config.logger,
|
|
95
|
+
assertActive: (action) => this.#assertActive(action),
|
|
96
|
+
registerBucket: (name, definition) => this.#runtime.registerRateLimitBucket(name, definition)
|
|
97
|
+
});
|
|
98
|
+
const status = this.#features.install(require_render.createStatusFeature());
|
|
85
99
|
this.#resources = require_render.createResources({
|
|
86
100
|
http: this.#runtime.http,
|
|
87
|
-
fetch: this.#runtime.config.fetch
|
|
101
|
+
fetch: this.#runtime.config.fetch,
|
|
102
|
+
status
|
|
88
103
|
});
|
|
89
104
|
}
|
|
90
105
|
#assertActive(action) {
|
|
@@ -117,6 +132,33 @@ var ItdRestClient = class ItdRestClient {
|
|
|
117
132
|
rateLimitState() {
|
|
118
133
|
return this.#runtime.rateLimitState();
|
|
119
134
|
}
|
|
135
|
+
/** Устанавливает REST feature поверх общего request pipeline клиента. */
|
|
136
|
+
install(feature) {
|
|
137
|
+
return this.#features.install(feature);
|
|
138
|
+
}
|
|
139
|
+
/** Устанавливает REST feature и публикует его API как readonly-свойство клиента. */
|
|
140
|
+
withFeature(key, feature) {
|
|
141
|
+
this.#assertActive("установить feature");
|
|
142
|
+
if (typeof key !== "string" || key.trim() === "" || key !== key.trim()) throw new require_errors.ItdConfigError("Свойство feature должно иметь непустое имя без краевых пробелов");
|
|
143
|
+
if (key === "then" || key in this) throw new require_errors.ItdConfigError(`Свойство клиента «${key}» уже занято или зарезервировано`);
|
|
144
|
+
if (!Object.isExtensible(this)) throw new require_errors.ItdConfigError("Нельзя опубликовать feature на нерасширяемом клиенте");
|
|
145
|
+
const api = this.install(feature);
|
|
146
|
+
Object.defineProperty(this, key, {
|
|
147
|
+
value: api,
|
|
148
|
+
enumerable: true,
|
|
149
|
+
configurable: false,
|
|
150
|
+
writable: false
|
|
151
|
+
});
|
|
152
|
+
return this;
|
|
153
|
+
}
|
|
154
|
+
/** Имена установленных feature в порядке установки. */
|
|
155
|
+
featureNames() {
|
|
156
|
+
return this.#features.names();
|
|
157
|
+
}
|
|
158
|
+
/** Установлен ли feature с таким именем. */
|
|
159
|
+
hasFeature(name) {
|
|
160
|
+
return this.#features.has(name);
|
|
161
|
+
}
|
|
120
162
|
/**
|
|
121
163
|
* Подключает плагин.
|
|
122
164
|
*
|
|
@@ -169,11 +211,23 @@ var ItdRestClient = class ItdRestClient {
|
|
|
169
211
|
* это {@link dispose}.
|
|
170
212
|
*/
|
|
171
213
|
async close() {
|
|
214
|
+
const errors = [];
|
|
172
215
|
try {
|
|
173
|
-
|
|
216
|
+
try {
|
|
217
|
+
await this.#features.close();
|
|
218
|
+
} catch (error) {
|
|
219
|
+
errors.push(error);
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
await this.#resources.closeTelemetry(false);
|
|
223
|
+
} catch (error) {
|
|
224
|
+
errors.push(error);
|
|
225
|
+
}
|
|
174
226
|
} finally {
|
|
175
227
|
this.#runtime.close();
|
|
176
228
|
}
|
|
229
|
+
if (errors.length === 1) throw errors[0];
|
|
230
|
+
if (errors.length > 1) throw new AggregateError(errors, "Не удалось закрыть клиент");
|
|
177
231
|
}
|
|
178
232
|
/**
|
|
179
233
|
* Окончательно освобождает клиент: выполняет {@link close}, отменяет незавершённые
|
|
@@ -196,11 +250,21 @@ var ItdRestClient = class ItdRestClient {
|
|
|
196
250
|
async #dispose() {
|
|
197
251
|
const errors = [];
|
|
198
252
|
this.#resources.prepareTelemetryClose();
|
|
253
|
+
try {
|
|
254
|
+
await this.#features.close();
|
|
255
|
+
} catch (error) {
|
|
256
|
+
errors.push(error);
|
|
257
|
+
}
|
|
199
258
|
try {
|
|
200
259
|
await this.#resources.closeTelemetry(true);
|
|
201
260
|
} catch (error) {
|
|
202
261
|
errors.push(error);
|
|
203
262
|
}
|
|
263
|
+
try {
|
|
264
|
+
await this.#features.dispose();
|
|
265
|
+
} catch (error) {
|
|
266
|
+
errors.push(error);
|
|
267
|
+
}
|
|
204
268
|
try {
|
|
205
269
|
this.#runtime.close();
|
|
206
270
|
await this.#runtime.dispose();
|
package/dist/rest/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#runtime","#resources","createClientRuntime","ITD_CATALOG","#assertActive","createResources","#disposed","ItdStateError","#disposePromise","#dispose","anonymousAuth","bearerToken"],"sources":["../../src/rest/client.ts"],"sourcesContent":["import { installAsyncDisposeFallback } from '../core/async-dispose.js';\nimport { type AuthProvider, anonymousAuth, bearerToken } from '../core/auth-provider.js';\nimport { ItdStateError } from '../core/errors.js';\nimport { type ClientRuntime, createClientRuntime } from '../core/execution/client-runtime.js';\nimport type { RawRequestOptions, RuntimeOptions } from '../core/options.js';\nimport type { ClientPlugin } from '../core/plugins/contracts.js';\nimport type { RateLimitBucketState } from '../core/scheduling/rate-limit.js';\nimport type { ServiceDefinition } from '../core/services.js';\nimport { ITD_CATALOG } from '../domain/catalog.js';\nimport type { CommentsResource } from '../resources/comments.js';\nimport type { FilesResource } from '../resources/files.js';\nimport type { HashtagsResource } from '../resources/hashtags.js';\nimport type { NotificationsResource } from '../resources/notifications.js';\nimport type { PlatformResource } from '../resources/platform.js';\nimport type { PostsResource } from '../resources/posts.js';\nimport type { ReportsResource } from '../resources/reports.js';\nimport type { SearchResource } from '../resources/search.js';\nimport type { SubscriptionResource } from '../resources/subscription.js';\nimport type { TelemetryResource } from '../resources/telemetry.js';\nimport type { UsersResource } from '../resources/users.js';\nimport type { VerificationResource } from '../resources/verification.js';\nimport { createResources, type RestResources } from './resources.js';\n\n/** Опции конструктора {@link ItdRestClient}. */\nexport interface RestClientOptions extends RuntimeOptions {\n /**\n * Авторизация. Строка — сокращение для {@link bearerToken}.\n *\n * Без неё доступны только публичные эндпоинты. Токен здесь считается готовым: продлевать\n * его клиент не умеет и на `401` отвечает ошибкой. Сессия, которая входит по паролю\n * и продлевает себя сама, живёт в полном `ItdClient`.\n */\n auth?: string | AuthProvider | undefined;\n}\n\n/**\n * Минимальный клиент REST API итд.com.\n *\n * Тот же конвейер запросов, что и у полного клиента, — с повторами, очередью, плагинами\n * и типизированными ошибками, — но без сессии, потока событий и нескольких аккаунтов.\n * Нужен там, где токен уже есть, а размер поставки важен: серверные интеграции, воркеры,\n * браузерные приложения.\n *\n * @example\n * ```ts\n * import { createRestClient } from 'itd-api/rest';\n *\n * const api = createRestClient({ auth: process.env.ITD_TOKEN });\n * const feed = await api.posts.list({ tab: 'popular' });\n * ```\n */\nexport class ItdRestClient {\n readonly #runtime: ClientRuntime;\n readonly #resources: RestResources;\n /** Общий результат терминальной очистки для идемпотентных повторных вызовов. */\n #disposePromise: Promise<void> | undefined;\n #disposed = false;\n\n /** Профили, подписки, блокировки, приватность. */\n get users(): UsersResource {\n return this.#resources.users;\n }\n\n /** Лента, публикация, реакции, репосты, комментарии к постам. */\n get posts(): PostsResource {\n return this.#resources.posts;\n }\n\n /** Ответы на комментарии и действия над ними. */\n get comments(): CommentsResource {\n return this.#resources.comments;\n }\n\n /** Загрузка файлов и медиа. */\n get files(): FilesResource {\n return this.#resources.files;\n }\n\n /** Уведомления: список, счётчик, отметки о прочтении, настройки. */\n get notifications(): NotificationsResource {\n return this.#resources.notifications;\n }\n\n /** Хэштеги и посты по ним. */\n get hashtags(): HashtagsResource {\n return this.#resources.hashtags;\n }\n\n /** Глобальный поиск по пользователям и хэштегам. */\n get search(): SearchResource {\n return this.#resources.search;\n }\n\n /** Жалобы на контент и пользователей. */\n get reports(): ReportsResource {\n return this.#resources.reports;\n }\n\n /** Верификация профиля. */\n get verification(): VerificationResource {\n return this.#resources.verification;\n }\n\n /** Подписка и способы оплаты. */\n get subscription(): SubscriptionResource {\n return this.#resources.subscription;\n }\n\n /** Сведения о платформе: версии приложений, изменения, анонсы, баннер события. */\n get platform(): PlatformResource {\n return this.#resources.platform;\n }\n\n /** Телеметрия просмотров. */\n get telemetry(): TelemetryResource {\n return this.#resources.telemetry;\n }\n\n constructor(options: RestClientOptions = {}) {\n const { auth, ...runtimeOptions } = options;\n\n this.#runtime = createClientRuntime(runtimeOptions, {\n catalog: ITD_CATALOG,\n assertActive: (action) => this.#assertActive(action),\n auth: () => resolveAuthProvider(auth),\n });\n this.#resources = createResources({\n http: this.#runtime.http,\n fetch: this.#runtime.config.fetch,\n });\n }\n\n #assertActive(action: string): void {\n if (!this.#disposed) return;\n throw new ItdStateError(\n `Клиент уже окончательно освобождён через dispose(); нельзя ${action}. Создайте новый клиент`,\n );\n }\n\n /** Базовый URL, к которому обращается клиент. */\n get baseUrl(): string {\n return this.#runtime.config.baseUrl;\n }\n\n /**\n * Выполняет произвольный запрос к API.\n *\n * Запасной путь для случаев, когда нужного метода ещё нет или ответ сервера разошёлся\n * с документацией. Проходит через ту же авторизацию, очередь и обработку ошибок.\n *\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n request<T = unknown>(options: RawRequestOptions): Promise<T> {\n return this.#runtime.http.request<T>({\n ...options,\n operationId: options.operationId ?? 'raw',\n });\n }\n\n /**\n * Остаток серверных лимитов по бакетам, через которые уже проходили запросы.\n *\n * Пустой массив при `rateLimit: false`.\n */\n rateLimitState(): RateLimitBucketState[] {\n return this.#runtime.rateLimitState();\n }\n\n /**\n * Подключает плагин.\n *\n * Сессионная идентичность плагину не передаётся: у клиента с готовым токеном её нет.\n * Плагинам, которые изолируют состояние по аккаунту, нужен полный `ItdClient`.\n *\n * @throws {ItdConfigError} если плагин задан неверно или уже подключён\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n use(plugin: ClientPlugin): this {\n this.#assertActive('подключить плагин');\n this.#runtime.plugins.add(plugin, {\n baseUrl: this.#runtime.config.baseUrl,\n logger: this.#runtime.config.logger,\n });\n return this;\n }\n\n /**\n * Отключает плагин и освобождает заведённые им ресурсы.\n *\n * @returns `false`, если такого плагина не было\n * @throws {ItdConfigError} если от плагина зависит другой подключённый плагин\n */\n unuse(name: string): Promise<boolean> {\n return this.#runtime.plugins.remove(name);\n }\n\n /** Имена подключённых плагинов в фактическом порядке выполнения обёрток. */\n pluginNames(): string[] {\n return this.#runtime.plugins.names();\n }\n\n /** Подключён ли плагин с таким именем. */\n hasPlugin(name: string): boolean {\n return this.#runtime.plugins.has(name);\n }\n\n /**\n * Регистрирует сервис платформы — домен, отличный от основного.\n *\n * @throws {ItdConfigError} если определение неверно или имя уже занято\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n defineService(definition: ServiceDefinition): this {\n this.#assertActive('зарегистрировать сервис');\n this.#runtime.services.define(definition);\n return this;\n }\n\n /**\n * Отправляет открытые накопители {@link telemetry} и останавливает очередь запросов.\n *\n * После вызова клиентом можно пользоваться снова. Терминальное освобождение —\n * это {@link dispose}.\n */\n async close(): Promise<void> {\n try {\n await this.#resources.closeTelemetry(false);\n } finally {\n this.#runtime.close();\n }\n }\n\n /**\n * Окончательно освобождает клиент: выполняет {@link close}, отменяет незавершённые\n * запросы и отключает все плагины.\n *\n * Терминальное состояние устанавливается сразу при первом вызове; повторные вызовы\n * возвращают тот же результат очистки.\n *\n * @example\n * ```ts\n * await using api = createRestClient({ auth: token });\n * ```\n */\n dispose(): Promise<void> {\n if (this.#disposePromise) return this.#disposePromise;\n this.#disposed = true;\n this.#disposePromise = this.#dispose();\n return this.#disposePromise;\n }\n\n async #dispose(): Promise<void> {\n const errors: unknown[] = [];\n // Телеметрия уходит через ещё установленный plugin pipeline и мимо проверки состояния.\n this.#resources.prepareTelemetryClose();\n try {\n await this.#resources.closeTelemetry(true);\n } catch (error) {\n errors.push(error);\n }\n try {\n this.#runtime.close();\n await this.#runtime.dispose();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length > 0) throw new AggregateError(errors, 'Не удалось освободить клиент');\n }\n\n /** Позволяет использовать клиент с `await using`. */\n [Symbol.asyncDispose](): Promise<void> {\n return this.dispose();\n }\n\n static {\n installAsyncDisposeFallback(ItdRestClient);\n }\n}\n\n/** Приводит опцию `auth` к провайдеру конвейера. */\nfunction resolveAuthProvider(auth: RestClientOptions['auth']): AuthProvider {\n if (auth === undefined) return anonymousAuth();\n return typeof auth === 'string' ? bearerToken(auth) : auth;\n}\n\n/**\n * Создаёт минимальный клиент REST API. Равнозначно конструктору {@link ItdRestClient}.\n *\n * @example\n * ```ts\n * const api = createRestClient({ auth: token, rateLimit: { concurrency: 4 } });\n * ```\n */\nexport function createRestClient(options: RestClientOptions = {}): ItdRestClient {\n return new ItdRestClient(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAa,gBAAb,MAAa,cAAc;CACzB;CACA;;CAEA;CACA,YAAY;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;EACrC,OAAO,KAAK,QAAQ;CACtB;CAEA;EACE,YAAA,4BAA4B,aAAa;CAC3C;AACF;;AAGA,SAAS,oBAAoB,MAA+C;CAC1E,IAAI,SAAS,KAAA,GAAW,OAAOU,sBAAAA,cAAc;CAC7C,OAAO,OAAO,SAAS,WAAWC,sBAAAA,YAAY,IAAI,IAAI;AACxD;;;;;;;;;AAUA,SAAgB,iBAAiB,UAA6B,CAAC,GAAkB;CAC/E,OAAO,IAAI,cAAc,OAAO;AAClC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#runtime","#features","#resources","ExtensibleOperationCatalog","ITD_CATALOG","createClientRuntime","#assertActive","FeatureRegistry","createStatusFeature","createResources","#disposed","ItdStateError","ItdConfigError","#disposePromise","#dispose","anonymousAuth","bearerToken"],"sources":["../../src/rest/client.ts"],"sourcesContent":["import { installAsyncDisposeFallback } from '../core/async-dispose.js';\nimport { type AuthProvider, anonymousAuth, bearerToken } from '../core/auth-provider.js';\nimport { ItdConfigError, ItdStateError } from '../core/errors.js';\nimport { type ClientRuntime, createClientRuntime } from '../core/execution/client-runtime.js';\nimport { ExtensibleOperationCatalog } from '../core/feature-catalog.js';\nimport { type ClientFeature, FeatureRegistry } from '../core/features.js';\nimport type { RawRequestOptions, RuntimeOptions } from '../core/options.js';\nimport type { ClientPlugin } from '../core/plugins/contracts.js';\nimport type { RateLimitBucketState } from '../core/scheduling/rate-limit.js';\nimport type { ServiceDefinition } from '../core/services.js';\nimport { ITD_CATALOG } from '../domain/catalog.js';\nimport type { CommentsResource } from '../resources/comments.js';\nimport type { FilesResource } from '../resources/files.js';\nimport type { HashtagsResource } from '../resources/hashtags.js';\nimport type { NotificationsResource } from '../resources/notifications.js';\nimport type { PlatformResource } from '../resources/platform.js';\nimport type { PostsResource } from '../resources/posts.js';\nimport type { ReportsResource } from '../resources/reports.js';\nimport type { SearchResource } from '../resources/search.js';\nimport { createStatusFeature } from '../resources/status.js';\nimport type { SubscriptionResource } from '../resources/subscription.js';\nimport type { TelemetryResource } from '../resources/telemetry.js';\nimport type { UsersResource } from '../resources/users.js';\nimport type { VerificationResource } from '../resources/verification.js';\nimport { createResources, type RestResources } from './resources.js';\n\n/** Опции конструктора {@link ItdRestClient}. */\nexport interface RestClientOptions extends RuntimeOptions {\n /**\n * Авторизация. Строка — сокращение для {@link bearerToken}.\n *\n * Без неё доступны только публичные эндпоинты. Токен здесь считается готовым: продлевать\n * его клиент не умеет и на `401` отвечает ошибкой. Сессия, которая входит по паролю\n * и продлевает себя сама, живёт в полном `ItdClient`.\n */\n auth?: string | AuthProvider | undefined;\n}\n\n/**\n * Минимальный клиент REST API итд.com.\n *\n * Тот же конвейер запросов, что и у полного клиента, — с повторами, очередью, плагинами\n * и типизированными ошибками, — но без сессии, потока событий и нескольких аккаунтов.\n * Нужен там, где токен уже есть, а размер поставки важен: серверные интеграции, воркеры,\n * браузерные приложения.\n *\n * @example\n * ```ts\n * import { createRestClient } from 'itd-api/rest';\n *\n * const api = createRestClient({ auth: process.env.ITD_TOKEN });\n * const feed = await api.posts.list({ tab: 'popular' });\n * ```\n */\nexport class ItdRestClient {\n readonly #runtime: ClientRuntime;\n readonly #features: FeatureRegistry;\n readonly #resources: RestResources;\n /** Общий результат терминальной очистки для идемпотентных повторных вызовов. */\n #disposePromise: Promise<void> | undefined;\n #disposed = false;\n\n /** Профили, подписки, блокировки, приватность. */\n get users(): UsersResource {\n return this.#resources.users;\n }\n\n /** Лента, публикация, реакции, репосты, комментарии к постам. */\n get posts(): PostsResource {\n return this.#resources.posts;\n }\n\n /** Ответы на комментарии и действия над ними. */\n get comments(): CommentsResource {\n return this.#resources.comments;\n }\n\n /** Загрузка файлов и медиа. */\n get files(): FilesResource {\n return this.#resources.files;\n }\n\n /** Уведомления: список, счётчик, отметки о прочтении, настройки. */\n get notifications(): NotificationsResource {\n return this.#resources.notifications;\n }\n\n /** Хэштеги и посты по ним. */\n get hashtags(): HashtagsResource {\n return this.#resources.hashtags;\n }\n\n /** Глобальный поиск по пользователям и хэштегам. */\n get search(): SearchResource {\n return this.#resources.search;\n }\n\n /** Жалобы на контент и пользователей. */\n get reports(): ReportsResource {\n return this.#resources.reports;\n }\n\n /** Верификация профиля. */\n get verification(): VerificationResource {\n return this.#resources.verification;\n }\n\n /** Подписка и способы оплаты. */\n get subscription(): SubscriptionResource {\n return this.#resources.subscription;\n }\n\n /** Сведения о платформе: версии приложений, изменения, анонсы, баннер события. */\n get platform(): PlatformResource {\n return this.#resources.platform;\n }\n\n /** Телеметрия просмотров. */\n get telemetry(): TelemetryResource {\n return this.#resources.telemetry;\n }\n\n constructor(options: RestClientOptions = {}) {\n const { auth, ...runtimeOptions } = options;\n const catalog = new ExtensibleOperationCatalog(ITD_CATALOG);\n\n this.#runtime = createClientRuntime(runtimeOptions, {\n catalog,\n assertActive: (action) => this.#assertActive(action),\n auth: () => resolveAuthProvider(auth),\n });\n this.#features = new FeatureRegistry({\n http: this.#runtime.http,\n services: this.#runtime.services,\n serviceOverrides: this.#runtime.config.services,\n catalog,\n baseUrl: this.#runtime.config.baseUrl,\n clock: this.#runtime.config.clock,\n logger: this.#runtime.config.logger,\n assertActive: (action) => this.#assertActive(action),\n registerBucket: (name, definition) => this.#runtime.registerRateLimitBucket(name, definition),\n });\n const status = this.#features.install(createStatusFeature());\n this.#resources = createResources({\n http: this.#runtime.http,\n fetch: this.#runtime.config.fetch,\n status,\n });\n }\n\n #assertActive(action: string): void {\n if (!this.#disposed) return;\n throw new ItdStateError(\n `Клиент уже окончательно освобождён через dispose(); нельзя ${action}. Создайте новый клиент`,\n );\n }\n\n /** Базовый URL, к которому обращается клиент. */\n get baseUrl(): string {\n return this.#runtime.config.baseUrl;\n }\n\n /**\n * Выполняет произвольный запрос к API.\n *\n * Запасной путь для случаев, когда нужного метода ещё нет или ответ сервера разошёлся\n * с документацией. Проходит через ту же авторизацию, очередь и обработку ошибок.\n *\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n request<T = unknown>(options: RawRequestOptions): Promise<T> {\n return this.#runtime.http.request<T>({\n ...options,\n operationId: options.operationId ?? 'raw',\n });\n }\n\n /**\n * Остаток серверных лимитов по бакетам, через которые уже проходили запросы.\n *\n * Пустой массив при `rateLimit: false`.\n */\n rateLimitState(): RateLimitBucketState[] {\n return this.#runtime.rateLimitState();\n }\n\n /** Устанавливает REST feature поверх общего request pipeline клиента. */\n install<TApi>(feature: ClientFeature<TApi>): TApi {\n return this.#features.install(feature);\n }\n\n /** Устанавливает REST feature и публикует его API как readonly-свойство клиента. */\n withFeature<const K extends string, TApi>(\n key: K,\n feature: ClientFeature<TApi>,\n ): this & { readonly [P in K]: TApi } {\n this.#assertActive('установить feature');\n if (typeof key !== 'string' || key.trim() === '' || key !== key.trim()) {\n throw new ItdConfigError('Свойство feature должно иметь непустое имя без краевых пробелов');\n }\n if (key === 'then' || key in this) {\n throw new ItdConfigError(`Свойство клиента «${key}» уже занято или зарезервировано`);\n }\n if (!Object.isExtensible(this)) {\n throw new ItdConfigError('Нельзя опубликовать feature на нерасширяемом клиенте');\n }\n\n const api = this.install(feature);\n Object.defineProperty(this, key, {\n value: api,\n enumerable: true,\n configurable: false,\n writable: false,\n });\n return this as this & { readonly [P in K]: TApi };\n }\n\n /** Имена установленных feature в порядке установки. */\n featureNames(): string[] {\n return this.#features.names();\n }\n\n /** Установлен ли feature с таким именем. */\n hasFeature(name: string): boolean {\n return this.#features.has(name);\n }\n\n /**\n * Подключает плагин.\n *\n * Сессионная идентичность плагину не передаётся: у клиента с готовым токеном её нет.\n * Плагинам, которые изолируют состояние по аккаунту, нужен полный `ItdClient`.\n *\n * @throws {ItdConfigError} если плагин задан неверно или уже подключён\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n use(plugin: ClientPlugin): this {\n this.#assertActive('подключить плагин');\n this.#runtime.plugins.add(plugin, {\n baseUrl: this.#runtime.config.baseUrl,\n logger: this.#runtime.config.logger,\n });\n return this;\n }\n\n /**\n * Отключает плагин и освобождает заведённые им ресурсы.\n *\n * @returns `false`, если такого плагина не было\n * @throws {ItdConfigError} если от плагина зависит другой подключённый плагин\n */\n unuse(name: string): Promise<boolean> {\n return this.#runtime.plugins.remove(name);\n }\n\n /** Имена подключённых плагинов в фактическом порядке выполнения обёрток. */\n pluginNames(): string[] {\n return this.#runtime.plugins.names();\n }\n\n /** Подключён ли плагин с таким именем. */\n hasPlugin(name: string): boolean {\n return this.#runtime.plugins.has(name);\n }\n\n /**\n * Регистрирует сервис платформы — домен, отличный от основного.\n *\n * @throws {ItdConfigError} если определение неверно или имя уже занято\n * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}\n */\n defineService(definition: ServiceDefinition): this {\n this.#assertActive('зарегистрировать сервис');\n this.#runtime.services.define(definition);\n return this;\n }\n\n /**\n * Отправляет открытые накопители {@link telemetry} и останавливает очередь запросов.\n *\n * После вызова клиентом можно пользоваться снова. Терминальное освобождение —\n * это {@link dispose}.\n */\n async close(): Promise<void> {\n const errors: unknown[] = [];\n try {\n try {\n await this.#features.close();\n } catch (error) {\n errors.push(error);\n }\n try {\n await this.#resources.closeTelemetry(false);\n } catch (error) {\n errors.push(error);\n }\n } finally {\n this.#runtime.close();\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'Не удалось закрыть клиент');\n }\n\n /**\n * Окончательно освобождает клиент: выполняет {@link close}, отменяет незавершённые\n * запросы и отключает все плагины.\n *\n * Терминальное состояние устанавливается сразу при первом вызове; повторные вызовы\n * возвращают тот же результат очистки.\n *\n * @example\n * ```ts\n * await using api = createRestClient({ auth: token });\n * ```\n */\n dispose(): Promise<void> {\n if (this.#disposePromise) return this.#disposePromise;\n this.#disposed = true;\n this.#disposePromise = this.#dispose();\n return this.#disposePromise;\n }\n\n async #dispose(): Promise<void> {\n const errors: unknown[] = [];\n // Телеметрия уходит через ещё установленный plugin pipeline и мимо проверки состояния.\n this.#resources.prepareTelemetryClose();\n try {\n await this.#features.close();\n } catch (error) {\n errors.push(error);\n }\n try {\n await this.#resources.closeTelemetry(true);\n } catch (error) {\n errors.push(error);\n }\n try {\n await this.#features.dispose();\n } catch (error) {\n errors.push(error);\n }\n try {\n this.#runtime.close();\n await this.#runtime.dispose();\n } catch (error) {\n errors.push(error);\n }\n if (errors.length > 0) throw new AggregateError(errors, 'Не удалось освободить клиент');\n }\n\n /** Позволяет использовать клиент с `await using`. */\n [Symbol.asyncDispose](): Promise<void> {\n return this.dispose();\n }\n\n static {\n installAsyncDisposeFallback(ItdRestClient);\n }\n}\n\n/** Приводит опцию `auth` к провайдеру конвейера. */\nfunction resolveAuthProvider(auth: RestClientOptions['auth']): AuthProvider {\n if (auth === undefined) return anonymousAuth();\n return typeof auth === 'string' ? bearerToken(auth) : auth;\n}\n\n/**\n * Создаёт минимальный клиент REST API. Равнозначно конструктору {@link ItdRestClient}.\n *\n * @example\n * ```ts\n * const api = createRestClient({ auth: token, rateLimit: { concurrency: 4 } });\n * ```\n */\nexport function createRestClient(options: RestClientOptions = {}): ItdRestClient {\n return new ItdRestClient(options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,gBAAb,MAAa,cAAc;CACzB;CACA;CACA;;CAEA;CACA,YAAY;;CAGZ,IAAI,QAAuB;EACzB,OAAO,KAAKE,WAAW;CACzB;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,WAA6B;EAC/B,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,gBAAuC;EACzC,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,WAA6B;EAC/B,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,SAAyB;EAC3B,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,UAA2B;EAC7B,OAAO,KAAKA,WAAW;CACzB;;CAGA,IAAI,eAAqC;EACvC,OAAO,KAAKA,WAAW;CACzB;;CAGA,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,cAAc;CAC7C,OAAO,OAAO,SAAS,WAAWC,sBAAAA,YAAY,IAAI,IAAI;AACxD;;;;;;;;;AAUA,SAAgB,iBAAiB,UAA6B,CAAC,GAAkB;CAC/E,OAAO,IAAI,cAAc,OAAO;AAClC"}
|
package/dist/rest/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as UserSummary, $t as RateLimitPacing, A as isItdFileError, B as Notification, Bt as RateLimitOptions, C as ItdStateError, Ct as ReportReason, D as isItdAuthError, Dt as ViewReason, E as isItdApiError, Et as SpanType, F as isItdServerError, Ft as Logger, G as FollowResult, Gt as ResponseContext, H as Actor, Ht as RequestContext, I as isItdStateError, It as OperationRequestOptions, J as PinsResult, Jt as RetryOptions, K as MyProfile, Kt as RetryContext, L as isItdValidationError, Lt as PaginationOptions, M as isItdNotFoundError, Mt as Unsubscribe, N as isItdPhoneVerificationError, Nt as ClientHooks, O as isItdConflictError, Ot as ViewSource, P as isItdRateLimitError, Pt as ErrorContextHook, Q as SubscriptionState, Qt as ServiceDefinition, R as NotificationEvent, Rt as RateLimitBucketContext, S as ItdServerError, T as ItdValidationError, Tt as ServiceState, Ut as RequestExtensions, V as NotificationSettings, Vt as RawRequestOptions, W as Author, Wt as RequestOptions, X as Profile, Xt as QueryParams, Y as PrivacySettings, Yt as RuntimeOptions, Z as PublicProfile, Zt as QueryValue, _ as ItdForbiddenError, _t as InteractionType, a as ItdAbortError, an as ItdOperationDefinition, at as DEFAULT_BASE_URL, b as ItdPhoneVerificationError, bt as Loose, c as ItdApiErrorKind, cn as isBuiltInOperationId, ct as IsoDate, d as ItdConflictError, dn as operationRetrySafety, dt as UserRef, en as RuntimeMode, f as ItdError, fn as BUCKET_LIMITS, ft as AccessType, g as ItdFileErrorReason, gn as
|
|
2
|
-
import { $ as poll, $t as CreatePostData, A as TelemetryResource, At as FilesResource, B as ReportInput, Bt as PinPostResult, C as DwellEntry, Ct as Report, D as TelemetryBatchOptions, Dt as UpdateNotificationSettingsInput, E as TelemetryBatch, Et as NotificationsResource, F as SubscriptionResource, Ft as Attachment, G as UserPostsParams, Gt as CommentBuilder, H as CommentsParams, Ht as PollOption, I as SearchResource, It as Comment, J as PostInput, Jt as BuilderInput, K as CreatePostInput, Kt as CommentInput, L as SearchResult, Lt as CommentReplyTo, M as ViewTracker, Mt as UploadedFile, N as ViewTrackerInput, Nt as CommentsResource, O as TelemetryClock, Ot as HashtagPostsParams, P as ViewTrackerOptions, Pt as RepliesParams, Q as PollInput, Qt as CreatePollInput, R as ReportsResource, Rt as Hashtag, S as UsersResource, Sn as
|
|
1
|
+
import { $ as UserSummary, $t as RateLimitPacing, A as isItdFileError, B as Notification, Bt as RateLimitOptions, C as ItdStateError, Ct as ReportReason, D as isItdAuthError, Dt as ViewReason, E as isItdApiError, Et as SpanType, F as isItdServerError, Ft as Logger, G as FollowResult, Gt as ResponseContext, H as Actor, Ht as RequestContext, I as isItdStateError, It as OperationRequestOptions, J as PinsResult, Jt as RetryOptions, K as MyProfile, Kt as RetryContext, L as isItdValidationError, Lt as PaginationOptions, M as isItdNotFoundError, Mt as Unsubscribe, N as isItdPhoneVerificationError, Nt as ClientHooks, O as isItdConflictError, Ot as ViewSource, P as isItdRateLimitError, Pt as ErrorContextHook, Q as SubscriptionState, Qt as ServiceDefinition, R as NotificationEvent, Rt as RateLimitBucketContext, S as ItdServerError, T as ItdValidationError, Tt as ServiceState, Ut as RequestExtensions, V as NotificationSettings, Vt as RawRequestOptions, W as Author, Wt as RequestOptions, X as Profile, Xt as QueryParams, Y as PrivacySettings, Yt as RuntimeOptions, Z as PublicProfile, Zt as QueryValue, _ as ItdForbiddenError, _n as RetrySafety, _t as InteractionType, a as ItdAbortError, an as ItdOperationDefinition, at as DEFAULT_BASE_URL, b as ItdPhoneVerificationError, bt as Loose, c as ItdApiErrorKind, cn as isBuiltInOperationId, ct as IsoDate, d as ItdConflictError, dn as operationRetrySafety, dt as UserRef, en as RuntimeMode, f as ItdError, fn as BUCKET_LIMITS, ft as AccessType, g as ItdFileErrorReason, gn as OperationMethod, gt as IncidentKind, h as ItdFileError, hn as FeatureOperationId, ht as FeedTab, i as formatNotificationText, in as CustomOperationId, it as tokenProvider, j as isItdForbiddenError, jt as Listener, k as isItdError, kt as WallAccess, l as ItdAuthError, ln as operationBucket, lt as Span, m as ItdFieldErrors, mn as RateLimitBucket, mt as CommentSort, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, on as OPERATIONS, ot as STATUS_SERVICE, p as ItdErrorKind, pn as DEFAULT_RATE_LIMIT_BUCKET, pt as AttachmentType, q as Pin, qt as RetryDecisionContext, r as isKnownNotificationType, rn as BuiltInOperationId, rt as bearerToken, s as ItdApiErrorInit, sn as OperationId, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, un as operationMethod, ut as UserId, v as ItdNetworkError, vt as ItdErrorCode, w as ItdTimeoutError, wt as ReportTargetType, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, yt as LikesVisibility, z as normalizeNotification, zt as RateLimitBucketOverride } from "../shared/url-DTfZ2toq.cjs";
|
|
2
|
+
import { $ as poll, $t as CreatePostData, A as TelemetryResource, At as FilesResource, B as ReportInput, Bt as PinPostResult, C as DwellEntry, Cn as FeatureBucketDefinition, Ct as Report, D as TelemetryBatchOptions, Dn as FeatureRequestOptions, Dt as UpdateNotificationSettingsInput, E as TelemetryBatch, En as FeatureOperationDefinition, Et as NotificationsResource, F as SubscriptionResource, Ft as Attachment, G as UserPostsParams, Gt as CommentBuilder, H as CommentsParams, Ht as PollOption, I as SearchResource, It as Comment, J as PostInput, Jt as BuilderInput, K as CreatePostInput, Kt as CommentInput, L as SearchResult, Lt as CommentReplyTo, M as ViewTracker, Mt as UploadedFile, N as ViewTrackerInput, Nt as CommentsResource, O as TelemetryClock, Ot as HashtagPostsParams, P as ViewTrackerOptions, Pt as RepliesParams, Q as PollInput, Qt as CreatePollInput, R as ReportsResource, Rt as Hashtag, S as UsersResource, Sn as ClientFeature, St as Portal, T as PhotoOpenInput, Tn as FeatureInstallation, Tt as NotificationListParams, U as FeedParams, Ut as Post, V as report, Vt as Poll, W as PostsResource, Wt as PostStats, X as post, Xt as isBuilder, Y as PostUpdateInput, Yt as ItdBuilder, Z as PollBuilder, Zt as CreateCommentInput, _ as fromUrl, _n as ClientPlugin, _t as StatusIncidentLine, a as isMyProfile, an as PaginationMode, at as MarkupContent, b as UpdateProfileInput, bn as PluginApi, bt as ChangelogEntry, c as ALLOWED_MIME_TYPES, cn as mapPage, ct as TextMarkup, d as AudioMimeType, dn as Subscription, dt as PlatformClientVersion, en as CreateReportInput, et as ParseMarkupOptions, f as IMAGE_MIME_TYPES, fn as RateLimitBucketState, ft as PlatformResource, g as fromStream, gn as AttemptNext, gt as StatusDay, h as VideoMimeType, hn as AttemptInterceptor, ht as ServiceStatus, i as statusDays, in as PageState, it as MarkupBuilder, j as VideoProgressInput, jt as UploadOptions, k as TelemetryOptions, kt as HashtagsResource, l as AUDIO_MIME_TYPES, ln as PaymentMethod, lt as autoSpans, m as VIDEO_MIME_TYPES, mn as AttemptExtensions, mt as PlatformStatus, n as SpanRenderFormat, nt as parseMarkdown, o as toDate, on as Paginator, ot as MarkupInput, p as ImageMimeType, pn as AttemptContext, pt as PlatformVersions, q as PostBuilder, qt as comment, r as renderSpans, rn as Page, rt as AutoSpansOptions, s as utcStampToIso, sn as PaginatorOptions, st as MarkupSpan, t as RenderSpansOptions, tn as UpdatePostInput, tt as parseHtml, u as AllowedMimeType, un as Session, ut as markup, v as VerificationResource, vn as OperationExtensions, vt as Announcement, w as InteractionEntry, wn as FeatureContext, wt as VerificationStatus, x as UserListParams, xn as PluginTeardown, xt as Clan, y as UpdatePrivacyInput, yn as OperationTransformer, yt as AnnouncementButton, z as ReportBuilder, zt as LikeResult } from "../shared/render-DO0F5YSm.cjs";
|
|
3
3
|
import { a as FileStreamOptions, c as LazyFile, d as UrlFileOptions, i as FileStreamContent, l as StreamFile, n as FileContext, o as FileTransferMode, r as FileInput, s as FromStreamOptions, t as FileContent, u as UrlFile } from "../shared/contracts-BoT7msmq.cjs";
|
|
4
4
|
//#region src/rest/client.d.ts
|
|
5
5
|
/** Опции конструктора {@link ItdRestClient}. */
|
|
@@ -73,6 +73,14 @@ declare class ItdRestClient {
|
|
|
73
73
|
* Пустой массив при `rateLimit: false`.
|
|
74
74
|
*/
|
|
75
75
|
rateLimitState(): RateLimitBucketState[];
|
|
76
|
+
/** Устанавливает REST feature поверх общего request pipeline клиента. */
|
|
77
|
+
install<TApi>(feature: ClientFeature<TApi>): TApi;
|
|
78
|
+
/** Устанавливает REST feature и публикует его API как readonly-свойство клиента. */
|
|
79
|
+
withFeature<const K extends string, TApi>(key: K, feature: ClientFeature<TApi>): this & { readonly [P in K]: TApi; };
|
|
80
|
+
/** Имена установленных feature в порядке установки. */
|
|
81
|
+
featureNames(): string[];
|
|
82
|
+
/** Установлен ли feature с таким именем. */
|
|
83
|
+
hasFeature(name: string): boolean;
|
|
76
84
|
/**
|
|
77
85
|
* Подключает плагин.
|
|
78
86
|
*
|
|
@@ -134,5 +142,5 @@ declare class ItdRestClient {
|
|
|
134
142
|
*/
|
|
135
143
|
declare function createRestClient(options?: RestClientOptions): ItdRestClient;
|
|
136
144
|
//#endregion
|
|
137
|
-
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, type Actor, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthProvider, type Author, type AutoSpansOptions, BUCKET_LIMITS, type BuilderInput, type BuiltInOperationId, type ChangelogEntry, type Clan, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, type DwellEntry, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRestClient, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, type MyProfile, type Notification, type NotificationEvent, type NotificationListParams, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type ItdOperationDefinition as OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, type RateLimitBucket, type RateLimitBucketContext, type RateLimitBucketOverride, type RateLimitBucketState, type RateLimitOptions, RateLimitPacing, type RawRequestOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResponseContext, type RestClientOptions, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, type RuntimeOptions, STATUS_SERVICE, type SearchResource, type SearchResult, type ServiceDefinition, ServiceState, type ServiceStatus, type Session, type Span, SpanRenderFormat, SpanType, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, anonymousAuth, autoSpans, bearerToken, canonicalNotificationType, comment, createRestClient, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, statusDays, systemClock, toDate, tokenProvider, utcStampToIso };
|
|
145
|
+
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, type Actor, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthProvider, type Author, type AutoSpansOptions, BUCKET_LIMITS, type BuilderInput, type BuiltInOperationId, type ChangelogEntry, type Clan, type ClientFeature, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, type DwellEntry, type ErrorContextHook, type FeatureBucketDefinition, type FeatureContext, type FeatureInstallation, type FeatureOperationDefinition, type FeatureOperationId, type FeatureRequestOptions, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRestClient, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, type MyProfile, type Notification, type NotificationEvent, type NotificationListParams, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type ItdOperationDefinition as OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, type RateLimitBucket, type RateLimitBucketContext, type RateLimitBucketOverride, type RateLimitBucketState, type RateLimitOptions, RateLimitPacing, type RawRequestOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResponseContext, type RestClientOptions, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, type RuntimeOptions, STATUS_SERVICE, type SearchResource, type SearchResult, type ServiceDefinition, ServiceState, type ServiceStatus, type Session, type Span, SpanRenderFormat, SpanType, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, anonymousAuth, autoSpans, bearerToken, canonicalNotificationType, comment, createRestClient, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, statusDays, systemClock, toDate, tokenProvider, utcStampToIso };
|
|
138
146
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/rest/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as UserSummary, $t as RateLimitPacing, A as isItdFileError, B as Notification, Bt as RateLimitOptions, C as ItdStateError, Ct as ReportReason, D as isItdAuthError, Dt as ViewReason, E as isItdApiError, Et as SpanType, F as isItdServerError, Ft as Logger, G as FollowResult, Gt as ResponseContext, H as Actor, Ht as RequestContext, I as isItdStateError, It as OperationRequestOptions, J as PinsResult, Jt as RetryOptions, K as MyProfile, Kt as RetryContext, L as isItdValidationError, Lt as PaginationOptions, M as isItdNotFoundError, Mt as Unsubscribe, N as isItdPhoneVerificationError, Nt as ClientHooks, O as isItdConflictError, Ot as ViewSource, P as isItdRateLimitError, Pt as ErrorContextHook, Q as SubscriptionState, Qt as ServiceDefinition, R as NotificationEvent, Rt as RateLimitBucketContext, S as ItdServerError, T as ItdValidationError, Tt as ServiceState, Ut as RequestExtensions, V as NotificationSettings, Vt as RawRequestOptions, W as Author, Wt as RequestOptions, X as Profile, Xt as QueryParams, Y as PrivacySettings, Yt as RuntimeOptions, Z as PublicProfile, Zt as QueryValue, _ as ItdForbiddenError, _t as InteractionType, a as ItdAbortError, an as ItdOperationDefinition, at as DEFAULT_BASE_URL, b as ItdPhoneVerificationError, bt as Loose, c as ItdApiErrorKind, cn as isBuiltInOperationId, ct as IsoDate, d as ItdConflictError, dn as operationRetrySafety, dt as UserRef, en as RuntimeMode, f as ItdError, fn as BUCKET_LIMITS, ft as AccessType, g as ItdFileErrorReason, gn as
|
|
2
|
-
import { $ as poll, $t as CreatePostData, A as TelemetryResource, At as FilesResource, B as ReportInput, Bt as PinPostResult, C as DwellEntry, Ct as Report, D as TelemetryBatchOptions, Dt as UpdateNotificationSettingsInput, E as TelemetryBatch, Et as NotificationsResource, F as SubscriptionResource, Ft as Attachment, G as UserPostsParams, Gt as CommentBuilder, H as CommentsParams, Ht as PollOption, I as SearchResource, It as Comment, J as PostInput, Jt as BuilderInput, K as CreatePostInput, Kt as CommentInput, L as SearchResult, Lt as CommentReplyTo, M as ViewTracker, Mt as UploadedFile, N as ViewTrackerInput, Nt as CommentsResource, O as TelemetryClock, Ot as HashtagPostsParams, P as ViewTrackerOptions, Pt as RepliesParams, Q as PollInput, Qt as CreatePollInput, R as ReportsResource, Rt as Hashtag, S as UsersResource, Sn as
|
|
1
|
+
import { $ as UserSummary, $t as RateLimitPacing, A as isItdFileError, B as Notification, Bt as RateLimitOptions, C as ItdStateError, Ct as ReportReason, D as isItdAuthError, Dt as ViewReason, E as isItdApiError, Et as SpanType, F as isItdServerError, Ft as Logger, G as FollowResult, Gt as ResponseContext, H as Actor, Ht as RequestContext, I as isItdStateError, It as OperationRequestOptions, J as PinsResult, Jt as RetryOptions, K as MyProfile, Kt as RetryContext, L as isItdValidationError, Lt as PaginationOptions, M as isItdNotFoundError, Mt as Unsubscribe, N as isItdPhoneVerificationError, Nt as ClientHooks, O as isItdConflictError, Ot as ViewSource, P as isItdRateLimitError, Pt as ErrorContextHook, Q as SubscriptionState, Qt as ServiceDefinition, R as NotificationEvent, Rt as RateLimitBucketContext, S as ItdServerError, T as ItdValidationError, Tt as ServiceState, Ut as RequestExtensions, V as NotificationSettings, Vt as RawRequestOptions, W as Author, Wt as RequestOptions, X as Profile, Xt as QueryParams, Y as PrivacySettings, Yt as RuntimeOptions, Z as PublicProfile, Zt as QueryValue, _ as ItdForbiddenError, _n as RetrySafety, _t as InteractionType, a as ItdAbortError, an as ItdOperationDefinition, at as DEFAULT_BASE_URL, b as ItdPhoneVerificationError, bt as Loose, c as ItdApiErrorKind, cn as isBuiltInOperationId, ct as IsoDate, d as ItdConflictError, dn as operationRetrySafety, dt as UserRef, en as RuntimeMode, f as ItdError, fn as BUCKET_LIMITS, ft as AccessType, g as ItdFileErrorReason, gn as OperationMethod, gt as IncidentKind, h as ItdFileError, hn as FeatureOperationId, ht as FeedTab, i as formatNotificationText, in as CustomOperationId, it as tokenProvider, j as isItdForbiddenError, jt as Listener, k as isItdError, kt as WallAccess, l as ItdAuthError, ln as operationBucket, lt as Span, m as ItdFieldErrors, mn as RateLimitBucket, mt as CommentSort, n as canonicalNotificationType, nn as systemClock, nt as anonymousAuth, o as ItdApiError, on as OPERATIONS, ot as STATUS_SERVICE, p as ItdErrorKind, pn as DEFAULT_RATE_LIMIT_BUCKET, pt as AttachmentType, q as Pin, qt as RetryDecisionContext, r as isKnownNotificationType, rn as BuiltInOperationId, rt as bearerToken, s as ItdApiErrorInit, sn as OperationId, st as LIBRARY_VERSION, t as resolveNotificationUrl, tn as ItdClock, tt as AuthProvider, u as ItdConfigError, un as operationMethod, ut as UserId, v as ItdNetworkError, vt as ItdErrorCode, w as ItdTimeoutError, wt as ReportTargetType, x as ItdRateLimitError, xt as NotificationType, y as ItdNotFoundError, yt as LikesVisibility, z as normalizeNotification, zt as RateLimitBucketOverride } from "../shared/url-DTfZ2toq.js";
|
|
2
|
+
import { $ as poll, $t as CreatePostData, A as TelemetryResource, At as FilesResource, B as ReportInput, Bt as PinPostResult, C as DwellEntry, Cn as FeatureBucketDefinition, Ct as Report, D as TelemetryBatchOptions, Dn as FeatureRequestOptions, Dt as UpdateNotificationSettingsInput, E as TelemetryBatch, En as FeatureOperationDefinition, Et as NotificationsResource, F as SubscriptionResource, Ft as Attachment, G as UserPostsParams, Gt as CommentBuilder, H as CommentsParams, Ht as PollOption, I as SearchResource, It as Comment, J as PostInput, Jt as BuilderInput, K as CreatePostInput, Kt as CommentInput, L as SearchResult, Lt as CommentReplyTo, M as ViewTracker, Mt as UploadedFile, N as ViewTrackerInput, Nt as CommentsResource, O as TelemetryClock, Ot as HashtagPostsParams, P as ViewTrackerOptions, Pt as RepliesParams, Q as PollInput, Qt as CreatePollInput, R as ReportsResource, Rt as Hashtag, S as UsersResource, Sn as ClientFeature, St as Portal, T as PhotoOpenInput, Tn as FeatureInstallation, Tt as NotificationListParams, U as FeedParams, Ut as Post, V as report, Vt as Poll, W as PostsResource, Wt as PostStats, X as post, Xt as isBuilder, Y as PostUpdateInput, Yt as ItdBuilder, Z as PollBuilder, Zt as CreateCommentInput, _ as fromUrl, _n as ClientPlugin, _t as StatusIncidentLine, a as isMyProfile, an as PaginationMode, at as MarkupContent, b as UpdateProfileInput, bn as PluginApi, bt as ChangelogEntry, c as ALLOWED_MIME_TYPES, cn as mapPage, ct as TextMarkup, d as AudioMimeType, dn as Subscription, dt as PlatformClientVersion, en as CreateReportInput, et as ParseMarkupOptions, f as IMAGE_MIME_TYPES, fn as RateLimitBucketState, ft as PlatformResource, g as fromStream, gn as AttemptNext, gt as StatusDay, h as VideoMimeType, hn as AttemptInterceptor, ht as ServiceStatus, i as statusDays, in as PageState, it as MarkupBuilder, j as VideoProgressInput, jt as UploadOptions, k as TelemetryOptions, kt as HashtagsResource, l as AUDIO_MIME_TYPES, ln as PaymentMethod, lt as autoSpans, m as VIDEO_MIME_TYPES, mn as AttemptExtensions, mt as PlatformStatus, n as SpanRenderFormat, nt as parseMarkdown, o as toDate, on as Paginator, ot as MarkupInput, p as ImageMimeType, pn as AttemptContext, pt as PlatformVersions, q as PostBuilder, qt as comment, r as renderSpans, rn as Page, rt as AutoSpansOptions, s as utcStampToIso, sn as PaginatorOptions, st as MarkupSpan, t as RenderSpansOptions, tn as UpdatePostInput, tt as parseHtml, u as AllowedMimeType, un as Session, ut as markup, v as VerificationResource, vn as OperationExtensions, vt as Announcement, w as InteractionEntry, wn as FeatureContext, wt as VerificationStatus, x as UserListParams, xn as PluginTeardown, xt as Clan, y as UpdatePrivacyInput, yn as OperationTransformer, yt as AnnouncementButton, z as ReportBuilder, zt as LikeResult } from "../shared/render-CgwKdOzu.js";
|
|
3
3
|
import { a as FileStreamOptions, c as LazyFile, d as UrlFileOptions, i as FileStreamContent, l as StreamFile, n as FileContext, o as FileTransferMode, r as FileInput, s as FromStreamOptions, t as FileContent, u as UrlFile } from "../shared/contracts-BoT7msmq.js";
|
|
4
4
|
//#region src/rest/client.d.ts
|
|
5
5
|
/** Опции конструктора {@link ItdRestClient}. */
|
|
@@ -73,6 +73,14 @@ declare class ItdRestClient {
|
|
|
73
73
|
* Пустой массив при `rateLimit: false`.
|
|
74
74
|
*/
|
|
75
75
|
rateLimitState(): RateLimitBucketState[];
|
|
76
|
+
/** Устанавливает REST feature поверх общего request pipeline клиента. */
|
|
77
|
+
install<TApi>(feature: ClientFeature<TApi>): TApi;
|
|
78
|
+
/** Устанавливает REST feature и публикует его API как readonly-свойство клиента. */
|
|
79
|
+
withFeature<const K extends string, TApi>(key: K, feature: ClientFeature<TApi>): this & { readonly [P in K]: TApi; };
|
|
80
|
+
/** Имена установленных feature в порядке установки. */
|
|
81
|
+
featureNames(): string[];
|
|
82
|
+
/** Установлен ли feature с таким именем. */
|
|
83
|
+
hasFeature(name: string): boolean;
|
|
76
84
|
/**
|
|
77
85
|
* Подключает плагин.
|
|
78
86
|
*
|
|
@@ -134,5 +142,5 @@ declare class ItdRestClient {
|
|
|
134
142
|
*/
|
|
135
143
|
declare function createRestClient(options?: RestClientOptions): ItdRestClient;
|
|
136
144
|
//#endregion
|
|
137
|
-
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, type Actor, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthProvider, type Author, type AutoSpansOptions, BUCKET_LIMITS, type BuilderInput, type BuiltInOperationId, type ChangelogEntry, type Clan, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, type DwellEntry, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRestClient, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, type MyProfile, type Notification, type NotificationEvent, type NotificationListParams, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type ItdOperationDefinition as OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, type RateLimitBucket, type RateLimitBucketContext, type RateLimitBucketOverride, type RateLimitBucketState, type RateLimitOptions, RateLimitPacing, type RawRequestOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResponseContext, type RestClientOptions, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, type RuntimeOptions, STATUS_SERVICE, type SearchResource, type SearchResult, type ServiceDefinition, ServiceState, type ServiceStatus, type Session, type Span, SpanRenderFormat, SpanType, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, anonymousAuth, autoSpans, bearerToken, canonicalNotificationType, comment, createRestClient, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, statusDays, systemClock, toDate, tokenProvider, utcStampToIso };
|
|
145
|
+
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, type Actor, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthProvider, type Author, type AutoSpansOptions, BUCKET_LIMITS, type BuilderInput, type BuiltInOperationId, type ChangelogEntry, type Clan, type ClientFeature, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, type DwellEntry, type ErrorContextHook, type FeatureBucketDefinition, type FeatureContext, type FeatureInstallation, type FeatureOperationDefinition, type FeatureOperationId, type FeatureRequestOptions, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRestClient, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, type MyProfile, type Notification, type NotificationEvent, type NotificationListParams, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type ItdOperationDefinition as OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, type RateLimitBucket, type RateLimitBucketContext, type RateLimitBucketOverride, type RateLimitBucketState, type RateLimitOptions, RateLimitPacing, type RawRequestOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResponseContext, type RestClientOptions, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, type RuntimeOptions, STATUS_SERVICE, type SearchResource, type SearchResult, type ServiceDefinition, ServiceState, type ServiceStatus, type Session, type Span, SpanRenderFormat, SpanType, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, anonymousAuth, autoSpans, bearerToken, canonicalNotificationType, comment, createRestClient, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, statusDays, systemClock, toDate, tokenProvider, utcStampToIso };
|
|
138
146
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/rest/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as operationRetrySafety, C as ViewSource, D as isBuiltInOperationId, E as OPERATIONS, H as RetrySafety, M as DEFAULT_RATE_LIMIT_BUCKET, N as createClientRuntime, O as operationBucket, S as ViewReason, T as ITD_CATALOG, Y as STATUS_SERVICE, Z as LIBRARY_VERSION, b as ServiceState, c as AccessType, ct as installAsyncDisposeFallback, d as FeedTab, et as RateLimitPacing, f as IncidentKind, g as NotificationType, h as LikesVisibility, j as BUCKET_LIMITS, k as operationMethod, l as AttachmentType, m as ItdErrorCode, n as formatNotificationText, o as canonicalNotificationType, p as InteractionType, q as DEFAULT_BASE_URL, r as normalizeNotification, s as isKnownNotificationType, st as systemClock, t as resolveNotificationUrl, tt as RuntimeMode, u as CommentSort, v as ReportReason, w as WallAccess, x as SpanType, y as ReportTargetType } from "../shared/url-IU0xN9wX.js";
|
|
2
2
|
import { A as isItdStateError, C as isItdError, D as isItdPhoneVerificationError, E as isItdNotFoundError, O as isItdRateLimitError, S as isItdConflictError, T as isItdForbiddenError, _ as ItdStateError, a as ItdConfigError, b as isItdApiError, c as ItdErrorKind, d as ItdForbiddenError, f as ItdNetworkError, g as ItdServerError, h as ItdRateLimitError, i as ItdAuthError, j as isItdValidationError, k as isItdServerError, l as ItdFileError, m as ItdPhoneVerificationError, n as ItdApiError, o as ItdConflictError, p as ItdNotFoundError, r as ItdApiErrorKind, s as ItdError, t as ItdAbortError, u as ItdFileErrorReason, v as ItdTimeoutError, w as isItdFileError, x as isItdAuthError, y as ItdValidationError } from "../shared/errors-Bhrd2fJd.js";
|
|
3
|
-
import {
|
|
3
|
+
import { C as utcStampToIso, D as mapPage, E as Paginator, O as FeatureRegistry, S as toDate, T as PaginationMode, _ as IMAGE_MIME_TYPES, a as fromStream, b as isBuilder, c as report, d as autoSpans, f as markup, g as AUDIO_MIME_TYPES, h as ALLOWED_MIME_TYPES, i as isMyProfile, k as ExtensibleOperationCatalog, l as post, m as parseMarkdown, n as renderSpans, o as fromUrl, p as parseHtml, r as statusDays, s as createResources, t as SpanRenderFormat, u as poll, v as VIDEO_MIME_TYPES, x as createStatusFeature, y as comment } from "../shared/render-C6HRPs10.js";
|
|
4
4
|
import { c as FileTransferMode } from "../shared/options-DtATYdLr.js";
|
|
5
|
-
import { n as bearerToken, r as tokenProvider, t as anonymousAuth } from "../shared/auth-provider-
|
|
5
|
+
import { n as bearerToken, r as tokenProvider, t as anonymousAuth } from "../shared/auth-provider-mYqxsSVa.js";
|
|
6
6
|
//#region src/rest/client.ts
|
|
7
7
|
/**
|
|
8
8
|
* Минимальный клиент REST API итд.com.
|
|
@@ -22,6 +22,7 @@ import { n as bearerToken, r as tokenProvider, t as anonymousAuth } from "../sha
|
|
|
22
22
|
*/
|
|
23
23
|
var ItdRestClient = class ItdRestClient {
|
|
24
24
|
#runtime;
|
|
25
|
+
#features;
|
|
25
26
|
#resources;
|
|
26
27
|
/** Общий результат терминальной очистки для идемпотентных повторных вызовов. */
|
|
27
28
|
#disposePromise;
|
|
@@ -76,14 +77,28 @@ var ItdRestClient = class ItdRestClient {
|
|
|
76
77
|
}
|
|
77
78
|
constructor(options = {}) {
|
|
78
79
|
const { auth, ...runtimeOptions } = options;
|
|
80
|
+
const catalog = new ExtensibleOperationCatalog(ITD_CATALOG);
|
|
79
81
|
this.#runtime = createClientRuntime(runtimeOptions, {
|
|
80
|
-
catalog
|
|
82
|
+
catalog,
|
|
81
83
|
assertActive: (action) => this.#assertActive(action),
|
|
82
84
|
auth: () => resolveAuthProvider(auth)
|
|
83
85
|
});
|
|
86
|
+
this.#features = new FeatureRegistry({
|
|
87
|
+
http: this.#runtime.http,
|
|
88
|
+
services: this.#runtime.services,
|
|
89
|
+
serviceOverrides: this.#runtime.config.services,
|
|
90
|
+
catalog,
|
|
91
|
+
baseUrl: this.#runtime.config.baseUrl,
|
|
92
|
+
clock: this.#runtime.config.clock,
|
|
93
|
+
logger: this.#runtime.config.logger,
|
|
94
|
+
assertActive: (action) => this.#assertActive(action),
|
|
95
|
+
registerBucket: (name, definition) => this.#runtime.registerRateLimitBucket(name, definition)
|
|
96
|
+
});
|
|
97
|
+
const status = this.#features.install(createStatusFeature());
|
|
84
98
|
this.#resources = createResources({
|
|
85
99
|
http: this.#runtime.http,
|
|
86
|
-
fetch: this.#runtime.config.fetch
|
|
100
|
+
fetch: this.#runtime.config.fetch,
|
|
101
|
+
status
|
|
87
102
|
});
|
|
88
103
|
}
|
|
89
104
|
#assertActive(action) {
|
|
@@ -116,6 +131,33 @@ var ItdRestClient = class ItdRestClient {
|
|
|
116
131
|
rateLimitState() {
|
|
117
132
|
return this.#runtime.rateLimitState();
|
|
118
133
|
}
|
|
134
|
+
/** Устанавливает REST feature поверх общего request pipeline клиента. */
|
|
135
|
+
install(feature) {
|
|
136
|
+
return this.#features.install(feature);
|
|
137
|
+
}
|
|
138
|
+
/** Устанавливает REST feature и публикует его API как readonly-свойство клиента. */
|
|
139
|
+
withFeature(key, feature) {
|
|
140
|
+
this.#assertActive("установить feature");
|
|
141
|
+
if (typeof key !== "string" || key.trim() === "" || key !== key.trim()) throw new ItdConfigError("Свойство feature должно иметь непустое имя без краевых пробелов");
|
|
142
|
+
if (key === "then" || key in this) throw new ItdConfigError(`Свойство клиента «${key}» уже занято или зарезервировано`);
|
|
143
|
+
if (!Object.isExtensible(this)) throw new ItdConfigError("Нельзя опубликовать feature на нерасширяемом клиенте");
|
|
144
|
+
const api = this.install(feature);
|
|
145
|
+
Object.defineProperty(this, key, {
|
|
146
|
+
value: api,
|
|
147
|
+
enumerable: true,
|
|
148
|
+
configurable: false,
|
|
149
|
+
writable: false
|
|
150
|
+
});
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
/** Имена установленных feature в порядке установки. */
|
|
154
|
+
featureNames() {
|
|
155
|
+
return this.#features.names();
|
|
156
|
+
}
|
|
157
|
+
/** Установлен ли feature с таким именем. */
|
|
158
|
+
hasFeature(name) {
|
|
159
|
+
return this.#features.has(name);
|
|
160
|
+
}
|
|
119
161
|
/**
|
|
120
162
|
* Подключает плагин.
|
|
121
163
|
*
|
|
@@ -168,11 +210,23 @@ var ItdRestClient = class ItdRestClient {
|
|
|
168
210
|
* это {@link dispose}.
|
|
169
211
|
*/
|
|
170
212
|
async close() {
|
|
213
|
+
const errors = [];
|
|
171
214
|
try {
|
|
172
|
-
|
|
215
|
+
try {
|
|
216
|
+
await this.#features.close();
|
|
217
|
+
} catch (error) {
|
|
218
|
+
errors.push(error);
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
await this.#resources.closeTelemetry(false);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
errors.push(error);
|
|
224
|
+
}
|
|
173
225
|
} finally {
|
|
174
226
|
this.#runtime.close();
|
|
175
227
|
}
|
|
228
|
+
if (errors.length === 1) throw errors[0];
|
|
229
|
+
if (errors.length > 1) throw new AggregateError(errors, "Не удалось закрыть клиент");
|
|
176
230
|
}
|
|
177
231
|
/**
|
|
178
232
|
* Окончательно освобождает клиент: выполняет {@link close}, отменяет незавершённые
|
|
@@ -195,11 +249,21 @@ var ItdRestClient = class ItdRestClient {
|
|
|
195
249
|
async #dispose() {
|
|
196
250
|
const errors = [];
|
|
197
251
|
this.#resources.prepareTelemetryClose();
|
|
252
|
+
try {
|
|
253
|
+
await this.#features.close();
|
|
254
|
+
} catch (error) {
|
|
255
|
+
errors.push(error);
|
|
256
|
+
}
|
|
198
257
|
try {
|
|
199
258
|
await this.#resources.closeTelemetry(true);
|
|
200
259
|
} catch (error) {
|
|
201
260
|
errors.push(error);
|
|
202
261
|
}
|
|
262
|
+
try {
|
|
263
|
+
await this.#features.dispose();
|
|
264
|
+
} catch (error) {
|
|
265
|
+
errors.push(error);
|
|
266
|
+
}
|
|
203
267
|
try {
|
|
204
268
|
this.#runtime.close();
|
|
205
269
|
await this.#runtime.dispose();
|