@salesforce/lds-network-nimbus 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.js ADDED
@@ -0,0 +1,807 @@
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
+ import ldsUseShortUrlGate from '@salesforce/gate/lds.useShortUrl';
10
+
11
+ const { keys, create, assign, entries } = Object;
12
+ const { stringify, parse } = JSON;
13
+ const { push, join, slice } = Array.prototype;
14
+ const { isArray, from } = Array;
15
+
16
+ function ldsParamsToString(params) {
17
+ const returnParams = create(null);
18
+ const keys$1 = keys(params);
19
+ for (let i = 0, len = keys$1.length; i < len; i++) {
20
+ const key = keys$1[i];
21
+ const value = params[key];
22
+ if (value === undefined) {
23
+ // filter out params that have no value
24
+ continue;
25
+ }
26
+ if (isArray(value)) {
27
+ // filter out empty arrays
28
+ if (value.length > 0) {
29
+ returnParams[key] = value.join(',');
30
+ }
31
+ }
32
+ else {
33
+ returnParams[key] = `${value}`;
34
+ }
35
+ if (isObject(value) === true && keys(value).length > 0) {
36
+ returnParams[key] = stringify(value);
37
+ }
38
+ }
39
+ return returnParams;
40
+ }
41
+ function statusTextFromStatusCode(status) {
42
+ switch (status) {
43
+ case HttpStatusCode.Ok:
44
+ return 'OK';
45
+ case HttpStatusCode.NotModified:
46
+ return 'Not Modified';
47
+ case HttpStatusCode.NotFound:
48
+ return 'Not Found';
49
+ case HttpStatusCode.BadRequest:
50
+ return 'Bad Request';
51
+ case HttpStatusCode.ServerError:
52
+ return 'Server Error';
53
+ default:
54
+ return `Unexpected HTTP Status Code: ${status}`;
55
+ }
56
+ }
57
+ function methodFromResourceRequestMethod(method) {
58
+ switch (method.toLowerCase()) {
59
+ case 'get':
60
+ return 'GET';
61
+ case 'put':
62
+ return 'PUT';
63
+ case 'post':
64
+ return 'POST';
65
+ case 'delete':
66
+ return 'DELETE';
67
+ case 'patch':
68
+ return 'PATCH';
69
+ default:
70
+ throw Error(`Unexpected method ${method}`);
71
+ }
72
+ }
73
+ function priorityFromResourceRequest(request) {
74
+ switch (request.priority) {
75
+ case 'background':
76
+ return 'background';
77
+ case 'high':
78
+ return 'high';
79
+ case 'normal':
80
+ default:
81
+ return 'normal';
82
+ }
83
+ }
84
+ function isStatusOk(status) {
85
+ return status >= 200 && status <= 299;
86
+ }
87
+ // adapted from adapter-utils untrustedIsObject
88
+ function isObject(value) {
89
+ return typeof value === 'object' && value !== null && isArray(value) === false;
90
+ }
91
+ function stringifyIfPresent(value) {
92
+ if (value === undefined || value === null) {
93
+ return null;
94
+ }
95
+ return stringify(value);
96
+ }
97
+ function parseIfPresent(value) {
98
+ if (value === undefined || value === null || value === '') {
99
+ return null;
100
+ }
101
+ return parse(value);
102
+ }
103
+ function buildNimbusNetworkPluginRequest(resourceRequest, resourceRequestContext) {
104
+ const { basePath, baseUri, method, headers, queryParams, body } = resourceRequest;
105
+ let observabilityContext = null;
106
+ if (resourceRequestContext !== undefined &&
107
+ resourceRequestContext.requestCorrelator !== undefined &&
108
+ resourceRequestContext.requestCorrelator.observabilityContext !==
109
+ undefined) {
110
+ ({ observabilityContext = null } =
111
+ resourceRequestContext.requestCorrelator);
112
+ }
113
+ return {
114
+ method: methodFromResourceRequestMethod(method),
115
+ body: stringifyIfPresent(body),
116
+ headers,
117
+ queryParams: ldsParamsToString(queryParams),
118
+ path: `${baseUri}${basePath}`,
119
+ priority: priorityFromResourceRequest(resourceRequest),
120
+ observabilityContext,
121
+ };
122
+ }
123
+ function buildLdsResponse(response) {
124
+ const { body: responseBody, headers, status } = response;
125
+ const statusText = statusTextFromStatusCode(status);
126
+ return {
127
+ statusText,
128
+ status,
129
+ body: parseIfPresent(responseBody),
130
+ headers,
131
+ ok: isStatusOk(status),
132
+ };
133
+ }
134
+
135
+ // so eslint doesn't complain about nimbus
136
+ const tasker = idleDetector.declareNotifierTaskMulti('NimbusNetworkAdapter');
137
+ const NimbusNetworkAdapter = (request, resourceRequestContext) => {
138
+ tasker.add();
139
+ return new Promise((resolve, reject) => {
140
+ try {
141
+ __nimbus.plugins.LdsNetworkAdapter.sendRequest(buildNimbusNetworkPluginRequest(request, resourceRequestContext), (response) => {
142
+ try {
143
+ resolve(buildLdsResponse(response));
144
+ }
145
+ catch (error) {
146
+ // don't leave promise hanging, catch any errors (eg: if native side
147
+ // returns malformed response) and call reject
148
+ reject(error);
149
+ }
150
+ }, (error) => {
151
+ reject(new Error(`type: ${error.type}, message: ${error.message}`));
152
+ });
153
+ }
154
+ catch (error) {
155
+ // don't leave promise hanging, catch any errors (eg: if native side
156
+ // fails to parse the request), and call reject
157
+ reject(error);
158
+ }
159
+ }).finally(() => tasker.done());
160
+ };
161
+
162
+ /**
163
+ * related-list-records/batch fields and optional fields could be like below.
164
+ * /ui-api/related-list-records/batch/001R0000006l1xKIAQ/Contacts,Opportunities?
165
+ * optionalFields=Contacts:Contact.Id,Contact.Name;Opportunities:Opportunity.Id
166
+ *
167
+ * the pattern is [{relativeListId}:{[fields]};{relativeListId}:{[fields]}]
168
+ */
169
+ const SEPARATOR_BETWEEN_SCOPES = ';';
170
+ const SEPARATOR_BETWEEN_SCOPE_AND_FIELDS = ':';
171
+ const SEPARATOR_BETWEEN_FIELDS = ',';
172
+ const UNSCOPED_IDENTIFIER = 'unscoped';
173
+ class ScopedFields {
174
+ constructor(scope, fields) {
175
+ this.fields = {};
176
+ this.scope = scope;
177
+ for (let i = 0, len = fields.length; i < len; i += 1) {
178
+ this.fields[fields[i]] = true;
179
+ }
180
+ }
181
+ isUnScoped() {
182
+ return this.scope === UNSCOPED_IDENTIFIER;
183
+ }
184
+ addField(field) {
185
+ this.fields[field] = true;
186
+ }
187
+ addFields(fields) {
188
+ fields.forEach(this.addField, this);
189
+ }
190
+ toQueryParameterValue() {
191
+ const joinedFields = join.call(Object.keys(this.fields), SEPARATOR_BETWEEN_FIELDS);
192
+ return this.isUnScoped()
193
+ ? joinedFields
194
+ : join.call([this.scope, joinedFields], SEPARATOR_BETWEEN_SCOPE_AND_FIELDS);
195
+ }
196
+ toQueryParams() {
197
+ return this.isUnScoped() ? Object.keys(this.fields) : this.toQueryParameterValue();
198
+ }
199
+ /**
200
+ * parse Contacts:Contact.Id,Contact.Name into a QueryFields
201
+ */
202
+ static fromQueryParameterValue(paramValue) {
203
+ if (paramValue === null || paramValue === '')
204
+ return;
205
+ const scopeToFields = paramValue.split(SEPARATOR_BETWEEN_SCOPE_AND_FIELDS);
206
+ if (scopeToFields.length === 1) {
207
+ //unscoped
208
+ return new ScopedFields(UNSCOPED_IDENTIFIER, scopeToFields[0].split(SEPARATOR_BETWEEN_FIELDS));
209
+ }
210
+ else if (scopeToFields.length === 2) {
211
+ const scope = scopeToFields[0];
212
+ const fields = scopeToFields[1];
213
+ if (scope === undefined || fields === null)
214
+ return;
215
+ return new ScopedFields(scope, fields.split(SEPARATOR_BETWEEN_FIELDS));
216
+ }
217
+ else {
218
+ return;
219
+ }
220
+ }
221
+ }
222
+ class ScopedFieldsCollection {
223
+ constructor() {
224
+ this.listIdToFieldsMap = {};
225
+ }
226
+ /**
227
+ * merge the from ScopedFieldsCollection into current one
228
+ * @param from
229
+ */
230
+ merge(from) {
231
+ const { listIdToFieldsMap } = from;
232
+ const scopes = Object.keys(listIdToFieldsMap);
233
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
234
+ const scope = scopes[i];
235
+ const scopedFields = listIdToFieldsMap[scope];
236
+ const existingScopedFields = this.listIdToFieldsMap[scope];
237
+ if (existingScopedFields) {
238
+ existingScopedFields.addFields(Object.keys(scopedFields.fields));
239
+ }
240
+ else {
241
+ this.listIdToFieldsMap[scope] = scopedFields;
242
+ }
243
+ }
244
+ }
245
+ toQueryParams() {
246
+ return this.countOfUnScoped() > 0
247
+ ? this.listIdToFieldsMap[UNSCOPED_IDENTIFIER].toQueryParams()
248
+ : this.toQueryParameterValue();
249
+ }
250
+ /**
251
+ * convert to query parameter value
252
+ * @returns
253
+ */
254
+ toQueryParameterValue() {
255
+ let result = [];
256
+ const scopes = Object.keys(this.listIdToFieldsMap);
257
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
258
+ const chunk = this.listIdToFieldsMap[scopes[i]].toQueryParameterValue();
259
+ if (chunk !== undefined)
260
+ result.push(chunk);
261
+ }
262
+ return join.call(result, SEPARATOR_BETWEEN_SCOPES);
263
+ }
264
+ /**
265
+ * split the ScopedFields into multiple ScopedFields
266
+ * which there max fields list length will not exceeded the specified maxLength
267
+ * @param maxLength
268
+ */
269
+ split(maxLength = MAX_STRING_LENGTH_PER_CHUNK) {
270
+ const size = this.size();
271
+ if (size > maxLength) {
272
+ const fieldsArray = [];
273
+ const scopes = Object.keys(this.listIdToFieldsMap);
274
+ for (let i = 0, len = scopes.length; i < len; i += 1) {
275
+ const { scope, fields } = this.listIdToFieldsMap[scopes[i]];
276
+ Object.keys(fields).forEach((field) => {
277
+ fieldsArray.push([scope, field]);
278
+ });
279
+ }
280
+ // Formula: # of fields per chunk = floor( max length per chunk / avg field length)
281
+ const averageFieldStringLength = size / fieldsArray.length;
282
+ const fieldsPerChunk = Math.floor(maxLength / averageFieldStringLength);
283
+ let j = fieldsPerChunk;
284
+ let result = [];
285
+ let current = null;
286
+ for (let i = 0, len = fieldsArray.length; i < len; i += 1) {
287
+ const scope = fieldsArray[i][0];
288
+ const field = fieldsArray[i][1];
289
+ if (current === null || !current.listIdToFieldsMap[scope]) {
290
+ j = fieldsPerChunk;
291
+ current = new ScopedFieldsCollection();
292
+ current.listIdToFieldsMap[scope] = new ScopedFields(scope, [field]);
293
+ result.push(current);
294
+ }
295
+ else {
296
+ current.listIdToFieldsMap[scope].addField(field);
297
+ }
298
+ j--;
299
+ if (j === 0) {
300
+ current = null;
301
+ }
302
+ }
303
+ return result;
304
+ }
305
+ else if (size > 0) {
306
+ return [this];
307
+ }
308
+ else {
309
+ return [];
310
+ }
311
+ }
312
+ size() {
313
+ return this.toQueryParameterValue().length;
314
+ }
315
+ countOfUnScoped() {
316
+ let count = 0;
317
+ const fieldsArray = Object.values(this.listIdToFieldsMap);
318
+ for (let i = 0, len = fieldsArray.length; i < len; i += 1) {
319
+ if (fieldsArray[i].isUnScoped()) {
320
+ count++;
321
+ }
322
+ }
323
+ return count;
324
+ }
325
+ countOfScoped() {
326
+ return Object.keys.length - this.countOfUnScoped();
327
+ }
328
+ isUnScopedMixedWithScoped() {
329
+ return this.countOfUnScoped() > 0 && this.countOfScoped() > 0;
330
+ }
331
+ /**
332
+ *
333
+ * @param paramValue like Contacts:Contact.Id,Contact.Name;Opportunities:Opportunity.Id
334
+ * @returns
335
+ */
336
+ static fromQueryParameterValue(paramValue) {
337
+ const result = new ScopedFieldsCollection();
338
+ if (paramValue) {
339
+ const relativeListChunks = paramValue.split(SEPARATOR_BETWEEN_SCOPES);
340
+ if (relativeListChunks.length === 0)
341
+ return result;
342
+ for (let i = 0, len = relativeListChunks.length; i < len; i += 1) {
343
+ const parsed = ScopedFields.fromQueryParameterValue(relativeListChunks[i]);
344
+ if (parsed) {
345
+ result.listIdToFieldsMap[parsed.scope] = parsed;
346
+ }
347
+ }
348
+ if (result.isUnScopedMixedWithScoped()) {
349
+ throw Error('mixing scoped and unscoped field list is not allowed.');
350
+ }
351
+ }
352
+ return result;
353
+ }
354
+ }
355
+
356
+ const MAX_STRING_LENGTH_PER_CHUNK = 10000;
357
+ //Salesforce/Akamai cdn uri max size is 8898 bytes, short than normal. Per
358
+ //https://help.salesforce.com/s/articleView?id=sf.community_builder_cdn_considerations.htm&type=5
359
+ //Due to we don't know the domain ResourceRequest, here we give 8000
360
+ const MAX_URL_LENGTH = 8000;
361
+ const PARSE_ERROR = 'PARSE_AGGREGATE_UI_RESPONSE_ERROR';
362
+ function isErrorResponse(response) {
363
+ return response.httpStatusCode >= 400;
364
+ }
365
+ /**
366
+ * merge the aggregate ui child responses into a single object representation
367
+ * @param response
368
+ * @param mergeFunc the function used to define how the records should be merged together
369
+ * @returns the merged record
370
+ */
371
+ function mergeAggregateUiResponse(response, mergeFunc) {
372
+ const { body } = response;
373
+ try {
374
+ if (body === null ||
375
+ body === undefined ||
376
+ body.compositeResponse === undefined ||
377
+ body.compositeResponse.length === 0) {
378
+ // We shouldn't even get into this state - a 200 with no body?
379
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
380
+ throw new Error('No response body in executeAggregateUi found');
381
+ }
382
+ // if the body has any non-2xx statuses then that's an error and we return
383
+ // the network response with that error
384
+ const error = body.compositeResponse.find(isErrorResponse);
385
+ if (error !== undefined) {
386
+ const { httpStatusCode, body: errorBody } = error;
387
+ const statusText = errorBody.length > 0 ? errorBody[0].errorCode : '';
388
+ return {
389
+ ...response,
390
+ ok: false,
391
+ status: httpStatusCode,
392
+ statusText,
393
+ body: errorBody,
394
+ };
395
+ }
396
+ // if we got here there are no errors in body, cast as such
397
+ const responses = body.compositeResponse;
398
+ const merged = responses.reduce((seed, resp) => {
399
+ if (seed === null) {
400
+ return resp.body;
401
+ }
402
+ return mergeFunc(seed, resp.body);
403
+ }, null);
404
+ return {
405
+ ...response,
406
+ body: merged,
407
+ };
408
+ }
409
+ catch (error) {
410
+ return {
411
+ ...response,
412
+ ok: false,
413
+ status: HttpStatusCode.ServerError,
414
+ statusText: PARSE_ERROR,
415
+ body: [
416
+ {
417
+ errorCode: PARSE_ERROR,
418
+ message: error.toString(),
419
+ },
420
+ ],
421
+ };
422
+ }
423
+ }
424
+ function buildAggregateUiUrl(params, resourceRequest) {
425
+ const { fields, optionalFields } = params;
426
+ const mergedParams = {
427
+ ...resourceRequest.queryParams,
428
+ fields,
429
+ optionalFields,
430
+ };
431
+ const queryString = [];
432
+ for (const [key, value] of entries(mergedParams)) {
433
+ if (value !== undefined) {
434
+ queryString.push(`${key}=${isArray(value) ? value.join(',') : value}`);
435
+ }
436
+ }
437
+ return `${resourceRequest.baseUri}${resourceRequest.basePath}?${join.call(queryString, '&')}`;
438
+ }
439
+ function shouldUseAggregateUiForFields(fieldsArray, optionalFieldsArray, maxLengthPerChunk) {
440
+ return fieldsArray.length + optionalFieldsArray.length >= maxLengthPerChunk;
441
+ }
442
+ function isSpanningRecord(fieldValue) {
443
+ return fieldValue !== null && typeof fieldValue === 'object';
444
+ }
445
+ function mergeRecordFields(first, second) {
446
+ const { fields: targetFields } = first;
447
+ const { fields: sourceFields } = second;
448
+ const fieldNames = keys(sourceFields);
449
+ for (let i = 0, len = fieldNames.length; i < len; i += 1) {
450
+ const fieldName = fieldNames[i];
451
+ const sourceField = sourceFields[fieldName];
452
+ const targetField = targetFields[fieldName];
453
+ if (isSpanningRecord(sourceField.value)) {
454
+ if (targetField === undefined) {
455
+ targetFields[fieldName] = sourceField;
456
+ continue;
457
+ }
458
+ mergeRecordFields(targetField.value, sourceField.value);
459
+ continue;
460
+ }
461
+ targetFields[fieldName] = sourceField;
462
+ }
463
+ return first;
464
+ }
465
+ function mergeBatchRecordsFields(first, second, collectionMergeFunc) {
466
+ const { results: targetResults } = first;
467
+ const { results: sourceResults } = second;
468
+ for (let i = 0, len = targetResults.length; i < len; i += 1) {
469
+ const targetResult = targetResults[i];
470
+ const sourceResult = sourceResults[i];
471
+ if (targetResult.statusCode !== HttpStatusCode.Ok)
472
+ continue;
473
+ if (sourceResult.statusCode !== HttpStatusCode.Ok) {
474
+ targetResults[i] = sourceResult;
475
+ continue;
476
+ }
477
+ collectionMergeFunc(targetResult.result, sourceResult.result);
478
+ }
479
+ return first;
480
+ }
481
+ /**
482
+ * Check to see if we have fields that are > max allowed characters long
483
+ * @param resourceRequest resource request to check
484
+ * @param endpoint Regular Expression to check the endpoint to aggregate
485
+ * @returns undefined if we should not aggregate. object if we should.
486
+ */
487
+ function createAggregateBatchRequestInfo(resourceRequest, endpoint) {
488
+ // only handle GETs on the given endpoint regex
489
+ if (!isGetRequestForEndpoint(endpoint, resourceRequest)) {
490
+ return undefined;
491
+ }
492
+ const { queryParams: { fields, optionalFields }, } = resourceRequest;
493
+ // only handle requests with fields or optional fields
494
+ if (fields === undefined && optionalFields === undefined) {
495
+ return undefined;
496
+ }
497
+ const fieldsArray = arrayOrEmpty(fields);
498
+ const optionalFieldsArray = arrayOrEmpty(optionalFields);
499
+ // if fields and optional fields are empty delegate request
500
+ if (fieldsArray.length === 0 && optionalFieldsArray.length === 0) {
501
+ return undefined;
502
+ }
503
+ const allowedMaxStringLengthPerChunk = getMaxLengthPerChunkAllowed(resourceRequest);
504
+ const fieldsString = fieldsArray.join(',');
505
+ const optionalFieldsString = optionalFieldsArray.join(',');
506
+ const shouldUseAggregate = shouldUseAggregateUiForFields(fieldsString, optionalFieldsString, allowedMaxStringLengthPerChunk);
507
+ if (!shouldUseAggregate) {
508
+ return undefined;
509
+ }
510
+ const fieldCollection = ScopedFieldsCollection.fromQueryParameterValue(fieldsString).split(allowedMaxStringLengthPerChunk);
511
+ const optionalFieldCollection = ScopedFieldsCollection.fromQueryParameterValue(optionalFieldsString).split(allowedMaxStringLengthPerChunk);
512
+ return {
513
+ fieldCollection,
514
+ optionalFieldCollection,
515
+ };
516
+ }
517
+ function createAggregateUiRequest(resourceRequest, compositeRequest) {
518
+ const aggregateUiPostBody = { compositeRequest };
519
+ const aggregateResourceRequest = {
520
+ method: 'post',
521
+ baseUri: resourceRequest.baseUri,
522
+ basePath: '/ui-api/aggregate-ui',
523
+ body: aggregateUiPostBody,
524
+ priority: resourceRequest.priority,
525
+ queryParams: {},
526
+ headers: {},
527
+ urlParams: {},
528
+ };
529
+ return aggregateResourceRequest;
530
+ }
531
+ function buildCompositeRequestByFields(referenceId, resourceRequest, recordsCompositeRequest) {
532
+ const { fieldCollection, optionalFieldCollection } = recordsCompositeRequest;
533
+ const compositeRequest = [];
534
+ if (fieldCollection !== undefined) {
535
+ for (let i = 0, len = fieldCollection.length; i < len; i += 1) {
536
+ const fieldChunk = fieldCollection[i].toQueryParams();
537
+ if (fieldChunk.length === 0) {
538
+ continue;
539
+ }
540
+ const url = buildAggregateUiUrl({
541
+ fields: fieldChunk,
542
+ }, resourceRequest);
543
+ push.call(compositeRequest, {
544
+ url,
545
+ referenceId: `${referenceId}_fields_${i}`,
546
+ });
547
+ }
548
+ }
549
+ if (optionalFieldCollection !== undefined) {
550
+ for (let i = 0, len = optionalFieldCollection.length; i < len; i += 1) {
551
+ const fieldChunk = optionalFieldCollection[i].toQueryParams();
552
+ if (fieldChunk.length === 0) {
553
+ continue;
554
+ }
555
+ const url = buildAggregateUiUrl({
556
+ optionalFields: fieldChunk,
557
+ }, resourceRequest);
558
+ push.call(compositeRequest, {
559
+ url,
560
+ referenceId: `${referenceId}_optionalFields_${i}`,
561
+ });
562
+ }
563
+ }
564
+ return compositeRequest;
565
+ }
566
+ /**
567
+ * Checks if a resource request is a GET method on the given endpoint
568
+ * @param endpoint Regular Expression of the endpoint
569
+ * @param request the resource request
570
+ */
571
+ function isGetRequestForEndpoint(endpoint, request) {
572
+ const { basePath, method } = request;
573
+ return endpoint.test(basePath) && method === 'get';
574
+ }
575
+ /**
576
+ * Checks if any is an array and returns it as an array.
577
+ * if not an array it returns an empty array.
578
+ * @param array the item to check is an array
579
+ * @returns the array or an empty array
580
+ */
581
+ function arrayOrEmpty(array) {
582
+ return array !== undefined && isArray(array) ? array : [];
583
+ }
584
+ /**
585
+ * Calculate the max lengh per chunk.
586
+ * If useShortUrlGate is open, allow max chunk size is MAX_URL_LENGTH - the url without fields and optional fields in url.
587
+ * Otherwise MAX_STRING_LENGTH_PER_CHUNK
588
+ * @param resourceRequest
589
+ * @returns
590
+ */
591
+ function getMaxLengthPerChunkAllowed(request) {
592
+ if (!ldsUseShortUrlGate.isOpen({ fallback: false })) {
593
+ return MAX_STRING_LENGTH_PER_CHUNK;
594
+ }
595
+ // Too much work to get exact length of the final url, so use stringified json to get the rough length.
596
+ const roughUrlLengthWithoutFieldsAndOptionFields = request.basePath.length +
597
+ request.baseUri.length +
598
+ (request.urlParams ? stringify(request.urlParams).length : 0) +
599
+ stringify({ ...request.queryParams, fields: {}, optionalFields: {} }).length;
600
+ // MAX_URL_LENGTH - full lenght without fields, optionalFields
601
+ return MAX_URL_LENGTH - roughUrlLengthWithoutFieldsAndOptionFields;
602
+ }
603
+
604
+ const RECORD_ENDPOINT_REGEX = /^\/ui-api\/records\/?(([a-zA-Z0-9]+))?$/;
605
+ const referenceId$3 = 'LDS_Records_AggregateUi';
606
+ /**
607
+ * Export to facilitate unit tests
608
+ * Merge the second getRecord result into the first one.
609
+ * If any is error response, merged result is error response.
610
+ * If both are sucesses, due to they are from same records,
611
+ * fields sub node will be merged recursively
612
+ */
613
+ function mergeGetRecordResult(first, second) {
614
+ // return the error if first is error.
615
+ if (isArray(first) && !isArray(second))
616
+ return first;
617
+ // return the error if second is error.
618
+ if (!isArray(first) && isArray(second))
619
+ return second;
620
+ // concat the error array if both are error
621
+ if (isArray(first) && isArray(second)) {
622
+ return [...first, ...second];
623
+ }
624
+ mergeRecordFields(first, second);
625
+ return first;
626
+ }
627
+ function makeNetworkChunkFieldsGetRecord(networkAdapter) {
628
+ return (resourceRequest, resourceRequestContext) => {
629
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RECORD_ENDPOINT_REGEX);
630
+ if (batchRequestInfo === undefined) {
631
+ return networkAdapter(resourceRequest, resourceRequestContext);
632
+ }
633
+ const compositeRequest = buildCompositeRequestByFields(referenceId$3, resourceRequest, batchRequestInfo);
634
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
635
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
636
+ return mergeAggregateUiResponse(response, mergeGetRecordResult);
637
+ });
638
+ };
639
+ }
640
+
641
+ const RECORDS_BATCH_ENDPOINT_REGEX = /^\/ui-api\/records\/batch\/?(([a-zA-Z0-9|,]+))?$/;
642
+ const referenceId$2 = 'LDS_Records_Batch_AggregateUi';
643
+ function makeNetworkChunkFieldsGetRecordsBatch(networkAdapter) {
644
+ return (resourceRequest, resourceRequestContext) => {
645
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RECORDS_BATCH_ENDPOINT_REGEX);
646
+ if (batchRequestInfo === undefined) {
647
+ return networkAdapter(resourceRequest, resourceRequestContext);
648
+ }
649
+ const compositeRequest = buildCompositeRequestByFields(referenceId$2, resourceRequest, batchRequestInfo);
650
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
651
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
652
+ return mergeAggregateUiResponse(response, (first, second) => {
653
+ return mergeBatchRecordsFields(first, second, (a, b) => {
654
+ return mergeRecordFields(a, b);
655
+ });
656
+ });
657
+ });
658
+ };
659
+ }
660
+
661
+ const RELATED_LIST_RECORDS_ENDPOINT_REGEX = /^\/ui-api\/related-list-records\/?(([a-zA-Z0-9]+))?\/?(([a-zA-Z0-9]+))?$/;
662
+ const referenceId$1 = 'LDS_Related_List_Records_AggregateUi';
663
+ const QUERY_KEY_FIELDS = 'fields';
664
+ const QUERY_KEY_OPTIONAL_FIELDS = 'optionalFields';
665
+ /**
666
+ * Merge the second related list record collection into first one and return it.
667
+ * It checks both collections should have exaction same records, otherwise error.
668
+ * Exports it for unit tests
669
+ */
670
+ function mergeRelatedRecordsFields(first, second) {
671
+ const { records: targetRecords } = first;
672
+ const { records: sourceRecords } = second;
673
+ if (sourceRecords.length === targetRecords.length &&
674
+ recordIdsAllMatch(targetRecords, sourceRecords)) {
675
+ first.fields = first.fields.concat(second.fields);
676
+ first.optionalFields = first.optionalFields.concat(second.optionalFields);
677
+ for (let i = 0, len = sourceRecords.length; i < len; i += 1) {
678
+ const targetRecord = targetRecords[i];
679
+ const sourceRecord = sourceRecords[i];
680
+ mergeRecordFields(targetRecord, sourceRecord);
681
+ }
682
+ mergePageUrls(first, second);
683
+ return first;
684
+ }
685
+ else {
686
+ // Throw error due to two collection are about different set of records
687
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
688
+ throw new Error('Aggregate UI response is invalid');
689
+ }
690
+ }
691
+ function makeNetworkChunkFieldsGetRelatedListRecords(networkAdapter) {
692
+ return (resourceRequest, resourceRequestContext) => {
693
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RELATED_LIST_RECORDS_ENDPOINT_REGEX);
694
+ if (batchRequestInfo === undefined) {
695
+ return networkAdapter(resourceRequest, resourceRequestContext);
696
+ }
697
+ const compositeRequest = buildCompositeRequestByFields(referenceId$1, resourceRequest, batchRequestInfo);
698
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
699
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
700
+ return mergeAggregateUiResponse(response, mergeRelatedRecordsFields);
701
+ });
702
+ };
703
+ }
704
+ /**
705
+ * merge the second related list record collection into first one and return it
706
+ */
707
+ function mergePageUrls(first, second) {
708
+ first.currentPageUrl = mergeUrl(first.currentPageUrl, second.currentPageUrl);
709
+ first.previousPageUrl = mergeUrl(first.previousPageUrl, second.previousPageUrl);
710
+ first.nextPageUrl = mergeUrl(first.nextPageUrl, second.nextPageUrl);
711
+ }
712
+ /**
713
+ * merge to paging url with different set of fields or optional fields as combined one
714
+ * the paging url is like
715
+ * /services/data/v58.0/ui-api/related-list-records/001R0000006l1xKIAQ/Contacts
716
+ * ?fields=Id%2CName&optionalFields=Contact.Id%2CContact.Name&pageSize=50&pageToken=0
717
+ * @param path1 url path and query parmeter without domain
718
+ * @param path2 url path and query parmeter without domain
719
+ *
720
+ * Export to unit test
721
+ */
722
+ function mergeUrl(path1, path2) {
723
+ if (path1 === null)
724
+ return path2;
725
+ if (path2 === null)
726
+ return path1;
727
+ // new Url(...) need the path1, path2 to be prefix-ed with this fake domain
728
+ const domain = 'http://c.com';
729
+ const url1 = new URL(domain + path1);
730
+ const url2 = new URL(domain + path2);
731
+ const searchParams1 = url1.searchParams;
732
+ const fields = mergeFields(url1, url2, QUERY_KEY_FIELDS);
733
+ if (fields && searchParams1.get(QUERY_KEY_FIELDS) !== fields) {
734
+ searchParams1.set(QUERY_KEY_FIELDS, fields);
735
+ }
736
+ const optionalFields = mergeFields(url1, url2, QUERY_KEY_OPTIONAL_FIELDS);
737
+ if (optionalFields && searchParams1.get(QUERY_KEY_OPTIONAL_FIELDS) !== optionalFields) {
738
+ searchParams1.set(QUERY_KEY_OPTIONAL_FIELDS, optionalFields);
739
+ }
740
+ from(searchParams1.keys())
741
+ .sort()
742
+ .forEach((key) => {
743
+ const value = searchParams1.get(key);
744
+ searchParams1.delete(key);
745
+ searchParams1.append(key, value);
746
+ });
747
+ return url1.toString().substr(domain.length);
748
+ }
749
+ function mergeFields(url1, url2, name) {
750
+ const fields1 = ScopedFieldsCollection.fromQueryParameterValue(url1.searchParams.get(name));
751
+ const fields2 = ScopedFieldsCollection.fromQueryParameterValue(url2.searchParams.get(name));
752
+ fields1.merge(fields2);
753
+ return fields1.toQueryParameterValue();
754
+ }
755
+ /**
756
+ * Checks that all records ids exist in both arrays
757
+ * @param first batch of first array or records
758
+ * @param second batch of second array or records
759
+ * @returns
760
+ */
761
+ function recordIdsAllMatch(first, second) {
762
+ const firstIds = first.map((record) => record.id);
763
+ const secondIds = second.map((record) => record.id);
764
+ return firstIds.every((id) => secondIds.includes(id));
765
+ }
766
+
767
+ const RELATED_LIST_RECORDS_BATCH_ENDPOINT_REGEX = /^\/ui-api\/related-list-records\/batch\/?(([a-zA-Z0-9]+))?\//;
768
+ const referenceId = 'LDS_Related_List_Records_AggregateUi';
769
+ function makeNetworkChunkFieldsGetRelatedListRecordsBatch(networkAdapter) {
770
+ return (resourceRequest, resourceRequestContext) => {
771
+ const batchRequestInfo = createAggregateBatchRequestInfo(resourceRequest, RELATED_LIST_RECORDS_BATCH_ENDPOINT_REGEX);
772
+ if (batchRequestInfo === undefined) {
773
+ return networkAdapter(resourceRequest, resourceRequestContext);
774
+ }
775
+ const compositeRequest = buildCompositeRequestByFields(referenceId, resourceRequest, batchRequestInfo);
776
+ const aggregateRequest = createAggregateUiRequest(resourceRequest, compositeRequest);
777
+ return networkAdapter(aggregateRequest, resourceRequestContext).then((response) => {
778
+ return mergeAggregateUiResponse(response, (first, second) => {
779
+ return mergeBatchRecordsFields(first, second, (a, b) => {
780
+ return mergeRelatedRecordsFields(a, b);
781
+ });
782
+ });
783
+ });
784
+ };
785
+ }
786
+
787
+ /**
788
+ * Higher order function that accepts a network adapter and returns a new network adapter
789
+ * that is capable of performing field batching to ensure that URL length limits are respected
790
+ * when hitting record endpoints that accept a field list
791
+ *
792
+ * @param networkAdapter the network adapter to do the call.
793
+ */
794
+ function makeNetworkAdapterChunkRecordFields(networkAdapter) {
795
+ // endpoint handlers that support aggregate-ui field batching
796
+ const batchHandlers = [
797
+ makeNetworkChunkFieldsGetRecord,
798
+ makeNetworkChunkFieldsGetRecordsBatch,
799
+ makeNetworkChunkFieldsGetRelatedListRecords,
800
+ makeNetworkChunkFieldsGetRelatedListRecordsBatch,
801
+ ];
802
+ return batchHandlers.reduce((network, handler) => {
803
+ return handler(network);
804
+ }, networkAdapter);
805
+ }
806
+
807
+ export { NimbusNetworkAdapter, makeNetworkAdapterChunkRecordFields };
@@ -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';
@@ -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,72 @@
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 declare const MAX_URL_LENGTH = 8000;
8
+ export interface CompositeRequest {
9
+ url: string;
10
+ referenceId: string;
11
+ }
12
+ interface UiApiClientOptions {
13
+ ifModifiedSince?: string;
14
+ ifUnmodifiedSince?: string;
15
+ }
16
+ export interface UiApiParams {
17
+ [name: string]: any;
18
+ clientOptions?: UiApiClientOptions;
19
+ }
20
+ export interface UiApiError {
21
+ errorCode: string;
22
+ message: string;
23
+ }
24
+ export type UiApiErrorResponse = Array<UiApiError>;
25
+ export type CompositeResponse<T> = {
26
+ body: T;
27
+ httpStatusCode: HttpStatusCode;
28
+ };
29
+ export interface CompositeResponseEnvelope<T> {
30
+ compositeResponse: CompositeResponse<T | UiApiErrorResponse>[];
31
+ }
32
+ /**
33
+ * Object Representation types allowed when merging
34
+ */
35
+ type SupportedAggregateRepresentation<T> = Extract<T, GetRecordResult | BatchRepresentation | RelatedListRecordCollectionRepresentation | RelatedListRecordCollectionBatchRepresentation>;
36
+ export type AggregateResponse<T> = FetchResponse<CompositeResponseEnvelope<SupportedAggregateRepresentation<T>>>;
37
+ /**
38
+ * Supported batch representation
39
+ */
40
+ type SupportedBatchRepresentation = RelatedListRecordCollectionBatchRepresentation | BatchRepresentation;
41
+ /**
42
+ * Supported batch representation
43
+ */
44
+ type SupportedBatchCollectionRepresentation = RelatedListRecordCollectionRepresentation | RecordRepresentation;
45
+ /**
46
+ * merge the aggregate ui child responses into a single object representation
47
+ * @param response
48
+ * @param mergeFunc the function used to define how the records should be merged together
49
+ * @returns the merged record
50
+ */
51
+ export declare function mergeAggregateUiResponse<T>(response: AggregateResponse<T>, mergeFunc: (first: T, second: T) => SupportedAggregateRepresentation<T>): FetchResponse<SupportedAggregateRepresentation<T> | UiApiErrorResponse>;
52
+ export declare function buildAggregateUiUrl(params: UiApiParams, resourceRequest: ResourceRequest): string;
53
+ export declare function shouldUseAggregateUiForFields(fieldsArray: string, optionalFieldsArray: string, maxLengthPerChunk: number): boolean;
54
+ export declare function isSpanningRecord(fieldValue: null | string | number | boolean | RecordRepresentation): fieldValue is RecordRepresentation;
55
+ export declare function mergeRecordFields(first: RecordRepresentation, second: RecordRepresentation): RecordRepresentation;
56
+ export declare function mergeBatchRecordsFields(first: SupportedBatchRepresentation, second: SupportedBatchRepresentation, collectionMergeFunc: (first: SupportedBatchCollectionRepresentation, second: SupportedBatchCollectionRepresentation) => SupportedBatchCollectionRepresentation): SupportedBatchRepresentation;
57
+ /**
58
+ * Check to see if we have fields that are > max allowed characters long
59
+ * @param resourceRequest resource request to check
60
+ * @param endpoint Regular Expression to check the endpoint to aggregate
61
+ * @returns undefined if we should not aggregate. object if we should.
62
+ */
63
+ export declare function createAggregateBatchRequestInfo(resourceRequest: ResourceRequest, endpoint: RegExp): {
64
+ fieldCollection: ScopedFieldsCollection[];
65
+ optionalFieldCollection: ScopedFieldsCollection[];
66
+ } | undefined;
67
+ export declare function createAggregateUiRequest(resourceRequest: ResourceRequest, compositeRequest: CompositeRequest[]): ResourceRequest;
68
+ export declare function buildCompositeRequestByFields(referenceId: string, resourceRequest: ResourceRequest, recordsCompositeRequest: {
69
+ fieldCollection: ScopedFieldsCollection[] | undefined;
70
+ optionalFieldCollection: ScopedFieldsCollection[] | undefined;
71
+ }): CompositeRequest[];
72
+ 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,46 @@
1
+ {
2
+ "name": "@salesforce/lds-network-nimbus",
3
+ "version": "0.131.0",
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/types/main.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/types/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": "luvioBundlesize",
25
+ "clean": "rm -rf dist"
26
+ },
27
+ "dependencies": {
28
+ "@luvio/engine": "0.138.8-244.1",
29
+ "@salesforce/lds-instrumentation": "1.131.0-244.6",
30
+ "o11y": "242.1.0"
31
+ },
32
+ "devDependencies": {
33
+ "@salesforce/lds-adapters-uiapi": "1.131.0-244.6",
34
+ "@salesforce/nimbus-plugin-lds": "1.131.0-244.6"
35
+ },
36
+ "luvioBundlesize": [
37
+ {
38
+ "path": "./dist/main.js",
39
+ "maxSize": {
40
+ "none": "32 kB",
41
+ "min": "12.5 kB",
42
+ "compressed": "6.5 kB"
43
+ }
44
+ }
45
+ ]
46
+ }