@bikefinder/sdk 0.12.0 → 0.23.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.
Files changed (68) hide show
  1. package/README.md +47 -128
  2. package/dist/chunk-HTKUP56M.js +786 -0
  3. package/dist/index.d.ts +17753 -39
  4. package/dist/index.js +385 -65
  5. package/dist/schemas.d.ts +17882 -0
  6. package/dist/schemas.js +174 -0
  7. package/package.json +20 -23
  8. package/dist/acquisition-schema.d.ts +0 -177
  9. package/dist/acquisition-schema.js +0 -250
  10. package/dist/device-schema.d.ts +0 -9095
  11. package/dist/device-schema.js +0 -10734
  12. package/dist/generated/client/client.gen.d.ts +0 -2
  13. package/dist/generated/client/client.gen.js +0 -217
  14. package/dist/generated/client/index.d.ts +0 -10
  15. package/dist/generated/client/index.js +0 -6
  16. package/dist/generated/client/types.gen.d.ts +0 -120
  17. package/dist/generated/client/types.gen.js +0 -2
  18. package/dist/generated/client/utils.gen.d.ts +0 -37
  19. package/dist/generated/client/utils.gen.js +0 -231
  20. package/dist/generated/client.gen.d.ts +0 -12
  21. package/dist/generated/client.gen.js +0 -3
  22. package/dist/generated/core/auth.gen.d.ts +0 -25
  23. package/dist/generated/core/auth.gen.js +0 -14
  24. package/dist/generated/core/bodySerializer.gen.d.ts +0 -25
  25. package/dist/generated/core/bodySerializer.gen.js +0 -57
  26. package/dist/generated/core/params.gen.d.ts +0 -43
  27. package/dist/generated/core/params.gen.js +0 -112
  28. package/dist/generated/core/pathSerializer.gen.d.ts +0 -33
  29. package/dist/generated/core/pathSerializer.gen.js +0 -114
  30. package/dist/generated/core/queryKeySerializer.gen.d.ts +0 -18
  31. package/dist/generated/core/queryKeySerializer.gen.js +0 -99
  32. package/dist/generated/core/serverSentEvents.gen.d.ts +0 -71
  33. package/dist/generated/core/serverSentEvents.gen.js +0 -136
  34. package/dist/generated/core/types.gen.d.ts +0 -83
  35. package/dist/generated/core/types.gen.js +0 -2
  36. package/dist/generated/core/utils.gen.d.ts +0 -19
  37. package/dist/generated/core/utils.gen.js +0 -87
  38. package/dist/generated/index.d.ts +0 -2
  39. package/dist/generated/index.js +0 -2
  40. package/dist/generated/sdk.gen.d.ts +0 -136
  41. package/dist/generated/sdk.gen.js +0 -1347
  42. package/dist/generated/types.gen.d.ts +0 -12633
  43. package/dist/generated/types.gen.js +0 -2
  44. package/dist/generated/zod.gen.d.ts +0 -40667
  45. package/dist/generated/zod.gen.js +0 -13757
  46. package/dist/signalr/BikeFinder.Api.Commands.d.ts +0 -1
  47. package/dist/signalr/BikeFinder.Api.Commands.js +0 -1
  48. package/dist/signalr/BikeFinder.Api.Firestore.d.ts +0 -1
  49. package/dist/signalr/BikeFinder.Api.Firestore.js +0 -1
  50. package/dist/signalr/BikeFinder.Api.Http.d.ts +0 -7
  51. package/dist/signalr/BikeFinder.Api.Http.js +0 -4
  52. package/dist/signalr/BikeFinder.Api.Observations.d.ts +0 -1
  53. package/dist/signalr/BikeFinder.Api.Observations.js +0 -1
  54. package/dist/signalr/BikeFinder.Api.Settings.d.ts +0 -1
  55. package/dist/signalr/BikeFinder.Api.Settings.js +0 -1
  56. package/dist/signalr/BikeFinder.Api.Trackers.d.ts +0 -22
  57. package/dist/signalr/BikeFinder.Api.Trackers.js +0 -4
  58. package/dist/signalr/BikeFinder.DeviceConfiguration.d.ts +0 -1
  59. package/dist/signalr/BikeFinder.DeviceConfiguration.js +0 -1
  60. package/dist/signalr/BikeFinder.Nucleus.Commands.d.ts +0 -1
  61. package/dist/signalr/BikeFinder.Nucleus.Commands.js +0 -1
  62. package/dist/signalr/BikeFinder.Observations.Model.d.ts +0 -1
  63. package/dist/signalr/BikeFinder.Observations.Model.js +0 -1
  64. package/dist/signalr/TypedSignalR.Client/BikeFinder.Api.Trackers.d.ts +0 -91
  65. package/dist/signalr/TypedSignalR.Client/BikeFinder.Api.Trackers.js +0 -1
  66. package/dist/signalr/TypedSignalR.Client/index.d.ts +0 -18
  67. package/dist/signalr/TypedSignalR.Client/index.js +0 -89
  68. package/openapi/api.json +0 -52163
