@celljs/ta-client 4.16.0 → 4.18.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,20 +25,14 @@ 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
- this.current = this.shown = { ...this.current, messages, start, tools };
35
+ this.current = this.shown = { ...this.current, messages, start, tools, synced: false };
41
36
  }
42
37
  }
43
38
  get state() {
@@ -61,6 +56,9 @@ class SessionStore {
61
56
  for (const stop of this.stop.splice(0)) {
62
57
  stop();
63
58
  }
59
+ // Not through `update`: what it shows changes, the calls it runs do not.
60
+ this.current = { ...this.current, synced: false };
61
+ this.show();
64
62
  await this.connection.server.detach(this.sessionId);
65
63
  }
66
64
  subscribe(listener) {
@@ -149,7 +147,7 @@ class SessionStore {
149
147
  }
150
148
  return result;
151
149
  }, error => {
152
- if (keep && ta_connection_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
150
+ if (keep && ta_remote_error_1.TaRemoteError.isConnectionLost(error) && this.hold(sent)) {
153
151
  throw error;
154
152
  }
155
153
  if (keep) {
@@ -193,7 +191,7 @@ class SessionStore {
193
191
  continue;
194
192
  }
195
193
  if (now - sent.heldAt >= this.holdMs) {
196
- this.fail(sent, ta_connection_1.TaRemoteError.notConnected());
194
+ this.fail(sent, ta_remote_error_1.TaRemoteError.notConnected());
197
195
  }
198
196
  else {
199
197
  next = Math.min(next, sent.heldAt + this.holdMs - now);
@@ -273,7 +271,7 @@ class SessionStore {
273
271
  return this.connection.server.respondUi(this.sessionId, response);
274
272
  }
275
273
  async attachAgain(attached) {
276
- var _a, _b;
274
+ var _a, _b, _c;
277
275
  const result = attached !== null && attached !== void 0 ? attached : (await this.connection.server.attach(this.sessionId, this.lastSeq, this.pageBytes ? { recentBytes: this.pageBytes } : undefined));
278
276
  let state = this.current;
279
277
  // A conversation given (one attached as it opened) is the session's from scratch, whatever this store had.
@@ -287,6 +285,8 @@ class SessionStore {
287
285
  messages: kept,
288
286
  tools: conversation.tools,
289
287
  start,
288
+ // Those loaded further up kept: the head they start in, as it was.
289
+ head: start === ((_c = conversation.start) !== null && _c !== void 0 ? _c : 0) ? conversation.head : this.current.head,
290
290
  runStart: kept === this.current.messages ? this.current.runStart : undefined,
291
291
  };
292
292
  this.lastSeq = result.lastSeq;
@@ -299,6 +299,7 @@ class SessionStore {
299
299
  pendingUi: result.pendingUi,
300
300
  pendingClientTools: result.pendingClientTools,
301
301
  working: result.info.isStreaming,
302
+ synced: true,
302
303
  };
303
304
  if (result.shownUi) {
304
305
  // What the extensions show now, whatever events were missed.
@@ -373,15 +374,16 @@ class SessionStore {
373
374
  ...this.current,
374
375
  messages: [...page.messages, ...this.current.messages],
375
376
  start: page.start,
377
+ head: page.head,
376
378
  loadingEarlier: false,
377
379
  runStart: runStart === undefined ? undefined : runStart + page.messages.length,
378
380
  });
379
381
  }
380
382
  async reload() {
381
- const { messages, start } = this.pageBytes
383
+ const { messages, start, head } = this.pageBytes
382
384
  ? 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 });
385
+ : { ...(await this.connection.server.getMessages(this.sessionId)), start: 0, head: undefined };
386
+ this.update({ ...this.current, messages, start, head, tools: {}, runStart: undefined });
385
387
  }
386
388
  apply(events) {
387
389
  const taken = this.take(this.current, events);
@@ -439,66 +441,6 @@ class SessionStore {
439
441
  listener(shown);
440
442
  }
441
443
  }
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
444
  }
503
445
  exports.SessionStore = SessionStore;
504
446
  //# 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 TaDesktopEvent, type TaErrorData, type TaEventEnvelope, type TaGatewayServer, type TaPackageServer, type TaPageServer, type TaPresenceServer, type TaRelayServer, type TaRemoteEvent, type TaRemoteServer, type TaRoomEvent, type TaRoomServer, type TaScreenShareServer, 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;
@@ -122,9 +57,15 @@ export declare class TaConnection {
122
57
  readonly gateway: TaGatewayServer;
123
58
  readonly relay: TaRelayServer;
124
59
  readonly remote: TaRemoteServer;
60
+ /** Desktops of other computers, seen and worked (docs/design/ta-desktop-remote.md). */
61
+ readonly screenShare: TaScreenShareServer;
125
62
  readonly rooms: TaRoomServer;
126
63
  /** What this page is at, for the others in the same Ta (docs/design/ta-team.md 7). */
127
64
  readonly presence: TaPresenceServer;
65
+ /** The voice services of calls (docs/design/ta-voice.md). */
66
+ readonly voice: TaVoiceServer;
67
+ /** Which requests of ta serve this page answers (onPageAsk, docs/design/ta-app-use.md 4.1). */
68
+ readonly pages: TaPageServer;
128
69
  protected socket?: TaSocket;
129
70
  protected closed: boolean;
130
71
  protected attempts: number;
@@ -137,6 +78,9 @@ export declare class TaConnection {
137
78
  protected readonly authListeners: Set<AuthEventListener>;
138
79
  protected readonly remoteListeners: Set<RemoteEventListener>;
139
80
  protected readonly roomListeners: Set<RoomEventListener>;
81
+ protected readonly voiceListeners: Set<VoiceEventListener>;
82
+ protected readonly desktopListeners: Set<(event: TaDesktopEvent) => void>;
83
+ protected pageAsk?: PageAskHandler;
140
84
  protected readonly sessionsListeners: Set<SessionsListener>;
141
85
  protected readonly openListeners: Set<OpenListener>;
142
86
  protected readonly closeListeners: Set<CloseListener>;
@@ -166,6 +110,12 @@ export declare class TaConnection {
166
110
  onRemoteEvent(listener: RemoteEventListener): () => void;
167
111
  /** What happens in the rooms, once this connection called TaRoomServer.watch. */
168
112
  onRoomEvent(listener: RoomEventListener): () => void;
113
+ /** What the voices this connection opened tell (TaVoiceServer.openVoice). */
114
+ /** Answers what ta serve asks this page (TaClient.onPageAsk): one handler, the last set; without one, an error. */
115
+ onPageAsk(handler: PageAskHandler | undefined): void;
116
+ /** What the desktops ask (a password), once this connection called TaScreenShareServer.watchDesktops. */
117
+ onScreenShareEvent(listener: (event: TaDesktopEvent) => void): () => void;
118
+ onVoiceEvent(listener: VoiceEventListener): () => void;
169
119
  /** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
170
120
  onSessions(listener: SessionsListener): () => void;
171
121
  onOpen(listener: OpenListener): () => void;
@@ -193,7 +143,8 @@ export declare class TaConnection {
193
143
  protected service<T extends object>(name: string): T;
194
144
  /**
195
145
  * Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
196
- * a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
146
+ * a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once; of a desktop, a view
147
+ * opened or text pasted by its id, input by its seq, a view by its revision (docs/design/ta-desktop-remote.md 5.3).
197
148
  */
198
149
  static resendable(service: string, method: string, params: readonly unknown[]): boolean;
199
150
  protected call(service: string, method: string, params: unknown[]): Promise<unknown>;
@@ -201,6 +152,8 @@ export declare class TaConnection {
201
152
  protected send(service: string, method: string, params: unknown[]): Promise<unknown>;
202
153
  /** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
203
154
  protected watchStalls(): void;
155
+ /** What the page answers to a request of ta serve, on the socket it came on. */
156
+ protected answerPage(id: RpcMessage['id'], kind: string, payload: unknown): Promise<void>;
204
157
  protected receive(text: string): void;
205
158
  }
206
159
  export {};
@@ -1,58 +1,14 @@
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. */
55
9
  const MESSAGE_METHODS = new Set(['prompt', 'steer', 'followUp']);
10
+ /** Calls of TaScreenShareServer that ta serve takes once (an id, a seq, a revision), so that they may go again. */
11
+ const DESKTOP_ONCE = new Set(['openDesktop', 'pasteToDesktop', 'sendDesktopInput', 'setDesktopView']);
56
12
  /**
57
13
  * A connection to `ta serve` on the `WebSocket` of the platform, with no other dependency, so that it
58
14
  * fits a browser, Electron or a mobile app. It reconnects until closed; `onOpen` runs each time, for
@@ -80,9 +36,15 @@ class TaConnection {
80
36
  this.gateway = this.service(ta_protocol_1.TA_GATEWAY_SERVICE);
81
37
  this.relay = this.service(ta_protocol_1.TA_RELAY_SERVICE);
82
38
  this.remote = this.service(ta_protocol_1.TA_REMOTE_SERVICE);
39
+ /** Desktops of other computers, seen and worked (docs/design/ta-desktop-remote.md). */
40
+ this.screenShare = this.service(ta_protocol_1.TA_SCREEN_SHARE_SERVICE);
83
41
  this.rooms = this.service(ta_protocol_1.TA_ROOM_SERVICE);
84
42
  /** What this page is at, for the others in the same Ta (docs/design/ta-team.md 7). */
85
43
  this.presence = this.service(ta_protocol_1.TA_PRESENCE_SERVICE);
44
+ /** The voice services of calls (docs/design/ta-voice.md). */
45
+ this.voice = this.service(ta_protocol_1.TA_VOICE_SERVICE);
46
+ /** Which requests of ta serve this page answers (onPageAsk, docs/design/ta-app-use.md 4.1). */
47
+ this.pages = this.service(ta_protocol_1.TA_PAGE_SERVICE);
86
48
  this.closed = false;
87
49
  this.attempts = 0;
88
50
  this.nextId = 0;
@@ -93,6 +55,8 @@ class TaConnection {
93
55
  this.authListeners = new Set();
94
56
  this.remoteListeners = new Set();
95
57
  this.roomListeners = new Set();
58
+ this.voiceListeners = new Set();
59
+ this.desktopListeners = new Set();
96
60
  this.sessionsListeners = new Set();
97
61
  this.openListeners = new Set();
98
62
  this.closeListeners = new Set();
@@ -146,6 +110,20 @@ class TaConnection {
146
110
  this.roomListeners.add(listener);
147
111
  return () => this.roomListeners.delete(listener);
148
112
  }
113
+ /** What the voices this connection opened tell (TaVoiceServer.openVoice). */
114
+ /** Answers what ta serve asks this page (TaClient.onPageAsk): one handler, the last set; without one, an error. */
115
+ onPageAsk(handler) {
116
+ this.pageAsk = handler;
117
+ }
118
+ /** What the desktops ask (a password), once this connection called TaScreenShareServer.watchDesktops. */
119
+ onScreenShareEvent(listener) {
120
+ this.desktopListeners.add(listener);
121
+ return () => this.desktopListeners.delete(listener);
122
+ }
123
+ onVoiceEvent(listener) {
124
+ this.voiceListeners.add(listener);
125
+ return () => this.voiceListeners.delete(listener);
126
+ }
149
127
  /** The open sessions as they change (TaClient.onSessions), once this connection called TaServer.watchSessions. */
150
128
  onSessions(listener) {
151
129
  this.sessionsListeners.add(listener);
@@ -242,7 +220,7 @@ class TaConnection {
242
220
  }
243
221
  if (reject && !opened) {
244
222
  this.failPending();
245
- reject(new TaRemoteError(`Cannot connect to ${this.options.url}.`));
223
+ reject(new ta_remote_error_1.TaRemoteError(`Cannot connect to ${this.options.url}.`));
246
224
  return;
247
225
  }
248
226
  this.lost(socket, opened);
@@ -286,7 +264,7 @@ class TaConnection {
286
264
  opened(waitMs) {
287
265
  const { waitForOpenMs: configured = 5000 } = this.options;
288
266
  const waitForOpenMs = configured <= 0 ? 0 : (waitMs !== null && waitMs !== void 0 ? waitMs : configured);
289
- const notConnected = () => TaRemoteError.notConnected();
267
+ const notConnected = () => ta_remote_error_1.TaRemoteError.notConnected();
290
268
  if (this.closed || waitForOpenMs <= 0) {
291
269
  return Promise.reject(notConnected());
292
270
  }
@@ -309,7 +287,7 @@ class TaConnection {
309
287
  }
310
288
  failPending() {
311
289
  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.'));
290
+ 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
291
  }
314
292
  this.pending.clear();
315
293
  }
@@ -320,13 +298,17 @@ class TaConnection {
320
298
  }
321
299
  /**
322
300
  * Whether a call may go again after a lost connection, as doing it twice does what doing it once does:
323
- * a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once.
301
+ * a read, or a message with its clientMessageId (TaPromptInput), which ta serve takes once; of a desktop, a view
302
+ * opened or text pasted by its id, input by its seq, a view by its revision (docs/design/ta-desktop-remote.md 5.3).
324
303
  */
325
304
  static resendable(service, method, params) {
326
305
  var _a;
327
306
  if (READ_METHOD.test(method)) {
328
307
  return true;
329
308
  }
309
+ if (service === ta_protocol_1.TA_SCREEN_SHARE_SERVICE) {
310
+ return DESKTOP_ONCE.has(method);
311
+ }
330
312
  return service === ta_protocol_1.TA_SERVER_SERVICE && MESSAGE_METHODS.has(method) && !!((_a = params[1]) === null || _a === void 0 ? void 0 : _a.clientMessageId);
331
313
  }
332
314
  async call(service, method, params) {
@@ -357,7 +339,7 @@ class TaConnection {
357
339
  send(service, method, params) {
358
340
  var _a;
359
341
  if (((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) !== WebSocket.OPEN) {
360
- return Promise.reject(TaRemoteError.notConnected());
342
+ return Promise.reject(ta_remote_error_1.TaRemoteError.notConnected());
361
343
  }
362
344
  const socket = this.socket;
363
345
  const id = ++this.nextId;
@@ -390,8 +372,26 @@ class TaConnection {
390
372
  }
391
373
  }, Math.min(1000, stallMs));
392
374
  }
375
+ /** What the page answers to a request of ta serve, on the socket it came on. */
376
+ async answerPage(id, kind, payload) {
377
+ var _a;
378
+ const socket = this.socket;
379
+ let reply;
380
+ try {
381
+ if (!this.pageAsk) {
382
+ throw new Error('This page answers nothing.');
383
+ }
384
+ reply = { result: (_a = (await this.pageAsk(kind, payload))) !== null && _a !== void 0 ? _a : null };
385
+ }
386
+ catch (error) {
387
+ reply = { error: { code: -32000, message: error instanceof Error ? error.message : String(error) } };
388
+ }
389
+ if (socket === this.socket) {
390
+ socket === null || socket === void 0 ? void 0 : socket.send(JSON.stringify({ jsonrpc: '2.0', id, ...reply }));
391
+ }
392
+ }
393
393
  receive(text) {
394
- var _a, _b, _c, _d, _e, _f, _g;
394
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
395
395
  this.lastReceivedAt = Date.now();
396
396
  const message = JSON.parse(text);
397
397
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onEvents`) {
@@ -443,12 +443,33 @@ class TaConnection {
443
443
  (_f = this.socket) === null || _f === void 0 ? void 0 : _f.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
444
444
  return;
445
445
  }
446
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onScreenShareEvent`) {
447
+ const [event] = message.params;
448
+ for (const listener of this.desktopListeners) {
449
+ listener(event);
450
+ }
451
+ (_g = this.socket) === null || _g === void 0 ? void 0 : _g.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
452
+ return;
453
+ }
454
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onVoiceEvent`) {
455
+ const [event] = message.params;
456
+ for (const listener of this.voiceListeners) {
457
+ listener(event);
458
+ }
459
+ (_h = this.socket) === null || _h === void 0 ? void 0 : _h.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
460
+ return;
461
+ }
462
+ if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onPageAsk`) {
463
+ const [kind, payload] = message.params;
464
+ void this.answerPage(message.id, kind, payload);
465
+ return;
466
+ }
446
467
  if (message.method === `${ta_protocol_1.TA_CLIENT_SERVICE}/onExtensionData`) {
447
468
  const [name, keys, cwd] = message.params;
448
469
  for (const listener of this.extensionDataListeners) {
449
470
  listener(name, keys, cwd !== null && cwd !== void 0 ? cwd : undefined);
450
471
  }
451
- (_g = this.socket) === null || _g === void 0 ? void 0 : _g.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
472
+ (_j = this.socket) === null || _j === void 0 ? void 0 : _j.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
452
473
  return;
453
474
  }
454
475
  const call = this.pending.get(message.id);
@@ -457,7 +478,7 @@ class TaConnection {
457
478
  }
458
479
  this.pending.delete(message.id);
459
480
  if (message.error) {
460
- call.reject(TaRemoteError.of(message.error));
481
+ call.reject(ta_remote_error_1.TaRemoteError.of(message.error));
461
482
  }
462
483
  else {
463
484
  call.resolve(message.result);