@bikefinder/sdk 0.33.3 → 0.35.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.
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  defaultAccountPreferences,
14
14
  directoryProfile,
15
15
  downloadReference,
16
+ errorData,
16
17
  factoryResetReport,
17
18
  firmwareAppInput,
18
19
  firmwareAvailability,
@@ -80,9 +81,13 @@ import {
80
81
  trackerLookupInput,
81
82
  trackerMemberAddInput,
82
83
  trackerMemberInput,
84
+ trackerMode,
85
+ trackerModeRead,
86
+ trackerModeStatus,
87
+ trackerModeWrite,
83
88
  trackerMovementAlertsInput,
84
89
  trackerPhotoContract
85
- } from "./chunk-425MMPO2.js";
90
+ } from "./chunk-ZSNSOMTF.js";
86
91
 
87
92
  // ../../src/client/client.ts
88
93
  import {
@@ -91,6 +96,7 @@ import {
91
96
  ORPCError
92
97
  } from "@orpc/client";
93
98
  import { RPCLink as HttpLink } from "@orpc/client/fetch";
99
+ import { DedupeRequestsPlugin } from "@orpc/client/plugins";
94
100
  import { RPCLink as WebSocketLink } from "@orpc/client/websocket";
95
101
  import {
96
102
  getContractRouter,
@@ -103,7 +109,7 @@ import {
103
109
  } from "@orpc/contract/plugins";
104
110
  import { isAsyncIteratorObject } from "@orpc/shared";
105
111
  import ReconnectingWebSocket from "partysocket/ws";
106
- import { pEvent } from "p-event";
112
+ import { pEvent, TimeoutError } from "p-event";
107
113
  import pTimeout from "p-timeout";
108
114
  import { z } from "zod";
109
115
 
@@ -111,22 +117,25 @@ import { z } from "zod";
111
117
  import { AsyncIteratorClass } from "@orpc/shared";
112
118
  var idleMs = 5 * 6e4;
113
119
  var replyMs = 15e3;
114
- function createBrowserKeepAlive(socket, page) {
120
+ function createBrowserKeepAlive(socket, page, probe) {
115
121
  let lastActivity = Date.now();
116
122
  const watches = /* @__PURE__ */ new Set();
117
123
  let timer;
124
+ let scheduled = 0;
118
125
  let disposed = false;
126
+ const lifetime = new AbortController();
119
127
  function schedule() {
128
+ const generation = ++scheduled;
120
129
  clearTimeout(timer);
121
130
  if (disposed || !watches.size || page.visibilityState !== "visible") return;
122
131
  timer = setTimeout(() => {
123
132
  if (socket.readyState !== socket.OPEN || page.visibilityState !== "visible")
124
133
  return;
125
- socket.send('{"action":"ping"}');
126
- timer = setTimeout(() => {
127
- if (socket.readyState === socket.OPEN && page.visibilityState === "visible")
134
+ const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(replyMs)]);
135
+ void probe(signal).catch(() => {
136
+ if (!disposed && generation === scheduled && watches.size && socket.readyState === socket.OPEN && page.visibilityState === "visible")
128
137
  socket.reconnect(4e3, "Realtime keepalive timed out.");
129
- }, replyMs);
138
+ });
130
139
  }, Math.max(0, idleMs - (Date.now() - lastActivity)));
131
140
  }
132
141
  return {
@@ -157,6 +166,7 @@ function createBrowserKeepAlive(socket, page) {
157
166
  },
158
167
  dispose() {
159
168
  disposed = true;
169
+ lifetime.abort();
160
170
  watches.forEach((stop) => stop());
161
171
  }
162
172
  };
@@ -172,8 +182,18 @@ var RealtimeDisconnectedError = class extends ORPCError {
172
182
  this.name = "RealtimeDisconnectedError";
173
183
  }
174
184
  };
185
+ var deduplicatedStaffReads = /* @__PURE__ */ new Set([
186
+ "staff.trackers.getDetails",
187
+ "staff.trackers.list",
188
+ "staff.trackers.lookup",
189
+ "staff.favorites.list",
190
+ "staff.aws.resolve",
191
+ "staff.aws.observations.current",
192
+ "staff.aws.observations.history",
193
+ "staff.aws.observations.watchSeed",
194
+ "staff.aws.commands.list"
195
+ ]);
175
196
  var gatewayError = z.object({ message: z.string() });
176
- var gatewayPong = z.strictObject({ action: z.literal("pong") });
177
197
  function endpoint(value, transport) {
178
198
  const url = new URL(value);
179
199
  const secure = transport === "http" ? "https:" : "wss:";
@@ -184,10 +204,11 @@ function endpoint(value, transport) {
184
204
  );
185
205
  return url;
186
206
  }
187
- function createApiClient(contract, audience, options, createNegotiatedRealtime) {
207
+ function createApiClient(contract, audience, options, wrapRealtime) {
188
208
  const base = endpoint(options.baseUrl, "http");
189
209
  base.pathname = `${base.pathname.replace(/\/+$/, "")}/rpc`;
190
210
  const lifetime = new AbortController();
211
+ let connectionGeneration = new AbortController();
191
212
  const timeoutMs = options.realtimeConnectTimeoutMs ?? 3e4;
192
213
  let disposed = false;
193
214
  const root = { [audience]: contract };
@@ -208,8 +229,22 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
208
229
  ]
209
230
  };
210
231
  }
