@omirion/orbit-sdk 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1684 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __export = (target, all) => {
5
+ for (var name in all)
6
+ __defProp(target, name, { get: all[name], enumerable: true });
7
+ };
8
+
9
+ // src/generated/core/bodySerializer.gen.ts
10
+ var serializeFormDataPair = (data, key, value) => {
11
+ if (typeof value === "string" || value instanceof Blob) {
12
+ data.append(key, value);
13
+ } else if (value instanceof Date) {
14
+ data.append(key, value.toISOString());
15
+ } else {
16
+ data.append(key, JSON.stringify(value));
17
+ }
18
+ };
19
+ var formDataBodySerializer = {
20
+ bodySerializer: (body) => {
21
+ const data = new FormData();
22
+ Object.entries(body).forEach(([key, value]) => {
23
+ if (value === void 0 || value === null) {
24
+ return;
25
+ }
26
+ if (Array.isArray(value)) {
27
+ value.forEach((v) => serializeFormDataPair(data, key, v));
28
+ } else {
29
+ serializeFormDataPair(data, key, value);
30
+ }
31
+ });
32
+ return data;
33
+ }
34
+ };
35
+ var jsonBodySerializer = {
36
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
37
+ };
38
+
39
+ // src/generated/core/serverSentEvents.gen.ts
40
+ function createSseClient({
41
+ onRequest,
42
+ onSseError,
43
+ onSseEvent,
44
+ responseTransformer,
45
+ responseValidator,
46
+ sseDefaultRetryDelay,
47
+ sseMaxRetryAttempts,
48
+ sseMaxRetryDelay,
49
+ sseSleepFn,
50
+ url,
51
+ ...options
52
+ }) {
53
+ let lastEventId;
54
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
55
+ const createStream = async function* () {
56
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
57
+ let attempt = 0;
58
+ const signal = options.signal ?? new AbortController().signal;
59
+ while (true) {
60
+ if (signal.aborted) break;
61
+ attempt++;
62
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
63
+ if (lastEventId !== void 0) {
64
+ headers.set("Last-Event-ID", lastEventId);
65
+ }
66
+ try {
67
+ const requestInit = {
68
+ redirect: "follow",
69
+ ...options,
70
+ body: options.serializedBody,
71
+ headers,
72
+ signal
73
+ };
74
+ let request = new Request(url, requestInit);
75
+ if (onRequest) {
76
+ request = await onRequest(url, requestInit);
77
+ }
78
+ const _fetch = options.fetch ?? globalThis.fetch;
79
+ const response = await _fetch(request);
80
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
81
+ if (!response.body) throw new Error("No body in SSE response");
82
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
83
+ let buffer = "";
84
+ const abortHandler = () => {
85
+ try {
86
+ reader.cancel();
87
+ } catch {
88
+ }
89
+ };
90
+ signal.addEventListener("abort", abortHandler);
91
+ try {
92
+ while (true) {
93
+ const { done, value } = await reader.read();
94
+ if (done) break;
95
+ buffer += value;
96
+ buffer = buffer.replace(/\r\n?/g, "\n");
97
+ const chunks = buffer.split("\n\n");
98
+ buffer = chunks.pop() ?? "";
99
+ for (const chunk of chunks) {
100
+ const lines = chunk.split("\n");
101
+ const dataLines = [];
102
+ let eventName;
103
+ for (const line of lines) {
104
+ if (line.startsWith("data:")) {
105
+ dataLines.push(line.replace(/^data:\s*/, ""));
106
+ } else if (line.startsWith("event:")) {
107
+ eventName = line.replace(/^event:\s*/, "");
108
+ } else if (line.startsWith("id:")) {
109
+ lastEventId = line.replace(/^id:\s*/, "");
110
+ } else if (line.startsWith("retry:")) {
111
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
112
+ if (!Number.isNaN(parsed)) {
113
+ retryDelay = parsed;
114
+ }
115
+ }
116
+ }
117
+ let data;
118
+ let parsedJson = false;
119
+ if (dataLines.length) {
120
+ const rawData = dataLines.join("\n");
121
+ try {
122
+ data = JSON.parse(rawData);
123
+ parsedJson = true;
124
+ } catch {
125
+ data = rawData;
126
+ }
127
+ }
128
+ if (parsedJson) {
129
+ if (responseValidator) {
130
+ await responseValidator(data);
131
+ }
132
+ if (responseTransformer) {
133
+ data = await responseTransformer(data);
134
+ }
135
+ }
136
+ onSseEvent?.({
137
+ data,
138
+ event: eventName,
139
+ id: lastEventId,
140
+ retry: retryDelay
141
+ });
142
+ if (dataLines.length) {
143
+ yield data;
144
+ }
145
+ }
146
+ }
147
+ } finally {
148
+ signal.removeEventListener("abort", abortHandler);
149
+ reader.releaseLock();
150
+ }
151
+ break;
152
+ } catch (error) {
153
+ onSseError?.(error);
154
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
155
+ break;
156
+ }
157
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
158
+ await sleep(backoff);
159
+ }
160
+ }
161
+ };
162
+ const stream = createStream();
163
+ return { stream };
164
+ }
165
+
166
+ // src/generated/core/pathSerializer.gen.ts
167
+ var separatorArrayExplode = (style) => {
168
+ switch (style) {
169
+ case "label":
170
+ return ".";
171
+ case "matrix":
172
+ return ";";
173
+ case "simple":
174
+ return ",";
175
+ default:
176
+ return "&";
177
+ }
178
+ };
179
+ var separatorArrayNoExplode = (style) => {
180
+ switch (style) {
181
+ case "form":
182
+ return ",";
183
+ case "pipeDelimited":
184
+ return "|";
185
+ case "spaceDelimited":
186
+ return "%20";
187
+ default:
188
+ return ",";
189
+ }
190
+ };
191
+ var separatorObjectExplode = (style) => {
192
+ switch (style) {
193
+ case "label":
194
+ return ".";
195
+ case "matrix":
196
+ return ";";
197
+ case "simple":
198
+ return ",";
199
+ default:
200
+ return "&";
201
+ }
202
+ };
203
+ var serializeArrayParam = ({
204
+ allowReserved,
205
+ explode,
206
+ name,
207
+ style,
208
+ value
209
+ }) => {
210
+ if (!explode) {
211
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
212
+ switch (style) {
213
+ case "label":
214
+ return `.${joinedValues2}`;
215
+ case "matrix":
216
+ return `;${name}=${joinedValues2}`;
217
+ case "simple":
218
+ return joinedValues2;
219
+ default:
220
+ return `${name}=${joinedValues2}`;
221
+ }
222
+ }
223
+ const separator = separatorArrayExplode(style);
224
+ const joinedValues = value.map((v) => {
225
+ if (style === "label" || style === "simple") {
226
+ return allowReserved ? v : encodeURIComponent(v);
227
+ }
228
+ return serializePrimitiveParam({
229
+ allowReserved,
230
+ name,
231
+ value: v
232
+ });
233
+ }).join(separator);
234
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
235
+ };
236
+ var serializePrimitiveParam = ({
237
+ allowReserved,
238
+ name,
239
+ value
240
+ }) => {
241
+ if (value === void 0 || value === null) {
242
+ return "";
243
+ }
244
+ if (typeof value === "object") {
245
+ throw new Error(
246
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
247
+ );
248
+ }
249
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
250
+ };
251
+ var serializeObjectParam = ({
252
+ allowReserved,
253
+ explode,
254
+ name,
255
+ style,
256
+ value,
257
+ valueOnly
258
+ }) => {
259
+ if (value instanceof Date) {
260
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
261
+ }
262
+ if (style !== "deepObject" && !explode) {
263
+ let values = [];
264
+ Object.entries(value).forEach(([key, v]) => {
265
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
266
+ });
267
+ const joinedValues2 = values.join(",");
268
+ switch (style) {
269
+ case "form":
270
+ return `${name}=${joinedValues2}`;
271
+ case "label":
272
+ return `.${joinedValues2}`;
273
+ case "matrix":
274
+ return `;${name}=${joinedValues2}`;
275
+ default:
276
+ return joinedValues2;
277
+ }
278
+ }
279
+ const separator = separatorObjectExplode(style);
280
+ const joinedValues = Object.entries(value).map(
281
+ ([key, v]) => serializePrimitiveParam({
282
+ allowReserved,
283
+ name: style === "deepObject" ? `${name}[${key}]` : key,
284
+ value: v
285
+ })
286
+ ).join(separator);
287
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
288
+ };
289
+
290
+ // src/generated/core/utils.gen.ts
291
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
292
+ var defaultPathSerializer = ({ path, url: _url }) => {
293
+ let url = _url;
294
+ const matches = _url.match(PATH_PARAM_RE);
295
+ if (matches) {
296
+ for (const match of matches) {
297
+ let explode = false;
298
+ let name = match.substring(1, match.length - 1);
299
+ let style = "simple";
300
+ if (name.endsWith("*")) {
301
+ explode = true;
302
+ name = name.substring(0, name.length - 1);
303
+ }
304
+ if (name.startsWith(".")) {
305
+ name = name.substring(1);
306
+ style = "label";
307
+ } else if (name.startsWith(";")) {
308
+ name = name.substring(1);
309
+ style = "matrix";
310
+ }
311
+ const value = path[name];
312
+ if (value === void 0 || value === null) {
313
+ continue;
314
+ }
315
+ if (Array.isArray(value)) {
316
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
317
+ continue;
318
+ }
319
+ if (typeof value === "object") {
320
+ url = url.replace(
321
+ match,
322
+ serializeObjectParam({
323
+ explode,
324
+ name,
325
+ style,
326
+ value,
327
+ valueOnly: true
328
+ })
329
+ );
330
+ continue;
331
+ }
332
+ if (style === "matrix") {
333
+ url = url.replace(
334
+ match,
335
+ `;${serializePrimitiveParam({
336
+ name,
337
+ value
338
+ })}`
339
+ );
340
+ continue;
341
+ }
342
+ const replaceValue = encodeURIComponent(
343
+ style === "label" ? `.${value}` : value
344
+ );
345
+ url = url.replace(match, replaceValue);
346
+ }
347
+ }
348
+ return url;
349
+ };
350
+ var getUrl = ({
351
+ baseUrl,
352
+ path,
353
+ query,
354
+ querySerializer,
355
+ url: _url
356
+ }) => {
357
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
358
+ let url = (baseUrl ?? "") + pathUrl;
359
+ if (path) {
360
+ url = defaultPathSerializer({ path, url });
361
+ }
362
+ let search = query ? querySerializer(query) : "";
363
+ if (search.startsWith("?")) {
364
+ search = search.substring(1);
365
+ }
366
+ if (search) {
367
+ url += `?${search}`;
368
+ }
369
+ return url;
370
+ };
371
+ function getValidRequestBody(options) {
372
+ const hasBody = options.body !== void 0;
373
+ const isSerializedBody = hasBody && options.bodySerializer;
374
+ if (isSerializedBody) {
375
+ if ("serializedBody" in options) {
376
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
377
+ return hasSerializedBody ? options.serializedBody : null;
378
+ }
379
+ return options.body !== "" ? options.body : null;
380
+ }
381
+ if (hasBody) {
382
+ return options.body;
383
+ }
384
+ return void 0;
385
+ }
386
+
387
+ // src/generated/core/auth.gen.ts
388
+ var getAuthToken = async (auth, callback) => {
389
+ const token = typeof callback === "function" ? await callback(auth) : callback;
390
+ if (!token) {
391
+ return;
392
+ }
393
+ if (auth.scheme === "bearer") {
394
+ return `Bearer ${token}`;
395
+ }
396
+ if (auth.scheme === "basic") {
397
+ return `Basic ${btoa(token)}`;
398
+ }
399
+ return token;
400
+ };
401
+
402
+ // src/generated/client/utils.gen.ts
403
+ var createQuerySerializer = ({
404
+ parameters = {},
405
+ ...args
406
+ } = {}) => {
407
+ const querySerializer = (queryParams) => {
408
+ const search = [];
409
+ if (queryParams && typeof queryParams === "object") {
410
+ for (const name in queryParams) {
411
+ const value = queryParams[name];
412
+ if (value === void 0 || value === null) {
413
+ continue;
414
+ }
415
+ const options = parameters[name] || args;
416
+ if (Array.isArray(value)) {
417
+ const serializedArray = serializeArrayParam({
418
+ allowReserved: options.allowReserved,
419
+ explode: true,
420
+ name,
421
+ style: "form",
422
+ value,
423
+ ...options.array
424
+ });
425
+ if (serializedArray) search.push(serializedArray);
426
+ } else if (typeof value === "object") {
427
+ const serializedObject = serializeObjectParam({
428
+ allowReserved: options.allowReserved,
429
+ explode: true,
430
+ name,
431
+ style: "deepObject",
432
+ value,
433
+ ...options.object
434
+ });
435
+ if (serializedObject) search.push(serializedObject);
436
+ } else {
437
+ const serializedPrimitive = serializePrimitiveParam({
438
+ allowReserved: options.allowReserved,
439
+ name,
440
+ value
441
+ });
442
+ if (serializedPrimitive) search.push(serializedPrimitive);
443
+ }
444
+ }
445
+ }
446
+ return search.join("&");
447
+ };
448
+ return querySerializer;
449
+ };
450
+ var getParseAs = (contentType) => {
451
+ if (!contentType) {
452
+ return "stream";
453
+ }
454
+ const cleanContent = contentType.split(";")[0]?.trim();
455
+ if (!cleanContent) {
456
+ return;
457
+ }
458
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
459
+ return "json";
460
+ }
461
+ if (cleanContent === "multipart/form-data") {
462
+ return "formData";
463
+ }
464
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
465
+ return "blob";
466
+ }
467
+ if (cleanContent.startsWith("text/")) {
468
+ return "text";
469
+ }
470
+ return;
471
+ };
472
+ var checkForExistence = (options, name) => {
473
+ if (!name) {
474
+ return false;
475
+ }
476
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
477
+ return true;
478
+ }
479
+ return false;
480
+ };
481
+ async function setAuthParams(options) {
482
+ for (const auth of options.security ?? []) {
483
+ if (checkForExistence(options, auth.name)) {
484
+ continue;
485
+ }
486
+ const token = await getAuthToken(auth, options.auth);
487
+ if (!token) {
488
+ continue;
489
+ }
490
+ const name = auth.name ?? "Authorization";
491
+ switch (auth.in) {
492
+ case "query":
493
+ if (!options.query) {
494
+ options.query = {};
495
+ }
496
+ options.query[name] = token;
497
+ break;
498
+ case "cookie":
499
+ options.headers.append("Cookie", `${name}=${token}`);
500
+ break;
501
+ case "header":
502
+ default:
503
+ options.headers.set(name, token);
504
+ break;
505
+ }
506
+ }
507
+ }
508
+ var buildUrl = (options) => getUrl({
509
+ baseUrl: options.baseUrl,
510
+ path: options.path,
511
+ query: options.query,
512
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
513
+ url: options.url
514
+ });
515
+ var mergeConfigs = (a, b) => {
516
+ const config = { ...a, ...b };
517
+ if (config.baseUrl?.endsWith("/")) {
518
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
519
+ }
520
+ config.headers = mergeHeaders(a.headers, b.headers);
521
+ return config;
522
+ };
523
+ var headersEntries = (headers) => {
524
+ const entries = [];
525
+ headers.forEach((value, key) => {
526
+ entries.push([key, value]);
527
+ });
528
+ return entries;
529
+ };
530
+ var mergeHeaders = (...headers) => {
531
+ const mergedHeaders = new Headers();
532
+ for (const header of headers) {
533
+ if (!header) {
534
+ continue;
535
+ }
536
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
537
+ for (const [key, value] of iterator) {
538
+ if (value === null) {
539
+ mergedHeaders.delete(key);
540
+ } else if (Array.isArray(value)) {
541
+ for (const v of value) {
542
+ mergedHeaders.append(key, v);
543
+ }
544
+ } else if (value !== void 0) {
545
+ mergedHeaders.set(
546
+ key,
547
+ typeof value === "object" ? JSON.stringify(value) : value
548
+ );
549
+ }
550
+ }
551
+ }
552
+ return mergedHeaders;
553
+ };
554
+ var Interceptors = class {
555
+ fns = [];
556
+ clear() {
557
+ this.fns = [];
558
+ }
559
+ eject(id) {
560
+ const index = this.getInterceptorIndex(id);
561
+ if (this.fns[index]) {
562
+ this.fns[index] = null;
563
+ }
564
+ }
565
+ exists(id) {
566
+ const index = this.getInterceptorIndex(id);
567
+ return Boolean(this.fns[index]);
568
+ }
569
+ getInterceptorIndex(id) {
570
+ if (typeof id === "number") {
571
+ return this.fns[id] ? id : -1;
572
+ }
573
+ return this.fns.indexOf(id);
574
+ }
575
+ update(id, fn) {
576
+ const index = this.getInterceptorIndex(id);
577
+ if (this.fns[index]) {
578
+ this.fns[index] = fn;
579
+ return id;
580
+ }
581
+ return false;
582
+ }
583
+ use(fn) {
584
+ this.fns.push(fn);
585
+ return this.fns.length - 1;
586
+ }
587
+ };
588
+ var createInterceptors = () => ({
589
+ error: new Interceptors(),
590
+ request: new Interceptors(),
591
+ response: new Interceptors()
592
+ });
593
+ var defaultQuerySerializer = createQuerySerializer({
594
+ allowReserved: false,
595
+ array: {
596
+ explode: true,
597
+ style: "form"
598
+ },
599
+ object: {
600
+ explode: true,
601
+ style: "deepObject"
602
+ }
603
+ });
604
+ var defaultHeaders = {
605
+ "Content-Type": "application/json"
606
+ };
607
+ var createConfig = (override = {}) => ({
608
+ ...jsonBodySerializer,
609
+ headers: defaultHeaders,
610
+ parseAs: "auto",
611
+ querySerializer: defaultQuerySerializer,
612
+ ...override
613
+ });
614
+
615
+ // src/generated/client/client.gen.ts
616
+ var createClient = (config = {}) => {
617
+ let _config = mergeConfigs(createConfig(), config);
618
+ const getConfig = () => ({ ..._config });
619
+ const setConfig = (config2) => {
620
+ _config = mergeConfigs(_config, config2);
621
+ return getConfig();
622
+ };
623
+ const interceptors = createInterceptors();
624
+ const beforeRequest = async (options) => {
625
+ const opts = {
626
+ ..._config,
627
+ ...options,
628
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
629
+ headers: mergeHeaders(_config.headers, options.headers),
630
+ serializedBody: void 0
631
+ };
632
+ if (opts.security) {
633
+ await setAuthParams(opts);
634
+ }
635
+ if (opts.requestValidator) {
636
+ await opts.requestValidator(opts);
637
+ }
638
+ if (opts.body !== void 0 && opts.bodySerializer) {
639
+ opts.serializedBody = opts.bodySerializer(opts.body);
640
+ }
641
+ if (opts.body === void 0 || opts.serializedBody === "") {
642
+ opts.headers.delete("Content-Type");
643
+ }
644
+ const resolvedOpts = opts;
645
+ const url = buildUrl(resolvedOpts);
646
+ return { opts: resolvedOpts, url };
647
+ };
648
+ const request = async (options) => {
649
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
650
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
651
+ let request2;
652
+ let response;
653
+ try {
654
+ const { opts, url } = await beforeRequest(options);
655
+ const requestInit = {
656
+ redirect: "follow",
657
+ ...opts,
658
+ body: getValidRequestBody(opts)
659
+ };
660
+ request2 = new Request(url, requestInit);
661
+ for (const fn of interceptors.request.fns) {
662
+ if (fn) {
663
+ request2 = await fn(request2, opts);
664
+ }
665
+ }
666
+ const _fetch = opts.fetch;
667
+ response = await _fetch(request2);
668
+ for (const fn of interceptors.response.fns) {
669
+ if (fn) {
670
+ response = await fn(response, request2, opts);
671
+ }
672
+ }
673
+ const result = {
674
+ request: request2,
675
+ response
676
+ };
677
+ if (response.ok) {
678
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
679
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
680
+ let emptyData;
681
+ switch (parseAs) {
682
+ case "arrayBuffer":
683
+ case "blob":
684
+ case "text":
685
+ emptyData = await response[parseAs]();
686
+ break;
687
+ case "formData":
688
+ emptyData = new FormData();
689
+ break;
690
+ case "stream":
691
+ emptyData = response.body;
692
+ break;
693
+ case "json":
694
+ default:
695
+ emptyData = {};
696
+ break;
697
+ }
698
+ return opts.responseStyle === "data" ? emptyData : {
699
+ data: emptyData,
700
+ ...result
701
+ };
702
+ }
703
+ let data;
704
+ switch (parseAs) {
705
+ case "arrayBuffer":
706
+ case "blob":
707
+ case "formData":
708
+ case "text":
709
+ data = await response[parseAs]();
710
+ break;
711
+ case "json": {
712
+ const text = await response.text();
713
+ data = text ? JSON.parse(text) : {};
714
+ break;
715
+ }
716
+ case "stream":
717
+ return opts.responseStyle === "data" ? response.body : {
718
+ data: response.body,
719
+ ...result
720
+ };
721
+ }
722
+ if (parseAs === "json") {
723
+ if (opts.responseValidator) {
724
+ await opts.responseValidator(data);
725
+ }
726
+ if (opts.responseTransformer) {
727
+ data = await opts.responseTransformer(data);
728
+ }
729
+ }
730
+ return opts.responseStyle === "data" ? data : {
731
+ data,
732
+ ...result
733
+ };
734
+ }
735
+ const textError = await response.text();
736
+ let jsonError;
737
+ try {
738
+ jsonError = JSON.parse(textError);
739
+ } catch {
740
+ }
741
+ throw jsonError ?? textError;
742
+ } catch (error) {
743
+ let finalError = error;
744
+ for (const fn of interceptors.error.fns) {
745
+ if (fn) {
746
+ finalError = await fn(finalError, response, request2, options);
747
+ }
748
+ }
749
+ finalError = finalError || {};
750
+ if (throwOnError) {
751
+ throw finalError;
752
+ }
753
+ return responseStyle === "data" ? void 0 : {
754
+ error: finalError,
755
+ request: request2,
756
+ response
757
+ };
758
+ }
759
+ };
760
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
761
+ const makeSseFn = (method) => async (options) => {
762
+ const { opts, url } = await beforeRequest(options);
763
+ return createSseClient({
764
+ ...opts,
765
+ body: opts.body,
766
+ method,
767
+ onRequest: async (url2, init) => {
768
+ let request2 = new Request(url2, init);
769
+ for (const fn of interceptors.request.fns) {
770
+ if (fn) {
771
+ request2 = await fn(request2, opts);
772
+ }
773
+ }
774
+ return request2;
775
+ },
776
+ serializedBody: getValidRequestBody(opts),
777
+ url
778
+ });
779
+ };
780
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
781
+ return {
782
+ buildUrl: _buildUrl,
783
+ connect: makeMethodFn("CONNECT"),
784
+ delete: makeMethodFn("DELETE"),
785
+ get: makeMethodFn("GET"),
786
+ getConfig,
787
+ head: makeMethodFn("HEAD"),
788
+ interceptors,
789
+ options: makeMethodFn("OPTIONS"),
790
+ patch: makeMethodFn("PATCH"),
791
+ post: makeMethodFn("POST"),
792
+ put: makeMethodFn("PUT"),
793
+ request,
794
+ setConfig,
795
+ sse: {
796
+ connect: makeSseFn("CONNECT"),
797
+ delete: makeSseFn("DELETE"),
798
+ get: makeSseFn("GET"),
799
+ head: makeSseFn("HEAD"),
800
+ options: makeSseFn("OPTIONS"),
801
+ patch: makeSseFn("PATCH"),
802
+ post: makeSseFn("POST"),
803
+ put: makeSseFn("PUT"),
804
+ trace: makeSseFn("TRACE")
805
+ },
806
+ trace: makeMethodFn("TRACE")
807
+ };
808
+ };
809
+
810
+ // src/generated/client.gen.ts
811
+ var client = createClient(createConfig({ baseUrl: "https://orbit.omirion.com" }));
812
+
813
+ // src/generated/sdk.gen.ts
814
+ var getIdentity = (options) => (options?.client ?? client).get({
815
+ security: [{ scheme: "bearer", type: "http" }],
816
+ url: "/api/v1/me",
817
+ ...options
818
+ });
819
+ var listProjects = (options) => (options?.client ?? client).get({
820
+ security: [{ scheme: "bearer", type: "http" }],
821
+ url: "/api/v1/projects",
822
+ ...options
823
+ });
824
+ var getProject = (options) => (options.client ?? client).get({
825
+ security: [{ scheme: "bearer", type: "http" }],
826
+ url: "/api/v1/projects/{id}",
827
+ ...options
828
+ });
829
+ var createProjectAppToken = (options) => (options.client ?? client).post({
830
+ security: [{ scheme: "bearer", type: "http" }],
831
+ url: "/api/v1/projects/{id}/app-token",
832
+ ...options
833
+ });
834
+ var rotateProjectAppToken = (options) => (options.client ?? client).post({
835
+ security: [{ scheme: "bearer", type: "http" }],
836
+ url: "/api/v1/projects/{id}/app-token/rotate",
837
+ ...options
838
+ });
839
+ var listDevices = (options) => (options?.client ?? client).get({
840
+ security: [{ scheme: "bearer", type: "http" }],
841
+ url: "/api/v1/devices",
842
+ ...options
843
+ });
844
+ var deleteDevice = (options) => (options.client ?? client).delete({
845
+ security: [{ scheme: "bearer", type: "http" }],
846
+ url: "/api/v1/devices/{id}",
847
+ ...options
848
+ });
849
+ var getDevice = (options) => (options.client ?? client).get({
850
+ security: [{ scheme: "bearer", type: "http" }],
851
+ url: "/api/v1/devices/{id}",
852
+ ...options
853
+ });
854
+ var resetDeviceToken = (options) => (options.client ?? client).post({
855
+ security: [{ scheme: "bearer", type: "http" }],
856
+ url: "/api/v1/devices/{id}/token/reset",
857
+ ...options
858
+ });
859
+ var getLatestTelemetry = (options) => (options.client ?? client).get({
860
+ security: [{ scheme: "bearer", type: "http" }],
861
+ url: "/api/v1/devices/{id}/telemetry/latest",
862
+ ...options
863
+ });
864
+ var getTelemetryHistory = (options) => (options.client ?? client).get({
865
+ security: [{ scheme: "bearer", type: "http" }],
866
+ url: "/api/v1/devices/{id}/telemetry",
867
+ ...options
868
+ });
869
+ var getTelemetryManifest = (options) => (options.client ?? client).get({
870
+ security: [{ scheme: "bearer", type: "http" }],
871
+ url: "/api/v1/devices/{id}/telemetry/manifest",
872
+ ...options
873
+ });
874
+ var listAdmissions = (options) => (options?.client ?? client).get({
875
+ security: [{ scheme: "bearer", type: "http" }],
876
+ url: "/api/v1/admissions",
877
+ ...options
878
+ });
879
+ var getAdmission = (options) => (options.client ?? client).get({
880
+ security: [{ scheme: "bearer", type: "http" }],
881
+ url: "/api/v1/admissions/{id}",
882
+ ...options
883
+ });
884
+ var acceptAdmission = (options) => (options.client ?? client).post({
885
+ security: [{ scheme: "bearer", type: "http" }],
886
+ url: "/api/v1/admissions/{id}/accept",
887
+ ...options,
888
+ headers: {
889
+ "Content-Type": "application/json",
890
+ ...options.headers
891
+ }
892
+ });
893
+ var rejectAdmission = (options) => (options.client ?? client).post({
894
+ security: [{ scheme: "bearer", type: "http" }],
895
+ url: "/api/v1/admissions/{id}/reject",
896
+ ...options
897
+ });
898
+ var dismissAdmission = (options) => (options.client ?? client).post({
899
+ security: [{ scheme: "bearer", type: "http" }],
900
+ url: "/api/v1/admissions/{id}/dismiss",
901
+ ...options
902
+ });
903
+ var uploadFirmware = (options) => (options?.client ?? client).post({
904
+ ...formDataBodySerializer,
905
+ security: [{ scheme: "bearer", type: "http" }],
906
+ url: "/api/v1/firmware/upload",
907
+ ...options,
908
+ headers: {
909
+ "Content-Type": null,
910
+ ...options?.headers
911
+ }
912
+ });
913
+ var listFirmwareBundles = (options) => (options?.client ?? client).get({
914
+ security: [{ scheme: "bearer", type: "http" }],
915
+ url: "/api/v1/firmware/bundles",
916
+ ...options
917
+ });
918
+ var deleteFirmwareBundle = (options) => (options.client ?? client).delete({
919
+ security: [{ scheme: "bearer", type: "http" }],
920
+ url: "/api/v1/firmware/bundles/{id}",
921
+ ...options
922
+ });
923
+ var getFirmwareBundle = (options) => (options.client ?? client).get({
924
+ security: [{ scheme: "bearer", type: "http" }],
925
+ url: "/api/v1/firmware/bundles/{id}",
926
+ ...options
927
+ });
928
+ var listFirmwareDeployments = (options) => (options?.client ?? client).get({
929
+ security: [{ scheme: "bearer", type: "http" }],
930
+ url: "/api/v1/firmware/deployments",
931
+ ...options
932
+ });
933
+ var triggerFirmwareDeployment = (options) => (options?.client ?? client).post({
934
+ security: [{ scheme: "bearer", type: "http" }],
935
+ url: "/api/v1/firmware/deployments",
936
+ ...options,
937
+ headers: {
938
+ "Content-Type": "application/json",
939
+ ...options?.headers
940
+ }
941
+ });
942
+ var getFirmwareDeployment = (options) => (options.client ?? client).get({
943
+ security: [{ scheme: "bearer", type: "http" }],
944
+ url: "/api/v1/firmware/deployments/{id}",
945
+ ...options
946
+ });
947
+ var cancelFirmwareDeployment = (options) => (options.client ?? client).post({
948
+ security: [{ scheme: "bearer", type: "http" }],
949
+ url: "/api/v1/firmware/deployments/{id}/cancel",
950
+ ...options,
951
+ headers: {
952
+ "Content-Type": "application/json",
953
+ ...options.headers
954
+ }
955
+ });
956
+ var rollbackFirmwareDeployment = (options) => (options.client ?? client).post({
957
+ security: [{ scheme: "bearer", type: "http" }],
958
+ url: "/api/v1/firmware/deployments/{id}/rollback",
959
+ ...options,
960
+ headers: {
961
+ "Content-Type": "application/json",
962
+ ...options.headers
963
+ }
964
+ });
965
+ var execDeviceCommand = (options) => (options.client ?? client).post({
966
+ security: [{ scheme: "bearer", type: "http" }],
967
+ url: "/api/v1/devices/{id}/command",
968
+ ...options,
969
+ headers: {
970
+ "Content-Type": "application/json",
971
+ ...options.headers
972
+ }
973
+ });
974
+ var getDeviceCommandInvocation = (options) => (options.client ?? client).get({
975
+ security: [{ scheme: "bearer", type: "http" }],
976
+ url: "/api/v1/devices/{id}/commands/{invocationId}",
977
+ ...options
978
+ });
979
+ var getDeviceCommands = (options) => (options.client ?? client).get({
980
+ security: [{ scheme: "bearer", type: "http" }],
981
+ url: "/api/v1/devices/{id}/commands",
982
+ ...options
983
+ });
984
+ var deleteCommandManifest = (options) => (options.client ?? client).delete({
985
+ security: [{ scheme: "bearer", type: "http" }],
986
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
987
+ ...options
988
+ });
989
+ var getCommandManifest = (options) => (options.client ?? client).get({
990
+ security: [{ scheme: "bearer", type: "http" }],
991
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
992
+ ...options
993
+ });
994
+ var updateCommandManifest = (options) => (options.client ?? client).put({
995
+ security: [{ scheme: "bearer", type: "http" }],
996
+ url: "/api/v1/projects/{projectId}/device-types/{slug}/commands",
997
+ ...options,
998
+ headers: {
999
+ "Content-Type": "application/json",
1000
+ ...options.headers
1001
+ }
1002
+ });
1003
+ var listDeviceTypes = (options) => (options.client ?? client).get({
1004
+ security: [{ scheme: "bearer", type: "http" }],
1005
+ url: "/api/v1/projects/{projectId}/device-types",
1006
+ ...options
1007
+ });
1008
+ var createDeviceType = (options) => (options.client ?? client).post({
1009
+ security: [{ scheme: "bearer", type: "http" }],
1010
+ url: "/api/v1/projects/{projectId}/device-types",
1011
+ ...options,
1012
+ headers: {
1013
+ "Content-Type": "application/json",
1014
+ ...options.headers
1015
+ }
1016
+ });
1017
+ var deleteDeviceType = (options) => (options.client ?? client).delete({
1018
+ security: [{ scheme: "bearer", type: "http" }],
1019
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1020
+ ...options
1021
+ });
1022
+ var getDeviceType = (options) => (options.client ?? client).get({
1023
+ security: [{ scheme: "bearer", type: "http" }],
1024
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1025
+ ...options
1026
+ });
1027
+ var updateDeviceType = (options) => (options.client ?? client).patch({
1028
+ security: [{ scheme: "bearer", type: "http" }],
1029
+ url: "/api/v1/projects/{projectId}/device-types/{slug}",
1030
+ ...options,
1031
+ headers: {
1032
+ "Content-Type": "application/json",
1033
+ ...options.headers
1034
+ }
1035
+ });
1036
+ var listWebhooks = (options) => (options?.client ?? client).get({
1037
+ security: [{ scheme: "bearer", type: "http" }],
1038
+ url: "/api/v1/webhooks",
1039
+ ...options
1040
+ });
1041
+ var createWebhook = (options) => (options?.client ?? client).post({
1042
+ security: [{ scheme: "bearer", type: "http" }],
1043
+ url: "/api/v1/webhooks",
1044
+ ...options,
1045
+ headers: {
1046
+ "Content-Type": "application/json",
1047
+ ...options?.headers
1048
+ }
1049
+ });
1050
+ var deleteWebhook = (options) => (options.client ?? client).delete({
1051
+ security: [{ scheme: "bearer", type: "http" }],
1052
+ url: "/api/v1/webhooks/{id}",
1053
+ ...options
1054
+ });
1055
+ var getWebhook = (options) => (options.client ?? client).get({
1056
+ security: [{ scheme: "bearer", type: "http" }],
1057
+ url: "/api/v1/webhooks/{id}",
1058
+ ...options
1059
+ });
1060
+ var updateWebhook = (options) => (options.client ?? client).patch({
1061
+ security: [{ scheme: "bearer", type: "http" }],
1062
+ url: "/api/v1/webhooks/{id}",
1063
+ ...options,
1064
+ headers: {
1065
+ "Content-Type": "application/json",
1066
+ ...options.headers
1067
+ }
1068
+ });
1069
+ var listWebhookDeliveries = (options) => (options.client ?? client).get({
1070
+ security: [{ scheme: "bearer", type: "http" }],
1071
+ url: "/api/v1/webhooks/{id}/deliveries",
1072
+ ...options
1073
+ });
1074
+
1075
+ // src/errors.ts
1076
+ var OrbitError = class extends Error {
1077
+ /** HTTP status, when the failure came from a response. */
1078
+ status;
1079
+ /** Stable machine-readable code (e.g. `E_RESOURCE_NOT_FOUND`), when present. */
1080
+ code;
1081
+ /** Offending field for validation errors, when present. */
1082
+ field;
1083
+ /** Raw parsed response body. */
1084
+ body;
1085
+ /** The raw `Response`, when one was received. */
1086
+ response;
1087
+ constructor(message, options = {}) {
1088
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
1089
+ this.name = new.target.name;
1090
+ this.status = options.status;
1091
+ this.code = options.code;
1092
+ this.field = options.field;
1093
+ this.body = options.body;
1094
+ this.response = options.response;
1095
+ }
1096
+ };
1097
+ var AuthenticationError = class extends OrbitError {
1098
+ };
1099
+ var InsufficientScopeError = class extends OrbitError {
1100
+ };
1101
+ var ResourceNotFoundError = class extends OrbitError {
1102
+ };
1103
+ var BadRequestError = class extends OrbitError {
1104
+ };
1105
+ var ValidationError = class extends OrbitError {
1106
+ fieldErrors;
1107
+ constructor(message, options = {}) {
1108
+ super(message, options);
1109
+ this.fieldErrors = options.fieldErrors ?? [];
1110
+ }
1111
+ };
1112
+ var BundleExistsError = class extends OrbitError {
1113
+ };
1114
+ var DeviceRpcError = class extends OrbitError {
1115
+ };
1116
+ var ServerError = class extends OrbitError {
1117
+ };
1118
+ var NetworkError = class extends OrbitError {
1119
+ };
1120
+ var RateLimitError = class extends OrbitError {
1121
+ retryAfterSeconds;
1122
+ constructor(message, options = {}) {
1123
+ super(message, options);
1124
+ this.retryAfterSeconds = options.retryAfterSeconds;
1125
+ }
1126
+ };
1127
+ function extractErrorFields(body) {
1128
+ if (!body || typeof body !== "object") return {};
1129
+ const record = body;
1130
+ if (typeof record.error === "string") {
1131
+ return {
1132
+ code: record.error,
1133
+ message: typeof record.message === "string" ? record.message : record.error
1134
+ };
1135
+ }
1136
+ if (Array.isArray(record.errors) && record.errors.length > 0) {
1137
+ const first = record.errors[0];
1138
+ return {
1139
+ code: typeof first.code === "string" ? first.code : void 0,
1140
+ message: typeof first.message === "string" ? first.message : void 0,
1141
+ field: typeof first.field === "string" ? first.field : first.field === null ? null : void 0
1142
+ };
1143
+ }
1144
+ if (typeof record.message === "string") return { message: record.message };
1145
+ return {};
1146
+ }
1147
+ function extractFieldErrors(body) {
1148
+ if (!body || typeof body !== "object") return [];
1149
+ const { errors } = body;
1150
+ if (!Array.isArray(errors)) return [];
1151
+ return errors.flatMap((entry) => {
1152
+ const record = entry;
1153
+ if (typeof record.message !== "string") return [];
1154
+ return [{ message: record.message, field: typeof record.field === "string" ? record.field : null }];
1155
+ });
1156
+ }
1157
+ var DEFAULT_MESSAGES = {
1158
+ 400: "Bad request.",
1159
+ 401: "Authentication failed.",
1160
+ 403: "The token is missing a required ability.",
1161
+ 404: "Resource not found.",
1162
+ 409: "Conflict.",
1163
+ 422: "Request validation failed.",
1164
+ 429: "Rate limited.",
1165
+ 502: "The device is offline or the command transport failed."
1166
+ };
1167
+ function parseRetryAfterSeconds(response) {
1168
+ const header = response?.headers?.get("retry-after");
1169
+ if (!header) return void 0;
1170
+ const seconds = Number(header);
1171
+ return Number.isFinite(seconds) ? seconds : void 0;
1172
+ }
1173
+ function normalizeError(status, body, response) {
1174
+ const { code, message, field } = extractErrorFields(body);
1175
+ const base = { status, code, field, body, response };
1176
+ const msg = message ?? DEFAULT_MESSAGES[status] ?? `Request failed with status ${status}.`;
1177
+ switch (status) {
1178
+ case 400:
1179
+ return new BadRequestError(msg, base);
1180
+ case 401:
1181
+ return new AuthenticationError(msg, base);
1182
+ case 403:
1183
+ return new InsufficientScopeError(msg, base);
1184
+ case 404:
1185
+ return new ResourceNotFoundError(msg, base);
1186
+ case 409:
1187
+ return new BundleExistsError(msg, base);
1188
+ case 422:
1189
+ return new ValidationError(msg, { ...base, fieldErrors: extractFieldErrors(body) });
1190
+ case 429:
1191
+ return new RateLimitError(msg, { ...base, retryAfterSeconds: parseRetryAfterSeconds(response) });
1192
+ case 502:
1193
+ return new DeviceRpcError(msg, base);
1194
+ default:
1195
+ if (status >= 500) return new ServerError(msg, base);
1196
+ return new OrbitError(msg, base);
1197
+ }
1198
+ }
1199
+
1200
+ // src/pagination.ts
1201
+ async function* paginate(fetchPage) {
1202
+ let cursor;
1203
+ for (; ; ) {
1204
+ const page = await fetchPage(cursor);
1205
+ for (const item of page.data) yield item;
1206
+ if (!page.hasMore || !page.nextCursor) return;
1207
+ cursor = page.nextCursor;
1208
+ }
1209
+ }
1210
+
1211
+ // src/usb.ts
1212
+ var SECURITY = [{ scheme: "bearer", type: "http" }];
1213
+ function listExportable(client2, deviceId) {
1214
+ return client2.get({
1215
+ security: SECURITY,
1216
+ url: `/api/v1/devices/${encodeURIComponent(deviceId)}/usb/exportable`,
1217
+ throwOnError: false
1218
+ });
1219
+ }
1220
+ function createTicket(client2, body) {
1221
+ return client2.post({
1222
+ security: SECURITY,
1223
+ url: "/api/v1/usb/ticket",
1224
+ body,
1225
+ throwOnError: false
1226
+ });
1227
+ }
1228
+
1229
+ // src/terminal.ts
1230
+ var SECURITY2 = [{ scheme: "bearer", type: "http" }];
1231
+ function createTicket2(client2, body) {
1232
+ return client2.post({
1233
+ security: SECURITY2,
1234
+ url: "/api/v1/terminal/ticket",
1235
+ body,
1236
+ throwOnError: false
1237
+ });
1238
+ }
1239
+
1240
+ // src/client.ts
1241
+ var DEFAULT_BASE_URL = "https://orbit.omirion.com";
1242
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 502, 503, 504]);
1243
+ var OrbitClient = class {
1244
+ #client;
1245
+ #maxRetries;
1246
+ #retryBaseDelayMs;
1247
+ /**
1248
+ * Who this token authenticates as, what it may do, and which projects it
1249
+ * reaches. Requires no ability, the cheapest way to verify a token works.
1250
+ */
1251
+ me;
1252
+ /**
1253
+ * Projects as a resource. Requires `api:projects:read`; {@link me} returns
1254
+ * the same ids under no ability.
1255
+ */
1256
+ projects;
1257
+ /**
1258
+ * Device types: the models a fleet identifies as. Reads need
1259
+ * `api:devices:read`; writes need `api:device-types:manage`.
1260
+ */
1261
+ deviceTypes;
1262
+ devices;
1263
+ admissions;
1264
+ telemetry;
1265
+ firmware;
1266
+ commands;
1267
+ /**
1268
+ * USB/IP passthrough. Requires the `api:usb:attach` ability, which grants raw
1269
+ * USB access to whatever hardware is attached to the device, so treat a token
1270
+ * carrying it accordingly.
1271
+ *
1272
+ * Hand-written rather than generated; see `usb.ts` for why.
1273
+ */
1274
+ usb;
1275
+ /**
1276
+ * Device shell. Requires the `api:terminal:open` ability, which is the widest
1277
+ * grant the API offers: the agent runs as root, so the session is a root
1278
+ * shell bounded by no manifest. Treat a token carrying it accordingly.
1279
+ *
1280
+ * Hand-written rather than generated; see `terminal.ts` for why.
1281
+ */
1282
+ terminal;
1283
+ webhooks;
1284
+ constructor(options) {
1285
+ if (!options || !options.token) {
1286
+ throw new OrbitError("An API token is required to construct OrbitClient.");
1287
+ }
1288
+ this.#client = createClient(
1289
+ createConfig({
1290
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1291
+ auth: () => options.token,
1292
+ // Without an explicit Accept the server may content-negotiate errors
1293
+ // into plain text, outside the JSON envelope the SDK parses.
1294
+ headers: { accept: "application/json" },
1295
+ ...options.fetch ? { fetch: options.fetch } : {}
1296
+ })
1297
+ );
1298
+ this.#maxRetries = options.maxRetries ?? 2;
1299
+ this.#retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
1300
+ const client2 = this.#client;
1301
+ const run = this.#run.bind(this);
1302
+ this.me = () => run(() => getIdentity({ client: client2, throwOnError: false }));
1303
+ this.projects = {
1304
+ list: (params = {}) => run(() => listProjects({ client: client2, query: params, throwOnError: false })),
1305
+ iterate: (params = {}) => paginate(async (cursor) => {
1306
+ const page = await run(
1307
+ () => listProjects({ client: client2, query: { ...params, cursor }, throwOnError: false })
1308
+ );
1309
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1310
+ }),
1311
+ get: (id) => run(() => getProject({ client: client2, path: { id }, throwOnError: false })),
1312
+ appToken: {
1313
+ create: (projectId) => run(
1314
+ () => createProjectAppToken({ client: client2, path: { id: projectId }, throwOnError: false })
1315
+ ),
1316
+ rotate: (projectId) => run(
1317
+ () => rotateProjectAppToken({ client: client2, path: { id: projectId }, throwOnError: false })
1318
+ )
1319
+ }
1320
+ };
1321
+ this.deviceTypes = {
1322
+ list: (projectId, params = {}) => run(
1323
+ () => listDeviceTypes({ client: client2, path: { projectId }, query: params, throwOnError: false })
1324
+ ),
1325
+ iterate: (projectId, params = {}) => paginate(async (cursor) => {
1326
+ const page = await run(
1327
+ () => listDeviceTypes({
1328
+ client: client2,
1329
+ path: { projectId },
1330
+ query: { ...params, cursor },
1331
+ throwOnError: false
1332
+ })
1333
+ );
1334
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1335
+ }),
1336
+ get: (projectId, slug) => run(
1337
+ () => getDeviceType({ client: client2, path: { projectId, slug }, throwOnError: false })
1338
+ ),
1339
+ create: (projectId, body) => run(
1340
+ () => createDeviceType({ client: client2, path: { projectId }, body, throwOnError: false })
1341
+ ),
1342
+ update: (projectId, slug, body) => run(
1343
+ () => updateDeviceType({ client: client2, path: { projectId, slug }, body, throwOnError: false })
1344
+ ),
1345
+ delete: async (projectId, slug) => {
1346
+ await run(
1347
+ () => deleteDeviceType({ client: client2, path: { projectId, slug }, throwOnError: false })
1348
+ );
1349
+ }
1350
+ };
1351
+ this.devices = {
1352
+ list: (params = {}) => run(() => listDevices({ client: client2, query: params, throwOnError: false })),
1353
+ get: (id) => run(() => getDevice({ client: client2, path: { id }, throwOnError: false })),
1354
+ iterate: (params = {}) => paginate(async (cursor) => {
1355
+ const page = await run(
1356
+ () => listDevices({ client: client2, query: { ...params, cursor }, throwOnError: false })
1357
+ );
1358
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1359
+ }),
1360
+ delete: async (id) => {
1361
+ await run(() => deleteDevice({ client: client2, path: { id }, throwOnError: false }));
1362
+ },
1363
+ resetToken: (id) => run(() => resetDeviceToken({ client: client2, path: { id }, throwOnError: false }))
1364
+ };
1365
+ this.admissions = {
1366
+ list: (params = {}) => run(
1367
+ () => listAdmissions({ client: client2, query: params, throwOnError: false })
1368
+ ),
1369
+ iterate: (params = {}) => paginate(async (cursor) => {
1370
+ const page = await run(
1371
+ () => listAdmissions({ client: client2, query: { ...params, cursor }, throwOnError: false })
1372
+ );
1373
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1374
+ }),
1375
+ get: (id) => run(() => getAdmission({ client: client2, path: { id }, throwOnError: false })),
1376
+ accept: (id, params) => run(
1377
+ () => acceptAdmission({ client: client2, path: { id }, body: params, throwOnError: false })
1378
+ ),
1379
+ reject: (id) => run(() => rejectAdmission({ client: client2, path: { id }, throwOnError: false })),
1380
+ dismiss: (id) => run(() => dismissAdmission({ client: client2, path: { id }, throwOnError: false }))
1381
+ };
1382
+ this.telemetry = {
1383
+ latest: (deviceId) => run(
1384
+ () => getLatestTelemetry({ client: client2, path: { id: deviceId }, throwOnError: false })
1385
+ ),
1386
+ history: (deviceId, params = {}) => run(
1387
+ () => getTelemetryHistory({ client: client2, path: { id: deviceId }, query: params, throwOnError: false })
1388
+ ).then((result) => result.data),
1389
+ manifest: (deviceId) => run(
1390
+ () => getTelemetryManifest({ client: client2, path: { id: deviceId }, throwOnError: false })
1391
+ )
1392
+ };
1393
+ this.firmware = {
1394
+ upload: (params) => run(
1395
+ () => uploadFirmware({ client: client2, body: params, throwOnError: false })
1396
+ ).then((result) => result.bundle),
1397
+ deleteBundle: async (id) => {
1398
+ await run(() => deleteFirmwareBundle({ client: client2, path: { id }, throwOnError: false }));
1399
+ },
1400
+ bundles: {
1401
+ list: (params = {}) => run(
1402
+ () => listFirmwareBundles({ client: client2, query: params, throwOnError: false })
1403
+ ),
1404
+ iterate: (params = {}) => paginate(async (cursor) => {
1405
+ const page = await run(
1406
+ () => listFirmwareBundles({ client: client2, query: { ...params, cursor }, throwOnError: false })
1407
+ );
1408
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1409
+ }),
1410
+ get: (id) => run(() => getFirmwareBundle({ client: client2, path: { id }, throwOnError: false }))
1411
+ },
1412
+ deployments: {
1413
+ trigger: (params) => run(
1414
+ () => triggerFirmwareDeployment({ client: client2, body: params, throwOnError: false })
1415
+ ).then((result) => result.deployments),
1416
+ list: (params = {}) => run(
1417
+ () => listFirmwareDeployments({ client: client2, query: params, throwOnError: false })
1418
+ ),
1419
+ iterate: (params = {}) => paginate(async (cursor) => {
1420
+ const page = await run(
1421
+ () => listFirmwareDeployments({ client: client2, query: { ...params, cursor }, throwOnError: false })
1422
+ );
1423
+ return {
1424
+ data: page.data,
1425
+ nextCursor: page.meta.nextCursor,
1426
+ hasMore: page.meta.hasMore
1427
+ };
1428
+ }),
1429
+ get: (id) => run(
1430
+ () => getFirmwareDeployment({ client: client2, path: { id }, throwOnError: false })
1431
+ ),
1432
+ cancel: (id, params = {}) => run(
1433
+ () => cancelFirmwareDeployment({ client: client2, path: { id }, body: params, throwOnError: false })
1434
+ ),
1435
+ rollback: (id, params = {}) => run(
1436
+ () => rollbackFirmwareDeployment({ client: client2, path: { id }, body: params, throwOnError: false })
1437
+ )
1438
+ }
1439
+ };
1440
+ this.commands = {
1441
+ exec: (deviceId, command) => run(
1442
+ () => execDeviceCommand({ client: client2, path: { id: deviceId }, body: command, throwOnError: false })
1443
+ ),
1444
+ get: (deviceId, invocationId) => run(
1445
+ () => getDeviceCommandInvocation({
1446
+ client: client2,
1447
+ path: { id: deviceId, invocationId },
1448
+ throwOnError: false
1449
+ })
1450
+ ),
1451
+ manifest: (deviceId) => run(
1452
+ () => getDeviceCommands({ client: client2, path: { id: deviceId }, throwOnError: false })
1453
+ )
1454
+ };
1455
+ this.usb = {
1456
+ list: (deviceId) => run(() => listExportable(client2, deviceId)).then(
1457
+ (result) => result.exports
1458
+ ),
1459
+ ticket: (params) => run(() => createTicket(client2, params))
1460
+ };
1461
+ this.terminal = {
1462
+ ticket: (params) => run(() => createTicket2(client2, params))
1463
+ };
1464
+ this.webhooks = {
1465
+ list: (params = {}) => run(
1466
+ () => listWebhooks({ client: client2, query: params, throwOnError: false })
1467
+ ),
1468
+ iterate: (params = {}) => paginate(async (cursor) => {
1469
+ const page = await run(
1470
+ () => listWebhooks({ client: client2, query: { ...params, cursor }, throwOnError: false })
1471
+ );
1472
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1473
+ }),
1474
+ create: (params) => run(
1475
+ () => createWebhook({ client: client2, body: params, throwOnError: false })
1476
+ ),
1477
+ get: (id) => run(() => getWebhook({ client: client2, path: { id }, throwOnError: false })),
1478
+ update: (id, params) => run(
1479
+ () => updateWebhook({ client: client2, path: { id }, body: params, throwOnError: false })
1480
+ ),
1481
+ delete: async (id) => {
1482
+ await run(() => deleteWebhook({ client: client2, path: { id }, throwOnError: false }));
1483
+ },
1484
+ deliveries: (id, params = {}) => run(
1485
+ () => listWebhookDeliveries({ client: client2, path: { id }, query: params, throwOnError: false })
1486
+ ),
1487
+ iterateDeliveries: (id, params = {}) => paginate(async (cursor) => {
1488
+ const page = await run(
1489
+ () => listWebhookDeliveries({
1490
+ client: client2,
1491
+ path: { id },
1492
+ query: { ...params, cursor },
1493
+ throwOnError: false
1494
+ })
1495
+ );
1496
+ return { data: page.data, nextCursor: page.meta.nextCursor, hasMore: page.meta.hasMore };
1497
+ })
1498
+ };
1499
+ }
1500
+ async #run(thunk) {
1501
+ let attempt = 0;
1502
+ for (; ; ) {
1503
+ let result;
1504
+ try {
1505
+ result = await thunk();
1506
+ } catch (cause) {
1507
+ if (attempt < this.#maxRetries) {
1508
+ await this.#sleep(this.#backoff(attempt));
1509
+ attempt++;
1510
+ continue;
1511
+ }
1512
+ throw new NetworkError("The request failed before a response was received.", { cause });
1513
+ }
1514
+ const { data, error, response } = result;
1515
+ const status = response?.status ?? 0;
1516
+ if (error === void 0 && status >= 200 && status < 300) {
1517
+ return data;
1518
+ }
1519
+ if (response === void 0) {
1520
+ if (attempt < this.#maxRetries) {
1521
+ await this.#sleep(this.#backoff(attempt));
1522
+ attempt++;
1523
+ continue;
1524
+ }
1525
+ throw new NetworkError("The request failed before a response was received.", {
1526
+ cause: error
1527
+ });
1528
+ }
1529
+ if (RETRYABLE_STATUS.has(status) && attempt < this.#maxRetries) {
1530
+ const retryAfter = parseRetryAfterSeconds(response);
1531
+ await this.#sleep(retryAfter !== void 0 ? retryAfter * 1e3 : this.#backoff(attempt));
1532
+ attempt++;
1533
+ continue;
1534
+ }
1535
+ throw normalizeError(status, error ?? data, response);
1536
+ }
1537
+ }
1538
+ #backoff(attempt) {
1539
+ const base = this.#retryBaseDelayMs * 2 ** attempt;
1540
+ return Math.floor(base * (0.5 + Math.random() * 0.5));
1541
+ }
1542
+ #sleep(ms) {
1543
+ if (ms <= 0) return Promise.resolve();
1544
+ return new Promise((resolve) => setTimeout(resolve, ms));
1545
+ }
1546
+ };
1547
+
1548
+ // src/telemetry.ts
1549
+ function decodeSample(sample, manifest) {
1550
+ const byKey = new Map(manifest.metrics.map((metric) => [metric.key, metric]));
1551
+ return Object.entries(sample.metrics).map(([key, value]) => {
1552
+ const definition = byKey.get(key);
1553
+ if (!definition) return { key, label: key, value };
1554
+ return {
1555
+ key,
1556
+ label: definition.label,
1557
+ value,
1558
+ unit: definition.unit,
1559
+ type: definition.type,
1560
+ deviceClass: definition.deviceClass,
1561
+ group: definition.group,
1562
+ definition
1563
+ };
1564
+ });
1565
+ }
1566
+ function decodeSamples(samples, manifest) {
1567
+ return samples.map((sample) => ({
1568
+ recordedAt: sample.recordedAt,
1569
+ metrics: decodeSample(sample, manifest)
1570
+ }));
1571
+ }
1572
+
1573
+ // src/webhooks.ts
1574
+ var WEBHOOK_REPLAY_TOLERANCE_SECONDS = 300;
1575
+ async function hmacSha256Hex(secret, message) {
1576
+ const encoder = new TextEncoder();
1577
+ const key = await crypto.subtle.importKey(
1578
+ "raw",
1579
+ encoder.encode(secret),
1580
+ { name: "HMAC", hash: "SHA-256" },
1581
+ false,
1582
+ ["sign"]
1583
+ );
1584
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
1585
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1586
+ }
1587
+ function timingSafeEqual(a, b) {
1588
+ const encoder = new TextEncoder();
1589
+ const ab = encoder.encode(a);
1590
+ const bb = encoder.encode(b);
1591
+ if (ab.length !== bb.length) return false;
1592
+ let diff = 0;
1593
+ for (let i = 0; i < ab.length; i++) diff |= (ab[i] ?? 0) ^ (bb[i] ?? 0);
1594
+ return diff === 0;
1595
+ }
1596
+ async function signWebhookPayload(secret, timestamp, rawBody) {
1597
+ return hmacSha256Hex(secret, `${timestamp}.${rawBody}`);
1598
+ }
1599
+ async function verifyWebhookSignature(params) {
1600
+ const timestamp = Number(params.timestamp);
1601
+ if (!Number.isFinite(timestamp)) return false;
1602
+ const tolerance = params.toleranceSeconds ?? WEBHOOK_REPLAY_TOLERANCE_SECONDS;
1603
+ const now = params.nowSeconds ?? Math.floor(Date.now() / 1e3);
1604
+ if (Math.abs(now - timestamp) > tolerance) return false;
1605
+ const expected = await signWebhookPayload(params.secret, timestamp, params.rawBody);
1606
+ return timingSafeEqual(expected, params.signature);
1607
+ }
1608
+ async function parseWebhookEvent(params) {
1609
+ if (!await verifyWebhookSignature(params)) return null;
1610
+ return JSON.parse(params.rawBody);
1611
+ }
1612
+
1613
+ // src/generated/index.ts
1614
+ var generated_exports = {};
1615
+ __export(generated_exports, {
1616
+ acceptAdmission: () => acceptAdmission,
1617
+ cancelFirmwareDeployment: () => cancelFirmwareDeployment,
1618
+ createDeviceType: () => createDeviceType,
1619
+ createProjectAppToken: () => createProjectAppToken,
1620
+ createWebhook: () => createWebhook,
1621
+ deleteCommandManifest: () => deleteCommandManifest,
1622
+ deleteDevice: () => deleteDevice,
1623
+ deleteDeviceType: () => deleteDeviceType,
1624
+ deleteFirmwareBundle: () => deleteFirmwareBundle,
1625
+ deleteWebhook: () => deleteWebhook,
1626
+ dismissAdmission: () => dismissAdmission,
1627
+ execDeviceCommand: () => execDeviceCommand,
1628
+ getAdmission: () => getAdmission,
1629
+ getCommandManifest: () => getCommandManifest,
1630
+ getDevice: () => getDevice,
1631
+ getDeviceCommandInvocation: () => getDeviceCommandInvocation,
1632
+ getDeviceCommands: () => getDeviceCommands,
1633
+ getDeviceType: () => getDeviceType,
1634
+ getFirmwareBundle: () => getFirmwareBundle,
1635
+ getFirmwareDeployment: () => getFirmwareDeployment,
1636
+ getIdentity: () => getIdentity,
1637
+ getLatestTelemetry: () => getLatestTelemetry,
1638
+ getProject: () => getProject,
1639
+ getTelemetryHistory: () => getTelemetryHistory,
1640
+ getTelemetryManifest: () => getTelemetryManifest,
1641
+ getWebhook: () => getWebhook,
1642
+ listAdmissions: () => listAdmissions,
1643
+ listDeviceTypes: () => listDeviceTypes,
1644
+ listDevices: () => listDevices,
1645
+ listFirmwareBundles: () => listFirmwareBundles,
1646
+ listFirmwareDeployments: () => listFirmwareDeployments,
1647
+ listProjects: () => listProjects,
1648
+ listWebhookDeliveries: () => listWebhookDeliveries,
1649
+ listWebhooks: () => listWebhooks,
1650
+ rejectAdmission: () => rejectAdmission,
1651
+ resetDeviceToken: () => resetDeviceToken,
1652
+ rollbackFirmwareDeployment: () => rollbackFirmwareDeployment,
1653
+ rotateProjectAppToken: () => rotateProjectAppToken,
1654
+ triggerFirmwareDeployment: () => triggerFirmwareDeployment,
1655
+ updateCommandManifest: () => updateCommandManifest,
1656
+ updateDeviceType: () => updateDeviceType,
1657
+ updateWebhook: () => updateWebhook,
1658
+ uploadFirmware: () => uploadFirmware
1659
+ });
1660
+
1661
+ exports.AuthenticationError = AuthenticationError;
1662
+ exports.BadRequestError = BadRequestError;
1663
+ exports.BundleExistsError = BundleExistsError;
1664
+ exports.DeviceRpcError = DeviceRpcError;
1665
+ exports.InsufficientScopeError = InsufficientScopeError;
1666
+ exports.NetworkError = NetworkError;
1667
+ exports.OrbitClient = OrbitClient;
1668
+ exports.OrbitError = OrbitError;
1669
+ exports.RateLimitError = RateLimitError;
1670
+ exports.ResourceNotFoundError = ResourceNotFoundError;
1671
+ exports.ServerError = ServerError;
1672
+ exports.ValidationError = ValidationError;
1673
+ exports.WEBHOOK_REPLAY_TOLERANCE_SECONDS = WEBHOOK_REPLAY_TOLERANCE_SECONDS;
1674
+ exports.decodeSample = decodeSample;
1675
+ exports.decodeSamples = decodeSamples;
1676
+ exports.normalizeError = normalizeError;
1677
+ exports.paginate = paginate;
1678
+ exports.parseRetryAfterSeconds = parseRetryAfterSeconds;
1679
+ exports.parseWebhookEvent = parseWebhookEvent;
1680
+ exports.raw = generated_exports;
1681
+ exports.signWebhookPayload = signWebhookPayload;
1682
+ exports.verifyWebhookSignature = verifyWebhookSignature;
1683
+ //# sourceMappingURL=index.cjs.map
1684
+ //# sourceMappingURL=index.cjs.map