@osdk/client 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/js/index.cjs +1381 -34
  2. package/build/js/index.cjs.map +1 -1
  3. package/build/js/index.mjs +1370 -18
  4. package/build/js/index.mjs.map +1 -1
  5. package/build/types/MinimalClientContext.d.ts +10 -6
  6. package/build/types/MinimalClientContext.d.ts.map +1 -1
  7. package/build/types/SatisfiesSemver.d.ts +4 -0
  8. package/build/types/SatisfiesSemver.d.ts.map +1 -0
  9. package/build/types/SatisfiesSemver.test.d.ts +2 -0
  10. package/build/types/SatisfiesSemver.test.d.ts.map +1 -0
  11. package/build/types/createClient.d.ts +12 -3
  12. package/build/types/createClient.d.ts.map +1 -1
  13. package/build/types/generatedNoCheck/Ontology.d.ts +2 -5
  14. package/build/types/generatedNoCheck/Ontology.d.ts.map +1 -1
  15. package/build/types/generatedNoCheck/OntologyMetadata.d.ts +5 -5
  16. package/build/types/generatedNoCheck/OntologyMetadata.d.ts.map +1 -1
  17. package/build/types/index.d.ts +9 -9
  18. package/build/types/index.d.ts.map +1 -1
  19. package/build/types/object/Result.d.ts +12 -0
  20. package/build/types/object/Result.d.ts.map +1 -0
  21. package/build/types/object/fetchPage.d.ts +8 -4
  22. package/build/types/object/fetchPage.d.ts.map +1 -1
  23. package/build/types/objectSet/ObjectSet.d.ts +4 -2
  24. package/build/types/objectSet/ObjectSet.d.ts.map +1 -1
  25. package/build/types/objectSet/createObjectSet.d.ts.map +1 -1
  26. package/build/types/ontology/loadFullObjectMetadata.d.ts.map +1 -1
  27. package/build/types/util/test/mockOntology.d.ts +1 -0
  28. package/build/types/util/test/mockOntology.d.ts.map +1 -1
  29. package/changelog/0.15.0/pr-145.v2.yml +5 -0
  30. package/changelog/0.15.0/pr-151.v2.yml +5 -0
  31. package/changelog/0.15.0/pr-155.v2.yml +5 -0
  32. package/changelog/0.15.0/pr-156.v2.yml +5 -0
  33. package/changelog/0.15.0/pr-157.v2.yml +5 -0
  34. package/package.json +8 -8
  35. package/build/js/chunk-AW6UQOAF.cjs +0 -1364
  36. package/build/js/chunk-AW6UQOAF.cjs.map +0 -1
  37. package/build/js/chunk-Y7UBQD5N.mjs +0 -1346
  38. package/build/js/chunk-Y7UBQD5N.mjs.map +0 -1
  39. package/build/js/public/objects.cjs +0 -16
  40. package/build/js/public/objects.cjs.map +0 -1
  41. package/build/js/public/objects.mjs +0 -3
  42. package/build/js/public/objects.mjs.map +0 -1
  43. package/build/types/public/objects.d.ts +0 -2
  44. package/build/types/public/objects.d.ts.map +0 -1
@@ -1,11 +1,1363 @@
1
- import { createObjectSet, createAsyncCache, isAttachment, isWireObjectSet, isObjectSet, getWireObjectSet, loadAllOntologies, loadOntologyEntities } from './chunk-Y7UBQD5N.mjs';
2
- export { object_exports as Objects, augment } from './chunk-Y7UBQD5N.mjs';
3
- import { applyActionV2, getObjectTypeV2, listInterfaceTypes, getInterfaceType, listOutgoingLinkTypesV2 } from '@osdk/gateway/requests';
4
- import { createClientContext, createOpenApiRequest } from '@osdk/shared.net';
1
+ import { createClientContext, createOpenApiRequest, PalantirApiError } from '@osdk/shared.net';
5
2
  export { createClientContext, isOk } from '@osdk/shared.net';
3
+ import { loadObjectSetV2, aggregateObjectSetV2, getObjectTypeV2, searchObjectsForInterface, applyActionV2, listInterfaceTypes, getInterfaceType, listOutgoingLinkTypesV2 } from '@osdk/gateway/requests';
4
+ import invariant2 from 'tiny-invariant';
5
+ import WebSocket from 'isomorphic-ws';
6
+ import { conjureFetch } from 'conjure-lite';
6
7
  import { wireObjectTypeFullMetadataToSdkObjectTypeDefinition, __UNSTABLE_wireInterfaceTypeV2ToSdkObjectDefinition } from '@osdk/generator-converters';
7
8
  import deepEqual from 'fast-deep-equal';