232
+ const httpOptions = linkOptions();
211
233
  const http = new HttpLink({
212
- ...linkOptions(),
234
+ ...httpOptions,
235
+ ...audience === "staff" && {
236
+ interceptors: [
237
+ ...httpOptions.interceptors ?? [],
238
+ ({ path, signal, next }) => signal && deduplicatedStaffReads.has(path.join(".")) ? pTimeout(next(), { milliseconds: Infinity, signal }) : next()
239
+ ],
240
+ plugins: [
241
+ ...httpOptions.plugins ?? [],
242
+ new DedupeRequestsPlugin({
243
+ filter: ({ path }) => deduplicatedStaffReads.has(path.join(".")),
244
+ groups: [{ condition: () => true, context: {} }]
245
+ })
246
+ ]
247
+ },
213
248
  url: base,
214
249
  fetch: (request, init) => {
215
250
  request.signal.throwIfAborted();
@@ -228,11 +263,10 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
228
263
  });
229
264
  const tickets = createORPCClient(http, { path: [audience, "realtime"] });
230
265
  let socket;
266
+ let reconnecting = false;
231
267
  let realtime;
232
268
  let ticketFailed = false;
233
269
  let ticketRejection = new AbortController();
234
- let staffFeeds = [];
235
- let negotiated;
236
270
  let supportsKeepAlive = false;
237
271
  let keepAlive;
238
272
  async function ticketUrl() {
@@ -253,7 +287,6 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
253
287
  receivedTicket = true;
254
288
  const url = endpoint(result.webSocketUrl, "websocket");
255
289
  url.searchParams.set("ticket", result.ticket);
256
- staffFeeds = result.staffFeeds ?? [];
257
290
  supportsKeepAlive = result.keepAlive === true;
258
291
  return url.href;
259
292
  } catch (error) {
@@ -283,27 +316,31 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
283
316
  { maxEnqueuedMessages: 0, WebSocket: options.webSocket }
284
317
  );
285
318
  const connection = socket;
286
- negotiated = createNegotiatedRealtime?.(
287
- connection,
288
- http,
289
- lifetime.signal,
290
- timeoutMs
291
- );
292
319
  connection.addEventListener("open", () => {
293
320
  if (disposed) return;
294
321
  connected = true;
322
+ reconnecting = false;
295
323
  if (supportsKeepAlive && typeof document !== "undefined")
296
- keepAlive = createBrowserKeepAlive(connection, document);
324
+ keepAlive = createBrowserKeepAlive(
325
+ connection,
326
+ document,
327
+ (signal) => native.call([audience, "realtime", "ping"], void 0, { signal, context: {} })
328
+ );
297
329
  options.onConnectionStateChange?.("connected");
298
- if (opened && !disposed) options.onReconnect?.();
330
+ if (opened && !disposed) {
331
+ const previous = connectionGeneration;
332
+ connectionGeneration = new AbortController();
333
+ previous.abort(new RealtimeDisconnectedError());
334
+ options.onReconnect?.();
335
+ }
299
336
  opened = true;
300
337
  });
301
338
  connection.addEventListener("close", () => {
302
339
  keepAlive?.dispose();
303
340
  keepAlive = void 0;
304
- negotiated?.disconnect();
305
341
  if (!connected) return;
306
342
  connected = false;
343
+ reconnecting = true;
307
344
  if (!disposed) options.onConnectionStateChange?.("reconnecting");
308
345
  });
309
346
  connection.addEventListener("error", () => {
@@ -324,27 +361,21 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
324
361
  return;
325
362
  }
326
363
  keepAlive?.activity();
327
- if (gatewayPong.safeParse(decoded).success) {
328
- event.stopImmediatePropagation();
329
- return;
330
- }
331
- if (negotiated?.consume(decoded)) {
332
- event.stopImmediatePropagation();
333
- return;
334
- }
335
364
  if (gatewayError.safeParse(decoded).success) {
336
365
  event.stopImmediatePropagation();
337
366
  connection.reconnect(4e3, "Gateway delivery failed.");
338
367
  }
339
368
  });
