@celljs/ta-client 4.16.0 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SessionStore = exports.HOLD_MS = void 0;
3
+ exports.SessionStore = void 0;
4
4
  const ta_protocol_1 = require("@celljs/ta-protocol");
5
+ const session_client_tools_1 = require("./session-client-tools");
5
6
  const session_reducer_1 = require("./session-reducer");
6
- const ta_connection_1 = require("./ta-connection");
7
- /** How long a message the connection could not take waits for it, on its way, before it shows as failed. */
8
- exports.HOLD_MS = 60000;
7
+ const session_store_options_1 = require("./session-store-options");
8
+ const ta_remote_error_1 = require("./ta-remote-error");
9
9
  /**
10
10
  * The state of one open session on a client: for any UI to render and subscribe to. It catches up by
11
11
  * itself after a reconnect, from the events it missed or, if those are gone, from the session.
12
12
  */
13
- class SessionStore {
13
+ class SessionStore extends session_client_tools_1.SessionClientTools {
14
14
  constructor(connection, sessionId, options = {}) {
15
15
  var _a, _b;
16
+ super();
16
17
  this.connection = connection;
17
18
  this.sessionId = sessionId;
18
19
  /** The session as the service told it. */
@@ -24,17 +25,11 @@ class SessionStore {
24
25
  this.eventListeners = new Set();
25
26
  this.goneListeners = new Set();
26
27
  this.stop = [];
27
- /** Calls of client tools this store is running or answering now, by id. */
28
- this.running = new Set();
29
- /** Results not yet taken by the server, by call id. */
30
- this.results = new Map();
31
- /** Calls another client took, by id: tried again only when the request comes again (that client left). */
32
- this.declined = new Map();
33
28
  /** The messages held that are being sent again now. */
34
29
  this.resending = new Set();
35
30
  this.clientTools = new Map(((_a = options.clientTools) !== null && _a !== void 0 ? _a : []).map(tool => [tool.definition.name, tool]));
36
31
  this.pageBytes = options.pageBytes;
37
- this.holdMs = (_b = options.holdMs) !== null && _b !== void 0 ? _b : exports.HOLD_MS;
32
+ this.holdMs = (_b = options.holdMs) !== null && _b !== void 0 ? _b : session_store_options_1.HOLD_MS;
38
33
  if (options.initial) {
39
34
  const { messages, start, tools } = options.initial;
40
35
  this.current = this.shown = { ...this.current, messages, start, tools };
@@ -149,7 +144,7 @@ class SessionStore {
149
144
  }
150
145
  return result;
151
146
  }, error => {
152
- if (keep && ta_connection_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
147
+ if (keep && ta_remote_error_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
153
148
  throw error;
154
149
  }
155
150
  if (keep) {
@@ -193,7 +188,7 @@ class SessionStore {
193
188
  continue;
194
189
  }
195
190
  if (now - sent.heldAt >= this.holdMs) {
196
- this.fail(sent, ta_connection_1.TaRemoteError.notConnected());
191
+ this.fail(sent, ta_remote_error_1.TaRemoteError.notConnected());
197
192
  }
198
193
  else {
199
194
  next = Math.min(next, sent.heldAt + this.holdMs - now);
@@ -273,7 +268,7 @@ class SessionStore {
273
268
  return this.connection.server.respondUi(this.sessionId, response);
274
269
  }
275
270
  async attachAgain(attached) {
276
- var _a, _b;
271
+ var _a, _b, _c;
277
272
  const result = attached !== null && attached !== void 0 ? attached : (await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined));
278
273
  let state = this.current;
279
274
  // A conversation given (one attached as it opened) is the session's from scratch, whatever this store had.
@@ -287,6 +282,8 @@ class SessionStore {
287
282
  messages: kept,
288
283
  tools: conversation.tools,
289
284
  start,
285
+ // Those loaded further up kept: the head they start in, as it was.
286
+ head: start === ((_c = conversation.start) !== null && _c !== void 0 ? _c : 0) ? conversation.head : this.current.head,
290
287
  runStart: kept === this.current.messages ? this.current.runStart : undefined,
291
288
  };
292
289
  this.lastSeq = result.lastSeq;
@@ -373,15 +370,16 @@ class SessionStore {
373
370
  ...this.current,
374
371
  messages: [...page.messages, ...this.current.messages],
375
372
  start: page.start,
373
+ head: page.head,
376
374
  loadingEarlier: false,
377
375
  runStart: runStart === undefined ? undefined : runStart + page.messages.length,
378
376
  });
379
377
  }
380
378
  async reload() {
381
- const { messages, start } = this.pageBytes
379
+ const { messages, start, head } = this.pageBytes
382
380
  ? await this.connection.server.getEarlierMessages(this.sessionId, undefined, undefined, this.pageBytes)
383
- : { ...(await this.connection.server.getMessages(this.sessionId)), start: 0 };
384
- this.update({ ...this.current, messages, start, tools: {}, runStart: undefined });
381
+ : { ...(await this.connection.server.getMessages(this.sessionId)), start: 0, head: undefined };
382
+ this.update({ ...this.current, messages, start, head, tools: {}, runStart: undefined });
385
383
  }
386
384
  apply(events) {
387
385
  const taken = this.take(this.current, events);
@@ -439,66 +437,6 @@ class SessionStore {
439
437
  listener(shown);
440
438
  }
441
439
  }
442
- runClientTools(state) {
443
- for (const request of state.pendingClientTools) {
444
- const tool = this.clientTools.get(request.toolName);
445
- if (tool && !this.running.has(request.id) && this.declined.get(request.id) !== request) {
446
- this.running.add(request.id);
447
- void this.answer(tool, request);
448
- }
449
- }
450
- for (const calls of [this.results, this.declined]) {
451
- for (const id of calls.keys()) {
452
- if (!state.pendingClientTools.some(request => request.id === id)) {
453
- calls.delete(id);
454
- }
455
- }
456
- }
457
- }
458
- /**
459
- * Runs a call once, if this client takes it: every page of the user gets it. A result that could not be
460
- * sent is sent again after a reconnect, not made again.
461
- */
462
- async answer(tool, request) {
463
- try {
464
- let result = this.results.get(request.id);
465
- if (!result) {
466
- // Not asked again before the request comes again, also when the connection was lost: the reconnect brings it.
467
- this.declined.set(request.id, request);
468
- if (!(await this.claim(request))) {
469
- return;
470
- }
471
- this.declined.delete(request.id);
472
- result = await this.run(tool, request);
473
- this.results.set(request.id, result);
474
- }
475
- await this.connection.server.respondClientTool(this.sessionId, result);
476
- this.results.delete(request.id);
477
- }
478
- catch (_a) {
479
- // The connection was lost; the reconnect sends the result if the call still waits.
480
- }
481
- finally {
482
- this.running.delete(request.id);
483
- }
484
- }
485
- /** Whether this client runs the call; a Ta service from before claims (a computer not updated yet, reached from a phone) lets every client run it, as it did. */
486
- claim(request) {
487
- return this.connection.server.claimClientTool(this.sessionId, request.id).catch(error => {
488
- if (ta_connection_1.TaRemoteError.isMethodNotFound(error)) {
489
- return true;
490
- }
491
- throw error;
492
- });
493
- }
494
- async run(tool, request) {
495
- try {
496
- return { id: request.id, output: await tool.run(request.input, request) };
497
- }
498
- catch (error) {
499
- return { id: request.id, output: error instanceof Error ? error.message : String(error), isError: true };
500
- }
501
- }
502
440
  }
503
441
  exports.SessionStore = SessionStore;
504
442
  //# sourceMappingURL=session-store.js.map
@@ -0,0 +1,45 @@
1
+ export interface TaConnectionOptions {
2
+ /** The `url` of serve.json. */
3
+ url: string;
4
+ /** The `token` of serve.json. */
5
+ token: string;
6
+ /** First wait before reconnecting; it doubles up to `maxReconnectDelayMs`. Default 250. */
7
+ reconnectDelayMs?: number;
8
+ /** Default 10000. */
9
+ maxReconnectDelayMs?: number;
10
+ /**
11
+ * How long a call made while the connection is down waits for it to come back before it fails, so
12
+ * that a short drop goes unnoticed. Default 5000; 0 fails at once.
13
+ */
14
+ waitForOpenMs?: number;
15
+ /**
16
+ * How long a call that is safe to send again (`TaConnection.resendable`: a read, a message with its
17
+ * clientMessageId) keeps trying across lost connections, waiting for each to come back, before it
18
+ * fails: a drop mended within it goes unseen. Default `waitForOpenMs`.
19
+ */
20
+ retryForMs?: number;
21
+ /**
22
+ * A call unanswered this long while nothing at all came over the connection makes it check that the
23
+ * connection is alive (`wake`): one gone without a word is made again in seconds, not when the system
24
+ * notices; the check waits as long for its answer. Default 5000; 0 never checks.
25
+ */
26
+ stallMs?: number;
27
+ /**
28
+ * Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
29
+ * a new socket for each connection, which takes care of access itself.
30
+ */
31
+ createSocket?: () => TaSocket;
32
+ }
33
+ /** What TaConnection uses of a WebSocket. */
34
+ export interface TaSocket {
35
+ readonly readyState: number;
36
+ onopen: ((event?: unknown) => void) | null;
37
+ onmessage: ((message: {
38
+ data: unknown;
39
+ }) => void) | null;
40
+ onclose: ((event?: unknown) => void) | null;
41
+ onerror?: ((event?: unknown) => void) | null;
42
+ send(text: string): void;
43
+ close(): void;
44
+ }
45
+ //# sourceMappingURL=ta-connection-options.d.ts.map
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=ta-connection-options.js.map
@@ -1,97 +1,32 @@
1
- import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, TaErrorCode, type TaErrorData, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaPresenceServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaRoomEvent, type TaRoomServer, type TaServer, type TaSessionInfo, type TaSettingsServer, type TaTerminalServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
2
- /**
3
- * A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
4
- * by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
5
- */
6
- export declare class TaRemoteError extends Error {
7
- readonly code?: TaErrorCode | undefined;
8
- readonly hint?: string | undefined;
9
- readonly rpcCode?: number | undefined;
10
- /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
11
- readonly data?: Readonly<Record<string, unknown>> | undefined;
12
- /** JSON-RPC's code for a method the server does not have. */
13
- static readonly METHOD_NOT_FOUND = -32601;
14
- constructor(message: string, code?: TaErrorCode | undefined, hint?: string | undefined, rpcCode?: number | undefined,
15
- /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
16
- data?: Readonly<Record<string, unknown>> | undefined);
17
- /** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
18
- static of(error: {
19
- message: string;
20
- code?: number;
21
- data?: {
22
- data?: TaErrorData;
23
- };
24
- }): TaRemoteError;
25
- /** What a call says that waited for a connection that did not come back. */
26
- static readonly NOT_CONNECTED = "Not connected to ta serve.";
27
- /** What a call says that was sent on a connection lost before its answer. */
28
- static readonly LOST = "The connection to ta serve was lost.";
29
- /** A call that waited for a connection that did not come back. */
30
- static notConnected(): TaRemoteError;
31
- /**
32
- * Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
33
- * words in a text (a web extension shows `error.message`, often inside its own words).
34
- */
35
- static isConnectionLost(cause: unknown): boolean;
36
- /** Whether the server has no such method: a ta serve from before it was added. */
37
- static isMethodNotFound(error: unknown): boolean;
38
- }
39
- export interface TaConnectionOptions {
40
- /** The `url` of serve.json. */
41
- url: string;
42
- /** The `token` of serve.json. */
43
- token: string;
44
- /** First wait before reconnecting; it doubles up to `maxReconnectDelayMs`. Default 250. */
45
- reconnectDelayMs?: number;
46
- /** Default 10000. */
47
- maxReconnectDelayMs?: number;
48
- /**
49
- * How long a call made while the connection is down waits for it to come back before it fails, so
50
- * that a short drop goes unnoticed. Default 5000; 0 fails at once.
51
- */
52
- waitForOpenMs?: number;
53
- /**
54
- * How long a call that is safe to send again (`TaConnection.resendable`: a read, a message with its
55
- * clientMessageId) keeps trying across lost connections, waiting for each to come back, before it
56
- * fails: a drop mended within it goes unseen. Default `waitForOpenMs`.
57
- */
58
- retryForMs?: number;
59
- /**
60
- * A call unanswered this long while nothing at all came over the connection makes it check that the
61
- * connection is alive (`wake`): one gone without a word is made again in seconds, not when the system
62
- * notices; the check waits as long for its answer. Default 5000; 0 never checks.
63
- */
64
- stallMs?: number;
65
- /**
66
- * Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
67
- * a new socket for each connection, which takes care of access itself.
68
- */
69
- createSocket?: () => TaSocket;
70
- }
71
- /** What TaConnection uses of a WebSocket. */
72
- export interface TaSocket {
73
- readonly readyState: number;
74
- onopen: ((event?: unknown) => void) | null;
75
- onmessage: ((message: {
76
- data: unknown;
77
- }) => void) | null;
78
- onclose: ((event?: unknown) => void) | null;
79
- onerror?: ((event?: unknown) => void) | null;
80
- send(text: string): void;
81
- close(): void;
82
- }
1
+ import { type TaAccessServer, type TaAuthEvent, type TaAuthServer, type TaErrorData, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaPageServer, type TaPresenceServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaRoomEvent, type TaRoomServer, type TaServer, type TaSessionInfo, type TaSettingsServer, type TaTerminalServer, type TaVoiceEvent, type TaVoiceServer, type TaWorkspaceServer } from '@celljs/ta-protocol';
2
+ import type { TaConnectionOptions, TaSocket } from './ta-connection-options';
83
3
  interface PendingCall {
84
4
  resolve(result: unknown): void;
85
5
  reject(error: Error): void;
86
6
  /** When it was sent, on the clock of Date.now(). */
87
7
  sentAt: number;
88
8
  }
9
+ interface RpcMessage {
10
+ id?: number | string | null;
11
+ method?: string;
12
+ params?: unknown[];
13
+ result?: unknown;
14
+ error?: {
15
+ message: string;
16
+ code?: number;
17
+ data?: {
18
+ data?: TaErrorData;
19
+ };
20
+ };
21
+ }
89
22
  type EventsListener = (events: TaEventEnvelope[]) => void;
90
23
  type TerminalListener = (terminalId: string, data: string, exitCode?: number) => void;
91
24
  type ExtensionDataListener = (name: string, keys: string[], cwd?: string) => void;
92
25
  type AuthEventListener = (loginId: string, event: TaAuthEvent) => void;
93
26
  type RemoteEventListener = (event: TaRemoteEvent) => void;
94
27
  type RoomEventListener = (event: TaRoomEvent) => void;
28
+ type VoiceEventListener = (event: TaVoiceEvent) => void;
29
+ type PageAskHandler = (kind: string, payload: unknown) => Promise<unknown>;
95
30
  type SessionsListener = (sessions: TaSessionInfo[]) => void;
96
31
  type OpenListener = () => void;
97
32
  type CloseListener = () => void;
@@ -125,6 +60,10 @@ export declare class TaConnection {
125
60
  readonly rooms: TaRoomServer;
126
61
  /** What this page is at, for the others in the same Ta (docs/design/ta-team.md 7). */
127
62
  readonly presence: TaPresenceServer;
63
+ /** The voice services of calls (docs/design/ta-voice.md). */
64
+ readonly voice: TaVoiceServer;
65
+ /** Which requests of ta serve this page answers (onPageAsk, docs/design/ta-app-use.md 4.1). */
66
+ readonly pages: TaPageServer;
128
67
  protected socket?: TaSocket;
129
68
  protected closed: boolean;
130
69
  protected attempts: number;
@@ -137,6 +76,8 @@ export declare class TaConnection {
137
76
  protected readonly authListeners: Set<AuthEventListener>;
138
77
  protected readonly remoteListeners: Set<RemoteEventListener>;
139
78
  protected readonly roomListeners: Set<RoomEventListener>;
79
+ protected readonly voiceListeners: Set<VoiceEventListener>;
80
+ protected pageAsk?: PageAskHandler;
140
81
  protected readonly sessionsListeners: Set<SessionsListener>;
141
82
  protected readonly openListeners: Set<OpenListener>;
142
83
  protected readonly closeListeners: Set<CloseListener>;
@@ -166,6 +107,10 @@ export declare class TaConnection {
166
107
  onRemoteEvent(listener: RemoteEventListener): () => void;
167
108
  /** What happens in the rooms, once this connection called TaRoomServer.watch. */
168
109
  onRoomEvent(listener: RoomEventListener): () => void;
110
+ /** What the voices this connection opened tell (TaVoiceServer.openVoice). */
111
+ /** Answers what ta serve asks this page (TaClient.onPageAsk): one handler, the last set; without one, an error. */
112
+ onPageAsk(handler: PageAskHandler | undefined): void;
113
+ onVoiceEvent(listener: VoiceEventListener): () => void;
169
114
  /** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
170
115
  onSessions(listener: SessionsListener): () => void;
171
116
  onOpen(listener: OpenListener): () => void;
@@ -201,6 +146,8 @@ export declare class TaConnection {
201
146
  protected send(service: string, method: string, params: unknown[]): Promise<unknown>;
202
147
  /** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
203
148
  protected watchStalls(): void;
149
+ /** What the page answers to a request of ta serve, on the socket it came on. */
150
+ protected answerPage(id: RpcMessage['id'], kind: string, payload: unknown): Promise<void>;
204
151
  protected receive(text: string): void;
205
152
  }
206
153
  export {};
@@ -1,54 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TaConnection = exports.TaRemoteError = void 0;
3
+ exports.TaConnection = void 0;
4
4
  const ta_protocol_1 = require("@celljs/ta-protocol");
5
- /**
6
- * A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
7
- * by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
8
- */
9
- class TaRemoteError extends Error {
10
- constructor(message, code, hint, rpcCode,
11
- /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
12
- data) {
13
- super(message);
14
- this.code = code;
15
- this.hint = hint;
16
- this.rpcCode = rpcCode;
17
- this.data = data;
18
- this.name = 'TaRemoteError';
19
- }
20
- /** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
21
- static of(error) {
22
- var _a;
23
- const data = (_a = error.data) === null || _a === void 0 ? void 0 : _a.data;
24
- return new TaRemoteError(error.message, data === null || data === void 0 ? void 0 : data.code, data === null || data === void 0 ? void 0 : data.hint, error.code, data);
25
- }
26
- /** A call that waited for a connection that did not come back. */
27
- static notConnected() {
28
- return new TaRemoteError(TaRemoteError.NOT_CONNECTED, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.');
29
- }
30
- /**
31
- * Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
32
- * words in a text (a web extension shows `error.message`, often inside its own words).
33
- */
34
- static isConnectionLost(cause) {
35
- if (typeof cause === 'string') {
36
- return cause.includes(TaRemoteError.NOT_CONNECTED) || cause.includes(TaRemoteError.LOST);
37
- }
38
- return (cause === null || cause === void 0 ? void 0 : cause.code) === ta_protocol_1.TaErrorCode.CONNECTION_LOST;
39
- }
40
- /** Whether the server has no such method: a ta serve from before it was added. */
41
- static isMethodNotFound(error) {
42
- return error instanceof TaRemoteError && error.rpcCode === TaRemoteError.METHOD_NOT_FOUND;
43
- }
44
- }
45
- exports.TaRemoteError = TaRemoteError;
46
- /** JSON-RPC's code for a method the server does not have. */
47
- TaRemoteError.METHOD_NOT_FOUND = -32601;
48
- /** What a call says that waited for a connection that did not come back. */
49
- TaRemoteError.NOT_CONNECTED = 'Not connected to ta serve.';
50
- /** What a call says that was sent on a connection lost before its answer. */
51
- TaRemoteError.LOST = 'The connection to ta serve was lost.';
5
+ const ta_remote_error_1 = require("./ta-remote-error");
52
6
  /** Methods that only read: sent again after a lost connection. */
53
7
  const READ_METHOD = /^(get|list|read|find)[A-Z]/;
54
8
  /** Methods whose input carries a clientMessageId, by which ta serve takes a message once however often it comes. */
@@ -83,6 +37,10 @@ class TaConnection {
83
37
  this.rooms = this.service(ta_protocol_1.TA_ROOM_SERVICE);
84
38
  /** What this page is at, for the others in the same Ta (docs/design/ta-team.md 7). */
85
39
  this.presence = this.service(ta_protocol_1.TA_PRESENCE_SERVICE);
40
+ /** The voice services of calls (docs/design/ta-voice.md). */
41
+ this.voice = this.service(ta_protocol_1.TA_VOICE_SERVICE);
42
+ /** Which requests of ta serve this page answers (onPageAsk, docs/design/ta-app-use.md 4.1). */
43
+ this.pages = this.service(ta_protocol_1.TA_PAGE_SERVICE);
86
44
  this.closed = false;
87
45
  this.attempts = 0;
88
46
  this.nextId = 0;
@@ -93,6 +51,7 @@ class TaConnection {
93
51
  this.authListeners = new Set();
94
52
  this.remoteListeners = new Set();
95
53
  this.roomListeners = new Set();
54
+ this.voiceListeners = new Set();
96
55
  this.sessionsListeners = new Set();
97
56
  this.openListeners = new Set();
98
57
  this.closeListeners = new Set();
@@ -146,6 +105,15 @@ class TaConnection {
146
105
  this.roomListeners.add(listener);
147
106
  return () => this.roomListeners.delete(listener);
148
107
  }
108
+ /** What the voices this connection opened tell (TaVoiceServer.openVoice). */
109
+ /** Answers what ta serve asks this page (TaClient.onPageAsk): one handler, the last set; without one, an error. */
110
+ onPageAsk(handler) {
111
+ this.pageAsk = handler;
112
+ }
113
+ onVoiceEvent(listener) {
114
+ this.voiceListeners.add(listener);
115
+ return () => this.voiceListeners.delete(listener);
116
+ }
149
117
  /** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
150
118
  onSessions(listener) {
151
119
  this.sessionsListeners.add(listener);
@@ -242,7 +210,7 @@ class TaConnection {
242
210
  }
243
211
  if (reject && !opened) {
244
212
  this.failPending();
245
- reject(new TaRemoteError(`Cannot connect to ${this.options.url}.`));
213
+ reject(new ta_remote_error_1.TaRemoteError(`Cannot connect to ${this.options.url}.`));
246
214
  return;
247
215
  }
248
216
  this.lost(socket, opened);
@@ -286,7 +254,7 @@ class TaConnection {
286
254
  opened(waitMs) {
287
255
  const { waitForOpenMs: configured = 5000 } = this.options;
288
256
  const waitForOpenMs = configured <= 0 ? 0 : (waitMs !== null && waitMs !== void 0 ? waitMs : configured);
289
- const notConnected = () => TaRemoteError.notConnected();
257
+ const notConnected = () => ta_remote_error_1.TaRemoteError.notConnected();
290
258
  if (this.closed || waitForOpenMs <= 0) {
291
259
  return Promise.reject(notConnected());
292
260
  }
@@ -309,7 +277,7 @@ class TaConnection {
309
277
  }
310
278
  failPending() {
311
279
  for (const call of this.pending.values()) {
312
- call.reject(new TaRemoteError(TaRemoteError.LOST, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
280
+ call.reject(new ta_remote_error_1.TaRemoteError(ta_remote_error_1.TaRemoteError.LOST, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
313
281
  }
314
282
  this.pending.clear();
315
283
  }
@@ -357,7 +325,7 @@ class TaConnection {
357
325
  send(service, method, params) {
358
326
  var _a;
359
327
  if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
360
- return Promise.reject(TaRemoteError.notConnected());
328
+ return Promise.reject(ta_remote_error_1.TaRemoteError.notConnected());
361
329
  }
362
330
  const socket = this.socket;
363
331
  const id = ++this.nextId;
@@ -390,8 +358,26 @@ class TaConnection {
390
358
  }
391
359
  }, Math.min(1000, stallMs));
392
360
  }
361
+ /** What the page answers to a request of ta serve, on the socket it came on. */
362
+ async answerPage(id, kind, payload) {
363
+ var _a;
364
+ const socket = this.socket;
365
+ let reply;
366
+ try {
367
+ if (!this.pageAsk) {
368
+ throw new Error('This page answers nothing.');
369
+ }
370
+ reply = { result: (_a = (await this.pageAsk(kind, payload))) !== null && _a !== void 0 ? _a : null };
371
+ }
372
+ catch (error) {
373
+ reply = { error: { code: -32000, message: error instanceof Error ? error.message : String(error) } };
374
+ }
375
+ if (socket === this.socket) {
376
+ socket === null || socket === void 0 ? void 0 : socket.send(JSON.stringify({ jsonrpc: '2.0', id, ...reply }));
377
+ }
378
+ }
393
379
  receive(text) {
394
- var _a, _b, _c, _d, _e, _f, _g;
380
+ var _a, _b, _c, _d, _e, _f, _g, _h;
395
381
  this.lastReceivedAt = Date.now();
396
382
  const message = JSON.parse(text);
397
383
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onEvents`) {
@@ -443,12 +429,25 @@ class TaConnection {
443
429
  (_f = this.socket) === null || _f === void 0 ? void 0 : _f.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
444
430
  return;
445
431
  }
432
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onVoiceEvent`) {
433
+ const [event] = message.params;
434
+ for (const listener of this.voiceListeners) {
435
+ listener(event);
436
+ }
437
+ (_g = this.socket) === null || _g === void 0 ? void 0 : _g.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
438
+ return;
439
+ }
440
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onPageAsk`) {
441
+ const [kind, payload] = message.params;
442
+ void this.answerPage(message.id, kind, payload);
443
+ return;
444
+ }
446
445
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onExtensionData`) {
447
446
  const [name, keys, cwd] = message.params;
448
447
  for (const listener of this.extensionDataListeners) {
449
448
  listener(name, keys, cwd !== null && cwd !== void 0 ? cwd : undefined);
450
449
  }
451
- (_g = this.socket) === null || _g === void 0 ? void 0 : _g.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
450
+ (_h = this.socket) === null || _h === void 0 ? void 0 : _h.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
452
451
  return;
453
452
  }
454
453
  const call = this.pending.get(message.id);
@@ -457,7 +456,7 @@ class TaConnection {
457
456
  }
458
457
  this.pending.delete(message.id);
459
458
  if (message.error) {
460
- call.reject(TaRemoteError.of(message.error));
459
+ call.reject(ta_remote_error_1.TaRemoteError.of(message.error));
461
460
  }
462
461
  else {
463
462
  call.resolve(message.result);
@@ -0,0 +1,39 @@
1
+ import { TaErrorCode, type TaErrorData } from '@celljs/ta-protocol';
2
+ /**
3
+ * A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
4
+ * by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
5
+ */
6
+ export declare class TaRemoteError extends Error {
7
+ readonly code?: TaErrorCode | undefined;
8
+ readonly hint?: string | undefined;
9
+ readonly rpcCode?: number | undefined;
10
+ /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
11
+ readonly data?: Readonly<Record<string, unknown>> | undefined;
12
+ /** JSON-RPC's code for a method the server does not have. */
13
+ static readonly METHOD_NOT_FOUND = -32601;
14
+ constructor(message: string, code?: TaErrorCode | undefined, hint?: string | undefined, rpcCode?: number | undefined,
15
+ /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
16
+ data?: Readonly<Record<string, unknown>> | undefined);
17
+ /** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
18
+ static of(error: {
19
+ message: string;
20
+ code?: number;
21
+ data?: {
22
+ data?: TaErrorData;
23
+ };
24
+ }): TaRemoteError;
25
+ /** What a call says that waited for a connection that did not come back. */
26
+ static readonly NOT_CONNECTED = "Not connected to ta serve.";
27
+ /** What a call says that was sent on a connection lost before its answer. */
28
+ static readonly LOST = "The connection to ta serve was lost.";
29
+ /** A call that waited for a connection that did not come back. */
30
+ static notConnected(): TaRemoteError;
31
+ /**
32
+ * Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
33
+ * words in a text (a web extension shows `error.message`, often inside its own words).
34
+ */
35
+ static isConnectionLost(cause: unknown): boolean;
36
+ /** Whether the server has no such method: a ta serve from before it was added. */
37
+ static isMethodNotFound(error: unknown): boolean;
38
+ }
39
+ //# sourceMappingURL=ta-remote-error.d.ts.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TaRemoteError = void 0;
4
+ const ta_protocol_1 = require("@celljs/ta-protocol");
5
+ /**
6
+ * A failed call. `code` is set for failures the server names; `rpcCode` is the code of JSON-RPC's error,
7
+ * by which a client tells a method an older ta serve does not have (`TaRemoteError.METHOD_NOT_FOUND`).
8
+ */
9
+ class TaRemoteError extends Error {
10
+ constructor(message, code, hint, rpcCode,
11
+ /** All ta serve said of the failure: for a refused call, the action it needs (TaForbiddenData). */
12
+ data) {
13
+ super(message);
14
+ this.code = code;
15
+ this.hint = hint;
16
+ this.rpcCode = rpcCode;
17
+ this.data = data;
18
+ this.name = 'TaRemoteError';
19
+ }
20
+ /** The error of a JSON-RPC answer: its code, and the code and hint of ta serve when it named the failure. */
21
+ static of(error) {
22
+ var _a;
23
+ const data = (_a = error.data) === null || _a === void 0 ? void 0 : _a.data;
24
+ return new TaRemoteError(error.message, data === null || data === void 0 ? void 0 : data.code, data === null || data === void 0 ? void 0 : data.hint, error.code, data);
25
+ }
26
+ /** A call that waited for a connection that did not come back. */
27
+ static notConnected() {
28
+ return new TaRemoteError(TaRemoteError.NOT_CONNECTED, ta_protocol_1.TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.');
29
+ }
30
+ /**
31
+ * Whether a failure is only that the connection was lost, which mends itself: by its code, or by its
32
+ * words in a text (a web extension shows `error.message`, often inside its own words).
33
+ */
34
+ static isConnectionLost(cause) {
35
+ if (typeof cause === 'string') {
36
+ return cause.includes(TaRemoteError.NOT_CONNECTED) || cause.includes(TaRemoteError.LOST);
37
+ }
38
+ return (cause === null || cause === void 0 ? void 0 : cause.code) === ta_protocol_1.TaErrorCode.CONNECTION_LOST;
39
+ }
40
+ /** Whether the server has no such method: a ta serve from before it was added. */
41
+ static isMethodNotFound(error) {
42
+ return error instanceof TaRemoteError && error.rpcCode === TaRemoteError.METHOD_NOT_FOUND;
43
+ }
44
+ }
45
+ exports.TaRemoteError = TaRemoteError;
46
+ /** JSON-RPC's code for a method the server does not have. */
47
+ TaRemoteError.METHOD_NOT_FOUND = -32601;
48
+ /** What a call says that waited for a connection that did not come back. */
49
+ TaRemoteError.NOT_CONNECTED = 'Not connected to ta serve.';
50
+ /** What a call says that was sent on a connection lost before its answer. */
51
+ TaRemoteError.LOST = 'The connection to ta serve was lost.';
52
+ //# sourceMappingURL=ta-remote-error.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-client",
3
- "version": "4.16.0",
3
+ "version": "4.17.0",
4
4
  "description": "A client of ta serve for any JavaScript runtime: connection and UI-independent session state",
5
5
  "homepage": "https://github.com/cellbang/ta",
6
6
  "bugs": {
@@ -29,7 +29,7 @@
29
29
  "watch": "tsc -b -w --preserveWatchOutput"
30
30
  },
31
31
  "dependencies": {
32
- "@celljs/ta-protocol": "4.16.0"
32
+ "@celljs/ta-protocol": "4.17.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@earendil-works/pi-ai": "^1.5.2",