@semiont/api-client 0.5.4 → 0.5.5

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/dist/index.d.ts CHANGED
@@ -1,23 +1,226 @@
1
+ import { KyInstance } from 'ky';
2
+ import { Observable, BehaviorSubject } from 'rxjs';
3
+ import { ConnectionState, SemiontError, TransportErrorCode, ITransport, IBackendOperations, BaseUrl, AccessToken, Logger, EventMap, ResourceId, EventBus, Email, components, GoogleCredential, RefreshToken, UserResponse, ListUsersResponse, UserDID, UpdateUserRequest, UpdateUserResponse, BackendDownload, ProgressEvent, HealthCheckResponse, StatusResponse, IContentTransport, PutBinaryRequest, PutBinaryOptions, ContentFormat } from '@semiont/core';
4
+
5
+ /** Minimal StateUnit surface — anything with a `dispose()` method. */
6
+ interface StateUnit {
7
+ dispose(): void;
8
+ }
9
+
10
+ interface BusEvent {
11
+ channel: string;
12
+ payload: Record<string, unknown>;
13
+ scope?: string;
14
+ }
15
+ interface ActorStateUnitOptions {
16
+ baseUrl: string;
17
+ token: string | (() => string);
18
+ channels: string[];
19
+ scope?: string;
20
+ reconnectMs?: number;
21
+ }
22
+ /** Time in the `reconnecting` state before transitioning to `degraded`. */
23
+ declare const DEGRADED_THRESHOLD_MS = 3000;
24
+ interface ActorStateUnit extends StateUnit {
25
+ on$<T = Record<string, unknown>>(channel: string): Observable<T>;
26
+ emit(channel: string, payload: Record<string, unknown>, emitScope?: string): Promise<void>;
27
+ state$: Observable<ConnectionState>;
28
+ addChannels(channels: string[], scope?: string): void;
29
+ removeChannels(channels: string[]): void;
30
+ start(): void;
31
+ stop(): void;
32
+ }
33
+ declare function createActorStateUnit(options: ActorStateUnitOptions): ActorStateUnit;
34
+
1
35
  /**
2
- * @semiont/api-client
36
+ * HttpTransport — the HTTP/SSE implementation of ITransport.
3
37
  *
4
- * HTTP-specific transport adapters for the Semiont SDK. The dev-facing
5
- * surface (`SemiontClient`, namespaces, session, state units, helpers)
6
- * lives in `@semiont/sdk`. The shared transport contract
7
- * (`ITransport`, `IContentTransport`, `BRIDGED_CHANNELS`,
8
- * `ConnectionState`, response types) lives in `@semiont/core`.
38
+ * Phase 1 of TRANSPORT-ABSTRACTION. Owns everything that crosses the wire
39
+ * in remote mode: the bus actor (SSE + POST /bus/emit), auth/admin/exchange/
40
+ * system HTTP endpoints, and connection-state plumbing.
9
41
  *
10
- * Most consumers do not import from this package directly `@semiont/sdk`
11
- * re-exports the HTTP adapters so a typical app does:
42
+ * Does NOT own the local coordination bus that lives on `SemiontClient`.
43
+ * `bridgeInto(bus)` wires SSE-received events into the caller-supplied bus
44
+ * once at construction.
45
+ */
46
+
47
+ type AuthResponse = components['schemas']['AuthResponse'];
48
+ type TokenRefreshResponse = components['schemas']['TokenRefreshResponse'];
49
+ type AdminUserStatsResponse = components['schemas']['AdminUserStatsResponse'];
50
+ type OAuthConfigResponse = components['schemas']['OAuthConfigResponse'];
51
+ declare class APIError extends SemiontError {
52
+ code: TransportErrorCode;
53
+ readonly status: number;
54
+ readonly statusText: string;
55
+ constructor(message: string, status: number, statusText: string, body?: unknown);
56
+ }
57
+ type TokenRefresher = () => Promise<string | null>;
58
+ interface HttpTransportConfig {
59
+ baseUrl: BaseUrl;
60
+ /** Observable token source; headers read the current value. */
61
+ token$?: BehaviorSubject<AccessToken | null>;
62
+ timeout?: number;
63
+ retry?: number;
64
+ logger?: Logger;
65
+ /** Optional 401-recovery hook. See {@link TokenRefresher}. */
66
+ tokenRefresher?: TokenRefresher;
67
+ }
68
+ declare class HttpTransport implements ITransport, IBackendOperations {
69
+ readonly baseUrl: BaseUrl;
70
+ private readonly http;
71
+ private readonly token$;
72
+ private readonly logger?;
73
+ private readonly errorsSubject;
74
+ /**
75
+ * Stream of `APIError` instances surfaced from any HTTP request just
76
+ * before the transport throws to the caller. Satisfies the `ITransport`
77
+ * `errors$` contract — see `@semiont/core/transport.ts`.
78
+ */
79
+ readonly errors$: Observable<SemiontError>;
80
+ private _actor;
81
+ private _actorStarted;
82
+ private disposed;
83
+ private activeResource;
84
+ /** Buses we've been asked to bridge wire events into. */
85
+ private readonly bridges;
86
+ constructor(config: HttpTransportConfig);
87
+ get actor(): ActorStateUnit;
88
+ emit<K extends keyof EventMap>(channel: K, payload: EventMap[K], resourceScope?: ResourceId): Promise<void>;
89
+ on<K extends keyof EventMap>(channel: K, handler: (payload: EventMap[K]) => void): () => void;
90
+ stream<K extends keyof EventMap>(channel: K): Observable<EventMap[K]>;
91
+ /**
92
+ * Wire this transport's SSE fan-in into the given bus. Every channel
93
+ * in `BRIDGED_CHANNELS` (and subsequently per-resource scoped channels
94
+ * opened by `subscribeToResource`) is published on the bus. Safe to
95
+ * call multiple times — each bus is added to the fan-out list.
96
+ */
97
+ bridgeInto(bus: EventBus): void;
98
+ subscribeToResource(resourceId: ResourceId): () => void;
99
+ private makeUnsubscriber;
100
+ get state$(): Observable<ConnectionState>;
101
+ dispose(): void;
102
+ /**
103
+ * Route a transport-level error onto `errors$`. Used by sibling adapters
104
+ * (e.g. `HttpContentTransport`'s XHR upload path) that don't go through
105
+ * the `ky` `beforeError` hook and need to surface failures on the same
106
+ * stream the rest of the transport publishes to.
107
+ */
108
+ pushError(error: SemiontError): void;
109
+ private authHeaders;
110
+ authenticatePassword(email: Email, password: string): Promise<AuthResponse>;
111
+ authenticateGoogle(credential: GoogleCredential): Promise<AuthResponse>;
112
+ refreshAccessToken(token: RefreshToken): Promise<TokenRefreshResponse>;
113
+ logout(): Promise<void>;
114
+ acceptTerms(): Promise<void>;
115
+ getCurrentUser(): Promise<UserResponse>;
116
+ generateMcpToken(): Promise<{
117
+ token: string;
118
+ }>;
119
+ getMediaToken(resourceId: ResourceId): Promise<{
120
+ token: string;
121
+ }>;
122
+ listUsers(): Promise<ListUsersResponse>;
123
+ getUserStats(): Promise<AdminUserStatsResponse>;
124
+ updateUser(id: UserDID, data: UpdateUserRequest): Promise<UpdateUserResponse>;
125
+ getOAuthConfig(): Promise<OAuthConfigResponse>;
126
+ backupKnowledgeBase(): Promise<BackendDownload>;
127
+ restoreKnowledgeBase(file: File): Observable<ProgressEvent>;
128
+ exportKnowledgeBase(params?: {
129
+ includeArchived?: boolean;
130
+ }): Promise<BackendDownload>;
131
+ importKnowledgeBase(file: File): Observable<ProgressEvent>;
132
+ /**
133
+ * POST a file to a server-sent-events endpoint and surface each `data:`
134
+ * frame as an Observable emission. Completes when the stream closes;
135
+ * errors if the request itself fails or the SSE stream is aborted.
136
+ * The returned Observable is cold — the POST happens on subscribe and
137
+ * is aborted via `AbortController` on unsubscribe.
138
+ */
139
+ private sseProgressStream;
140
+ healthCheck(): Promise<HealthCheckResponse>;
141
+ getStatus(): Promise<StatusResponse>;
142
+ /**
143
+ * Temporary escape hatch for the ongoing transport migration: namespaces
144
+ * that still need to issue ad-hoc HTTP calls (e.g. legacy browse/mark
145
+ * HTTP fallbacks) can borrow the configured `ky` instance here. Will be
146
+ * deleted once all namespaces route through bus channels or through
147
+ * typed methods on this transport.
148
+ */
149
+ get rawHttp(): KyInstance;
150
+ /**
151
+ * Current access token (synchronously read from the BehaviorSubject).
152
+ * Used by content-transport and legacy namespace HTTP fallbacks that
153
+ * need to pass `auth: token` through some code paths.
154
+ */
155
+ getToken(): AccessToken | undefined;
156
+ }
157
+
158
+ /**
159
+ * HttpContentTransport — binary I/O over HTTP.
160
+ *
161
+ * Phase 1 of TRANSPORT-ABSTRACTION. Narrow by design because binary has
162
+ * different backpressure and streaming characteristics than typed command
163
+ * payloads. Uses the HttpTransport's underlying ky instance + token, so
164
+ * retries, logging, and auth behave identically to the rest of the wire.
165
+ *
166
+ * Two `putBinary` paths live side by side, selected by runtime
167
+ * environment + caller intent:
168
+ * - **ky path (default + Node)** — the original `ky.post(...)` path.
169
+ * Keeps retry-with-refresh, beforeError → APIError, observability
170
+ * spans intact. Hits when no `onProgress`/`signal` is passed, OR
171
+ * when `XMLHttpRequest` isn't available in the runtime (Node
172
+ * workers, the CLI). On Node-side `signal`-aborts: the in-flight
173
+ * `fetch` continues in the background and the `cancelled` flag in
174
+ * `yield.resource` suppresses the resolve/reject callbacks.
175
+ * - **XHR path (browsers with `onProgress` or `signal`)** — hand-rolled
176
+ * because `ky` wraps `fetch` which can't observe upload byte-
177
+ * progress today (`Request({ duplex: 'half' })` is the long-term
178
+ * direction; not yet widely available across the webviews this
179
+ * codepath needs to run in). Threads auth + traceparent headers,
180
+ * emits `onProgress` from `xhr.upload.onprogress`, supports
181
+ * cancellation via the `signal` option (calling `xhr.abort()`),
182
+ * and routes failures onto the same `transport.errors$` stream
183
+ * the ky path uses.
12
184
  *
13
- * ```ts
14
- * import { SemiontClient, HttpTransport, HttpContentTransport } from '@semiont/sdk';
15
- * ```
185
+ * The runtime check on `XMLHttpRequest` is the load-bearing seam: a
186
+ * Node worker calling `client.yield.resource(...)` (which always passes
187
+ * a `signal` for unsubscribe-aborts) must NOT take the XHR path —
188
+ * `XMLHttpRequest` is undefined and the upload throws synchronously.
189
+ * Browsers always have it; Node does not.
16
190
  *
17
- * Direct imports are appropriate when constructing the transport stack
18
- * by hand (CLI factories, MCP entrypoints, worker pools).
191
+ * v1 limitation: the XHR path does NOT auto-refresh on 401. Mitigation:
192
+ * the session's proactive refresh fires before token expiry, so an
193
+ * upload that *starts* with a fresh token usually completes. An upload
194
+ * spanning the narrow window between expiry and proactive-refresh would
195
+ * fail; the existing `errors$` → modal path surfaces it as session-
196
+ * expired. If retry-with-refresh on the upload path becomes a real
197
+ * complaint, wire a manual retry loop here that reads `token$` afresh.
19
198
  */