8
- import invariant from 'tiny-invariant';
9
+
10
+ // src/index.ts
11
+
12
+ // src/actions/ActionValidationError.ts
13
+ var ActionValidationError = class extends Error {
14
+ constructor(validation) {
15
+ super("Validation Error");
16
+ this.validation = validation;
17
+ }
18
+ };
19
+
20
+ // src/object/Attachment.ts
21
+ var Attachment = class {
22
+ constructor(rid) {
23
+ this.rid = rid;
24
+ }
25
+ };
26
+ function isAttachment(o) {
27
+ return o instanceof Attachment;
28
+ }
29
+ function legacyToModernSingleAggregationResult(entry) {
30
+ return entry.metrics.reduce((accumulator, curValue) => {
31
+ const parts = curValue.name.split(".");
32
+ if (parts[0] === "count") {
33
+ return accumulator;
34
+ }
35
+ !(parts.length === 2) ? process.env.NODE_ENV !== "production" ? invariant2(false, "assumed we were getting a `${key}.${type}`") : invariant2(false) : void 0;
36
+ if (!(parts[0] in accumulator)) {
37
+ accumulator[parts[0]] = {};
38
+ }
39
+ accumulator[parts[0]][parts[1]] = curValue.value;
40
+ return accumulator;
41
+ }, {});
42
+ }
43
+
44
+ // src/internal/conversions/modernToLegacyAggregationClause.ts
45
+ function modernToLegacyAggregationClause(select) {
46
+ return Object.entries(select).flatMap(([k, v]) => {
47
+ if (k === "$count") {
48
+ if (v)
49
+ return {
50
+ type: "count",
51
+ name: "count"
52
+ };
53
+ return [];
54
+ } else if (Array.isArray(v)) {
55
+ return v.map((v2) => {
56
+ return {
57
+ type: v2,
58
+ name: `${k}.${v2}`,
59
+ field: k
60
+ };
61
+ });
62
+ } else {
63
+ return [{
64
+ type: v,
65
+ // FIXME v has additional possible values
66
+ name: `${k}.${v}`,
67
+ field: k
68
+ }];
69
+ }
70
+ });
71
+ }
72
+
73
+ // src/query/aggregations/GroupByClause.ts
74
+ var DurationMapping = {
75
+ "sec": "SECONDS",
76
+ "seconds": "SECONDS",
77
+ "min": "MINUTES",
78
+ "minute": "MINUTES",
79
+ "minutes": "MINUTES",
80
+ "hr": "HOURS",
81
+ "hrs": "HOURS",
82
+ "hour": "HOURS",
83
+ "hours": "HOURS",
84
+ "day": "DAYS",
85
+ "days": "DAYS",
86
+ "wk": "WEEKS",
87
+ "week": "WEEKS",
88
+ "weeks": "WEEKS",
89
+ "mos": "MONTHS",
90
+ "month": "MONTHS",
91
+ "months": "MONTHS",
92
+ "yr": "YEARS",
93
+ "year": "YEARS",
94
+ "years": "YEARS",
95
+ "quarter": "QUARTERS",
96
+ "quarters": "QUARTERS"
97
+ };
98
+
99
+ // src/internal/conversions/modernToLegacyGroupByClause.ts
100
+ function modernToLegacyGroupByClause(groupByClause) {
101
+ if (!groupByClause)
102
+ return [];
103
+ return Object.entries(groupByClause).flatMap(([field, type]) => {
104
+ if (type === "exact") {
105
+ return [{
106
+ type,
107
+ field
108
+ }];
109
+ } else if ("exactWithLimit" in type) {
110
+ {
111
+ return [{
112
+ type: "exact",
113
+ field,
114
+ maxGroupCount: type.exactWithLimit
115
+ }];
116
+ }
117
+ } else if ("fixedWidth" in type) {
118
+ return [{
119
+ type: "fixedWidth",
120
+ field,
121
+ fixedWidth: type.fixedWidth
122
+ }];
123
+ } else if ("ranges" in type) {
124
+ return [{
125
+ type: "ranges",
126
+ field,
127
+ ranges: type.ranges.map((range) => convertRange(range))
128
+ }];
129
+ } else if ("duration" in type) {
130
+ return [{
131
+ type: "duration",
132
+ field,
133
+ value: type.duration[0],
134
+ unit: DurationMapping[type.duration[1]]
135
+ }];
136
+ } else
137
+ return [];
138
+ });
139
+ }
140
+ function convertRange(range) {
141
+ return {
142
+ startValue: range[0],
143
+ endValue: range[1]
144
+ };
145
+ }
146
+
147
+ // src/query/WhereClause.ts
148
+ var DistanceUnitMapping = {
149
+ "centimeter": "CENTIMETERS",
150
+ "centimeters": "CENTIMETERS",
151
+ "cm": "CENTIMETERS",
152
+ "meter": "METERS",
153
+ "meters": "METERS",
154
+ "m": "METERS",
155
+ "kilometer": "KILOMETERS",
156
+ "kilometers": "KILOMETERS",
157
+ "km": "KILOMETERS",
158
+ "inch": "INCHES",
159
+ "inches": "INCHES",
160
+ "foot": "FEET",
161
+ "feet": "FEET",
162
+ "yard": "YARDS",
163
+ "yards": "YARDS",
164
+ "mile": "MILES",
165
+ "miles": "MILES",
166
+ "nautical_mile": "NAUTICAL_MILES",
167
+ "nauticalMile": "NAUTICAL_MILES",
168
+ "nautical miles": "NAUTICAL_MILES"
169
+ };
170
+
171
+ // src/internal/conversions/modernToLegacyWhereClause.ts
172
+ function modernToLegacyWhereClause(whereClause) {
173
+ if ("$and" in whereClause) {
174
+ return {
175
+ type: "and",
176
+ value: whereClause.$and.map(modernToLegacyWhereClause)
177
+ };
178
+ } else if ("$or" in whereClause) {
179
+ return {
180
+ type: "or",
181
+ value: whereClause.$or.map(modernToLegacyWhereClause)
182
+ };
183
+ } else if ("$not" in whereClause) {
184
+ return {
185
+ type: "not",
186
+ value: modernToLegacyWhereClause(whereClause.$not)
187
+ };
188
+ }
189
+ const parts = Object.entries(whereClause);
190
+ if (parts.length === 1) {
191
+ return handleWherePair(parts[0]);
192
+ }
193
+ return {
194
+ type: "and",
195
+ value: parts.map(handleWherePair)
196
+ };
197
+ }
198
+ function makeGeoFilterBbox(field, bbox, filterType) {
199
+ return {
200
+ type: filterType === "$within" ? "withinBoundingBox" : "intersectsBoundingBox",
201
+ field,
202
+ value: {
203
+ topLeft: {
204
+ type: "Point",
205
+ coordinates: [bbox[0], bbox[3]]
206
+ },
207
+ bottomRight: {
208
+ type: "Point",
209
+ coordinates: [bbox[2], bbox[1]]
210
+ }
211
+ }
212
+ };
213
+ }
214
+ function makeGeoFilterPolygon(field, coordinates, filterType) {
215
+ return {
216
+ type: filterType,
217
+ field,
218
+ value: {
219
+ type: "Polygon",
220
+ coordinates
221
+ }
222
+ };
223
+ }
224
+ function handleWherePair([field, filter]) {
225
+ !(filter != null) ? process.env.NODE_ENV !== "production" ? invariant2(false, "Defined key values are only allowed when they are not undefined.") : invariant2(false) : void 0;
226
+ if (typeof filter === "string" || typeof filter === "number" || typeof filter === "boolean") {
227
+ return {
228
+ type: "eq",
229
+ field,
230
+ value: filter
231
+ };
232
+ }
233
+ const keysOfFilter = Object.keys(filter);
234
+ const hasDollarSign = keysOfFilter.some((key) => key.startsWith("$"));
235
+ !(!hasDollarSign || keysOfFilter.length === 1) ? process.env.NODE_ENV !== "production" ? invariant2(false, "WhereClause Filter with multiple clauses isn't allowed") : invariant2(false) : void 0;
236
+ if (!hasDollarSign) {
237
+ throw new Error(`Unsupported filter. Did you forget to use a $-prefixed filter? (${JSON.stringify(filter)})`);
238
+ }
239
+ const firstKey = keysOfFilter[0];
240
+ !(filter[firstKey] != null) ? process.env.NODE_ENV !== "production" ? invariant2(false) : invariant2(false) : void 0;
241
+ if (firstKey === "$ne") {
242
+ return {
243
+ type: "not",
244
+ value: {
245
+ type: "eq",
246
+ field,
247
+ value: filter[firstKey]
248
+ }
249
+ };
250
+ }
251
+ if (firstKey === "$within") {
252
+ const withinBody = filter[firstKey];
253
+ if (Array.isArray(withinBody)) {
254
+ return makeGeoFilterBbox(field, withinBody, firstKey);
255
+ } else if ("bbox" in withinBody && !("type" in withinBody)) {
256
+ return makeGeoFilterBbox(field, withinBody.bbox, firstKey);
257
+ } else if ("distance" in withinBody && "of" in withinBody) {
258
+ return {
259
+ type: "withinDistanceOf",
260
+ field,
261
+ value: {
262
+ center: Array.isArray(withinBody.of) ? {
263
+ type: "Point",
264
+ coordinates: withinBody.of
265
+ } : withinBody.of,
266
+ distance: {
267
+ value: withinBody.distance[0],
268
+ unit: DistanceUnitMapping[withinBody.distance[1]]
269
+ }
270
+ }
271
+ };
272
+ } else {
273
+ const coordinates = "polygon" in withinBody ? withinBody.polygon : withinBody.coordinates;
274
+ return makeGeoFilterPolygon(field, coordinates, "withinPolygon");
275
+ }
276
+ }
277
+ if (firstKey === "$intersects") {
278
+ const intersectsBody = filter[firstKey];
279
+ if (Array.isArray(intersectsBody)) {
280
+ return makeGeoFilterBbox(field, intersectsBody, firstKey);
281
+ } else if ("bbox" in intersectsBody && !("type" in intersectsBody)) {
282
+ return makeGeoFilterBbox(field, intersectsBody.bbox, firstKey);
283
+ } else {
284
+ const coordinates = "polygon" in intersectsBody ? intersectsBody.polygon : intersectsBody.coordinates;
285
+ return makeGeoFilterPolygon(field, coordinates, "intersectsPolygon");
286
+ }
287
+ }
288
+ return {
289
+ type: firstKey.substring(1),
290
+ field,
291
+ value: filter[firstKey]
292
+ };
293
+ }
294
+
295
+ // src/object/Cache.ts
296
+ function createCache(fn) {
297
+ const cache = /* @__PURE__ */ new WeakMap();
298
+ function get(client, key) {
299
+ if (cache.get(client) == null) {
300
+ cache.set(client, /* @__PURE__ */ new Map());
301
+ }
302
+ let r = cache.get(client).get(key);
303
+ if (r === void 0 && fn !== void 0) {
304
+ return set(client, key, fn(client, key));
305
+ } else {
306
+ return r;
307
+ }
308
+ }
309
+ function set(client, key, value) {
310
+ if (cache.get(client) == null) {
311
+ cache.set(client, /* @__PURE__ */ new Map());
312
+ }
313
+ cache.get(client).set(key, value);
314
+ return value;
315
+ }
316
+ function remove(client, key) {
317
+ if (cache.get(client) == null)
318
+ return false;
319
+ return cache.get(client).delete(key);
320
+ }
321
+ return {
322
+ get,
323
+ set,
324
+ remove
325
+ };
326
+ }
327
+ function createAsyncCache(fn, createCacheLocal = createCache) {
328
+ const cache = createCacheLocal();
329
+ const inProgress = createCacheLocal();
330
+ const ret = {
331
+ getOrUndefined: function getOrUndefined(client, key) {
332
+ return cache.get(client, key);
333
+ },
334
+ get: async function get(client, key) {
335
+ return cache.get(client, key) ?? inProgress.get(client, key) ?? ret.set(client, key, fn(client, key));
336
+ },
337
+ set: async function set(client, k, v) {
338
+ try {
339
+ const r = await inProgress.set(client, k, v);
340
+ cache.set(client, k, r);
341
+ inProgress.remove(client, k);
342
+ return r;
343
+ } catch (e) {
344
+ inProgress.remove(client, k);
345
+ throw e;
346
+ }
347
+ }
348
+ };
349
+ return ret;
350
+ }
351
+ function augment(type, ...properties) {
352
+ return {
353
+ [type.apiName]: properties
354
+ };
355
+ }
356
+ function objectSetToSearchJsonV2(objectSet, expectedApiName, existingWhere = void 0) {
357
+ if (objectSet.type === "base") {
358
+ if (objectSet.objectType !== expectedApiName) {
359
+ throw new Error(`Expected objectSet.objectType to be ${expectedApiName}, but got ${objectSet.objectType}`);
360
+ }
361
+ return existingWhere;
362
+ }
363
+ if (objectSet.type === "filter") {
364
+ return objectSetToSearchJsonV2(objectSet.objectSet, expectedApiName, existingWhere == null ? objectSet.where : {
365
+ type: "and",
366
+ value: [existingWhere, objectSet.where]
367
+ });
368
+ }
369
+ throw new Error(`Unsupported objectSet type: ${objectSet.type}`);
370
+ }
371
+ async function fetchInterfacePage(client, interfaceType, args, objectSet) {
372
+ const result = await searchObjectsForInterface(createOpenApiRequest(client.stack, client.fetch), client.ontology.metadata.ontologyApiName, interfaceType.apiName, applyFetchArgs(args, {
373
+ augmentedProperties: args.augment ?? {},
374
+ augmentedSharedPropertyTypes: {},
375
+ otherInterfaceTypes: [],
376
+ selectedObjectTypes: [],
377
+ selectedSharedPropertyTypes: args.select ?? [],
378
+ where: objectSetToSearchJsonV2(objectSet, interfaceType.apiName)
379
+ }), {
380
+ preview: true
381
+ });
382
+ result.data = await convertWireToOsdkObjects(
383
+ client,
384
+ result.data,
385
+ // drop readonly
386
+ interfaceType.apiName,
387
+ !args.includeRid
388
+ );
389
+ return result;
390
+ }
391
+ async function fetchPageInternal(client, objectType, objectSet, args = {}) {
392
+ if (objectType.type === "interface") {
393
+ return await fetchInterfacePage(client, objectType, args, objectSet);
394
+ } else {
395
+ return await fetchObjectPage(client, objectType, args, objectSet);
396
+ }
397
+ }
398
+ async function fetchPageWithErrorsInternal(client, objectType, objectSet, args = {}) {
399
+ try {
400
+ const result = await fetchPageInternal(client, objectType, objectSet, args);
401
+ return {
402
+ value: result
403
+ };
404
+ } catch (e) {
405
+ if (e instanceof Error) {
406
+ return {
407
+ error: e
408
+ };
409
+ }
410
+ return {
411
+ error: e
412
+ };
413
+ }
414
+ }
415
+ async function fetchPage(client, objectType, args, objectSet = {
416
+ type: "base",
417
+ objectType: objectType["apiName"]
418
+ }) {
419
+ return fetchPageInternal(client, objectType, objectSet, args);
420
+ }
421
+ function applyFetchArgs(args, body) {
422
+ if (args?.nextPageToken) {
423
+ body.pageToken = args.nextPageToken;
424
+ }
425
+ if (args?.pageSize != null) {
426
+ body.pageSize = args.pageSize;
427
+ }
428
+ if (args?.orderBy != null) {
429
+ body.orderBy = {
430
+ fields: Object.entries(args.orderBy).map(([field, direction]) => ({
431
+ field,
432
+ direction
433
+ }))
434
+ };
435
+ }
436
+ return body;
437
+ }
438
+ async function fetchObjectPage(client, objectType, args, objectSet) {
439
+ const r = await loadObjectSetV2(createOpenApiRequest(client.stack, client.fetch), client.ontology.metadata.ontologyApiName, applyFetchArgs(args, {
440
+ objectSet,
441
+ // We have to do the following case because LoadObjectSetRequestV2 isnt readonly
442
+ select: args?.select ?? [],
443
+ // FIXME?
444
+ excludeRid: !args?.includeRid
445
+ }));
446
+ return Promise.resolve({
447
+ data: await convertWireToOsdkObjects(client, r.data, void 0),
448
+ nextPageToken: r.nextPageToken
449
+ });
450
+ }
451
+
452
+ // src/object/fetchSingle.ts
453
+ async function fetchSingle(client, objectType, args, objectSet) {
454
+ const result = await fetchPage(client, objectType, {
455
+ ...args,
456
+ pageSize: 1
457
+ }, objectSet);
458
+ if (result.data.length !== 1 || result.nextPageToken != null) {
459
+ throw new PalantirApiError(`Expected a single result but got ${result.data.length} instead${result.nextPageToken != null ? " with nextPageToken set" : ""}`);
460
+ }
461
+ return result.data[0];
462
+ }
463
+
464
+ // src/object/convertWireToOsdkObjects.ts
465
+ var OriginClient = Symbol();
466
+ var UnderlyingObject = Symbol();
467
+ var InterfaceDefinitions = Symbol();
468
+ var LinkFetcherProxyHandler = class {
469
+ constructor(objDef, primaryKey, client) {
470
+ this.objDef = objDef;
471
+ this.primaryKey = primaryKey;
472
+ this.client = client;
473
+ }
474
+ get(_target, p) {
475
+ const linkDef = this.objDef.links[p];
476
+ if (linkDef == null) {
477
+ return;
478
+ }
479
+ const objectSet = createObjectSet(this.objDef, this.client).where({
480
+ [this.objDef.primaryKeyApiName]: this.primaryKey
481
+ }).pivotTo(p);
482
+ if (!linkDef.multiplicity) {
483
+ return {
484
+ get: (options) => fetchSingle(this.client, this.objDef, options ?? {}, getWireObjectSet(objectSet))
485
+ };
486
+ } else {
487
+ return objectSet;
488
+ }
489
+ }
490
+ ownKeys() {
491
+ return Object.keys(this.objDef.links);
492
+ }
493
+ getOwnPropertyDescriptor(target, p) {
494
+ return {
495
+ enumerable: true,
496
+ configurable: true,
497
+ get: () => {
498
+ return this.get(target, p);
499
+ }
500
+ };
501
+ }
502
+ };
503
+ function createPrototype(objDef, client) {
504
+ if (process.env.NODE_ENV !== "production") {
505
+ !(objDef.type === "object") ? process.env.NODE_ENV !== "production" ? invariant2(false, "Expected object definition") : invariant2(false) : void 0;
506
+ }
507
+ const sharedPropertyDefs = {
508
+ $as: {
509
+ value: $as
510
+ }
511
+ };
512
+ const interfaceProto = Object.defineProperties({}, sharedPropertyDefs);
513
+ const objectProto = Object.defineProperties({}, {
514
+ $link: {
515
+ get: function() {
516
+ return new Proxy({}, new LinkFetcherProxyHandler(objDef, this["$primaryKey"], client));
517
+ }
518
+ },
519
+ ...sharedPropertyDefs
520
+ });
521
+ function $as(newDef) {
522
+ if (typeof newDef === "string") {
523
+ if (newDef === objDef.apiName) {
524
+ return this[UnderlyingObject];
525
+ }
526
+ const def = objDef[InterfaceDefinitions][newDef];
527
+ if (!def) {
528
+ throw new Error(`Object does not implement interface '${newDef}'.`);
529
+ }
530
+ newDef = def;
531
+ } else if (newDef.apiName === objDef.apiName) {
532
+ return this[UnderlyingObject];
533
+ }
534
+ if (newDef.type !== "interface" && newDef.apiName !== this.$apiName) {
535
+ throw new Error(`'${newDef.apiName}' is not an interface of '${this.$objectType}'.`);
536
+ }
537
+ const underlying = this[UnderlyingObject];
538
+ const common = {
539
+ enumerable: true,
540
+ configurable: true
541
+ };
542
+ return Object.create(interfaceProto, {
543
+ $apiName: {
544
+ value: newDef.apiName,
545
+ ...common
546
+ },
547
+ $objectType: {
548
+ value: objDef.apiName,
549
+ ...common
550
+ },
551
+ $primaryKey: {
552
+ value: this["$primaryKey"],
553
+ ...common
554
+ },
555
+ ...Object.fromEntries(Object.keys(newDef.properties).map((p) => {
556
+ const value = underlying[objDef.spts[p]];
557
+ return [p, {
558
+ value,
559
+ enumerable: value !== void 0
560
+ }];
561
+ })),
562
+ [UnderlyingObject]: {
563
+ value: underlying
564
+ }
565
+ });
566
+ }
567
+ return objectProto;
568
+ }
569
+ function createConverter(objDef) {
570
+ const steps = [];
571
+ for (const [key, value] of Object.entries(objDef.properties)) {
572
+ if (value.type === "attachment") {
573
+ steps.push((o) => {
574
+ if (o[key] != null) {
575
+ if (Array.isArray(o[key])) {
576
+ o[key] = o[key].map((a) => new Attachment(a.rid));
577
+ } else {
578
+ o[key] = new Attachment(o[key].rid);
579
+ }
580
+ }
581
+ });
582
+ }
583
+ }
584
+ return steps.length > 0 ? (o) => {
585
+ for (const step of steps) {
586
+ step(o);
587
+ }
588
+ } : void 0;
589
+ }
590
+ var protoConverterCache = createCache((client, objectDef) => {
591
+ const proto = createPrototype(objectDef, client);
592
+ const converter = createConverter(objectDef);
593
+ return [proto, converter];
594
+ });
595
+ async function convertWireToOsdkObjects(client, objects, interfaceApiName, forceRemoveRid = false) {
596
+ if (forceRemoveRid) {
597
+ for (const obj of objects) {
598
+ delete obj.__rid;
599
+ }
600
+ }
601
+ fixObjectPropertiesInline(objects);
602
+ const localObjectCache = createLocalObjectCacheAndInitiatePreseed(objects, client);
603
+ for (const obj of objects) {
604
+ const objectDef = await localObjectCache.get(client, obj.$apiName);
605
+ if (objectDef == null) {
606
+ throw new Error(`Failed to find ontology definition for '${obj.$apiName}'`);
607
+ }
608
+ if (interfaceApiName !== void 0) {
609
+ for (const [sptProp, regularProp] of Object.entries(objectDef.spts)) {
610
+ if (sptProp in obj) {
611
+ const value = obj[sptProp];
612
+ delete obj[sptProp];
613
+ if (value !== void 0) {
614
+ obj[regularProp] = value;
615
+ }
616
+ }
617
+ }
618
+ }
619
+ internalConvertObjectInPlace(objectDef, client, obj);
620
+ }
621
+ if (interfaceApiName) {
622
+ return objects.map((o) => o.$as(interfaceApiName));
623
+ } else {
624
+ return objects;
625
+ }
626
+ }
627
+ function createLocalObjectCacheAndInitiatePreseed(objects, client) {
628
+ const localInterfaceCache = createAsyncCache((client2, apiName) => client2.ontology.provider.getInterfaceDefinition(apiName));
629
+ const localObjectCache = createAsyncCache(async (client2, apiName) => {
630
+ const objectDef = await client2.ontology.provider.getObjectDefinition(apiName);
631
+ const interfaceDefs = Object.fromEntries((await Promise.all(objectDef.implements?.map((i) => localInterfaceCache.get(client2, i)) ?? [])).map((i) => [i.apiName, i]));
632
+ if (objectDef[InterfaceDefinitions] == null) {
633
+ Object.defineProperty(objectDef, InterfaceDefinitions, {
634
+ value: interfaceDefs,
635
+ enumerable: false,
636
+ configurable: false,
637
+ writable: false
638
+ });
639
+ }
640
+ return objectDef;
641
+ });
642
+ const uniqueApiNames = /* @__PURE__ */ new Set();
643
+ for (const {
644
+ $apiName
645
+ } of objects) {
646
+ if (uniqueApiNames.has($apiName))
647
+ continue;
648
+ uniqueApiNames.add($apiName);
649
+ localObjectCache.get(client, $apiName);
650
+ }
651
+ return localObjectCache;
652
+ }
653
+ function fixObjectPropertiesInline(objs) {
654
+ for (const obj of objs) {
655
+ if (obj.__rid) {
656
+ obj.$rid = obj.__rid;
657
+ delete obj.__rid;
658
+ }
659
+ obj.$apiName = obj.__apiName;
660
+ obj.$objectType = obj.__apiName;
661
+ obj.$primaryKey = obj.__primaryKey;
662
+ {
663
+ Object.defineProperties(obj, {
664
+ "__apiName": {
665
+ enumerable: false
666
+ },
667
+ "__primaryKey": {
668
+ enumerable: false
669
+ }
670
+ });
671
+ }
672
+ }
673
+ }
674
+ function internalConvertObjectInPlace(objectDef, client, obj) {
675
+ const [proto, converter] = protoConverterCache.get(client, objectDef);
676
+ Object.setPrototypeOf(obj, proto);
677
+ Object.defineProperties(obj, {
678
+ [OriginClient]: {
679
+ value: client
680
+ },
681
+ [UnderlyingObject]: {
682
+ value: obj
683
+ }
684
+ });
685
+ if (converter) {
686
+ converter(obj);
687
+ }
688
+ }
689
+ async function aggregate(clientCtx, objectType, objectSet = {
690
+ type: "base",
691
+ objectType: objectType["apiName"]
692
+ }, req) {
693
+ const body = {
694
+ aggregation: modernToLegacyAggregationClause(req.select),
695
+ groupBy: [],
696
+ where: void 0
697
+ };
698
+ if (req.groupBy) {
699
+ body.groupBy = modernToLegacyGroupByClause(req.groupBy);
700
+ }
701
+ if (req.where) {
702
+ body.where = modernToLegacyWhereClause(req.where);
703
+ }
704
+ const result = await aggregateObjectSetV2(createOpenApiRequest(clientCtx.stack, clientCtx.fetch), clientCtx.ontology.metadata.ontologyApiName, {
705
+ objectSet,
706
+ groupBy: body.groupBy,
707
+ aggregation: body.aggregation
708
+ });
709
+ if (!req.groupBy) {
710
+ !(result.data.length === 1) ? process.env.NODE_ENV !== "production" ? invariant2(false, "no group by clause should mean only one data result") : invariant2(false) : void 0;
711
+ return {
712
+ ...aggregationToCountResult(result.data[0]),
713
+ ...legacyToModernSingleAggregationResult(result.data[0])
714
+ };
715
+ }
716
+ const ret = result.data.map((entry) => {
717
+ return {
718
+ $group: entry.group,
719
+ ...aggregationToCountResult(entry),
720
+ ...legacyToModernSingleAggregationResult(entry)
721
+ };
722
+ });
723
+ return ret;
724
+ }
725
+ function aggregationToCountResult(entry) {
726
+ for (const aggregateResult of entry.metrics) {
727
+ if (aggregateResult.name === "count") {
728
+ return {
729
+ $count: aggregateResult.value
730
+ };
731
+ }
732
+ }
733
+ }
734
+
735
+ // src/util/WireObjectSet.ts
736
+ var WIRE_OBJECT_SET_TYPES = /* @__PURE__ */ new Set(["base", "filter", "intersect", "reference", "searchAround", "static", "subtract", "union"]);
737
+ function isWireObjectSet(o) {
738
+ return o != null && typeof o === "object" && WIRE_OBJECT_SET_TYPES.has(o.type);
739
+ }
740
+ async function createTemporaryObjectSet(ctx, request) {
741
+ return conjureFetch(ctx, `/objectSets/temporary`, "POST", request);
742
+ }
743
+ async function batchEnableWatcher(ctx, request) {
744
+ return conjureFetch(ctx, `/object-set-watcher/batchEnableWatcher`, "POST", request);
745
+ }
746
+ async function loadAllOntologies(ctx, request) {
747
+ return conjureFetch(ctx, `/ontology/ontology/ontologies/load/all`, "POST", request);
748
+ }
749
+ async function loadOntologyEntities(ctx, request) {
750
+ return conjureFetch(ctx, `/ontology/ontology/loadEntities`, "POST", request);
751
+ }
752
+
753
+ // src/objectSet/toConjureObjectSet.ts
754
+ function toConjureObjectSet(objectSet, objectPropertyMapping) {
755
+ switch (objectSet.type) {
756
+ case "base":
757
+ return {
758
+ type: "base",
759
+ base: {
760
+ objectTypeId: objectPropertyMapping.id
761
+ }
762
+ };
763
+ case "static":
764
+ return {
765
+ type: "static",
766
+ static: {
767
+ objectRids: objectSet.objects,
768
+ provenance: void 0
769
+ }
770
+ };
771
+ case "reference":
772
+ return {
773
+ type: "referenced",
774
+ referenced: {
775
+ objectSetRid: objectSet.reference
776
+ }
777
+ };
778
+ case "filter":
779
+ return {
780
+ type: "filtered",
781
+ filtered: {
782
+ objectSet: toConjureObjectSet(objectSet.objectSet, objectPropertyMapping),
783
+ runtimeDerivedProperties: void 0,
784
+ filter: mapWhereClauseToObjectSetFilter(objectSet.where, objectPropertyMapping)
785
+ }
786
+ };
787
+ case "union":
788
+ return {
789
+ type: "unioned",
790
+ unioned: {
791
+ objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
792
+ }
793
+ };
794
+ case "intersect":
795
+ return {
796
+ type: "intersected",
797
+ intersected: {
798
+ objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
799
+ }
800
+ };
801
+ case "subtract":
802
+ return {
803
+ type: "subtracted",
804
+ subtracted: {
805
+ objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
806
+ }
807
+ };
808
+ case "searchAround":
809
+ throw new Error("not implemented");
810
+ }
811
+ }
812
+ async function getObjectSetBaseType(objectSet) {
813
+ switch (objectSet.type) {
814
+ case "base":
815
+ return objectSet.objectType;
816
+ case "static":
817
+ throw new Error("not implemented");
818
+ case "reference":
819
+ throw new Error("not implemented");
820
+ case "filter":
821
+ return getObjectSetBaseType(objectSet.objectSet);
822
+ case "union":
823
+ return getObjectSetBaseType(objectSet.objectSets[0]);
824
+ case "intersect":
825
+ return getObjectSetBaseType(objectSet.objectSets[0]);
826
+ case "subtract":
827
+ return getObjectSetBaseType(objectSet.objectSets[0]);
828
+ case "searchAround":
829
+ throw new Error("not implemented");
830
+ }
831
+ }
832
+ function mapWhereClauseToObjectSetFilter(objectSetFilter, propertyMapping) {
833
+ switch (objectSetFilter.type) {
834
+ case "lt":
835
+ return {
836
+ type: "range",
837
+ range: {
838
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
839
+ lt: objectSetFilter.value,
840
+ lte: void 0,
841
+ gt: void 0,
842
+ gte: void 0
843
+ }
844
+ };
845
+ case "gt":
846
+ return {
847
+ type: "range",
848
+ range: {
849
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
850
+ gt: objectSetFilter.value,
851
+ lte: void 0,
852
+ lt: void 0,
853
+ gte: void 0
854
+ }
855
+ };
856
+ case "lte":
857
+ return {
858
+ type: "range",
859
+ range: {
860
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
861
+ lte: objectSetFilter.value,
862
+ lt: void 0,
863
+ gt: void 0,
864
+ gte: void 0
865
+ }
866
+ };
867
+ case "gte":
868
+ return {
869
+ type: "range",
870
+ range: {
871
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
872
+ gte: objectSetFilter.value,
873
+ lt: void 0,
874
+ lte: void 0,
875
+ gt: void 0
876
+ }
877
+ };
878
+ case "eq":
879
+ return {
880
+ type: "exactMatch",
881
+ exactMatch: {
882
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
883
+ terms: []
884
+ }
885
+ };
886
+ case "and":
887
+ return {
888
+ type: "and",
889
+ and: {
890
+ filters: objectSetFilter.value.map((filter) => mapWhereClauseToObjectSetFilter(filter, propertyMapping))
891
+ }
892
+ };
893
+ case "or":
894
+ return {
895
+ type: "or",
896
+ or: {
897
+ filters: objectSetFilter.value.map((filter) => mapWhereClauseToObjectSetFilter(filter, propertyMapping))
898
+ }
899
+ };
900
+ case "isNull":
901
+ return {
902
+ type: "not",
903
+ not: {
904
+ filter: {
905
+ type: "hasProperty",
906
+ hasProperty: {
907
+ propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field]
908
+ }
909
+ }
910
+ }
911
+ };
912
+ case "not":
913
+ return {
914
+ type: "not",
915
+ not: {
916
+ filter: mapWhereClauseToObjectSetFilter(objectSetFilter.value, propertyMapping)
917
+ }
918
+ };
919
+ case "contains":
920
+ case "startsWith":
921
+ case "containsAllTermsInOrder":
922
+ case "containsAnyTerm":
923
+ case "containsAllTerms":
924
+ case "withinDistanceOf":
925
+ case "withinBoundingBox":
926
+ case "intersectsBoundingBox":
927
+ case "doesNotIntersectBoundingBox":
928
+ case "withinPolygon":
929
+ case "intersectsPolygon":
930
+ case "doesNotIntersectPolygon":
931
+ case "containsAllTermsInOrderPrefixLastTerm":
932
+ throw new Error("not implemented");
933
+ }
934
+ }
935
+
936
+ // src/objectSet/ObjectSetListenerWebsocket.ts
937
+ var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
938
+ var MINIMUM_RECONNECT_DELAY_MS = 5 * 1e3;
939
+ var ObjectSetListenerWebsocket = class _ObjectSetListenerWebsocket {
940
+ static #instances = /* @__PURE__ */ new WeakMap();
941
+ // FIXME
942
+ static getInstance(client) {
943
+ let instance = _ObjectSetListenerWebsocket.#instances.get(client);
944
+ if (instance == null) {
945
+ instance = new _ObjectSetListenerWebsocket(client);
946
+ _ObjectSetListenerWebsocket.#instances.set(client, instance);
947
+ }
948
+ return instance;
949
+ }
950
+ #ws;
951
+ #lastWsConnect = 0;
952
+ #client;
953
+ /** map of listenerId to listener */
954
+ #listeners = /* @__PURE__ */ new Map();
955
+ /** map of subscriptionId to listenerId */
956
+ #subscriptionToRequestId = /* @__PURE__ */ new Map();
957
+ #conjureContext;
958
+ #metadataContext;
959
+ #ossContext;
960
+ constructor(client) {
961
+ this.#client = client;
962
+ const stackUrl = new URL(client.stack);
963
+ this.#conjureContext = {
964
+ baseUrl: stackUrl.origin,
965
+ servicePath: "/object-set-watcher/api",
966
+ fetchFn: client.fetch,
967
+ tokenProvider: async () => await client.tokenProvider()
968
+ };
969
+ this.#ossContext = {
970
+ baseUrl: stackUrl.origin,
971
+ servicePath: "/object-set-service/api",
972
+ fetchFn: client.fetch,
973
+ tokenProvider: async () => await client.tokenProvider()
974
+ };
975
+ this.#metadataContext = {
976
+ baseUrl: stackUrl.origin,
977
+ servicePath: "/ontology-metadata/api",
978
+ fetchFn: client.fetch,
979
+ tokenProvider: async () => await client.tokenProvider()
980
+ };
981
+ }
982
+ subscribe(objectSet, listener) {
983
+ const requestId = crypto.randomUUID();
984
+ const expiry = setTimeout(() => {
985
+ this.#expire(requestId);
986
+ }, ONE_DAY_MS);
987
+ this.#listeners.set(requestId, {
988
+ listener,
989
+ objectSet,
990
+ expiry
991
+ });
992
+ this.#subscribe(requestId, objectSet);
993
+ return () => {
994
+ this.#unsubscribe(requestId);
995
+ };
996
+ }
997
+ async #subscribe(requestId, objectSet) {
998
+ try {
999
+ const [temporaryObjectSet] = await Promise.all([
1000
+ // create a time-bounded object set representation for watching
1001
+ this.#createTemporaryObjectSet(objectSet),
1002
+ this.#ensureWebsocket(),
1003
+ // look up the object type's rid and ensure that we have enabled object set watcher for that rid
1004
+ // TODO ???
1005
+ getObjectSetBaseType(objectSet).then((baseType) => getObjectTypeV2(createOpenApiRequest(this.#client.stack, this.#client.fetch), this.#client.ontology.metadata.ontologyApiName, baseType)).then((objectType) => this.#enableObjectSetsWatcher([objectType.rid]))
1006
+ ]);
1007
+ if (!this.#listeners.has(requestId)) {
1008
+ return;
1009
+ }
1010
+ const subscribe = {
1011
+ id: requestId,
1012
+ requests: [{
1013
+ objectSet: temporaryObjectSet.objectSetRid,
1014
+ objectSetContext: {
1015
+ objectSetFilterContext: {
1016
+ parameterOverrides: {}
1017
+ }
1018
+ },
1019
+ watchAllLinks: false
1020
+ }]
1021
+ };
1022
+ this.#ws?.send(JSON.stringify(subscribe));
1023
+ } catch (error) {
1024
+ this.#getCallbackByRequestId(requestId, "onError")?.(error);
1025
+ }
1026
+ }
1027
+ #expire(requestId) {
1028
+ const state = this.#listeners.get(requestId);
1029
+ if (state) {
1030
+ const {
1031
+ subscriptionId,
1032
+ objectSet
1033
+ } = state;
1034
+ if (subscriptionId) {
1035
+ state.subscriptionId = void 0;
1036
+ this.#subscriptionToRequestId.delete(subscriptionId);
1037
+ }
1038
+ this.#subscribe(requestId, objectSet);
1039
+ }
1040
+ }
1041
+ #unsubscribe(requestId) {
1042
+ const data = this.#listeners.get(requestId);
1043
+ if (data == null) {
1044
+ return;
1045
+ }
1046
+ this.#listeners.delete(requestId);
1047
+ clearTimeout(data.expiry);
1048
+ const {
1049
+ subscriptionId
1050
+ } = data;
1051
+ if (subscriptionId != null) {
1052
+ this.#subscriptionToRequestId.delete(subscriptionId);
1053
+ }
1054
+ if (this.#listeners.size === 0) {
1055
+ this.#destroyWebsocket();
1056
+ }
1057
+ }
1058
+ async #ensureWebsocket() {
1059
+ if (this.#ws == null) {
1060
+ const {
1061
+ stack,
1062
+ tokenProvider
1063
+ } = this.#client;
1064
+ const base = new URL(stack);
1065
+ const url = `wss://${base.host}/object-set-watcher/ws/subscriptions`;
1066
+ const token = await tokenProvider();
1067
+ if (this.#ws == null) {
1068
+ const nextConnectTime = (this.#lastWsConnect ?? 0) + MINIMUM_RECONNECT_DELAY_MS;
1069
+ if (nextConnectTime > Date.now()) {
1070
+ await new Promise((resolve) => {
1071
+ setTimeout(resolve, nextConnectTime - Date.now());
1072
+ });
1073
+ }
1074
+ this.#lastWsConnect = Date.now();
1075
+ if (this.#ws == null) {
1076
+ this.#ws = new WebSocket(url, [`Bearer-${token}`]);
1077
+ this.#ws.addEventListener("close", this.#onClose);
1078
+ this.#ws.addEventListener("message", this.#onMessage);
1079
+ this.#ws.addEventListener("open", this.#onOpen);
1080
+ }
1081
+ }
1082
+ if (this.#ws.readyState === WebSocket.CONNECTING) {
1083
+ return new Promise((resolve, reject) => {
1084
+ this.#ws.addEventListener("open", () => {
1085
+ resolve();
1086
+ });
1087
+ this.#ws.addEventListener("error", (event) => {
1088
+ reject(new Error(event.toString()));
1089
+ });
1090
+ });
1091
+ }
1092
+ }
1093
+ }
1094
+ #onOpen = () => {
1095
+ for (const [requestId, state] of this.#listeners) {
1096
+ this.#subscribe(requestId, state.objectSet);
1097
+ }
1098
+ };
1099
+ #onMessage = async (message) => {
1100
+ const data = JSON.parse(message.data.toString());
1101
+ switch (data.type) {
1102
+ case "objectSetChanged": {
1103
+ if (data.objectSetChanged.confidenceValue) {
1104
+ this.#getCallback(data.objectSetChanged.id, "onOutOfDate")?.();
1105
+ break;
1106
+ }
1107
+ const {
1108
+ id: subscriptionId,
1109
+ objects
1110
+ } = data.objectSetChanged;
1111
+ const callback = this.#getCallback(subscriptionId, "onChange");
1112
+ if (callback) {
1113
+ callback(await convertFoundryToOsdkObjects(this.#client, this.#metadataContext, objects));
1114
+ }
1115
+ break;
1116
+ }
1117
+ case "refreshObjectSet": {
1118
+ const {
1119
+ id: subscriptionId
1120
+ } = data.refreshObjectSet;
1121
+ this.#getCallback(subscriptionId, "onOutOfDate")?.();
1122
+ break;
1123
+ }
1124
+ case "subscribeResponses": {
1125
+ const {
1126
+ id: requestId,
1127
+ responses
1128
+ } = data.subscribeResponses;
1129
+ const listenerData = this.#listeners.get(requestId);
1130
+ if (listenerData == null) {
1131
+ return;
1132
+ }
1133
+ if (responses.length !== 1) {
1134
+ throw new Error("Got more than one response but we only expect a single one");
1135
+ }
1136
+ const response = responses[0];
1137
+ switch (response.type) {
1138
+ case "error":
1139
+ this.#getCallbackByRequestId(requestId, "onError")?.(response.error);
1140
+ this.#unsubscribe(requestId);
1141
+ return;
1142
+ case "qos":
1143
+ this.#destroyWebsocket();
1144
+ this.#ensureWebsocket();
1145
+ return;
1146
+ case "success":
1147
+ const {
1148
+ id: subscriptionId
1149
+ } = response.success;
1150
+ listenerData.subscriptionId = subscriptionId;
1151
+ this.#subscriptionToRequestId.set(subscriptionId, requestId);
1152
+ this.#getCallbackByRequestId(requestId, "onOutOfDate")?.();
1153
+ break;
1154
+ default:
1155
+ this.#getCallbackByRequestId(requestId, "onError")?.(response);
1156
+ }
1157
+ break;
1158
+ }
1159
+ }
1160
+ };
1161
+ #onClose = () => {
1162
+ this.#destroyWebsocket();
1163
+ };
1164
+ async #enableObjectSetsWatcher(objectTypeRids) {
1165
+ return batchEnableWatcher(this.#conjureContext, {
1166
+ requests: objectTypeRids
1167
+ });
1168
+ }
1169
+ async #createTemporaryObjectSet(objectSet) {
1170
+ const objectSetBaseType = await getObjectSetBaseType(objectSet);
1171
+ const mapping = await getOntologyPropertyMappingForApiName(this.#client, this.#metadataContext, objectSetBaseType);
1172
+ const temporaryObjectSet = await createTemporaryObjectSet(this.#ossContext, {
1173
+ objectSet: toConjureObjectSet(objectSet, mapping),
1174
+ timeToLive: "ONE_DAY",
1175
+ objectSetFilterContext: {
1176
+ parameterOverrides: {}
1177
+ }
1178
+ });
1179
+ return {
1180
+ objectSetRid: temporaryObjectSet.objectSetRid
1181
+ };
1182
+ }
1183
+ #destroyWebsocket = () => {
1184
+ if (this.#ws) {
1185
+ this.#ws.removeEventListener("open", this.#onOpen);
1186
+ this.#ws.removeEventListener("message", this.#onMessage);
1187
+ this.#ws.removeEventListener("close", this.#onClose);
1188
+ if (this.#ws.readyState !== WebSocket.CLOSING && this.#ws.readyState !== WebSocket.CLOSED) {
1189
+ this.#ws.close();
1190
+ }
1191
+ this.#ws = void 0;
1192
+ }
1193
+ this.#subscriptionToRequestId.clear();
1194
+ for (const state of this.#listeners.values()) {
1195
+ state.subscriptionId = void 0;
1196
+ }
1197
+ if (this.#listeners.size > 0) {
1198
+ this.#ensureWebsocket();
1199
+ }
1200
+ };
1201
+ #getCallbackByRequestId(requestId, type) {
1202
+ const maybeListener = this.#listeners.get(requestId);
1203
+ return maybeListener?.listener?.[type];
1204
+ }
1205
+ #getCallback(subscriptionId, type) {
1206
+ const requestId = this.#subscriptionToRequestId.get(subscriptionId);
1207
+ if (requestId) {
1208
+ return this.#getCallbackByRequestId(requestId, type);
1209
+ }
1210
+ return;
1211
+ }
1212
+ };
1213
+ async function convertFoundryToOsdkObjects(client, ctx, objects) {
1214
+ const osdkObjects = await Promise.all(objects.map(async (object) => {
1215
+ const propertyMapping = await getOntologyPropertyMappingForRid(ctx, client.ontology.metadata.ontologyRid, object.type);
1216
+ const convertedObject = Object.fromEntries([...Object.entries(object.properties).map(([key, value]) => {
1217
+ return [propertyMapping?.propertyIdToApiNameMapping[key], value];
1218
+ }), [propertyMapping?.propertyIdToApiNameMapping[Object.entries(object.key)[0][0]], Object.entries(object.key)[0][1]], ["__apiName", propertyMapping?.apiName], ["$apiName", propertyMapping?.apiName]]);
1219
+ return convertedObject;
1220
+ }));
1221
+ return await convertWireToOsdkObjects(client, osdkObjects, void 0);
1222
+ }
1223
+ var objectTypeMapping = /* @__PURE__ */ new WeakMap();
1224
+ var objectApiNameToRid = /* @__PURE__ */ new Map();
1225
+ async function getOntologyPropertyMappingForApiName(client, ctx, objectApiName) {
1226
+ if (objectApiNameToRid.has(objectApiName)) {
1227
+ return objectTypeMapping.get(ctx)?.get(objectApiNameToRid.get(objectApiName));
1228
+ }
1229
+ const wireObjectType = await getObjectTypeV2(createOpenApiRequest(client.stack, client.fetch), client.ontology.metadata.ontologyApiName, objectApiName);
1230
+ return getOntologyPropertyMappingForRid(ctx, client.ontology.metadata.ontologyRid, wireObjectType.rid);
1231
+ }
1232
+ var cachedAllOntologies;
1233
+ async function getOntologyVersionForRid(ctx, ontologyRid) {
1234
+ cachedAllOntologies ??= await loadAllOntologies(ctx, {});
1235
+ !cachedAllOntologies.ontologies[ontologyRid] ? process.env.NODE_ENV !== "production" ? invariant2(false, "ontology should be loaded") : invariant2(false) : void 0;
1236
+ return cachedAllOntologies.ontologies[ontologyRid].currentOntologyVersion;
1237
+ }
1238
+ async function getOntologyPropertyMappingForRid(ctx, ontologyRid, objectRid) {
1239
+ if (!objectTypeMapping.has(ctx)) {
1240
+ objectTypeMapping.set(ctx, /* @__PURE__ */ new Map());
1241
+ }
1242
+ if (!objectTypeMapping.get(ctx).has(objectRid)) {
1243
+ const ontologyVersion = await getOntologyVersionForRid(ctx, ontologyRid);
1244
+ const body = {
1245
+ objectTypeVersions: {
1246
+ // TODO: Undefined drops this in the body
1247
+ [objectRid]: ontologyVersion
1248
+ },
1249
+ linkTypeVersions: {},
1250
+ loadRedacted: false,
1251
+ includeObjectTypesWithoutSearchableDatasources: true
1252
+ };
1253
+ const entities = await loadOntologyEntities(ctx, body);
1254
+ !entities.objectTypes[objectRid] ? process.env.NODE_ENV !== "production" ? invariant2(false, "object type should be loaded") : invariant2(false) : void 0;
1255
+ const propertyIdToApiNameMapping = Object.fromEntries(Object.values(entities.objectTypes[objectRid].propertyTypes).map((property) => {
1256
+ return [property.id, property.apiName];
1257
+ }));
1258
+ const propertyApiNameToIdMapping = Object.fromEntries(Object.values(entities.objectTypes[objectRid].propertyTypes).map((property) => {
1259
+ return [property.id, property.apiName];
1260
+ }));
1261
+ objectTypeMapping.get(ctx)?.set(objectRid, {
1262
+ apiName: entities.objectTypes[objectRid].apiName,
1263
+ id: entities.objectTypes[objectRid].id,
1264
+ propertyIdToApiNameMapping,
1265
+ propertyApiNameToIdMapping
1266
+ });
1267
+ objectApiNameToRid.set(entities.objectTypes[objectRid].apiName, objectRid);
1268
+ }
1269
+ return objectTypeMapping.get(ctx)?.get(objectRid);
1270
+ }
1271
+
1272
+ // src/objectSet/createObjectSet.ts
1273
+ function isObjectTypeDefinition(def) {
1274
+ return def.type === "object";
1275
+ }
1276
+ function isObjectSet(o) {
1277
+ return o != null && typeof o === "object" && isWireObjectSet(objectSetDefinitions.get(o));
1278
+ }
1279
+ function getWireObjectSet(objectSet) {
1280
+ return objectSetDefinitions.get(objectSet);
1281
+ }
1282
+ var objectSetDefinitions = /* @__PURE__ */ new WeakMap();
1283
+ function createObjectSet(objectType, clientCtx, objectSet = {
1284
+ type: "base",
1285
+ objectType: objectType["apiName"]
1286
+ }) {
1287
+ const base = {
1288
+ aggregate: aggregate.bind(globalThis, clientCtx, objectType, objectSet),
1289
+ aggregateOrThrow: aggregate.bind(globalThis, clientCtx, objectType, objectSet),
1290
+ fetchPage: fetchPageInternal.bind(globalThis, clientCtx, objectType, objectSet),
1291
+ fetchPageWithErrors: fetchPageWithErrorsInternal.bind(globalThis, clientCtx, objectType, objectSet),
1292
+ fetchPageOrThrow: fetchPageInternal.bind(globalThis, clientCtx, objectType, objectSet),
1293
+ where: (clause) => {
1294
+ return createObjectSet(objectType, clientCtx, {
1295
+ type: "filter",
1296
+ objectSet,
1297
+ where: modernToLegacyWhereClause(clause)
1298
+ });
1299
+ },
1300
+ pivotTo: function(type) {
1301
+ return createSearchAround(type)();
1302
+ },
1303
+ union: (...objectSets) => {
1304
+ return createObjectSet(objectType, clientCtx, {
1305
+ type: "union",
1306
+ objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
1307
+ });
1308
+ },
1309
+ intersect: (...objectSets) => {
1310
+ return createObjectSet(objectType, clientCtx, {
1311
+ type: "intersect",
1312
+ objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
1313
+ });
1314
+ },
1315
+ subtract: (...objectSets) => {
1316
+ return createObjectSet(objectType, clientCtx, {
1317
+ type: "subtract",
1318
+ objectSets: [objectSet, ...objectSets.map((os) => objectSetDefinitions.get(os))]
1319
+ });
1320
+ },
1321
+ subscribe(listener) {
1322
+ const instance = ObjectSetListenerWebsocket.getInstance(clientCtx);
1323
+ return instance.subscribe(objectSet, listener);
1324
+ },
1325
+ asyncIter: async function* () {
1326
+ let nextPageToken = void 0;
1327
+ do {
1328
+ const result = await base.fetchPage({
1329
+ nextPageToken
1330
+ });
1331
+ for (const obj of await convertWireToOsdkObjects(clientCtx, result.data, void 0)) {
1332
+ yield obj;
1333
+ }
1334
+ } while (nextPageToken != null);
1335
+ },
1336
+ get: isObjectTypeDefinition(objectType) ? async (primaryKey, options) => {
1337
+ const withPk = {
1338
+ type: "filter",
1339
+ objectSet,
1340
+ where: {
1341
+ type: "eq",
1342
+ field: objectType.primaryKeyApiName,
1343
+ value: primaryKey
1344
+ }
1345
+ };
1346
+ return await fetchSingle(clientCtx, objectType, options, withPk);
1347
+ } : void 0
1348
+ };
1349
+ function createSearchAround(link) {
1350
+ return () => {
1351
+ return createObjectSet(objectType, clientCtx, {
1352
+ type: "searchAround",
1353
+ objectSet,
1354
+ link
1355
+ });
1356
+ };
1357
+ }
1358
+ objectSetDefinitions.set(base, objectSet);
1359
+ return base;
1360
+ }
9
1361
 
