@zapiack/react-native 0.1.0 → 0.2.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,371 @@
1
+ // src/realtime.ts
2
+ var ZapiackRealtimeError = class extends Error {
3
+ constructor(message, code = 0, reason) {
4
+ super(message);
5
+ this.code = code;
6
+ this.reason = reason;
7
+ this.name = "ZapiackRealtimeError";
8
+ }
9
+ };
10
+ var DEFAULT_REALTIME_URL = "wss://rt.zapiack.com";
11
+ var OPEN = 1;
12
+ var MAX_OUTBOX = 100;
13
+ var browserRealtimeEnv = () => ({
14
+ socket: (url) => new globalThis.WebSocket(url),
15
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
16
+ clearTimeout: (id) => clearTimeout(id),
17
+ setInterval: (fn, ms) => setInterval(fn, ms),
18
+ clearInterval: (id) => clearInterval(id),
19
+ random: () => Math.random()
20
+ });
21
+ var after = (a, b) => {
22
+ if (!b) return true;
23
+ const [am = 0, as = 0] = a.split("-").map(Number);
24
+ const [bm = 0, bs = 0] = b.split("-").map(Number);
25
+ return am > bm || am === bm && as > bs;
26
+ };
27
+ var ZapiackRealtime = class {
28
+ constructor(options, env = browserRealtimeEnv(), now = Date.now) {
29
+ this.env = env;
30
+ this.now = now;
31
+ this.ws = null;
32
+ this._state = "idle";
33
+ this.subs = /* @__PURE__ */ new Map();
34
+ this.presenceHandlers = /* @__PURE__ */ new Map();
35
+ this.members = /* @__PURE__ */ new Map();
36
+ this.waiting = /* @__PURE__ */ new Map();
37
+ this.pending = /* @__PURE__ */ new Map();
38
+ this.rpcSeq = 0;
39
+ this.stateHandlers = /* @__PURE__ */ new Set();
40
+ this.errorHandlers = /* @__PURE__ */ new Set();
41
+ this.outbox = [];
42
+ this.attempt = 0;
43
+ this.wanted = false;
44
+ this.heard = 0;
45
+ this.ackSeq = 0;
46
+ this.first = null;
47
+ /** Set by an error the server marks fatal, for runtimes that cannot see a custom close code. */
48
+ this.refused = false;
49
+ this._connId = null;
50
+ if (typeof options?.getToken !== "function") throw new ZapiackRealtimeError("getToken is required: a function that asks your server for a token.");
51
+ this.o = { url: DEFAULT_REALTIME_URL, heartbeatMs: 25e3, backoffMs: { min: 1e3, max: 3e4 }, ackTimeoutMs: 1e4, ...options };
52
+ }
53
+ get state() {
54
+ return this._state;
55
+ }
56
+ /** This connection's id, once connected. Other members use it to signal you. */
57
+ get connectionId() {
58
+ return this._connId;
59
+ }
60
+ onState(fn) {
61
+ this.stateHandlers.add(fn);
62
+ return () => this.stateHandlers.delete(fn);
63
+ }
64
+ onError(fn) {
65
+ this.errorHandlers.add(fn);
66
+ return () => this.errorHandlers.delete(fn);
67
+ }
68
+ /** Connects and resolves once the server has said hello. It keeps itself connected afterwards until `disconnect()`. */
69
+ connect() {
70
+ if (this._state === "connected") return Promise.resolve();
71
+ if (this.first) return new Promise((resolve, reject) => this.chain(resolve, reject));
72
+ this.wanted = true;
73
+ return new Promise((resolve, reject) => {
74
+ this.first = { resolve, reject };
75
+ void this.open();
76
+ });
77
+ }
78
+ chain(resolve, reject) {
79
+ const f = this.first;
80
+ this.first = {
81
+ resolve: () => {
82
+ f.resolve();
83
+ resolve();
84
+ },
85
+ reject: (e) => {
86
+ f.reject(e);
87
+ reject(e);
88
+ }
89
+ };
90
+ }
91
+ /** Leaves for good: closes the socket, forgets the pending sends. Subscriptions stay, for a later `connect()`. */
92
+ disconnect() {
93
+ this.wanted = false;
94
+ this.env.clearTimeout(this.retry);
95
+ this.stopBeat();
96
+ const ws = this.ws;
97
+ this.ws = null;
98
+ ws?.close(1e3, "bye");
99
+ this.failAll(new ZapiackRealtimeError("Disconnected."));
100
+ this.outbox = [];
101
+ this.set("closed");
102
+ }
103
+ /** Calls `handler` for every message on the channel, now and after reconnects. Returns how to stop. */
104
+ subscribe(channel, handler, options = {}) {
105
+ let sub = this.subs.get(channel);
106
+ const fresh = !sub;
107
+ if (!sub) this.subs.set(channel, sub = { handlers: /* @__PURE__ */ new Set(), cursor: options.resumeFrom });
108
+ sub.handlers.add(handler);
109
+ if (fresh) this.send({ op: "subscribe", channel, resumeFrom: sub.cursor });
110
+ return () => {
111
+ const s = this.subs.get(channel);
112
+ if (!s) return;
113
+ s.handlers.delete(handler);
114
+ if (s.handlers.size === 0) {
115
+ this.subs.delete(channel);
116
+ this.presenceHandlers.delete(channel);
117
+ this.members.delete(channel);
118
+ this.send({ op: "unsubscribe", channel });
119
+ }
120
+ };
121
+ }
122
+ /** Sends a message. Resolves when the server confirms, unless `ack: false`. */
123
+ publish(channel, data, options = {}) {
124
+ const frame = { op: "publish", channel, event: options.event ?? "message", data, persist: options.persist === true };
125
+ if (options.ack === false) {
126
+ this.send(frame);
127
+ return Promise.resolve();
128
+ }
129
+ const ackId = `a${++this.ackSeq}`;
130
+ frame["ackId"] = ackId;
131
+ return new Promise((resolve, reject) => {
132
+ const timer = this.env.setTimeout(() => {
133
+ this.waiting.delete(ackId);
134
+ reject(new ZapiackRealtimeError("The server did not confirm in time.", 0));
135
+ }, this.o.ackTimeoutMs);
136
+ this.waiting.set(ackId, { resolve, reject, timer });
137
+ if (!this.send(frame)) {
138
+ this.settle(ackId)?.reject(new ZapiackRealtimeError("Could not send: too many messages waiting for a connection.", 429));
139
+ }
140
+ });
141
+ }
142
+ /**
143
+ * Asks a Zapiack service something over this connection and waits for the answer: the way a call client talks to the media server.
144
+ * Needs a token minted for a call. It is never queued for later: if the line is down it fails at once, because an answer to an old
145
+ * question is worse than none.
146
+ */
147
+ request(method, data = {}) {
148
+ if (!this.ws || this.ws.readyState !== OPEN || this._state !== "connected") return Promise.reject(new ZapiackRealtimeError("Not connected.", 0, "no_route"));
149
+ const correlationId = `r${++this.rpcSeq}`;
150
+ return new Promise((resolve, reject) => {
151
+ const timer = this.env.setTimeout(() => {
152
+ this.pending.delete(correlationId);
153
+ reject(new ZapiackRealtimeError("The server did not answer in time.", 0, "timeout"));
154
+ }, this.o.ackTimeoutMs + 2e3);
155
+ this.pending.set(correlationId, { resolve, reject, timer });
156
+ this.ws.send(JSON.stringify({ op: "rpc", method, correlationId, data }));
157
+ });
158
+ }
159
+ /** Sends to one connection in a channel you are subscribed to. Used for peer-to-peer setup such as WebRTC. */
160
+ signal(channel, to, event, data) {
161
+ this.send({ op: "signal", channel, to, event, data });
162
+ }
163
+ /** Presence in a channel you are subscribed to. */
164
+ presence(channel) {
165
+ return {
166
+ enter: (data = null) => this.send({ op: "presence.enter", channel, data }),
167
+ update: (data) => this.send({ op: "presence.update", channel, data }),
168
+ leave: () => this.send({ op: "presence.leave", channel }),
169
+ /** Who is here now, as last told. */
170
+ members: () => [...this.members.get(channel)?.values() ?? []],
171
+ onChange: (fn) => {
172
+ let set = this.presenceHandlers.get(channel);
173
+ if (!set) this.presenceHandlers.set(channel, set = /* @__PURE__ */ new Set());
174
+ set.add(fn);
175
+ return () => set.delete(fn);
176
+ }
177
+ };
178
+ }
179
+ // ───────────────────────────── internals
180
+ set(s) {
181
+ if (this._state === s) return;
182
+ this._state = s;
183
+ for (const fn of this.stateHandlers) fn(s);
184
+ }
185
+ fail(e) {
186
+ for (const fn of this.errorHandlers) fn(e);
187
+ }
188
+ settle(ackId) {
189
+ const w = this.waiting.get(ackId);
190
+ if (!w) return void 0;
191
+ this.waiting.delete(ackId);
192
+ this.env.clearTimeout(w.timer);
193
+ return w;
194
+ }
195
+ failAll(e) {
196
+ for (const id of [...this.waiting.keys()]) this.settle(id)?.reject(e);
197
+ this.failRequests(e);
198
+ }
199
+ failRequests(e) {
200
+ for (const [id, p] of [...this.pending]) {
201
+ this.pending.delete(id);
202
+ this.env.clearTimeout(p.timer);
203
+ p.reject(e);
204
+ }
205
+ }
206
+ /** Writes now if the line is open, otherwise keeps it (a short while) for when it is. False when there is no room. */
207
+ send(frame) {
208
+ const text = JSON.stringify(frame);
209
+ if (this.ws && this.ws.readyState === OPEN && this._state === "connected") {
210
+ this.ws.send(text);
211
+ return true;
212
+ }
213
+ if (frame["op"] === "subscribe" || frame["op"] === "unsubscribe") return true;
214
+ if (this.outbox.length >= MAX_OUTBOX) return false;
215
+ this.outbox.push(text);
216
+ return true;
217
+ }
218
+ async open() {
219
+ if (!this.wanted) return;
220
+ this.set(this.attempt === 0 && this._state !== "reconnecting" ? "connecting" : "reconnecting");
221
+ let token;
222
+ try {
223
+ token = await this.o.getToken();
224
+ if (!token || typeof token !== "string") throw new Error("getToken returned no token.");
225
+ } catch (e) {
226
+ this.fail(new ZapiackRealtimeError(`Could not get a token: ${e instanceof Error ? e.message : String(e)}`, 0));
227
+ return this.later();
228
+ }
229
+ if (!this.wanted) return;
230
+ let ws;
231
+ try {
232
+ ws = this.env.socket(`${this.o.url.replace(/\/+$/, "")}/?token=${encodeURIComponent(token)}`);
233
+ } catch (e) {
234
+ this.fail(new ZapiackRealtimeError(`Could not open the connection: ${e instanceof Error ? e.message : String(e)}`, 0));
235
+ return this.later();
236
+ }
237
+ this.ws = ws;
238
+ ws.onmessage = (ev) => this.onFrame(ws, ev.data);
239
+ ws.onerror = () => void 0;
240
+ ws.onclose = (ev) => this.onClose(ws, ev?.code ?? 1006);
241
+ }
242
+ onFrame(ws, raw) {
243
+ if (ws !== this.ws) return;
244
+ this.heard = this.now();
245
+ let f;
246
+ try {
247
+ f = JSON.parse(String(raw));
248
+ } catch {
249
+ return;
250
+ }
251
+ switch (f["op"]) {
252
+ case "hello":
253
+ this._connId = f["connId"];
254
+ this.attempt = 0;
255
+ this.set("connected");
256
+ this.rejoin();
257
+ for (const text of this.outbox.splice(0)) ws.send(text);
258
+ this.startBeat(ws);
259
+ this.first?.resolve();
260
+ this.first = null;
261
+ return;
262
+ case "message":
263
+ return this.onMessage(f);
264
+ case "ack": {
265
+ this.settle(f["ackId"])?.resolve({ msgId: f["msgId"], delivered: f["delivered"] ?? 0 });
266
+ return;
267
+ }
268
+ case "rpc.result":
269
+ case "rpc.error": {
270
+ const id = String(f["correlationId"]);
271
+ const p = this.pending.get(id);
272
+ if (!p) return;
273
+ this.pending.delete(id);
274
+ this.env.clearTimeout(p.timer);
275
+ if (f["op"] === "rpc.result") p.resolve(f["data"]);
276
+ else p.reject(new ZapiackRealtimeError(String(f["message"] ?? "The request failed."), 0, String(f["code"] ?? "internal")));
277
+ return;
278
+ }
279
+ case "error": {
280
+ if (f["fatal"] === true) this.refused = true;
281
+ const err = new ZapiackRealtimeError(String(f["message"] ?? "Error"), Number(f["code"] ?? 0));
282
+ const ref = typeof f["ref"] === "string" ? f["ref"] : void 0;
283
+ if (ref && this.settle(ref)?.reject(err)) return;
284
+ return this.fail(err);
285
+ }
286
+ case "presence.members": {
287
+ const map = /* @__PURE__ */ new Map();
288
+ for (const m of f["members"] ?? []) map.set(m.connId, m);
289
+ this.members.set(f["channel"], map);
290
+ return;
291
+ }
292
+ case "resume.failed":
293
+ return this.fail(new ZapiackRealtimeError(`Missed messages on ${f["channel"]} could not be replayed. Reload its history.`, 410));
294
+ }
295
+ }
296
+ onMessage(m) {
297
+ if (m.event.startsWith("presence.")) return this.onPresence(m);
298
+ const sub = this.subs.get(m.channel);
299
+ if (!sub) return;
300
+ if (m.persisted) {
301
+ if (!after(m.msgId, sub.cursor)) return;
302
+ sub.cursor = m.msgId;
303
+ }
304
+ for (const h of [...sub.handlers]) {
305
+ try {
306
+ h(m);
307
+ } catch {
308
+ }
309
+ }
310
+ }
311
+ onPresence(m) {
312
+ const d = m.data;
313
+ const action = m.event.slice("presence.".length);
314
+ const map = this.members.get(m.channel) ?? /* @__PURE__ */ new Map();
315
+ this.members.set(m.channel, map);
316
+ if (action === "leave") map.delete(d.connId);
317
+ else map.set(d.connId, { connId: d.connId, user: d.user, data: d.data, at: m.ts });
318
+ for (const fn of this.presenceHandlers.get(m.channel) ?? []) fn({ action, member: { connId: d.connId, user: d.user, data: d.data } });
319
+ }
320
+ rejoin() {
321
+ for (const [channel, sub] of this.subs) this.ws?.send(JSON.stringify({ op: "subscribe", channel, resumeFrom: sub.cursor }));
322
+ }
323
+ startBeat(ws) {
324
+ this.stopBeat();
325
+ this.heard = this.now();
326
+ this.beat = this.env.setInterval(() => {
327
+ if (ws !== this.ws) return;
328
+ if (this.now() - this.heard > this.o.heartbeatMs * 2) return void ws.close(4e3, "no heartbeat");
329
+ if (ws.readyState === OPEN) ws.send('{"op":"ping"}');
330
+ }, this.o.heartbeatMs);
331
+ }
332
+ stopBeat() {
333
+ this.env.clearInterval(this.beat);
334
+ this.beat = void 0;
335
+ }
336
+ onClose(ws, code) {
337
+ if (ws !== this.ws) return;
338
+ this.ws = null;
339
+ this.stopBeat();
340
+ this._connId = null;
341
+ this.failRequests(new ZapiackRealtimeError("The connection dropped.", 0, "no_route"));
342
+ if (!this.wanted) return;
343
+ if (code === 4403 || this.refused) {
344
+ this.refused = false;
345
+ this.wanted = false;
346
+ this.failAll(new ZapiackRealtimeError("The project does not allow this connection.", 403));
347
+ this.first?.reject(new ZapiackRealtimeError("The project does not allow this connection.", 403));
348
+ this.first = null;
349
+ this.set("closed");
350
+ return;
351
+ }
352
+ this.set("reconnecting");
353
+ this.later(code === 4401 || code === 1012 ? 0 : void 0);
354
+ }
355
+ later(force) {
356
+ this.env.clearTimeout(this.retry);
357
+ this.attempt += 1;
358
+ const { min, max } = this.o.backoffMs;
359
+ const ceiling = Math.min(max, min * 2 ** (this.attempt - 1));
360
+ const wait = force ?? Math.round(min + this.env.random() * (ceiling - min));
361
+ this.set("reconnecting");
362
+ this.retry = this.env.setTimeout(() => void this.open(), wait);
363
+ }
364
+ };
365
+
366
+ export {
367
+ ZapiackRealtimeError,
368
+ DEFAULT_REALTIME_URL,
369
+ browserRealtimeEnv,
370
+ ZapiackRealtime
371
+ };
package/dist/index.d.mts CHANGED
@@ -1,3 +1,5 @@
1
+ export { D as DEFAULT_REALTIME_URL, P as PresenceMember, b as PublishOptions, c as PublishResult, R as RealtimeEnv, d as RealtimeMessage, e as RealtimeOptions, f as RealtimeState, S as SocketLike, Z as ZapiackRealtime, a as ZapiackRealtimeError, g as browserRealtimeEnv } from './realtime-BAcafCSr.mjs';
2
+
1
3
  /** What was tapped, handed to the app so it can route. */
