@bikefinder/sdk 0.33.1 → 0.33.3

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/README.md CHANGED
@@ -76,8 +76,14 @@ does not call `onConnectionError`.
76
76
 
77
77
  Full reconnects end existing subscriptions. Use `onReconnect` to explicitly
78
78
  subscribe again. The SDK does not replay events or retry writes automatically.
79
+ When the API advertises keepalive support, the browser SDK probes an idle socket
80
+ after five minutes while a visible page has active watches. A missed reply
81
+ triggers the usual reconnect. The reply checks the Gateway connection.
79
82
  Each ticket attempt has its own deadline (`realtimeConnectTimeoutMs`, 30 seconds
80
83
  by default), so a stalled token provider or ticket request can time out and retry.
84
+ Pending subscriptions wait through transient connection failures within the same
85
+ connection-wait deadline. Ticket admission errors such as a denied sign-in or
86
+ rate limit are returned immediately.
81
87
  Retain the original request ID when explicitly retrying an uncertain mutation.
82
88
 
83
89
  Photo metadata supports HTTP `list` and WebSocket `watchPage`, with the same
@@ -424,6 +424,7 @@ var realtimeTicket = z7.object({
424
424
  ticket: z7.string().regex(/^[A-Za-z0-9_-]{43}$/),
425
425
  expiresAt: z7.iso.datetime(),
426
426
  webSocketUrl: z7.url({ protocol: /^wss?$/ }),
427
+ keepAlive: z7.literal(true).optional(),
427
428
  staffFeeds: z7.array(z7.string()).transform(
428
429
  (values) => values.filter(
429
430
  (value) => staffRealtimeFeed.safeParse(value).success
package/dist/index.d.ts CHANGED
@@ -15,6 +15,7 @@ export declare const realtimeTicket: z.ZodObject<{
15
15
  ticket: z.ZodString;
16
16
  expiresAt: z.ZodISODateTime;
17
17
  webSocketUrl: z.ZodURL;
18
+ keepAlive: z.ZodOptional<z.ZodLiteral<true>>;
18
19
  staffFeeds: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<("observations" | "observation-watches" | "commands" | "settings")[], string[]>>>;
19
20
  }, z.core.$strip>;
20
21
  export declare const realtimeContract: {
@@ -22,6 +23,7 @@ export declare const realtimeContract: {
22
23
  ticket: z.ZodString;
23
24
  expiresAt: z.ZodISODateTime;
24
25
  webSocketUrl: z.ZodURL;
26
+ keepAlive: z.ZodOptional<z.ZodLiteral<true>>;
25
27
  staffFeeds: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<("observations" | "observation-watches" | "commands" | "settings")[], string[]>>>;
26
28
  }, z.core.$strip>, import("@orpc/contract").MergedErrorMap<Record<never, never>, {
27
29
  readonly invalid: {
package/dist/index.js CHANGED
@@ -82,7 +82,7 @@ import {
82
82
  trackerMemberInput,
83
83
  trackerMovementAlertsInput,
84
84
  trackerPhotoContract
85
- } from "./chunk-IYM3P32E.js";
85
+ } from "./chunk-425MMPO2.js";
86
86
 
87
87
  // ../../src/client/client.ts
88
88
  import {
@@ -101,10 +101,68 @@ import {
101
101
  RequestValidationPlugin,
102
102
  ResponseValidationPlugin
103
103
  } from "@orpc/contract/plugins";
104
+ import { isAsyncIteratorObject } from "@orpc/shared";
104
105
  import ReconnectingWebSocket from "partysocket/ws";
105
106
  import { pEvent } from "p-event";
106
107
  import pTimeout from "p-timeout";
107
108
  import { z } from "zod";
109
+
110
+ // ../../src/client/keep-alive.ts
111
+ import { AsyncIteratorClass } from "@orpc/shared";
112
+ var idleMs = 5 * 6e4;
113
+ var replyMs = 15e3;
114
+ function createBrowserKeepAlive(socket, page) {
115
+ let lastActivity = Date.now();
116
+ const watches = /* @__PURE__ */ new Set();
117
+ let timer;
118
+ let disposed = false;
119
+ function schedule() {
120
+ clearTimeout(timer);
121
+ if (disposed || !watches.size || page.visibilityState !== "visible") return;
122
+ timer = setTimeout(() => {
123
+ if (socket.readyState !== socket.OPEN || page.visibilityState !== "visible")
124
+ return;
125
+ socket.send('{"action":"ping"}');
126
+ timer = setTimeout(() => {
127
+ if (socket.readyState === socket.OPEN && page.visibilityState === "visible")
128
+ socket.reconnect(4e3, "Realtime keepalive timed out.");
129
+ }, replyMs);
130
+ }, Math.max(0, idleMs - (Date.now() - lastActivity)));
131
+ }
132
+ return {
133
+ activity() {
134
+ lastActivity = Date.now();
135
+ schedule();
136
+ },
137
+ track(iterator, signal) {
138
+ if (disposed || signal?.aborted) return iterator;
139
+ function stop() {
140
+ if (!watches.delete(stop)) return;
141
+ signal?.removeEventListener("abort", stop);
142
+ if (!watches.size) {
143
+ page.removeEventListener("visibilitychange", schedule);
144
+ clearTimeout(timer);
145
+ }
146
+ }
147
+ watches.add(stop);
148
+ if (watches.size === 1) {
149
+ page.addEventListener("visibilitychange", schedule);
150
+ schedule();
151
+ }
152
+ signal?.addEventListener("abort", stop, { once: true });
153
+ return new AsyncIteratorClass(() => iterator.next(), async (reason) => {
154
+ stop();
155
+ if (reason !== "next") await iterator.return?.();
156
+ });
157
+ },
158
+ dispose() {
159
+ disposed = true;
160
+ watches.forEach((stop) => stop());
161
+ }
162
+ };
163
+ }
164
+
165
+ // ../../src/client/client.ts
108
166
  var RealtimeDisconnectedError = class extends ORPCError {
109
167
  constructor() {
110
168
  super("stream_unavailable", {
@@ -115,6 +173,7 @@ var RealtimeDisconnectedError = class extends ORPCError {
115
173
  }
116
174
  };
117
175
  var gatewayError = z.object({ message: z.string() });
176
+ var gatewayPong = z.strictObject({ action: z.literal("pong") });
118
177
  function endpoint(value, transport) {
119
178
  const url = new URL(value);
120
179
  const secure = transport === "http" ? "https:" : "wss:";
@@ -170,12 +229,16 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
170
229
  const tickets = createORPCClient(http, { path: [audience, "realtime"] });
171
230
  let socket;
172
231
  let realtime;
173
- let ticketError;
232
+ let ticketFailed = false;
233
+ let ticketRejection = new AbortController();
174
234
  let staffFeeds = [];
175
235
  let negotiated;
236
+ let supportsKeepAlive = false;
237
+ let keepAlive;
176
238
  async function ticketUrl() {
177
239
  lifetime.signal.throwIfAborted();
178
- ticketError = void 0;
240
+ ticketFailed = false;
241
+ let receivedTicket = false;
179
242
  const attempt = new AbortController();
180
243
  try {
181
244
  const result = await pTimeout(
@@ -187,17 +250,25 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
187
250
  }
188
251
  );
189
252
  lifetime.signal.throwIfAborted();
253
+ receivedTicket = true;
190
254
  const url = endpoint(result.webSocketUrl, "websocket");
191
255
  url.searchParams.set("ticket", result.ticket);
192
256
  staffFeeds = result.staffFeeds ?? [];
257
+ supportsKeepAlive = result.keepAlive === true;
193
258
  return url.href;
194
259
  } catch (error) {
195
- attempt.abort(error);
196
- if (error instanceof Error && !disposed) {
197
- ticketError = error;
198
- options.onConnectionError?.(error);
260
+ const failure = error instanceof Error ? error : new Error("Realtime ticket request failed.", { cause: error });
261
+ attempt.abort(failure);
262
+ ticketFailed = true;
263
+ if (!disposed) {
264
+ if (receivedTicket || failure instanceof ORPCError && failure.status >= 400 && failure.status < 500 && failure.status !== 408) {
265
+ const rejected = ticketRejection;
266
+ ticketRejection = new AbortController();
267
+ rejected.abort(failure);
268
+ }
269
+ options.onConnectionError?.(failure);
199
270
  }
200
- throw error;
271
+ throw failure;
201
272
  }
202
273
  }
203
274
  function websocket() {
@@ -221,18 +292,22 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
221
292
  connection.addEventListener("open", () => {
222
293
  if (disposed) return;
223
294
  connected = true;
295
+ if (supportsKeepAlive && typeof document !== "undefined")
296
+ keepAlive = createBrowserKeepAlive(connection, document);
224
297
  options.onConnectionStateChange?.("connected");
225
298
  if (opened && !disposed) options.onReconnect?.();
226
299
  opened = true;
227
300
  });
228
301
  connection.addEventListener("close", () => {
302
+ keepAlive?.dispose();
303
+ keepAlive = void 0;
229
304
  negotiated?.disconnect();
230
305
  if (!connected) return;
231
306
  connected = false;
232
307
  if (!disposed) options.onConnectionStateChange?.("reconnecting");
233
308
  });
234
309
  connection.addEventListener("error", () => {
235
- if (!disposed && !ticketError)
310
+ if (!disposed && !ticketFailed)
236
311
  options.onConnectionError?.(
237
312
  new Error("Realtime WebSocket connection failed.")
238
313
  );
@@ -248,6 +323,11 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
248
323
  connection.reconnect(4e3, "Invalid Gateway response.");
249
324
  return;
250
325
  }
326
+ keepAlive?.activity();
327
+ if (gatewayPong.safeParse(decoded).success) {
328
+ event.stopImmediatePropagation();
329
+ return;
330
+ }
251
331
  if (negotiated?.consume(decoded)) {
252
332
  event.stopImmediatePropagation();
253
333
  return;
@@ -262,32 +342,32 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
262
342
  }
263
343
  const link = new DynamicLink(async (request, path) => {
264
344
  lifetime.signal.throwIfAborted();
345
+ request.signal?.throwIfAborted();
265
346
  const procedure = getContractRouter(root, path);
266
347
  if (!isContractProcedure(procedure) || !getEventIteratorSchemaDetails(procedure["~orpc"].outputSchema))
267
348
  return http;
268
349
  const link2 = websocket();
269
350
  const connection = socket;
270
351
  if (connection.readyState !== connection.OPEN) {
271
- try {
272
- await pEvent(connection, "open", {
273
- rejectionEvents: ["close", "error"],
274
- signal: request.signal ? AbortSignal.any([lifetime.signal, request.signal]) : lifetime.signal,
275
- timeout: timeoutMs
276
- });
277
- } catch (error) {
278
- lifetime.signal.throwIfAborted();
279
- request.signal?.throwIfAborted();
280
- if (ticketError) throw ticketError;
281
- if (error instanceof Event && error.type === "close")
282
- throw new RealtimeDisconnectedError();
283
- if (error && typeof error === "object" && "error" in error && error.error instanceof Error)
284
- throw error.error;
285
- throw error instanceof Error ? error : new Error("Realtime connection failed.", { cause: error });
286
- }
352
+ const signals = [lifetime.signal, ticketRejection.signal];
353
+ if (request.signal) signals.push(request.signal);
354
+ await pEvent(connection, "open", {
355
+ rejectionEvents: [],
356
+ signal: AbortSignal.any(signals),
357
+ timeout: timeoutMs
358
+ });
287
359
  }
288
360
  lifetime.signal.throwIfAborted();
289
361
  request.signal?.throwIfAborted();
290
- return negotiated?.select(path, staffFeeds) ?? link2;
362
+ const transport = negotiated?.select(path, staffFeeds) ?? link2;
363
+ const monitor = keepAlive;
364
+ if (!monitor) return transport;
365
+ return {
366
+ async call(path2, input, options2) {
367
+ const result = await transport.call(path2, input, options2);
368
+ return isAsyncIteratorObject(result) ? monitor.track(result, options2.signal) : result;
369
+ }
370
+ };
291
371
  });
292
372
  const api = createORPCClient(link, {
293
373
  path: [audience]
package/dist/schemas.d.ts CHANGED
@@ -15,6 +15,7 @@ export declare const realtimeTicket: z.ZodObject<{
15
15
  ticket: z.ZodString;
16
16
  expiresAt: z.ZodISODateTime;
17
17
  webSocketUrl: z.ZodURL;
18
+ keepAlive: z.ZodOptional<z.ZodLiteral<true>>;
18
19
  staffFeeds: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<("observations" | "observation-watches" | "commands" | "settings")[], string[]>>>;
19
20
  }, z.core.$strip>;
20
21
  export declare const realtimeContract: {
@@ -22,6 +23,7 @@ export declare const realtimeContract: {
22
23
  ticket: z.ZodString;
23
24
  expiresAt: z.ZodISODateTime;
24
25
  webSocketUrl: z.ZodURL;
26
+ keepAlive: z.ZodOptional<z.ZodLiteral<true>>;
25
27
  staffFeeds: z.ZodOptional<z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<("observations" | "observation-watches" | "commands" | "settings")[], string[]>>>;
26
28
  }, z.core.$strip>, import("@orpc/contract").MergedErrorMap<Record<never, never>, {
27
29
  readonly invalid: {
package/dist/schemas.js CHANGED
@@ -96,7 +96,7 @@ import {
96
96
  trackerSubscription,
97
97
  trackerSummary,
98
98
  trackerSummaryFields
99
- } from "./chunk-IYM3P32E.js";
99
+ } from "./chunk-425MMPO2.js";
100
100
  export {
101
101
  account,
102
102
  accountPreferencePatch,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bikefinder/sdk",
3
- "version": "0.33.1",
3
+ "version": "0.33.3",
4
4
  "description": "Typed HTTP and WebSocket client for BikeFinder.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -35,6 +35,7 @@
35
35
  "dependencies": {
36
36
  "@orpc/client": "1.16.3",
37
37
  "@orpc/contract": "1.16.3",
38
+ "@orpc/shared": "1.16.3",
38
39
  "decimal.js": "10.6.0",
39
40
  "p-event": "8.0.2",
40
41
  "p-timeout": "8.1.0",