20
- export { HttpTransport, type HttpTransportConfig, type TokenRefresher, APIError, } from './transport/http-transport';
21
- export { HttpContentTransport } from './transport/http-content-transport';
22
- export { createActorStateUnit, type ActorStateUnit, type BusEvent, type ActorStateUnitOptions, DEGRADED_THRESHOLD_MS, } from './transport/actor-state-unit';
23
- //# sourceMappingURL=index.d.ts.map
199
+
200
+ declare class HttpContentTransport implements IContentTransport {
201
+ private readonly transport;
202
+ constructor(transport: HttpTransport);
203
+ putBinary(request: PutBinaryRequest, options?: PutBinaryOptions): Promise<{
204
+ resourceId: ResourceId;
205
+ }>;
206
+ getBinary(resourceId: ResourceId, options?: {
207
+ accept?: ContentFormat | string;
208
+ auth?: AccessToken;
209
+ }): Promise<{
210
+ data: ArrayBuffer;
211
+ contentType: string;
212
+ }>;
213
+ getBinaryStream(resourceId: ResourceId, options?: {
214
+ accept?: ContentFormat | string;
215
+ auth?: AccessToken;
216
+ }): Promise<{
217
+ stream: ReadableStream<Uint8Array>;
218
+ contentType: string;
219
+ }>;
220
+ dispose(): void;
221
+ /** Auth header + W3C trace propagation for the active span. */
222
+ private requestHeaders;
223
+ }
224
+
225
+ export { APIError, DEGRADED_THRESHOLD_MS, HttpContentTransport, HttpTransport, createActorStateUnit };
226
+ export type { ActorStateUnit, ActorStateUnitOptions, BusEvent, HttpTransportConfig, TokenRefresher };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@semiont/api-client",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Semiont API SDK - types, client, and utilities",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -31,9 +31,9 @@
31
31
  "scripts": {
32
32
  "pretypecheck": "npm run build --workspace=@semiont/core --if-present && npm run build --workspace=@semiont/observability --if-present",
33
33
  "typecheck": "tsc --noEmit",
34
- "build": "npm run typecheck && tsup && tsc -p tsconfig.build.json",
34
+ "build": "npm run typecheck && tsup && tsc -p tsconfig.build.json && rollup -c rollup.dts.config.mjs && rm -rf dist-types",
35
35
  "watch": "tsup --watch",
36
- "clean": "rm -rf dist",
36
+ "clean": "rm -rf dist dist-types",
37
37
  "test": "vitest run",
38
38
  "test:watch": "vitest",
39
39
  "test:coverage": "vitest run --coverage"
@@ -46,6 +46,8 @@
46
46
  },