2
4
  interface ZapiackTap {
3
5
  messageId: string;
@@ -43,6 +45,12 @@ declare const ZapiackPush: {
43
45
  track(name: string, properties?: Record<string, unknown>): Promise<boolean>;
44
46
  /** Sends anything waiting. Call when the app comes to the foreground. */
45
47
  flush(): Promise<void>;
48
+ /**
49
+ * Lets Zapiack start Live Activities on iOS 17.2 and later: a template push with a timer or progress then counts down on the lock
50
+ * screen and in the Dynamic Island. Also add ZapiackLiveActivityWidget to a widget extension (see the iOS README). Does nothing on
51
+ * Android, where those pushes are drawn in the notification itself.
52
+ */
53
+ enableLiveActivities(): Promise<void>;
46
54
  /** Notifications tapped while the app is running. Returns a function that stops listening. */
47
55
  onTap(listener: (tap: ZapiackTap) => void): () => void;
48
56
  /** The notification that opened the app, if it was opened by tapping one. Resolves it once. */
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { D as DEFAULT_REALTIME_URL, P as PresenceMember, b as PublishOptions, c as PublishResult, R as RealtimeEnv, d as RealtimeMessage, e as RealtimeOptions, f as RealtimeState, S as SocketLike, Z as ZapiackRealtime, a as ZapiackRealtimeError, g as browserRealtimeEnv } from './realtime-BAcafCSr.js';
2
+
1
3
  /** What was tapped, handed to the app so it can route. */
2
4
  interface ZapiackTap {
3
5
  messageId: string;
@@ -43,6 +45,12 @@ declare const ZapiackPush: {
43
45
  track(name: string, properties?: Record<string, unknown>): Promise<boolean>;
44
46
  /** Sends anything waiting. Call when the app comes to the foreground. */
45
47
  flush(): Promise<void>;
48
+ /**
49
+ * Lets Zapiack start Live Activities on iOS 17.2 and later: a template push with a timer or progress then counts down on the lock
50
+ * screen and in the Dynamic Island. Also add ZapiackLiveActivityWidget to a widget extension (see the iOS README). Does nothing on
51
+ * Android, where those pushes are drawn in the notification itself.
52
+ */
53
+ enableLiveActivities(): Promise<void>;
46
54
  /** Notifications tapped while the app is running. Returns a function that stops listening. */
47
55
  onTap(listener: (tap: ZapiackTap) => void): () => void;
48
56
  /** The notification that opened the app, if it was opened by tapping one. Resolves it once. */