@osdk/client 0.21.0 → 0.22.0-beta.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 (61) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/build/browser/{chunk-2KBOMZHU.js → chunk-CHT6RCVZ.js} +232 -190
  3. package/build/browser/chunk-CHT6RCVZ.js.map +1 -0
  4. package/build/browser/index.js +2 -2
  5. package/build/browser/public/unstable-do-not-use.js +2 -2
  6. package/build/esm/Client.d.ts +5 -4
  7. package/build/esm/Client.d.ts.map +1 -1
  8. package/build/esm/__unstable/UnstableClient.d.ts +2 -2
  9. package/build/esm/__unstable/UnstableClient.d.ts.map +1 -1
  10. package/build/esm/actions/applyAction.d.ts +17 -2
  11. package/build/esm/actions/applyAction.d.ts.map +1 -1
  12. package/build/esm/{chunk-2KBOMZHU.js → chunk-CHT6RCVZ.js} +232 -190
  13. package/build/esm/chunk-CHT6RCVZ.js.map +1 -0
  14. package/build/esm/createAttachmentFromRid.d.ts +6 -0
  15. package/build/esm/createAttachmentFromRid.d.ts.map +1 -1
  16. package/build/esm/createClient.d.ts.map +1 -1
  17. package/build/esm/index.d.ts +1 -1
  18. package/build/esm/index.d.ts.map +1 -1
  19. package/build/esm/index.js +2 -2
  20. package/build/esm/intellisense.test.d.ts +2 -0
  21. package/build/esm/intellisense.test.d.ts.map +1 -0
  22. package/build/esm/intellisense.test.helpers/callsQueryAcceptsObject.d.ts +2 -0
  23. package/build/esm/intellisense.test.helpers/callsQueryAcceptsObject.d.ts.map +1 -0
  24. package/build/esm/object/Cache.d.ts +0 -39
  25. package/build/esm/object/Cache.d.ts.map +1 -1
  26. package/build/esm/objectSet/ObjectSetListenerWebsocket.d.ts.map +1 -1
  27. package/build/esm/objectSet/createUnstableObjectSet.d.ts +1 -5
  28. package/build/esm/objectSet/createUnstableObjectSet.d.ts.map +1 -1
  29. package/build/esm/ontology/OntologyProvider.d.ts +2 -2
  30. package/build/esm/ontology/OntologyProvider.d.ts.map +1 -1
  31. package/build/esm/public/unstable-do-not-use.js +2 -2
  32. package/build/esm/queries/applyQuery.d.ts +2 -1
  33. package/build/esm/queries/applyQuery.d.ts.map +1 -1
  34. package/build/esm/queries/types.d.ts +21 -0
  35. package/build/esm/queries/types.d.ts.map +1 -0
  36. package/build/esm/tsserver.d.ts +34 -0
  37. package/build/esm/tsserver.d.ts.map +1 -0
  38. package/build/esm/util/NOOP.d.ts +4 -0
  39. package/build/esm/util/NOOP.d.ts.map +1 -0
  40. package/build/esm/util/NullableProps.d.ts +6 -0
  41. package/build/esm/util/NullableProps.d.ts.map +1 -0
  42. package/build/esm/util/addUserAgentAndRequestContextHeaders.d.ts.map +1 -1
  43. package/build/esm/util/partialBy.d.ts +3 -0
  44. package/build/esm/util/partialBy.d.ts.map +1 -0
  45. package/package.json +17 -11
  46. package/build/browser/chunk-2KBOMZHU.js.map +0 -1
  47. package/build/cjs/chunk-XJRGYEPE.cjs +0 -2286
  48. package/build/cjs/chunk-XJRGYEPE.cjs.map +0 -1
  49. package/build/cjs/index.cjs +0 -38
  50. package/build/cjs/index.cjs.map +0 -1
  51. package/build/cjs/public/unstable-do-not-use.cjs +0 -879
  52. package/build/cjs/public/unstable-do-not-use.cjs.map +0 -1
  53. package/build/esm/ObjectSetCreator.d.ts +0 -19
  54. package/build/esm/ObjectSetCreator.d.ts.map +0 -1
  55. package/build/esm/OsdkObjectFrom.test.d.ts +0 -2
  56. package/build/esm/OsdkObjectFrom.test.d.ts.map +0 -1
  57. package/build/esm/chunk-2KBOMZHU.js.map +0 -1
  58. package/build/esm/queries/createQueryInvoker.d.ts +0 -5
  59. package/build/esm/queries/createQueryInvoker.d.ts.map +0 -1
  60. package/build/esm/util/test/mockOntology.d.ts +0 -66
  61. package/build/esm/util/test/mockOntology.d.ts.map +0 -1
