@twinfinity/twin 6.0.1 → 6.0.2-ci.29168

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 (84) hide show
  1. package/dist/BuildInfo.js +3 -3
  2. package/dist/TwinClient.d.ts +159 -0
  3. package/dist/TwinClient.d.ts.map +1 -1
  4. package/dist/TwinClient.js +323 -28
  5. package/dist/TwinClient.js.map +1 -1
  6. package/dist/errors.d.ts +114 -3
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +142 -0
  9. package/dist/errors.js.map +1 -1
  10. package/dist/tsconfig.tsbuildinfo +1 -1
  11. package/dist/types/asset-types-api.d.ts +76 -0
  12. package/dist/types/asset-types-api.d.ts.map +1 -0
  13. package/dist/types/asset-types-api.js +5 -0
  14. package/dist/types/asset-types-api.js.map +1 -0
  15. package/dist/types/index.d.ts +2 -0
  16. package/dist/types/index.d.ts.map +1 -1
  17. package/dist/types/index.js +2 -0
  18. package/dist/types/index.js.map +1 -1
  19. package/dist/types/twin-permissions-api.d.ts +20 -0
  20. package/dist/types/twin-permissions-api.d.ts.map +1 -0
  21. package/dist/types/twin-permissions-api.js +2 -0
  22. package/dist/types/twin-permissions-api.js.map +1 -0
  23. package/docs/assets/hierarchy.js +1 -1
  24. package/docs/assets/navigation.js +1 -1
  25. package/docs/assets/search.js +1 -1
  26. package/docs/classes/AssetBatchError.html +1 -1
  27. package/docs/classes/AssetCatalogTooLargeError.html +16 -0
  28. package/docs/classes/AssetCategoryConflictError.html +3 -0
  29. package/docs/classes/AssetCategoryForbiddenError.html +2 -0
  30. package/docs/classes/AssetCategoryNotFoundError.html +2 -0
  31. package/docs/classes/AssetCategoryValidationError.html +3 -0
  32. package/docs/classes/AssetConflictError.html +1 -1
  33. package/docs/classes/AssetForbiddenError.html +1 -1
  34. package/docs/classes/AssetNotFoundError.html +1 -1
  35. package/docs/classes/AssetTypeConflictError.html +3 -0
  36. package/docs/classes/AssetTypeForbiddenError.html +2 -0
  37. package/docs/classes/AssetTypeNotFoundError.html +2 -0
  38. package/docs/classes/AssetTypeValidationError.html +3 -0
  39. package/docs/classes/AssetValidationError.html +1 -1
  40. package/docs/classes/ProcessorNotFoundError.html +1 -1
  41. package/docs/classes/TwinClient.html +114 -41
  42. package/docs/classes/TwinConflictError.html +1 -1
  43. package/docs/classes/TwinFileConflictError.html +1 -1
  44. package/docs/classes/TwinFileNotFoundError.html +1 -1
  45. package/docs/classes/TwinFileValidationError.html +1 -1
  46. package/docs/classes/TwinNotFoundError.html +1 -1
  47. package/docs/classes/TwinUnauthenticatedError.html +6 -0
  48. package/docs/classes/TwinValidationError.html +1 -1
  49. package/docs/functions/isAssetCatalogTooLargeErrorBody.html +6 -0
  50. package/docs/functions/readErrorBody.html +10 -0
  51. package/docs/hierarchy.html +1 -1
  52. package/docs/interfaces/AssetCatalogCategory.html +7 -0
  53. package/docs/interfaces/AssetCatalogResponse.html +6 -0
  54. package/docs/interfaces/AssetCatalogTooLargeErrorBody.html +15 -0
  55. package/docs/interfaces/AssetCategoryDelete.html +2 -0
  56. package/docs/interfaces/AssetCategoryGet.html +14 -0
  57. package/docs/interfaces/AssetCategoryPut.html +7 -0
  58. package/docs/interfaces/AssetTypeDelete.html +2 -0
  59. package/docs/interfaces/AssetTypeGet.html +16 -0
  60. package/docs/interfaces/AssetTypePut.html +9 -0
  61. package/docs/interfaces/ITwinClient.html +115 -42
  62. package/docs/interfaces/MyPermissions.html +7 -0
  63. package/docs/interfaces/TwinErrorBody.html +2 -2
  64. package/docs/interfaces/TwinSpecification.html +1 -1
  65. package/docs/modules.html +1 -1
  66. package/docs/types/TwinCapability.html +6 -0
  67. package/docs/types/TwinErrorCause.html +8 -0
  68. package/docs/types/TwinErrorItemKind.html +4 -0
  69. package/package.json +3 -3
  70. package/src/BuildInfo.ts +41 -41
  71. package/src/TwinClient.ts +2010 -1496
  72. package/src/errors.ts +360 -117
  73. package/src/index.ts +3 -3
  74. package/src/types/Twin.ts +7 -7
  75. package/src/types/TwinGeometryInfo.ts +7 -7
  76. package/src/types/asset-api.ts +60 -60
  77. package/src/types/asset-batch-api.ts +88 -88
  78. package/src/types/asset-types-api.ts +86 -0
  79. package/src/types/common.ts +10 -10
  80. package/src/types/generated.ts +574 -574
  81. package/src/types/index.ts +8 -6
  82. package/src/types/twin-api.ts +99 -99
  83. package/src/types/twin-file-api.ts +67 -67
  84. package/src/types/twin-permissions-api.ts +20 -0