10
1362
  // src/util/isOntologyObjectV2.ts
11
1363
  function isOntologyObjectV2(o) {
@@ -41,14 +1393,6 @@ function toDataValue(value) {
41
1393
  return value;
42
1394
  }
43
1395
 
44
- // src/actions/ActionValidationError.ts
45
- var ActionValidationError = class extends Error {
46
- constructor(validation) {
47
- super("Validation Error");
48
- this.validation = validation;
49
- }
50
- };
51
-
52
1396
  // src/actions/applyAction.ts
53
1397
  async function applyAction(client, action, parameters, options = {}) {
54
1398
  const response = await applyActionV2(createOpenApiRequest(client.stack, client.fetch), client.ontology.metadata.ontologyApiName, action.apiName, {
@@ -120,9 +1464,8 @@ async function loadAllOutgoingLinkTypes(client, objtype) {
120
1464
  return linkTypes;
121
1465
  }
122
1466
  function makeConjureContext(client, servicePath) {
123
- const baseUrl = client.stack.startsWith("https://") ? client.stack : `https://${client.stack}`;
124
1467
  return {
125
- baseUrl,
1468
+ baseUrl: client.stack,
126
1469
  servicePath,
127
1470
  fetchFn: client.fetch,
128
1471
  tokenProvider: async () => await client.tokenProvider()
@@ -158,7 +1501,7 @@ async function loadSptMap(ctx, ontologyMetadata, ontologyRid, objectRid) {
158
1501
  };
159
1502
  const entities = await loadOntologyEntities(ctx, body);
160
1503
  const objectType = entities.objectTypes[objectRid];
161
- !objectType ? process.env.NODE_ENV !== "production" ? invariant(false, "object type should be loaded") : invariant(false) : void 0;
1504
+ !objectType ? process.env.NODE_ENV !== "production" ? invariant2(false, "object type should be loaded") : invariant2(false) : void 0;
162
1505
  const sptMap = {};
163
1506
  for (const property of Object.values(objectType.propertyTypes)) {
164
1507
  if (property.sharedPropertyTypeApiName && property.apiName) {
@@ -217,7 +1560,7 @@ var createStandardOntologyProviderFactory = (client) => {
217
1560
  };
218
1561
 
219
1562
  // src/util/UserAgent.ts
220
- var USER_AGENT = `osdk-client/${"0.14.0"}`;
1563
+ var USER_AGENT = `osdk-client/${"0.15.0"}`;
221
1564
 
222
1565
  // src/createMinimalClient.ts
223
1566
  function createMinimalClient(metadata, stack, tokenProvider, ontologyCachingOptions = {}, fetchFn = global.fetch) {
@@ -269,7 +1612,16 @@ function createFutureClientPlus(metadata, stack, tokenProvider, ontologyCachingO
269
1612
  }
270
1613
  return [clientCtx, clientFn];
271
1614
  }
1615
+ function createFutureClient(metadata, stack, tokenProvider, ontologyCachingOptions = {}, fetchFn = fetch) {
1616
+ return createFutureClientPlus(metadata, stack, tokenProvider, ontologyCachingOptions, fetchFn)[1];
1617
+ }
1618
+ function isOntologyMetadata(ontology) {
1619
+ return "ontologyRid" in ontology || "ontologyApiName" in ontology;
1620
+ }
272
1621
  function createClient(ontology, stack, tokenProvider, ontologyCachingOptions = {}, fetchFn = fetch) {
1622
+ if (isOntologyMetadata(ontology)) {
1623
+ return createFutureClient(ontology, stack, tokenProvider, ontologyCachingOptions, fetchFn);
1624
+ }
273
1625
  const [clientCtx, clientFn] = createFutureClientPlus(ontology.metadata, stack, tokenProvider, ontologyCachingOptions, fetchFn);
274
1626
  const objectSetFactory = (type) => createObjectSet(ontology["objects"][type] ?? ontology["interfaces"]?.[type], clientCtx);
275
1627
  const oldActionInvoker = createOldActionInvoker(clientCtx, ontology);
@@ -301,6 +1653,6 @@ function createClient(ontology, stack, tokenProvider, ontologyCachingOptions = {
301
1653
  return client;
302
1654
  }
303
1655
 
304
- export { ActionValidationError, createClient, createMinimalClient };
1656
+ export { ActionValidationError, augment, createClient, createMinimalClient };
305
1657
  //# sourceMappingURL=out.js.map
306
1658
  //# sourceMappingURL=index.mjs.map