package/dist/index.js CHANGED
@@ -1,70 +1,390 @@
1
- import { HubConnectionBuilder, HttpTransportType, LogLevel, } from "@microsoft/signalr";
2
- import { createClient } from "./generated/client/index.js";
3
- import { ApiRequests } from "./generated/sdk.gen.js";
4
- import { getHubProxyFactory } from "./signalr/TypedSignalR.Client/index.js";
5
- export function createBikeFinderClient(options) {
6
- const origin = new URL(options.baseUrl);
7
- if (origin.pathname !== "/" ||
8
- origin.search ||
9
- origin.hash ||
10
- origin.username ||
11
- origin.password ||
12
- !["https:", "http:"].includes(origin.protocol))
13
- throw new TypeError("baseUrl must be an HTTP(S) API origin without credentials, path, query or fragment.");
14
- const scope = new AbortController();
15
- const getToken = () => {
16
- scope.signal.throwIfAborted();
17
- return options.getToken();
1
+ import {
2
+ account,
3
+ accountPreferencePatch,
4
+ accountPreferences,
5
+ batteryObservation,
6
+ bikeChanges,
7
+ bikeEditInput,
8
+ bluetoothContract,
9
+ bluetoothCredentials,
10
+ bluetoothPin,
11
+ bluetoothPinChange,
12
+ customerContract,
13
+ directoryProfile,
14
+ downloadReference,
15
+ factoryResetReport,
16
+ firmwareAppInput,
17
+ firmwareAvailability,
18
+ firmwareClientReport,
19
+ firmwareReportInput,
20
+ firmwareReportOutcome,
21
+ firmwareTransfer,
22
+ firmwareUpdateInput,
23
+ gen1FirmwareContract,
24
+ historyContract,
25
+ historyCursor,
26
+ historyEntry,
27
+ historyInput,
28
+ historyPage,
29
+ inboxContract,
30
+ inboxPage,
31
+ inboxPageInput,
32
+ invitationInput,
33
+ invitationRedeemInput,
34
+ locationObservation,
35
+ membershipName,
36
+ migratedSession,
37
+ notification,
38
+ notificationSource,
39
+ photo,
40
+ photoDownloadInput,
41
+ photoInput,
42
+ photoPage,
43
+ photoPageInput,
44
+ photoUploadContract,
45
+ photoUploadInput,
46
+ photoUploadSession,
47
+ photoUploadStartInput,
48
+ pushContract,
49
+ pushRegistrationInput,
50
+ pushRemovalInput,
51
+ pushToken,
52
+ realtimeContract,
53
+ realtimeTicket,
54
+ startFirmwareUpdate,
55
+ subscription,
56
+ subscriptionAllocationContract,
57
+ subscriptionAllocationInput,
58
+ subscriptionContract,
59
+ subscriptionPage,
60
+ theftContract,
61
+ theftSubmission,
62
+ trackerAdmission,
63
+ trackerChangeContract,
64
+ trackerClaimInput,
65
+ trackerFirmwareRelease,
66
+ trackerFirmwareReleases,
67
+ trackerFirmwareUpdate,
68
+ trackerInvitation,
69
+ trackerInvitationContract,
70
+ trackerLookupContract,
71
+ trackerLookupInput,
72
+ trackerMemberAddInput,
73
+ trackerMemberInput,
74
+ trackerMovementAlertsInput,
75
+ trackerPhotoContract
76
+ } from "./chunk-HTKUP56M.js";
77
+
78
+ // ../../src/Client/client.ts
79
+ import { createORPCClient, DynamicLink } from "@orpc/client";
80
+ import { RPCLink as HttpLink } from "@orpc/client/fetch";
81
+ import { RPCLink as WebSocketLink } from "@orpc/client/websocket";
82
+ import {
83
+ getContractRouter,
84
+ getEventIteratorSchemaDetails,
85
+ isContractProcedure
86
+ } from "@orpc/contract";
87
+ import {
88
+ RequestValidationPlugin,
89
+ ResponseValidationPlugin
90
+ } from "@orpc/contract/plugins";
91
+ import ReconnectingWebSocket from "partysocket/ws";
92
+ import { pEvent } from "p-event";
93
+ import { z } from "zod";
94
+ var gatewayError = z.object({ message: z.string() });
95
+ function endpoint(value, transport) {
96
+ const url = new URL(value);
97
+ const secure = transport === "http" ? "https:" : "wss:";
98
+ const local = transport === "http" ? "http:" : "ws:";
99
+ if (url.username || url.password || url.search || url.hash || url.protocol !== secure && !(url.protocol === local && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
100
+ throw new Error(
101
+ "Use a secure API endpoint, or a loopback endpoint for development."
102
+ );
103
+ return url;
104
+ }
105
+ function createApiClient(contract, audience, options) {
106
+ const base = endpoint(options.baseUrl, "http");
107
+ base.pathname = `${base.pathname.replace(/\/+$/, "")}/rpc`;
108
+ const lifetime = new AbortController();
109
+ const root = { [audience]: contract };
110
+ function linkOptions() {
111
+ return {
112
+ interceptors: [
113
+ ({ next, ...request }) => {
114
+ lifetime.signal.throwIfAborted();
115
+ return next({
116
+ ...request,
117
+ signal: request.signal ? AbortSignal.any([lifetime.signal, request.signal]) : lifetime.signal
118
+ });
119
+ }
120
+ ],
121
+ plugins: [
122
+ new RequestValidationPlugin(root),
123
+ new ResponseValidationPlugin(root)
124
+ ]
18
125
  };
19
- const http = createClient({
20
- baseUrl: origin.origin,
21
- auth: getToken,
22
- fetch: options.fetch,
23
- redirect: "error",
24
- credentials: "omit",
25
- });
26
- http.interceptors.request.use((request) => {
27
- if (new URL(request.url).origin !== origin.origin)
28
- throw new TypeError("Requests must target the configured API origin.");
29
- return new Request(request, {
30
- signal: AbortSignal.any([request.signal, scope.signal]),
31
- redirect: "error",
32
- credentials: "omit",
126
+ }
127
+ const http = new HttpLink({
128
+ ...linkOptions(),
129
+ url: base,
130
+ fetch: (request, init) => (options.fetch ?? globalThis.fetch)(request, {
131
+ ...init,
132
+ credentials: "omit",
133
+ redirect: "error",
134
+ cache: "no-store"
135
+ }),
136
+ async headers() {
137
+ const token = await options.accessToken();
138
+ lifetime.signal.throwIfAborted();
139
+ return token ? { authorization: `Bearer ${token}` } : {};
140
+ }
141
+ });
142
+ const tickets = createORPCClient(http, { path: [audience, "realtime"] });
143
+ let socket;
144
+ let realtime;
145
+ let ticketError;
146
+ function websocket() {
147
+ if (realtime) return realtime;
148
+ options.onConnectionStateChange?.("connecting");
149
+ let opened = false;
150
+ socket = new ReconnectingWebSocket(
151
+ async () => {
152
+ ticketError = void 0;
153
+ const result = await tickets.ticket().catch((error) => {
154
+ if (error instanceof Error) {
155
+ ticketError = error;
156
+ options.onConnectionError?.(error);
157
+ }
158
+ throw error;
33
159
  });
160
+ lifetime.signal.throwIfAborted();
161
+ const url = endpoint(result.webSocketUrl, "websocket");
162
+ url.searchParams.set("ticket", result.ticket);
163
+ return url.href;
164
+ },
165
+ [],
166
+ { maxEnqueuedMessages: 0 }
167
+ );
168
+ const connection = socket;
169
+ connection.addEventListener("open", () => {
170
+ options.onConnectionStateChange?.("connected");
171
+ if (opened) options.onReconnect?.();
172
+ opened = true;
34
173
  });
35
- http.interceptors.error.use((error, response) => {
36
- if (!response || response.ok)
37
- throw error;
38
- return error;
174
+ connection.addEventListener("close", () => {
175
+ options.onConnectionStateChange?.(
176
+ lifetime.signal.aborted ? "closed" : "reconnecting"
177
+ );
39
178
  });
40
- const connection = (path) => new HubConnectionBuilder()
41
- .withUrl(origin.origin + path, {
42
- transport: HttpTransportType.WebSockets,
43
- // Negotiation enables stateful reconnect; cookies retain task affinity.
44
- withCredentials: true,
45
- accessTokenFactory: getToken,
46
- })
47
- .withStatefulReconnect()
48
- .withAutomaticReconnect()
49
- .configureLogging(LogLevel.None)
50
- .build();
51
- const customer = connection("/v1/stream");
52
- const staff = connection("/v1/admin/stream");
53
- return {
54
- requests: new ApiRequests({ client: http }),
55
- realtime: {
56
- connection: customer,
57
- hub: getHubProxyFactory("ITrackerHub").createHubProxy(customer),
58
- },
59
- staffRealtime: {
60
- connection: staff,
61
- hub: getHubProxyFactory("IStaffTrackerHub").createHubProxy(staff),
62
- },
63
- async dispose() {
64
- scope.abort();
65
- await Promise.all([customer.stop(), staff.stop()]);
66
- },
67
- };
179
+ connection.addEventListener("message", (event) => {
180
+ let decoded;
181
+ try {
182
+ if (typeof event.data !== "string")
183
+ throw new Error("Expected JSON text.");
184
+ decoded = JSON.parse(event.data);
185
+ } catch {
186
+ event.stopImmediatePropagation();
187
+ connection.reconnect(4e3, "Invalid Gateway response.");
188
+ return;
189
+ }
190
+ if (gatewayError.safeParse(decoded).success) {
191
+ event.stopImmediatePropagation();
192
+ connection.reconnect(4e3, "Gateway delivery failed.");
193
+ }
194
+ });
195
+ realtime = new WebSocketLink({ ...linkOptions(), websocket: connection });
196
+ return realtime;
197
+ }
198
+ const link = new DynamicLink(async (request, path) => {
199
+ lifetime.signal.throwIfAborted();
200
+ const procedure = getContractRouter(root, path);
201
+ if (!isContractProcedure(procedure) || !getEventIteratorSchemaDetails(procedure["~orpc"].outputSchema))
202
+ return http;
203
+ const link2 = websocket();
204
+ const connection = socket;
205
+ if (connection.readyState !== connection.OPEN) {
206
+ try {
207
+ await pEvent(connection, "open", {
208
+ rejectionEvents: ["close", "error"],
209
+ signal: request.signal ? AbortSignal.any([lifetime.signal, request.signal]) : lifetime.signal,
210
+ timeout: options.realtimeConnectTimeoutMs ?? 3e4
211
+ });
212
+ } catch (error) {
213
+ lifetime.signal.throwIfAborted();
214
+ request.signal?.throwIfAborted();
215
+ if (ticketError) throw ticketError;
216
+ if (error && typeof error === "object" && "error" in error && error.error instanceof Error)
217
+ throw error.error;
218
+ throw error instanceof Error ? error : new Error("Realtime connection failed.", { cause: error });
219
+ }
220
+ }
221
+ lifetime.signal.throwIfAborted();
222
+ request.signal?.throwIfAborted();
223
+ return link2;
224
+ });
225
+ const api = createORPCClient(link, {
226
+ path: [audience]
227
+ });
228
+ return {
229
+ api,
230
+ dispose() {
231
+ socket?.close(1e3, "Client disposed.");
232
+ lifetime.abort(new DOMException("Client disposed.", "AbortError"));
233
+ options.onConnectionStateChange?.("closed");
234
+ }
235
+ };
236
+ }
237
+
238
+ // src/index.ts
239
+ import { ORPCError } from "@orpc/client";
240
+
241
+ // src/photo-upload.ts
242
+ async function uploadPhoto(uploads, input, fetch = globalThis.fetch) {
243
+ input.signal?.throwIfAborted();
244
+ if (input.body.size < 4 || input.body.size > 10 * 1024 * 1024 || input.body.type && input.body.type.toLowerCase() !== "image/jpeg")
245
+ throw new TypeError("Use an image/jpeg Blob of at most 10 MiB.");
246
+ const bytes = await input.body.arrayBuffer();
247
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
248
+ input.signal?.throwIfAborted();
249
+ const operation = { id: input.id, requestId: input.requestId };
250
+ const session = await uploads.start(
251
+ {
252
+ ...operation,
253
+ kind: input.kind,
254
+ length: bytes.byteLength,
255
+ sha256: Array.from(
256
+ hash,
257
+ (value) => value.toString(16).padStart(2, "0")
258
+ ).join("")
259
+ },
260
+ { signal: input.signal }
261
+ );
262
+ if (session.status === "published") return { photoId: session.photoId };
263
+ if (Date.parse(session.expiresAt) <= Date.now())
264
+ throw new Error(
265
+ "Obtain a current photo upload session before sending bytes."
266
+ );
267
+ const url = new URL(session.url);
268
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || !url.hostname.endsWith(".s3.eu-north-1.amazonaws.com") || !decodeURIComponent(url.pathname).startsWith(
269
+ "/photo-uploads/" + input.id + "/"
270
+ ))
271
+ throw new TypeError(
272
+ "The photo upload session targets an unexpected storage endpoint."
273
+ );
274
+ const uploaded = await fetch(url, {
275
+ method: "PUT",
276
+ body: input.body,
277
+ credentials: "omit",
278
+ redirect: "error",
279
+ signal: input.signal,
280
+ headers: session.headers
281
+ });
282
+ if (!uploaded.ok && uploaded.status !== 412)
283
+ throw new Error(
284
+ "The private photo upload failed (" + uploaded.status + "). Retry with the same request ID."
285
+ );
286
+ return uploads.complete(operation, { signal: input.signal });
287
+ }
288
+
289
+ // src/index.ts
290
+ function createBikeFinderClient(options) {
291
+ const client = createApiClient(customerContract, "customer", options);
292
+ const uploads = new AbortController();
293
+ return {
294
+ ...client,
295
+ uploadPhoto: (input) => uploadPhoto(
296
+ client.api.trackers.photos.uploads,
297
+ {
298
+ ...input,
299
+ signal: AbortSignal.any([
300
+ uploads.signal,
301
+ ...input.signal ? [input.signal] : []
302
+ ])
303
+ },
304
+ options.fetch
305
+ ),
306
+ dispose() {
307
+ uploads.abort();
308
+ client.dispose();
309
+ }
310
+ };
68
311
  }
69
- export { acquisitionDefinition } from "./acquisition-schema.js";
70
- export { observationValueSchema, observationDefinitions, settingsValueSchema, } from "./device-schema.js";
312
+ export {
313
+ ORPCError,
314
+ account,
315
+ accountPreferencePatch,
316
+ accountPreferences,
317
+ batteryObservation,
318
+ bikeChanges,
319
+ bikeEditInput,
320
+ bluetoothContract,
321
+ bluetoothCredentials,
322
+ bluetoothPin,
323
+ bluetoothPinChange,
324
+ createBikeFinderClient,
325
+ customerContract,
326
+ directoryProfile,
327
+ downloadReference,
328
+ factoryResetReport,
329
+ firmwareAppInput,
330
+ firmwareAvailability,
331
+ firmwareClientReport,
332
+ firmwareReportInput,
333
+ firmwareReportOutcome,
334
+ firmwareTransfer,
335
+ firmwareUpdateInput,
336
+ gen1FirmwareContract,
337
+ historyContract,
338
+ historyCursor,
339
+ historyEntry,
340
+ historyInput,
341
+ historyPage,
342
+ inboxContract,
343
+ inboxPage,
344
+ inboxPageInput,
345
+ invitationInput,
346
+ invitationRedeemInput,
347
+ locationObservation,
348
+ membershipName,
349
+ migratedSession,
350
+ notification,
351
+ notificationSource,
352
+ photo,
353
+ photoDownloadInput,
354
+ photoInput,
355
+ photoPage,
356
+ photoPageInput,
357
+ photoUploadContract,
358
+ photoUploadInput,
359
+ photoUploadSession,
360
+ photoUploadStartInput,
361
+ pushContract,
362
+ pushRegistrationInput,
363
+ pushRemovalInput,
364
+ pushToken,
365
+ realtimeContract,
366
+ realtimeTicket,
367
+ startFirmwareUpdate,
368
+ subscription,
369
+ subscriptionAllocationContract,
370
+ subscriptionAllocationInput,
371
+ subscriptionContract,
372
+ subscriptionPage,
373
+ theftContract,
374
+ theftSubmission,
375
+ trackerAdmission,
376
+ trackerChangeContract,
377
+ trackerClaimInput,
378
+ trackerFirmwareRelease,
379
+ trackerFirmwareReleases,
380
+ trackerFirmwareUpdate,
381
+ trackerInvitation,
382
+ trackerInvitationContract,
383
+ trackerLookupContract,
384
+ trackerLookupInput,
385
+ trackerMemberAddInput,
386
+ trackerMemberInput,
387
+ trackerMovementAlertsInput,
388
+ trackerPhotoContract,
389
+ uploadPhoto
390
+ };