package/src/TwinClient.ts CHANGED
@@ -1,1496 +1,2010 @@
1
- import { TwinfinityHttpClient, HttpMethod } from '@twinfinity/authentication';
2
- import {
3
- readT8ClientModelWithFactories,
4
- readT8ClientModelWithGeometry,
5
- readT8GIModelWithFactories,
6
- T8ClientEntityTypeDTO,
7
- T8ClientModel,
8
- T8ClientModelDTO,
9
- T8ClientProductConnectionsDTO,
10
- T8ClientProductDTO,
11
- T8ClientProjectConnectionsDTO,
12
- T8ClientProjectDTO,
13
- T8ClientUnitDTO,
14
- T8EntityType,
15
- T8GIMeshDescriptor,
16
- T8GIMeshDescriptorDTO,
17
- T8GIStyle,
18
- T8GIStyleDTO,
19
- T8GIRegion,
20
- T8GIRegionDTO,
21
- T8Product,
22
- T8ProductWithGeometry,
23
- T8Project,
24
- T8Unit
25
- } from '@twinfinity/t8-client-model';
26
- import type { T8ProjectWithGeometry } from '@twinfinity/t8-client-model';
27
- import type { T8GIModelGeneric } from '@twinfinity/t8-client-model';
28
- import type {
29
- PaginatedResponse,
30
- ListTwinItem,
31
- TwinGet,
32
- TwinPut,
33
- TwinVersionContentResponse,
34
- TwinProcessorEvent,
35
- TwinDiagnosticsResponse,
36
- AssetListItem,
37
- AssetGet,
38
- AssetPost,
39
- AssetPut,
40
- AssetBatchOperation,
41
- AssetBatchResponse,
42
- AssetBatchGetResponse,
43
- TwinFileGet,
44
- TwinFilePut,
45
- TwinFileDelete,
46
- TwinFileListOptions,
47
- TwinFileVersionListOptions,
48
- TwinContentResponse
49
- } from './types';
50
- import {
51
- TwinValidationError,
52
- TwinConflictError,
53
- TwinNotFoundError,
54
- ProcessorNotFoundError,
55
- AssetValidationError,
56
- AssetForbiddenError,
57
- AssetConflictError,
58
- AssetNotFoundError,
59
- AssetBatchError,
60
- TwinFileValidationError,
61
- TwinFileConflictError,
62
- TwinFileNotFoundError
63
- } from './errors';
64
- import { Twin } from './types/Twin';
65
- import { TwinGeometryInfo } from './types/TwinGeometryInfo';
66
-
67
- export interface ITwinClient {
68
- /**
69
- * @param relatedTo - Filter twins by container ID.
70
- * @throws {TwinValidationError} On invalid query parameters (400).
71
- */
72
- listTwins(
73
- relatedTo?: string,
74
- page?: string,
75
- limit?: number,
76
- signal?: AbortSignal
77
- ): Promise<PaginatedResponse<ListTwinItem>>;
78
-
79
- /**
80
- * Fetches all twins by auto-paginating through {@link listTwins}. Caps at 1000 pages.
81
- * @param relatedTo - Filter twins by container ID.
82
- */
83
- listAllTwins(relatedTo?: string, signal?: AbortSignal): Promise<ListTwinItem[]>;
84
-
85
- /**
86
- * @param twin - Twin ID string, or `{id, version}` to fetch a specific version.
87
- * @throws {TwinNotFoundError} When the twin or version does not exist (404).
88
- */
89
- getTwin(twin: string | { id: string; version: number }, signal?: AbortSignal): Promise<TwinGet>;
90
-
91
- /**
92
- * @throws {TwinValidationError} On invalid query parameters (400).
93
- */
94
- listTwinVersions(
95
- id: string,
96
- options?: {
97
- includeDeleted?: boolean;
98
- page?: string;
99
- limit?: number;
100
- },
101
- signal?: AbortSignal
102
- ): Promise<PaginatedResponse<ListTwinItem>>;
103
-
104
- downloadTwinContent(
105
- twinId: string,
106
- twinVersion: number,
107
- content: TwinContentResponse,
108
- signal?: AbortSignal
109
- ): Promise<ArrayBuffer>;
110
-
111
- /**
112
- * Downloads and deserializes the T8 client model (t8cm + t8cm-ext) using default types.
113
- * When no version is specified, searches versions newest-first for one containing t8cm content.
114
- *
115
- * @param twin - Twin ID string, or `{id, version}` to load a specific version.
116
- * @throws {Error} When no version has t8cm content.
117
- */
118
- loadTwin(
119
- twin: string | { id: string; version: number },
120
- signal?: AbortSignal
121
- ): Promise<Twin<T8Project, T8Product<T8EntityType>, T8EntityType, T8Unit>>;
122
-
123
- /**
124
- * Downloads and deserializes the T8 client model using custom factory functions for domain-specific types.
125
- * When no version is specified, searches versions newest-first for one containing t8cm content.
126
- *
127
- * @param twin - Twin ID string, or `{id, version}` to load a specific version.
128
- * @throws {Error} When no version has t8cm content.
129
- */
130
- loadTwinWithFactories<TProject, TProduct, TEntityType, TUnit>(
131
- twin: string | { id: string; version: number },
132
- projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
133
- productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
134
- entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
135
- unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
136
- connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
137
- connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
138
- signal?: AbortSignal
139
- ): Promise<Twin<TProject, TProduct, TEntityType, TUnit>>;
140
-
141
- /**
142
- * Downloads and deserializes geometry info (t8gi) using default types.
143
- * When no version is specified, searches versions newest-first for one containing t8gi content.
144
- *
145
- * @param twin - Twin ID string, or `{id, version}` to load a specific version.
146
- * @throws {Error} When no version has t8gi content.
147
- */
148
- loadGeometryInfo(
149
- twin: string | { id: string; version: number },
150
- signal?: AbortSignal
151
- ): Promise<TwinGeometryInfo<T8GIMeshDescriptor, T8GIStyle, T8GIRegion>>;
152
-
153
- /**
154
- * Downloads and deserializes geometry info (t8gi) using custom factory functions.
155
- * When no version is specified, searches versions newest-first for one containing t8gi content.
156
- *
157
- * @param twin - Twin ID string, or `{id, version}` to load a specific version.
158
- * @throws {Error} When no version has t8gi content.
159
- */
160
- loadGeometryInfoWithFactories<TMeshDescriptor, TStyle, TRegion>(
161
- twin: string | { id: string; version: number },
162
- meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
163
- styleFactory: (dto: T8GIStyleDTO) => TStyle,
164
- regionFactory: (dto: T8GIRegionDTO) => TRegion,
165
- signal?: AbortSignal
166
- ): Promise<TwinGeometryInfo<TMeshDescriptor, TStyle, TRegion>>;
167
-
168
- /**
169
- * Downloads and deserializes both the client model (t8cm) and geometry (t8gi/t8gd) into a combined result.
170
- * When no version is specified, searches versions newest-first for one containing both t8cm and t8gi content.
171
- *
172
- * @param twin - Twin ID string, or `{id, version}` to load a specific version.
173
- * @throws {Error} When no version has both t8cm and t8gi content.
174
- */
175
- loadTwinWithGeometry(
176
- twin: string | { id: string; version: number },
177
- signal?: AbortSignal
178
- ): Promise<Twin<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit>>;
179
-
180
- /**
181
- * Creates a new twin or updates an existing one (upsert). Provide `etag` in the twin body to update.
182
- *
183
- * @throws {TwinValidationError} On invalid request body (400).
184
- * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
185
- */
186
- createOrUpdateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet>;
187
-
188
- /** Alias for {@link createOrUpdateTwin}. */
189
- updateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet>;
190
-
191
- /**
192
- * @throws {TwinNotFoundError} When the twin does not exist (404).
193
- * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
194
- */
195
- restoreTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet>;
196
-
197
- /**
198
- * @throws {TwinNotFoundError} When the twin or version does not exist (404).
199
- */
200
- getTwinVersionContent(
201
- twinId: string,
202
- twinVersion: number,
203
- signal?: AbortSignal
204
- ): Promise<TwinVersionContentResponse>;
205
-
206
- /**
207
- * Returns content for the latest twin version.
208
- * @throws {TwinNotFoundError} When the twin does not exist (404).
209
- */
210
- getTwinContent(twinId: string, signal?: AbortSignal): Promise<TwinVersionContentResponse>;
211
-
212
- /** @throws {TwinNotFoundError} When the twin does not exist (404). */
213
- getTwinDiagnostics(twinId: string, signal?: AbortSignal): Promise<TwinDiagnosticsResponse>;
214
-
215
- /** @throws {TwinNotFoundError} When the twin or version does not exist (404). */
216
- getTwinVersionDiagnostics(
217
- twinId: string,
218
- twinVersion: number,
219
- signal?: AbortSignal
220
- ): Promise<TwinDiagnosticsResponse>;
221
-
222
- /**
223
- * @throws {TwinValidationError} On invalid query parameters (400).
224
- * @throws {TwinNotFoundError} When the twin or version does not exist (404).
225
- */
226
- getTwinVersionEvents(
227
- twinId: string,
228
- twinVersion: number,
229
- offset?: number,
230
- limit?: number,
231
- signal?: AbortSignal
232
- ): Promise<PaginatedResponse<TwinProcessorEvent>>;
233
-
234
- /**
235
- * @throws {TwinValidationError} On invalid query parameters (400).
236
- * @throws {ProcessorNotFoundError} When the processor does not exist for this twin version (404).
237
- */
238
- getProcessorEvents(
239
- twinId: string,
240
- twinVersion: number,
241
- processorId: string,
242
- offset?: number,
243
- limit?: number,
244
- signal?: AbortSignal
245
- ): Promise<PaginatedResponse<TwinProcessorEvent>>;
246
-
247
- /**
248
- * @throws {AssetValidationError} On invalid query parameters (400).
249
- * @throws {AssetNotFoundError} When the twin does not exist (404).
250
- */
251
- listAssets(
252
- twinId: string,
253
- offset?: number,
254
- limit?: number,
255
- options?: { includeDeleted?: boolean },
256
- signal?: AbortSignal
257
- ): Promise<PaginatedResponse<AssetListItem>>;
258
-
259
- /** @throws {AssetNotFoundError} When the asset does not exist (404). */
260
- getAsset(twinId: string, assetId: string, signal?: AbortSignal): Promise<AssetGet>;
261
-
262
- /** @throws {AssetValidationError} On invalid request body (400). The error's `errorBody` has structured detail. */
263
- createAssets(twinId: string, assets: AssetPost[], signal?: AbortSignal): Promise<AssetGet[]>;
264
-
265
- /**
266
- * @throws {AssetValidationError} On invalid request body (400). The error's `errorBody` has structured detail.
267
- * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
268
- */
269
- updateAsset(twinId: string, assetId: string, asset: AssetPut, signal?: AbortSignal): Promise<AssetGet>;
270
-
271
- /**
272
- * @throws {AssetNotFoundError} When the asset does not exist (404).
273
- * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
274
- */
275
- deleteAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet>;
276
-
277
- /**
278
- * @throws {AssetNotFoundError} When the asset does not exist (404).
279
- * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
280
- */
281
- restoreAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet>;
282
-
283
- /**
284
- * Executes a batch of asset operations (upsert, delete, restore) atomically.
285
- * All operations succeed or all are rolled back.
286
- *
287
- * @param operations - Array of batch operations (max 1000).
288
- * @throws {AssetValidationError} On validation failure (400).
289
- * @throws {AssetForbiddenError} On insufficient permissions (403).
290
- * @throws {AssetBatchError} On conflict (409) or not found (404). The error's `response` has per-item results with reverted statuses.
291
- */
292
- batchAssets(twinId: string, operations: AssetBatchOperation[], signal?: AbortSignal): Promise<AssetBatchResponse>;
293
-
294
- /**
295
- * Retrieves multiple assets by ID in a single request.
296
- *
297
- * @param ids - Array of asset IDs (max 1000).
298
- * @throws {AssetValidationError} On validation failure (400).
299
- */
300
- batchGetAssets(twinId: string, ids: string[], signal?: AbortSignal): Promise<AssetBatchGetResponse>;
301
-
302
- /**
303
- * @throws {TwinNotFoundError} When the twin does not exist (404).
304
- * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
305
- */
306
- deleteTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet>;
307
-
308
- /** @throws {TwinFileValidationError} On invalid query parameters (400). */
309
- listTwinFiles(
310
- twinId: string,
311
- options?: TwinFileListOptions,
312
- signal?: AbortSignal
313
- ): Promise<PaginatedResponse<TwinFileGet>>;
314
-
315
- /**
316
- * @throws {TwinFileNotFoundError} When the file does not exist (404).
317
- * @throws {TwinFileValidationError} On invalid request (400).
318
- */
319
- getTwinFile(twinId: string, fileId: string, signal?: AbortSignal): Promise<TwinFileGet>;
320
-
321
- /**
322
- * @throws {TwinFileValidationError} On invalid request body (400).
323
- * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
324
- */
325
- createOrUpdateTwinFile(
326
- twinId: string,
327
- fileId: string,
328
- twinFile: TwinFilePut,
329
- signal?: AbortSignal
330
- ): Promise<TwinFileGet>;
331
-
332
- /**
333
- * @throws {TwinFileNotFoundError} When the file does not exist (404).
334
- * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
335
- * @throws {TwinFileValidationError} On invalid request (400).
336
- */
337
- deleteTwinFile(
338
- twinId: string,
339
- fileId: string,
340
- deleteRequest: TwinFileDelete,
341
- signal?: AbortSignal
342
- ): Promise<TwinFileGet>;
343
-
344
- /**
345
- * @throws {TwinFileNotFoundError} When the file does not exist (404).
346
- * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
347
- * @throws {TwinFileValidationError} On invalid request (400).
348
- */
349
- restoreTwinFile(twinId: string, fileId: string, etag: string, signal?: AbortSignal): Promise<TwinFileGet>;
350
-
351
- /** @throws {TwinFileNotFoundError} When the file does not exist (404). */
352
- getTwinFileContent(twinId: string, fileId: string, signal?: AbortSignal): Promise<Blob>;
353
-
354
- /** @throws {TwinFileNotFoundError} When the file or version does not exist (404). */
355
- getTwinFileVersion(twinId: string, fileId: string, version: number, signal?: AbortSignal): Promise<TwinFileGet>;
356
-
357
- /** @throws {TwinFileValidationError} On invalid query parameters (400). */
358
- listTwinFileVersions(
359
- twinId: string,
360
- fileId: string,
361
- options?: TwinFileVersionListOptions,
362
- signal?: AbortSignal
363
- ): Promise<PaginatedResponse<TwinFileGet>>;
364
-
365
- /** @throws {TwinFileNotFoundError} When the file or version does not exist (404). */
366
- getTwinFileVersionContent(twinId: string, fileId: string, version: number, signal?: AbortSignal): Promise<Blob>;
367
- }
368
-
369
- export class TwinClient implements ITwinClient {
370
- private readonly _baseUrl: string;
371
-
372
- constructor(
373
- baseUrl: string | URL,
374
- private readonly _httpClient: TwinfinityHttpClient
375
- ) {
376
- this._baseUrl = `${baseUrl}/_ps/twins`;
377
- }
378
-
379
- async listTwins(
380
- relatedTo?: string,
381
- page: string | undefined = undefined,
382
- limit = 100,
383
- signal?: AbortSignal
384
- ): Promise<PaginatedResponse<ListTwinItem>> {
385
- const params = new URLSearchParams();
386
- if (relatedTo) params.set('relatedTo', relatedTo);
387
- if (page !== undefined) params.set('page', page);
388
- if (limit !== 100) params.set('limit', limit.toString());
389
-
390
- const url = params.toString() ? `${this._baseUrl}?${params}` : this._baseUrl;
391
-
392
- const response = await this._httpClient.fetch(HttpMethod.Get, url, {
393
- headers: { 'Content-Type': 'application/json' },
394
- signal
395
- });
396
-
397
- if (response.ok) {
398
- return (await response.json()) as PaginatedResponse<ListTwinItem>;
399
- }
400
-
401
- if (response.status === 400) {
402
- const errorBody = await response.json();
403
- throw new TwinValidationError(`Twin listing validation failed: ${errorBody.detail}`, errorBody);
404
- }
405
-
406
- const errorText = await response.text();
407
- throw new Error(`Failed to list twins: ${response.status} ${response.statusText} - ${errorText}`);
408
- }
409
-
410
- async listAllTwins(relatedTo?: string, signal?: AbortSignal): Promise<ListTwinItem[]> {
411
- const allTwins: ListTwinItem[] = [];
412
- let page: string | undefined = undefined;
413
- const limit = 100;
414
- const maxPages = 1000;
415
-
416
- for (let pageCount = 0; pageCount < maxPages; pageCount++) {
417
- const response = await this.listTwins(relatedTo, page, limit, signal);
418
- allTwins.push(...response.data);
419
-
420
- if (response.data.length < limit) {
421
- break;
422
- }
423
-
424
- page = response.pagination.nextPage;
425
- }
426
-
427
- return allTwins;
428
- }
429
-
430
- async getTwin(twin: string | { id: string; version: number }, signal?: AbortSignal): Promise<TwinGet> {
431
- const twinId = typeof twin === 'string' ? twin : twin.id;
432
- const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
433
- const response = await this._httpClient.fetch(
434
- HttpMethod.Get,
435
- `${this._baseUrl}/${twinId}${specifiedVersion !== undefined ? `/versions/${specifiedVersion}` : ''}`,
436
- {
437
- headers: { 'Content-Type': 'application/json' },
438
- signal
439
- }
440
- );
441
-
442
- if (response.ok) {
443
- return (await response.json()) as TwinGet;
444
- }
445
-
446
- if (response.status === 404) {
447
- throw new TwinNotFoundError(`Twin ${twinId} not found`);
448
- }
449
-
450
- const errorText = await response.text();
451
- throw new Error(`Failed to get twin: ${response.status} ${response.statusText} - ${errorText}`);
452
- }
453
-
454
- async listTwinVersions(
455
- id: string,
456
- options?: {
457
- includeDeleted?: boolean;
458
- page: string | undefined;
459
- limit?: number;
460
- },
461
- signal?: AbortSignal
462
- ): Promise<PaginatedResponse<ListTwinItem>> {
463
- const params = new URLSearchParams();
464
- if (options?.page !== undefined) params.set('page', options.page);
465
- if (options?.limit !== undefined && options.limit !== 100) params.set('limit', options.limit.toString());
466
- if (options?.includeDeleted) params.set('includeDeleted', 'true');
467
-
468
- const url = `${this._baseUrl}/${id}/versions${params.toString() ? `?${params}` : ''}`;
469
-
470
- const response = await this._httpClient.fetch(HttpMethod.Get, url, {
471
- headers: { 'Content-Type': 'application/json' },
472
- signal
473
- });
474
-
475
- if (response.ok) {
476
- return (await response.json()) as PaginatedResponse<ListTwinItem>;
477
- }
478
-
479
- if (response.status === 400) {
480
- const errorBody = await response.json();
481
- throw new TwinValidationError(`Twin listing validation failed: ${errorBody.detail}`, errorBody);
482
- }
483
-
484
- const errorText = await response.text();
485
- throw new Error(`Failed to list twins: ${response.status} ${response.statusText} - ${errorText}`);
486
- }
487
-
488
- async downloadTwinContent(
489
- twinId: string,
490
- twinVersion: number,
491
- content: TwinContentResponse,
492
- signal?: AbortSignal
493
- ): Promise<ArrayBuffer> {
494
- const response = await this._httpClient.fetch(
495
- HttpMethod.Get,
496
- `${this._baseUrl}/${twinId}/versions/${twinVersion}/contents/${content.id}/content`,
497
- { signal }
498
- );
499
- if (response.ok) {
500
- const blob = await response.blob();
501
- return await blob.arrayBuffer();
502
- }
503
-
504
- throw new Error(`Failed to download twin content: ${response.status} ${response.statusText}`);
505
- }
506
-
507
- private async loadTwinVersion<TProject, TProduct, TEntityType, TUnit>(
508
- twinId: string,
509
- twinVersion: number,
510
- projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
511
- productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
512
- entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
513
- unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
514
- connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
515
- connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
516
- signal?: AbortSignal
517
- ): Promise<T8ClientModel<TProject, TProduct, TEntityType, TUnit> | undefined> {
518
- const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
519
-
520
- const t8cmItem = twinContent.content.find((item) => item.format === 't8cm');
521
-
522
- if (t8cmItem === undefined) {
523
- return undefined;
524
- }
525
-
526
- const t8cmExtensions = twinContent.content.filter((item) => item.format === 't8cm-ext');
527
-
528
- const data = await Promise.all(
529
- [this.downloadTwinContent(twinId, twinVersion, t8cmItem, signal)].concat(
530
- t8cmExtensions.map((ext) => this.downloadTwinContent(twinId, twinVersion, ext, signal))
531
- )
532
- );
533
-
534
- return readT8ClientModelWithFactories<TProject, TProduct, TEntityType, TUnit>(
535
- data,
536
- projectFactory,
537
- productFactory,
538
- entityTypeFactory,
539
- unitFactory,
540
- connectProject,
541
- connectProduct
542
- );
543
- }
544
-
545
- loadTwin(
546
- twin: string | { id: string; version: number },
547
- signal?: AbortSignal
548
- ): Promise<Twin<T8Project, T8Product<T8EntityType>, T8EntityType, T8Unit>> {
549
- return this.loadTwinWithFactories(
550
- twin,
551
- T8Project.create<T8Product<T8EntityType>, T8Unit>,
552
- T8Product.create<T8EntityType, T8Unit>,
553
- T8EntityType.create,
554
- T8Unit.create,
555
- T8Project.connect,
556
- T8Product.connect,
557
- signal
558
- );
559
- }
560
-
561
- async loadTwinWithFactories<TProject, TProduct, TEntityType, TUnit>(
562
- twin: string | { id: string; version: number },
563
- projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
564
- productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
565
- entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
566
- unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
567
- connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
568
- connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
569
- signal?: AbortSignal
570
- ): Promise<Twin<TProject, TProduct, TEntityType, TUnit>> {
571
- let page: string | undefined = undefined;
572
- const twinId = typeof twin === 'string' ? twin : twin.id;
573
- const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
574
- if (specifiedVersion !== undefined) {
575
- return {
576
- id: twinId,
577
- version: specifiedVersion,
578
- model: await this.loadTwinVersion(
579
- twinId,
580
- specifiedVersion,
581
- projectFactory,
582
- productFactory,
583
- entityTypeFactory,
584
- unitFactory,
585
- connectProject,
586
- connectProduct,
587
- signal
588
- )
589
- };
590
- }
591
-
592
- const maxPages = 100;
593
- for (let pageCount = 0; pageCount < maxPages; pageCount++) {
594
- const versions = await this.listTwinVersions(twinId, { page }, signal);
595
- if (versions.data.length === 0) {
596
- break;
597
- }
598
- for (const versionItem of versions.data) {
599
- const loadedModel = await this.loadTwinVersion(
600
- twinId,
601
- versionItem.version,
602
- projectFactory,
603
- productFactory,
604
- entityTypeFactory,
605
- unitFactory,
606
- connectProject,
607
- connectProduct,
608
- signal
609
- );
610
- if (loadedModel !== undefined) {
611
- return {
612
- id: twinId,
613
- version: versionItem.version,
614
- model: loadedModel
615
- };
616
- }
617
- }
618
- page = versions.pagination.nextPage;
619
- }
620
-
621
- throw new Error(`Twin ${twinId} does not have a client model`);
622
- }
623
-
624
- private async loadGeometryInfoVersion<TMeshDescriptor, TStyle, TRegion>(
625
- twinId: string,
626
- twinVersion: number,
627
- meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
628
- styleFactory: (dto: T8GIStyleDTO) => TStyle,
629
- regionFactory: (dto: T8GIRegionDTO) => TRegion,
630
- signal?: AbortSignal
631
- ): Promise<T8GIModelGeneric<TMeshDescriptor, TStyle, TRegion> | undefined> {
632
- const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
633
-
634
- const t8giItem = twinContent.content.find((item) => item.format === 't8gi');
635
-
636
- if (t8giItem === undefined) {
637
- return undefined;
638
- }
639
-
640
- const data = await this.downloadTwinContent(twinId, twinVersion, t8giItem, signal);
641
-
642
- return readT8GIModelWithFactories(data, meshDescriptorFactory, styleFactory, regionFactory);
643
- }
644
-
645
- loadGeometryInfo(
646
- twin: string | { id: string; version: number },
647
- signal?: AbortSignal
648
- ): Promise<TwinGeometryInfo<T8GIMeshDescriptor, T8GIStyle, T8GIRegion>> {
649
- return this.loadGeometryInfoWithFactories(
650
- twin,
651
- T8GIMeshDescriptor.create,
652
- T8GIStyle.create,
653
- T8GIRegion.create,
654
- signal
655
- );
656
- }
657
-
658
- async loadGeometryInfoWithFactories<TMeshDescriptor, TStyle, TRegion>(
659
- twin: string | { id: string; version: number },
660
- meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
661
- styleFactory: (dto: T8GIStyleDTO) => TStyle,
662
- regionFactory: (dto: T8GIRegionDTO) => TRegion,
663
- signal?: AbortSignal
664
- ): Promise<TwinGeometryInfo<TMeshDescriptor, TStyle, TRegion>> {
665
- let page: string | undefined = undefined;
666
- const twinId = typeof twin === 'string' ? twin : twin.id;
667
- const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
668
-
669
- if (specifiedVersion !== undefined) {
670
- return {
671
- id: twinId,
672
- version: specifiedVersion,
673
- model: await this.loadGeometryInfoVersion(
674
- twinId,
675
- specifiedVersion,
676
- meshDescriptorFactory,
677
- styleFactory,
678
- regionFactory,
679
- signal
680
- )
681
- };
682
- }
683
-
684
- const maxPages = 100;
685
- for (let pageCount = 0; pageCount < maxPages; pageCount++) {
686
- const versions = await this.listTwinVersions(twinId, { page }, signal);
687
- if (versions.data.length === 0) {
688
- break;
689
- }
690
- for (const versionItem of versions.data) {
691
- const model = await this.loadGeometryInfoVersion(
692
- twinId,
693
- versionItem.version,
694
- meshDescriptorFactory,
695
- styleFactory,
696
- regionFactory,
697
- signal
698
- );
699
- if (model !== undefined) {
700
- return {
701
- id: twinId,
702
- version: versionItem.version,
703
- model
704
- };
705
- }
706
- }
707
- page = versions.pagination.nextPage;
708
- }
709
-
710
- throw new Error(`Twin ${twinId} does not have geometry info`);
711
- }
712
-
713
- private async loadTwinWithGeometryVersion(
714
- twinId: string,
715
- twinVersion: number,
716
- signal?: AbortSignal
717
- ): Promise<T8ClientModel<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit> | undefined> {
718
- const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
719
-
720
- const t8cmItem = twinContent.content.find((item) => item.format === 't8cm');
721
- const t8giItem = twinContent.content.find((item) => item.format === 't8gi');
722
-
723
- if (t8cmItem === undefined || t8giItem === undefined) {
724
- return undefined;
725
- }
726
-
727
- const t8cmExtensions = twinContent.content.filter((item) => item.format === 't8cm-ext');
728
- const t8gdItem = twinContent.content.find((item) => item.format === 't8gd');
729
-
730
- const downloads = [
731
- this.downloadTwinContent(twinId, twinVersion, t8cmItem, signal),
732
- ...t8cmExtensions.map((ext) => this.downloadTwinContent(twinId, twinVersion, ext, signal)),
733
- this.downloadTwinContent(twinId, twinVersion, t8giItem, signal),
734
- ...(t8gdItem ? [this.downloadTwinContent(twinId, twinVersion, t8gdItem, signal)] : [])
735
- ];
736
-
737
- const allData = await Promise.all(downloads);
738
-
739
- const t8cmCount = 1 + t8cmExtensions.length;
740
- const t8cmData = allData.slice(0, t8cmCount);
741
- const t8giData = allData[t8cmCount];
742
- const t8gdData = t8gdItem ? allData[t8cmCount + 1] : undefined;
743
-
744
- return readT8ClientModelWithGeometry(t8cmData, t8giData, t8gdData);
745
- }
746
-
747
- async loadTwinWithGeometry(
748
- twin: string | { id: string; version: number },
749
- signal?: AbortSignal
750
- ): Promise<Twin<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit>> {
751
- let page: string | undefined = undefined;
752
- const twinId = typeof twin === 'string' ? twin : twin.id;
753
- const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
754
-
755
- if (specifiedVersion !== undefined) {
756
- return {
757
- id: twinId,
758
- version: specifiedVersion,
759
- model: await this.loadTwinWithGeometryVersion(twinId, specifiedVersion, signal)
760
- };
761
- }
762
-
763
- const maxPages = 100;
764
- for (let pageCount = 0; pageCount < maxPages; pageCount++) {
765
- const versions = await this.listTwinVersions(twinId, { page }, signal);
766
- if (versions.data.length === 0) {
767
- break;
768
- }
769
- for (const versionItem of versions.data) {
770
- const model = await this.loadTwinWithGeometryVersion(twinId, versionItem.version, signal);
771
- if (model !== undefined) {
772
- return {
773
- id: twinId,
774
- version: versionItem.version,
775
- model
776
- };
777
- }
778
- }
779
- page = versions.pagination.nextPage;
780
- }
781
-
782
- throw new Error(`Twin ${twinId} does not have a client model with geometry`);
783
- }
784
-
785
- async createOrUpdateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet> {
786
- const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}`, {
787
- headers: { 'Content-Type': 'application/json' },
788
- body: JSON.stringify(twin),
789
- signal
790
- });
791
-
792
- if (response.ok) {
793
- return (await response.json()) as TwinGet;
794
- }
795
-
796
- if (response.status === 400) {
797
- const errorBody = await response.json();
798
- throw new TwinValidationError(`Twin validation failed: ${errorBody.detail}`, errorBody);
799
- }
800
-
801
- if (response.status === 409) {
802
- const conflictedTwin = (await response.json()) as TwinGet;
803
- throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
804
- }
805
-
806
- const errorText = await response.text();
807
- throw new Error(`Failed to create/update twin: ${response.status} ${response.statusText} - ${errorText}`);
808
- }
809
-
810
- async updateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet> {
811
- return this.createOrUpdateTwin(twinId, twin, signal);
812
- }
813
-
814
- async deleteTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet> {
815
- const response = await this._httpClient.fetch(HttpMethod.Delete, `${this._baseUrl}/${twinId}`, {
816
- headers: { 'Content-Type': 'application/json' },
817
- body: JSON.stringify({ etag }),
818
- signal
819
- });
820
-
821
- if (response.ok) {
822
- return (await response.json()) as TwinGet;
823
- }
824
-
825
- if (response.status === 404) {
826
- throw new TwinNotFoundError(`Twin ${twinId} not found`);
827
- }
828
-
829
- if (response.status === 409) {
830
- const conflictedTwin = (await response.json()) as TwinGet;
831
- throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
832
- }
833
-
834
- const errorText = await response.text();
835
- throw new Error(`Failed to delete twin: ${response.status} ${response.statusText} - ${errorText}`);
836
- }
837
-
838
- async restoreTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet> {
839
- const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/restore`, {
840
- headers: { 'Content-Type': 'application/json' },
841
- body: JSON.stringify({ etag }),
842
- signal
843
- });
844
-
845
- if (response.ok) {
846
- return (await response.json()) as TwinGet;
847
- }
848
-
849
- if (response.status === 404) {
850
- throw new TwinNotFoundError(`Twin ${twinId} not found`);
851
- }
852
-
853
- if (response.status === 409) {
854
- const conflictedTwin = (await response.json()) as TwinGet;
855
- throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
856
- }
857
-
858
- const errorText = await response.text();
859
- throw new Error(`Failed to restore twin: ${response.status} ${response.statusText} - ${errorText}`);
860
- }
861
-
862
- async getTwinVersionContent(
863
- twinId: string,
864
- twinVersion: number,
865
- signal?: AbortSignal
866
- ): Promise<TwinVersionContentResponse> {
867
- const response = await this._httpClient.fetch(
868
- HttpMethod.Get,
869
- `${this._baseUrl}/${twinId}/versions/${twinVersion}/contents`,
870
- { headers: { 'Content-Type': 'application/json' }, signal }
871
- );
872
-
873
- if (response.ok) {
874
- return (await response.json()) as TwinVersionContentResponse;
875
- }
876
-
877
- if (response.status === 404) {
878
- throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
879
- }
880
-
881
- const errorText = await response.text();
882
- throw new Error(`Failed to get twin version content: ${response.status} ${response.statusText} - ${errorText}`);
883
- }
884
-
885
- async getTwinContent(twinId: string, signal?: AbortSignal): Promise<TwinVersionContentResponse> {
886
- const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/contents`, {
887
- headers: { 'Content-Type': 'application/json' },
888
- signal
889
- });
890
-
891
- if (response.ok) {
892
- return (await response.json()) as TwinVersionContentResponse;
893
- }
894
-
895
- if (response.status === 404) {
896
- throw new TwinNotFoundError(`Twin ${twinId} not found`);
897
- }
898
-
899
- const errorText = await response.text();
900
- throw new Error(`Failed to get twin content: ${response.status} ${response.statusText} - ${errorText}`);
901
- }
902
-
903
- async getTwinDiagnostics(twinId: string, signal?: AbortSignal): Promise<TwinDiagnosticsResponse> {
904
- const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/diagnostics`, {
905
- headers: { 'Content-Type': 'application/json' },
906
- signal
907
- });
908
-
909
- if (response.ok) {
910
- return (await response.json()) as TwinDiagnosticsResponse;
911
- }
912
-
913
- if (response.status === 404) {
914
- throw new TwinNotFoundError(`Twin ${twinId} not found`);
915
- }
916
-
917
- const errorText = await response.text();
918
- throw new Error(`Failed to get twin diagnostics: ${response.status} ${response.statusText} - ${errorText}`);
919
- }
920
-
921
- async getTwinVersionDiagnostics(
922
- twinId: string,
923
- twinVersion: number,
924
- signal?: AbortSignal
925
- ): Promise<TwinDiagnosticsResponse> {
926
- const response = await this._httpClient.fetch(
927
- HttpMethod.Get,
928
- `${this._baseUrl}/${twinId}/versions/${twinVersion}/diagnostics`,
929
- { headers: { 'Content-Type': 'application/json' }, signal }
930
- );
931
-
932
- if (response.ok) {
933
- return (await response.json()) as TwinDiagnosticsResponse;
934
- }
935
-
936
- if (response.status === 404) {
937
- throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
938
- }
939
-
940
- const errorText = await response.text();
941
- throw new Error(
942
- `Failed to get twin version diagnostics: ${response.status} ${response.statusText} - ${errorText}`
943
- );
944
- }
945
-
946
- async getTwinVersionEvents(
947
- twinId: string,
948
- twinVersion: number,
949
- offset = 0,
950
- limit = 100,
951
- signal?: AbortSignal
952
- ): Promise<PaginatedResponse<TwinProcessorEvent>> {
953
- const url = `${this._baseUrl}/${twinId}/versions/${twinVersion}/events?offset=${offset}&limit=${limit}`;
954
-
955
- const response = await this._httpClient.fetch(HttpMethod.Get, url, {
956
- headers: { 'Content-Type': 'application/json' },
957
- signal
958
- });
959
-
960
- if (response.ok) {
961
- return (await response.json()) as PaginatedResponse<TwinProcessorEvent>;
962
- }
963
-
964
- if (response.status === 400) {
965
- const errorBody = await response.json();
966
- throw new TwinValidationError(`Twin events validation failed: ${errorBody.detail}`, errorBody);
967
- }
968
-
969
- if (response.status === 404) {
970
- throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
971
- }
972
-
973
- const errorText = await response.text();
974
- throw new Error(`Failed to get twin version events: ${response.status} ${response.statusText} - ${errorText}`);
975
- }
976
-
977
- async getProcessorEvents(
978
- twinId: string,
979
- twinVersion: number,
980
- processorId: string,
981
- offset = 0,
982
- limit = 100,
983
- signal?: AbortSignal
984
- ): Promise<PaginatedResponse<TwinProcessorEvent>> {
985
- const url = `${this._baseUrl}/${twinId}/versions/${twinVersion}/processors/${processorId}/events?offset=${offset}&limit=${limit}`;
986
-
987
- const response = await this._httpClient.fetch(HttpMethod.Get, url, {
988
- headers: { 'Content-Type': 'application/json' },
989
- signal
990
- });
991
-
992
- if (response.ok) {
993
- return (await response.json()) as PaginatedResponse<TwinProcessorEvent>;
994
- }
995
-
996
- if (response.status === 400) {
997
- const errorBody = await response.json();
998
- throw new TwinValidationError(`Processor events validation failed: ${errorBody.detail}`, errorBody);
999
- }
1000
-
1001
- if (response.status === 404) {
1002
- throw new ProcessorNotFoundError(
1003
- `Processor ${processorId} not found for twin ${twinId} version ${twinVersion}`
1004
- );
1005
- }
1006
-
1007
- const errorText = await response.text();
1008
- throw new Error(`Failed to get processor events: ${response.status} ${response.statusText} - ${errorText}`);
1009
- }
1010
-
1011
- async listAssets(
1012
- twinId: string,
1013
- offset = 0,
1014
- limit = 100,
1015
- options?: { includeDeleted?: boolean },
1016
- signal?: AbortSignal
1017
- ): Promise<PaginatedResponse<AssetListItem>> {
1018
- const includeDeleted = options?.includeDeleted ?? false;
1019
- const params = `offset=${offset}&limit=${limit}${includeDeleted ? '&includeDeleted=true' : ''}`;
1020
- const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/assets?${params}`, {
1021
- headers: { 'Content-Type': 'application/json' },
1022
- signal
1023
- });
1024
-
1025
- if (response.ok) {
1026
- return (await response.json()) as PaginatedResponse<AssetListItem>;
1027
- }
1028
-
1029
- if (response.status === 400) {
1030
- const errorBody = await response.json();
1031
- throw new AssetValidationError(`Asset listing validation failed: ${errorBody.detail}`, errorBody);
1032
- }
1033
-
1034
- if (response.status === 404) {
1035
- throw new AssetNotFoundError(`Twin ${twinId} not found`);
1036
- }
1037
-
1038
- const errorText = await response.text();
1039
- throw new Error(`Failed to list assets: ${response.status} ${response.statusText} - ${errorText}`);
1040
- }
1041
-
1042
- async getAsset(twinId: string, assetId: string, signal?: AbortSignal): Promise<AssetGet> {
1043
- const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/assets/${assetId}`, {
1044
- headers: { 'Content-Type': 'application/json' },
1045
- signal
1046
- });
1047
-
1048
- if (response.ok) {
1049
- return (await response.json()) as AssetGet;
1050
- }
1051
-
1052
- if (response.status === 404) {
1053
- throw new AssetNotFoundError(`Asset ${assetId} not found`);
1054
- }
1055
-
1056
- const errorText = await response.text();
1057
- throw new Error(`Failed to get asset: ${response.status} ${response.statusText} - ${errorText}`);
1058
- }
1059
-
1060
- async createAssets(twinId: string, assets: AssetPost[], signal?: AbortSignal): Promise<AssetGet[]> {
1061
- const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets`, {
1062
- headers: { 'Content-Type': 'application/json' },
1063
- body: JSON.stringify(assets),
1064
- signal
1065
- });
1066
-
1067
- if (response.status === 201) {
1068
- return (await response.json()) as AssetGet[];
1069
- }
1070
-
1071
- if (response.status === 400) {
1072
- const errorBody = await response.json();
1073
- throw new AssetValidationError(`Asset validation failed: ${errorBody.detail}`, errorBody);
1074
- }
1075
-
1076
- const errorText = await response.text();
1077
- throw new Error(`Failed to create assets: ${response.status} ${response.statusText} - ${errorText}`);
1078
- }
1079
-
1080
- async updateAsset(twinId: string, assetId: string, asset: AssetPut, signal?: AbortSignal): Promise<AssetGet> {
1081
- const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/assets/${assetId}`, {
1082
- headers: { 'Content-Type': 'application/json' },
1083
- body: JSON.stringify(asset),
1084
- signal
1085
- });
1086
-
1087
- if (response.ok) {
1088
- return (await response.json()) as AssetGet;
1089
- }
1090
-
1091
- if (response.status === 409) {
1092
- const conflictedAsset = (await response.json()) as AssetGet;
1093
- throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1094
- }
1095
-
1096
- if (response.status === 400) {
1097
- const errorBody = await response.json();
1098
- throw new AssetValidationError(`Asset validation failed: ${errorBody.detail}`, errorBody);
1099
- }
1100
-
1101
- const errorText = await response.text();
1102
- throw new Error(`Failed to update asset: ${response.status} ${response.statusText} - ${errorText}`);
1103
- }
1104
-
1105
- async deleteAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet> {
1106
- const response = await this._httpClient.fetch(
1107
- HttpMethod.Delete,
1108
- `${this._baseUrl}/${twinId}/assets/${assetId}`,
1109
- {
1110
- headers: { 'Content-Type': 'application/json' },
1111
- body: JSON.stringify({ etag }),
1112
- signal
1113
- }
1114
- );
1115
-
1116
- if (response.ok) {
1117
- return (await response.json()) as AssetGet;
1118
- }
1119
-
1120
- if (response.status === 409) {
1121
- const conflictedAsset = (await response.json()) as AssetGet;
1122
- throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1123
- }
1124
-
1125
- if (response.status === 404) {
1126
- throw new AssetNotFoundError(`Asset ${assetId} not found`);
1127
- }
1128
-
1129
- const errorText = await response.text();
1130
- throw new Error(`Failed to delete asset: ${response.status} ${response.statusText} - ${errorText}`);
1131
- }
1132
-
1133
- async restoreAsset(twinId: string, assetId: string, etag: string): Promise<AssetGet> {
1134
- const response = await this._httpClient.fetch(
1135
- HttpMethod.Put,
1136
- `${this._baseUrl}/${twinId}/assets/${assetId}/restore`,
1137
- {
1138
- headers: { 'Content-Type': 'application/json' },
1139
- body: JSON.stringify({ etag })
1140
- }
1141
- );
1142
-
1143
- if (response.ok) {
1144
- return (await response.json()) as AssetGet;
1145
- }
1146
-
1147
- if (response.status === 409) {
1148
- const conflictedAsset = (await response.json()) as AssetGet;
1149
- throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1150
- }
1151
-
1152
- if (response.status === 404) {
1153
- throw new AssetNotFoundError(`Asset ${assetId} not found`);
1154
- }
1155
-
1156
- const errorText = await response.text();
1157
- throw new Error(`Failed to restore asset: ${response.status} ${response.statusText} - ${errorText}`);
1158
- }
1159
-
1160
- async batchAssets(
1161
- twinId: string,
1162
- operations: AssetBatchOperation[],
1163
- signal?: AbortSignal
1164
- ): Promise<AssetBatchResponse> {
1165
- const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets/batch`, {
1166
- headers: { 'Content-Type': 'application/json' },
1167
- body: JSON.stringify({ operations }),
1168
- signal
1169
- });
1170
-
1171
- if (response.ok) {
1172
- return (await response.json()) as AssetBatchResponse;
1173
- }
1174
-
1175
- if (response.status === 400) {
1176
- const errorBody = await response.json();
1177
- throw new AssetValidationError(`Asset batch validation failed: ${errorBody.detail}`, errorBody);
1178
- }
1179
-
1180
- if (response.status === 403) {
1181
- const errorText = await response.text();
1182
- throw new AssetForbiddenError(`Asset batch forbidden: ${errorText}`);
1183
- }
1184
-
1185
- if (response.status === 404 || response.status === 409) {
1186
- const batchResponse = (await response.json()) as AssetBatchResponse;
1187
- throw new AssetBatchError(`Asset batch operation failed with status ${response.status}`, batchResponse);
1188
- }
1189
-
1190
- const errorText = await response.text();
1191
- throw new Error(`Failed to execute asset batch: ${response.status} ${response.statusText} - ${errorText}`);
1192
- }
1193
-
1194
- async batchGetAssets(twinId: string, ids: string[], signal?: AbortSignal): Promise<AssetBatchGetResponse> {
1195
- const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets/batch-get`, {
1196
- headers: { 'Content-Type': 'application/json' },
1197
- body: JSON.stringify({ ids }),
1198
- signal
1199
- });
1200
-
1201
- if (response.ok) {
1202
- return (await response.json()) as AssetBatchGetResponse;
1203
- }
1204
-
1205
- if (response.status === 400) {
1206
- const errorBody = await response.json();
1207
- throw new AssetValidationError(`Asset batch-get validation failed: ${errorBody.detail}`, errorBody);
1208
- }
1209
-
1210
- const errorText = await response.text();
1211
- throw new Error(`Failed to batch-get assets: ${response.status} ${response.statusText} - ${errorText}`);
1212
- }
1213
-
1214
- async listTwinFiles(
1215
- twinId: string,
1216
- options: TwinFileListOptions = {},
1217
- signal?: AbortSignal
1218
- ): Promise<PaginatedResponse<TwinFileGet>> {
1219
- const { includeDeleted = false, checkedIn = false, version, page = undefined, limit = 100 } = options;
1220
-
1221
- if (version !== undefined && !checkedIn) {
1222
- throw new Error('The "version" option can only be used when "checkedIn" is true.');
1223
- }
1224
-
1225
- const params = new URLSearchParams();
1226
- if (includeDeleted) params.set('includeDeleted', 'true');
1227
- if (checkedIn) params.set('checkedIn', 'true');
1228
- if (version !== undefined) params.set('version', version.toString());
1229
- if (page !== undefined) params.set('page', page);
1230
- if (limit !== 100) params.set('limit', limit.toString());
1231
-
1232
- const url = params.toString()
1233
- ? `${this._baseUrl}/${twinId}/files?${params}`
1234
- : `${this._baseUrl}/${twinId}/files`;
1235
-
1236
- const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1237
- headers: { 'Content-Type': 'application/json' },
1238
- signal
1239
- });
1240
-
1241
- if (response.ok) {
1242
- return (await response.json()) as PaginatedResponse<TwinFileGet>;
1243
- }
1244
-
1245
- if (response.status === 400) {
1246
- const errorBody = await response.json();
1247
- throw new TwinFileValidationError(`Twin file listing validation failed: ${errorBody.detail}`, errorBody);
1248
- }
1249
-
1250
- const errorText = await response.text();
1251
- throw new Error(`Failed to list twin files: ${response.status} ${response.statusText} - ${errorText}`);
1252
- }
1253
-
1254
- async getTwinFile(twinId: string, fileId: string, signal?: AbortSignal): Promise<TwinFileGet> {
1255
- const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1256
- headers: { 'Content-Type': 'application/json' },
1257
- signal
1258
- });
1259
-
1260
- if (response.ok) {
1261
- return (await response.json()) as TwinFileGet;
1262
- }
1263
-
1264
- if (response.status === 404) {
1265
- throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1266
- }
1267
-
1268
- if (response.status === 400) {
1269
- const errorText = await response.text();
1270
- throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1271
- }
1272
-
1273
- const errorText = await response.text();
1274
- throw new Error(`Failed to get twin file: ${response.status} ${response.statusText} - ${errorText}`);
1275
- }
1276
-
1277
- async createOrUpdateTwinFile(
1278
- twinId: string,
1279
- fileId: string,
1280
- twinFile: TwinFilePut,
1281
- signal?: AbortSignal
1282
- ): Promise<TwinFileGet> {
1283
- const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1284
- headers: { 'Content-Type': 'application/json' },
1285
- body: JSON.stringify(twinFile),
1286
- signal
1287
- });
1288
-
1289
- if (response.ok || response.status === 201) {
1290
- return (await response.json()) as TwinFileGet;
1291
- }
1292
-
1293
- if (response.status === 400) {
1294
- const errorBody = await response.json();
1295
- throw new TwinFileValidationError(`Twin file validation failed`, errorBody);
1296
- }
1297
-
1298
- if (response.status === 409) {
1299
- const conflictedFile = (await response.json()) as TwinFileGet;
1300
- throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1301
- }
1302
-
1303
- const errorText = await response.text();
1304
- throw new Error(`Failed to create/update twin file: ${response.status} ${response.statusText} - ${errorText}`);
1305
- }
1306
-
1307
- async deleteTwinFile(
1308
- twinId: string,
1309
- fileId: string,
1310
- deleteRequest: TwinFileDelete,
1311
- signal?: AbortSignal
1312
- ): Promise<TwinFileGet> {
1313
- const response = await this._httpClient.fetch(HttpMethod.Delete, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1314
- headers: { 'Content-Type': 'application/json' },
1315
- body: JSON.stringify(deleteRequest),
1316
- signal
1317
- });
1318
-
1319
- if (response.ok) {
1320
- return (await response.json()) as TwinFileGet;
1321
- }
1322
-
1323
- if (response.status === 404) {
1324
- throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1325
- }
1326
-
1327
- if (response.status === 409) {
1328
- const conflictedFile = (await response.json()) as TwinFileGet;
1329
- throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1330
- }
1331
-
1332
- if (response.status === 400) {
1333
- const errorText = await response.text();
1334
- throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1335
- }
1336
-
1337
- const errorText = await response.text();
1338
- throw new Error(`Failed to delete twin file: ${response.status} ${response.statusText} - ${errorText}`);
1339
- }
1340
-
1341
- async restoreTwinFile(twinId: string, fileId: string, etag: string, signal?: AbortSignal): Promise<TwinFileGet> {
1342
- const response = await this._httpClient.fetch(
1343
- HttpMethod.Put,
1344
- `${this._baseUrl}/${twinId}/files/${fileId}/restore`,
1345
- {
1346
- headers: { 'Content-Type': 'application/json' },
1347
- body: JSON.stringify({ etag }),
1348
- signal
1349
- }
1350
- );
1351
-
1352
- if (response.ok) {
1353
- return (await response.json()) as TwinFileGet;
1354
- }
1355
-
1356
- if (response.status === 404) {
1357
- throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1358
- }
1359
-
1360
- if (response.status === 409) {
1361
- const conflictedFile = (await response.json()) as TwinFileGet;
1362
- throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1363
- }
1364
-
1365
- if (response.status === 400) {
1366
- const errorText = await response.text();
1367
- throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1368
- }
1369
-
1370
- const errorText = await response.text();
1371
- throw new Error(`Failed to restore twin file: ${response.status} ${response.statusText} - ${errorText}`);
1372
- }
1373
-
1374
- async getTwinFileContent(twinId: string, fileId: string, signal?: AbortSignal): Promise<Blob> {
1375
- const response = await this._httpClient.fetch(
1376
- HttpMethod.Get,
1377
- `${this._baseUrl}/${twinId}/files/${fileId}/content`,
1378
- { signal }
1379
- );
1380
-
1381
- if (response.ok) {
1382
- return await response.blob();
1383
- }
1384
-
1385
- if (response.status === 404) {
1386
- throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1387
- }
1388
-
1389
- const errorText = await response.text();
1390
- throw new Error(`Failed to get twin file content: ${response.status} ${response.statusText} - ${errorText}`);
1391
- }
1392
-
1393
- async getTwinFileVersion(
1394
- twinId: string,
1395
- fileId: string,
1396
- version: number,
1397
- signal?: AbortSignal
1398
- ): Promise<TwinFileGet> {
1399
- const response = await this._httpClient.fetch(
1400
- HttpMethod.Get,
1401
- `${this._baseUrl}/${twinId}/files/${fileId}/versions/${version}`,
1402
- { signal }
1403
- );
1404
-
1405
- if (response.ok) {
1406
- return (await response.json()) as TwinFileGet;
1407
- }
1408
-
1409
- if (response.status === 404) {
1410
- throw new TwinFileNotFoundError(`Twin file ${fileId} version ${version} not found`);
1411
- }
1412
-
1413
- const errorText = await response.text();
1414
- throw new Error(`Failed to get twin file version: ${response.status} ${response.statusText} - ${errorText}`);
1415
- }
1416
-
1417
- async listTwinFileVersions(
1418
- twinId: string,
1419
- fileId: string,
1420
- options?: TwinFileVersionListOptions,
1421
- signal?: AbortSignal
1422
- ): Promise<PaginatedResponse<TwinFileGet>> {
1423
- const params = new URLSearchParams();
1424
- if (options?.includeDeleted !== undefined) params.append('includeDeleted', String(options.includeDeleted));
1425
- if (options?.offset !== undefined) params.append('offset', String(options.offset));
1426
- if (options?.limit !== undefined) params.append('limit', String(options.limit));
1427
-
1428
- const response = await this._httpClient.fetch(
1429
- HttpMethod.Get,
1430
- `${this._baseUrl}/${twinId}/files/${fileId}/versions?${params.toString()}`,
1431
- { signal }
1432
- );
1433
-
1434
- if (response.ok) {
1435
- return (await response.json()) as PaginatedResponse<TwinFileGet>;
1436
- }
1437
-
1438
- if (response.status === 400) {
1439
- const errorBody = await response.json();
1440
- throw new TwinFileValidationError(
1441
- `Twin file version listing validation failed: ${errorBody.detail}`,
1442
- errorBody
1443
- );
1444
- }
1445
-
1446
- const errorText = await response.text();
1447
- throw new Error(`Failed to list twin file versions: ${response.status} ${response.statusText} - ${errorText}`);
1448
- }
1449
-
1450
- async getTwinFileVersionContent(
1451
- twinId: string,
1452
- fileId: string,
1453
- version: number,
1454
- signal?: AbortSignal
1455
- ): Promise<Blob> {
1456
- const response = await this._httpClient.fetch(
1457
- HttpMethod.Get,
1458
- `${this._baseUrl}/${twinId}/files/${fileId}/versions/${version}/content`,
1459
- { signal }
1460
- );
1461
-
1462
- if (response.ok) {
1463
- return await response.blob();
1464
- }
1465
-
1466
- if (response.status === 404) {
1467
- throw new TwinFileNotFoundError(`Twin file ${fileId} version ${version} content not found`);
1468
- }
1469
-
1470
- const errorText = await response.text();
1471
- throw new Error(
1472
- `Failed to get twin file version content: ${response.status} ${response.statusText} - ${errorText}`
1473
- );
1474
- }
1475
-
1476
- async createOrUpdateTwinRaw(twinId: string, twin: unknown, signal?: AbortSignal): Promise<Response> {
1477
- return await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}`, {
1478
- headers: { 'Content-Type': 'application/json' },
1479
- body: JSON.stringify(twin),
1480
- signal
1481
- });
1482
- }
1483
-
1484
- async createOrUpdateTwinFileRaw(
1485
- twinId: string,
1486
- fileId: string,
1487
- twinFile: unknown,
1488
- signal?: AbortSignal
1489
- ): Promise<Response> {
1490
- return await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1491
- headers: { 'Content-Type': 'application/json' },
1492
- body: JSON.stringify(twinFile),
1493
- signal
1494
- });
1495
- }
1496
- }
1
+ import { TwinfinityHttpClient, HttpMethod } from '@twinfinity/authentication';
2
+ import {
3
+ readT8ClientModelWithFactories,
4
+ readT8ClientModelWithGeometry,
5
+ readT8GIModelWithFactories,
6
+ T8ClientEntityTypeDTO,
7
+ T8ClientModel,
8
+ T8ClientModelDTO,
9
+ T8ClientProductConnectionsDTO,
10
+ T8ClientProductDTO,
11
+ T8ClientProjectConnectionsDTO,
12
+ T8ClientProjectDTO,
13
+ T8ClientUnitDTO,
14
+ T8EntityType,
15
+ T8GIMeshDescriptor,
16
+ T8GIMeshDescriptorDTO,
17
+ T8GIStyle,
18
+ T8GIStyleDTO,
19
+ T8GIRegion,
20
+ T8GIRegionDTO,
21
+ T8Product,
22
+ T8ProductWithGeometry,
23
+ T8Project,
24
+ T8Unit
25
+ } from '@twinfinity/t8-client-model';
26
+ import type { T8ProjectWithGeometry } from '@twinfinity/t8-client-model';
27
+ import type { T8GIModelGeneric } from '@twinfinity/t8-client-model';
28
+ import type {
29
+ PaginatedResponse,
30
+ ListTwinItem,
31
+ TwinGet,
32
+ TwinPut,
33
+ TwinVersionContentResponse,
34
+ TwinProcessorEvent,
35
+ TwinDiagnosticsResponse,
36
+ AssetListItem,
37
+ AssetGet,
38
+ AssetPost,
39
+ AssetPut,
40
+ AssetBatchOperation,
41
+ AssetBatchResponse,
42
+ AssetBatchGetResponse,
43
+ TwinFileGet,
44
+ TwinFilePut,
45
+ TwinFileDelete,
46
+ TwinFileListOptions,
47
+ TwinFileVersionListOptions,
48
+ TwinContentResponse
49
+ } from './types';
50
+ import {
51
+ TwinValidationError,
52
+ TwinConflictError,
53
+ TwinNotFoundError,
54
+ ProcessorNotFoundError,
55
+ AssetValidationError,
56
+ AssetForbiddenError,
57
+ AssetConflictError,
58
+ AssetNotFoundError,
59
+ AssetBatchError,
60
+ TwinFileValidationError,
61
+ TwinFileConflictError,
62
+ TwinFileNotFoundError,
63
+ AssetCategoryValidationError,
64
+ AssetCategoryConflictError,
65
+ AssetCategoryNotFoundError,
66
+ AssetCategoryForbiddenError,
67
+ AssetTypeValidationError,
68
+ AssetTypeConflictError,
69
+ AssetTypeNotFoundError,
70
+ AssetTypeForbiddenError,
71
+ AssetCatalogTooLargeError,
72
+ isAssetCatalogTooLargeErrorBody,
73
+ TwinUnauthenticatedError,
74
+ readErrorBody
75
+ } from './errors';
76
+ import type {
77
+ AssetCategoryGet,
78
+ AssetCategoryPut,
79
+ AssetCatalogResponse,
80
+ AssetTypeGet,
81
+ AssetTypePut
82
+ } from './types/asset-types-api';
83
+ import type { MyPermissions } from './types/twin-permissions-api';
84
+ import { Twin } from './types/Twin';
85
+ import { TwinGeometryInfo } from './types/TwinGeometryInfo';
86
+
87
+ export interface ITwinClient {
88
+ /**
89
+ * @param relatedTo - Filter twins by container ID.
90
+ * @throws {TwinValidationError} On invalid query parameters (400).
91
+ */
92
+ listTwins(
93
+ relatedTo?: string,
94
+ page?: string,
95
+ limit?: number,
96
+ signal?: AbortSignal
97
+ ): Promise<PaginatedResponse<ListTwinItem>>;
98
+
99
+ /**
100
+ * Fetches all twins by auto-paginating through {@link listTwins}. Caps at 1000 pages.
101
+ * @param relatedTo - Filter twins by container ID.
102
+ */
103
+ listAllTwins(relatedTo?: string, signal?: AbortSignal): Promise<ListTwinItem[]>;
104
+
105
+ /**
106
+ * @param twin - Twin ID string, or `{id, version}` to fetch a specific version.
107
+ * @throws {TwinNotFoundError} When the twin or version does not exist (404).
108
+ */
109
+ getTwin(twin: string | { id: string; version: number }, signal?: AbortSignal): Promise<TwinGet>;
110
+
111
+ /**
112
+ * @throws {TwinValidationError} On invalid query parameters (400).
113
+ */
114
+ listTwinVersions(
115
+ id: string,
116
+ options?: {
117
+ includeDeleted?: boolean;
118
+ page?: string;
119
+ limit?: number;
120
+ },
121
+ signal?: AbortSignal
122
+ ): Promise<PaginatedResponse<ListTwinItem>>;
123
+
124
+ downloadTwinContent(
125
+ twinId: string,
126
+ twinVersion: number,
127
+ content: TwinContentResponse,
128
+ signal?: AbortSignal
129
+ ): Promise<ArrayBuffer>;
130
+
131
+ /**
132
+ * Downloads and deserializes the T8 client model (t8cm + t8cm-ext) using default types.
133
+ * When no version is specified, searches versions newest-first for one containing t8cm content.
134
+ *
135
+ * @param twin - Twin ID string, or `{id, version}` to load a specific version.
136
+ * @throws {Error} When no version has t8cm content.
137
+ */
138
+ loadTwin(
139
+ twin: string | { id: string; version: number },
140
+ signal?: AbortSignal
141
+ ): Promise<Twin<T8Project, T8Product<T8EntityType>, T8EntityType, T8Unit>>;
142
+
143
+ /**
144
+ * Downloads and deserializes the T8 client model using custom factory functions for domain-specific types.
145
+ * When no version is specified, searches versions newest-first for one containing t8cm content.
146
+ *
147
+ * @param twin - Twin ID string, or `{id, version}` to load a specific version.
148
+ * @throws {Error} When no version has t8cm content.
149
+ */
150
+ loadTwinWithFactories<TProject, TProduct, TEntityType, TUnit>(
151
+ twin: string | { id: string; version: number },
152
+ projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
153
+ productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
154
+ entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
155
+ unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
156
+ connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
157
+ connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
158
+ signal?: AbortSignal
159
+ ): Promise<Twin<TProject, TProduct, TEntityType, TUnit>>;
160
+
161
+ /**
162
+ * Downloads and deserializes geometry info (t8gi) using default types.
163
+ * When no version is specified, searches versions newest-first for one containing t8gi content.
164
+ *
165
+ * @param twin - Twin ID string, or `{id, version}` to load a specific version.
166
+ * @throws {Error} When no version has t8gi content.
167
+ */
168
+ loadGeometryInfo(
169
+ twin: string | { id: string; version: number },
170
+ signal?: AbortSignal
171
+ ): Promise<TwinGeometryInfo<T8GIMeshDescriptor, T8GIStyle, T8GIRegion>>;
172
+
173
+ /**
174
+ * Downloads and deserializes geometry info (t8gi) using custom factory functions.
175
+ * When no version is specified, searches versions newest-first for one containing t8gi content.
176
+ *
177
+ * @param twin - Twin ID string, or `{id, version}` to load a specific version.
178
+ * @throws {Error} When no version has t8gi content.
179
+ */
180
+ loadGeometryInfoWithFactories<TMeshDescriptor, TStyle, TRegion>(
181
+ twin: string | { id: string; version: number },
182
+ meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
183
+ styleFactory: (dto: T8GIStyleDTO) => TStyle,
184
+ regionFactory: (dto: T8GIRegionDTO) => TRegion,
185
+ signal?: AbortSignal
186
+ ): Promise<TwinGeometryInfo<TMeshDescriptor, TStyle, TRegion>>;
187
+
188
+ /**
189
+ * Downloads and deserializes both the client model (t8cm) and geometry (t8gi/t8gd) into a combined result.
190
+ * When no version is specified, searches versions newest-first for one containing both t8cm and t8gi content.
191
+ *
192
+ * @param twin - Twin ID string, or `{id, version}` to load a specific version.
193
+ * @throws {Error} When no version has both t8cm and t8gi content.
194
+ */
195
+ loadTwinWithGeometry(
196
+ twin: string | { id: string; version: number },
197
+ signal?: AbortSignal
198
+ ): Promise<Twin<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit>>;
199
+
200
+ /**
201
+ * Creates a new twin or updates an existing one (upsert). Provide `etag` in the twin body to update.
202
+ *
203
+ * @throws {TwinValidationError} On invalid request body (400).
204
+ * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
205
+ */
206
+ createOrUpdateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet>;
207
+
208
+ /** Alias for {@link createOrUpdateTwin}. */
209
+ updateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet>;
210
+
211
+ /**
212
+ * @throws {TwinNotFoundError} When the twin does not exist (404).
213
+ * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
214
+ */
215
+ restoreTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet>;
216
+
217
+ /**
218
+ * @throws {TwinNotFoundError} When the twin or version does not exist (404).
219
+ */
220
+ getTwinVersionContent(
221
+ twinId: string,
222
+ twinVersion: number,
223
+ signal?: AbortSignal
224
+ ): Promise<TwinVersionContentResponse>;
225
+
226
+ /**
227
+ * Returns content for the latest twin version.
228
+ * @throws {TwinNotFoundError} When the twin does not exist (404).
229
+ */
230
+ getTwinContent(twinId: string, signal?: AbortSignal): Promise<TwinVersionContentResponse>;
231
+
232
+ /** @throws {TwinNotFoundError} When the twin does not exist (404). */
233
+ getTwinDiagnostics(twinId: string, signal?: AbortSignal): Promise<TwinDiagnosticsResponse>;
234
+
235
+ /** @throws {TwinNotFoundError} When the twin or version does not exist (404). */
236
+ getTwinVersionDiagnostics(
237
+ twinId: string,
238
+ twinVersion: number,
239
+ signal?: AbortSignal
240
+ ): Promise<TwinDiagnosticsResponse>;
241
+
242
+ /**
243
+ * @throws {TwinValidationError} On invalid query parameters (400).
244
+ * @throws {TwinNotFoundError} When the twin or version does not exist (404).
245
+ */
246
+ getTwinVersionEvents(
247
+ twinId: string,
248
+ twinVersion: number,
249
+ offset?: number,
250
+ limit?: number,
251
+ signal?: AbortSignal
252
+ ): Promise<PaginatedResponse<TwinProcessorEvent>>;
253
+
254
+ /**
255
+ * @throws {TwinValidationError} On invalid query parameters (400).
256
+ * @throws {ProcessorNotFoundError} When the processor does not exist for this twin version (404).
257
+ */
258
+ getProcessorEvents(
259
+ twinId: string,
260
+ twinVersion: number,
261
+ processorId: string,
262
+ offset?: number,
263
+ limit?: number,
264
+ signal?: AbortSignal
265
+ ): Promise<PaginatedResponse<TwinProcessorEvent>>;
266
+
267
+ /**
268
+ * @throws {AssetValidationError} On invalid query parameters (400).
269
+ * @throws {AssetNotFoundError} When the twin does not exist (404).
270
+ */
271
+ listAssets(
272
+ twinId: string,
273
+ offset?: number,
274
+ limit?: number,
275
+ options?: { includeDeleted?: boolean },
276
+ signal?: AbortSignal
277
+ ): Promise<PaginatedResponse<AssetListItem>>;
278
+
279
+ /** @throws {AssetNotFoundError} When the asset does not exist (404). */
280
+ getAsset(twinId: string, assetId: string, signal?: AbortSignal): Promise<AssetGet>;
281
+
282
+ /** @throws {AssetValidationError} On invalid request body (400). The error's `errorBody` has structured detail. */
283
+ createAssets(twinId: string, assets: AssetPost[], signal?: AbortSignal): Promise<AssetGet[]>;
284
+
285
+ /**
286
+ * @throws {AssetValidationError} On invalid request body (400). The error's `errorBody` has structured detail.
287
+ * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
288
+ */
289
+ updateAsset(twinId: string, assetId: string, asset: AssetPut, signal?: AbortSignal): Promise<AssetGet>;
290
+
291
+ /**
292
+ * @throws {AssetNotFoundError} When the asset does not exist (404).
293
+ * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
294
+ */
295
+ deleteAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet>;
296
+
297
+ /**
298
+ * @throws {AssetNotFoundError} When the asset does not exist (404).
299
+ * @throws {AssetConflictError} On etag mismatch (409). The error's `currentAsset` contains the server's current state.
300
+ */
301
+ restoreAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet>;
302
+
303
+ /**
304
+ * Executes a batch of asset operations (upsert, delete, restore) atomically.
305
+ * All operations succeed or all are rolled back.
306
+ *
307
+ * @param operations - Array of batch operations (max 1000).
308
+ * @throws {AssetValidationError} On validation failure (400).
309
+ * @throws {AssetForbiddenError} On insufficient permissions (403).
310
+ * @throws {AssetBatchError} On conflict (409) or not found (404). The error's `response` has per-item results with reverted statuses.
311
+ */
312
+ batchAssets(twinId: string, operations: AssetBatchOperation[], signal?: AbortSignal): Promise<AssetBatchResponse>;
313
+
314
+ /**
315
+ * Retrieves multiple assets by ID in a single request.
316
+ *
317
+ * @param ids - Array of asset IDs (max 1000).
318
+ * @throws {AssetValidationError} On validation failure (400).
319
+ */
320
+ batchGetAssets(twinId: string, ids: string[], signal?: AbortSignal): Promise<AssetBatchGetResponse>;
321
+
322
+ /**
323
+ * @throws {TwinNotFoundError} When the twin does not exist (404).
324
+ * @throws {TwinConflictError} On etag mismatch (409). The error's `currentTwin` contains the server's current state.
325
+ */
326
+ deleteTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet>;
327
+
328
+ /** @throws {TwinFileValidationError} On invalid query parameters (400). */
329
+ listTwinFiles(
330
+ twinId: string,
331
+ options?: TwinFileListOptions,
332
+ signal?: AbortSignal
333
+ ): Promise<PaginatedResponse<TwinFileGet>>;
334
+
335
+ /**
336
+ * @throws {TwinFileNotFoundError} When the file does not exist (404).
337
+ * @throws {TwinFileValidationError} On invalid request (400).
338
+ */
339
+ getTwinFile(twinId: string, fileId: string, signal?: AbortSignal): Promise<TwinFileGet>;
340
+
341
+ /**
342
+ * @throws {TwinFileValidationError} On invalid request body (400).
343
+ * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
344
+ */
345
+ createOrUpdateTwinFile(
346
+ twinId: string,
347
+ fileId: string,
348
+ twinFile: TwinFilePut,
349
+ signal?: AbortSignal
350
+ ): Promise<TwinFileGet>;
351
+
352
+ /**
353
+ * @throws {TwinFileNotFoundError} When the file does not exist (404).
354
+ * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
355
+ * @throws {TwinFileValidationError} On invalid request (400).
356
+ */
357
+ deleteTwinFile(
358
+ twinId: string,
359
+ fileId: string,
360
+ deleteRequest: TwinFileDelete,
361
+ signal?: AbortSignal
362
+ ): Promise<TwinFileGet>;
363
+
364
+ /**
365
+ * @throws {TwinFileNotFoundError} When the file does not exist (404).
366
+ * @throws {TwinFileConflictError} On etag mismatch (409). The error's `currentTwinFile` contains the server's current state.
367
+ * @throws {TwinFileValidationError} On invalid request (400).
368
+ */
369
+ restoreTwinFile(twinId: string, fileId: string, etag: string, signal?: AbortSignal): Promise<TwinFileGet>;
370
+
371
+ /** @throws {TwinFileNotFoundError} When the file does not exist (404). */
372
+ getTwinFileContent(twinId: string, fileId: string, signal?: AbortSignal): Promise<Blob>;
373
+
374
+ /** @throws {TwinFileNotFoundError} When the file or version does not exist (404). */
375
+ getTwinFileVersion(twinId: string, fileId: string, version: number, signal?: AbortSignal): Promise<TwinFileGet>;
376
+
377
+ /** @throws {TwinFileValidationError} On invalid query parameters (400). */
378
+ listTwinFileVersions(
379
+ twinId: string,
380
+ fileId: string,
381
+ options?: TwinFileVersionListOptions,
382
+ signal?: AbortSignal
383
+ ): Promise<PaginatedResponse<TwinFileGet>>;
384
+
385
+ /** @throws {TwinFileNotFoundError} When the file or version does not exist (404). */
386
+ getTwinFileVersionContent(twinId: string, fileId: string, version: number, signal?: AbortSignal): Promise<Blob>;
387
+
388
+ // ---------- Asset categories (TWINS-3643) ----------
389
+
390
+ /**
391
+ * Returns the caller's named, customer-scoped capabilities against the
392
+ * Twin service (e.g. `ViewAssetTypes`, `EditAssetTypes`). The admin app
393
+ * uses this to enable or disable buttons instead of letting the user
394
+ * click through to a 403.
395
+ *
396
+ * No client-side cache — every call hits the wire. Underlying scope
397
+ * grants don't shift within a session, so callers are expected to
398
+ * memoise the result themselves (e.g. via React Query / a once-on-mount
399
+ * fetch) rather than calling this on every render.
400
+ *
401
+ * Throws {@link TwinUnauthenticatedError} on 401 (no valid auth context;
402
+ * caller should redirect to login). Returns an empty `permissions` array
403
+ * on 403 (authenticated but no Twin-service capabilities). Unknown
404
+ * capability strings should be ignored — adding a new capability is a
405
+ * non-breaking change.
406
+ */
407
+ getMyPermissions(signal?: AbortSignal): Promise<MyPermissions>;
408
+
409
+ /**
410
+ * Returns the Twinfinity meta-schema document — the JSON Schema describing
411
+ * valid asset-type metadata schemas. The bytes the backend itself
412
+ * validates against, served verbatim. Power-user tools (Monaco-backed
413
+ * JSON editors, schema-aware tooling) fetch this at runtime so their
414
+ * in-editor diagnostics line up with what the server will accept,
415
+ * decoupled from the FE bundle's build time.
416
+ */
417
+ getAssetTypeMetaSchema(signal?: AbortSignal): Promise<Record<string, unknown>>;
418
+
419
+ /**
420
+ * @throws {AssetCategoryValidationError} On invalid query parameters (400).
421
+ */
422
+ listAssetCategories(
423
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
424
+ signal?: AbortSignal
425
+ ): Promise<PaginatedResponse<AssetCategoryGet>>;
426
+
427
+ /** @throws {AssetCategoryNotFoundError} When the category does not exist (404). */
428
+ getAssetCategory(categoryId: string, signal?: AbortSignal): Promise<AssetCategoryGet>;
429
+
430
+ /**
431
+ * Upserts an asset category. Provide an empty/missing etag for first writes
432
+ * and the existing etag to update.
433
+ *
434
+ * @throws {AssetCategoryValidationError} On invalid request body (400).
435
+ * @throws {AssetCategoryConflictError} On etag mismatch (409). The error's `currentCategory` contains the server's current state.
436
+ */
437
+ putAssetCategory(categoryId: string, body: AssetCategoryPut, signal?: AbortSignal): Promise<AssetCategoryGet>;
438
+
439
+ /**
440
+ * Returns every version of a single asset category, newest first. Mirrors
441
+ * `listAssetTypeVersions` and `twin.get_twin_versions`.
442
+ *
443
+ * @throws {AssetCategoryNotFoundError} When the category's header row does not exist (404).
444
+ */
445
+ listAssetCategoryVersions(
446
+ categoryId: string,
447
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
448
+ signal?: AbortSignal
449
+ ): Promise<PaginatedResponse<AssetCategoryGet>>;
450
+
451
+ /**
452
+ * Soft-deletes a category. Inserts a new asset_category_versions row with
453
+ * `is_deleted=true`; the previous version is retained as an audit trail.
454
+ *
455
+ * @throws {AssetCategoryNotFoundError} When the category does not exist (404).
456
+ * @throws {AssetCategoryConflictError} On etag mismatch (409).
457
+ */
458
+ deleteAssetCategory(categoryId: string, etag: string, signal?: AbortSignal): Promise<AssetCategoryGet>;
459
+
460
+ /**
461
+ * Restores a soft-deleted category. Inserts a new asset_category_versions
462
+ * row with `is_deleted=false`; mirrors twin restore.
463
+ *
464
+ * @throws {AssetCategoryNotFoundError} When the category does not exist (404).
465
+ * @throws {AssetCategoryConflictError} On etag mismatch (409).
466
+ */
467
+ restoreAssetCategory(categoryId: string, etag: string, signal?: AbortSignal): Promise<AssetCategoryGet>;
468
+
469
+ // ---------- Asset types (TWINS-3643) ----------
470
+
471
+ /** @throws {AssetTypeValidationError} On invalid query parameters (400). */
472
+ listAssetTypes(
473
+ categoryId: string,
474
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
475
+ signal?: AbortSignal
476
+ ): Promise<PaginatedResponse<AssetTypeGet>>;
477
+
478
+ /** @throws {AssetTypeNotFoundError} When the category or type does not exist (404). */
479
+ getAssetType(categoryId: string, typeId: string, signal?: AbortSignal): Promise<AssetTypeGet>;
480
+
481
+ /**
482
+ * Returns every version of a single asset type, newest first. Mirrors
483
+ * `twin.get_twin_versions`.
484
+ *
485
+ * @throws {AssetTypeNotFoundError} When the type's header row does not exist (404).
486
+ */
487
+ listAssetTypeVersions(
488
+ categoryId: string,
489
+ typeId: string,
490
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
491
+ signal?: AbortSignal
492
+ ): Promise<PaginatedResponse<AssetTypeGet>>;
493
+
494
+ /**
495
+ * Upserts an asset type. The metadata schema is validated against the
496
+ * Twinfinity meta-schema at the API boundary; invalid schemas surface as
497
+ * a 400 with `cause: MetadataSchemaInvalid`.
498
+ *
499
+ * @throws {AssetTypeValidationError} On invalid request body (400). The error's `errorBody` carries the structured cause.
500
+ * @throws {AssetTypeConflictError} On etag mismatch (409). The error's `currentType` contains the server's current state.
501
+ */
502
+ putAssetType(categoryId: string, typeId: string, body: AssetTypePut, signal?: AbortSignal): Promise<AssetTypeGet>;
503
+
504
+ /**
505
+ * Soft-deletes a type. Inserts a new asset_type_versions row with
506
+ * `is_deleted=true`; the previous version is retained as an audit trail.
507
+ *
508
+ * @throws {AssetTypeNotFoundError} When the type does not exist (404).
509
+ * @throws {AssetTypeConflictError} On etag mismatch (409).
510
+ */
511
+ deleteAssetType(categoryId: string, typeId: string, etag: string, signal?: AbortSignal): Promise<AssetTypeGet>;
512
+
513
+ /**
514
+ * Restores a soft-deleted type. Inserts a new asset_type_versions row with
515
+ * `is_deleted=false`; mirrors twin restore.
516
+ *
517
+ * @throws {AssetTypeNotFoundError} When the type does not exist (404).
518
+ * @throws {AssetTypeConflictError} On etag mismatch (409).
519
+ */
520
+ restoreAssetType(categoryId: string, typeId: string, etag: string, signal?: AbortSignal): Promise<AssetTypeGet>;
521
+
522
+ /**
523
+ * Returns the customer's asset-type catalog: categories nested with
524
+ * their latest non-deleted types and full metadata schemas inline. One
525
+ * round-trip is enough to populate a picker dropdown and render any
526
+ * per-type metadata form.
527
+ */
528
+ getAssetTypeCatalog(signal?: AbortSignal): Promise<AssetCatalogResponse>;
529
+ }
530
+
531
+ export class TwinClient implements ITwinClient {
532
+ private readonly _baseUrl: string;
533
+ private readonly _assetTypeCatalogUrl: string;
534
+
535
+ constructor(
536
+ baseUrl: string | URL,
537
+ private readonly _httpClient: TwinfinityHttpClient
538
+ ) {
539
+ const base = String(baseUrl).replace(/\/+$/, '');
540
+ this._baseUrl = `${base}/_ps/twins`;
541
+ this._assetTypeCatalogUrl = `${base}/_ps/asset-type-catalog`;
542
+ }
543
+
544
+ async listTwins(
545
+ relatedTo?: string,
546
+ page: string | undefined = undefined,
547
+ limit = 100,
548
+ signal?: AbortSignal
549
+ ): Promise<PaginatedResponse<ListTwinItem>> {
550
+ const params = new URLSearchParams();
551
+ if (relatedTo) params.set('relatedTo', relatedTo);
552
+ if (page !== undefined) params.set('page', page);
553
+ if (limit !== 100) params.set('limit', limit.toString());
554
+
555
+ const url = params.toString() ? `${this._baseUrl}?${params}` : this._baseUrl;
556
+
557
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
558
+ headers: { Accept: 'application/json' },
559
+ signal
560
+ });
561
+
562
+ if (response.ok) {
563
+ return (await response.json()) as PaginatedResponse<ListTwinItem>;
564
+ }
565
+
566
+ if (response.status === 400) {
567
+ const errorBody = await readErrorBody(response);
568
+ throw new TwinValidationError(`Twin listing validation failed: ${errorBody.detail}`, errorBody);
569
+ }
570
+
571
+ const errorText = await response.text();
572
+ throw new Error(`Failed to list twins: ${response.status} ${response.statusText} - ${errorText}`);
573
+ }
574
+
575
+ async listAllTwins(relatedTo?: string, signal?: AbortSignal): Promise<ListTwinItem[]> {
576
+ const allTwins: ListTwinItem[] = [];
577
+ let page: string | undefined = undefined;
578
+ const limit = 100;
579
+ const maxPages = 1000;
580
+
581
+ for (let pageCount = 0; pageCount < maxPages; pageCount++) {
582
+ const response = await this.listTwins(relatedTo, page, limit, signal);
583
+ allTwins.push(...response.data);
584
+
585
+ if (response.data.length < limit) {
586
+ break;
587
+ }
588
+
589
+ page = response.pagination.nextPage;
590
+ }
591
+
592
+ return allTwins;
593
+ }
594
+
595
+ async getTwin(twin: string | { id: string; version: number }, signal?: AbortSignal): Promise<TwinGet> {
596
+ const twinId = typeof twin === 'string' ? twin : twin.id;
597
+ const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
598
+ const response = await this._httpClient.fetch(
599
+ HttpMethod.Get,
600
+ `${this._baseUrl}/${twinId}${specifiedVersion !== undefined ? `/versions/${specifiedVersion}` : ''}`,
601
+ {
602
+ headers: { Accept: 'application/json' },
603
+ signal
604
+ }
605
+ );
606
+
607
+ if (response.ok) {
608
+ return (await response.json()) as TwinGet;
609
+ }
610
+
611
+ if (response.status === 404) {
612
+ throw new TwinNotFoundError(`Twin ${twinId} not found`);
613
+ }
614
+
615
+ const errorText = await response.text();
616
+ throw new Error(`Failed to get twin: ${response.status} ${response.statusText} - ${errorText}`);
617
+ }
618
+
619
+ async listTwinVersions(
620
+ id: string,
621
+ options?: {
622
+ includeDeleted?: boolean;
623
+ page: string | undefined;
624
+ limit?: number;
625
+ },
626
+ signal?: AbortSignal
627
+ ): Promise<PaginatedResponse<ListTwinItem>> {
628
+ const params = new URLSearchParams();
629
+ if (options?.page !== undefined) params.set('page', options.page);
630
+ if (options?.limit !== undefined && options.limit !== 100) params.set('limit', options.limit.toString());
631
+ if (options?.includeDeleted) params.set('includeDeleted', 'true');
632
+
633
+ const url = `${this._baseUrl}/${id}/versions${params.toString() ? `?${params}` : ''}`;
634
+
635
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
636
+ headers: { Accept: 'application/json' },
637
+ signal
638
+ });
639
+
640
+ if (response.ok) {
641
+ return (await response.json()) as PaginatedResponse<ListTwinItem>;
642
+ }
643
+
644
+ if (response.status === 400) {
645
+ const errorBody = await readErrorBody(response);
646
+ throw new TwinValidationError(`Twin listing validation failed: ${errorBody.detail}`, errorBody);
647
+ }
648
+
649
+ const errorText = await response.text();
650
+ throw new Error(`Failed to list twins: ${response.status} ${response.statusText} - ${errorText}`);
651
+ }
652
+
653
+ async downloadTwinContent(
654
+ twinId: string,
655
+ twinVersion: number,
656
+ content: TwinContentResponse,
657
+ signal?: AbortSignal
658
+ ): Promise<ArrayBuffer> {
659
+ const response = await this._httpClient.fetch(
660
+ HttpMethod.Get,
661
+ `${this._baseUrl}/${twinId}/versions/${twinVersion}/contents/${content.id}/content`,
662
+ { signal }
663
+ );
664
+ if (response.ok) {
665
+ const blob = await response.blob();
666
+ return await blob.arrayBuffer();
667
+ }
668
+
669
+ throw new Error(`Failed to download twin content: ${response.status} ${response.statusText}`);
670
+ }
671
+
672
+ private async loadTwinVersion<TProject, TProduct, TEntityType, TUnit>(
673
+ twinId: string,
674
+ twinVersion: number,
675
+ projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
676
+ productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
677
+ entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
678
+ unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
679
+ connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
680
+ connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
681
+ signal?: AbortSignal
682
+ ): Promise<T8ClientModel<TProject, TProduct, TEntityType, TUnit> | undefined> {
683
+ const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
684
+
685
+ const t8cmItem = twinContent.content.find((item) => item.format === 't8cm');
686
+
687
+ if (t8cmItem === undefined) {
688
+ return undefined;
689
+ }
690
+
691
+ const t8cmExtensions = twinContent.content.filter((item) => item.format === 't8cm-ext');
692
+
693
+ const data = await Promise.all(
694
+ [this.downloadTwinContent(twinId, twinVersion, t8cmItem, signal)].concat(
695
+ t8cmExtensions.map((ext) => this.downloadTwinContent(twinId, twinVersion, ext, signal))
696
+ )
697
+ );
698
+
699
+ return readT8ClientModelWithFactories<TProject, TProduct, TEntityType, TUnit>(
700
+ data,
701
+ projectFactory,
702
+ productFactory,
703
+ entityTypeFactory,
704
+ unitFactory,
705
+ connectProject,
706
+ connectProduct
707
+ );
708
+ }
709
+
710
+ loadTwin(
711
+ twin: string | { id: string; version: number },
712
+ signal?: AbortSignal
713
+ ): Promise<Twin<T8Project, T8Product<T8EntityType>, T8EntityType, T8Unit>> {
714
+ return this.loadTwinWithFactories(
715
+ twin,
716
+ T8Project.create<T8Product<T8EntityType>, T8Unit>,
717
+ T8Product.create<T8EntityType, T8Unit>,
718
+ T8EntityType.create,
719
+ T8Unit.create,
720
+ T8Project.connect,
721
+ T8Product.connect,
722
+ signal
723
+ );
724
+ }
725
+
726
+ async loadTwinWithFactories<TProject, TProduct, TEntityType, TUnit>(
727
+ twin: string | { id: string; version: number },
728
+ projectFactory: (dto: T8ClientProjectDTO<TUnit>) => TProject,
729
+ productFactory: (dto: T8ClientProductDTO<TUnit>) => TProduct,
730
+ entityTypeFactory: (dto: T8ClientEntityTypeDTO<TUnit>) => TEntityType,
731
+ unitFactory: (dto: T8ClientUnitDTO, dataModel: T8ClientModelDTO) => TUnit,
732
+ connectProject: (dto: T8ClientProjectConnectionsDTO<TProduct>, project: TProject) => void,
733
+ connectProduct: (dto: T8ClientProductConnectionsDTO<TProduct, TEntityType>, product: TProduct) => void,
734
+ signal?: AbortSignal
735
+ ): Promise<Twin<TProject, TProduct, TEntityType, TUnit>> {
736
+ let page: string | undefined = undefined;
737
+ const twinId = typeof twin === 'string' ? twin : twin.id;
738
+ const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
739
+ if (specifiedVersion !== undefined) {
740
+ return {
741
+ id: twinId,
742
+ version: specifiedVersion,
743
+ model: await this.loadTwinVersion(
744
+ twinId,
745
+ specifiedVersion,
746
+ projectFactory,
747
+ productFactory,
748
+ entityTypeFactory,
749
+ unitFactory,
750
+ connectProject,
751
+ connectProduct,
752
+ signal
753
+ )
754
+ };
755
+ }
756
+
757
+ const maxPages = 100;
758
+ for (let pageCount = 0; pageCount < maxPages; pageCount++) {
759
+ const versions = await this.listTwinVersions(twinId, { page }, signal);
760
+ if (versions.data.length === 0) {
761
+ break;
762
+ }
763
+ for (const versionItem of versions.data) {
764
+ const loadedModel = await this.loadTwinVersion(
765
+ twinId,
766
+ versionItem.version,
767
+ projectFactory,
768
+ productFactory,
769
+ entityTypeFactory,
770
+ unitFactory,
771
+ connectProject,
772
+ connectProduct,
773
+ signal
774
+ );
775
+ if (loadedModel !== undefined) {
776
+ return {
777
+ id: twinId,
778
+ version: versionItem.version,
779
+ model: loadedModel
780
+ };
781
+ }
782
+ }
783
+ page = versions.pagination.nextPage;
784
+ }
785
+
786
+ throw new Error(`Twin ${twinId} does not have a client model`);
787
+ }
788
+
789
+ private async loadGeometryInfoVersion<TMeshDescriptor, TStyle, TRegion>(
790
+ twinId: string,
791
+ twinVersion: number,
792
+ meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
793
+ styleFactory: (dto: T8GIStyleDTO) => TStyle,
794
+ regionFactory: (dto: T8GIRegionDTO) => TRegion,
795
+ signal?: AbortSignal
796
+ ): Promise<T8GIModelGeneric<TMeshDescriptor, TStyle, TRegion> | undefined> {
797
+ const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
798
+
799
+ const t8giItem = twinContent.content.find((item) => item.format === 't8gi');
800
+
801
+ if (t8giItem === undefined) {
802
+ return undefined;
803
+ }
804
+
805
+ const data = await this.downloadTwinContent(twinId, twinVersion, t8giItem, signal);
806
+
807
+ return readT8GIModelWithFactories(data, meshDescriptorFactory, styleFactory, regionFactory);
808
+ }
809
+
810
+ loadGeometryInfo(
811
+ twin: string | { id: string; version: number },
812
+ signal?: AbortSignal
813
+ ): Promise<TwinGeometryInfo<T8GIMeshDescriptor, T8GIStyle, T8GIRegion>> {
814
+ return this.loadGeometryInfoWithFactories(
815
+ twin,
816
+ T8GIMeshDescriptor.create,
817
+ T8GIStyle.create,
818
+ T8GIRegion.create,
819
+ signal
820
+ );
821
+ }
822
+
823
+ async loadGeometryInfoWithFactories<TMeshDescriptor, TStyle, TRegion>(
824
+ twin: string | { id: string; version: number },
825
+ meshDescriptorFactory: (dto: T8GIMeshDescriptorDTO) => TMeshDescriptor,
826
+ styleFactory: (dto: T8GIStyleDTO) => TStyle,
827
+ regionFactory: (dto: T8GIRegionDTO) => TRegion,
828
+ signal?: AbortSignal
829
+ ): Promise<TwinGeometryInfo<TMeshDescriptor, TStyle, TRegion>> {
830
+ let page: string | undefined = undefined;
831
+ const twinId = typeof twin === 'string' ? twin : twin.id;
832
+ const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
833
+
834
+ if (specifiedVersion !== undefined) {
835
+ return {
836
+ id: twinId,
837
+ version: specifiedVersion,
838
+ model: await this.loadGeometryInfoVersion(
839
+ twinId,
840
+ specifiedVersion,
841
+ meshDescriptorFactory,
842
+ styleFactory,
843
+ regionFactory,
844
+ signal
845
+ )
846
+ };
847
+ }
848
+
849
+ const maxPages = 100;
850
+ for (let pageCount = 0; pageCount < maxPages; pageCount++) {
851
+ const versions = await this.listTwinVersions(twinId, { page }, signal);
852
+ if (versions.data.length === 0) {
853
+ break;
854
+ }
855
+ for (const versionItem of versions.data) {
856
+ const model = await this.loadGeometryInfoVersion(
857
+ twinId,
858
+ versionItem.version,
859
+ meshDescriptorFactory,
860
+ styleFactory,
861
+ regionFactory,
862
+ signal
863
+ );
864
+ if (model !== undefined) {
865
+ return {
866
+ id: twinId,
867
+ version: versionItem.version,
868
+ model
869
+ };
870
+ }
871
+ }
872
+ page = versions.pagination.nextPage;
873
+ }
874
+
875
+ throw new Error(`Twin ${twinId} does not have geometry info`);
876
+ }
877
+
878
+ private async loadTwinWithGeometryVersion(
879
+ twinId: string,
880
+ twinVersion: number,
881
+ signal?: AbortSignal
882
+ ): Promise<T8ClientModel<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit> | undefined> {
883
+ const twinContent = await this.getTwinVersionContent(twinId, twinVersion, signal);
884
+
885
+ const t8cmItem = twinContent.content.find((item) => item.format === 't8cm');
886
+ const t8giItem = twinContent.content.find((item) => item.format === 't8gi');
887
+
888
+ if (t8cmItem === undefined || t8giItem === undefined) {
889
+ return undefined;
890
+ }
891
+
892
+ const t8cmExtensions = twinContent.content.filter((item) => item.format === 't8cm-ext');
893
+ const t8gdItem = twinContent.content.find((item) => item.format === 't8gd');
894
+
895
+ const downloads = [
896
+ this.downloadTwinContent(twinId, twinVersion, t8cmItem, signal),
897
+ ...t8cmExtensions.map((ext) => this.downloadTwinContent(twinId, twinVersion, ext, signal)),
898
+ this.downloadTwinContent(twinId, twinVersion, t8giItem, signal),
899
+ ...(t8gdItem ? [this.downloadTwinContent(twinId, twinVersion, t8gdItem, signal)] : [])
900
+ ];
901
+
902
+ const allData = await Promise.all(downloads);
903
+
904
+ const t8cmCount = 1 + t8cmExtensions.length;
905
+ const t8cmData = allData.slice(0, t8cmCount);
906
+ const t8giData = allData[t8cmCount];
907
+ const t8gdData = t8gdItem ? allData[t8cmCount + 1] : undefined;
908
+
909
+ return readT8ClientModelWithGeometry(t8cmData, t8giData, t8gdData);
910
+ }
911
+
912
+ async loadTwinWithGeometry(
913
+ twin: string | { id: string; version: number },
914
+ signal?: AbortSignal
915
+ ): Promise<Twin<T8ProjectWithGeometry, T8ProductWithGeometry, T8EntityType, T8Unit>> {
916
+ let page: string | undefined = undefined;
917
+ const twinId = typeof twin === 'string' ? twin : twin.id;
918
+ const specifiedVersion = typeof twin === 'string' ? undefined : twin.version;
919
+
920
+ if (specifiedVersion !== undefined) {
921
+ return {
922
+ id: twinId,
923
+ version: specifiedVersion,
924
+ model: await this.loadTwinWithGeometryVersion(twinId, specifiedVersion, signal)
925
+ };
926
+ }
927
+
928
+ const maxPages = 100;
929
+ for (let pageCount = 0; pageCount < maxPages; pageCount++) {
930
+ const versions = await this.listTwinVersions(twinId, { page }, signal);
931
+ if (versions.data.length === 0) {
932
+ break;
933
+ }
934
+ for (const versionItem of versions.data) {
935
+ const model = await this.loadTwinWithGeometryVersion(twinId, versionItem.version, signal);
936
+ if (model !== undefined) {
937
+ return {
938
+ id: twinId,
939
+ version: versionItem.version,
940
+ model
941
+ };
942
+ }
943
+ }
944
+ page = versions.pagination.nextPage;
945
+ }
946
+
947
+ throw new Error(`Twin ${twinId} does not have a client model with geometry`);
948
+ }
949
+
950
+ async createOrUpdateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet> {
951
+ const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}`, {
952
+ headers: { 'Content-Type': 'application/json' },
953
+ body: JSON.stringify(twin),
954
+ signal
955
+ });
956
+
957
+ if (response.ok) {
958
+ return (await response.json()) as TwinGet;
959
+ }
960
+
961
+ if (response.status === 400) {
962
+ const errorBody = await readErrorBody(response);
963
+ throw new TwinValidationError(`Twin validation failed: ${errorBody.detail}`, errorBody);
964
+ }
965
+
966
+ if (response.status === 409) {
967
+ const conflictedTwin = (await response.json()) as TwinGet;
968
+ throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
969
+ }
970
+
971
+ const errorText = await response.text();
972
+ throw new Error(`Failed to create/update twin: ${response.status} ${response.statusText} - ${errorText}`);
973
+ }
974
+
975
+ async updateTwin(twinId: string, twin: TwinPut, signal?: AbortSignal): Promise<TwinGet> {
976
+ return this.createOrUpdateTwin(twinId, twin, signal);
977
+ }
978
+
979
+ async deleteTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet> {
980
+ const response = await this._httpClient.fetch(HttpMethod.Delete, `${this._baseUrl}/${twinId}`, {
981
+ headers: { 'Content-Type': 'application/json' },
982
+ body: JSON.stringify({ etag }),
983
+ signal
984
+ });
985
+
986
+ if (response.ok) {
987
+ return (await response.json()) as TwinGet;
988
+ }
989
+
990
+ if (response.status === 404) {
991
+ throw new TwinNotFoundError(`Twin ${twinId} not found`);
992
+ }
993
+
994
+ if (response.status === 409) {
995
+ const conflictedTwin = (await response.json()) as TwinGet;
996
+ throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
997
+ }
998
+
999
+ const errorText = await response.text();
1000
+ throw new Error(`Failed to delete twin: ${response.status} ${response.statusText} - ${errorText}`);
1001
+ }
1002
+
1003
+ async restoreTwin(twinId: string, etag: string, signal?: AbortSignal): Promise<TwinGet> {
1004
+ const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/restore`, {
1005
+ headers: { 'Content-Type': 'application/json' },
1006
+ body: JSON.stringify({ etag }),
1007
+ signal
1008
+ });
1009
+
1010
+ if (response.ok) {
1011
+ return (await response.json()) as TwinGet;
1012
+ }
1013
+
1014
+ if (response.status === 404) {
1015
+ throw new TwinNotFoundError(`Twin ${twinId} not found`);
1016
+ }
1017
+
1018
+ if (response.status === 409) {
1019
+ const conflictedTwin = (await response.json()) as TwinGet;
1020
+ throw new TwinConflictError('Twin has been modified by another user', conflictedTwin);
1021
+ }
1022
+
1023
+ const errorText = await response.text();
1024
+ throw new Error(`Failed to restore twin: ${response.status} ${response.statusText} - ${errorText}`);
1025
+ }
1026
+
1027
+ async getTwinVersionContent(
1028
+ twinId: string,
1029
+ twinVersion: number,
1030
+ signal?: AbortSignal
1031
+ ): Promise<TwinVersionContentResponse> {
1032
+ const response = await this._httpClient.fetch(
1033
+ HttpMethod.Get,
1034
+ `${this._baseUrl}/${twinId}/versions/${twinVersion}/contents`,
1035
+ { headers: { Accept: 'application/json' }, signal }
1036
+ );
1037
+
1038
+ if (response.ok) {
1039
+ return (await response.json()) as TwinVersionContentResponse;
1040
+ }
1041
+
1042
+ if (response.status === 404) {
1043
+ throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
1044
+ }
1045
+
1046
+ const errorText = await response.text();
1047
+ throw new Error(`Failed to get twin version content: ${response.status} ${response.statusText} - ${errorText}`);
1048
+ }
1049
+
1050
+ async getTwinContent(twinId: string, signal?: AbortSignal): Promise<TwinVersionContentResponse> {
1051
+ const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/contents`, {
1052
+ headers: { Accept: 'application/json' },
1053
+ signal
1054
+ });
1055
+
1056
+ if (response.ok) {
1057
+ return (await response.json()) as TwinVersionContentResponse;
1058
+ }
1059
+
1060
+ if (response.status === 404) {
1061
+ throw new TwinNotFoundError(`Twin ${twinId} not found`);
1062
+ }
1063
+
1064
+ const errorText = await response.text();
1065
+ throw new Error(`Failed to get twin content: ${response.status} ${response.statusText} - ${errorText}`);
1066
+ }
1067
+
1068
+ async getTwinDiagnostics(twinId: string, signal?: AbortSignal): Promise<TwinDiagnosticsResponse> {
1069
+ const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/diagnostics`, {
1070
+ headers: { Accept: 'application/json' },
1071
+ signal
1072
+ });
1073
+
1074
+ if (response.ok) {
1075
+ return (await response.json()) as TwinDiagnosticsResponse;
1076
+ }
1077
+
1078
+ if (response.status === 404) {
1079
+ throw new TwinNotFoundError(`Twin ${twinId} not found`);
1080
+ }
1081
+
1082
+ const errorText = await response.text();
1083
+ throw new Error(`Failed to get twin diagnostics: ${response.status} ${response.statusText} - ${errorText}`);
1084
+ }
1085
+
1086
+ async getTwinVersionDiagnostics(
1087
+ twinId: string,
1088
+ twinVersion: number,
1089
+ signal?: AbortSignal
1090
+ ): Promise<TwinDiagnosticsResponse> {
1091
+ const response = await this._httpClient.fetch(
1092
+ HttpMethod.Get,
1093
+ `${this._baseUrl}/${twinId}/versions/${twinVersion}/diagnostics`,
1094
+ { headers: { Accept: 'application/json' }, signal }
1095
+ );
1096
+
1097
+ if (response.ok) {
1098
+ return (await response.json()) as TwinDiagnosticsResponse;
1099
+ }
1100
+
1101
+ if (response.status === 404) {
1102
+ throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
1103
+ }
1104
+
1105
+ const errorText = await response.text();
1106
+ throw new Error(
1107
+ `Failed to get twin version diagnostics: ${response.status} ${response.statusText} - ${errorText}`
1108
+ );
1109
+ }
1110
+
1111
+ async getTwinVersionEvents(
1112
+ twinId: string,
1113
+ twinVersion: number,
1114
+ offset = 0,
1115
+ limit = 100,
1116
+ signal?: AbortSignal
1117
+ ): Promise<PaginatedResponse<TwinProcessorEvent>> {
1118
+ const url = `${this._baseUrl}/${twinId}/versions/${twinVersion}/events?offset=${offset}&limit=${limit}`;
1119
+
1120
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1121
+ headers: { Accept: 'application/json' },
1122
+ signal
1123
+ });
1124
+
1125
+ if (response.ok) {
1126
+ return (await response.json()) as PaginatedResponse<TwinProcessorEvent>;
1127
+ }
1128
+
1129
+ if (response.status === 400) {
1130
+ const errorBody = await readErrorBody(response);
1131
+ throw new TwinValidationError(`Twin events validation failed: ${errorBody.detail}`, errorBody);
1132
+ }
1133
+
1134
+ if (response.status === 404) {
1135
+ throw new TwinNotFoundError(`Twin ${twinId} version ${twinVersion} not found`);
1136
+ }
1137
+
1138
+ const errorText = await response.text();
1139
+ throw new Error(`Failed to get twin version events: ${response.status} ${response.statusText} - ${errorText}`);
1140
+ }
1141
+
1142
+ async getProcessorEvents(
1143
+ twinId: string,
1144
+ twinVersion: number,
1145
+ processorId: string,
1146
+ offset = 0,
1147
+ limit = 100,
1148
+ signal?: AbortSignal
1149
+ ): Promise<PaginatedResponse<TwinProcessorEvent>> {
1150
+ const url = `${this._baseUrl}/${twinId}/versions/${twinVersion}/processors/${processorId}/events?offset=${offset}&limit=${limit}`;
1151
+
1152
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1153
+ headers: { Accept: 'application/json' },
1154
+ signal
1155
+ });
1156
+
1157
+ if (response.ok) {
1158
+ return (await response.json()) as PaginatedResponse<TwinProcessorEvent>;
1159
+ }
1160
+
1161
+ if (response.status === 400) {
1162
+ const errorBody = await readErrorBody(response);
1163
+ throw new TwinValidationError(`Processor events validation failed: ${errorBody.detail}`, errorBody);
1164
+ }
1165
+
1166
+ if (response.status === 404) {
1167
+ throw new ProcessorNotFoundError(
1168
+ `Processor ${processorId} not found for twin ${twinId} version ${twinVersion}`
1169
+ );
1170
+ }
1171
+
1172
+ const errorText = await response.text();
1173
+ throw new Error(`Failed to get processor events: ${response.status} ${response.statusText} - ${errorText}`);
1174
+ }
1175
+
1176
+ async listAssets(
1177
+ twinId: string,
1178
+ offset = 0,
1179
+ limit = 100,
1180
+ options?: { includeDeleted?: boolean },
1181
+ signal?: AbortSignal
1182
+ ): Promise<PaginatedResponse<AssetListItem>> {
1183
+ const includeDeleted = options?.includeDeleted ?? false;
1184
+ const params = `offset=${offset}&limit=${limit}${includeDeleted ? '&includeDeleted=true' : ''}`;
1185
+ const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/assets?${params}`, {
1186
+ headers: { Accept: 'application/json' },
1187
+ signal
1188
+ });
1189
+
1190
+ if (response.ok) {
1191
+ return (await response.json()) as PaginatedResponse<AssetListItem>;
1192
+ }
1193
+
1194
+ if (response.status === 400) {
1195
+ const errorBody = await readErrorBody(response);
1196
+ throw new AssetValidationError(`Asset listing validation failed: ${errorBody.detail}`, errorBody);
1197
+ }
1198
+
1199
+ if (response.status === 404) {
1200
+ throw new AssetNotFoundError(`Twin ${twinId} not found`);
1201
+ }
1202
+
1203
+ const errorText = await response.text();
1204
+ throw new Error(`Failed to list assets: ${response.status} ${response.statusText} - ${errorText}`);
1205
+ }
1206
+
1207
+ async getAsset(twinId: string, assetId: string, signal?: AbortSignal): Promise<AssetGet> {
1208
+ const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/assets/${assetId}`, {
1209
+ headers: { Accept: 'application/json' },
1210
+ signal
1211
+ });
1212
+
1213
+ if (response.ok) {
1214
+ return (await response.json()) as AssetGet;
1215
+ }
1216
+
1217
+ if (response.status === 404) {
1218
+ throw new AssetNotFoundError(`Asset ${assetId} not found`);
1219
+ }
1220
+
1221
+ const errorText = await response.text();
1222
+ throw new Error(`Failed to get asset: ${response.status} ${response.statusText} - ${errorText}`);
1223
+ }
1224
+
1225
+ async createAssets(twinId: string, assets: AssetPost[], signal?: AbortSignal): Promise<AssetGet[]> {
1226
+ const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets`, {
1227
+ headers: { 'Content-Type': 'application/json' },
1228
+ body: JSON.stringify(assets),
1229
+ signal
1230
+ });
1231
+
1232
+ if (response.status === 201) {
1233
+ return (await response.json()) as AssetGet[];
1234
+ }
1235
+
1236
+ if (response.status === 400) {
1237
+ const errorBody = await readErrorBody(response);
1238
+ throw new AssetValidationError(`Asset validation failed: ${errorBody.detail}`, errorBody);
1239
+ }
1240
+
1241
+ const errorText = await response.text();
1242
+ throw new Error(`Failed to create assets: ${response.status} ${response.statusText} - ${errorText}`);
1243
+ }
1244
+
1245
+ async updateAsset(twinId: string, assetId: string, asset: AssetPut, signal?: AbortSignal): Promise<AssetGet> {
1246
+ const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/assets/${assetId}`, {
1247
+ headers: { 'Content-Type': 'application/json' },
1248
+ body: JSON.stringify(asset),
1249
+ signal
1250
+ });
1251
+
1252
+ if (response.ok) {
1253
+ return (await response.json()) as AssetGet;
1254
+ }
1255
+
1256
+ if (response.status === 409) {
1257
+ const conflictedAsset = (await response.json()) as AssetGet;
1258
+ throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1259
+ }
1260
+
1261
+ if (response.status === 400) {
1262
+ const errorBody = await readErrorBody(response);
1263
+ throw new AssetValidationError(`Asset validation failed: ${errorBody.detail}`, errorBody);
1264
+ }
1265
+
1266
+ const errorText = await response.text();
1267
+ throw new Error(`Failed to update asset: ${response.status} ${response.statusText} - ${errorText}`);
1268
+ }
1269
+
1270
+ async deleteAsset(twinId: string, assetId: string, etag: string, signal?: AbortSignal): Promise<AssetGet> {
1271
+ const response = await this._httpClient.fetch(
1272
+ HttpMethod.Delete,
1273
+ `${this._baseUrl}/${twinId}/assets/${assetId}`,
1274
+ {
1275
+ headers: { 'Content-Type': 'application/json' },
1276
+ body: JSON.stringify({ etag }),
1277
+ signal
1278
+ }
1279
+ );
1280
+
1281
+ if (response.ok) {
1282
+ return (await response.json()) as AssetGet;
1283
+ }
1284
+
1285
+ if (response.status === 409) {
1286
+ const conflictedAsset = (await response.json()) as AssetGet;
1287
+ throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1288
+ }
1289
+
1290
+ if (response.status === 404) {
1291
+ throw new AssetNotFoundError(`Asset ${assetId} not found`);
1292
+ }
1293
+
1294
+ const errorText = await response.text();
1295
+ throw new Error(`Failed to delete asset: ${response.status} ${response.statusText} - ${errorText}`);
1296
+ }
1297
+
1298
+ async restoreAsset(twinId: string, assetId: string, etag: string): Promise<AssetGet> {
1299
+ const response = await this._httpClient.fetch(
1300
+ HttpMethod.Put,
1301
+ `${this._baseUrl}/${twinId}/assets/${assetId}/restore`,
1302
+ {
1303
+ headers: { 'Content-Type': 'application/json' },
1304
+ body: JSON.stringify({ etag })
1305
+ }
1306
+ );
1307
+
1308
+ if (response.ok) {
1309
+ return (await response.json()) as AssetGet;
1310
+ }
1311
+
1312
+ if (response.status === 409) {
1313
+ const conflictedAsset = (await response.json()) as AssetGet;
1314
+ throw new AssetConflictError('Asset has been modified by another user', conflictedAsset);
1315
+ }
1316
+
1317
+ if (response.status === 404) {
1318
+ throw new AssetNotFoundError(`Asset ${assetId} not found`);
1319
+ }
1320
+
1321
+ const errorText = await response.text();
1322
+ throw new Error(`Failed to restore asset: ${response.status} ${response.statusText} - ${errorText}`);
1323
+ }
1324
+
1325
+ async batchAssets(
1326
+ twinId: string,
1327
+ operations: AssetBatchOperation[],
1328
+ signal?: AbortSignal
1329
+ ): Promise<AssetBatchResponse> {
1330
+ const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets/batch`, {
1331
+ headers: { 'Content-Type': 'application/json' },
1332
+ body: JSON.stringify({ operations }),
1333
+ signal
1334
+ });
1335
+
1336
+ if (response.ok) {
1337
+ return (await response.json()) as AssetBatchResponse;
1338
+ }
1339
+
1340
+ if (response.status === 400) {
1341
+ const errorBody = await readErrorBody(response);
1342
+ throw new AssetValidationError(`Asset batch validation failed: ${errorBody.detail}`, errorBody);
1343
+ }
1344
+
1345
+ if (response.status === 403) {
1346
+ const errorText = await response.text();
1347
+ throw new AssetForbiddenError(`Asset batch forbidden: ${errorText}`);
1348
+ }
1349
+
1350
+ if (response.status === 404 || response.status === 409) {
1351
+ const batchResponse = (await response.json()) as AssetBatchResponse;
1352
+ throw new AssetBatchError(`Asset batch operation failed with status ${response.status}`, batchResponse);
1353
+ }
1354
+
1355
+ const errorText = await response.text();
1356
+ throw new Error(`Failed to execute asset batch: ${response.status} ${response.statusText} - ${errorText}`);
1357
+ }
1358
+
1359
+ async batchGetAssets(twinId: string, ids: string[], signal?: AbortSignal): Promise<AssetBatchGetResponse> {
1360
+ const response = await this._httpClient.fetch(HttpMethod.Post, `${this._baseUrl}/${twinId}/assets/batch-get`, {
1361
+ headers: { 'Content-Type': 'application/json' },
1362
+ body: JSON.stringify({ ids }),
1363
+ signal
1364
+ });
1365
+
1366
+ if (response.ok) {
1367
+ return (await response.json()) as AssetBatchGetResponse;
1368
+ }
1369
+
1370
+ if (response.status === 400) {
1371
+ const errorBody = await readErrorBody(response);
1372
+ throw new AssetValidationError(`Asset batch-get validation failed: ${errorBody.detail}`, errorBody);
1373
+ }
1374
+
1375
+ const errorText = await response.text();
1376
+ throw new Error(`Failed to batch-get assets: ${response.status} ${response.statusText} - ${errorText}`);
1377
+ }
1378
+
1379
+ async listTwinFiles(
1380
+ twinId: string,
1381
+ options: TwinFileListOptions = {},
1382
+ signal?: AbortSignal
1383
+ ): Promise<PaginatedResponse<TwinFileGet>> {
1384
+ const { includeDeleted = false, checkedIn = false, version, page = undefined, limit = 100 } = options;
1385
+
1386
+ if (version !== undefined && !checkedIn) {
1387
+ throw new Error('The "version" option can only be used when "checkedIn" is true.');
1388
+ }
1389
+
1390
+ const params = new URLSearchParams();
1391
+ if (includeDeleted) params.set('includeDeleted', 'true');
1392
+ if (checkedIn) params.set('checkedIn', 'true');
1393
+ if (version !== undefined) params.set('version', version.toString());
1394
+ if (page !== undefined) params.set('page', page);
1395
+ if (limit !== 100) params.set('limit', limit.toString());
1396
+
1397
+ const url = params.toString()
1398
+ ? `${this._baseUrl}/${twinId}/files?${params}`
1399
+ : `${this._baseUrl}/${twinId}/files`;
1400
+
1401
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1402
+ headers: { Accept: 'application/json' },
1403
+ signal
1404
+ });
1405
+
1406
+ if (response.ok) {
1407
+ return (await response.json()) as PaginatedResponse<TwinFileGet>;
1408
+ }
1409
+
1410
+ if (response.status === 400) {
1411
+ const errorBody = await readErrorBody(response);
1412
+ throw new TwinFileValidationError(`Twin file listing validation failed: ${errorBody.detail}`, errorBody);
1413
+ }
1414
+
1415
+ const errorText = await response.text();
1416
+ throw new Error(`Failed to list twin files: ${response.status} ${response.statusText} - ${errorText}`);
1417
+ }
1418
+
1419
+ async getTwinFile(twinId: string, fileId: string, signal?: AbortSignal): Promise<TwinFileGet> {
1420
+ const response = await this._httpClient.fetch(HttpMethod.Get, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1421
+ headers: { Accept: 'application/json' },
1422
+ signal
1423
+ });
1424
+
1425
+ if (response.ok) {
1426
+ return (await response.json()) as TwinFileGet;
1427
+ }
1428
+
1429
+ if (response.status === 404) {
1430
+ throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1431
+ }
1432
+
1433
+ if (response.status === 400) {
1434
+ const errorText = await response.text();
1435
+ throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1436
+ }
1437
+
1438
+ const errorText = await response.text();
1439
+ throw new Error(`Failed to get twin file: ${response.status} ${response.statusText} - ${errorText}`);
1440
+ }
1441
+
1442
+ async createOrUpdateTwinFile(
1443
+ twinId: string,
1444
+ fileId: string,
1445
+ twinFile: TwinFilePut,
1446
+ signal?: AbortSignal
1447
+ ): Promise<TwinFileGet> {
1448
+ const response = await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1449
+ headers: { 'Content-Type': 'application/json' },
1450
+ body: JSON.stringify(twinFile),
1451
+ signal
1452
+ });
1453
+
1454
+ if (response.ok || response.status === 201) {
1455
+ return (await response.json()) as TwinFileGet;
1456
+ }
1457
+
1458
+ if (response.status === 400) {
1459
+ const errorBody = await readErrorBody(response);
1460
+ throw new TwinFileValidationError(`Twin file validation failed`, errorBody);
1461
+ }
1462
+
1463
+ if (response.status === 409) {
1464
+ const conflictedFile = (await response.json()) as TwinFileGet;
1465
+ throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1466
+ }
1467
+
1468
+ const errorText = await response.text();
1469
+ throw new Error(`Failed to create/update twin file: ${response.status} ${response.statusText} - ${errorText}`);
1470
+ }
1471
+
1472
+ async deleteTwinFile(
1473
+ twinId: string,
1474
+ fileId: string,
1475
+ deleteRequest: TwinFileDelete,
1476
+ signal?: AbortSignal
1477
+ ): Promise<TwinFileGet> {
1478
+ const response = await this._httpClient.fetch(HttpMethod.Delete, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1479
+ headers: { 'Content-Type': 'application/json' },
1480
+ body: JSON.stringify(deleteRequest),
1481
+ signal
1482
+ });
1483
+
1484
+ if (response.ok) {
1485
+ return (await response.json()) as TwinFileGet;
1486
+ }
1487
+
1488
+ if (response.status === 404) {
1489
+ throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1490
+ }
1491
+
1492
+ if (response.status === 409) {
1493
+ const conflictedFile = (await response.json()) as TwinFileGet;
1494
+ throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1495
+ }
1496
+
1497
+ if (response.status === 400) {
1498
+ const errorText = await response.text();
1499
+ throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1500
+ }
1501
+
1502
+ const errorText = await response.text();
1503
+ throw new Error(`Failed to delete twin file: ${response.status} ${response.statusText} - ${errorText}`);
1504
+ }
1505
+
1506
+ async restoreTwinFile(twinId: string, fileId: string, etag: string, signal?: AbortSignal): Promise<TwinFileGet> {
1507
+ const response = await this._httpClient.fetch(
1508
+ HttpMethod.Put,
1509
+ `${this._baseUrl}/${twinId}/files/${fileId}/restore`,
1510
+ {
1511
+ headers: { 'Content-Type': 'application/json' },
1512
+ body: JSON.stringify({ etag }),
1513
+ signal
1514
+ }
1515
+ );
1516
+
1517
+ if (response.ok) {
1518
+ return (await response.json()) as TwinFileGet;
1519
+ }
1520
+
1521
+ if (response.status === 404) {
1522
+ throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1523
+ }
1524
+
1525
+ if (response.status === 409) {
1526
+ const conflictedFile = (await response.json()) as TwinFileGet;
1527
+ throw new TwinFileConflictError('Twin file has been modified by another user', conflictedFile);
1528
+ }
1529
+
1530
+ if (response.status === 400) {
1531
+ const errorText = await response.text();
1532
+ throw new TwinFileValidationError(`Twin file validation failed: ${errorText}`);
1533
+ }
1534
+
1535
+ const errorText = await response.text();
1536
+ throw new Error(`Failed to restore twin file: ${response.status} ${response.statusText} - ${errorText}`);
1537
+ }
1538
+
1539
+ async getTwinFileContent(twinId: string, fileId: string, signal?: AbortSignal): Promise<Blob> {
1540
+ const response = await this._httpClient.fetch(
1541
+ HttpMethod.Get,
1542
+ `${this._baseUrl}/${twinId}/files/${fileId}/content`,
1543
+ { signal }
1544
+ );
1545
+
1546
+ if (response.ok) {
1547
+ return await response.blob();
1548
+ }
1549
+
1550
+ if (response.status === 404) {
1551
+ throw new TwinFileNotFoundError(`Twin file ${fileId} not found`);
1552
+ }
1553
+
1554
+ const errorText = await response.text();
1555
+ throw new Error(`Failed to get twin file content: ${response.status} ${response.statusText} - ${errorText}`);
1556
+ }
1557
+
1558
+ async getTwinFileVersion(
1559
+ twinId: string,
1560
+ fileId: string,
1561
+ version: number,
1562
+ signal?: AbortSignal
1563
+ ): Promise<TwinFileGet> {
1564
+ const response = await this._httpClient.fetch(
1565
+ HttpMethod.Get,
1566
+ `${this._baseUrl}/${twinId}/files/${fileId}/versions/${version}`,
1567
+ { signal }
1568
+ );
1569
+
1570
+ if (response.ok) {
1571
+ return (await response.json()) as TwinFileGet;
1572
+ }
1573
+
1574
+ if (response.status === 404) {
1575
+ throw new TwinFileNotFoundError(`Twin file ${fileId} version ${version} not found`);
1576
+ }
1577
+
1578
+ const errorText = await response.text();
1579
+ throw new Error(`Failed to get twin file version: ${response.status} ${response.statusText} - ${errorText}`);
1580
+ }
1581
+
1582
+ async listTwinFileVersions(
1583
+ twinId: string,
1584
+ fileId: string,
1585
+ options?: TwinFileVersionListOptions,
1586
+ signal?: AbortSignal
1587
+ ): Promise<PaginatedResponse<TwinFileGet>> {
1588
+ const params = new URLSearchParams();
1589
+ if (options?.includeDeleted !== undefined) params.append('includeDeleted', String(options.includeDeleted));
1590
+ if (options?.offset !== undefined) params.append('offset', String(options.offset));
1591
+ if (options?.limit !== undefined) params.append('limit', String(options.limit));
1592
+
1593
+ const response = await this._httpClient.fetch(
1594
+ HttpMethod.Get,
1595
+ `${this._baseUrl}/${twinId}/files/${fileId}/versions?${params.toString()}`,
1596
+ { signal }
1597
+ );
1598
+
1599
+ if (response.ok) {
1600
+ return (await response.json()) as PaginatedResponse<TwinFileGet>;
1601
+ }
1602
+
1603
+ if (response.status === 400) {
1604
+ const errorBody = await readErrorBody(response);
1605
+ throw new TwinFileValidationError(
1606
+ `Twin file version listing validation failed: ${errorBody.detail}`,
1607
+ errorBody
1608
+ );
1609
+ }
1610
+
1611
+ const errorText = await response.text();
1612
+ throw new Error(`Failed to list twin file versions: ${response.status} ${response.statusText} - ${errorText}`);
1613
+ }
1614
+
1615
+ async getTwinFileVersionContent(
1616
+ twinId: string,
1617
+ fileId: string,
1618
+ version: number,
1619
+ signal?: AbortSignal
1620
+ ): Promise<Blob> {
1621
+ const response = await this._httpClient.fetch(
1622
+ HttpMethod.Get,
1623
+ `${this._baseUrl}/${twinId}/files/${fileId}/versions/${version}/content`,
1624
+ { signal }
1625
+ );
1626
+
1627
+ if (response.ok) {
1628
+ return await response.blob();
1629
+ }
1630
+
1631
+ if (response.status === 404) {
1632
+ throw new TwinFileNotFoundError(`Twin file ${fileId} version ${version} content not found`);
1633
+ }
1634
+
1635
+ const errorText = await response.text();
1636
+ throw new Error(
1637
+ `Failed to get twin file version content: ${response.status} ${response.statusText} - ${errorText}`
1638
+ );
1639
+ }
1640
+
1641
+ async createOrUpdateTwinRaw(twinId: string, twin: unknown, signal?: AbortSignal): Promise<Response> {
1642
+ return await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}`, {
1643
+ headers: { 'Content-Type': 'application/json' },
1644
+ body: JSON.stringify(twin),
1645
+ signal
1646
+ });
1647
+ }
1648
+
1649
+ async createOrUpdateTwinFileRaw(
1650
+ twinId: string,
1651
+ fileId: string,
1652
+ twinFile: unknown,
1653
+ signal?: AbortSignal
1654
+ ): Promise<Response> {
1655
+ return await this._httpClient.fetch(HttpMethod.Put, `${this._baseUrl}/${twinId}/files/${fileId}`, {
1656
+ headers: { 'Content-Type': 'application/json' },
1657
+ body: JSON.stringify(twinFile),
1658
+ signal
1659
+ });
1660
+ }
1661
+
1662
+ // ---------- Asset categories ----------
1663
+
1664
+ async getMyPermissions(signal?: AbortSignal): Promise<MyPermissions> {
1665
+ const url = `${this._baseUrl}/permissions/me`;
1666
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1667
+ headers: { Accept: 'application/json' },
1668
+ signal
1669
+ });
1670
+ if (response.ok) {
1671
+ return (await response.json()) as MyPermissions;
1672
+ }
1673
+ // 401: no valid auth context. Throw so consumers can redirect to
1674
+ // login / refresh tokens rather than mistake an expired session for
1675
+ // "logged-in user with no grants."
1676
+ if (response.status === 401) {
1677
+ throw new TwinUnauthenticatedError('Not authenticated');
1678
+ }
1679
+ // 403: authenticated but no Twin-service capabilities. Surface as an
1680
+ // empty array so consumers can treat it like a logged-in user with
1681
+ // zero grants.
1682
+ if (response.status === 403) {
1683
+ return { permissions: [] };
1684
+ }
1685
+ throw new Error(`Failed to fetch permissions: ${response.status} ${response.statusText}`);
1686
+ }
1687
+
1688
+ async getAssetTypeMetaSchema(signal?: AbortSignal): Promise<Record<string, unknown>> {
1689
+ const url = `${this._assetTypeCatalogUrl}/meta-schema`;
1690
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1691
+ headers: { Accept: 'application/schema+json, application/json' },
1692
+ signal
1693
+ });
1694
+ if (!response.ok) {
1695
+ throw new Error(`Failed to fetch meta-schema: ${response.status} ${response.statusText}`);
1696
+ }
1697
+ return (await response.json()) as Record<string, unknown>;
1698
+ }
1699
+
1700
+ async listAssetCategories(
1701
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
1702
+ signal?: AbortSignal
1703
+ ): Promise<PaginatedResponse<AssetCategoryGet>> {
1704
+ const params = new URLSearchParams();
1705
+ if (options?.page !== undefined) params.set('page', options.page);
1706
+ if (options?.limit !== undefined) params.set('limit', options.limit.toString());
1707
+ if (options?.includeDeleted) params.set('includeDeleted', 'true');
1708
+
1709
+ const url = params.toString()
1710
+ ? `${this._assetTypeCatalogUrl}/categories?${params}`
1711
+ : `${this._assetTypeCatalogUrl}/categories`;
1712
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1713
+ headers: { Accept: 'application/json' },
1714
+ signal
1715
+ });
1716
+
1717
+ if (response.ok) return (await response.json()) as PaginatedResponse<AssetCategoryGet>;
1718
+ if (response.status === 403) throw new AssetCategoryForbiddenError('Asset category listing forbidden');
1719
+ if (response.status === 400) {
1720
+ const errorBody = await readErrorBody(response);
1721
+ throw new AssetCategoryValidationError(`Asset category listing failed: ${errorBody.detail}`, errorBody);
1722
+ }
1723
+ throw new Error(`Failed to list asset categories: ${response.status} ${response.statusText}`);
1724
+ }
1725
+
1726
+ async getAssetCategory(categoryId: string, signal?: AbortSignal): Promise<AssetCategoryGet> {
1727
+ const response = await this._httpClient.fetch(
1728
+ HttpMethod.Get,
1729
+ `${this._assetTypeCatalogUrl}/categories/${categoryId}`,
1730
+ {
1731
+ headers: { Accept: 'application/json' },
1732
+ signal
1733
+ }
1734
+ );
1735
+ if (response.ok) return (await response.json()) as AssetCategoryGet;
1736
+ if (response.status === 403)
1737
+ throw new AssetCategoryForbiddenError(`Asset category ${categoryId} read forbidden`);
1738
+ if (response.status === 404) throw new AssetCategoryNotFoundError(`Asset category ${categoryId} not found`);
1739
+ throw new Error(`Failed to get asset category: ${response.status} ${response.statusText}`);
1740
+ }
1741
+
1742
+ async putAssetCategory(
1743
+ categoryId: string,
1744
+ body: AssetCategoryPut,
1745
+ signal?: AbortSignal
1746
+ ): Promise<AssetCategoryGet> {
1747
+ const response = await this._httpClient.fetch(
1748
+ HttpMethod.Put,
1749
+ `${this._assetTypeCatalogUrl}/categories/${categoryId}`,
1750
+ {
1751
+ headers: { 'Content-Type': 'application/json' },
1752
+ body: JSON.stringify(body),
1753
+ signal
1754
+ }
1755
+ );
1756
+ if (response.ok) return (await response.json()) as AssetCategoryGet;
1757
+ if (response.status === 403) throw new AssetCategoryForbiddenError('Asset category upsert forbidden');
1758
+ if (response.status === 409) {
1759
+ const current = (await response.json()) as AssetCategoryGet;
1760
+ throw new AssetCategoryConflictError('Asset category was modified by another user', current);
1761
+ }
1762
+ if (response.status === 400) {
1763
+ const errorBody = await readErrorBody(response);
1764
+ throw new AssetCategoryValidationError(`Asset category validation failed: ${errorBody.detail}`, errorBody);
1765
+ }
1766
+ const errorText = await response.text();
1767
+ throw new Error(`Failed to upsert asset category: ${response.status} ${response.statusText} - ${errorText}`);
1768
+ }
1769
+
1770
+ async deleteAssetCategory(categoryId: string, etag: string, signal?: AbortSignal): Promise<AssetCategoryGet> {
1771
+ return this._categoryDeleteOrRestore(categoryId, etag, /*isRestore*/ false, signal);
1772
+ }
1773
+
1774
+ async restoreAssetCategory(categoryId: string, etag: string, signal?: AbortSignal): Promise<AssetCategoryGet> {
1775
+ return this._categoryDeleteOrRestore(categoryId, etag, /*isRestore*/ true, signal);
1776
+ }
1777
+
1778
+ private async _categoryDeleteOrRestore(
1779
+ categoryId: string,
1780
+ etag: string,
1781
+ isRestore: boolean,
1782
+ signal?: AbortSignal
1783
+ ): Promise<AssetCategoryGet> {
1784
+ const url = isRestore
1785
+ ? `${this._assetTypeCatalogUrl}/categories/${categoryId}/restore`
1786
+ : `${this._assetTypeCatalogUrl}/categories/${categoryId}`;
1787
+ const method = isRestore ? HttpMethod.Put : HttpMethod.Delete;
1788
+ const response = await this._httpClient.fetch(method, url, {
1789
+ headers: { 'Content-Type': 'application/json' },
1790
+ body: JSON.stringify({ etag }),
1791
+ signal
1792
+ });
1793
+ if (response.ok) return (await response.json()) as AssetCategoryGet;
1794
+ if (response.status === 403) {
1795
+ const op = isRestore ? 'restore' : 'delete';
1796
+ throw new AssetCategoryForbiddenError(`Asset category ${op} forbidden`);
1797
+ }
1798
+ if (response.status === 409) {
1799
+ const current = (await response.json()) as AssetCategoryGet;
1800
+ throw new AssetCategoryConflictError('Asset category was modified by another user', current);
1801
+ }
1802
+ if (response.status === 404) throw new AssetCategoryNotFoundError(`Asset category ${categoryId} not found`);
1803
+ const errorText = await response.text();
1804
+ const op = isRestore ? 'restore' : 'delete';
1805
+ throw new Error(`Failed to ${op} asset category: ${response.status} ${response.statusText} - ${errorText}`);
1806
+ }
1807
+
1808
+ async listAssetCategoryVersions(
1809
+ categoryId: string,
1810
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
1811
+ signal?: AbortSignal
1812
+ ): Promise<PaginatedResponse<AssetCategoryGet>> {
1813
+ const params = new URLSearchParams();
1814
+ if (options?.page !== undefined) params.set('page', options.page);
1815
+ if (options?.limit !== undefined) params.set('limit', options.limit.toString());
1816
+ if (options?.includeDeleted) params.set('includeDeleted', 'true');
1817
+
1818
+ const baseUrl = `${this._assetTypeCatalogUrl}/categories/${categoryId}/versions`;
1819
+ const url = params.toString() ? `${baseUrl}?${params}` : baseUrl;
1820
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1821
+ headers: { Accept: 'application/json' },
1822
+ signal
1823
+ });
1824
+
1825
+ if (response.ok) return (await response.json()) as PaginatedResponse<AssetCategoryGet>;
1826
+ if (response.status === 403) throw new AssetCategoryForbiddenError('Asset category version listing forbidden');
1827
+ if (response.status === 400) {
1828
+ const errorBody = await readErrorBody(response);
1829
+ throw new AssetCategoryValidationError(
1830
+ `Asset category version listing failed: ${errorBody.detail}`,
1831
+ errorBody
1832
+ );
1833
+ }
1834
+ if (response.status === 404) throw new AssetCategoryNotFoundError(`Asset category ${categoryId} not found`);
1835
+ throw new Error(`Failed to list asset category versions: ${response.status} ${response.statusText}`);
1836
+ }
1837
+
1838
+ // ---------- Asset types ----------
1839
+
1840
+ async listAssetTypes(
1841
+ categoryId: string,
1842
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
1843
+ signal?: AbortSignal
1844
+ ): Promise<PaginatedResponse<AssetTypeGet>> {
1845
+ const params = new URLSearchParams();
1846
+ if (options?.page !== undefined) params.set('page', options.page);
1847
+ if (options?.limit !== undefined) params.set('limit', options.limit.toString());
1848
+ if (options?.includeDeleted) params.set('includeDeleted', 'true');
1849
+
1850
+ const baseUrl = `${this._assetTypeCatalogUrl}/categories/${categoryId}/types`;
1851
+ const url = params.toString() ? `${baseUrl}?${params}` : baseUrl;
1852
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1853
+ headers: { Accept: 'application/json' },
1854
+ signal
1855
+ });
1856
+
1857
+ if (response.ok) return (await response.json()) as PaginatedResponse<AssetTypeGet>;
1858
+ if (response.status === 403) throw new AssetTypeForbiddenError('Asset type listing forbidden');
1859
+ if (response.status === 400) {
1860
+ const errorBody = await readErrorBody(response);
1861
+ throw new AssetTypeValidationError(`Asset type listing failed: ${errorBody.detail}`, errorBody);
1862
+ }
1863
+ throw new Error(`Failed to list asset types: ${response.status} ${response.statusText}`);
1864
+ }
1865
+
1866
+ async getAssetType(categoryId: string, typeId: string, signal?: AbortSignal): Promise<AssetTypeGet> {
1867
+ const response = await this._httpClient.fetch(
1868
+ HttpMethod.Get,
1869
+ `${this._assetTypeCatalogUrl}/categories/${categoryId}/types/${typeId}`,
1870
+ { headers: { Accept: 'application/json' }, signal }
1871
+ );
1872
+ if (response.ok) return (await response.json()) as AssetTypeGet;
1873
+ if (response.status === 403) throw new AssetTypeForbiddenError(`Asset type ${typeId} read forbidden`);
1874
+ if (response.status === 404) throw new AssetTypeNotFoundError(`Asset type ${typeId} not found`);
1875
+ throw new Error(`Failed to get asset type: ${response.status} ${response.statusText}`);
1876
+ }
1877
+
1878
+ async listAssetTypeVersions(
1879
+ categoryId: string,
1880
+ typeId: string,
1881
+ options?: { page?: string; limit?: number; includeDeleted?: boolean },
1882
+ signal?: AbortSignal
1883
+ ): Promise<PaginatedResponse<AssetTypeGet>> {
1884
+ const params = new URLSearchParams();
1885
+ if (options?.page !== undefined) params.set('page', options.page);
1886
+ if (options?.limit !== undefined) params.set('limit', options.limit.toString());
1887
+ if (options?.includeDeleted) params.set('includeDeleted', 'true');
1888
+
1889
+ const baseUrl = `${this._assetTypeCatalogUrl}/categories/${categoryId}/types/${typeId}/versions`;
1890
+ const url = params.toString() ? `${baseUrl}?${params}` : baseUrl;
1891
+ const response = await this._httpClient.fetch(HttpMethod.Get, url, {
1892
+ headers: { Accept: 'application/json' },
1893
+ signal
1894
+ });
1895
+
1896
+ if (response.ok) return (await response.json()) as PaginatedResponse<AssetTypeGet>;
1897
+ if (response.status === 403) throw new AssetTypeForbiddenError('Asset type version listing forbidden');
1898
+ if (response.status === 400) {
1899
+ const errorBody = await readErrorBody(response);
1900
+ throw new AssetTypeValidationError(`Asset type version listing failed: ${errorBody.detail}`, errorBody);
1901
+ }
1902
+ if (response.status === 404) throw new AssetTypeNotFoundError(`Asset type ${typeId} not found`);
1903
+ throw new Error(`Failed to list asset type versions: ${response.status} ${response.statusText}`);
1904
+ }
1905
+
1906
+ async putAssetType(
1907
+ categoryId: string,
1908
+ typeId: string,
1909
+ body: AssetTypePut,
1910
+ signal?: AbortSignal
1911
+ ): Promise<AssetTypeGet> {
1912
+ const response = await this._httpClient.fetch(
1913
+ HttpMethod.Put,
1914
+ `${this._assetTypeCatalogUrl}/categories/${categoryId}/types/${typeId}`,
1915
+ {
1916
+ headers: { 'Content-Type': 'application/json' },
1917
+ body: JSON.stringify(body),
1918
+ signal
1919
+ }
1920
+ );
1921
+ if (response.ok) return (await response.json()) as AssetTypeGet;
1922
+ if (response.status === 403) throw new AssetTypeForbiddenError('Asset type upsert forbidden');
1923
+ if (response.status === 409) {
1924
+ const current = (await response.json()) as AssetTypeGet;
1925
+ throw new AssetTypeConflictError('Asset type was modified by another user', current);
1926
+ }
1927
+ if (response.status === 400) {
1928
+ const errorBody = await readErrorBody(response);
1929
+ throw new AssetTypeValidationError(`Asset type validation failed: ${errorBody.detail}`, errorBody);
1930
+ }
1931
+ const errorText = await response.text();
1932
+ throw new Error(`Failed to upsert asset type: ${response.status} ${response.statusText} - ${errorText}`);
1933
+ }
1934
+
1935
+ async deleteAssetType(
1936
+ categoryId: string,
1937
+ typeId: string,
1938
+ etag: string,
1939
+ signal?: AbortSignal
1940
+ ): Promise<AssetTypeGet> {
1941
+ return this._typeDeleteOrRestore(categoryId, typeId, etag, /*isRestore*/ false, signal);
1942
+ }
1943
+
1944
+ async restoreAssetType(
1945
+ categoryId: string,
1946
+ typeId: string,
1947
+ etag: string,
1948
+ signal?: AbortSignal
1949
+ ): Promise<AssetTypeGet> {
1950
+ return this._typeDeleteOrRestore(categoryId, typeId, etag, /*isRestore*/ true, signal);
1951
+ }
1952
+
1953
+ private async _typeDeleteOrRestore(
1954
+ categoryId: string,
1955
+ typeId: string,
1956
+ etag: string,
1957
+ isRestore: boolean,
1958
+ signal?: AbortSignal
1959
+ ): Promise<AssetTypeGet> {
1960
+ const url = isRestore
1961
+ ? `${this._assetTypeCatalogUrl}/categories/${categoryId}/types/${typeId}/restore`
1962
+ : `${this._assetTypeCatalogUrl}/categories/${categoryId}/types/${typeId}`;
1963
+ const method = isRestore ? HttpMethod.Put : HttpMethod.Delete;
1964
+ const response = await this._httpClient.fetch(method, url, {
1965
+ headers: { 'Content-Type': 'application/json' },
1966
+ body: JSON.stringify({ etag }),
1967
+ signal
1968
+ });
1969
+ if (response.ok) return (await response.json()) as AssetTypeGet;
1970
+ if (response.status === 403) {
1971
+ const op = isRestore ? 'restore' : 'delete';
1972
+ throw new AssetTypeForbiddenError(`Asset type ${op} forbidden`);
1973
+ }
1974
+ if (response.status === 409) {
1975
+ const current = (await response.json()) as AssetTypeGet;
1976
+ throw new AssetTypeConflictError('Asset type was modified by another user', current);
1977
+ }
1978
+ if (response.status === 404) throw new AssetTypeNotFoundError(`Asset type ${typeId} not found`);
1979
+ const errorText = await response.text();
1980
+ const op = isRestore ? 'restore' : 'delete';
1981
+ throw new Error(`Failed to ${op} asset type: ${response.status} ${response.statusText} - ${errorText}`);
1982
+ }
1983
+
1984
+ async getAssetTypeCatalog(signal?: AbortSignal): Promise<AssetCatalogResponse> {
1985
+ const response = await this._httpClient.fetch(HttpMethod.Get, this._assetTypeCatalogUrl, {
1986
+ headers: { Accept: 'application/json' },
1987
+ signal
1988
+ });
1989
+ if (response.ok) return (await response.json()) as AssetCatalogResponse;
1990
+ if (response.status === 403) throw new AssetCategoryForbiddenError('Asset type catalog read forbidden');
1991
+ if (response.status === 400) {
1992
+ // The server emits a single structured 400 here today —
1993
+ // `cause: 'CatalogTooLarge'` — to flag a tenant whose catalog
1994
+ // overflows the per-customer cap. Surface as a typed error so
1995
+ // picker UIs can render "use search" instead of crashing on
1996
+ // missing rows. Any other 400 (malformed CatalogTooLarge body,
1997
+ // future cause) falls through to the generic error below so the
1998
+ // caller still sees the raw response.
1999
+ const errorBody = await readErrorBody(response);
2000
+ if (isAssetCatalogTooLargeErrorBody(errorBody)) {
2001
+ throw new AssetCatalogTooLargeError(`Asset type catalog too large: ${errorBody.detail}`, errorBody);
2002
+ }
2003
+ throw new Error(
2004
+ `Failed to get asset-type catalog: ${response.status} ${response.statusText} - ${errorBody.detail}`
2005
+ );
2006
+ }
2007
+ const errorText = await response.text();
2008
+ throw new Error(`Failed to get asset-type catalog: ${response.status} ${response.statusText} - ${errorText}`);
2009
+ }
2010
+ }