@lynkoria/client 0.0.0-stage → 0.1.1
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/CHANGELOG.md +9 -0
- package/LICENSE +201 -0
- package/README.md +79 -2
- package/dist/index.d.ts +221 -0
- package/dist/index.js +546 -0
- package/package.json +39 -3
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lynkoria/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@lynkoria/client)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
Client SDK for **browsers and Electron**: realtime messaging, presence, typing, attachments and calls.
|
|
7
|
+
Your app never holds a service key. It gets short-lived tokens from **your** backend, which authorizes the
|
|
8
|
+
user and asks Lynkoria for them with [`@lynkoria/server`](https://www.npmjs.com/package/@lynkoria/server).
|
|
9
|
+
|
|
10
|
+
**[Documentation](https://lynkoria.com/docs/)** · [Client SDK guide](https://lynkoria.com/docs/client-sdk/) ·
|
|
11
|
+
[Quickstart](https://lynkoria.com/docs/quickstart/) · [Messaging](https://lynkoria.com/docs/messaging/) ·
|
|
12
|
+
[Calls](https://lynkoria.com/docs/calls/)
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @lynkoria/client
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
ES module with TypeScript types. `livekit-client` is only loaded when a user joins a call, so messaging-only
|
|
21
|
+
apps do not download the media engine.
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createLynkoria } from '@lynkoria/client';
|
|
27
|
+
|
|
28
|
+
const rtc = createLynkoria({
|
|
29
|
+
baseUrl: 'https://api.lynkoria.com',
|
|
30
|
+
getMessagingToken: () => myBackend.fetchLynkoriaMessagingToken(),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
rtc.connect();
|
|
34
|
+
|
|
35
|
+
// Messaging: history, live events and sending.
|
|
36
|
+
const history = await rtc.messages.history('conv_123');
|
|
37
|
+
const off = rtc.onMessage((event) => render(event)); // ordered, deduplicated, resynced after gaps
|
|
38
|
+
await rtc.messages.send({
|
|
39
|
+
conversationId: 'conv_123',
|
|
40
|
+
clientMessageId: rtc.ids.create(), // retry with the same ID: never duplicates
|
|
41
|
+
text: 'Hello',
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Presence.
|
|
45
|
+
const unsubscribe = rtc.presence.subscribe('user_456', (p) => render(p.status));
|
|
46
|
+
|
|
47
|
+
// Calls: your backend returns a join token from @lynkoria/server.
|
|
48
|
+
const session = await rtc.calls.join({ getJoinToken: () => myBackend.fetchJoinToken('call_789') });
|
|
49
|
+
await session.setMicrophoneEnabled(false);
|
|
50
|
+
await session.startScreenShare();
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## What it covers
|
|
54
|
+
|
|
55
|
+
| Area | API | Guide |
|
|
56
|
+
| ------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
|
|
57
|
+
| Connection | `connect`, `disconnect`, `onConnectionState`, `onError` | [Client SDK](https://lynkoria.com/docs/client-sdk/) |
|
|
58
|
+
| Messages | `messages.history`, `send`, `edit`, `delete`, `react`, `markRead`, `onMessage`, `onRead` | [Messaging](https://lynkoria.com/docs/messaging/) |
|
|
59
|
+
| Conversations | `conversations.list`, `track`, `untrack`, `resync`, `onConversationUpdated` | [Messaging](https://lynkoria.com/docs/messaging/) |
|
|
60
|
+
| Presence | `presence.subscribe`, `get`, `setStatus`, `typing.start`, `stop`, `onTyping` | [Presence](https://lynkoria.com/docs/presence/) |
|
|
61
|
+
| Attachments | `attachments.upload`, `downloadUrl` | [File security](https://lynkoria.com/docs/file-security-and-scanning/) |
|
|
62
|
+
| Calls | `calls.join`, mute, camera, screen share, devices, participants | [Calls](https://lynkoria.com/docs/calls/) |
|
|
63
|
+
|
|
64
|
+
## Delivery guarantees
|
|
65
|
+
|
|
66
|
+
PostgreSQL is the source of truth. Realtime events carry a per-conversation `seq`: the client applies them
|
|
67
|
+
in order, drops duplicates, and after a gap or a reconnect fetches the missed events. Retrying `send` with
|
|
68
|
+
the same `clientMessageId` never creates a duplicate.
|
|
69
|
+
|
|
70
|
+
## Frameworks
|
|
71
|
+
|
|
72
|
+
- React: [`@lynkoria/react`](https://www.npmjs.com/package/@lynkoria/react) hooks.
|
|
73
|
+
- Next.js and TanStack Start: [Next.js guide](https://lynkoria.com/docs/nextjs/), [TanStack guide](https://lynkoria.com/docs/tanstack/).
|
|
74
|
+
- React Native: messaging works with platform `fetch` and an ID generator
|
|
75
|
+
(`ids: { create: () => yourUuid() }` when `crypto.randomUUID` is missing). For native calls, use
|
|
76
|
+
[`@lynkoria/react-native`](https://www.npmjs.com/package/@lynkoria/react-native).
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
[Apache-2.0](./LICENSE)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { Attachment, CallSignalEvent, ConversationEvent, ConversationEventPage, ConversationReadEvent, ConversationUpdatedEvent, ErrorCode, LynkoriaError, LynkoriaError as LynkoriaError$1, ManualStatus, Message, NotificationPreferences, Presence, PushProvider, TypingEvent } from "@lynkoria/contracts";
|
|
2
|
+
import { Room, RoomConnectOptions, RoomOptions } from "livekit-client";
|
|
3
|
+
export type * from "@lynkoria/contracts";
|
|
4
|
+
type CallConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
|
|
5
|
+
type CallDeviceKind = 'audioinput' | 'audiooutput' | 'videoinput';
|
|
6
|
+
type ConnectionQuality = 'excellent' | 'good' | 'poor' | 'lost' | 'unknown';
|
|
7
|
+
/** A snapshot of one participant, local or remote. */
|
|
8
|
+
type CallParticipant = {
|
|
9
|
+
/** Lynkoria media identity: `project:user:device`. */
|
|
10
|
+
identity: string;
|
|
11
|
+
name: string;
|
|
12
|
+
isLocal: boolean;
|
|
13
|
+
isMicrophoneEnabled: boolean;
|
|
14
|
+
isCameraEnabled: boolean;
|
|
15
|
+
isScreenShareEnabled: boolean;
|
|
16
|
+
isSpeaking: boolean;
|
|
17
|
+
connectionQuality: ConnectionQuality;
|
|
18
|
+
};
|
|
19
|
+
type JoinCallOptions = {
|
|
20
|
+
/** Calls your product backend, which authorizes the user and asks Lynkoria for a join token. */
|
|
21
|
+
getJoinToken: () => Promise<{
|
|
22
|
+
url: string;
|
|
23
|
+
token: string;
|
|
24
|
+
}>;
|
|
25
|
+
roomOptions?: RoomOptions;
|
|
26
|
+
connectOptions?: RoomConnectOptions;
|
|
27
|
+
};
|
|
28
|
+
type CallSession = {
|
|
29
|
+
/** The underlying LiveKit room, for rendering with @livekit/components-react or custom UI. */
|
|
30
|
+
readonly room: Room;
|
|
31
|
+
readonly state: CallConnectionState;
|
|
32
|
+
setMicrophoneEnabled(enabled: boolean): Promise<void>;
|
|
33
|
+
setCameraEnabled(enabled: boolean): Promise<void>;
|
|
34
|
+
startScreenShare(): Promise<void>;
|
|
35
|
+
stopScreenShare(): Promise<void>;
|
|
36
|
+
onStateChange(listener: (state: CallConnectionState) => void): () => void;
|
|
37
|
+
/** Local participant first, then remote participants in join order. */
|
|
38
|
+
readonly participants: CallParticipant[];
|
|
39
|
+
/** Fires on joins, leaves, mute/camera/screen changes, active speakers and connection quality. */
|
|
40
|
+
onParticipantsChange(listener: (participants: CallParticipant[]) => void): () => void;
|
|
41
|
+
/** Available devices of a kind (asks for permission first if labels are hidden). */
|
|
42
|
+
listDevices(kind: CallDeviceKind): Promise<MediaDeviceInfo[]>;
|
|
43
|
+
/** Switches the active microphone, camera or speaker for this call. */
|
|
44
|
+
switchDevice(kind: CallDeviceKind, deviceId: string): Promise<void>;
|
|
45
|
+
leave(): Promise<void>;
|
|
46
|
+
};
|
|
47
|
+
type TokenResult = string | {
|
|
48
|
+
token: string;
|
|
49
|
+
expiresAt?: string;
|
|
50
|
+
};
|
|
51
|
+
/** Reads `exp` from a JWT without verifying it (verification happens on the server). */
|
|
52
|
+
export declare function jwtExpiry(token: string): number | null;
|
|
53
|
+
type SequenceDecision = 'apply' | 'duplicate' | 'gap';
|
|
54
|
+
/**
|
|
55
|
+
* Tracks the last applied conversation sequence number (plan §9.2 step 7). An event with
|
|
56
|
+
* `seq > last + 1` means realtime delivery dropped something: resync with `after_seq = last`.
|
|
57
|
+
*/
|
|
58
|
+
export declare class SequenceTracker {
|
|
59
|
+
private readonly last;
|
|
60
|
+
get(conversationId: string): number | undefined;
|
|
61
|
+
/** Set the baseline, e.g. after loading history. Never moves backwards. */
|
|
62
|
+
set(conversationId: string, seq: number): void;
|
|
63
|
+
conversations(): string[];
|
|
64
|
+
forget(conversationId: string): void;
|
|
65
|
+
decide(conversationId: string, seq: number): SequenceDecision;
|
|
66
|
+
}
|
|
67
|
+
export type ConnectionState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
|
|
68
|
+
export type LynkoriaClientOptions = {
|
|
69
|
+
/** e.g. https://api.lynkoria.com */
|
|
70
|
+
baseUrl: string;
|
|
71
|
+
/** Calls your product backend, which mints a Lynkoria messaging token with its service key. */
|
|
72
|
+
getMessagingToken: () => Promise<TokenResult>;
|
|
73
|
+
/** Injectable platform adapters (React Native: no `window`, maybe no `crypto.randomUUID`). */
|
|
74
|
+
ids?: {
|
|
75
|
+
create(): string;
|
|
76
|
+
};
|
|
77
|
+
fetch?: typeof fetch;
|
|
78
|
+
socketPath?: string;
|
|
79
|
+
heartbeatMs?: number;
|
|
80
|
+
};
|
|
81
|
+
type IdempotentSend = {
|
|
82
|
+
conversationId: string;
|
|
83
|
+
text?: string;
|
|
84
|
+
attachmentIds?: string[];
|
|
85
|
+
parentMessageId?: string;
|
|
86
|
+
/** Stable per logical message; reuse it when retrying. Generated if omitted. */
|
|
87
|
+
clientMessageId?: string;
|
|
88
|
+
};
|
|
89
|
+
export type LynkoriaClient = ReturnType<typeof createLynkoria>;
|
|
90
|
+
export declare function createLynkoria(opts: LynkoriaClientOptions): {
|
|
91
|
+
connect: () => void;
|
|
92
|
+
disconnect: () => void;
|
|
93
|
+
readonly connectionState: ConnectionState;
|
|
94
|
+
onConnectionState: (l: (s: ConnectionState) => void) => () => void;
|
|
95
|
+
onError: (l: (e: LynkoriaError$1) => void) => () => void;
|
|
96
|
+
/** Every applied conversation event, in sequence order per conversation, deduplicated. */
|
|
97
|
+
onMessage: (l: (e: ConversationEvent) => void) => () => void;
|
|
98
|
+
onPresenceChange: (l: (p: Presence) => void) => () => void;
|
|
99
|
+
onCallStateChange: (l: (e: CallSignalEvent) => void) => () => void;
|
|
100
|
+
onTyping: (l: (e: TypingEvent & {
|
|
101
|
+
typing: boolean;
|
|
102
|
+
}) => void) => () => void;
|
|
103
|
+
onRead: (l: (e: ConversationReadEvent) => void) => () => void;
|
|
104
|
+
onConversationUpdated: (l: (e: ConversationUpdatedEvent) => void) => () => void;
|
|
105
|
+
ids: {
|
|
106
|
+
create(): string;
|
|
107
|
+
};
|
|
108
|
+
conversations: {
|
|
109
|
+
list: (params?: {
|
|
110
|
+
limit?: number;
|
|
111
|
+
cursor?: string;
|
|
112
|
+
}) => Promise<{
|
|
113
|
+
items: {
|
|
114
|
+
id: string;
|
|
115
|
+
tenantId: string;
|
|
116
|
+
type: "channel" | "dm" | "group" | "session";
|
|
117
|
+
productConversationId: string | null;
|
|
118
|
+
title: string | null;
|
|
119
|
+
lastSeq: number;
|
|
120
|
+
lastMessageAt: string | null;
|
|
121
|
+
createdAt: string;
|
|
122
|
+
readSeq?: number | undefined;
|
|
123
|
+
}[];
|
|
124
|
+
nextCursor: string | null;
|
|
125
|
+
}>;
|
|
126
|
+
/** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
|
|
127
|
+
track: (conversationId: string, lastSeq: number) => void;
|
|
128
|
+
untrack: (conversationId: string) => void;
|
|
129
|
+
resync: (conversationId: string) => Promise<void>;
|
|
130
|
+
};
|
|
131
|
+
messages: {
|
|
132
|
+
/** Latest history page (or older, with `beforeSeq`). Also starts tracking the conversation. */
|
|
133
|
+
history(conversationId: string, params?: {
|
|
134
|
+
beforeSeq?: number;
|
|
135
|
+
limit?: number;
|
|
136
|
+
}): Promise<ConversationEventPage>;
|
|
137
|
+
send(input: IdempotentSend): Promise<Message>;
|
|
138
|
+
edit: (messageId: string, text: string) => Promise<{
|
|
139
|
+
id: string;
|
|
140
|
+
conversationId: string;
|
|
141
|
+
seq: number;
|
|
142
|
+
senderId: string;
|
|
143
|
+
clientMessageId: string;
|
|
144
|
+
kind: "system" | "text";
|
|
145
|
+
body: string | null;
|
|
146
|
+
attachments: {
|
|
147
|
+
id: string;
|
|
148
|
+
fileName: string;
|
|
149
|
+
mediaType: string;
|
|
150
|
+
size: number;
|
|
151
|
+
status: "pending" | "ready" | "rejected";
|
|
152
|
+
scanStatus?: "clean" | "failed" | "infected" | "not_scanned" | "pending" | "rejected" | undefined;
|
|
153
|
+
}[];
|
|
154
|
+
reactions: {
|
|
155
|
+
userId: string;
|
|
156
|
+
emoji: string;
|
|
157
|
+
}[];
|
|
158
|
+
parentMessageId: string | null;
|
|
159
|
+
createdAt: string;
|
|
160
|
+
editedAt: string | null;
|
|
161
|
+
deletedAt: string | null;
|
|
162
|
+
}>;
|
|
163
|
+
delete: (messageId: string) => Promise<void>;
|
|
164
|
+
react: (messageId: string, emoji: string) => Promise<void>;
|
|
165
|
+
unreact: (messageId: string, emoji: string) => Promise<void>;
|
|
166
|
+
markRead: (conversationId: string, seq: number) => Promise<{
|
|
167
|
+
readSeq: number;
|
|
168
|
+
}>;
|
|
169
|
+
};
|
|
170
|
+
presence: {
|
|
171
|
+
/** Subscribe to one user's presence; returns an unsubscribe function. */
|
|
172
|
+
subscribe(userId: string, listener: (p: Presence) => void): () => void;
|
|
173
|
+
get: (userId: string) => Promise<{
|
|
174
|
+
userId: string;
|
|
175
|
+
status: "away" | "busy" | "dnd" | "offline" | "online";
|
|
176
|
+
lastSeenAt: string | null;
|
|
177
|
+
}>;
|
|
178
|
+
setStatus: (status: ManualStatus) => Promise<null>;
|
|
179
|
+
};
|
|
180
|
+
typing: {
|
|
181
|
+
/** Throttled to one event per 3 s per conversation. */
|
|
182
|
+
start(conversationId: string): void;
|
|
183
|
+
stop(conversationId: string): void;
|
|
184
|
+
};
|
|
185
|
+
attachments: {
|
|
186
|
+
/** Presigned direct upload; large files never pass through the socket server. */
|
|
187
|
+
upload(conversationId: string, file: Blob, fileName: string): Promise<Attachment>;
|
|
188
|
+
downloadUrl: (attachmentId: string) => Promise<{
|
|
189
|
+
url: string;
|
|
190
|
+
expiresAt: string;
|
|
191
|
+
}>;
|
|
192
|
+
};
|
|
193
|
+
calls: {
|
|
194
|
+
join: (options: JoinCallOptions) => Promise<CallSession>;
|
|
195
|
+
};
|
|
196
|
+
/** Device push registration for native apps (React Native uses this client for messaging). */
|
|
197
|
+
push: {
|
|
198
|
+
/** Call on every FCM/APNs/PushKit token refresh; idempotent. */
|
|
199
|
+
register: (input: {
|
|
200
|
+
provider: PushProvider;
|
|
201
|
+
token: string;
|
|
202
|
+
appId: string;
|
|
203
|
+
apnsEnvironment?: 'sandbox' | 'production';
|
|
204
|
+
}) => Promise<{
|
|
205
|
+
id: string;
|
|
206
|
+
deviceId: string;
|
|
207
|
+
platform: "android" | "ios";
|
|
208
|
+
provider: "apns" | "apns_voip" | "fcm";
|
|
209
|
+
appId: string;
|
|
210
|
+
updatedAt: string;
|
|
211
|
+
}>;
|
|
212
|
+
/** Call on sign-out so this device stops receiving the user's pushes. */
|
|
213
|
+
unregister: (provider?: PushProvider) => Promise<void>;
|
|
214
|
+
preferences: () => Promise<{
|
|
215
|
+
calls: boolean;
|
|
216
|
+
messages: boolean;
|
|
217
|
+
}>;
|
|
218
|
+
setPreferences: (prefs: NotificationPreferences) => Promise<void>;
|
|
219
|
+
};
|
|
220
|
+
};
|
|
221
|
+
export { type CallConnectionState, type CallDeviceKind, type CallParticipant, type CallSession, type ConnectionQuality, ErrorCode, type JoinCallOptions, LynkoriaError, type SequenceDecision };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
import { ErrorCode, ErrorCode as ErrorCode$1, LynkoriaError, LynkoriaError as LynkoriaError$1 } from "@lynkoria/contracts";
|
|
2
|
+
import { io } from "socket.io-client";
|
|
3
|
+
// src/emitter.ts
|
|
4
|
+
var Emitter = class {
|
|
5
|
+
listeners = /* @__PURE__ */ new Set();
|
|
6
|
+
on(listener) {
|
|
7
|
+
this.listeners.add(listener);
|
|
8
|
+
return () => this.listeners.delete(listener);
|
|
9
|
+
}
|
|
10
|
+
emit(value) {
|
|
11
|
+
for (const l of this.listeners) try {
|
|
12
|
+
l(value);
|
|
13
|
+
} catch {}
|
|
14
|
+
}
|
|
15
|
+
clear() {
|
|
16
|
+
this.listeners.clear();
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
// src/media.ts
|
|
20
|
+
/**
|
|
21
|
+
* Internal media adapter (plan §10.3 rule 6): the only place that talks to livekit-client, loaded
|
|
22
|
+
* lazily so messaging-only apps never download the media engine. The server returns the media URL
|
|
23
|
+
* with every token, so no LiveKit hostname or region is baked into apps.
|
|
24
|
+
*/
|
|
25
|
+
var LiveKitMediaProvider = class {
|
|
26
|
+
async join(opts) {
|
|
27
|
+
const { Room, RoomEvent, ConnectionState } = await import("livekit-client");
|
|
28
|
+
const { url, token } = await opts.getJoinToken();
|
|
29
|
+
const room = new Room({
|
|
30
|
+
adaptiveStream: true,
|
|
31
|
+
dynacast: true,
|
|
32
|
+
...opts.roomOptions
|
|
33
|
+
});
|
|
34
|
+
const map = (s) => s === ConnectionState.Connected ? "connected" : s === ConnectionState.Connecting ? "connecting" : s === ConnectionState.Reconnecting || s === ConnectionState.SignalReconnecting ? "reconnecting" : "disconnected";
|
|
35
|
+
try {
|
|
36
|
+
await room.connect(url, token, opts.connectOptions);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
await room.disconnect();
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
const lp = () => room.localParticipant;
|
|
42
|
+
const snapshot = () => [room.localParticipant, ...room.remoteParticipants.values()].map((p) => ({
|
|
43
|
+
identity: p.identity,
|
|
44
|
+
name: p.name || p.identity,
|
|
45
|
+
isLocal: p === room.localParticipant,
|
|
46
|
+
isMicrophoneEnabled: p.isMicrophoneEnabled,
|
|
47
|
+
isCameraEnabled: p.isCameraEnabled,
|
|
48
|
+
isScreenShareEnabled: p.isScreenShareEnabled,
|
|
49
|
+
isSpeaking: p.isSpeaking,
|
|
50
|
+
connectionQuality: p.connectionQuality
|
|
51
|
+
}));
|
|
52
|
+
const participantEvents = [
|
|
53
|
+
RoomEvent.ParticipantConnected,
|
|
54
|
+
RoomEvent.ParticipantDisconnected,
|
|
55
|
+
RoomEvent.ParticipantNameChanged,
|
|
56
|
+
RoomEvent.TrackPublished,
|
|
57
|
+
RoomEvent.TrackUnpublished,
|
|
58
|
+
RoomEvent.TrackMuted,
|
|
59
|
+
RoomEvent.TrackUnmuted,
|
|
60
|
+
RoomEvent.LocalTrackPublished,
|
|
61
|
+
RoomEvent.LocalTrackUnpublished,
|
|
62
|
+
RoomEvent.ActiveSpeakersChanged,
|
|
63
|
+
RoomEvent.ConnectionQualityChanged
|
|
64
|
+
];
|
|
65
|
+
return {
|
|
66
|
+
room,
|
|
67
|
+
get state() {
|
|
68
|
+
return map(room.state);
|
|
69
|
+
},
|
|
70
|
+
setMicrophoneEnabled: async (enabled) => void await lp().setMicrophoneEnabled(enabled),
|
|
71
|
+
setCameraEnabled: async (enabled) => void await lp().setCameraEnabled(enabled),
|
|
72
|
+
startScreenShare: async () => void await lp().setScreenShareEnabled(true),
|
|
73
|
+
stopScreenShare: async () => void await lp().setScreenShareEnabled(false),
|
|
74
|
+
onStateChange: (listener) => {
|
|
75
|
+
const handler = (s) => listener(map(s));
|
|
76
|
+
room.on(RoomEvent.ConnectionStateChanged, handler);
|
|
77
|
+
return () => void room.off(RoomEvent.ConnectionStateChanged, handler);
|
|
78
|
+
},
|
|
79
|
+
get participants() {
|
|
80
|
+
return snapshot();
|
|
81
|
+
},
|
|
82
|
+
onParticipantsChange: (listener) => {
|
|
83
|
+
const handler = () => listener(snapshot());
|
|
84
|
+
for (const e of participantEvents) room.on(e, handler);
|
|
85
|
+
return () => {
|
|
86
|
+
for (const e of participantEvents) room.off(e, handler);
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
listDevices: (kind) => Room.getLocalDevices(kind),
|
|
90
|
+
switchDevice: async (kind, deviceId) => void await room.switchActiveDevice(kind, deviceId),
|
|
91
|
+
leave: () => room.disconnect()
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
// src/sequence.ts
|
|
96
|
+
/**
|
|
97
|
+
* Tracks the last applied conversation sequence number (plan §9.2 step 7). An event with
|
|
98
|
+
* `seq > last + 1` means realtime delivery dropped something: resync with `after_seq = last`.
|
|
99
|
+
*/
|
|
100
|
+
var SequenceTracker = class {
|
|
101
|
+
last = /* @__PURE__ */ new Map();
|
|
102
|
+
get(conversationId) {
|
|
103
|
+
return this.last.get(conversationId);
|
|
104
|
+
}
|
|
105
|
+
/** Set the baseline, e.g. after loading history. Never moves backwards. */
|
|
106
|
+
set(conversationId, seq) {
|
|
107
|
+
const cur = this.last.get(conversationId);
|
|
108
|
+
if (cur === void 0 || seq > cur) this.last.set(conversationId, seq);
|
|
109
|
+
}
|
|
110
|
+
conversations() {
|
|
111
|
+
return [...this.last.keys()];
|
|
112
|
+
}
|
|
113
|
+
forget(conversationId) {
|
|
114
|
+
this.last.delete(conversationId);
|
|
115
|
+
}
|
|
116
|
+
decide(conversationId, seq) {
|
|
117
|
+
const cur = this.last.get(conversationId);
|
|
118
|
+
if (cur === void 0) {
|
|
119
|
+
this.last.set(conversationId, seq);
|
|
120
|
+
return "apply";
|
|
121
|
+
}
|
|
122
|
+
if (seq <= cur) return "duplicate";
|
|
123
|
+
if (seq === cur + 1) {
|
|
124
|
+
this.last.set(conversationId, seq);
|
|
125
|
+
return "apply";
|
|
126
|
+
}
|
|
127
|
+
return "gap";
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
// src/tokens.ts
|
|
131
|
+
/** Reads `exp` from a JWT without verifying it (verification happens on the server). */
|
|
132
|
+
function jwtExpiry(token) {
|
|
133
|
+
try {
|
|
134
|
+
const payload = token.split(".")[1];
|
|
135
|
+
if (!payload) return null;
|
|
136
|
+
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
137
|
+
const exp = JSON.parse(json).exp;
|
|
138
|
+
return typeof exp === "number" ? exp * 1e3 : null;
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Caches the messaging token from the product backend; refreshes it within 60 s of expiry. */
|
|
144
|
+
var TokenSource = class {
|
|
145
|
+
fetchToken;
|
|
146
|
+
cached = null;
|
|
147
|
+
inflight = null;
|
|
148
|
+
constructor(fetchToken) {
|
|
149
|
+
this.fetchToken = fetchToken;
|
|
150
|
+
}
|
|
151
|
+
expiresAt() {
|
|
152
|
+
return this.cached?.expiresAt ?? null;
|
|
153
|
+
}
|
|
154
|
+
invalidate() {
|
|
155
|
+
this.cached = null;
|
|
156
|
+
}
|
|
157
|
+
async token() {
|
|
158
|
+
if (this.cached && this.cached.expiresAt - Date.now() > 6e4) return this.cached.token;
|
|
159
|
+
this.inflight ??= (async () => {
|
|
160
|
+
try {
|
|
161
|
+
const res = await this.fetchToken();
|
|
162
|
+
const token = typeof res === "string" ? res : res.token;
|
|
163
|
+
const explicitExpiry = typeof res === "object" && res.expiresAt ? Date.parse(res.expiresAt) : NaN;
|
|
164
|
+
const expiresAt = Number.isFinite(explicitExpiry) ? explicitExpiry : jwtExpiry(token) ?? Date.now() + 3e5;
|
|
165
|
+
this.cached = {
|
|
166
|
+
token,
|
|
167
|
+
expiresAt
|
|
168
|
+
};
|
|
169
|
+
return token;
|
|
170
|
+
} finally {
|
|
171
|
+
this.inflight = null;
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
return this.inflight;
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
// src/index.ts
|
|
178
|
+
function defaultIds() {
|
|
179
|
+
return { create: () => {
|
|
180
|
+
const c = globalThis.crypto;
|
|
181
|
+
if (c?.randomUUID) return c.randomUUID().replaceAll("-", "");
|
|
182
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
183
|
+
if (c?.getRandomValues) c.getRandomValues(bytes);
|
|
184
|
+
else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
185
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
186
|
+
} };
|
|
187
|
+
}
|
|
188
|
+
const conv = (id) => `/v1/conversations/${encodeURIComponent(id)}`;
|
|
189
|
+
const jitter = (ms) => ms * (.8 + Math.random() * .4);
|
|
190
|
+
function createLynkoria(opts) {
|
|
191
|
+
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
192
|
+
const doFetch = opts.fetch ?? ((...args) => fetch(...args));
|
|
193
|
+
const ids = opts.ids ?? defaultIds();
|
|
194
|
+
const tokens = new TokenSource(opts.getMessagingToken);
|
|
195
|
+
const tracker = new SequenceTracker();
|
|
196
|
+
const media = new LiveKitMediaProvider();
|
|
197
|
+
const connectionState = new Emitter();
|
|
198
|
+
const errors = new Emitter();
|
|
199
|
+
const messageEvents = new Emitter();
|
|
200
|
+
const presenceEvents = new Emitter();
|
|
201
|
+
const callEvents = new Emitter();
|
|
202
|
+
const typingEvents = new Emitter();
|
|
203
|
+
const readEvents = new Emitter();
|
|
204
|
+
const conversationEvents = new Emitter();
|
|
205
|
+
let state = "idle";
|
|
206
|
+
const setState = (s) => {
|
|
207
|
+
if (s !== state) connectionState.emit(state = s);
|
|
208
|
+
};
|
|
209
|
+
let socket = null;
|
|
210
|
+
let heartbeat = null;
|
|
211
|
+
let refreshTimer = null;
|
|
212
|
+
let retryTimer = null;
|
|
213
|
+
let retries = 0;
|
|
214
|
+
let wantConnected = false;
|
|
215
|
+
const presenceSubs = /* @__PURE__ */ new Map();
|
|
216
|
+
const resyncing = /* @__PURE__ */ new Map();
|
|
217
|
+
const resyncAgain = /* @__PURE__ */ new Set();
|
|
218
|
+
const typingSentAt = /* @__PURE__ */ new Map();
|
|
219
|
+
async function request(method, path, body, retry = true) {
|
|
220
|
+
const token = await tokens.token();
|
|
221
|
+
let res;
|
|
222
|
+
try {
|
|
223
|
+
res = await doFetch(`${base}${path}`, {
|
|
224
|
+
method,
|
|
225
|
+
headers: {
|
|
226
|
+
authorization: `Bearer ${token}`,
|
|
227
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
228
|
+
},
|
|
229
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
230
|
+
});
|
|
231
|
+
} catch (err) {
|
|
232
|
+
throw new LynkoriaError$1(ErrorCode$1.Unavailable, `Network error: ${err.message}`);
|
|
233
|
+
}
|
|
234
|
+
if (res.status === 401 && retry) {
|
|
235
|
+
tokens.invalidate();
|
|
236
|
+
return request(method, path, body, false);
|
|
237
|
+
}
|
|
238
|
+
if (res.status === 204) return void 0;
|
|
239
|
+
const text = await res.text();
|
|
240
|
+
let json = null;
|
|
241
|
+
try {
|
|
242
|
+
json = text ? JSON.parse(text) : null;
|
|
243
|
+
} catch {
|
|
244
|
+
throw new LynkoriaError$1(ErrorCode$1.Unavailable, `Invalid API response (HTTP ${res.status})`, res.status);
|
|
245
|
+
}
|
|
246
|
+
if (!res.ok) throw LynkoriaError$1.fromBody(res.status, json);
|
|
247
|
+
return json;
|
|
248
|
+
}
|
|
249
|
+
function deliver(event) {
|
|
250
|
+
const decision = tracker.decide(event.conversationId, event.seq);
|
|
251
|
+
if (decision === "apply") messageEvents.emit(event);
|
|
252
|
+
else if (decision === "gap") {
|
|
253
|
+
resyncAgain.add(event.conversationId);
|
|
254
|
+
resync(event.conversationId);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/** Fetches everything after the last applied seq and replays it in order (deduped by seq). */
|
|
258
|
+
function resync(conversationId) {
|
|
259
|
+
const existing = resyncing.get(conversationId);
|
|
260
|
+
if (existing) return existing;
|
|
261
|
+
tracker.set(conversationId, 0);
|
|
262
|
+
const run = (async () => {
|
|
263
|
+
try {
|
|
264
|
+
for (;;) {
|
|
265
|
+
resyncAgain.delete(conversationId);
|
|
266
|
+
const after = tracker.get(conversationId) ?? 0;
|
|
267
|
+
const page = await request("GET", `/v1/conversations/${encodeURIComponent(conversationId)}/messages?after_seq=${after}&limit=200`);
|
|
268
|
+
for (const ev of page.items) if (tracker.decide(conversationId, ev.seq) === "apply") messageEvents.emit(ev);
|
|
269
|
+
if (page.hasMore && tracker.get(conversationId) === after) throw new LynkoriaError$1(ErrorCode$1.Internal, "History did not advance its sequence");
|
|
270
|
+
if (!page.hasMore && !resyncAgain.has(conversationId)) break;
|
|
271
|
+
}
|
|
272
|
+
} catch (err) {
|
|
273
|
+
errors.emit(err instanceof LynkoriaError$1 ? err : new LynkoriaError$1(ErrorCode$1.Internal, String(err)));
|
|
274
|
+
} finally {
|
|
275
|
+
resyncing.delete(conversationId);
|
|
276
|
+
}
|
|
277
|
+
})();
|
|
278
|
+
resyncing.set(conversationId, run);
|
|
279
|
+
return run;
|
|
280
|
+
}
|
|
281
|
+
function scheduleRefresh() {
|
|
282
|
+
if (refreshTimer) clearTimeout(refreshTimer);
|
|
283
|
+
const exp = tokens.expiresAt();
|
|
284
|
+
if (!exp) return;
|
|
285
|
+
refreshTimer = setTimeout(() => void refreshSession(), Math.max(5e3, exp - Date.now() - 12e4));
|
|
286
|
+
}
|
|
287
|
+
async function refreshSession() {
|
|
288
|
+
if (!socket?.connected) return;
|
|
289
|
+
tokens.invalidate();
|
|
290
|
+
try {
|
|
291
|
+
const token = await tokens.token();
|
|
292
|
+
await emitAck((s) => s.timeout(1e4).emitWithAck("session:refresh", { token }));
|
|
293
|
+
scheduleRefresh();
|
|
294
|
+
} catch (err) {
|
|
295
|
+
errors.emit(err instanceof LynkoriaError$1 ? err : new LynkoriaError$1(ErrorCode$1.Unavailable, "Session refresh failed"));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function ensureSocket() {
|
|
299
|
+
if (socket) return socket;
|
|
300
|
+
const s = io(base, {
|
|
301
|
+
path: opts.socketPath ?? "/socket.io/",
|
|
302
|
+
transports: ["websocket"],
|
|
303
|
+
autoConnect: false,
|
|
304
|
+
reconnectionDelay: 1e3,
|
|
305
|
+
reconnectionDelayMax: 3e4,
|
|
306
|
+
randomizationFactor: .5,
|
|
307
|
+
auth: (cb) => {
|
|
308
|
+
(async () => {
|
|
309
|
+
let token = "";
|
|
310
|
+
try {
|
|
311
|
+
token = await tokens.token();
|
|
312
|
+
} catch {}
|
|
313
|
+
cb({ token });
|
|
314
|
+
})();
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
s.on("connect", () => {
|
|
318
|
+
retries = 0;
|
|
319
|
+
if (retryTimer) clearTimeout(retryTimer);
|
|
320
|
+
setState("connected");
|
|
321
|
+
scheduleRefresh();
|
|
322
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
323
|
+
heartbeat = setInterval(() => s.emit("presence:heartbeat"), jitter(opts.heartbeatMs ?? 25e3));
|
|
324
|
+
for (const id of tracker.conversations()) resync(id);
|
|
325
|
+
if (presenceSubs.size > 0) subscribePresence([...presenceSubs.keys()]);
|
|
326
|
+
});
|
|
327
|
+
s.on("disconnect", () => {
|
|
328
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
329
|
+
if (refreshTimer) clearTimeout(refreshTimer);
|
|
330
|
+
setState(wantConnected ? "reconnecting" : "disconnected");
|
|
331
|
+
if (wantConnected && !s.active) {
|
|
332
|
+
tokens.invalidate();
|
|
333
|
+
retryTimer = setTimeout(() => {
|
|
334
|
+
if (wantConnected) s.connect();
|
|
335
|
+
}, jitter(Math.min(3e4, 1e3 * 2 ** retries++)));
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
s.on("connect_error", (err) => {
|
|
339
|
+
setState("reconnecting");
|
|
340
|
+
tokens.invalidate();
|
|
341
|
+
errors.emit(new LynkoriaError$1(ErrorCode$1.Unauthorized, err.message));
|
|
342
|
+
if (!s.active && wantConnected) {
|
|
343
|
+
const delay = jitter(Math.min(3e4, 1e3 * 2 ** retries++));
|
|
344
|
+
if (retryTimer) clearTimeout(retryTimer);
|
|
345
|
+
retryTimer = setTimeout(() => {
|
|
346
|
+
if (wantConnected) s.connect();
|
|
347
|
+
}, delay);
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
s.on("session:expiring", () => void refreshSession());
|
|
351
|
+
for (const name of [
|
|
352
|
+
"message:created",
|
|
353
|
+
"message:updated",
|
|
354
|
+
"message:deleted",
|
|
355
|
+
"reaction:added",
|
|
356
|
+
"reaction:removed"
|
|
357
|
+
]) s.on(name, deliver);
|
|
358
|
+
s.on("presence:changed", (p) => {
|
|
359
|
+
presenceEvents.emit(p);
|
|
360
|
+
for (const cb of presenceSubs.get(p.userId) ?? []) cb(p);
|
|
361
|
+
});
|
|
362
|
+
s.on("typing:start", (e) => typingEvents.emit({
|
|
363
|
+
...e,
|
|
364
|
+
typing: true
|
|
365
|
+
}));
|
|
366
|
+
s.on("typing:stop", (e) => typingEvents.emit({
|
|
367
|
+
...e,
|
|
368
|
+
typing: false
|
|
369
|
+
}));
|
|
370
|
+
s.on("conversation:read", (e) => readEvents.emit(e));
|
|
371
|
+
s.on("conversation:updated", (e) => conversationEvents.emit(e));
|
|
372
|
+
for (const name of [
|
|
373
|
+
"call:invited",
|
|
374
|
+
"call:ringing",
|
|
375
|
+
"call:accepted",
|
|
376
|
+
"call:declined",
|
|
377
|
+
"call:ended"
|
|
378
|
+
]) s.on(name, (e) => callEvents.emit(e));
|
|
379
|
+
socket = s;
|
|
380
|
+
return s;
|
|
381
|
+
}
|
|
382
|
+
function connect() {
|
|
383
|
+
wantConnected = true;
|
|
384
|
+
const s = ensureSocket();
|
|
385
|
+
if (!s.connected && !s.active) {
|
|
386
|
+
setState(state === "idle" ? "connecting" : "reconnecting");
|
|
387
|
+
s.connect();
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function disconnect() {
|
|
391
|
+
wantConnected = false;
|
|
392
|
+
for (const t of [
|
|
393
|
+
heartbeat,
|
|
394
|
+
refreshTimer,
|
|
395
|
+
retryTimer
|
|
396
|
+
]) if (t) clearTimeout(t);
|
|
397
|
+
socket?.disconnect();
|
|
398
|
+
setState("disconnected");
|
|
399
|
+
}
|
|
400
|
+
async function emitAck(fn) {
|
|
401
|
+
const res = await fn(ensureSocket());
|
|
402
|
+
if (!res.ok) throw new LynkoriaError$1(res.error.code, res.error.message);
|
|
403
|
+
return res.data;
|
|
404
|
+
}
|
|
405
|
+
async function subscribePresence(userIds) {
|
|
406
|
+
if (!socket?.connected || userIds.length === 0) return;
|
|
407
|
+
for (let i = 0; i < userIds.length; i += 200) {
|
|
408
|
+
const batch = userIds.slice(i, i + 200);
|
|
409
|
+
try {
|
|
410
|
+
const initial = await emitAck((s) => s.timeout(1e4).emitWithAck("presence:subscribe", { userIds: batch }));
|
|
411
|
+
for (const p of initial) for (const cb of presenceSubs.get(p.userId) ?? []) cb(p);
|
|
412
|
+
} catch (err) {
|
|
413
|
+
errors.emit(err instanceof LynkoriaError$1 ? err : new LynkoriaError$1(ErrorCode$1.Unavailable, "Presence subscribe failed"));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return {
|
|
418
|
+
connect,
|
|
419
|
+
disconnect,
|
|
420
|
+
get connectionState() {
|
|
421
|
+
return state;
|
|
422
|
+
},
|
|
423
|
+
onConnectionState: (l) => connectionState.on(l),
|
|
424
|
+
onError: (l) => errors.on(l),
|
|
425
|
+
/** Every applied conversation event, in sequence order per conversation, deduplicated. */
|
|
426
|
+
onMessage: (l) => messageEvents.on(l),
|
|
427
|
+
onPresenceChange: (l) => presenceEvents.on(l),
|
|
428
|
+
onCallStateChange: (l) => callEvents.on(l),
|
|
429
|
+
onTyping: (l) => typingEvents.on(l),
|
|
430
|
+
onRead: (l) => readEvents.on(l),
|
|
431
|
+
onConversationUpdated: (l) => conversationEvents.on(l),
|
|
432
|
+
ids,
|
|
433
|
+
conversations: {
|
|
434
|
+
list: (params = {}) => {
|
|
435
|
+
const q = new URLSearchParams();
|
|
436
|
+
if (params.limit) q.set("limit", String(params.limit));
|
|
437
|
+
if (params.cursor) q.set("cursor", params.cursor);
|
|
438
|
+
return request("GET", `/v1/conversations${q.size ? `?${q}` : ""}`);
|
|
439
|
+
},
|
|
440
|
+
/** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
|
|
441
|
+
track: (conversationId, lastSeq) => tracker.set(conversationId, lastSeq),
|
|
442
|
+
untrack: (conversationId) => tracker.forget(conversationId),
|
|
443
|
+
resync
|
|
444
|
+
},
|
|
445
|
+
messages: {
|
|
446
|
+
/** Latest history page (or older, with `beforeSeq`). Also starts tracking the conversation. */
|
|
447
|
+
async history(conversationId, params = {}) {
|
|
448
|
+
const q = new URLSearchParams({ limit: String(params.limit ?? 50) });
|
|
449
|
+
q.set("before_seq", String(params.beforeSeq ?? Number.MAX_SAFE_INTEGER));
|
|
450
|
+
const page = await request("GET", `${conv(conversationId)}/messages?${q}`);
|
|
451
|
+
if (params.beforeSeq === void 0) tracker.set(conversationId, page.lastSeq);
|
|
452
|
+
return page;
|
|
453
|
+
},
|
|
454
|
+
async send(input) {
|
|
455
|
+
const body = {
|
|
456
|
+
clientMessageId: input.clientMessageId ?? ids.create(),
|
|
457
|
+
text: input.text ?? "",
|
|
458
|
+
attachmentIds: input.attachmentIds ?? [],
|
|
459
|
+
...input.parentMessageId ? { parentMessageId: input.parentMessageId } : {}
|
|
460
|
+
};
|
|
461
|
+
if (socket?.connected) try {
|
|
462
|
+
return (await emitAck((s) => s.timeout(1e4).emitWithAck("message:send", {
|
|
463
|
+
conversationId: input.conversationId,
|
|
464
|
+
...body
|
|
465
|
+
}))).message;
|
|
466
|
+
} catch (err) {
|
|
467
|
+
if (err instanceof LynkoriaError$1) throw err;
|
|
468
|
+
}
|
|
469
|
+
return (await request("POST", `${conv(input.conversationId)}/messages`, body)).message;
|
|
470
|
+
},
|
|
471
|
+
edit: (messageId, text) => request("PATCH", `/v1/messages/${encodeURIComponent(messageId)}`, { text }),
|
|
472
|
+
delete: (messageId) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}`),
|
|
473
|
+
react: (messageId, emoji) => request("POST", `/v1/messages/${encodeURIComponent(messageId)}/reactions`, { emoji }),
|
|
474
|
+
unreact: (messageId, emoji) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`),
|
|
475
|
+
markRead: (conversationId, seq) => request("POST", `${conv(conversationId)}/read`, { seq })
|
|
476
|
+
},
|
|
477
|
+
presence: {
|
|
478
|
+
/** Subscribe to one user's presence; returns an unsubscribe function. */
|
|
479
|
+
subscribe(userId, listener) {
|
|
480
|
+
let set = presenceSubs.get(userId);
|
|
481
|
+
if (!set) {
|
|
482
|
+
presenceSubs.set(userId, set = /* @__PURE__ */ new Set());
|
|
483
|
+
connect();
|
|
484
|
+
subscribePresence([userId]);
|
|
485
|
+
}
|
|
486
|
+
set.add(listener);
|
|
487
|
+
return () => {
|
|
488
|
+
const cur = presenceSubs.get(userId);
|
|
489
|
+
cur?.delete(listener);
|
|
490
|
+
if (cur && cur.size === 0) {
|
|
491
|
+
presenceSubs.delete(userId);
|
|
492
|
+
socket?.emit("presence:unsubscribe", { userIds: [userId] });
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
},
|
|
496
|
+
get: (userId) => request("GET", `/v1/presence/${encodeURIComponent(userId)}`),
|
|
497
|
+
setStatus: (status) => emitAck((s) => s.timeout(1e4).emitWithAck("presence:set-status", { status }))
|
|
498
|
+
},
|
|
499
|
+
typing: {
|
|
500
|
+
/** Throttled to one event per 3 s per conversation. */
|
|
501
|
+
start(conversationId) {
|
|
502
|
+
const last = typingSentAt.get(conversationId) ?? 0;
|
|
503
|
+
if (Date.now() - last < 3e3) return;
|
|
504
|
+
typingSentAt.set(conversationId, Date.now());
|
|
505
|
+
socket?.emit("typing:start", { conversationId });
|
|
506
|
+
},
|
|
507
|
+
stop(conversationId) {
|
|
508
|
+
typingSentAt.delete(conversationId);
|
|
509
|
+
socket?.emit("typing:stop", { conversationId });
|
|
510
|
+
}
|
|
511
|
+
},
|
|
512
|
+
attachments: {
|
|
513
|
+
/** Presigned direct upload; large files never pass through the socket server. */
|
|
514
|
+
async upload(conversationId, file, fileName) {
|
|
515
|
+
const intent = await request("POST", "/v1/attachments/upload-intent", {
|
|
516
|
+
conversationId,
|
|
517
|
+
fileName,
|
|
518
|
+
size: file.size,
|
|
519
|
+
mediaType: file.type || "application/octet-stream"
|
|
520
|
+
});
|
|
521
|
+
const put = await doFetch(intent.uploadUrl, {
|
|
522
|
+
method: "PUT",
|
|
523
|
+
headers: intent.headers,
|
|
524
|
+
body: file
|
|
525
|
+
});
|
|
526
|
+
if (!put.ok) throw new LynkoriaError$1(ErrorCode$1.BadRequest, `Upload failed with HTTP ${put.status}`, put.status);
|
|
527
|
+
return request("POST", `/v1/attachments/${encodeURIComponent(intent.attachment.id)}/complete`);
|
|
528
|
+
},
|
|
529
|
+
downloadUrl: (attachmentId) => request("GET", `/v1/attachments/${encodeURIComponent(attachmentId)}/url`)
|
|
530
|
+
},
|
|
531
|
+
calls: { join: (options) => media.join(options) },
|
|
532
|
+
/** Device push registration for native apps (React Native uses this client for messaging). */
|
|
533
|
+
push: {
|
|
534
|
+
/** Call on every FCM/APNs/PushKit token refresh; idempotent. */
|
|
535
|
+
register: (input) => request("PUT", "/v1/push/devices", {
|
|
536
|
+
platform: input.provider === "fcm" ? "android" : "ios",
|
|
537
|
+
...input
|
|
538
|
+
}),
|
|
539
|
+
/** Call on sign-out so this device stops receiving the user's pushes. */
|
|
540
|
+
unregister: (provider) => request("DELETE", `/v1/push/devices${provider ? `?provider=${provider}` : ""}`),
|
|
541
|
+
preferences: () => request("GET", "/v1/push/preferences"),
|
|
542
|
+
setPreferences: (prefs) => request("PUT", "/v1/push/preferences", prefs)
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
export { ErrorCode, LynkoriaError, SequenceTracker, createLynkoria, jwtExpiry };
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lynkoria/client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Lynkoria communications client SDK (browser, Electron, React Native)",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md",
|
|
11
|
+
"CHANGELOG.md"
|
|
12
|
+
],
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@lynkoria/contracts": "^0.1.1",
|
|
27
|
+
"livekit-client": "^2.24.0",
|
|
28
|
+
"socket.io-client": "^4.8.4"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@lynkoria/config": "0.0.0",
|
|
32
|
+
"tsdown": "^0.23.7",
|
|
33
|
+
"typescript": "^7.0.2",
|
|
34
|
+
"vitest": "^5.1.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown",
|
|
38
|
+
"dev": "tsdown --watch --no-clean",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"test": "vitest run"
|
|
41
|
+
}
|
|
6
42
|
}
|