@salesforce/lds-network-nimbus 1.100.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,82 @@
1
+ Terms of Use
2
+
3
+ Copyright 2022 Salesforce, Inc. All rights reserved.
4
+
5
+ These Terms of Use govern the download, installation, and/or use of this
6
+ software provided by Salesforce, Inc. ("Salesforce") (the "Software"), were
7
+ last updated on April 15, 2022, and constitute a legally binding
8
+ agreement between you and Salesforce. If you do not agree to these Terms of
9
+ Use, do not install or use the Software.
10
+
11
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free
12
+ copyright license to reproduce, prepare derivative works of, publicly
13
+ display, publicly perform, sublicense, and distribute the Software and
14
+ derivative works subject to these Terms. These Terms shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ Subject to the limited rights expressly granted hereunder, Salesforce
18
+ reserves all rights, title, and interest in and to all intellectual
19
+ property subsisting in the Software. No rights are granted to you hereunder
20
+ other than as expressly set forth herein. Users residing in countries on
21
+ the United States Office of Foreign Assets Control sanction list, or which
22
+ are otherwise subject to a US export embargo, may not use the Software.
23
+
24
+ Implementation of the Software may require development work, for which you
25
+ are responsible. The Software may contain bugs, errors and
26
+ incompatibilities and is made available on an AS IS basis without support,
27
+ updates, or service level commitments.
28
+
29
+ Salesforce reserves the right at any time to modify, suspend, or
30
+ discontinue, the Software (or any part thereof) with or without notice. You
31
+ agree that Salesforce shall not be liable to you or to any third party for
32
+ any modification, suspension, or discontinuance.
33
+
34
+ You agree to defend Salesforce against any claim, demand, suit or
35
+ proceeding made or brought against Salesforce by a third party arising out
36
+ of or accruing from (a) your use of the Software, and (b) any application
37
+ you develop with the Software that infringes any copyright, trademark,
38
+ trade secret, trade dress, patent, or other intellectual property right of
39
+ any person or defames any person or violates their rights of publicity or
40
+ privacy (each a "Claim Against Salesforce"), and will indemnify Salesforce
41
+ from any damages, attorney fees, and costs finally awarded against
42
+ Salesforce as a result of, or for any amounts paid by Salesforce under a
43
+ settlement approved by you in writing of, a Claim Against Salesforce,
44
+ provided Salesforce (x) promptly gives you written notice of the Claim
45
+ Against Salesforce, (y) gives you sole control of the defense and
46
+ settlement of the Claim Against Salesforce (except that you may not settle
47
+ any Claim Against Salesforce unless it unconditionally releases Salesforce
48
+ of all liability), and (z) gives you all reasonable assistance, at your
49
+ expense.
50
+
51
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT
52
+ SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES,
54
+ INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
55
+ PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA,
56
+ OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN
57
+ CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU
58
+ HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
59
+
60
+ These Terms of Use shall be governed exclusively by the internal laws of
61
+ the State of California, without regard to its conflicts of laws
62
+ rules. Each party hereby consents to the exclusive jurisdiction of the
63
+ state and federal courts located in San Francisco County, California to
64
+ adjudicate any dispute arising out of or relating to these Terms of Use and
65
+ the download, installation, and/or use of the Software. Except as expressly
66
+ stated herein, these Terms of Use constitute the entire agreement between
67
+ the parties, and supersede all prior and contemporaneous agreements,
68
+ proposals, or representations, written or oral, concerning their subject
69
+ matter. No modification, amendment, or waiver of any provision of these
70
+ Terms of Use shall be effective unless it is by an update to these Terms of
71
+ Use that Salesforce makes available, or is in writing and signed by the
72
+ party against whom the modification, amendment, or waiver is to be
73
+ asserted.
74
+
75
+ Data Privacy: Salesforce may collect, process, and store device,
76
+ system, and other information related to your use of the Software. This
77
+ information includes, but is not limited to, IP address, user metrics, and
78
+ other data ("Usage Data"). Salesforce may use Usage Data for analytics,
79
+ product development, and marketing purposes. You acknowledge that files
80
+ generated in conjunction with the Software may contain sensitive or
81
+ confidential data, and you are solely responsible for anonymizing and
82
+ protecting such data.
package/dist/main.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { NimbusNetworkAdapter } from './network/NimbusNetworkAdapter';
2
+ export { makeNetworkAdapterChunkRecordFields } from './network/record-field-batching/makeNetworkAdapterChunkRecordFields';
3
+ export { CompositeResponseEnvelope } from './network/record-field-batching/utils';
package/dist/main.js ADDED
@@ -0,0 +1,782 @@
1
+ /**
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ import { idleDetector } from 'o11y/client';
8
+ import { HttpStatusCode } from '@luvio/engine';
9
+
10
+ const { keys, create, assign, entries } = Object;
11
+ const { stringify, parse } = JSON;
12
+ const { push, join, slice } = Array.prototype;
13
+ const { isArray, from } = Array;
14
+
15
+ function ldsParamsToString(params) {
16
+ const returnParams = create(null);
17
+ const keys$1 = keys(params);
18
+ for (let i = 0, len = keys$1.length; i < len; i++) {
19
+ const key = keys$1[i];
20
+ const value = params[key];
21
+ if (value === undefined) {
22
+ // filter out params that have no value
23
+ continue;
24
+ }
25
+ if (isArray(value)) {
26
+ // filter out empty arrays
27
+ if (value.length > 0) {
28
+ returnParams[key] = value.join(',');
29
+ }
30
+ }
31
+ else {
32
+ returnParams[key] = `${value}`;
33
+ }
34
+ if (isObject(value) === true && keys(value).length > 0) {
35
+ returnParams[key] = stringify(value);
36
+ }
37
+ }
38
+ return returnParams;
39
+ }
40
+ function statusTextFromStatusCode(status) {
41
+ switch (status) {
42
+ case HttpStatusCode.Ok:
43
+ return 'OK';
44
+ case HttpStatusCode.NotModified:
45
+ return 'Not Modified';
46
+ case HttpStatusCode.NotFound:
47
+ return 'Not Found';
48
+ case HttpStatusCode.BadRequest:
49
+ return 'Bad Request';
50
+ case HttpStatusCode.ServerError:
51
+ return 'Server Error';
52
+ default:
53
+ return `Unexpected HTTP Status Code: ${status}`;
54
+ }
55
+ }
56
+ function methodFromResourceRequestMethod(method) {
57
+ switch (method.toLowerCase()) {
58
+ case 'get':
59
+ return 'GET';
60
+ case 'put':
61
+ return 'PUT';
62
+ case 'post':
63
+ return 'POST';
64
+ case 'delete':
65
+ return 'DELETE';
66
+ case 'patch':
67
+ return 'PATCH';
68
+ default:
69
+ throw Error(`Unexpected method ${method}`);
70
+ }
71
+ }
72
+ function priorityFromResourceRequest(request) {
73
+ switch (request.priority) {
74
+ case 'background':
75
+ return 'background';
76
+ case 'high':
77
+ return 'high';
78
+ case 'normal':
79
+ default:
80
+ return 'normal';
81
+ }
82
+ }
83
+ function isStatusOk(status) {
84
+ return status >= 200 && status <= 299;
85
+ }
86
+ // adapted from adapter-utils untrustedIsObject
87
+ function isObject(value) {
88
+ return typeof value === 'object' && value !== null && isArray(value) === false;
89
+ }
90
+ function stringifyIfPresent(value) {
91
+ if (value === undefined || value === null) {
92
+ return null;
93
+ }
94
+ return stringify(value);
95
+ }
96
+ function parseIfPresent(value) {
97
+ if (value === undefined || value === null || value === '') {
98
+ return null;
99
+ }
100
+ return parse(value);
101
+ }
102
+ function buildNimbusNetworkPluginRequest(resourceRequest, resourceRequestContext) {
103
+ const { basePath, baseUri, method, headers, queryParams, body } = resourceRequest;
104
+ let observabilityContext = null;
105
+ if (resourceRequestContext !== undefined &&
106
+ resourceRequestContext.requestCorrelator !== undefined &&
107
+ resourceRequestContext.requestCorrelator.observabilityContext !==
108
+ undefined) {
109
+ ({ observabilityContext = null } =
110
+ resourceRequestContext.requestCorrelator);
111
+ }
112
+ return {
113
+ method: methodFromResourceRequestMethod(method),
114
+ body: stringifyIfPresent(body),
115
+ headers,
116
+ queryParams: ldsParamsToString(queryParams),
117
+ path: `${baseUri}${basePath}`,
118
+ priority: priorityFromResourceRequest(resourceRequest),
119
+ observabilityContext,
120
+ };
121
+ }
122
+ function buildLdsResponse(response) {
123
+ const { body: responseBody, headers, status } = response;
124
+ const statusText = statusTextFromStatusCode(status);
125
+ return {
126
+ statusText,
127
+ status,
128
+ body: parseIfPresent(responseBody),
129
+ headers,
130
+ ok: isStatusOk(status),
131
+ };
132
+ }
133
+
134
+ // so eslint doesn't complain about nimbus
135
+ const tasker = idleDetector.declareNotifierTaskMulti('NimbusNetworkAdapter');
136
+ const NimbusNetworkAdapter = (request, resourceRequestContext) => {
137
+ tasker.add();
138
+ return new Promise((resolve, reject) => {
139
+ try {
140
+ __nimbus.plugins.LdsNetworkAdapter.sendRequest(buildNimbusNetworkPluginRequest(request, resourceRequestContext), (response) => {
141
+ try {
142
+ resolve(buildLdsResponse(response));
143
+ }
144
+ catch (error) {
145
+ // don't leave promise hanging, catch any errors (eg: if native side
146
+ // returns malformed response) and call reject
147
+ reject(error);
148
+ }
149
+ }, (error) => {
150
+ reject(new Error(`type: ${error.type}, message: ${error.message}`));
151
+ });
152
+ }
153
+ catch (error) {
154
+ // don't leave promise hanging, catch any errors (eg: if native side
155
+ // fails to parse the request), and call reject
156
+ reject(error);
157
+ }
158
+ }).finally(() => tasker.done());
159
+ };
160
+
161
+ /**
162
+ * related-list-records/batch fields and optional fields could be like below.
163
+ * /ui-api/related-list-records/batch/001R0000006l1xKIAQ/Contacts,Opportunities?
164
+ * optionalFields=Contacts:Contact.Id,Contact.Name;Opportunities:Opportunity.Id
165
+ *
166
+ * the pattern is [{relativeListId}:{[fields]};{relativeListId}:{[fields]}]
167
+ */
168
+ const SEPARATOR_BETWEEN_SCOPES = ';';
169
+ const SEPARATOR_BETWEEN_SCOPE_AND_FIELDS = ':';
170
+ const SEPARATOR_BETWEEN_FIELDS = ',';
171
+ const UNSCOPED_IDENTIFIER = 'unscoped';
172
+ class ScopedFields {
173
+ constructor(scope, fields) {
174
+ this.fields = {};
175
+ this.scope = scope;
176
+ for (let i = 0, len = fields.length; i < len; i += 1) {
177
+ this.fields[fields[i]] = true;
178
+ }
179
+ }
180
+ isUnScoped() {
181
+ return this.scope === UNSCOPED_IDENTIFIER;
182
+ }
183
+ addField(field) {
184
+ this.fields[field] = true;
185
+ }
186
+ addFields(fields) {
187
+ fields.forEach(this.addField, this);
188
+ }
189
+ toQueryParameterValue() {
190
+ const joinedFields = join.call(Object.keys(this.fields), SEPARATOR_BETWEEN_FIELDS);
191
+ return this.isUnScoped()
192
+ ? joinedFields
193
+ : join.call([this.scope, joinedFields], SEPARATOR_BETWEEN_SCOPE_AND_FIELDS);
194
+ }
195
+ toQueryParams() {
196
+ return this.isUnScoped() ? Object.keys(this.fields) : this.toQueryParameterValue();
197
+ }
198
+ /**
199
+ * parse Contacts:Contact.Id,Contact.Name into a QueryFields
200
+ */
201
+ static fromQueryParameterValue(paramValue) {
202
+ if (paramValue === null || paramValue === '')
203
+ return;
204
+ const scopeToFields = paramValue.split(SEPARATOR_BETWEEN_SCOPE_AND_FIELDS);
205
+ if (scopeToFields.length === 1) {
206
+ //unscoped
207
+ return new ScopedFields(UNSCOPED_IDENTIFIER, scopeToFields[0].split(SEPARATOR_BETWEEN_FIELDS));
208
+ }
209
+ else if (scopeToFields.length === 2) {
210
+ const scope = scopeToFields[0];
211
+ const fields = scopeToFields[1];
212
+ if (scope === undefined || fields === null)
213
+ return;
214
+ return new ScopedFields(scope, fields.split(SEPARATOR_BETWEEN_FIELDS));
215
+ }
216
+ else {
217
+ return;
218
+ }
219
+ }
220
+ }
221
+ class ScopedFieldsCollection {
222
+ constructor() {
223
+ this.listIdToFieldsMap = {};
224
+ }
225
+ /**
226
+ * merge the from ScopedFieldsCollection into current one
227
+ * @param from
228
+ */
229
+ merge(from) {
230
+ const { listIdToFieldsMap } = from;
231
+ const scopes = Object.keys(listIdToFieldsMap);
232
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
233
+ const scope = scopes[i];
234
+ const scopedFields = listIdToFieldsMap[scope];
235
+ const existingScopedFields = this.listIdToFieldsMap[scope];
236
+ if (existingScopedFields) {
237
+ existingScopedFields.addFields(Object.keys(scopedFields.fields));
238
+ }
239
+ else {
240
+ this.listIdToFieldsMap[scope] = scopedFields;
241
+ }
242
+ }
243
+ }
244
+ toQueryParams() {
245
+ return this.countOfUnScoped() > 0
246
+ ? this.listIdToFieldsMap[UNSCOPED_IDENTIFIER].toQueryParams()
247
+ : this.toQueryParameterValue();
248
+ }
249
+ /**
250
+ * convert to query parameter value
251
+ * @returns
252
+ */
253
+ toQueryParameterValue() {
254
+ let result = [];
255
+ const scopes = Object.keys(this.listIdToFieldsMap);
256
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
257
+ const chunk = this.listIdToFieldsMap[scopes[i]].toQueryParameterValue();
258
+ if (chunk !== undefined)
259
+ result.push(chunk);
260
+ }
261
+ return join.call(result, SEPARATOR_BETWEEN_SCOPES);
262
+ }
263
+ /**
264
+ * split the ScopedFields into multiple ScopedFields
265
+ * which there max fields list length will not exceeded the specified maxLength
266
+ * @param maxLength
267
+ */
268
+ split(maxLength = MAX_STRING_LENGTH_PER_CHUNK) {
269
+ const size = this.size();
270
+ if (size > maxLength) {
271
+ const fieldsArray = [];
272
+ const scopes = Object.keys(this.listIdToFieldsMap);
273
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
274
+ const { scope, fields } = this.listIdToFieldsMap[scopes[i]];
275
+ Object.keys(fields).forEach((field) => {
276
+ fieldsArray.push([scope, field]);
277
+ });
278
+ }
279
+ // Formula: # of fields per chunk = floor( max length per chunk / avg field length)
280
+ const averageFieldStringLength = size / fieldsArray.length;
281
+ const fieldsPerChunk = Math.floor(maxLength / averageFieldStringLength);
282
+ let j = fieldsPerChunk;
283
+ let result = [];
284
+ let current = null;
285
+ for (let i = 0, len = fieldsArray.length; i < len; i += 1) {
286
+ const scope = fieldsArray[i][0];
287
+ const field = fieldsArray[i][1];
288
+ if (current === null || !current.listIdToFieldsMap[scope]) {
289
+ j = fieldsPerChunk;
290
+ current = new ScopedFieldsCollection();
291
+ current.listIdToFieldsMap[scope] = new ScopedFields(scope, [field]);
292
+ result.push(current);
293
+ }
294
+ else {
295
+ current.listIdToFieldsMap[scope].addField(field);
296
+ }
297
+ j--;
298
+ if (j === 0) {
299
+ current = null;
300
+ }
301
+ }
302
+ return result;
303
+ }
304
+ else if (size > 0) {
305
+ return [this];
306
+ }
307
+ else {
308
+ return [];
309
+ }
310
+ }
311
+ size() {
312
+ return this.toQueryParameterValue().length;
313
+ }
314
+ countOfUnScoped() {
315
+ let count = 0;
316
+ const fieldsArray = Object.values(this.listIdToFieldsMap);
317
+ for (let i = 0, len = fieldsArray.length; i < len; i += 1) {
318
+ if (fieldsArray[i].isUnScoped()) {
319
+ count++;
320
+ }
321
+ }
322
+ return count;
323
+ }
324
+ countOfScoped() {
325
+ return Object.keys.length - this.countOfUnScoped();
326
+ }
327
+ isUnScopedMixedWithScoped() {
328
+ return this.countOfUnScoped() > 0 && this.countOfScoped() > 0;
329
+ }
330
+ /**
331
+ *
332
+ * @param paramValue like Contacts:Contact.Id,Contact.Name;Opportunities:Opportunity.Id
333
+ * @returns
334
+ */
335
+ static fromQueryParameterValue(paramValue) {
336
+ const result = new ScopedFieldsCollection();
337
+ if (paramValue) {
338
+ const relativeListChunks = paramValue.split(SEPARATOR_BETWEEN_SCOPES);
339
+ if (relativeListChunks.length === 0)
340
+ return result;
341
+ for (let i = 0, len = relativeListChunks.length; i < len; i += 1) {
342
+ const parsed = ScopedFields.fromQueryParameterValue(relativeListChunks[i]);
343
+ if (parsed) {
344
+ result.listIdToFieldsMap[parsed.scope] = parsed;
345
+ }
346
+ }
347
+ if (result.isUnScopedMixedWithScoped()) {
348
+ throw Error('mixing scoped and unscoped field list is not allowed.');
349
+ }
350
+ }
351
+ return result;
352
+ }
353
+ }
354
+
355
+ const MAX_STRING_LENGTH_PER_CHUNK = 10000;
356
+ const PARSE_ERROR = 'PARSE_AGGREGATE_UI_RESPONSE_ERROR';
357
+ function isErrorResponse(response) {
358
+ return response.httpStatusCode >= 400;
359
+ }
360
+ /**
361
+ * merge the aggregate ui child responses into a single object representation
362
+ * @param response
363
+ * @param mergeFunc the function used to define how the records should be merged together
364
+ * @returns the merged record
365
+ */
366
+ function mergeAggregateUiResponse(response, mergeFunc) {
367
+ const { body } = response;
368
+ try {
369
+ if (body === null ||
370
+ body === undefined ||
371
+ body.compositeResponse === undefined ||
372
+ body.compositeResponse.length === 0) {
373
+ // We shouldn't even get into this state - a 200 with no body?
374
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
375
+ throw new Error('No response body in executeAggregateUi found');
376
+ }
377
+ // if the body has any non-2xx statuses then that's an error and we return
378
+ // the network response with that error
379
+ const error = body.compositeResponse.find(isErrorResponse);
380
+ if (error !== undefined) {
381
+ const { httpStatusCode, body: errorBody } = error;
382
+ const statusText = errorBody.length > 0 ? errorBody[0].errorCode : '';
383
+ return {
384
+ ...response,
385
+ ok: false,
386
+ status: httpStatusCode,
387
+ statusText,
388
+ body: errorBody,
389
+ };
390
+ }
391
+ // if we got here there are no errors in body, cast as such
392
+ const responses = body.compositeResponse;
393
+ const merged = responses.reduce((seed, resp) => {
394
+ if (seed === null) {
395
+ return resp.body;
396
+ }
397
+ return mergeFunc(seed, resp.body);
398
+ }, null);
399
+ return {
400
+ ...response,
401
+ body: merged,
402
+ };
403
+ }
404
+ catch (error) {
405
+ return {
406
+ ...response,
407
+ ok: false,
408
+ status: HttpStatusCode.ServerError,
409
+ statusText: PARSE_ERROR,
410
+ body: [
411
+ {
412
+ errorCode: PARSE_ERROR,
413
+ message: error.toString(),
414
+ },
415
+ ],
416
+ };
417
+ }
418
+ }
419
+ function buildAggregateUiUrl(params, resourceRequest) {
420
+ const { fields, optionalFields } = params;
421
+ const mergedParams = {
422
+ ...resourceRequest.queryParams,
423
+ fields,
424
+ optionalFields,
425
+ };
426
+ const queryString = [];
427
+ for (const [key, value] of entries(mergedParams)) {
428
+ if (value !== undefined) {
429
+ queryString.push(`${key}=${isArray(value) ? value.join(',') : value}`);
430
+ }
431
+ }
432
+ return `${resourceRequest.baseUri}${resourceRequest.basePath}?${join.call(queryString, '&')}`;
433
+ }
434
+ function shouldUseAggregateUiForFields(fieldsArray, optionalFieldsArray) {
435
+ return fieldsArray.length + optionalFieldsArray.length >= MAX_STRING_LENGTH_PER_CHUNK;
436
+ }
437
+ function isSpanningRecord(fieldValue) {
438
+ return fieldValue !== null && typeof fieldValue === 'object';
439
+ }
440
+ function mergeRecordFields(first, second) {
441
+ const { fields: targetFields } = first;
442
+ const { fields: sourceFields } = second;
443
+ const fieldNames = keys(sourceFields);
444
+ for (let i = 0, len = fieldNames.length; i < len; i += 1) {
445
+ const fieldName = fieldNames[i];
446
+ const sourceField = sourceFields[fieldName];
447
+ const targetField = targetFields[fieldName];
448
+ if (isSpanningRecord(sourceField.value)) {
449
+ if (targetField === undefined) {
450
+ targetFields[fieldName] = sourceField;
451
+ continue;
452
+ }
453
+ mergeRecordFields(targetField.value, sourceField.value);
454
+ continue;
455
+ }
456
+ targetFields[fieldName] = sourceField;
457
+ }
458
+ return first;
459
+ }
460
+ function mergeBatchRecordsFields(first, second, collectionMergeFunc) {
461
+ const { results: targetResults } = first;
462
+ const { results: sourceResults } = second;
463
+ for (let i = 0, len = targetResults.length; i < len; i += 1) {
464
+ const targetResult = targetResults[i];
465
+ const sourceResult = sourceResults[i];
466
+ if (targetResult.statusCode !== HttpStatusCode.Ok)
467
+ continue;
468
+ if (sourceResult.statusCode !== HttpStatusCode.Ok) {
469
+ targetResults[i] = sourceResult;
470
+ continue;
471
+ }
472
+ collectionMergeFunc(targetResult.result, sourceResult.result);
473
+ }
474
+ return first;
475
+ }
476
+ /**
477
+ * Check to see if we have fields that are > max allowed characters long
478
+ * @param resourceRequest resource request to check
479
+ * @param endpoint Regular Expression to check the endpoint to aggregate
480
+ * @returns undefined if we should not aggregate. object if we should.
481
+ */
482
+ function createAggregateBatchRequestInfo(resourceRequest, endpoint) {
483
+ // only handle GETs on the given endpoint regex
484
+ if (!isGetRequestForEndpoint(endpoint, resourceRequest)) {
485
+ return undefined;
486
+ }
487
+ const { queryParams: { fields, optionalFields }, } = resourceRequest;
488
+ // only handle requests with fields or optional fields
489
+ if (fields === undefined && optionalFields === undefined) {
490
+ return undefined;
491
+ }
492
+ const fieldsArray = arrayOrEmpty(fields);
493
+ const optionalFieldsArray = arrayOrEmpty(optionalFields);
494
+ // if fields and optional fields are empty delegate request
495
+ if (fieldsArray.length === 0 && optionalFieldsArray.length === 0) {
496
+ return undefined;
497
+ }
498
+ const fieldsString = fieldsArray.join(',');
499
+ const optionalFieldsString = optionalFieldsArray.join(',');
500
+ const shouldUseAggregate = shouldUseAggregateUiForFields(fieldsString, optionalFieldsString);
501
+ if (!shouldUseAggregate) {
502
+ return undefined;
503
+ }
504
+ const fieldCollection = ScopedFieldsCollection.fromQueryParameterValue(fieldsString).split(MAX_STRING_LENGTH_PER_CHUNK);
505
+ const optionalFieldCollection = ScopedFieldsCollection.fromQueryParameterValue(optionalFieldsString).split(MAX_STRING_LENGTH_PER_CHUNK);
506
+ return {
507
+ fieldCollection,
508
+ optionalFieldCollection,
509
+ };
510
+ }
511
+ function createAggregateUiRequest(resourceRequest, compositeRequest) {
512
+ const aggregateUiPostBody = { compositeRequest };
513
+ const aggregateResourceRequest = {
514
+ method: 'post',
515
+ baseUri: resourceRequest.baseUri,
516
+ basePath: '/ui-api/aggregate-ui',
517
+ body: aggregateUiPostBody,
518
+ priority: resourceRequest.priority,
519
+ queryParams: {},
520
+ headers: {},
521
+ urlParams: {},
522
+ };
523
+ return aggregateResourceRequest;
524
+ }
525
+ function buildCompositeRequestByFields(referenceId, resourceRequest, recordsCompositeRequest) {
526
+ const { fieldCollection, optionalFieldCollection } = recordsCompositeRequest;
527
+ const compositeRequest = [];
528
+ if (fieldCollection !== undefined) {
529
+ for (let i = 0, len = fieldCollection.length; i < len; i += 1) {
530
+ const fieldChunk = fieldCollection[i].toQueryParams();
531
+ if (fieldChunk.length === 0) {
532
+ continue;
533
+ }
534
+ const url = buildAggregateUiUrl({
535
+ fields: fieldChunk,
536
+ }, resourceRequest);
537
+ push.call(compositeRequest, {
538
+ url,
539
+ referenceId: `${referenceId}_fields_${i}`,
540
+ });
541
+ }
542
+ }
543
+ if (optionalFieldCollection !== undefined) {
544
+ for (let i = 0, len = optionalFieldCollection.length; i < len; i += 1) {
545
+ const fieldChunk = optionalFieldCollection[i].toQueryParams();
546
+ if (fieldChunk.length === 0) {
547
+ continue;
548
+ }
549
+ const url = buildAggregateUiUrl({
550
+ optionalFields: fieldChunk,
551
+ }, resourceRequest);
552
+ push.call(compositeRequest, {
553
+ url,
554
+ referenceId: `${referenceId}_optionalFields_${i}`,
555
+ });
556
+ }
557
+ }
558
+ return compositeRequest;
559
+ }
560
+ /**
561
+ * Checks if a resource request is a GET method on the given endpoint
562
+ * @param endpoint Regular Expression of the endpoint
563
+ * @param request the resource request
564
+ */
565
+ function isGetRequestForEndpoint(endpoint, request) {
566
+ const { basePath, method } = request;
567
+ return endpoint.test(basePath) && method === 'get';
568
+ }
569
+ /**
570
+ * Checks if any is an array and returns it as an array.
571
+ * if not an array it returns an empty array.
572
+ * @param array the item to check is an array
573
+ * @returns the array or an empty array
574
+ */
575
+ function arrayOrEmpty(array) {
576
+ return array !== undefined && isArray(array) ? array : [];
577
+ }
578
+
579
+ const RECORD_ENDPOINT_REGEX = /^\/ui-api\/records\/?(([a-zA-Z0-9]+))?$/;
580
+ const referenceId$3 = 'LDS_Records_AggregateUi';
581
+ /**
582
+ * Export to facilitate unit tests
583
+ * Merge the second getRecord result into the first one.
584
+ * If any is error response, merged result is error response.
585
+ * If both are sucesses, due to they are from same records,
586
+ * fields sub node will be merged recursively
587
+ */
588
+ function mergeGetRecordResult(first, second) {
589
+ // return the error if first is error.
590
+ if (isArray(first) && !isArray(second))
591
+ return first;
592
+ // return the error if second is error.
593
+ if (!isArray(first) && isArray(second))
594
+ return second;
595
+ // concat the error array if both are error
596
+ if (isArray(first) && isArray(second)) {
597
+ return [...first, ...second];
598
+ }
599
+ mergeRecordFields(first, second);
600
+ return first;
601
+ }
602
+ function makeNetworkChunkFieldsGetRecord(networkAdapter) {
603
+ return (resourceRequest, resourceRequestContext) => {
604
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RECORD_ENDPOINT_REGEX);
605
+ if (batchRequestInfo === undefined) {
606
+ return networkAdapter(resourceRequest, resourceRequestContext);
607
+ }
608
+ const compositeRequest = buildCompositeRequestByFields(referenceId$3, resourceRequest, batchRequestInfo);
609
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
610
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
611
+ return mergeAggregateUiResponse(response, mergeGetRecordResult);
612
+ });
613
+ };
614
+ }
615
+
616
+ const RECORDS_BATCH_ENDPOINT_REGEX = /^\/ui-api\/records\/batch\/?(([a-zA-Z0-9|,]+))?$/;
617
+ const referenceId$2 = 'LDS_Records_Batch_AggregateUi';
618
+ function makeNetworkChunkFieldsGetRecordsBatch(networkAdapter) {
619
+ return (resourceRequest, resourceRequestContext) => {
620
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RECORDS_BATCH_ENDPOINT_REGEX);
621
+ if (batchRequestInfo === undefined) {
622
+ return networkAdapter(resourceRequest, resourceRequestContext);
623
+ }
624
+ const compositeRequest = buildCompositeRequestByFields(referenceId$2, resourceRequest, batchRequestInfo);
625
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
626
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
627
+ return mergeAggregateUiResponse(response, (first, second) => {
628
+ return mergeBatchRecordsFields(first, second, (a, b) => {
629
+ return mergeRecordFields(a, b);
630
+ });
631
+ });
632
+ });
633
+ };
634
+ }
635
+
636
+ const RELATED_LIST_RECORDS_ENDPOINT_REGEX = /^\/ui-api\/related-list-records\/?(([a-zA-Z0-9]+))?\/?(([a-zA-Z0-9]+))?$/;
637
+ const referenceId$1 = 'LDS_Related_List_Records_AggregateUi';
638
+ const QUERY_KEY_FIELDS = 'fields';
639
+ const QUERY_KEY_OPTIONAL_FIELDS = 'optionalFields';
640
+ /**
641
+ * Merge the second related list record collection into first one and return it.
642
+ * It checks both collections should have exaction same records, otherwise error.
643
+ * Exports it for unit tests
644
+ */
645
+ function mergeRelatedRecordsFields(first, second) {
646
+ const { records: targetRecords } = first;
647
+ const { records: sourceRecords } = second;
648
+ if (sourceRecords.length === targetRecords.length &&
649
+ recordIdsAllMatch(targetRecords, sourceRecords)) {
650
+ first.fields = first.fields.concat(second.fields);
651
+ first.optionalFields = first.optionalFields.concat(second.optionalFields);
652
+ for (let i = 0, len = sourceRecords.length; i < len; i += 1) {
653
+ const targetRecord = targetRecords[i];
654
+ const sourceRecord = sourceRecords[i];
655
+ mergeRecordFields(targetRecord, sourceRecord);
656
+ }
657
+ mergePageUrls(first, second);
658
+ return first;
659
+ }
660
+ else {
661
+ // Throw error due to two collection are about different set of records
662
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
663
+ throw new Error('Aggregate UI response is invalid');
664
+ }
665
+ }
666
+ function makeNetworkChunkFieldsGetRelatedListRecords(networkAdapter) {
667
+ return (resourceRequest, resourceRequestContext) => {
668
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RELATED_LIST_RECORDS_ENDPOINT_REGEX);
669
+ if (batchRequestInfo === undefined) {
670
+ return networkAdapter(resourceRequest, resourceRequestContext);
671
+ }
672
+ const compositeRequest = buildCompositeRequestByFields(referenceId$1, resourceRequest, batchRequestInfo);
673
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
674
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
675
+ return mergeAggregateUiResponse(response, mergeRelatedRecordsFields);
676
+ });
677
+ };
678
+ }
679
+ /**
680
+ * merge the second related list record collection into first one and return it
681
+ */
682
+ function mergePageUrls(first, second) {
683
+ first.currentPageUrl = mergeUrl(first.currentPageUrl, second.currentPageUrl);
684
+ first.previousPageUrl = mergeUrl(first.previousPageUrl, second.previousPageUrl);
685
+ first.nextPageUrl = mergeUrl(first.nextPageUrl, second.nextPageUrl);
686
+ }
687
+ /**
688
+ * merge to paging url with different set of fields or optional fields as combined one
689
+ * the paging url is like
690
+ * /services/data/v58.0/ui-api/related-list-records/001R0000006l1xKIAQ/Contacts
691
+ * ?fields=Id%2CName&optionalFields=Contact.Id%2CContact.Name&pageSize=50&pageToken=0
692
+ * @param path1 url path and query parmeter without domain
693
+ * @param path2 url path and query parmeter without domain
694
+ *
695
+ * Export to unit test
696
+ */
697
+ function mergeUrl(path1, path2) {
698
+ if (path1 === null)
699
+ return path2;
700
+ if (path2 === null)
701
+ return path1;
702
+ // new Url(...) need the path1, path2 to be prefix-ed with this fake domain
703
+ const domain = 'http://c.com';
704
+ const url1 = new URL(domain + path1);
705
+ const url2 = new URL(domain + path2);
706
+ const searchParams1 = url1.searchParams;
707
+ const fields = mergeFields(url1, url2, QUERY_KEY_FIELDS);
708
+ if (fields && searchParams1.get(QUERY_KEY_FIELDS) !== fields) {
709
+ searchParams1.set(QUERY_KEY_FIELDS, fields);
710
+ }
711
+ const optionalFields = mergeFields(url1, url2, QUERY_KEY_OPTIONAL_FIELDS);
712
+ if (optionalFields && searchParams1.get(QUERY_KEY_OPTIONAL_FIELDS) !== optionalFields) {
713
+ searchParams1.set(QUERY_KEY_OPTIONAL_FIELDS, optionalFields);
714
+ }
715
+ from(searchParams1.keys())
716
+ .sort()
717
+ .forEach((key) => {
718
+ const value = searchParams1.get(key);
719
+ searchParams1.delete(key);
720
+ searchParams1.append(key, value);
721
+ });
722
+ return url1.toString().substr(domain.length);
723
+ }
724
+ function mergeFields(url1, url2, name) {
725
+ const fields1 = ScopedFieldsCollection.fromQueryParameterValue(url1.searchParams.get(name));
726
+ const fields2 = ScopedFieldsCollection.fromQueryParameterValue(url2.searchParams.get(name));
727
+ fields1.merge(fields2);
728
+ return fields1.toQueryParameterValue();
729
+ }
730
+ /**
731
+ * Checks that all records ids exist in both arrays
732
+ * @param first batch of first array or records
733
+ * @param second batch of second array or records
734
+ * @returns
735
+ */
736
+ function recordIdsAllMatch(first, second) {
737
+ const firstIds = first.map((record) => record.id);
738
+ const secondIds = second.map((record) => record.id);
739
+ return firstIds.every((id) => secondIds.includes(id));
740
+ }
741
+
742
+ const RELATED_LIST_RECORDS_BATCH_ENDPOINT_REGEX = /^\/ui-api\/related-list-records\/batch\/?(([a-zA-Z0-9]+))?\//;
743
+ const referenceId = 'LDS_Related_List_Records_AggregateUi';
744
+ function makeNetworkChunkFieldsGetRelatedListRecordsBatch(networkAdapter) {
745
+ return (resourceRequest, resourceRequestContext) => {
746
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RELATED_LIST_RECORDS_BATCH_ENDPOINT_REGEX);
747
+ if (batchRequestInfo === undefined) {
748
+ return networkAdapter(resourceRequest, resourceRequestContext);
749
+ }
750
+ const compositeRequest = buildCompositeRequestByFields(referenceId, resourceRequest, batchRequestInfo);
751
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
752
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
753
+ return mergeAggregateUiResponse(response, (first, second) => {
754
+ return mergeBatchRecordsFields(first, second, (a, b) => {
755
+ return mergeRelatedRecordsFields(a, b);
756
+ });
757
+ });
758
+ });
759
+ };
760
+ }
761
+
762
+ /**
763
+ * Higher order function that accepts a network adapter and returns a new network adapter
764
+ * that is capable of performing field batching to ensure that URL length limits are respected
765
+ * when hitting record endpoints that accept a field list
766
+ *
767
+ * @param networkAdapter the network adapter to do the call.
768
+ */
769
+ function makeNetworkAdapterChunkRecordFields(networkAdapter) {
770
+ // endpoint handlers that support aggregate-ui field batching
771
+ const batchHandlers = [
772
+ makeNetworkChunkFieldsGetRecord,
773
+ makeNetworkChunkFieldsGetRecordsBatch,
774
+ makeNetworkChunkFieldsGetRelatedListRecords,
775
+ makeNetworkChunkFieldsGetRelatedListRecordsBatch,
776
+ ];
777
+ return batchHandlers.reduce((network, handler) => {
778
+ return handler(network);
779
+ }, networkAdapter);
780
+ }
781
+
782
+ export { NimbusNetworkAdapter, makeNetworkAdapterChunkRecordFields };
@@ -0,0 +1,2 @@
1
+ import type { NetworkAdapter } from '@luvio/engine';
2
+ export declare const NimbusNetworkAdapter: NetworkAdapter;
@@ -0,0 +1,2 @@
1
+ import type { Activity } from 'o11y/client';
2
+ export declare const activity: Activity;
@@ -0,0 +1,5 @@
1
+ import type { Instrumentation } from 'o11y/client';
2
+ export { activity } from './activity';
3
+ export { instrumentation } from './instrumentation';
4
+ export { idleDetector } from './idleDetector';
5
+ export declare function getInstrumentation(_name: string): Instrumentation;
@@ -0,0 +1,2 @@
1
+ import type { IdleDetector } from 'o11y/client';
2
+ export declare const idleDetector: IdleDetector;
@@ -0,0 +1,15 @@
1
+ import type { Activity, MetricsTags, Schema, SchematizedData } from 'o11y/client';
2
+ declare function log(_schema: Schema, _data?: SchematizedData): void;
3
+ declare function error(_err: Error, _userSchemaOrText?: string, _data?: SchematizedData): void;
4
+ declare function startActivity(_name: string): Activity;
5
+ declare function incrementCounter(_operation: string, _increment?: number, _hasError?: boolean, _tags?: MetricsTags): void;
6
+ declare function trackValue(_operation: string, _value: number, _hasError?: boolean, _tags?: MetricsTags): void;
7
+ export declare const instrumentation: {
8
+ log: typeof log;
9
+ error: typeof error;
10
+ startActivity: typeof startActivity;
11
+ incrementCounter: typeof incrementCounter;
12
+ trackValue: typeof trackValue;
13
+ };
14
+ export declare const METRIC_KEYS: {};
15
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { Request, Response } from '@salesforce/nimbus-plugin-lds';
2
+ import type { ResourceRequest, FetchResponse, ResourceRequestContext } from '@luvio/engine';
3
+ export declare function buildNimbusNetworkPluginRequest(resourceRequest: ResourceRequest, resourceRequestContext: ResourceRequestContext): Request;
4
+ export declare function buildLdsResponse(response: Response): FetchResponse<any>;
@@ -0,0 +1,44 @@
1
+ export declare class ScopedFields {
2
+ scope: string;
3
+ fields: Record<string, true>;
4
+ constructor(scope: string, fields: Array<string>);
5
+ isUnScoped(): boolean;
6
+ addField(field: string): void;
7
+ addFields(fields: Array<string>): void;
8
+ toQueryParameterValue(): string;
9
+ toQueryParams(): string | string[];
10
+ /**
11
+ * parse Contacts:Contact.Id,Contact.Name into a QueryFields
12
+ */
13
+ static fromQueryParameterValue(paramValue: string): ScopedFields | undefined;
14
+ }
15
+ export declare class ScopedFieldsCollection {
16
+ listIdToFieldsMap: Record<string, ScopedFields>;
17
+ /**
18
+ * merge the from ScopedFieldsCollection into current one
19
+ * @param from
20
+ */
21
+ merge(from: ScopedFieldsCollection): void;
22
+ toQueryParams(): string | string[];
23
+ /**
24
+ * convert to query parameter value
25
+ * @returns
26
+ */
27
+ toQueryParameterValue(): string;
28
+ /**
29
+ * split the ScopedFields into multiple ScopedFields
30
+ * which there max fields list length will not exceeded the specified maxLength
31
+ * @param maxLength
32
+ */
33
+ split(maxLength?: number): Array<ScopedFieldsCollection>;
34
+ size(): number;
35
+ countOfUnScoped(): number;
36
+ countOfScoped(): number;
37
+ isUnScopedMixedWithScoped(): boolean;
38
+ /**
39
+ *
40
+ * @param paramValue like Contacts:Contact.Id,Contact.Name;Opportunities:Opportunity.Id
41
+ * @returns
42
+ */
43
+ static fromQueryParameterValue(paramValue: String | null): ScopedFieldsCollection;
44
+ }
@@ -0,0 +1,9 @@
1
+ import type { NetworkAdapter } from '@luvio/engine';
2
+ /**
3
+ * Higher order function that accepts a network adapter and returns a new network adapter
4
+ * that is capable of performing field batching to ensure that URL length limits are respected
5
+ * when hitting record endpoints that accept a field list
6
+ *
7
+ * @param networkAdapter the network adapter to do the call.
8
+ */
9
+ export declare function makeNetworkAdapterChunkRecordFields(networkAdapter: NetworkAdapter): NetworkAdapter;
@@ -0,0 +1,15 @@
1
+ import type { NetworkAdapter, FetchResponse } from '@luvio/engine';
2
+ import type { RecordRepresentation } from '@salesforce/lds-adapters-uiapi';
3
+ import type { AggregateResponse, UiApiErrorResponse } from './utils';
4
+ export type GetRecordResult = RecordRepresentation | UiApiErrorResponse;
5
+ export type GetRecordAggregateResponse = AggregateResponse<GetRecordResult>;
6
+ export type GetRecordResponse = FetchResponse<GetRecordResult>;
7
+ /**
8
+ * Export to facilitate unit tests
9
+ * Merge the second getRecord result into the first one.
10
+ * If any is error response, merged result is error response.
11
+ * If both are sucesses, due to they are from same records,
12
+ * fields sub node will be merged recursively
13
+ */
14
+ export declare function mergeGetRecordResult(first: GetRecordResult, second: GetRecordResult): GetRecordResult;
15
+ export declare function makeNetworkChunkFieldsGetRecord(networkAdapter: NetworkAdapter): NetworkAdapter;
@@ -0,0 +1,7 @@
1
+ import type { FetchResponse, NetworkAdapter } from '@luvio/engine';
2
+ import type { BatchRepresentation } from '@salesforce/lds-adapters-uiapi';
3
+ import type { AggregateResponse } from './utils';
4
+ export declare const RECORDS_BATCH_ENDPOINT_REGEX: RegExp;
5
+ export type GetRecordsBatchAggregateResponse = AggregateResponse<BatchRepresentation>;
6
+ export type GetRecordsBatchResponse = FetchResponse<BatchRepresentation>;
7
+ export declare function makeNetworkChunkFieldsGetRecordsBatch(networkAdapter: NetworkAdapter): NetworkAdapter;
@@ -0,0 +1,22 @@
1
+ import type { NetworkAdapter } from '@luvio/engine';
2
+ import type { AggregateResponse } from './utils';
3
+ import type { RelatedListRecordCollectionRepresentation } from '@salesforce/lds-adapters-uiapi';
4
+ export type RelatedListAggregateResponse = AggregateResponse<RelatedListRecordCollectionRepresentation>;
5
+ /**
6
+ * Merge the second related list record collection into first one and return it.
7
+ * It checks both collections should have exaction same records, otherwise error.
8
+ * Exports it for unit tests
9
+ */
10
+ export declare function mergeRelatedRecordsFields(first: RelatedListRecordCollectionRepresentation, second: RelatedListRecordCollectionRepresentation): RelatedListRecordCollectionRepresentation;
11
+ export declare function makeNetworkChunkFieldsGetRelatedListRecords(networkAdapter: NetworkAdapter): NetworkAdapter;
12
+ /**
13
+ * merge to paging url with different set of fields or optional fields as combined one
14
+ * the paging url is like
15
+ * /services/data/v58.0/ui-api/related-list-records/001R0000006l1xKIAQ/Contacts
16
+ * ?fields=Id%2CName&optionalFields=Contact.Id%2CContact.Name&pageSize=50&pageToken=0
17
+ * @param path1 url path and query parmeter without domain
18
+ * @param path2 url path and query parmeter without domain
19
+ *
20
+ * Export to unit test
21
+ */
22
+ export declare function mergeUrl(path1: string | null, path2: string | null): string | null;
@@ -0,0 +1,6 @@
1
+ import type { FetchResponse, NetworkAdapter } from '@luvio/engine';
2
+ import type { AggregateResponse } from './utils';
3
+ import type { RelatedListRecordCollectionBatchRepresentation } from '@salesforce/lds-adapters-uiapi';
4
+ export type RelatedListBatchAggregateResponse = AggregateResponse<RelatedListRecordCollectionBatchRepresentation>;
5
+ export type RelatedListBatchResponse = FetchResponse<RelatedListRecordCollectionBatchRepresentation>;
6
+ export declare function makeNetworkChunkFieldsGetRelatedListRecordsBatch(networkAdapter: NetworkAdapter): NetworkAdapter;
@@ -0,0 +1,71 @@
1
+ import type { ResourceRequest, FetchResponse } from '@luvio/engine';
2
+ import { HttpStatusCode } from '@luvio/engine';
3
+ import type { RecordRepresentation, BatchRepresentation, RelatedListRecordCollectionRepresentation, RelatedListRecordCollectionBatchRepresentation } from '@salesforce/lds-adapters-uiapi';
4
+ import type { GetRecordResult } from './makeNetworkChunkFieldsGetRecord';
5
+ import { ScopedFieldsCollection } from './ScopedFields';
6
+ export declare const MAX_STRING_LENGTH_PER_CHUNK = 10000;
7
+ export interface CompositeRequest {
8
+ url: string;
9
+ referenceId: string;
10
+ }
11
+ interface UiApiClientOptions {
12
+ ifModifiedSince?: string;
13
+ ifUnmodifiedSince?: string;
14
+ }
15
+ export interface UiApiParams {
16
+ [name: string]: any;
17
+ clientOptions?: UiApiClientOptions;
18
+ }
19
+ export interface UiApiError {
20
+ errorCode: string;
21
+ message: string;
22
+ }
23
+ export type UiApiErrorResponse = Array<UiApiError>;
24
+ export type CompositeResponse<T> = {
25
+ body: T;
26
+ httpStatusCode: HttpStatusCode;
27
+ };
28
+ export interface CompositeResponseEnvelope<T> {
29
+ compositeResponse: CompositeResponse<T | UiApiErrorResponse>[];
30
+ }
31
+ /**
32
+ * Object Representation types allowed when merging
33
+ */
34
+ type SupportedAggregateRepresentation<T> = Extract<T, GetRecordResult | BatchRepresentation | RelatedListRecordCollectionRepresentation | RelatedListRecordCollectionBatchRepresentation>;
35
+ export type AggregateResponse<T> = FetchResponse<CompositeResponseEnvelope<SupportedAggregateRepresentation<T>>>;
36
+ /**
37
+ * Supported batch representation
38
+ */
39
+ type SupportedBatchRepresentation = RelatedListRecordCollectionBatchRepresentation | BatchRepresentation;
40
+ /**
41
+ * Supported batch representation
42
+ */
43
+ type SupportedBatchCollectionRepresentation = RelatedListRecordCollectionRepresentation | RecordRepresentation;
44
+ /**
45
+ * merge the aggregate ui child responses into a single object representation
46
+ * @param response
47
+ * @param mergeFunc the function used to define how the records should be merged together
48
+ * @returns the merged record
49
+ */
50
+ export declare function mergeAggregateUiResponse<T>(response: AggregateResponse<T>, mergeFunc: (first: T, second: T) => SupportedAggregateRepresentation<T>): FetchResponse<SupportedAggregateRepresentation<T> | UiApiErrorResponse>;
51
+ export declare function buildAggregateUiUrl(params: UiApiParams, resourceRequest: ResourceRequest): string;
52
+ export declare function shouldUseAggregateUiForFields(fieldsArray: string, optionalFieldsArray: string): boolean;
53
+ export declare function isSpanningRecord(fieldValue: null | string | number | boolean | RecordRepresentation): fieldValue is RecordRepresentation;
54
+ export declare function mergeRecordFields(first: RecordRepresentation, second: RecordRepresentation): RecordRepresentation;
55
+ export declare function mergeBatchRecordsFields(first: SupportedBatchRepresentation, second: SupportedBatchRepresentation, collectionMergeFunc: (first: SupportedBatchCollectionRepresentation, second: SupportedBatchCollectionRepresentation) => SupportedBatchCollectionRepresentation): SupportedBatchRepresentation;
56
+ /**
57
+ * Check to see if we have fields that are > max allowed characters long
58
+ * @param resourceRequest resource request to check
59
+ * @param endpoint Regular Expression to check the endpoint to aggregate
60
+ * @returns undefined if we should not aggregate. object if we should.
61
+ */
62
+ export declare function createAggregateBatchRequestInfo(resourceRequest: ResourceRequest, endpoint: RegExp): {
63
+ fieldCollection: ScopedFieldsCollection[];
64
+ optionalFieldCollection: ScopedFieldsCollection[];
65
+ } | undefined;
66
+ export declare function createAggregateUiRequest(resourceRequest: ResourceRequest, compositeRequest: CompositeRequest[]): ResourceRequest;
67
+ export declare function buildCompositeRequestByFields(referenceId: string, resourceRequest: ResourceRequest, recordsCompositeRequest: {
68
+ fieldCollection: ScopedFieldsCollection[] | undefined;
69
+ optionalFieldCollection: ScopedFieldsCollection[] | undefined;
70
+ }): CompositeRequest[];
71
+ export {};
@@ -0,0 +1,29 @@
1
+ declare const keys: {
2
+ (o: object): string[];
3
+ (o: {}): string[];
4
+ }, create: {
5
+ (o: object | null): any;
6
+ (o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;
7
+ }, assign: {
8
+ <T extends {}, U>(target: T, source: U): T & U;
9
+ <T_1 extends {}, U_1, V>(target: T_1, source1: U_1, source2: V): T_1 & U_1 & V;
10
+ <T_2 extends {}, U_2, V_1, W>(target: T_2, source1: U_2, source2: V_1, source3: W): T_2 & U_2 & V_1 & W;
11
+ (target: object, ...sources: any[]): any;
12
+ }, entries: {
13
+ <T>(o: {
14
+ [s: string]: T;
15
+ } | ArrayLike<T>): [string, T][];
16
+ (o: {}): [string, any][];
17
+ };
18
+ declare const stringify: {
19
+ (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string;
20
+ (value: any, replacer?: (string | number)[] | null | undefined, space?: string | number | undefined): string;
21
+ }, parse: (text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => any;
22
+ declare const push: (...items: any[]) => number, join: (separator?: string | undefined) => string, slice: (start?: number | undefined, end?: number | undefined) => any[];
23
+ declare const isArray: (arg: any) => arg is any[], from: {
24
+ <T>(arrayLike: ArrayLike<T>): T[];
25
+ <T_1, U>(arrayLike: ArrayLike<T_1>, mapfn: (v: T_1, k: number) => U, thisArg?: any): U[];
26
+ <T_2>(iterable: Iterable<T_2> | ArrayLike<T_2>): T_2[];
27
+ <T_3, U_1>(iterable: Iterable<T_3> | ArrayLike<T_3>, mapfn: (v: T_3, k: number) => U_1, thisArg?: any): U_1[];
28
+ };
29
+ export { keys as ObjectKeys, create as ObjectCreate, assign as ObjectAssign, entries as ObjectEntries, push as ArrayPrototypePush, join as ArrayPrototypeJoin, slice as ArrayPrototypeSlice, isArray as ArrayIsArray, from as ArrayFrom, stringify as JSONStringify, parse as JSONParse, };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@salesforce/lds-network-nimbus",
3
+ "version": "1.100.2",
4
+ "license": "SEE LICENSE IN LICENSE.txt",
5
+ "description": "A nimbus-plugin-based implementation of the Luvio NetworkAdapter.",
6
+ "main": "dist/main.js",
7
+ "module": "dist/main.js",
8
+ "types": "dist/main.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/main.d.ts",
15
+ "import": "./dist/main.js",
16
+ "default": "./dist/main.js"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "prepare": "yarn build",
21
+ "build": "rollup --config rollup.config.js",
22
+ "test:debug": "node --inspect-brk ../../node_modules/.bin/jest --runInBand",
23
+ "test:unit": "NODE_ENV=production jest",
24
+ "test:size": "bundlesize",
25
+ "clean": "rm -rf dist"
26
+ },
27
+ "dependencies": {
28
+ "@luvio/engine": "0.135.4",
29
+ "@salesforce/lds-instrumentation": "^1.100.2",
30
+ "o11y": "242.1.0"
31
+ },
32
+ "devDependencies": {
33
+ "@salesforce/lds-adapters-uiapi": "^1.100.2",
34
+ "@salesforce/nimbus-plugin-lds": "^1.100.2"
35
+ },
36
+ "bundlesize": [
37
+ {
38
+ "path": "./dist/main.js",
39
+ "maxSize": "10 kB",
40
+ "compression": "brotli"
41
+ }
42
+ ]
43
+ }