340
- realtime = new WebSocketLink({ ...linkOptions(), websocket: connection });
369
+ const native = new WebSocketLink({ ...linkOptions(), websocket: connection });
370
+ realtime = wrapRealtime?.(native, http, timeoutMs) ?? native;
341
371
  return realtime;
342
372
  }
343
373
  const link = new DynamicLink(async (request, path) => {
344
374
  lifetime.signal.throwIfAborted();
345
375
  request.signal?.throwIfAborted();
346
376
  const procedure = getContractRouter(root, path);
347
- if (!isContractProcedure(procedure) || !getEventIteratorSchemaDetails(procedure["~orpc"].outputSchema))
377
+ const ping = path.length === 3 && path[1] === "realtime" && path[2] === "ping";
378
+ if (!ping && (!isContractProcedure(procedure) || !getEventIteratorSchemaDetails(procedure["~orpc"].outputSchema)))
348
379
  return http;
349
380
  const link2 = websocket();
350
381
  const connection = socket;
@@ -359,7 +390,7 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
359
390
  }
360
391
  lifetime.signal.throwIfAborted();
361
392
  request.signal?.throwIfAborted();
362
- const transport = negotiated?.select(path, staffFeeds) ?? link2;
393
+ const transport = link2;
363
394
  const monitor = keepAlive;
364
395
  if (!monitor) return transport;
365
396
  return {
@@ -374,10 +405,52 @@ function createApiClient(contract, audience, options, createNegotiatedRealtime)
374
405
  });
375
406
  return {
376
407
  api,
408
+ async *watch(subscribe, { signal: caller } = {}) {
409
+ const signal = caller ? AbortSignal.any([lifetime.signal, caller]) : lifetime.signal;
410
+ let delay = 500;
411
+ while (true) {
412
+ signal.throwIfAborted();
413
+ const generation = connectionGeneration.signal;
414
+ const attempt = new AbortController();
415
+ const request = AbortSignal.any([signal, generation, attempt.signal]);
416
+ const startedConnected = socket && socket.readyState === socket.OPEN;
417
+ let retryAfterSeconds;
418
+ try {
419
+ const stream = await subscribe(api, request);
420
+ for await (const value of stream) {
421
+ request.throwIfAborted();
422
+ delay = 500;
423
+ yield value;
424
+ }
425
+ } catch (error) {
426
+ signal.throwIfAborted();
427
+ if (error instanceof ORPCError) {
428
+ const details = errorData.safeParse(error.data);
429
+ if (!(error instanceof RealtimeDisconnectedError) && (![408, 429, 500, 502, 503, 504].includes(error.status) || details.success && details.data.recovery.action !== "retry_read" && !(error.status === 429 && details.data.recovery.action === "retry_same_request") && !(error.status === 503 && error.code === "service_unavailable" && details.data.recovery.action === "verify_outcome") || error.status === 500 && !details.success))
430
+ throw error;
431
+ if (details.success) retryAfterSeconds = details.data.retryAfterSeconds;
432
+ } else if (!generation.aborted && !(error instanceof TimeoutError) && !(reconnecting && error instanceof Error && error.name === "AbortError") && !(startedConnected && socket?.readyState !== socket?.OPEN)) {
433
+ throw error;
434
+ }
435
+ } finally {
436
+ attempt.abort();
437
+ }
438
+ signal.throwIfAborted();
439
+ if (generation.aborted && retryAfterSeconds === void 0) continue;
440
+ try {
441
+ await pEvent(retryAfterSeconds === void 0 ? generation : signal, "abort", {
442
+ signal,
443
+ timeout: Math.max(delay, (retryAfterSeconds ?? 0) * 1e3)
444
+ });
445
+ } catch (error) {
446
+ if (!(error instanceof TimeoutError)) throw error;
447
+ }
448
+ delay = Math.min(delay * 2, 3e4);
449
+ }
450
+ },
377
451
  dispose() {
378
452
  if (disposed) return;
379
453
  disposed = true;
380
- negotiated?.disconnect();
381
454
  socket?.close(1e3, "Client disposed.");
382
455
  lifetime.abort(new DOMException("Client disposed.", "AbortError"));
383
456
  options.onConnectionStateChange?.("closed");
@@ -554,6 +627,10 @@ export {
554
627
  trackerLookupInput,
555
628
  trackerMemberAddInput,
556
629
  trackerMemberInput,
630
+ trackerMode,
631
+ trackerModeRead,
632
+ trackerModeStatus,
633
+ trackerModeWrite,
557
634
  trackerMovementAlertsInput,
558
635
  trackerPhotoContract,
559
636
  uploadPhoto