47
47
  "devDependencies": {
48
48
  "@vitest/coverage-v8": "^4.1.0",
49
+ "rollup": "^4.60.3",
50
+ "rollup-plugin-dts": "^6.4.1",
49
51
  "tsup": "^8.5.1",
50
52
  "typescript": "^6.0.2"
51
53
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,aAAa,EACb,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACnB,QAAQ,GACT,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAO1E,OAAO,EACL,oBAAoB,EACpB,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,qBAAqB,EAC1B,qBAAqB,GACtB,MAAM,8BAA8B,CAAC"}
@@ -1,32 +0,0 @@
1
- import { Observable } from 'rxjs';
2
- import { type ConnectionState } from '@semiont/core';
3
- /** Minimal StateUnit surface — anything with a `dispose()` method. */
4
- interface StateUnit {
5
- dispose(): void;
6
- }
7
- export type { ConnectionState };
8
- export interface BusEvent {
9
- channel: string;
10
- payload: Record<string, unknown>;
11
- scope?: string;
12
- }
13
- export interface ActorStateUnitOptions {
14
- baseUrl: string;
15
- token: string | (() => string);
16
- channels: string[];
17
- scope?: string;
18
- reconnectMs?: number;
19
- }
20
- /** Time in the `reconnecting` state before transitioning to `degraded`. */
21
- export declare const DEGRADED_THRESHOLD_MS = 3000;
22
- export interface ActorStateUnit extends StateUnit {
23
- on$<T = Record<string, unknown>>(channel: string): Observable<T>;
24
- emit(channel: string, payload: Record<string, unknown>, emitScope?: string): Promise<void>;
25
- state$: Observable<ConnectionState>;
26
- addChannels(channels: string[], scope?: string): void;
27
- removeChannels(channels: string[]): void;
28
- start(): void;
29
- stop(): void;
30
- }
31
- export declare function createActorStateUnit(options: ActorStateUnitOptions): ActorStateUnit;
32
- //# sourceMappingURL=actor-state-unit.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"actor-state-unit.d.ts","sourceRoot":"","sources":["../../src/transport/actor-state-unit.ts"],"names":[],"mappings":"AAAA,OAAO,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YD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CA8TnF"}
@@ -1,69 +0,0 @@
1
- /**
2
- * HttpContentTransport — binary I/O over HTTP.
3
- *
4
- * Phase 1 of TRANSPORT-ABSTRACTION. Narrow by design because binary has
5
- * different backpressure and streaming characteristics than typed command
6
- * payloads. Uses the HttpTransport's underlying ky instance + token, so
7
- * retries, logging, and auth behave identically to the rest of the wire.
8
- *
9
- * Two `putBinary` paths live side by side, selected by runtime
10
- * environment + caller intent:
11
- * - **ky path (default + Node)** — the original `ky.post(...)` path.
12
- * Keeps retry-with-refresh, beforeError → APIError, observability
13
- * spans intact. Hits when no `onProgress`/`signal` is passed, OR
14
- * when `XMLHttpRequest` isn't available in the runtime (Node
15
- * workers, the CLI). On Node-side `signal`-aborts: the in-flight
16
- * `fetch` continues in the background and the `cancelled` flag in
17
- * `yield.resource` suppresses the resolve/reject callbacks.
18
- * - **XHR path (browsers with `onProgress` or `signal`)** — hand-rolled
19
- * because `ky` wraps `fetch` which can't observe upload byte-
20
- * progress today (`Request({ duplex: 'half' })` is the long-term
21
- * direction; not yet widely available across the webviews this
22
- * codepath needs to run in). Threads auth + traceparent headers,
23
- * emits `onProgress` from `xhr.upload.onprogress`, supports
24
- * cancellation via the `signal` option (calling `xhr.abort()`),
25
- * and routes failures onto the same `transport.errors$` stream
26
- * the ky path uses.
27
- *
28
- * The runtime check on `XMLHttpRequest` is the load-bearing seam: a
29
- * Node worker calling `client.yield.resource(...)` (which always passes
30
- * a `signal` for unsubscribe-aborts) must NOT take the XHR path —
31
- * `XMLHttpRequest` is undefined and the upload throws synchronously.
32
- * Browsers always have it; Node does not.
33
- *
34
- * v1 limitation: the XHR path does NOT auto-refresh on 401. Mitigation:
35
- * the session's proactive refresh fires before token expiry, so an
36
- * upload that *starts* with a fresh token usually completes. An upload
37
- * spanning the narrow window between expiry and proactive-refresh would
38
- * fail; the existing `errors$` → modal path surfaces it as session-
39
- * expired. If retry-with-refresh on the upload path becomes a real
40
- * complaint, wire a manual retry loop here that reads `token$` afresh.
41
- */
42
- import type { AccessToken, ContentFormat, ResourceId, PutBinaryOptions } from '@semiont/core';
43
- import type { HttpTransport } from './http-transport';
44
- import type { IContentTransport, PutBinaryRequest } from '@semiont/core';
45
- export declare class HttpContentTransport implements IContentTransport {
46
- private readonly transport;
47
- constructor(transport: HttpTransport);
48
- putBinary(request: PutBinaryRequest, options?: PutBinaryOptions): Promise<{
49
- resourceId: ResourceId;
50
- }>;
51
- getBinary(resourceId: ResourceId, options?: {
52
- accept?: ContentFormat | string;
53
- auth?: AccessToken;
54
- }): Promise<{
55
- data: ArrayBuffer;
56
- contentType: string;
57
- }>;
58
- getBinaryStream(resourceId: ResourceId, options?: {
59
- accept?: ContentFormat | string;
60
- auth?: AccessToken;
61
- }): Promise<{
62
- stream: ReadableStream<Uint8Array>;
63
- contentType: string;
64
- }>;
65
- dispose(): void;
66
- /** Auth header + W3C trace propagation for the active span. */
67
- private requestHeaders;
68
- }
69
- //# sourceMappingURL=http-content-transport.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-content-transport.d.ts","sourceRoot":"","sources":["../../src/transport/http-content-transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAG9F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEzE,qBAAa,oBAAqB,YAAW,iBAAiB;IAChD,OAAO,CAAC,QAAQ,CAAC,SAAS;gBAAT,SAAS,EAAE,aAAa;IAE/C,SAAS,CACb,OAAO,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC;QAAE,UAAU,EAAE,UAAU,CAAA;KAAE,CAAC;IAoDhC,SAAS,CACb,UAAU,EAAE,UAAU,EACtB,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,WAAW,CAAA;KAAE,GAChE,OAAO,CAAC;QAAE,IAAI,EAAE,WAAW,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAmBhD,eAAe,CACnB,UAAU,EAAE,UAAU,EACtB,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,aAAa,GAAG,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,WAAW,CAAA;KAAE,GAChE,OAAO,CAAC;QAAE,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAwBvE,OAAO,IAAI,IAAI;IAKf,+DAA+D;IAC/D,OAAO,CAAC,cAAc;CAUvB"}
@@ -1,130 +0,0 @@
1
- /**
2
- * HttpTransport — the HTTP/SSE implementation of ITransport.
3
- *
4
- * Phase 1 of TRANSPORT-ABSTRACTION. Owns everything that crosses the wire
5
- * in remote mode: the bus actor (SSE + POST /bus/emit), auth/admin/exchange/
6
- * system HTTP endpoints, and connection-state plumbing.
7
- *
8
- * Does NOT own the local coordination bus — that lives on `SemiontClient`.
9
- * `bridgeInto(bus)` wires SSE-received events into the caller-supplied bus
10
- * once at construction.
11
- */
12
- import { type KyInstance } from 'ky';
13
- import { BehaviorSubject, Observable } from 'rxjs';
14
- import type { AccessToken, BaseUrl, Email, EventBus, EventMap, GoogleCredential, Logger, RefreshToken, ResourceId, UserDID, components } from '@semiont/core';
15
- import { SemiontError } from '@semiont/core';
16
- import type { TransportErrorCode } from '@semiont/core';
17
- import { type ActorStateUnit } from './actor-state-unit';
18
- import type { BackendDownload, ConnectionState, IBackendOperations, ITransport, HealthCheckResponse, StatusResponse, UserResponse, UpdateUserRequest, UpdateUserResponse, ListUsersResponse, ProgressEvent } from '@semiont/core';
19
- type AuthResponse = components['schemas']['AuthResponse'];
20
- type TokenRefreshResponse = components['schemas']['TokenRefreshResponse'];
21
- type AdminUserStatsResponse = components['schemas']['AdminUserStatsResponse'];
22
- type OAuthConfigResponse = components['schemas']['OAuthConfigResponse'];
23
- export declare class APIError extends SemiontError {
24
- code: TransportErrorCode;
25
- readonly status: number;
26
- readonly statusText: string;
27
- constructor(message: string, status: number, statusText: string, body?: unknown);
28
- }
29
- export type TokenRefresher = () => Promise<string | null>;
30
- export interface HttpTransportConfig {
31
- baseUrl: BaseUrl;
32
- /** Observable token source; headers read the current value. */
33
- token$?: BehaviorSubject<AccessToken | null>;
34
- timeout?: number;
35
- retry?: number;
36
- logger?: Logger;
37
- /** Optional 401-recovery hook. See {@link TokenRefresher}. */
38
- tokenRefresher?: TokenRefresher;
39
- }
40
- export declare class HttpTransport implements ITransport, IBackendOperations {
41
- readonly baseUrl: BaseUrl;
42
- private readonly http;
43
- private readonly token$;
44
- private readonly logger?;
45
- private readonly errorsSubject;
46
- /**
47
- * Stream of `APIError` instances surfaced from any HTTP request just
48
- * before the transport throws to the caller. Satisfies the `ITransport`
49
- * `errors$` contract — see `@semiont/core/transport.ts`.
50
- */
51
- readonly errors$: Observable<SemiontError>;
52
- private _actor;
53
- private _actorStarted;
54
- private disposed;
55
- private activeResource;
56
- /** Buses we've been asked to bridge wire events into. */
57
- private readonly bridges;
58
- constructor(config: HttpTransportConfig);
59
- get actor(): ActorStateUnit;
60
- emit<K extends keyof EventMap>(channel: K, payload: EventMap[K], resourceScope?: ResourceId): Promise<void>;
61
- on<K extends keyof EventMap>(channel: K, handler: (payload: EventMap[K]) => void): () => void;
62
- stream<K extends keyof EventMap>(channel: K): Observable<EventMap[K]>;
63
- /**
64
- * Wire this transport's SSE fan-in into the given bus. Every channel
65
- * in `BRIDGED_CHANNELS` (and subsequently per-resource scoped channels
66
- * opened by `subscribeToResource`) is published on the bus. Safe to
67
- * call multiple times — each bus is added to the fan-out list.
68
- */
69
- bridgeInto(bus: EventBus): void;
70
- subscribeToResource(resourceId: ResourceId): () => void;
71
- private makeUnsubscriber;
72
- get state$(): Observable<ConnectionState>;
73
- dispose(): void;
74
- /**
75
- * Route a transport-level error onto `errors$`. Used by sibling adapters
76
- * (e.g. `HttpContentTransport`'s XHR upload path) that don't go through
77
- * the `ky` `beforeError` hook and need to surface failures on the same
78
- * stream the rest of the transport publishes to.
79
- */
80
- pushError(error: SemiontError): void;
81
- private authHeaders;
82
- authenticatePassword(email: Email, password: string): Promise<AuthResponse>;
83
- authenticateGoogle(credential: GoogleCredential): Promise<AuthResponse>;
84
- refreshAccessToken(token: RefreshToken): Promise<TokenRefreshResponse>;
85
- logout(): Promise<void>;
86
- acceptTerms(): Promise<void>;
87
- getCurrentUser(): Promise<UserResponse>;
88
- generateMcpToken(): Promise<{
89
- token: string;
90
- }>;
91
- getMediaToken(resourceId: ResourceId): Promise<{
92
- token: string;
93
- }>;
94
- listUsers(): Promise<ListUsersResponse>;
95
- getUserStats(): Promise<AdminUserStatsResponse>;
96
- updateUser(id: UserDID, data: UpdateUserRequest): Promise<UpdateUserResponse>;
97
- getOAuthConfig(): Promise<OAuthConfigResponse>;
98
- backupKnowledgeBase(): Promise<BackendDownload>;
99
- restoreKnowledgeBase(file: File): Observable<ProgressEvent>;
100
- exportKnowledgeBase(params?: {
101
- includeArchived?: boolean;
102
- }): Promise<BackendDownload>;
103
- importKnowledgeBase(file: File): Observable<ProgressEvent>;
104
- /**
105
- * POST a file to a server-sent-events endpoint and surface each `data:`
106
- * frame as an Observable emission. Completes when the stream closes;
107
- * errors if the request itself fails or the SSE stream is aborted.
108
- * The returned Observable is cold — the POST happens on subscribe and
109
- * is aborted via `AbortController` on unsubscribe.
110
- */
111
- private sseProgressStream;
112
- healthCheck(): Promise<HealthCheckResponse>;
113
- getStatus(): Promise<StatusResponse>;
114
- /**
115
- * Temporary escape hatch for the ongoing transport migration: namespaces
116
- * that still need to issue ad-hoc HTTP calls (e.g. legacy browse/mark
117
- * HTTP fallbacks) can borrow the configured `ky` instance here. Will be
118
- * deleted once all namespaces route through bus channels or through
119
- * typed methods on this transport.
120
- */
121
- get rawHttp(): KyInstance;
122
- /**
123
- * Current access token (synchronously read from the BehaviorSubject).
124
- * Used by content-transport and legacy namespace HTTP fallbacks that
125
- * need to pass `auth: token` through some code paths.
126
- */
127
- getToken(): AccessToken | undefined;
128
- }
129
- export type { ConnectionState } from '@semiont/core';
130
- //# sourceMappingURL=http-transport.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-transport.d.ts","sourceRoot":"","sources":["../../src/transport/http-transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAW,EAAa,KAAK,UAAU,EAAE,MAAM,IAAI,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,UAAU,EAA8B,MAAM,MAAM,CAAC;AAC/E,OAAO,KAAK,EACV,WAAW,EACX,OAAO,EACP,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,YAAY,EACZ,UAAU,EACV,OAAO,EACP,UAAU,EACX,MAAM,eAAe,CAAC;AACvB,OAAO,EAGL,YAAY,EAEb,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAExD,OAAO,EAAwB,KAAK,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAC/E,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,UAAU,EACV,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EACjB,aAAa,EACd,MAAM,eAAe,CAAC;AAGvB,KAAK,YAAY,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,cAAc,CAAC,CAAC;AAC1D,KAAK,oBAAoB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,sBAAsB,CAAC,CAAC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