@@ -1,879 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkXJRGYEPE_cjs = require('../chunk-XJRGYEPE.cjs');
4
- var shared_client = require('@osdk/shared.client');
5
- var client_unstable = require('@osdk/client.unstable');
6
- var client_unstable_osw = require('@osdk/client.unstable.osw');
7
- var WebSocket = require('isomorphic-ws');
8
- var invariant2 = require('tiny-invariant');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);
13
- var invariant2__default = /*#__PURE__*/_interopDefault(invariant2);
14
-
15
- // src/ontology/makeConjureContext.ts
16
- function makeConjureContext({
17
- baseUrl,
18
- fetch: fetchFn,
19
- tokenProvider
20
- }, servicePath) {
21
- return {
22
- baseUrl,
23
- servicePath,
24
- fetchFn,
25
- tokenProvider
26
- };
27
- }
28
-
29
- // src/__unstable/ConjureSupport.ts
30
- var cachedAllOntologies;
31
- async function getOntologyVersionForRid(ctx, ontologyRid) {
32
- cachedAllOntologies ??= await client_unstable.loadAllOntologies(ctx, {});
33
- !cachedAllOntologies.ontologies[ontologyRid] ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "ontology should be loaded") : invariant2__default.default(false) : void 0;
34
- return cachedAllOntologies.ontologies[ontologyRid].currentOntologyVersion;
35
- }
36
- var strongMemoAsync = (fn) => chunkXJRGYEPE_cjs.createSimpleAsyncCache("strong", fn).get;
37
- var weakMemoAsync = (fn) => chunkXJRGYEPE_cjs.createSimpleAsyncCache("weak", fn).get;
38
- var MetadataClient = class {
39
- #client;
40
- #ctx;
41
- #logger;
42
- constructor(client) {
43
- this.#client = client;
44
- this.#ctx = makeConjureContext(client, "/ontology-metadata/api");
45
- this.#client.ontologyProvider.getObjectDefinition;
46
- this.#logger = this.#client.logger?.child({
47
- mcc: true
48
- });
49
- }
50
- forObjectByRid = strongMemoAsync(async (rid) => {
51
- return Promise.resolve({
52
- getPropertyMapping: this.#objectPropertyMapping.bind(this, rid),
53
- getLinkMapping: this.#objectLinkMapping.bind(this, rid),
54
- getRid: () => rid,
55
- getApiName: async () => (await this.#getConjureObjectType(rid)).apiName
56
- });
57
- });
58
- forObjectByApiName = strongMemoAsync(async (objectApiName) => {
59
- const objectDef = await this.#client.ontologyProvider.getObjectDefinition(objectApiName);
60
- return this.forObjectByRid(objectDef.rid);
61
- });
62
- #objectPropertyMapping = strongMemoAsync(async (objectTypeRid) => {
63
- const conjureObjectType = await this.#getConjureObjectType(objectTypeRid);
64
- return createObjectPropertyMapping(conjureObjectType);
65
- });
66
- #objectLinkMapping = strongMemoAsync(async (objectTypeRid) => {
67
- const linkTypes = await client_unstable.getLinkTypesForObjectTypes(this.#ctx, {
68
- includeObjectTypesWithoutSearchableDatasources: true,
69
- loadRedacted: false,
70
- objectTypeBranches: {},
71
- objectTypeVersions: {
72
- [objectTypeRid]: await this.ontologyVersion("")
73
- }
74
- });
75
- !linkTypes.linkTypes[objectTypeRid] ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "link type should be loaded") : invariant2__default.default(false) : void 0;
76
- const ret = {};
77
- for (const l of linkTypes.linkTypes[objectTypeRid]) {
78
- const helper = ({
79
- apiName
80
- }, linkSide, otherObjectType) => {
81
- if (apiName) {
82
- ret[apiName] = {
83
- apiName,
84
- directedLinkTypeRid: {
85
- linkTypeRid: l.rid,
86
- linkSide
87
- },
88
- otherObjectType
89
- };
90
- }
91
- };
92
- if (l.definition.type === "oneToMany") {
93
- const {
94
- oneToMany: {
95
- objectTypeRidManySide,
96
- manyToOneLinkMetadata,
97
- objectTypeRidOneSide,
98
- oneToManyLinkMetadata
99
- }
100
- } = l.definition;
101
- if (objectTypeRidManySide === objectTypeRid) {
102
- helper(manyToOneLinkMetadata, "TARGET", objectTypeRidOneSide);
103
- }
104
- if (objectTypeRidOneSide === objectTypeRid) {
105
- helper(oneToManyLinkMetadata, "SOURCE", objectTypeRidManySide);
106
- }
107
- } else if (l.definition.type === "manyToMany") {
108
- const {
109
- manyToMany: {
110
- objectTypeRidA,
111
- objectTypeAToBLinkMetadata,
112
- objectTypeRidB,
113
- objectTypeBToALinkMetadata
114
- }
115
- } = l.definition;
116
- if (objectTypeRidA === objectTypeRid) {
117
- helper(objectTypeAToBLinkMetadata, "SOURCE", objectTypeRidB);
118
- }
119
- if (objectTypeRidB === objectTypeRid) {
120
- helper(objectTypeBToALinkMetadata, "TARGET", objectTypeRidA);
121
- }
122
- }
123
- }
124
- return ret;
125
- });
126
- #getConjureObjectType = strongMemoAsync(async (objectTypeRid) => {
127
- this.#logger?.debug(`getConjureObjectType(${objectTypeRid})`);
128
- const body = {
129
- objectTypeVersions: {
130
- [objectTypeRid]: await this.ontologyVersion("")
131
- },
132
- linkTypeVersions: {},
133
- loadRedacted: false,
134
- includeObjectTypesWithoutSearchableDatasources: true
135
- };
136
- const entities = await client_unstable.loadOntologyEntities(this.#ctx, body);
137
- !entities.objectTypes[objectTypeRid] ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "object type should be loaded") : invariant2__default.default(false) : void 0;
138
- return entities.objectTypes[objectTypeRid];
139
- });
140
- ontologyVersion = strongMemoAsync(async (_) => getOntologyVersionForRid(this.#ctx, await this.#client.ontologyRid));
141
- };
142
- var metadataCacheClient = weakMemoAsync((client) => Promise.resolve(new MetadataClient(client)));
143
- function createObjectPropertyMapping(conjureOT) {
144
- !(conjureOT.primaryKeys.length === 1) ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, `only one primary key supported, got ${conjureOT.primaryKeys.length}`) : invariant2__default.default(false) : void 0;
145
- const pkRid = conjureOT.primaryKeys[0];
146
- const pkProperty = Object.values(conjureOT.propertyTypes).find((a) => a.rid === pkRid);
147
- if (!pkProperty) {
148
- throw new Error(`Could not find PK property by rid: ${pkRid}`);
149
- }
150
- const propertyIdToApiNameMapping = Object.fromEntries(Object.values(conjureOT.propertyTypes).map((property) => {
151
- return [property.id, property.apiName];
152
- }));
153
- const propertyApiNameToIdMapping = Object.fromEntries(Object.values(conjureOT.propertyTypes).map((property) => {
154
- return [property.apiName, property.id];
155
- }));
156
- return {
157
- apiName: conjureOT.apiName,
158
- id: conjureOT.id,
159
- propertyIdToApiNameMapping,
160
- propertyApiNameToIdMapping,
161
- pk: {
162
- rid: pkRid,
163
- apiName: pkProperty.apiName,
164
- type: pkProperty.type
165
- }
166
- };
167
- }
168
-
169
- // src/objectSet/conjureUnionType.ts
170
- function conjureUnionType(type, value) {
171
- return {
172
- type,
173
- [type]: value
174
- };
175
- }
176
-
177
- // src/objectSet/toConjureObjectSet.ts
178
- function toConjureObjectSet(objectSet, objectPropertyMapping) {
179
- switch (objectSet.type) {
180
- case "base":
181
- return conjureUnionType("base", {
182
- objectTypeId: objectPropertyMapping.id
183
- });
184
- case "static":
185
- return conjureUnionType("static", {
186
- objectRids: objectSet.objects,
187
- provenance: void 0
188
- });
189
- case "reference":
190
- return conjureUnionType("referenced", {
191
- objectSetRid: objectSet.reference
192
- });
193
- case "filter":
194
- return conjureUnionType("filtered", {
195
- objectSet: toConjureObjectSet(objectSet.objectSet, objectPropertyMapping),
196
- runtimeDerivedProperties: void 0,
197
- filter: mapWhereClauseToObjectSetFilter(objectSet.where, objectPropertyMapping)
198
- });
199
- case "union":
200
- return conjureUnionType("unioned", {
201
- objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
202
- });
203
- case "intersect":
204
- return conjureUnionType("intersected", {
205
- objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
206
- });
207
- case "subtract":
208
- return conjureUnionType("subtracted", {
209
- objectSets: objectSet.objectSets.map((os) => toConjureObjectSet(os, objectPropertyMapping))
210
- });
211
- case "searchAround":
212
- throw new Error("not implemented");
213
- }
214
- }
215
- async function getObjectSetBaseType(objectSet) {
216
- switch (objectSet.type) {
217
- case "base":
218
- return objectSet.objectType;
219
- case "static":
220
- throw new Error("not implemented");
221
- case "reference":
222
- throw new Error("not implemented");
223
- case "filter":
224
- return getObjectSetBaseType(objectSet.objectSet);
225
- case "union":
226
- return getObjectSetBaseType(objectSet.objectSets[0]);
227
- case "intersect":
228
- return getObjectSetBaseType(objectSet.objectSets[0]);
229
- case "subtract":
230
- return getObjectSetBaseType(objectSet.objectSets[0]);
231
- case "searchAround":
232
- throw new Error("not implemented");
233
- }
234
- }
235
- function mapWhereClauseToObjectSetFilter(objectSetFilter, propertyMapping) {
236
- switch (objectSetFilter.type) {
237
- case "lt":
238
- return conjureUnionType("range", {
239
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
240
- lt: objectSetFilter.value,
241
- lte: void 0,
242
- gt: void 0,
243
- gte: void 0
244
- });
245
- case "gt":
246
- return conjureUnionType("range", {
247
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
248
- gt: objectSetFilter.value,
249
- lte: void 0,
250
- lt: void 0,
251
- gte: void 0
252
- });
253
- case "lte":
254
- return conjureUnionType("range", {
255
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
256
- lte: objectSetFilter.value,
257
- lt: void 0,
258
- gt: void 0,
259
- gte: void 0
260
- });
261
- case "gte":
262
- return conjureUnionType("range", {
263
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
264
- gte: objectSetFilter.value,
265
- lt: void 0,
266
- lte: void 0,
267
- gt: void 0
268
- });
269
- case "eq":
270
- return conjureUnionType("exactMatch", {
271
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field],
272
- terms: [objectSetFilter.value]
273
- });
274
- case "and":
275
- return conjureUnionType("and", {
276
- filters: objectSetFilter.value.map((filter) => mapWhereClauseToObjectSetFilter(filter, propertyMapping))
277
- });
278
- case "or":
279
- return conjureUnionType("or", {
280
- filters: objectSetFilter.value.map((filter) => mapWhereClauseToObjectSetFilter(filter, propertyMapping))
281
- });
282
- case "isNull":
283
- return conjureUnionType("not", {
284
- filter: {
285
- type: "hasProperty",
286
- hasProperty: {
287
- propertyId: propertyMapping.propertyApiNameToIdMapping[objectSetFilter.field]
288
- }
289
- }
290
- });
291
- case "not":
292
- return conjureUnionType("not", {
293
- filter: mapWhereClauseToObjectSetFilter(objectSetFilter.value, propertyMapping)
294
- });
295
- case "contains":
296
- case "startsWith":
297
- case "containsAllTermsInOrder":
298
- case "containsAnyTerm":
299
- case "containsAllTerms":
300
- case "withinDistanceOf":
301
- case "withinBoundingBox":
302
- case "intersectsBoundingBox":
303
- case "doesNotIntersectBoundingBox":
304
- case "withinPolygon":
305
- case "intersectsPolygon":
306
- case "doesNotIntersectPolygon":
307
- case "containsAllTermsInOrderPrefixLastTerm":
308
- throw new Error("not implemented");
309
- }
310
- }
311
-
312
- // src/objectSet/ObjectSetListenerWebsocket.ts
313
- var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
314
- var MINIMUM_RECONNECT_DELAY_MS = 5 * 1e3;
315
- function doNothing() {
316
- }
317
- function fillOutListener({
318
- onChange = doNothing,
319
- onError = doNothing,
320
- onOutOfDate = doNothing
321
- }) {
322
- return {
323
- onChange,
324
- onError,
325
- onOutOfDate
326
- };
327
- }
328
- function isReady(sub) {
329
- return sub.temporaryObjectSetId != null;
330
- }
331
- function subscriptionIsDone(sub) {
332
- return sub.status === "done" || sub.status === "error";
333
- }
334
- var ObjectSetListenerWebsocket = class _ObjectSetListenerWebsocket {
335
- static #instances = /* @__PURE__ */ new WeakMap();
336
- // FIXME
337
- static getInstance(client) {
338
- let instance = _ObjectSetListenerWebsocket.#instances.get(client.clientCacheKey);
339
- if (instance == null) {
340
- instance = new _ObjectSetListenerWebsocket(client);
341
- _ObjectSetListenerWebsocket.#instances.set(client.clientCacheKey, instance);
342
- }
343
- return instance;
344
- }
345
- #ws;
346
- #lastWsConnect = 0;
347
- #client;
348
- #logger;
349
- /**
350
- * map of requestId to all active subscriptions at the time of the request
351
- */
352
- #pendingSubscriptions = /* @__PURE__ */ new Map();
353
- /**
354
- * Map of subscriptionId to Subscription. Note: the subscriptionId may be
355
- * temporary and not the actual subscriptionId from the server.
356
- */
357
- #subscriptions = /* @__PURE__ */ new Map();
358
- #oswContext;
359
- #metadataContext;
360
- #ossContext;
361
- #maybeDisconnectTimeout;
362
- // DO NOT CONSTRUCT DIRECTLY. ONLY EXPOSED AS A TESTING SEAM
363
- constructor(client, {
364
- objectSetExpiryMs = ONE_DAY_MS,
365
- minimumReconnectDelayMs = MINIMUM_RECONNECT_DELAY_MS
366
- } = {}) {
367
- this.OBJECT_SET_EXPIRY_MS = objectSetExpiryMs;
368
- this.MINIMUM_RECONNECT_DELAY_MS = minimumReconnectDelayMs;
369
- this.#client = client;
370
- this.#logger = client.logger?.child({}, {
371
- msgPrefix: "<OSW> "
372
- });
373
- !(client.baseUrl.startsWith("https://") || client.baseUrl.startsWith("http://")) ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "Stack must be a URL") : invariant2__default.default(false) : void 0;
374
- this.#oswContext = {
375
- baseUrl: client.baseUrl,
376
- servicePath: "/object-set-watcher/api",
377
- fetchFn: client.fetch,
378
- tokenProvider: async () => await client.tokenProvider()
379
- };
380
- this.#ossContext = {
381
- ...this.#oswContext,
382
- servicePath: "/object-set-service/api"
383
- };
384
- this.#metadataContext = {
385
- ...this.#oswContext,
386
- servicePath: "/ontology-metadata/api"
387
- };
388
- }
389
- async subscribe(objectSet, listener) {
390
- {
391
- globalThis.crypto ??= (await import('crypto')).webcrypto;
392
- }
393
- const sub = {
394
- listener: fillOutListener(listener),
395
- objectSet,
396
- status: "preparing",
397
- // Since we don't have a real subscription id yet but we need to keep
398
- // track of this reference, we can just use a random uuid.
399
- subscriptionId: `TMP-${crypto.randomUUID()}`
400
- };
401
- this.#subscriptions.set(sub.subscriptionId, sub);
402
- this.#initiateSubscribe(sub);
403
- return () => {
404
- this.#unsubscribe(sub);
405
- };
406
- }
407
- /**
408
- * Called at least once for every subscription.
409
- *
410
- * - Resets pending expiry
411
- * - Recreates temporary object set
412
- * - Triggers a full subscribe message
413
- *
414
- * @returns
415
- */
416
- async #initiateSubscribe(sub) {
417
- if (process?.env?.NODE_ENV !== "production") {
418
- this.#logger?.trace("#initiateSubscribe()");
419
- }
420
- if (sub.expiry) {
421
- clearTimeout(sub.expiry);
422
- }
423
- sub.expiry = setTimeout(() => this.#expire(sub), this.OBJECT_SET_EXPIRY_MS);
424
- const ontologyRid = await this.#client.ontologyRid;
425
- try {
426
- const [temporaryObjectSet] = await Promise.all([
427
- // create a time-bounded object set representation for watching
428
- this.#createTemporaryObjectSet(sub.objectSet),
429
- this.#ensureWebsocket(),
430
- // look up the object type's rid and ensure that we have enabled object set watcher for that rid
431
- // TODO ???
432
- getObjectSetBaseType(sub.objectSet).then((baseType) => chunkXJRGYEPE_cjs.esm_exports.ObjectTypesV2.getObjectTypeV2(this.#client, ontologyRid, baseType)).then((objectType) => this.#enableObjectSetsWatcher([objectType.rid]))
433
- ]);
434
- if (subscriptionIsDone(sub)) {
435
- return;
436
- }
437
- sub.temporaryObjectSetId = temporaryObjectSet.objectSetRid;
438
- if (this.#ws?.readyState === WebSocket__default.default.OPEN) {
439
- this.#sendSubscribeMessage();
440
- }
441
- } catch (error) {
442
- this.#logger?.error(error, "Error in #initiateSubscribe");
443
- sub.listener.onError(error);
444
- }
445
- }
446
- #sendSubscribeMessage() {
447
- if (process?.env?.NODE_ENV !== "production") {
448
- this.#logger?.trace("#sendSubscribeMessage()");
449
- }
450
- const readySubs = [...this.#subscriptions.values()].filter(isReady);
451
- if (readySubs.length === 0) {
452
- if (process?.env?.NODE_ENV !== "production") {
453
- this.#logger?.trace("#sendSubscribeMessage(): aborting due to no ready subscriptions");
454
- }
455
- return;
456
- }
457
- const id = crypto.randomUUID();
458
- this.#pendingSubscriptions.set(id, readySubs);
459
- const subscribe = {
460
- id,
461
- requests: readySubs.map(({
462
- temporaryObjectSetId
463
- }) => ({
464
- objectSet: temporaryObjectSetId,
465
- objectSetContext: {
466
- objectSetFilterContext: {
467
- parameterOverrides: {}
468
- }
469
- },
470
- watchAllLinks: false
471
- }))
472
- };
473
- if (process?.env?.NODE_ENV !== "production") {
474
- this.#logger?.trace({
475
- payload: subscribe
476
- }, "sending subscribe message");
477
- }
478
- this.#ws?.send(JSON.stringify(subscribe));
479
- }
480
- #expire(sub) {
481
- if (process?.env?.NODE_ENV !== "production") {
482
- this.#logger?.trace({
483
- subscription: sub
484
- }, "#expire()");
485
- }
486
- sub.status = "expired";
487
- this.#initiateSubscribe(sub);
488
- }
489
- #unsubscribe(sub, newStatus = "done") {
490
- if (subscriptionIsDone(sub)) {
491
- return;
492
- }
493
- sub.status = newStatus;
494
- sub.listener = fillOutListener({});
495
- if (sub.expiry) {
496
- clearTimeout(sub.expiry);
497
- sub.expiry = void 0;
498
- }
499
- this.#subscriptions.delete(sub.subscriptionId);
500
- if (this.#maybeDisconnectTimeout) {
501
- clearTimeout(this.#maybeDisconnectTimeout);
502
- }
503
- this.#maybeDisconnectTimeout = setTimeout(
504
- () => {
505
- this.#maybeDisconnectTimeout = void 0;
506
- if (this.#subscriptions.size === 0) {
507
- this.#cycleWebsocket();
508
- }
509
- },
510
- 15e3
511
- /* ms */
512
- );
513
- }
514
- async #ensureWebsocket() {
515
- if (this.#ws == null) {
516
- const {
517
- baseUrl,
518
- tokenProvider
519
- } = this.#client;
520
- const base = new URL(baseUrl);
521
- const url = `wss://${base.host}/object-set-watcher/ws/subscriptions`;
522
- const token = await tokenProvider();
523
- if (this.#ws == null) {
524
- const nextConnectTime = (this.#lastWsConnect ?? 0) + this.MINIMUM_RECONNECT_DELAY_MS;
525
- if (nextConnectTime > Date.now()) {
526
- await new Promise((resolve) => {
527
- setTimeout(resolve, nextConnectTime - Date.now());
528
- });
529
- }
530
- this.#lastWsConnect = Date.now();
531
- if (this.#ws == null) {
532
- if (process?.env?.NODE_ENV !== "production") {
533
- this.#logger?.trace("Creating websocket");
534
- }
535
- this.#ws = new WebSocket__default.default(url, [`Bearer-${token}`]);
536
- this.#ws.addEventListener("close", this.#onClose);
537
- this.#ws.addEventListener("message", this.#onMessage);
538
- this.#ws.addEventListener("open", this.#onOpen);
539
- }
540
- }
541
- if (this.#ws.readyState === WebSocket__default.default.CONNECTING) {
542
- const ws = this.#ws;
543
- return new Promise((resolve, reject) => {
544
- function cleanup() {
545
- ws.removeEventListener("open", open);
546
- ws.removeEventListener("error", error);
547
- ws.removeEventListener("close", cleanup);
548
- }
549
- function open() {
550
- cleanup();
551
- resolve();
552
- }
553
- function error(evt) {
554
- cleanup();
555
- reject(evt);
556
- }
557
- ws.addEventListener("open", open);
558
- ws.addEventListener("error", error);
559
- ws.addEventListener("close", cleanup);
560
- });
561
- }
562
- }
563
- }
564
- #onOpen = () => {
565
- this.#sendSubscribeMessage();
566
- };
567
- #onMessage = async (message) => {
568
- const data = JSON.parse(message.data.toString());
569
- if (process?.env?.NODE_ENV !== "production") {
570
- this.#logger?.trace({
571
- payload: data
572
- }, "received message from ws");
573
- }
574
- switch (data.type) {
575
- case "objectSetChanged":
576
- return this.#handleMessage_objectSetChanged(data.objectSetChanged);
577
- case "refreshObjectSet":
578
- return this.#handleMessage_refreshObjectSet(data.refreshObjectSet);
579
- case "subscribeResponses":
580
- return this.#handleMessage_subscribeResponses(data.subscribeResponses);
581
- case "subscriptionClosed": {
582
- const payload = data.subscriptionClosed;
583
- return this.#handleMessage_subscriptionClosed(payload);
584
- }
585
- default:
586
- process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "Unexpected message type") : invariant2__default.default(false) ;
587
- }
588
- };
589
- #handleMessage_objectSetChanged = async (payload) => {
590
- const sub = this.#subscriptions.get(payload.id);
591
- !sub ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, `Expected subscription id ${payload.id}`) : invariant2__default.default(false) : void 0;
592
- if ("confidenceValue" in payload) {
593
- sub.listener.onOutOfDate();
594
- return;
595
- }
596
- const objects = payload.updates.filter(function(a) {
597
- return a.type === "object";
598
- }).map((a) => a.object);
599
- !(objects.length === payload.updates.length) ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "currently only support full updates not reference updates") : invariant2__default.default(false) : void 0;
600
- sub.listener.onChange(await convertFoundryToOsdkObjects(this.#client, this.#metadataContext, objects));
601
- };
602
- #handleMessage_refreshObjectSet = (payload) => {
603
- const sub = this.#subscriptions.get(payload.id);
604
- !sub ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, `Expected subscription id ${payload.id}`) : invariant2__default.default(false) : void 0;
605
- sub.listener.onOutOfDate();
606
- };
607
- #handleMessage_subscribeResponses = (payload) => {
608
- const {
609
- id,
610
- responses
611
- } = payload;
612
- const subs = this.#pendingSubscriptions.get(id);
613
- !subs ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, `should have a pending subscription for ${id}`) : invariant2__default.default(false) : void 0;
614
- this.#pendingSubscriptions.delete(id);
615
- for (let i = 0; i < responses.length; i++) {
616
- const sub = subs[i];
617
- const response = responses[i];
618
- switch (response.type) {
619
- case "error":
620
- sub.listener.onError(response.error);
621
- this.#unsubscribe(sub, "error");
622
- break;
623
- case "qos":
624
- this.#cycleWebsocket();
625
- break;
626
- case "success":
627
- const shouldFireOutOfDate = sub.status === "expired" || sub.status === "reconnecting";
628
- if (process?.env?.NODE_ENV !== "production") {
629
- this.#logger?.trace({
630
- shouldFireOutOfDate
631
- }, "success");
632
- }
633
- sub.status = "subscribed";
634
- if (sub.subscriptionId !== response.success.id) {
635
- this.#subscriptions.delete(sub.subscriptionId);
636
- sub.subscriptionId = response.success.id;
637
- this.#subscriptions.set(sub.subscriptionId, sub);
638
- }
639
- if (shouldFireOutOfDate) sub.listener.onOutOfDate();
640
- break;
641
- default:
642
- sub.listener.onError(response);
643
- }
644
- }
645
- };
646
- #handleMessage_subscriptionClosed(payload) {
647
- const sub = this.#subscriptions.get(payload.id);
648
- !sub ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, `Expected subscription id ${payload.id}`) : invariant2__default.default(false) : void 0;
649
- sub.listener.onError(payload.error);
650
- this.#unsubscribe(sub, "error");
651
- }
652
- #onClose = (event) => {
653
- if (process?.env?.NODE_ENV !== "production") {
654
- this.#logger?.trace({
655
- event
656
- }, "Received close event from ws", event);
657
- }
658
- this.#cycleWebsocket();
659
- };
660
- async #enableObjectSetsWatcher(objectTypeRids) {
661
- return client_unstable_osw.batchEnableWatcher(this.#oswContext, {
662
- requests: objectTypeRids
663
- });
664
- }
665
- async #createTemporaryObjectSet(objectSet) {
666
- const objectSetBaseType = await getObjectSetBaseType(objectSet);
667
- const mcc = await metadataCacheClient(this.#client);
668
- const objectInfo = await mcc.forObjectByApiName(objectSetBaseType);
669
- const propMapping = await objectInfo.getPropertyMapping();
670
- const temporaryObjectSet = await client_unstable.createTemporaryObjectSet(this.#ossContext, {
671
- objectSet: toConjureObjectSet(objectSet, propMapping),
672
- timeToLive: "ONE_DAY",
673
- // MUST keep in sync with the value for expiry in `#initiateSubscribe`.
674
- objectSetFilterContext: {
675
- parameterOverrides: {}
676
- }
677
- });
678
- return {
679
- objectSetRid: temporaryObjectSet.objectSetRid
680
- };
681
- }
682
- #cycleWebsocket = () => {
683
- if (this.#ws) {
684
- this.#ws.removeEventListener("open", this.#onOpen);
685
- this.#ws.removeEventListener("message", this.#onMessage);
686
- this.#ws.removeEventListener("close", this.#onClose);
687
- if (this.#ws.readyState !== WebSocket__default.default.CLOSING && this.#ws.readyState !== WebSocket__default.default.CLOSED) {
688
- this.#ws.close();
689
- }
690
- this.#ws = void 0;
691
- }
692
- if (this.#subscriptions.size > 0) {
693
- if (process?.env?.NODE_ENV !== "production") {
694
- for (const s of this.#subscriptions.values()) {
695
- !(s.status !== "done" && s.status !== "error") ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false, "should not have done/error subscriptions still") : invariant2__default.default(false) : void 0;
696
- }
697
- }
698
- for (const s of this.#subscriptions.values()) {
699
- if (s.status === "subscribed") s.status = "reconnecting";
700
- }
701
- this.#ensureWebsocket();
702
- }
703
- };
704
- };
705
- async function convertFoundryToOsdkObjects(client, ctx, objects) {
706
- const osdkObjects = await Promise.all(objects.map(async (object) => {
707
- const propertyMapping = await (await (await metadataCacheClient(client)).forObjectByRid(object.type)).getPropertyMapping();
708
- const convertedObject = Object.fromEntries([...Object.entries(object.properties).map(([key, value]) => {
709
- return [propertyMapping?.propertyIdToApiNameMapping[key], value];
710
- }), [propertyMapping?.propertyIdToApiNameMapping[Object.entries(object.key)[0][0]], Object.entries(object.key)[0][1]], ["__apiName", propertyMapping?.apiName], ["$apiName", propertyMapping?.apiName]]);
711
- return convertedObject;
712
- }));
713
- return await chunkXJRGYEPE_cjs.convertWireToOsdkObjects(client, osdkObjects, void 0);
714
- }
715
-
716
- // src/objectSet/createUnstableObjectSet.ts
717
- function UNSTABLE_createObjectSet(objectType, clientCtx, objectSet = {
718
- type: "base",
719
- objectType: objectType["apiName"]
720
- }) {
721
- return Object.assign(
722
- chunkXJRGYEPE_cjs.createObjectSet(objectType, clientCtx, objectSet),
723
- {
724
- subscribe(listener) {
725
- const pendingSubscribe = ObjectSetListenerWebsocket.getInstance(clientCtx).subscribe(objectSet, listener);
726
- return async () => (await pendingSubscribe)();
727
- }
728
- }
729
- // cast is needed because we are relying on the where clause doing the right thing via client.createObjectSet
730
- );
731
- }
732
-
733
- // src/pageRequestAsAsyncIter.ts
734
- function getResults(x) {
735
- return x.results;
736
- }
737
- function applyPageToken(payload, {
738
- pageToken
739
- }) {
740
- return pageToken ? {
741
- ...payload,
742
- pageToken
743
- } : void 0;
744
- }
745
- async function* pageRequestAsAsyncIter(call, values, nextArgs, initialPayload) {
746
- let payload = initialPayload;
747
- while (payload) {
748
- const r = await call(payload);
749
- for (const q of values(r)) {
750
- yield q;
751
- }
752
- payload = nextArgs(payload, r);
753
- }
754
- }
755
-
756
- // src/__unstable/createBulkLinksAsyncIterFactory.ts
757
- function createBulkLinksAsyncIterFactory(ctx) {
758
- return async function* (objs, linkTypes) {
759
- if (objs.length === 0) {
760
- return;
761
- }
762
- ctx.logger?.debug("Preparing to fetch bulk links");
763
- !objs.every((a) => a.$objectType === objs[0].$objectType) ? process.env.NODE_ENV !== "production" ? invariant2__default.default(false) : invariant2__default.default(false) : void 0;
764
- const mcc = await metadataCacheClient(ctx);
765
- const helper = await mcc.forObjectByApiName(objs[0].$objectType);
766
- const [objectTypeRid, propertyMapping, fullLinkMapping] = await Promise.all([helper.getRid(), helper.getPropertyMapping(), helper.getLinkMapping()]);
767
- const linkMapping = Object.fromEntries(Object.entries(fullLinkMapping).filter(([apiName]) => linkTypes.includes(apiName)));
768
- for (const linkType of linkTypes) {
769
- if (linkMapping[linkType] == null) {
770
- throw "Unable to find link type: " + linkType;
771
- }
772
- }
773
- const req = {
774
- objectSetContext: {
775
- forkRid: void 0,
776
- objectSetFilterContext: {
777
- parameterOverrides: {}
778
- },
779
- ontologyBranchRid: void 0,
780
- owningRid: void 0,
781
- reportUsage: void 0,
782
- workstateRid: void 0
783
- },
784
- responseOptions: {
785
- includeObjectSetEntities: true,
786
- includeUsageCost: false
787
- },
788
- pageSize: 1e3,
789
- pageToken: void 0,
790
- linksRequests: [{
791
- directedLinkTypes: Object.values(linkMapping).map(({
792
- directedLinkTypeRid
793
- }) => directedLinkTypeRid),
794
- objects: conjureUnionType("objects", objs.map((o) => conjureUnionType("objectLocatorV2", {
795
- objectTypeRid,
796
- objectPrimaryKey: {
797
- [propertyMapping.pk.rid]: conjureUnionType(propertyMapping.pk.type.type, o.$primaryKey)
798
- }
799
- })))
800
- }]
801
- };
802
- const bulkLinksIter = pageRequestAsAsyncIter(client_unstable.getBulkLinksPage.bind(void 0, makeConjureContext(ctx, "/object-set-service/api")), getResults, applyPageToken, req);
803
- for await (const item of bulkLinksIter) {
804
- const {
805
- objectIdentifier
806
- } = item;
807
- const obj = findObject(objectIdentifier, objs);
808
- for (const link of item.links) {
809
- const ref = link.link[link.linkSide === "SOURCE" ? "objectSideB" : "objectSideA"];
810
- const pk = getPrimaryKeyOrThrow(ref);
811
- const otherObjectApiName = await (await mcc.forObjectByRid(pk.objectTypeRid)).getApiName();
812
- const mappedLink = Object.values(linkMapping).find((a) => a.directedLinkTypeRid.linkTypeRid === link.link.linkTypeRid && a.directedLinkTypeRid.linkSide === link.linkSide);
813
- if (!mappedLink) throw new Error("Could not find link type");
814
- yield {
815
- object: obj,
816
- linkApiName: mappedLink.apiName,
817
- otherObjectApiName,
818
- otherObjectPk: pk.pkValue
819
- };
820
- }
821
- }
822
- };
823
- }
824
- function findObject(objectIdentifier, objs) {
825
- const {
826
- pkValue
827
- } = getPrimaryKeyOrThrow(objectIdentifier);
828
- const obj = objs.find((o) => o.$primaryKey === pkValue);
829
- if (obj == null) {
830
- throw new Error(`Needed to find object with pk ${pkValue}} and could not`);
831
- }
832
- return obj;
833
- }
834
- function getPrimaryKeyOrThrow(ref) {
835
- if ("type" in ref && ref.type !== "objectLocatorV2") {
836
- throw new Error("We do not support looking up object by rid");
837
- }
838
- const pks = Object.entries(ref.objectLocatorV2.objectPrimaryKey);
839
- if (pks.length !== 1) {
840
- throw new Error("Unable to support this request due to multiple pks");
841
- }
842
- return {
843
- objectTypeRid: ref.objectLocatorV2.objectTypeRid,
844
- pkValue: pks[0][1][pks[0][1].type]
845
- };
846
- }
847
-
848
- // src/__unstable/UNSTABLE_createClient.ts
849
- function UNSTABLE_createClient(...args) {
850
- const client = chunkXJRGYEPE_cjs.createClientInternal(UNSTABLE_createObjectSet, ...args);
851
- const unstableClient = Object.defineProperties(client, {
852
- __UNSTABLE_getBulkLinks: {
853
- get: () => createBulkLinksAsyncIterFactory(client[shared_client.symbolClientContext])
854
- },
855
- __UNSTABLE_preexistingObjectSet: {
856
- get: () => (definition, rid) => {
857
- return UNSTABLE_createObjectSet(definition, client[shared_client.symbolClientContext], {
858
- type: "intersect",
859
- objectSets: [{
860
- type: "base",
861
- objectType: definition.apiName
862
- }, {
863
- type: "reference",
864
- reference: rid
865
- }]
866
- });
867
- }
868
- }
869
- });
870
- return unstableClient;
871
- }
872
-
873
- Object.defineProperty(exports, "augment", {
874
- enumerable: true,
875
- get: function () { return chunkXJRGYEPE_cjs.augment; }
876
- });
877
- exports.createClient = UNSTABLE_createClient;
878
- //# sourceMappingURL=unstable-do-not-use.cjs.map
879
- //# sourceMappingURL=unstable-do-not-use.cjs.map