@raucheacho/phono-web 0.0.0-stage → 0.1.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.
@@ -0,0 +1,110 @@
1
+ import { type AnnouncementFiles } from "./announcements";
2
+ import { type CallAudioSnapshot, type TalkMode } from "./audio";
3
+ import { type Phono } from "./client";
4
+ import type { AnnouncementCode, Call, PublicHandle } from "./types";
5
+ export interface PhoneCall {
6
+ call: Call;
7
+ direction: "incoming" | "outgoing";
8
+ /** Qui est en face, prêt à afficher. */
9
+ peer: string;
10
+ }
11
+ export interface PhoneState {
12
+ /** L'identité de ce téléphone, une fois `start()` fait. */
13
+ identity: PublicHandle | null;
14
+ ready: boolean;
15
+ /** Les appels qui sonnent ici et attendent qu'on décroche. */
16
+ ringing: PhoneCall[];
17
+ /** L'appel en cours : il sonne chez l'autre, ou on parle. */
18
+ current: PhoneCall | null;
19
+ /** Le dernier appel terminé, pour afficher « Appel terminé ». */
20
+ ended: PhoneCall | null;
21
+ audio: CallAudioSnapshot | null;
22
+ mode: TalkMode;
23
+ error: string | null;
24
+ /**
25
+ * L'appel n'a pas abouti : l'annonce d'opérateur en cours (`busy`,
26
+ * `unavailable`, `not_assigned`), le temps qu'elle se joue. Votre écran
27
+ * peut l'afficher (« Occupé »), même avec `announcements: false`.
28
+ */
29
+ announcement: AnnouncementCode | null;
30
+ }
31
+ export interface PhoneOptions {
32
+ /** « open » : micro ouvert, comme un téléphone (défaut). « ptt » : appuyer pour parler. */
33
+ mode?: TalkMode;
34
+ /** Jouer la sonnerie et la tonalité de retour. Vrai par défaut. */
35
+ tones?: boolean;
36
+ /** Faire clignoter le titre de l'onglet pendant qu'un appel sonne. Vrai par défaut. */
37
+ titleAlert?: boolean;
38
+ /**
39
+ * Les annonces d'opérateur quand un appel n'aboutit pas. Vrai par défaut :
40
+ * celles de votre organisation, sinon celles de Phono. Vos propres fichiers
41
+ * par code (`{ busy: "/sons/occupe.mp3" }`) ; `false` pour n'en jouer aucune.
42
+ */
43
+ announcements?: boolean | AnnouncementFiles;
44
+ }
45
+ type Listener = (state: PhoneState) => void;
46
+ /**
47
+ * Un téléphone dans le navigateur, au nom d'une identité : il sonne, appelle,
48
+ * décroche, parle.
49
+ *
50
+ * ```ts
51
+ * const phone = phono.phone();
52
+ * phone.subscribe((s) => render(s));
53
+ * await phone.start();
54
+ * button.onclick = () => phone.dial("jean.acme");
55
+ * ```
56
+ *
57
+ * `dial()` et `answer()` doivent venir d'un geste (un clic) : c'est ce qui
58
+ * autorise le navigateur à jouer du son et à demander le micro.
59
+ */
60
+ export declare class Phone {
61
+ readonly phono: Phono;
62
+ private readonly options;
63
+ private state;
64
+ private listeners;
65
+ private audio;
66
+ private unsubscribers;
67
+ private stopTone;
68
+ private toneKind;
69
+ private stopTitle;
70
+ private starting;
71
+ private announcementUrls;
72
+ private stopAnnouncement;
73
+ constructor(phono: Phono, options?: PhoneOptions);
74
+ getState(): PhoneState;
75
+ subscribe(listener: Listener): () => void;
76
+ /** Charge l'identité, écoute les sonneries, et reprend un appel qui sonnait déjà. */
77
+ start(): Promise<void>;
78
+ /** Appeler une identité (`jean.acme`). */
79
+ dial(to: string): Promise<void>;
80
+ /** Décrocher. Sans argument : le premier appel qui sonne. */
81
+ answer(callId?: string): Promise<void>;
82
+ /** Refuser. Sans argument : le premier appel qui sonne. */
83
+ reject(callId?: string): Promise<void>;
84
+ /** Raccrocher — ou annuler un appel qui sonne encore chez l'autre. */
85
+ hangup(): Promise<void>;
86
+ setMuted(muted: boolean): void;
87
+ setMode(mode: TalkMode): void;
88
+ /** Appuyer pour parler (mode « ptt »). */
89
+ press(): void;
90
+ release(): void;
91
+ clearError(): void;
92
+ /** Couper l'annonce d'opérateur en cours. */
93
+ endAnnouncement(): void;
94
+ /** Coupe tout : l'appel en cours, l'écoute, les sonneries. */
95
+ destroy(): void;
96
+ private onEvent;
97
+ /** Joue l'annonce : votre fichier, sinon celle de l'organisation. */
98
+ private announce;
99
+ private joinAudio;
100
+ private endAudio;
101
+ private mine;
102
+ private describe;
103
+ private addRinging;
104
+ private removeRinging;
105
+ private fail;
106
+ private set;
107
+ /** Sonnerie, tonalité de retour et titre suivent l'état. */
108
+ private syncAlerts;
109
+ }
110
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { Phono } from "./client";
2
+ import type { Phone, PhoneState } from "./phone";
3
+ import type { EventType, PhonoEvent } from "./types";
4
+ /**
5
+ * L'état d'un téléphone, qui se met à jour tout seul.
6
+ *
7
+ * ```tsx
8
+ * const { ringing, current } = usePhone(phone);
9
+ * ```
10
+ */
11
+ export declare function usePhone(phone: Phone): PhoneState;
12
+ /** Un événement temps réel, tant que le composant est monté. */
13
+ export declare function usePhonoEvent<T = unknown>(phono: Phono | null, type: EventType | "*", handler: (event: PhonoEvent<T>) => void): void;
package/dist/react.js ADDED
@@ -0,0 +1,18 @@
1
+ // src/react.ts
2
+ import { useEffect, useRef, useSyncExternalStore } from "react";
3
+ function usePhone(phone) {
4
+ return useSyncExternalStore((cb) => phone.subscribe(cb), () => phone.getState(), () => phone.getState());
5
+ }
6
+ function usePhonoEvent(phono, type, handler) {
7
+ const ref = useRef(handler);
8
+ ref.current = handler;
9
+ useEffect(() => {
10
+ if (!phono)
11
+ return;
12
+ return phono.realtime().on(type, (ev) => ref.current(ev));
13
+ }, [phono, type]);
14
+ }
15
+ export {
16
+ usePhonoEvent,
17
+ usePhone
18
+ };
@@ -0,0 +1,39 @@
1
+ import type { Phono } from "./client";
2
+ import type { EventType, PhonoEvent } from "./types";
3
+ export type RealtimeStatus = "connecting" | "connected" | "reconnecting" | "closed";
4
+ /**
5
+ * Les événements d'une identité, en direct : sa boîte de réception Konet.
6
+ *
7
+ * ```ts
8
+ * phono.realtime().on("message.created", (ev) => console.log(ev.data));
9
+ * ```
10
+ *
11
+ * La connexion s'ouvre au premier `on()`. Son jeton est renouvelé avant
12
+ * d'expirer ; si elle est perdue pour de bon (réseau coupé longtemps), un
13
+ * nouveau jeton est demandé et elle repart.
14
+ */
15
+ export declare class Realtime {
16
+ private readonly phono;
17
+ private handlers;
18
+ private statusHandlers;
19
+ private client;
20
+ private opening;
21
+ private closed;
22
+ private retryTimer;
23
+ private renewTimer;
24
+ status: RealtimeStatus;
25
+ constructor(phono: Phono);
26
+ /** `type` : un type d'événement, ou `*` pour tous. Rend de quoi se désabonner. */
27
+ on<T = unknown>(type: EventType | "*", handler: (event: PhonoEvent<T>) => void): () => void;
28
+ onStatus(handler: (s: RealtimeStatus) => void): () => void;
29
+ /** Attend que la boîte soit rejointe. */
30
+ ready(): Promise<void>;
31
+ /** À appeler quand l'onglet revient au premier plan : vérifie la connexion. */
32
+ check(): void;
33
+ close(): void;
34
+ private open;
35
+ private connect;
36
+ private scheduleRetry;
37
+ private dispatch;
38
+ private setStatus;
39
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Le talkie dans le navigateur : un canal où l'on parle à tour de rôle.
3
+ *
4
+ * Repris de la console de dispatch de Livro (apps/dispatch/src/lib/ptt.ts),
5
+ * qui le fait tourner sur le terrain : le même fil que les téléphones — des
6
+ * trames Opus sur un sujet Konet, une voix à la fois, arbitrée par le serveur
7
+ * (le « floor ») — et les mêmes worklets de goul-audio pour capter, encoder,
8
+ * décoder et lisser la lecture. Ce fichier n'orchestre que le reste : les
9
+ * permissions, le canal, le floor, et l'état dont une interface a besoin.
10
+ *
11
+ * ```ts
12
+ * const talkie = phono.talkie(channelId);
13
+ * talkie.subscribe(({ state, holder }) => render(state, holder));
14
+ * await talkie.start(); // on entend le canal
15
+ * button.onpointerdown = () => talkie.press(); // on parle
16
+ * button.onpointerup = () => talkie.release();
17
+ * ```
18
+ */
19
+ import type { AudioAssets, Phono } from "./client";
20
+ export type TalkieState = "idle" | "connecting"
21
+ /** Canal rejoint : on entend. Le micro est une autre affaire (micReady). */
22
+ | "ready"
23
+ /** On tient le canal et on parle. */
24
+ | "transmitting"
25
+ /** Quelqu'un d'autre parle. */
26
+ | "listening" | "denied" | "error";
27
+ export interface TalkieSnapshot {
28
+ state: TalkieState;
29
+ /** L'id de l'identifiant qui tient le canal, ou null. */
30
+ holder: string | null;
31
+ /** Vrai quand la voix d'en face arrive vraiment (pas seulement le floor). */
32
+ remoteSpeaking: boolean;
33
+ /** Faux tant que le micro n'est pas accordé et branché. */
34
+ micReady: boolean;
35
+ /** Les identifiants (ids) à l'écoute du canal en ce moment, soi compris. */
36
+ online: string[];
37
+ error: string | null;
38
+ }
39
+ type Listener = (snapshot: TalkieSnapshot) => void;
40
+ export declare class Talkie {
41
+ private readonly phono;
42
+ readonly channelId: string;
43
+ private readonly assets;
44
+ private listeners;
45
+ private snapshot;
46
+ private client;
47
+ private channel;
48
+ private context;
49
+ private micStream;
50
+ private capture;
51
+ private playback;
52
+ private wasmBytes;
53
+ private speakingTimer;
54
+ private renewTimer;
55
+ private stopped;
56
+ constructor(phono: Phono, channelId: string, assets?: AudioAssets);
57
+ subscribe(listener: Listener): () => void;
58
+ get state(): TalkieSnapshot;
59
+ /**
60
+ * Rejoint le canal et commence à écouter. Le micro n'est **pas** sur ce
61
+ * chemin : écouter ne demande aucune permission, et ne doit pas attendre
62
+ * qu'on réponde à une question du navigateur. Il est demandé au premier
63
+ * appui — un geste, le seul moment où le navigateur l'affiche à coup sûr —
64
+ * ou tout de suite s'il est déjà accordé.
65
+ */
66
+ start(): Promise<void>;
67
+ private reconnect;
68
+ private prepareMicIfAlreadyGranted;
69
+ /** Appuyer : prend le canal et commence à émettre. */
70
+ press(): Promise<void>;
71
+ /** Relâcher : rend le canal. */
72
+ release(): Promise<void>;
73
+ /** Quitte le canal et coupe tout. */
74
+ stop(): void;
75
+ private buildPlayback;
76
+ private ensureCapture;
77
+ private initWorklet;
78
+ private sendFrame;
79
+ private markRemoteSpeaking;
80
+ private onFloorChanged;
81
+ private isPermissionDenied;
82
+ private describe;
83
+ private emit;
84
+ }
85
+ export {};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Les sonneries, en WebAudio : rien à télécharger.
3
+ *
4
+ * Un navigateur ne joue pas de son tant que la page n'a pas reçu de geste.
5
+ * La sonnerie d'un appel entrant peut donc rester muette ; `titleAlert` fait
6
+ * clignoter le titre de l'onglet, qui se voit toujours.
7
+ */
8
+ type Stop = () => void;
9
+ /** Deux bips toutes les deux secondes. */
10
+ export declare function ringtone(): Stop;
11
+ /** La tonalité de retour : 440 Hz, 1,5 s toutes les 5 s, comme en France. */
12
+ export declare function ringback(): Stop;
13
+ export declare function titleAlert(text: string): Stop;
14
+ export {};
@@ -0,0 +1,284 @@
1
+ export type IdentityKind = "human" | "agent" | "guest";
2
+ export interface PublicHandle {
3
+ id: string;
4
+ handle: string;
5
+ display_name: string;
6
+ kind: IdentityKind;
7
+ /** La photo de profil, s'il y en a une : GET /v1/avatars/{avatar_id}, sans jeton. */
8
+ avatar_id?: string;
9
+ }
10
+ /** `GET /v1/me` : l'identité, et son organisation. */
11
+ export interface Me {
12
+ handle: PublicHandle;
13
+ /** `kind` : « company » (transcription comprise) ou « personal ». */
14
+ org: {
15
+ id: string;
16
+ slug: string;
17
+ name?: string;
18
+ kind?: "company" | "personal";
19
+ record_calls: boolean;
20
+ };
21
+ }
22
+ export type ParticipantState = "invited" | "joined" | "left" | "declined" | "missed";
23
+ export interface Participant {
24
+ handle: PublicHandle;
25
+ state: ParticipantState;
26
+ recording_media_id?: string;
27
+ joined_at?: string;
28
+ left_at?: string;
29
+ }
30
+ export interface TranscriptLine {
31
+ speaker: string;
32
+ handle_id: string;
33
+ start_ms: number;
34
+ end_ms: number;
35
+ text: string;
36
+ }
37
+ export interface Call {
38
+ id: string;
39
+ initiated_by: PublicHandle;
40
+ status: "ringing" | "active" | "ended";
41
+ end_reason?: "completed" | "declined" | "missed" | "cancelled";
42
+ recorded: boolean;
43
+ transcript?: TranscriptLine[];
44
+ created_at: string;
45
+ answered_at?: string;
46
+ ended_at?: string;
47
+ participants: Participant[];
48
+ }
49
+ /** Ce qu'il faut pour rejoindre l'audio d'un appel. */
50
+ export interface AudioCredentials {
51
+ url: string;
52
+ token: string;
53
+ topic: string;
54
+ binary_mode: "multiplex";
55
+ event: string;
56
+ }
57
+ /** La réponse des routes qui créent ou décrochent un appel. */
58
+ export interface CallEnvelope {
59
+ call: Call;
60
+ audio?: AudioCredentials;
61
+ }
62
+ export interface Message {
63
+ id: string;
64
+ conversation_id: string;
65
+ sender_id: string;
66
+ kind: "text" | "voice" | "image" | "file" | "location" | "system";
67
+ body: string;
68
+ media_id?: string;
69
+ duration_ms?: number;
70
+ transcript?: string;
71
+ created_at: string;
72
+ read_at?: string;
73
+ /** Les réactions, une par personne. */
74
+ reactions?: Reaction[];
75
+ /** La forme d'onde d'un vocal : des niveaux de 0 à 100. */
76
+ waveform?: number[];
77
+ /** Le message auquel celui-ci répond, en résumé. */
78
+ reply_to?: MessageRef;
79
+ /** Une image ou un fichier (GET /v1/media/{media_id}). */
80
+ attachment?: Attachment;
81
+ /** Une position partagée. */
82
+ location?: Location;
83
+ delivered_at?: string;
84
+ edited_at?: string;
85
+ /** Supprimé pour tout le monde : il n'en reste que l'auteur et la date. */
86
+ deleted_at?: string;
87
+ /** Il passe la sourdine et réveille le téléphone. */
88
+ urgent?: boolean;
89
+ }
90
+ export interface MessageRef {
91
+ id: string;
92
+ sender_id: string;
93
+ kind: Message["kind"];
94
+ body: string;
95
+ deleted?: boolean;
96
+ }
97
+ export interface Attachment {
98
+ content_type: string;
99
+ filename?: string;
100
+ size_bytes: number;
101
+ width?: number;
102
+ height?: number;
103
+ }
104
+ export interface Location {
105
+ lat: number;
106
+ lng: number;
107
+ label?: string;
108
+ }
109
+ export interface GroupRef {
110
+ id: string;
111
+ title: string;
112
+ }
113
+ export interface Group extends GroupRef {
114
+ members: (PublicHandle & {
115
+ role: "admin" | "member";
116
+ joined_at: string;
117
+ })[];
118
+ created_at: string;
119
+ }
120
+ export interface SearchHit {
121
+ message: Message;
122
+ peer?: PublicHandle;
123
+ group?: GroupRef;
124
+ }
125
+ export interface Transfer {
126
+ id: string;
127
+ conversation_id: string;
128
+ from: PublicHandle;
129
+ to: PublicHandle;
130
+ peer: PublicHandle;
131
+ note?: string;
132
+ created_at: string;
133
+ }
134
+ /** La réponse d'absence. `hours.days` : {"1": ["09:00", "18:00"]}, 1 = lundi. */
135
+ export interface Away {
136
+ message: string;
137
+ always?: boolean;
138
+ hours?: {
139
+ tz: string;
140
+ days: Record<string, [string, string]>;
141
+ };
142
+ }
143
+ /** Un emoji posé sur un message. */
144
+ export interface Reaction {
145
+ handle_id: string;
146
+ emoji: string;
147
+ }
148
+ /** Ce que l'on fait dans une conversation (événement `conversation.activity`). */
149
+ export type Activity = "typing" | "recording" | "idle";
150
+ /** `message.reacted` : `emoji` vide, la réaction de `reactor` a été retirée. */
151
+ export interface ReactionEventData {
152
+ message_id: string;
153
+ conversation_id: string;
154
+ reactor: PublicHandle;
155
+ emoji: string;
156
+ reactions: Reaction[];
157
+ }
158
+ /** `conversation.activity` : sans nouvelle après quelques secondes, considérez que c'est fini. */
159
+ export interface ActivityEventData {
160
+ from: PublicHandle;
161
+ state: Activity;
162
+ }
163
+ export interface Conversation {
164
+ id: string;
165
+ /** « direct » (`peer`) ou « group » (`group`). */
166
+ kind?: "direct" | "group";
167
+ peer?: PublicHandle;
168
+ group?: GroupRef;
169
+ last_message?: Message;
170
+ unread: number;
171
+ last_message_at: string;
172
+ muted_until?: string;
173
+ archived?: boolean;
174
+ }
175
+ /** `GET /v1/contacts` : l'équipe, les contacts établis hors de l'organisation,
176
+ * et les gens avec qui on a parlé récemment. */
177
+ export interface Contacts {
178
+ team: Contact[];
179
+ contacts: Contact[];
180
+ recent: Contact[];
181
+ }
182
+ /**
183
+ * Ce qu'est un identifiant pour vous. Hors de son organisation, on n'écrit et
184
+ * on n'appelle qu'un `contact` : une demande, que l'autre accepte.
185
+ */
186
+ export type Relation = "team" | "contact" | "outgoing" | "incoming" | "blocked" | "none";
187
+ /** `GET /v1/handles/{handle}` : l'identifiant, et votre relation avec lui. */
188
+ export interface LookedUpHandle extends PublicHandle {
189
+ relation: Relation;
190
+ }
191
+ /** Une demande de contact, reçue ou envoyée — ou un identifiant bloqué. */
192
+ export interface ContactRequest extends PublicHandle {
193
+ note?: string;
194
+ created_at: string;
195
+ }
196
+ export interface ContactRequests {
197
+ incoming: ContactRequest[];
198
+ outgoing: ContactRequest[];
199
+ }
200
+ /** `contact.requested` (from, note) et `contact.accepted` (by). */
201
+ export interface ContactEventData {
202
+ from?: PublicHandle;
203
+ by?: PublicHandle;
204
+ note?: string | null;
205
+ recipient: PublicHandle;
206
+ }
207
+ export interface Contact extends PublicHandle {
208
+ /** Le dernier échange, pour les contacts récents. */
209
+ last_at?: string;
210
+ }
211
+ /** L'enveloppe d'un événement : temps réel et webhooks. */
212
+ export interface PhonoEvent<T = unknown> {
213
+ id: string;
214
+ type: EventType;
215
+ created_at: string;
216
+ data: T;
217
+ }
218
+ export interface MessageEventData {
219
+ message: Message;
220
+ sender: PublicHandle;
221
+ recipient: PublicHandle;
222
+ }
223
+ export type EventType = "message.created" | "message.transcribed" | "message.read" | "message.reacted" | "conversation.activity" | "message.updated" | "message.deleted" | "message.delivered" | "conversation.transferred" | "group.updated" | "call.ringing" | "call.updated" | "call.answered" | "call.ended" | "call.transcribed" | "contact.requested" | "contact.accepted" | "channel.updated" | "channel.deleted" | "channel.floor" | "channel.invited" | "transmission.created" | "transmission.transcribed" | (string & {});
224
+ export interface ChannelMember extends PublicHandle {
225
+ role: "admin" | "member";
226
+ /** « invited » tant que l'invitation n'est pas acceptée : il n'entend rien. */
227
+ status: "invited" | "active";
228
+ joined_at: string;
229
+ }
230
+ /**
231
+ * Un canal fermé, où l'on parle à tour de rôle. Celui d'une entreprise réunit
232
+ * son équipe ; celui d'un compte personnel, des contacts qui ont accepté son
233
+ * invitation (12 au plus).
234
+ */
235
+ export interface Channel {
236
+ id: string;
237
+ name: string;
238
+ personal: boolean;
239
+ max_members: number;
240
+ record: boolean;
241
+ created_at: string;
242
+ members: ChannelMember[];
243
+ last_transmission?: Transmission;
244
+ }
245
+ /** Une prise de parole : de la prise du canal à sa remise. */
246
+ export interface Transmission {
247
+ id: string;
248
+ channel_id: string;
249
+ speaker?: PublicHandle;
250
+ media_id?: string;
251
+ duration_ms: number;
252
+ gaps: number;
253
+ transcript?: string;
254
+ /** La forme de la voix, comme pour un vocal. */
255
+ waveform?: number[];
256
+ started_at: string;
257
+ ended_at: string;
258
+ }
259
+ /** De quoi rejoindre un canal sur Konet. */
260
+ export interface ChannelAudioCredentials {
261
+ url: string;
262
+ token: string;
263
+ topic: string;
264
+ binary_mode: "exclusive";
265
+ event: string;
266
+ expires_at: string;
267
+ }
268
+ /**
269
+ * Une annonce d'opérateur, jouée chez l'appelant quand un appel n'aboutit pas :
270
+ * - `busy` : « votre correspondant est actuellement en ligne » ;
271
+ * - `unavailable` : « … n'est pas disponible » (pas de réponse, refusé, pas en contact) ;
272
+ * - `not_assigned` : « l'identifiant Phono que vous avez demandé n'est pas attribué ».
273
+ */
274
+ export type AnnouncementCode = "busy" | "unavailable" | "not_assigned";
275
+ export interface Announcement {
276
+ code: AnnouncementCode;
277
+ lang: string;
278
+ /** Un Ogg Opus public : celui de votre organisation, ou celui de Phono. */
279
+ url: string;
280
+ }
281
+ export interface Announcements {
282
+ lang: string;
283
+ announcements: Record<AnnouncementCode, Announcement>;
284
+ }
package/dist/types.js ADDED
File without changes
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@raucheacho/phono-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Appels, messages et vocaux Phono dans le navigateur.",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./react": {
14
+ "types": "./dist/react.d.ts",
15
+ "default": "./dist/react.js"
16
+ },
17
+ "./assets/*": "./assets/*",
18
+ "./types": {
19
+ "types": "./dist/types.d.ts",
20
+ "default": "./dist/types.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "src",
25
+ "dist",
26
+ "assets"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "build": "node scripts/goul-assets.mjs && rm -rf dist && bun build src/index.ts src/react.ts src/types.ts --outdir dist --target browser --format esm --splitting --packages external && tsc -p tsconfig.build.json --emitDeclarationOnly",
33
+ "check-types": "tsc --noEmit",
34
+ "test": "bun test",
35
+ "goul-assets": "node scripts/goul-assets.mjs",
36
+ "prepack": "node scripts/goul-assets.mjs",
37
+ "release": "bun run build && node scripts/publish.mjs"
38
+ },
39
+ "dependencies": {
40
+ "@raucheacho/goul-audio-web": "^1.0.1",
41
+ "@raucheacho/konet-js": "^0.6.1"
42
+ },
43
+ "peerDependencies": {
44
+ "react": ">=18"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "react": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "devDependencies": {
52
+ "@types/react": "19.2.2",
53
+ "typescript": "5.9.2"
54
+ }
55
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Les annonces d'opérateur : « votre correspondant est actuellement en
3
+ * ligne », « … n'est pas disponible », « l'identifiant Phono que vous avez
4
+ * demandé n'est pas attribué ».
5
+ *
6
+ * Ce sont des fichiers : ceux de Phono, ceux que votre organisation a déposés
7
+ * dans le dashboard, ou les vôtres (`new Phone(phono, { announcements: { busy: "/occupe.mp3" } })`).
8
+ */
9
+
10
+ import type { AnnouncementCode, Call } from "./types";
11
+
12
+ /** Vos fichiers, par code : une URL que le navigateur sait lire. */
13
+ export type AnnouncementFiles = Partial<Record<AnnouncementCode, string>>;
14
+
15
+ /** L'annonce d'un appel qui s'est terminé sans avoir eu lieu, ou null. */
16
+ export function announcementForEnd(call: Call): AnnouncementCode | null {
17
+ if (call.answered_at) return null;
18
+ return call.end_reason === "missed" || call.end_reason === "declined" ? "unavailable" : null;
19
+ }
20
+
21
+ /** L'annonce d'une erreur de `calls.create`, ou null. */
22
+ export function announcementForError(code: string): AnnouncementCode | null {
23
+ switch (code) {
24
+ case "busy":
25
+ return "busy";
26
+ case "handle_not_found":
27
+ return "not_assigned";
28
+ case "contact_required":
29
+ case "unavailable":
30
+ return "unavailable";
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /**
36
+ * Joue un fichier une fois. `done` se résout à la fin, ou à l'arrêt ; un
37
+ * navigateur qui refuse de jouer (pas de geste, format illisible) se tait.
38
+ */
39
+ export function playAnnouncement(url: string): { done: Promise<void>; stop: () => void } {
40
+ if (typeof Audio === "undefined") return { done: Promise.resolve(), stop: () => {} };
41
+ const audio = new Audio(url);
42
+ let finish = () => {};
43
+ const done = new Promise<void>((resolve) => {
44
+ finish = resolve;
45
+ audio.onended = () => resolve();
46
+ audio.onerror = () => resolve();
47
+ });
48
+ audio.play().catch(() => finish());
49
+ return {
50
+ done,
51
+ stop: () => {
52
+ audio.pause();
53
+ audio.removeAttribute("src");
54
+ finish();
55
+ },
56
+ };
57
+ }