@salesforce/lds-adapters-graphql 1.124.2 → 1.124.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/es/es2018/graphql-service.js +2098 -2098
  2. package/dist/{types → es/es2018/types}/src/__mocks__/@salesforce/lds-adapters-uiapi/sfdc/graphqlAdapters.d.ts +1 -1
  3. package/dist/{types → es/es2018/types}/src/configuration.d.ts +9 -9
  4. package/dist/{types → es/es2018/types}/src/custom/connection.d.ts +17 -17
  5. package/dist/{types → es/es2018/types}/src/custom/record.d.ts +46 -46
  6. package/dist/{types → es/es2018/types}/src/main.d.ts +20 -20
  7. package/dist/{types → es/es2018/types}/src/sfdc.d.ts +5 -5
  8. package/dist/{types → es/es2018/types}/src/type/Argument.d.ts +10 -10
  9. package/dist/{types → es/es2018/types}/src/type/CustomField.d.ts +4 -4
  10. package/dist/{types → es/es2018/types}/src/type/Document.d.ts +11 -11
  11. package/dist/{types → es/es2018/types}/src/type/Field.d.ts +4 -4
  12. package/dist/{types → es/es2018/types}/src/type/ObjectField.d.ts +2 -2
  13. package/dist/{types → es/es2018/types}/src/type/Operation.d.ts +5 -5
  14. package/dist/{types → es/es2018/types}/src/type/ScalarField.d.ts +2 -2
  15. package/dist/{types → es/es2018/types}/src/type/Selection.d.ts +23 -23
  16. package/dist/{types → es/es2018/types}/src/type/Variable.d.ts +4 -4
  17. package/dist/{types → es/es2018/types}/src/util/adapter.d.ts +16 -16
  18. package/dist/{types → es/es2018/types}/src/util/ast-to-string.d.ts +7 -7
  19. package/dist/{types → es/es2018/types}/src/util/equal.d.ts +7 -7
  20. package/dist/{types → es/es2018/types}/src/util/ingest.d.ts +18 -18
  21. package/dist/{types → es/es2018/types}/src/util/language.d.ts +20 -20
  22. package/dist/{types → es/es2018/types}/src/util/merge.d.ts +1 -1
  23. package/dist/{types → es/es2018/types}/src/util/read.d.ts +4 -4
  24. package/dist/{types → es/es2018/types}/src/util/serialize.d.ts +12 -12
  25. package/dist/{types → es/es2018/types}/src/util/sortUsingKey.d.ts +1 -1
  26. package/dist/{types → es/es2018/types}/src/util/synthetic-fields.d.ts +15 -15
  27. package/package.json +5 -5
  28. package/sfdc/index.d.ts +1 -1
  29. package/sfdc/index.js +2112 -2112
  30. package/dist/umd/es2018/graphql-service.js +0 -2164
  31. package/dist/umd/es5/graphql-service.js +0 -2182
@@ -10,2146 +10,2146 @@ import { astResolver } from '@luvio/graphql-parser';
10
10
  import { graphqlAdapterFactory } from '@salesforce/lds-adapters-uiapi';
11
11
  import { createIngestRecordWithFields, keyBuilderRecord } from '@salesforce/lds-adapters-uiapi';
12
12
 
13
- const { isArray } = Array;
14
- const { keys, freeze, create } = Object;
15
- const { hasOwnProperty } = Object.prototype;
13
+ const { isArray } = Array;
14
+ const { keys, freeze, create } = Object;
15
+ const { hasOwnProperty } = Object.prototype;
16
16
  const { parse, stringify } = JSON;
17
17
 
18
- function sortAndCopyUsingObjectKey(arr, key) {
19
- return [...arr].sort((a, b) => {
20
- const aKey = a[key];
21
- const bKey = b[key];
22
- if (aKey < bKey) {
23
- return -1;
24
- }
25
- if (aKey > bKey) {
26
- return 1;
27
- }
28
- return 0;
29
- });
18
+ function sortAndCopyUsingObjectKey(arr, key) {
19
+ return [...arr].sort((a, b) => {
20
+ const aKey = a[key];
21
+ const bKey = b[key];
22
+ if (aKey < bKey) {
23
+ return -1;
24
+ }
25
+ if (aKey > bKey) {
26
+ return 1;
27
+ }
28
+ return 0;
29
+ });
30
30
  }
31
31
 
32
- function untrustedIsObject(untrusted) {
33
- return typeof untrusted === 'object' && untrusted !== null && isArray(untrusted) === false;
34
- }
35
- function deepFreeze(value) {
36
- // No need to freeze primitives
37
- if (typeof value !== 'object' || value === null) {
38
- return;
39
- }
40
- if (isArray(value)) {
41
- for (let i = 0, len = value.length; i < len; i += 1) {
42
- deepFreeze(value[i]);
43
- }
44
- }
45
- else {
46
- const keys$1 = keys(value);
47
- for (let i = 0, len = keys$1.length; i < len; i += 1) {
48
- const v = value[keys$1[i]];
49
- deepFreeze(v);
50
- }
51
- }
52
- return freeze(value);
53
- }
54
- /**
55
- * A deterministic JSON stringify implementation. Heavily adapted from https://github.com/epoberezkin/fast-json-stable-stringify.
56
- * This is needed because insertion order for JSON.stringify(object) affects output:
57
- * JSON.stringify({a: 1, b: 2})
58
- * "{"a":1,"b":2}"
59
- * JSON.stringify({b: 2, a: 1})
60
- * "{"b":2,"a":1}"
61
- * @param data Data to be JSON-stringified.
62
- * @returns JSON.stringified value with consistent ordering of keys.
63
- */
64
- function stableJSONStringify(node) {
65
- // This is for Date values.
66
- if (node && node.toJSON && typeof node.toJSON === 'function') {
67
- // eslint-disable-next-line no-param-reassign
68
- node = node.toJSON();
69
- }
70
- if (node === undefined) {
71
- return '';
72
- }
73
- if (typeof node === 'number') {
74
- return isFinite(node) ? '' + node : 'null';
75
- }
76
- if (typeof node !== 'object') {
77
- return stringify(node);
78
- }
79
- let i;
80
- let out;
81
- if (isArray(node)) {
82
- node.sort();
83
- out = '[';
84
- for (i = 0; i < node.length; i++) {
85
- if (i) {
86
- out += ',';
87
- }
88
- out += stableJSONStringify(node[i]) || 'null';
89
- }
90
- return out + ']';
91
- }
92
- if (node === null) {
93
- return 'null';
94
- }
95
- const keys$1 = keys(node).sort();
96
- out = '';
97
- for (i = 0; i < keys$1.length; i++) {
98
- const key = keys$1[i];
99
- const value = stableJSONStringify(node[key]);
100
- if (!value) {
101
- continue;
102
- }
103
- if (out) {
104
- out += ',';
105
- }
106
- out += key + ':' + value;
107
- }
108
- return '{' + out + '}';
109
- }
110
- const namespace = 'GraphQL';
32
+ function untrustedIsObject(untrusted) {
33
+ return typeof untrusted === 'object' && untrusted !== null && isArray(untrusted) === false;
34
+ }
35
+ function deepFreeze(value) {
36
+ // No need to freeze primitives
37
+ if (typeof value !== 'object' || value === null) {
38
+ return;
39
+ }
40
+ if (isArray(value)) {
41
+ for (let i = 0, len = value.length; i < len; i += 1) {
42
+ deepFreeze(value[i]);
43
+ }
44
+ }
45
+ else {
46
+ const keys$1 = keys(value);
47
+ for (let i = 0, len = keys$1.length; i < len; i += 1) {
48
+ const v = value[keys$1[i]];
49
+ deepFreeze(v);
50
+ }
51
+ }
52
+ return freeze(value);
53
+ }
54
+ /**
55
+ * A deterministic JSON stringify implementation. Heavily adapted from https://github.com/epoberezkin/fast-json-stable-stringify.
56
+ * This is needed because insertion order for JSON.stringify(object) affects output:
57
+ * JSON.stringify({a: 1, b: 2})
58
+ * "{"a":1,"b":2}"
59
+ * JSON.stringify({b: 2, a: 1})
60
+ * "{"b":2,"a":1}"
61
+ * @param data Data to be JSON-stringified.
62
+ * @returns JSON.stringified value with consistent ordering of keys.
63
+ */
64
+ function stableJSONStringify(node) {
65
+ // This is for Date values.
66
+ if (node && node.toJSON && typeof node.toJSON === 'function') {
67
+ // eslint-disable-next-line no-param-reassign
68
+ node = node.toJSON();
69
+ }
70
+ if (node === undefined) {
71
+ return '';
72
+ }
73
+ if (typeof node === 'number') {
74
+ return isFinite(node) ? '' + node : 'null';
75
+ }
76
+ if (typeof node !== 'object') {
77
+ return stringify(node);
78
+ }
79
+ let i;
80
+ let out;
81
+ if (isArray(node)) {
82
+ node.sort();
83
+ out = '[';
84
+ for (i = 0; i < node.length; i++) {
85
+ if (i) {
86
+ out += ',';
87
+ }
88
+ out += stableJSONStringify(node[i]) || 'null';
89
+ }
90
+ return out + ']';
91
+ }
92
+ if (node === null) {
93
+ return 'null';
94
+ }
95
+ const keys$1 = keys(node).sort();
96
+ out = '';
97
+ for (i = 0; i < keys$1.length; i++) {
98
+ const key = keys$1[i];
99
+ const value = stableJSONStringify(node[key]);
100
+ if (!value) {
101
+ continue;
102
+ }
103
+ if (out) {
104
+ out += ',';
105
+ }
106
+ out += key + ':' + value;
107
+ }
108
+ return '{' + out + '}';
109
+ }
110
+ const namespace = 'GraphQL';
111
111
  const representationName = 'graphql';
112
112
 
113
- function serialize$1(args) {
114
- return serializeArgs(args, { render: false });
115
- }
116
- function render$1(args, variables) {
117
- return serializeArgs(args, { render: true, variables });
118
- }
119
- function serializeArgs(args, option) {
120
- const sortedArgs = option.render === true ? sortAndCopyUsingObjectKey(args, 'name') : args;
121
- let str = '';
122
- for (let i = 0, len = sortedArgs.length; i < len; i += 1) {
123
- str = `${str}${serializeArgumentNode(sortedArgs[i], option)}`;
124
- if (len > 1 && i < len - 1) {
125
- str = `${str},`;
126
- }
127
- }
128
- return str;
129
- }
130
- function serializeArgumentValueNode(valueDefinition, option) {
131
- const { kind } = valueDefinition;
132
- switch (kind) {
133
- case 'ObjectValue':
134
- return serializeAndSortObjectValueNode(valueDefinition, option);
135
- case 'ListValue':
136
- return serializeAndSortListValueNode(valueDefinition, option);
137
- case 'Variable':
138
- return serializeVariableNode$1(valueDefinition, option);
139
- default:
140
- return serializeValueNode(valueDefinition);
141
- }
142
- }
143
- function serializeVariableNode$1(literalValueNode, option) {
144
- if (option.render === false) {
145
- return `$${literalValueNode.name}`;
146
- }
147
- return `${serializeVariableValue(option.variables[literalValueNode.name])}`;
148
- }
149
- function serializeVariableValue(value) {
150
- return stableJSONStringify(value);
151
- }
152
- function serializeAndSortListValueNode(objectValueDefinition, option) {
153
- const { values } = objectValueDefinition;
154
- const str = [];
155
- const sorted = option.render === true ? sortAndCopyUsingObjectKey(values, 'value') : values;
156
- for (let i = 0, len = sorted.length; i < len; i += 1) {
157
- str.push(serializeArgumentValueNode(sorted[i], option));
158
- }
159
- return `[${str.join(',')}]`;
160
- }
161
- function serializeAndSortObjectValueNode(objectValueDefinition, option) {
162
- const { fields } = objectValueDefinition;
163
- let str = '';
164
- const fieldKeys = keys(fields).sort();
165
- for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
166
- const fieldKey = fieldKeys[i];
167
- str = `${str}${fieldKey}:${serializeArgumentValueNode(fields[fieldKey], option)}`;
168
- if (len > 1 && i < len - 1) {
169
- str = `${str},`;
170
- }
171
- }
172
- return `{${str}}`;
173
- }
174
- function serializeArgumentNode(arg, option) {
175
- const { name, value } = arg;
176
- return `${name}:${serializeArgumentValueNode(value, option)}`;
113
+ function serialize$1(args) {
114
+ return serializeArgs(args, { render: false });
115
+ }
116
+ function render$1(args, variables) {
117
+ return serializeArgs(args, { render: true, variables });
118
+ }
119
+ function serializeArgs(args, option) {
120
+ const sortedArgs = option.render === true ? sortAndCopyUsingObjectKey(args, 'name') : args;
121
+ let str = '';
122
+ for (let i = 0, len = sortedArgs.length; i < len; i += 1) {
123
+ str = `${str}${serializeArgumentNode(sortedArgs[i], option)}`;
124
+ if (len > 1 && i < len - 1) {
125
+ str = `${str},`;
126
+ }
127
+ }
128
+ return str;
129
+ }
130
+ function serializeArgumentValueNode(valueDefinition, option) {
131
+ const { kind } = valueDefinition;
132
+ switch (kind) {
133
+ case 'ObjectValue':
134
+ return serializeAndSortObjectValueNode(valueDefinition, option);
135
+ case 'ListValue':
136
+ return serializeAndSortListValueNode(valueDefinition, option);
137
+ case 'Variable':
138
+ return serializeVariableNode$1(valueDefinition, option);
139
+ default:
140
+ return serializeValueNode(valueDefinition);
141
+ }
142
+ }
143
+ function serializeVariableNode$1(literalValueNode, option) {
144
+ if (option.render === false) {
145
+ return `$${literalValueNode.name}`;
146
+ }
147
+ return `${serializeVariableValue(option.variables[literalValueNode.name])}`;
148
+ }
149
+ function serializeVariableValue(value) {
150
+ return stableJSONStringify(value);
151
+ }
152
+ function serializeAndSortListValueNode(objectValueDefinition, option) {
153
+ const { values } = objectValueDefinition;
154
+ const str = [];
155
+ const sorted = option.render === true ? sortAndCopyUsingObjectKey(values, 'value') : values;
156
+ for (let i = 0, len = sorted.length; i < len; i += 1) {
157
+ str.push(serializeArgumentValueNode(sorted[i], option));
158
+ }
159
+ return `[${str.join(',')}]`;
160
+ }
161
+ function serializeAndSortObjectValueNode(objectValueDefinition, option) {
162
+ const { fields } = objectValueDefinition;
163
+ let str = '';
164
+ const fieldKeys = keys(fields).sort();
165
+ for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
166
+ const fieldKey = fieldKeys[i];
167
+ str = `${str}${fieldKey}:${serializeArgumentValueNode(fields[fieldKey], option)}`;
168
+ if (len > 1 && i < len - 1) {
169
+ str = `${str},`;
170
+ }
171
+ }
172
+ return `{${str}}`;
173
+ }
174
+ function serializeArgumentNode(arg, option) {
175
+ const { name, value } = arg;
176
+ return `${name}:${serializeArgumentValueNode(value, option)}`;
177
177
  }
178
178
 
179
- function render(sel, variables) {
180
- return serializeField(sel, { render: true, variables });
181
- }
182
- function serializeField(sel, option) {
183
- const { name: fieldName } = sel;
184
- if (sel.kind === 'ScalarFieldSelection') {
185
- return fieldName;
186
- }
187
- const { arguments: selectionArguments } = sel;
188
- if (selectionArguments === undefined || selectionArguments.length === 0) {
189
- return fieldName;
190
- }
191
- return `${fieldName}(${option.render === true
192
- ? render$1(selectionArguments, option.variables)
193
- : serialize$1(selectionArguments)})`;
179
+ function render(sel, variables) {
180
+ return serializeField(sel, { render: true, variables });
181
+ }
182
+ function serializeField(sel, option) {
183
+ const { name: fieldName } = sel;
184
+ if (sel.kind === 'ScalarFieldSelection') {
185
+ return fieldName;
186
+ }
187
+ const { arguments: selectionArguments } = sel;
188
+ if (selectionArguments === undefined || selectionArguments.length === 0) {
189
+ return fieldName;
190
+ }
191
+ return `${fieldName}(${option.render === true
192
+ ? render$1(selectionArguments, option.variables)
193
+ : serialize$1(selectionArguments)})`;
194
194
  }
195
195
 
196
- function readScalarFieldSelection(builder, source, fieldName, sink) {
197
- const gqlData = source[fieldName];
198
- if (gqlData !== undefined && gqlData !== null && gqlData.__ref !== undefined) {
199
- if (process.env.NODE_ENV !== 'production') {
200
- throw new Error(`Scalar requested at "${fieldName}" but is instead an object at "${gqlData.__ref}"`);
201
- }
202
- }
203
- builder.readScalar(fieldName, source, sink);
196
+ function readScalarFieldSelection(builder, source, fieldName, sink) {
197
+ const gqlData = source[fieldName];
198
+ if (gqlData !== undefined && gqlData !== null && gqlData.__ref !== undefined) {
199
+ if (process.env.NODE_ENV !== 'production') {
200
+ throw new Error(`Scalar requested at "${fieldName}" but is instead an object at "${gqlData.__ref}"`);
201
+ }
202
+ }
203
+ builder.readScalar(fieldName, source, sink);
204
204
  }
205
205
 
206
- const CUSTOM_FIELD_NODE_TYPE = 'Record';
207
- const RECORD_DEFAULT_FIELD_VALUES = ['value', 'displayValue'];
208
- function collectObjectFieldSelection(data) {
209
- return {
210
- value: data.value,
211
- displayValue: data.displayValue,
212
- };
213
- }
214
- function childTypeIsChildRelationships(sel, _data) {
215
- return sel.type === CONNECTION_NODE_TYPE;
216
- }
217
- function childTypeIsSpanningGqlRecord(sel, _data) {
218
- return sel.type === CUSTOM_FIELD_NODE_TYPE;
219
- }
220
- function convertAstToTrie(ast) {
221
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
222
- const children = {};
223
- const trie = {
224
- name: ast.name,
225
- children,
226
- };
227
- for (let i = 0, len = selections.length; i < len; i += 1) {
228
- const sel = getLuvioFieldNodeSelection(selections[i]);
229
- const { name: selName, kind } = sel;
230
- switch (kind) {
231
- case 'ObjectFieldSelection': {
232
- children[selName] = {
233
- name: selName,
234
- children: {},
235
- };
236
- break;
237
- }
238
- case 'CustomFieldSelection': {
239
- children[selName] = convertAstToTrie(sel);
240
- break;
241
- }
242
- }
243
- }
244
- return trie;
245
- }
246
- function formatSpanningCustomFieldSelection(sel, data) {
247
- if (data === null) {
248
- return {
249
- value: {
250
- displayValue: null,
251
- value: null,
252
- },
253
- trie: convertAstToTrie(sel),
254
- };
255
- }
256
- const { recordRepresentation, fieldsTrie } = convertToRecordRepresentation(sel, data);
257
- return {
258
- trie: fieldsTrie,
259
- value: {
260
- displayValue: data.DisplayValue,
261
- value: recordRepresentation,
262
- },
263
- };
264
- }
265
- function convertToRecordRepresentation(ast, record) {
266
- const { Id, WeakEtag, ApiName, LastModifiedById, LastModifiedDate, SystemModstamp, ldsRecordTypeId, } = record;
267
- const { luvioSelections } = ast;
268
- if (luvioSelections === undefined) {
269
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
270
- throw new Error('Undefined selections');
271
- }
272
- const trieChildren = {};
273
- const trie = {
274
- name: ApiName,
275
- children: trieChildren,
276
- };
277
- const childRelationships = {};
278
- const fieldsBag = {};
279
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
280
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
281
- const { name: fieldName, alias } = sel;
282
- const propertyName = alias === undefined ? fieldName : alias;
283
- const data = record[propertyName];
284
- switch (sel.kind) {
285
- case 'ObjectFieldSelection': {
286
- trieChildren[fieldName] = {
287
- name: fieldName,
288
- children: {},
289
- };
290
- fieldsBag[fieldName] = collectObjectFieldSelection(data);
291
- break;
292
- }
293
- case 'CustomFieldSelection': {
294
- if (childTypeIsSpanningGqlRecord(sel)) {
295
- const { value, trie } = formatSpanningCustomFieldSelection(sel, data);
296
- trieChildren[fieldName] = trie;
297
- fieldsBag[fieldName] = value;
298
- }
299
- else if (childTypeIsChildRelationships(sel)) {
300
- childRelationships[fieldName] = {
301
- ast: sel,
302
- data: data,
303
- };
304
- }
305
- break;
306
- }
307
- }
308
- }
309
- const rep = {
310
- apiName: ApiName,
311
- eTag: '',
312
- lastModifiedById: LastModifiedById.value,
313
- lastModifiedDate: LastModifiedDate.value,
314
- systemModstamp: SystemModstamp.value,
315
- recordTypeId: ldsRecordTypeId === null ? null : ldsRecordTypeId.value,
316
- recordTypeInfo: null,
317
- childRelationships: {},
318
- id: Id,
319
- weakEtag: WeakEtag,
320
- fields: fieldsBag,
321
- };
322
- return {
323
- recordRepresentation: rep,
324
- fieldsTrie: trie,
325
- childRelationships,
326
- };
327
- }
328
- const defaultRecordFieldsFragmentName = 'defaultRecordFields';
329
- const defaultRecordFieldsFragment = `fragment ${defaultRecordFieldsFragmentName} on Record { __typename, ApiName, WeakEtag, Id, DisplayValue, SystemModstamp { value } LastModifiedById { value } LastModifiedDate { value } ldsRecordTypeId: RecordTypeId(fallback: true) { value } }`;
330
- function getChildRelationshipsKey(recordKey, propertyName) {
331
- return `${recordKey}__childRelationships__${propertyName}`;
332
- }
333
- const createIngest$4 = (ast, variables) => {
334
- return (data, path, luvio, store, timestamp) => {
335
- const { recordRepresentation, fieldsTrie, childRelationships } = convertToRecordRepresentation(ast, data);
336
- const ingestRecord = createIngestRecordWithFields(fieldsTrie, {
337
- name: recordRepresentation.apiName,
338
- children: {},
339
- });
340
- const recordIngest = ingestRecord(recordRepresentation, path, luvio, store, timestamp);
341
- const recordKey = recordIngest.__ref;
342
- const childRelationshipKeys = Object.keys(childRelationships);
343
- for (let i = 0, len = childRelationshipKeys.length; i < len; i += 1) {
344
- const propertyName = childRelationshipKeys[i];
345
- const childRelationship = childRelationships[propertyName];
346
- const { ast: childRelationshipAst, data: childRelationshipData } = childRelationship;
347
- const fullPath = getChildRelationshipsKey(recordKey, propertyName);
348
- createIngest$1(childRelationshipAst, fullPath, variables)(childRelationshipData, {
349
- parent: {
350
- data,
351
- key: recordKey,
352
- existing: undefined,
353
- },
354
- fullPath: fullPath,
355
- propertyName: propertyName,
356
- }, luvio, store, timestamp);
357
- }
358
- return recordIngest;
359
- };
360
- };
361
- const recordProperties = {
362
- Id: {
363
- propertyName: 'id',
364
- },
365
- ApiName: {
366
- propertyName: 'apiName',
367
- },
368
- };
369
- function getNonSpanningField(sel, builder, source) {
370
- const sink = {};
371
- const { luvioSelections } = sel;
372
- if (luvioSelections === undefined) {
373
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
374
- throw new Error('Empty selections not supported');
375
- }
376
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
377
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
378
- const { kind } = sel;
379
- const name = sel.name;
380
- builder.enterPath(name);
381
- if (kind !== 'ScalarFieldSelection') {
382
- if (process.env.NODE_ENV !== 'production') {
383
- throw new Error(`Unexpected kind "${kind}"`);
384
- }
385
- }
386
- builder.assignScalar(name, sink, source[name]);
387
- builder.exitPath();
388
- }
389
- return sink;
390
- }
391
- function getCustomSelection(luvio, selection, builder, options, variables) {
392
- const { type } = selection;
393
- switch (type) {
394
- case 'Record':
395
- return readRecordRepresentation(luvio, selection, builder, options, variables);
396
- }
397
- }
398
- function getScalarValue(selectionName, state) {
399
- if (selectionName === 'DisplayValue') {
400
- const { parentFieldValue } = state;
401
- if (parentFieldValue === undefined) {
402
- if (process.env.NODE_ENV !== 'production') {
403
- throw new Error('Unable to calculate DisplayValue');
404
- }
405
- else {
406
- return undefined;
407
- }
408
- }
409
- return parentFieldValue.displayValue;
410
- }
411
- const assignment = recordProperties[selectionName];
412
- if (assignment === undefined) {
413
- if (process.env.NODE_ENV !== 'production') {
414
- throw new Error(`Unknown assignment for ScalarFieldSelection at property "${selectionName}"`);
415
- }
416
- }
417
- return state.source[assignment.propertyName];
418
- }
419
- function assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables) {
420
- const key = getChildRelationshipsKey(recordKey, propertyName);
421
- const resolved = resolveKey(builder, key);
422
- if (resolved === undefined) {
423
- return;
424
- }
425
- const data = createRead$2(luvio, sel, variables)(resolved.value, builder);
426
- builder.assignNonScalar(sink, propertyName, data);
427
- }
428
- function assignSelection(luvio, selection, builder, state, variables) {
429
- const sel = getLuvioFieldNodeSelection(selection);
430
- const { name: selectionName, kind, alias } = sel;
431
- const propertyName = alias === undefined ? selectionName : alias;
432
- const { source, sink } = state;
433
- const { fields } = source;
434
- builder.enterPath(selectionName);
435
- switch (kind) {
436
- case 'ScalarFieldSelection': {
437
- builder.assignScalar(propertyName, sink, getScalarValue(selectionName, state));
438
- break;
439
- }
440
- case 'ObjectFieldSelection': {
441
- // regular field, not spanning
442
- const field = propertyLookup(builder, selectionName, fields);
443
- if (field.state === PropertyLookupResultState.Missing) {
444
- break;
445
- }
446
- const resolved = resolveLink(builder, field.value);
447
- if (resolved === undefined) {
448
- break;
449
- }
450
- const data = getNonSpanningField(sel, builder, resolved.value);
451
- builder.assignNonScalar(sink, propertyName, data);
452
- break;
453
- }
454
- case 'CustomFieldSelection': {
455
- if (sel.type === 'Connection') {
456
- const recordKey = keyBuilderRecord(luvio, {
457
- recordId: state.source.id,
458
- });
459
- assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables);
460
- }
461
- else {
462
- const field = fields[selectionName];
463
- const resolvedParentFieldValue = resolveLink(builder, field);
464
- if (resolvedParentFieldValue === undefined) {
465
- break;
466
- }
467
- const { value: spanningFieldResult } = resolvedParentFieldValue;
468
- const { value: spanningFieldValue } = spanningFieldResult;
469
- if (spanningFieldValue === null || typeof spanningFieldValue !== 'object') {
470
- sink[propertyName] = null;
471
- break;
472
- }
473
- const resolvedSpanningRecordValue = resolveLink(builder, spanningFieldValue);
474
- if (resolvedSpanningRecordValue === undefined) {
475
- break;
476
- }
477
- const data = getCustomSelection(luvio, sel, builder, {
478
- source: resolvedSpanningRecordValue.value,
479
- parentFieldValue: spanningFieldResult,
480
- }, variables);
481
- builder.assignNonScalar(sink, propertyName, data);
482
- }
483
- }
484
- }
485
- builder.exitPath();
486
- }
487
- function readRecordRepresentation(luvio, ast, builder, options, variables) {
488
- const { luvioSelections } = ast;
489
- if (luvioSelections === undefined) {
490
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
491
- throw new Error('Empty selections not supported');
492
- }
493
- const sink = {};
494
- const state = {
495
- source: options.source,
496
- sink,
497
- parentFieldValue: options.parentFieldValue,
498
- };
499
- for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
500
- assignSelection(luvio, luvioSelections[i], builder, state, variables);
501
- }
502
- return sink;
503
- }
504
- const createRead$3 = (luvio, ast, variables) => {
505
- return (data, builder) => {
506
- return readRecordRepresentation(luvio, ast, builder, {
507
- source: data,
508
- parentFieldValue: undefined,
509
- }, variables);
510
- };
206
+ const CUSTOM_FIELD_NODE_TYPE = 'Record';
207
+ const RECORD_DEFAULT_FIELD_VALUES = ['value', 'displayValue'];
208
+ function collectObjectFieldSelection(data) {
209
+ return {
210
+ value: data.value,
211
+ displayValue: data.displayValue,
212
+ };
213
+ }
214
+ function childTypeIsChildRelationships(sel, _data) {
215
+ return sel.type === CONNECTION_NODE_TYPE;
216
+ }
217
+ function childTypeIsSpanningGqlRecord(sel, _data) {
218
+ return sel.type === CUSTOM_FIELD_NODE_TYPE;
219
+ }
220
+ function convertAstToTrie(ast) {
221
+ const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
222
+ const children = {};
223
+ const trie = {
224
+ name: ast.name,
225
+ children,
226
+ };
227
+ for (let i = 0, len = selections.length; i < len; i += 1) {
228
+ const sel = getLuvioFieldNodeSelection(selections[i]);
229
+ const { name: selName, kind } = sel;
230
+ switch (kind) {
231
+ case 'ObjectFieldSelection': {
232
+ children[selName] = {
233
+ name: selName,
234
+ children: {},
235
+ };
236
+ break;
237
+ }
238
+ case 'CustomFieldSelection': {
239
+ children[selName] = convertAstToTrie(sel);
240
+ break;
241
+ }
242
+ }
243
+ }
244
+ return trie;
245
+ }
246
+ function formatSpanningCustomFieldSelection(sel, data) {
247
+ if (data === null) {
248
+ return {
249
+ value: {
250
+ displayValue: null,
251
+ value: null,
252
+ },
253
+ trie: convertAstToTrie(sel),
254
+ };
255
+ }
256
+ const { recordRepresentation, fieldsTrie } = convertToRecordRepresentation(sel, data);
257
+ return {
258
+ trie: fieldsTrie,
259
+ value: {
260
+ displayValue: data.DisplayValue,
261
+ value: recordRepresentation,
262
+ },
263
+ };
264
+ }
265
+ function convertToRecordRepresentation(ast, record) {
266
+ const { Id, WeakEtag, ApiName, LastModifiedById, LastModifiedDate, SystemModstamp, ldsRecordTypeId, } = record;
267
+ const { luvioSelections } = ast;
268
+ if (luvioSelections === undefined) {
269
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
270
+ throw new Error('Undefined selections');
271
+ }
272
+ const trieChildren = {};
273
+ const trie = {
274
+ name: ApiName,
275
+ children: trieChildren,
276
+ };
277
+ const childRelationships = {};
278
+ const fieldsBag = {};
279
+ for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
280
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
281
+ const { name: fieldName, alias } = sel;
282
+ const propertyName = alias === undefined ? fieldName : alias;
283
+ const data = record[propertyName];
284
+ switch (sel.kind) {
285
+ case 'ObjectFieldSelection': {
286
+ trieChildren[fieldName] = {
287
+ name: fieldName,
288
+ children: {},
289
+ };
290
+ fieldsBag[fieldName] = collectObjectFieldSelection(data);
291
+ break;
292
+ }
293
+ case 'CustomFieldSelection': {
294
+ if (childTypeIsSpanningGqlRecord(sel)) {
295
+ const { value, trie } = formatSpanningCustomFieldSelection(sel, data);
296
+ trieChildren[fieldName] = trie;
297
+ fieldsBag[fieldName] = value;
298
+ }
299
+ else if (childTypeIsChildRelationships(sel)) {
300
+ childRelationships[fieldName] = {
301
+ ast: sel,
302
+ data: data,
303
+ };
304
+ }
305
+ break;
306
+ }
307
+ }
308
+ }
309
+ const rep = {
310
+ apiName: ApiName,
311
+ eTag: '',
312
+ lastModifiedById: LastModifiedById.value,
313
+ lastModifiedDate: LastModifiedDate.value,
314
+ systemModstamp: SystemModstamp.value,
315
+ recordTypeId: ldsRecordTypeId === null ? null : ldsRecordTypeId.value,
316
+ recordTypeInfo: null,
317
+ childRelationships: {},
318
+ id: Id,
319
+ weakEtag: WeakEtag,
320
+ fields: fieldsBag,
321
+ };
322
+ return {
323
+ recordRepresentation: rep,
324
+ fieldsTrie: trie,
325
+ childRelationships,
326
+ };
327
+ }
328
+ const defaultRecordFieldsFragmentName = 'defaultRecordFields';
329
+ const defaultRecordFieldsFragment = `fragment ${defaultRecordFieldsFragmentName} on Record { __typename, ApiName, WeakEtag, Id, DisplayValue, SystemModstamp { value } LastModifiedById { value } LastModifiedDate { value } ldsRecordTypeId: RecordTypeId(fallback: true) { value } }`;
330
+ function getChildRelationshipsKey(recordKey, propertyName) {
331
+ return `${recordKey}__childRelationships__${propertyName}`;
332
+ }
333
+ const createIngest$4 = (ast, variables) => {
334
+ return (data, path, luvio, store, timestamp) => {
335
+ const { recordRepresentation, fieldsTrie, childRelationships } = convertToRecordRepresentation(ast, data);
336
+ const ingestRecord = createIngestRecordWithFields(fieldsTrie, {
337
+ name: recordRepresentation.apiName,
338
+ children: {},
339
+ });
340
+ const recordIngest = ingestRecord(recordRepresentation, path, luvio, store, timestamp);
341
+ const recordKey = recordIngest.__ref;
342
+ const childRelationshipKeys = Object.keys(childRelationships);
343
+ for (let i = 0, len = childRelationshipKeys.length; i < len; i += 1) {
344
+ const propertyName = childRelationshipKeys[i];
345
+ const childRelationship = childRelationships[propertyName];
346
+ const { ast: childRelationshipAst, data: childRelationshipData } = childRelationship;
347
+ const fullPath = getChildRelationshipsKey(recordKey, propertyName);
348
+ createIngest$1(childRelationshipAst, fullPath, variables)(childRelationshipData, {
349
+ parent: {
350
+ data,
351
+ key: recordKey,
352
+ existing: undefined,
353
+ },
354
+ fullPath: fullPath,
355
+ propertyName: propertyName,
356
+ }, luvio, store, timestamp);
357
+ }
358
+ return recordIngest;
359
+ };
360
+ };
361
+ const recordProperties = {
362
+ Id: {
363
+ propertyName: 'id',
364
+ },
365
+ ApiName: {
366
+ propertyName: 'apiName',
367
+ },
368
+ };
369
+ function getNonSpanningField(sel, builder, source) {
370
+ const sink = {};
371
+ const { luvioSelections } = sel;
372
+ if (luvioSelections === undefined) {
373
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
374
+ throw new Error('Empty selections not supported');
375
+ }
376
+ for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
377
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
378
+ const { kind } = sel;
379
+ const name = sel.name;
380
+ builder.enterPath(name);
381
+ if (kind !== 'ScalarFieldSelection') {
382
+ if (process.env.NODE_ENV !== 'production') {
383
+ throw new Error(`Unexpected kind "${kind}"`);
384
+ }
385
+ }
386
+ builder.assignScalar(name, sink, source[name]);
387
+ builder.exitPath();
388
+ }
389
+ return sink;
390
+ }
391
+ function getCustomSelection(luvio, selection, builder, options, variables) {
392
+ const { type } = selection;
393
+ switch (type) {
394
+ case 'Record':
395
+ return readRecordRepresentation(luvio, selection, builder, options, variables);
396
+ }
397
+ }
398
+ function getScalarValue(selectionName, state) {
399
+ if (selectionName === 'DisplayValue') {
400
+ const { parentFieldValue } = state;
401
+ if (parentFieldValue === undefined) {
402
+ if (process.env.NODE_ENV !== 'production') {
403
+ throw new Error('Unable to calculate DisplayValue');
404
+ }
405
+ else {
406
+ return undefined;
407
+ }
408
+ }
409
+ return parentFieldValue.displayValue;
410
+ }
411
+ const assignment = recordProperties[selectionName];
412
+ if (assignment === undefined) {
413
+ if (process.env.NODE_ENV !== 'production') {
414
+ throw new Error(`Unknown assignment for ScalarFieldSelection at property "${selectionName}"`);
415
+ }
416
+ }
417
+ return state.source[assignment.propertyName];
418
+ }
419
+ function assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables) {
420
+ const key = getChildRelationshipsKey(recordKey, propertyName);
421
+ const resolved = resolveKey(builder, key);
422
+ if (resolved === undefined) {
423
+ return;
424
+ }
425
+ const data = createRead$2(luvio, sel, variables)(resolved.value, builder);
426
+ builder.assignNonScalar(sink, propertyName, data);
427
+ }
428
+ function assignSelection(luvio, selection, builder, state, variables) {
429
+ const sel = getLuvioFieldNodeSelection(selection);
430
+ const { name: selectionName, kind, alias } = sel;
431
+ const propertyName = alias === undefined ? selectionName : alias;
432
+ const { source, sink } = state;
433
+ const { fields } = source;
434
+ builder.enterPath(selectionName);
435
+ switch (kind) {
436
+ case 'ScalarFieldSelection': {
437
+ builder.assignScalar(propertyName, sink, getScalarValue(selectionName, state));
438
+ break;
439
+ }
440
+ case 'ObjectFieldSelection': {
441
+ // regular field, not spanning
442
+ const field = propertyLookup(builder, selectionName, fields);
443
+ if (field.state === PropertyLookupResultState.Missing) {
444
+ break;
445
+ }
446
+ const resolved = resolveLink(builder, field.value);
447
+ if (resolved === undefined) {
448
+ break;
449
+ }
450
+ const data = getNonSpanningField(sel, builder, resolved.value);
451
+ builder.assignNonScalar(sink, propertyName, data);
452
+ break;
453
+ }
454
+ case 'CustomFieldSelection': {
455
+ if (sel.type === 'Connection') {
456
+ const recordKey = keyBuilderRecord(luvio, {
457
+ recordId: state.source.id,
458
+ });
459
+ assignConnectionSelection(luvio, builder, sink, sel, recordKey, propertyName, variables);
460
+ }
461
+ else {
462
+ const field = fields[selectionName];
463
+ const resolvedParentFieldValue = resolveLink(builder, field);
464
+ if (resolvedParentFieldValue === undefined) {
465
+ break;
466
+ }
467
+ const { value: spanningFieldResult } = resolvedParentFieldValue;
468
+ const { value: spanningFieldValue } = spanningFieldResult;
469
+ if (spanningFieldValue === null || typeof spanningFieldValue !== 'object') {
470
+ sink[propertyName] = null;
471
+ break;
472
+ }
473
+ const resolvedSpanningRecordValue = resolveLink(builder, spanningFieldValue);
474
+ if (resolvedSpanningRecordValue === undefined) {
475
+ break;
476
+ }
477
+ const data = getCustomSelection(luvio, sel, builder, {
478
+ source: resolvedSpanningRecordValue.value,
479
+ parentFieldValue: spanningFieldResult,
480
+ }, variables);
481
+ builder.assignNonScalar(sink, propertyName, data);
482
+ }
483
+ }
484
+ }
485
+ builder.exitPath();
486
+ }
487
+ function readRecordRepresentation(luvio, ast, builder, options, variables) {
488
+ const { luvioSelections } = ast;
489
+ if (luvioSelections === undefined) {
490
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
491
+ throw new Error('Empty selections not supported');
492
+ }
493
+ const sink = {};
494
+ const state = {
495
+ source: options.source,
496
+ sink,
497
+ parentFieldValue: options.parentFieldValue,
498
+ };
499
+ for (let i = 0, len = luvioSelections.length; i < len; i += 1) {
500
+ assignSelection(luvio, luvioSelections[i], builder, state, variables);
501
+ }
502
+ return sink;
503
+ }
504
+ const createRead$3 = (luvio, ast, variables) => {
505
+ return (data, builder) => {
506
+ return readRecordRepresentation(luvio, ast, builder, {
507
+ source: data,
508
+ parentFieldValue: undefined,
509
+ }, variables);
510
+ };
511
511
  };
512
512
 
513
- const createIngest$3 = (ast, variables) => {
514
- const { type } = ast;
515
- switch (type) {
516
- case CUSTOM_FIELD_NODE_TYPE:
517
- return createIngest$4(ast, variables);
518
- case CONNECTION_NODE_TYPE:
519
- return createIngest$1(ast, keyBuilder(ast, variables), variables);
520
- }
521
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
522
- throw new Error(`Unsupported type: "${type}"`);
513
+ const createIngest$3 = (ast, variables) => {
514
+ const { type } = ast;
515
+ switch (type) {
516
+ case CUSTOM_FIELD_NODE_TYPE:
517
+ return createIngest$4(ast, variables);
518
+ case CONNECTION_NODE_TYPE:
519
+ return createIngest$1(ast, keyBuilder(ast, variables), variables);
520
+ }
521
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
522
+ throw new Error(`Unsupported type: "${type}"`);
523
523
  };
524
524
 
525
- function merge(existing, incoming) {
526
- if (existing === undefined) {
527
- return incoming;
528
- }
529
- // Merge existing and incoming values together
530
- return {
531
- ...existing,
532
- ...incoming,
533
- };
525
+ function merge(existing, incoming) {
526
+ if (existing === undefined) {
527
+ return incoming;
528
+ }
529
+ // Merge existing and incoming values together
530
+ return {
531
+ ...existing,
532
+ ...incoming,
533
+ };
534
534
  }
535
535
 
536
- function resolveValue(ast, variables, source) {
537
- const { alias } = ast;
538
- const propertyName = render(ast, variables);
539
- if (process.env.NODE_ENV !== 'production') {
540
- if (alias !== undefined && alias in source) {
541
- throw new Error(`Invalid alias "${alias}" passed to "equal" function. All aliases need to be normalized before calling equal`);
542
- }
543
- }
544
- return source[propertyName];
545
- }
546
- function linkEquals(ast, variables, existing, incoming) {
547
- const value = resolveValue(ast, variables, existing);
548
- if (value === undefined) {
549
- return false;
550
- }
551
- const incomingLink = resolveValue(ast, variables, incoming);
552
- if (process.env.NODE_ENV !== 'production') {
553
- if (incomingLink === undefined) {
554
- throw new Error('Unexpected undefined link');
555
- }
556
- }
557
- return value.__ref === incomingLink.__ref;
558
- }
559
- function scalarFieldEquals(ast, variables, existing, incoming) {
560
- const { name } = ast;
561
- const value = existing[name];
562
- if (value === undefined) {
563
- return false;
564
- }
565
- return value === resolveValue(ast, variables, incoming);
566
- }
567
- function equals(ast, variables, existing, incoming) {
568
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
569
- for (let i = 0, len = selections.length; i < len; i += 1) {
570
- const sel = getLuvioFieldNodeSelection(selections[i]);
571
- if (sel.kind === 'ScalarFieldSelection') {
572
- if (scalarFieldEquals(sel, variables, existing, incoming) === false) {
573
- return false;
574
- }
575
- }
576
- else {
577
- if (linkEquals(sel, variables, existing, incoming) === false) {
578
- return false;
579
- }
580
- }
581
- }
582
- return true;
536
+ function resolveValue(ast, variables, source) {
537
+ const { alias } = ast;
538
+ const propertyName = render(ast, variables);
539
+ if (process.env.NODE_ENV !== 'production') {
540
+ if (alias !== undefined && alias in source) {
541
+ throw new Error(`Invalid alias "${alias}" passed to "equal" function. All aliases need to be normalized before calling equal`);
542
+ }
543
+ }
544
+ return source[propertyName];
545
+ }
546
+ function linkEquals(ast, variables, existing, incoming) {
547
+ const value = resolveValue(ast, variables, existing);
548
+ if (value === undefined) {
549
+ return false;
550
+ }
551
+ const incomingLink = resolveValue(ast, variables, incoming);
552
+ if (process.env.NODE_ENV !== 'production') {
553
+ if (incomingLink === undefined) {
554
+ throw new Error('Unexpected undefined link');
555
+ }
556
+ }
557
+ return value.__ref === incomingLink.__ref;
558
+ }
559
+ function scalarFieldEquals(ast, variables, existing, incoming) {
560
+ const { name } = ast;
561
+ const value = existing[name];
562
+ if (value === undefined) {
563
+ return false;
564
+ }
565
+ return value === resolveValue(ast, variables, incoming);
566
+ }
567
+ function equals(ast, variables, existing, incoming) {
568
+ const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
569
+ for (let i = 0, len = selections.length; i < len; i += 1) {
570
+ const sel = getLuvioFieldNodeSelection(selections[i]);
571
+ if (sel.kind === 'ScalarFieldSelection') {
572
+ if (scalarFieldEquals(sel, variables, existing, incoming) === false) {
573
+ return false;
574
+ }
575
+ }
576
+ else {
577
+ if (linkEquals(sel, variables, existing, incoming) === false) {
578
+ return false;
579
+ }
580
+ }
581
+ }
582
+ return true;
583
583
  }
584
584
 
585
- const DEFAULT_GRAPHQL_TTL = 30000;
586
- const GRAPHQL_INGEST_VERSION = 'GRAPHQL_INGEST_VERSION_1';
587
- function createIngest$2(ast, variables) {
588
- if (ast.kind === 'CustomFieldSelection') {
589
- return createIngest$3(ast, variables);
590
- }
591
- return genericCreateIngest(ast, variables);
592
- }
593
- function publishDataIfChanged(params) {
594
- const { store, key, ast, incoming, luvio, variables } = params;
595
- const existing = store.readEntry(key);
596
- if (existing === undefined || equals(ast, variables, existing, incoming) === false) {
597
- const newData = merge(existing, incoming);
598
- luvio.storePublish(key, newData);
599
- }
600
- }
601
- function genericCreateIngest(ast, variables) {
602
- let selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
603
- return (data, path, luvio, store, timestamp) => {
604
- const { fullPath } = path;
605
- for (let i = 0, len = selections.length; i < len; i += 1) {
606
- const sel = getLuvioFieldNodeSelection(selections[i]);
607
- if (sel.kind === 'ScalarFieldSelection') {
608
- continue;
609
- }
610
- const { name: fieldName, alias } = sel;
611
- const readPropertyName = alias === undefined ? fieldName : alias;
612
- const propertyFullPath = `${fullPath}__${fieldName}`;
613
- const writePropertyName = render(sel, variables);
614
- const childPath = {
615
- parent: {
616
- existing: null,
617
- key: fullPath,
618
- data,
619
- },
620
- propertyName: readPropertyName,
621
- fullPath: propertyFullPath,
622
- };
623
- data[writePropertyName] = createIngest$2(sel, variables)(data[readPropertyName], childPath, luvio, store, timestamp);
624
- if (writePropertyName !== readPropertyName && data[readPropertyName] !== undefined) {
625
- delete data[readPropertyName];
626
- }
627
- }
628
- publishDataIfChanged({
629
- ast,
630
- luvio,
631
- store,
632
- key: fullPath,
633
- variables: {},
634
- incoming: data,
635
- });
636
- if (data && data.__typename !== undefined) {
637
- luvio.publishStoreMetadata(fullPath, {
638
- representationName: data.__typename,
639
- namespace: namespace,
640
- ttl: DEFAULT_GRAPHQL_TTL,
641
- version: GRAPHQL_INGEST_VERSION,
642
- });
643
- }
644
- return {
645
- __ref: fullPath,
646
- };
647
- };
585
+ const DEFAULT_GRAPHQL_TTL = 30000;
586
+ const GRAPHQL_INGEST_VERSION = 'GRAPHQL_INGEST_VERSION_1';
587
+ function createIngest$2(ast, variables) {
588
+ if (ast.kind === 'CustomFieldSelection') {
589
+ return createIngest$3(ast, variables);
590
+ }
591
+ return genericCreateIngest(ast, variables);
592
+ }
593
+ function publishDataIfChanged(params) {
594
+ const { store, key, ast, incoming, luvio, variables } = params;
595
+ const existing = store.readEntry(key);
596
+ if (existing === undefined || equals(ast, variables, existing, incoming) === false) {
597
+ const newData = merge(existing, incoming);
598
+ luvio.storePublish(key, newData);
599
+ }
600
+ }
601
+ function genericCreateIngest(ast, variables) {
602
+ let selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
603
+ return (data, path, luvio, store, timestamp) => {
604
+ const { fullPath } = path;
605
+ for (let i = 0, len = selections.length; i < len; i += 1) {
606
+ const sel = getLuvioFieldNodeSelection(selections[i]);
607
+ if (sel.kind === 'ScalarFieldSelection') {
608
+ continue;
609
+ }
610
+ const { name: fieldName, alias } = sel;
611
+ const readPropertyName = alias === undefined ? fieldName : alias;
612
+ const propertyFullPath = `${fullPath}__${fieldName}`;
613
+ const writePropertyName = render(sel, variables);
614
+ const childPath = {
615
+ parent: {
616
+ existing: null,
617
+ key: fullPath,
618
+ data,
619
+ },
620
+ propertyName: readPropertyName,
621
+ fullPath: propertyFullPath,
622
+ };
623
+ data[writePropertyName] = createIngest$2(sel, variables)(data[readPropertyName], childPath, luvio, store, timestamp);
624
+ if (writePropertyName !== readPropertyName && data[readPropertyName] !== undefined) {
625
+ delete data[readPropertyName];
626
+ }
627
+ }
628
+ publishDataIfChanged({
629
+ ast,
630
+ luvio,
631
+ store,
632
+ key: fullPath,
633
+ variables: {},
634
+ incoming: data,
635
+ });
636
+ if (data && data.__typename !== undefined) {
637
+ luvio.publishStoreMetadata(fullPath, {
638
+ representationName: data.__typename,
639
+ namespace: namespace,
640
+ ttl: DEFAULT_GRAPHQL_TTL,
641
+ version: GRAPHQL_INGEST_VERSION,
642
+ });
643
+ }
644
+ return {
645
+ __ref: fullPath,
646
+ };
647
+ };
648
648
  }
649
649
 
650
- const CONNECTION_NODE_TYPE = 'Connection';
651
- const TYPENAME_FIELD$1 = '__typename';
652
- const PAGE_INFO_REQUIRED_FIELDS = ['hasNextPage', 'hasPreviousPage'];
653
- const EDGE_REQUIRED_FIELDS = ['cursor'];
654
- const PROPERTY_NAME_EDGES = 'edges';
655
- const PROPERTY_NAME_PAGE_INFO = 'pageInfo';
656
- const PROPERTY_NAME_TOTAL_COUNT = 'totalCount';
657
- function keyBuilder(ast, variables) {
658
- const { arguments: args, name } = ast;
659
- if (args === undefined) {
660
- return `${namespace}::${CONNECTION_NODE_TYPE}:${name}()`;
661
- }
662
- const serialized = render$1(args, variables);
663
- return `${namespace}::${CONNECTION_NODE_TYPE}:${name}(${serialized})`;
664
- }
665
- function selectEdges(luvio, builder, ast, links, variables) {
666
- const sink = [];
667
- for (let i = 0, len = links.length; i < len; i += 1) {
668
- builder.enterPath(i);
669
- const link = links[i];
670
- const resolved = followLink(luvio, ast, builder, link, variables);
671
- builder.assignNonScalar(sink, i, resolved);
672
- builder.exitPath();
673
- }
674
- return sink;
675
- }
676
- const createRead$2 = (luvio, ast, variables) => {
677
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
678
- return (source, builder) => {
679
- const sink = {};
680
- for (let i = 0, len = selections.length; i < len; i += 1) {
681
- const sel = getLuvioFieldNodeSelection(selections[i]);
682
- const { name, kind } = sel;
683
- if (kind === 'ScalarFieldSelection') {
684
- readScalarFieldSelection(builder, source, name, sink);
685
- continue;
686
- }
687
- const readPropertyName = render(sel, variables);
688
- builder.enterPath(readPropertyName);
689
- const edges = resolveLink(builder, source[readPropertyName]);
690
- if (edges === undefined) {
691
- builder.exitPath();
692
- break;
693
- }
694
- if (readPropertyName === PROPERTY_NAME_EDGES) {
695
- const data = selectEdges(luvio, builder, sel, edges.value, variables);
696
- builder.assignNonScalar(sink, readPropertyName, data);
697
- }
698
- else {
699
- if (process.env.NODE_ENV !== 'production') {
700
- throw new Error('Not supported');
701
- }
702
- }
703
- builder.exitPath();
704
- }
705
- return sink;
706
- };
707
- };
708
- function ingestConnectionProperty(sel, data, path, luvio, store, timestamp, variables) {
709
- const propertyName = sel.name;
710
- switch (propertyName) {
711
- case PROPERTY_NAME_EDGES:
712
- return ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables);
713
- }
714
- }
715
- function ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables) {
716
- const key = path.fullPath;
717
- const existing = store.readEntry(key);
718
- let hasChanges = existing === undefined || data.length !== existing.length;
719
- for (let i = 0, len = data.length; i < len; i += 1) {
720
- const incomingItem = (data[i] = createIngest$2(sel, variables)(data[i], {
721
- parent: {
722
- data,
723
- existing: null,
724
- key,
725
- },
726
- propertyName: i,
727
- fullPath: `${key}__${i}`,
728
- }, luvio, store, timestamp));
729
- const existingItem = existing !== undefined ? existing[i] : undefined;
730
- if (existingItem === undefined || existingItem.__ref !== incomingItem.__ref) {
731
- hasChanges = true;
732
- }
733
- }
734
- if (hasChanges === true) {
735
- luvio.storePublish(key, data);
736
- }
737
- luvio.publishStoreMetadata(key, {
738
- representationName: CONNECTION_NODE_TYPE,
739
- namespace: namespace,
740
- ttl: DEFAULT_GRAPHQL_TTL,
741
- version: GRAPHQL_INGEST_VERSION,
742
- });
743
- return {
744
- __ref: key,
745
- };
746
- }
747
- const createIngest$1 = (ast, key, variables) => {
748
- const { luvioSelections } = ast;
749
- const selections = luvioSelections === undefined ? [] : luvioSelections;
750
- return (data, path, luvio, store, timestamp) => {
751
- for (let i = 0, len = selections.length; i < len; i += 1) {
752
- const sel = getLuvioFieldNodeSelection(selections[i]);
753
- const { kind } = sel;
754
- const propertyName = sel.name;
755
- if (kind !== 'ObjectFieldSelection') {
756
- continue;
757
- }
758
- data[propertyName] = ingestConnectionProperty(sel, data[propertyName], {
759
- parent: {
760
- existing: null,
761
- key,
762
- data,
763
- },
764
- fullPath: `${key}__${propertyName}`,
765
- propertyName,
766
- }, luvio, store, timestamp, variables);
767
- }
768
- publishDataIfChanged({
769
- key,
770
- luvio,
771
- store,
772
- incoming: data,
773
- variables: {},
774
- ast,
775
- });
776
- const typeName = data.__typename;
777
- luvio.publishStoreMetadata(key, {
778
- representationName: typeName,
779
- namespace: namespace,
780
- ttl: DEFAULT_GRAPHQL_TTL,
781
- version: GRAPHQL_INGEST_VERSION,
782
- });
783
- return {
784
- __ref: key,
785
- };
786
- };
787
- };
788
- function serialize(def, state) {
789
- const { luvioSelections, arguments: args } = def;
790
- if (luvioSelections === undefined) {
791
- if (process.env.NODE_ENV !== 'production') {
792
- throw new Error('Connection field node must have selections');
793
- }
794
- return '';
795
- }
796
- const argsString = args === undefined || args.length === 0 ? '' : `(${serializeArguments(args)})`;
797
- const seenFields = {};
798
- const serializedFields = [];
799
- for (let i = 0; i < luvioSelections.length; i++) {
800
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
801
- const { name: fieldName } = sel;
802
- seenFields[fieldName] = true;
803
- if (fieldName === PROPERTY_NAME_PAGE_INFO) {
804
- serializedFields.push(serializePageInfo(sel, state));
805
- }
806
- else if (fieldName === PROPERTY_NAME_EDGES) {
807
- serializedFields.push(serializeEdges(sel, state));
808
- }
809
- else {
810
- serializedFields.push(serializeFieldNode(sel, state));
811
- }
812
- }
813
- appendRequiredConnectionFields(seenFields, serializedFields);
814
- return `${serializeFieldNodeName(def)}${argsString} { ${serializedFields.join(' ')} }`;
815
- }
816
- function serializeEdges(node, state) {
817
- if (!isLuvioFieldNodeObjectFieldNode(node)) {
818
- if (process.env.NODE_ENV !== 'production') {
819
- throw new Error('PageInfo must be an ObjectFieldNode');
820
- }
821
- return '';
822
- }
823
- const { luvioSelections } = node;
824
- if (luvioSelections === undefined)
825
- return '';
826
- const seenFields = {};
827
- const serializedFields = [];
828
- for (let i = 0; i < luvioSelections.length; i++) {
829
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
830
- seenFields[sel.name] = true;
831
- serializedFields.push(serializeFieldNode(sel, state));
832
- }
833
- appendRequiredFields(EDGE_REQUIRED_FIELDS, seenFields, serializedFields);
834
- insertTypeName(seenFields, serializedFields);
835
- return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
836
- }
837
- function serializePageInfo(node, state) {
838
- if (!isLuvioFieldNodeObjectFieldNode(node)) {
839
- if (process.env.NODE_ENV !== 'production') {
840
- throw new Error('PageInfo must be an ObjectFieldNode');
841
- }
842
- return '';
843
- }
844
- const { luvioSelections } = node;
845
- if (luvioSelections === undefined)
846
- return '';
847
- const seenFields = {};
848
- const serializedFields = [];
849
- for (let i = 0; i < luvioSelections.length; i++) {
850
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
851
- seenFields[sel.name] = true;
852
- serializedFields.push(serializeFieldNode(sel, state));
853
- }
854
- appendRequiredFields(PAGE_INFO_REQUIRED_FIELDS, seenFields, serializedFields);
855
- return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
856
- }
857
- function appendRequiredFields(requiredFields, seenFields, result) {
858
- for (let i = 0; i < requiredFields.length; i++) {
859
- const fieldName = requiredFields[i];
860
- if (seenFields[fieldName] !== true) {
861
- result.push(fieldName);
862
- }
863
- }
864
- }
865
- function appendRequiredConnectionFields(seenFields, result) {
866
- if (seenFields[PROPERTY_NAME_PAGE_INFO] !== true) {
867
- result.push('pageInfo { hasNextPage hasPreviousPage }');
868
- }
869
- if (seenFields[PROPERTY_NAME_TOTAL_COUNT] !== true) {
870
- result.push(PROPERTY_NAME_TOTAL_COUNT);
871
- }
872
- insertTypeName(seenFields, result);
873
- }
874
- function insertTypeName(seenFields, result) {
875
- if (seenFields[TYPENAME_FIELD$1] !== true) {
876
- result.unshift(TYPENAME_FIELD$1);
877
- }
650
+ const CONNECTION_NODE_TYPE = 'Connection';
651
+ const TYPENAME_FIELD$1 = '__typename';
652
+ const PAGE_INFO_REQUIRED_FIELDS = ['hasNextPage', 'hasPreviousPage'];
653
+ const EDGE_REQUIRED_FIELDS = ['cursor'];
654
+ const PROPERTY_NAME_EDGES = 'edges';
655
+ const PROPERTY_NAME_PAGE_INFO = 'pageInfo';
656
+ const PROPERTY_NAME_TOTAL_COUNT = 'totalCount';
657
+ function keyBuilder(ast, variables) {
658
+ const { arguments: args, name } = ast;
659
+ if (args === undefined) {
660
+ return `${namespace}::${CONNECTION_NODE_TYPE}:${name}()`;
661
+ }
662
+ const serialized = render$1(args, variables);
663
+ return `${namespace}::${CONNECTION_NODE_TYPE}:${name}(${serialized})`;
664
+ }
665
+ function selectEdges(luvio, builder, ast, links, variables) {
666
+ const sink = [];
667
+ for (let i = 0, len = links.length; i < len; i += 1) {
668
+ builder.enterPath(i);
669
+ const link = links[i];
670
+ const resolved = followLink(luvio, ast, builder, link, variables);
671
+ builder.assignNonScalar(sink, i, resolved);
672
+ builder.exitPath();
673
+ }
674
+ return sink;
675
+ }
676
+ const createRead$2 = (luvio, ast, variables) => {
677
+ const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
678
+ return (source, builder) => {
679
+ const sink = {};
680
+ for (let i = 0, len = selections.length; i < len; i += 1) {
681
+ const sel = getLuvioFieldNodeSelection(selections[i]);
682
+ const { name, kind } = sel;
683
+ if (kind === 'ScalarFieldSelection') {
684
+ readScalarFieldSelection(builder, source, name, sink);
685
+ continue;
686
+ }
687
+ const readPropertyName = render(sel, variables);
688
+ builder.enterPath(readPropertyName);
689
+ const edges = resolveLink(builder, source[readPropertyName]);
690
+ if (edges === undefined) {
691
+ builder.exitPath();
692
+ break;
693
+ }
694
+ if (readPropertyName === PROPERTY_NAME_EDGES) {
695
+ const data = selectEdges(luvio, builder, sel, edges.value, variables);
696
+ builder.assignNonScalar(sink, readPropertyName, data);
697
+ }
698
+ else {
699
+ if (process.env.NODE_ENV !== 'production') {
700
+ throw new Error('Not supported');
701
+ }
702
+ }
703
+ builder.exitPath();
704
+ }
705
+ return sink;
706
+ };
707
+ };
708
+ function ingestConnectionProperty(sel, data, path, luvio, store, timestamp, variables) {
709
+ const propertyName = sel.name;
710
+ switch (propertyName) {
711
+ case PROPERTY_NAME_EDGES:
712
+ return ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables);
713
+ }
714
+ }
715
+ function ingestConnectionEdges(sel, data, path, luvio, store, timestamp, variables) {
716
+ const key = path.fullPath;
717
+ const existing = store.readEntry(key);
718
+ let hasChanges = existing === undefined || data.length !== existing.length;
719
+ for (let i = 0, len = data.length; i < len; i += 1) {
720
+ const incomingItem = (data[i] = createIngest$2(sel, variables)(data[i], {
721
+ parent: {
722
+ data,
723
+ existing: null,
724
+ key,
725
+ },
726
+ propertyName: i,
727
+ fullPath: `${key}__${i}`,
728
+ }, luvio, store, timestamp));
729
+ const existingItem = existing !== undefined ? existing[i] : undefined;
730
+ if (existingItem === undefined || existingItem.__ref !== incomingItem.__ref) {
731
+ hasChanges = true;
732
+ }
733
+ }
734
+ if (hasChanges === true) {
735
+ luvio.storePublish(key, data);
736
+ }
737
+ luvio.publishStoreMetadata(key, {
738
+ representationName: CONNECTION_NODE_TYPE,
739
+ namespace: namespace,
740
+ ttl: DEFAULT_GRAPHQL_TTL,
741
+ version: GRAPHQL_INGEST_VERSION,
742
+ });
743
+ return {
744
+ __ref: key,
745
+ };
746
+ }
747
+ const createIngest$1 = (ast, key, variables) => {
748
+ const { luvioSelections } = ast;
749
+ const selections = luvioSelections === undefined ? [] : luvioSelections;
750
+ return (data, path, luvio, store, timestamp) => {
751
+ for (let i = 0, len = selections.length; i < len; i += 1) {
752
+ const sel = getLuvioFieldNodeSelection(selections[i]);
753
+ const { kind } = sel;
754
+ const propertyName = sel.name;
755
+ if (kind !== 'ObjectFieldSelection') {
756
+ continue;
757
+ }
758
+ data[propertyName] = ingestConnectionProperty(sel, data[propertyName], {
759
+ parent: {
760
+ existing: null,
761
+ key,
762
+ data,
763
+ },
764
+ fullPath: `${key}__${propertyName}`,
765
+ propertyName,
766
+ }, luvio, store, timestamp, variables);
767
+ }
768
+ publishDataIfChanged({
769
+ key,
770
+ luvio,
771
+ store,
772
+ incoming: data,
773
+ variables: {},
774
+ ast,
775
+ });
776
+ const typeName = data.__typename;
777
+ luvio.publishStoreMetadata(key, {
778
+ representationName: typeName,
779
+ namespace: namespace,
780
+ ttl: DEFAULT_GRAPHQL_TTL,
781
+ version: GRAPHQL_INGEST_VERSION,
782
+ });
783
+ return {
784
+ __ref: key,
785
+ };
786
+ };
787
+ };
788
+ function serialize(def, state) {
789
+ const { luvioSelections, arguments: args } = def;
790
+ if (luvioSelections === undefined) {
791
+ if (process.env.NODE_ENV !== 'production') {
792
+ throw new Error('Connection field node must have selections');
793
+ }
794
+ return '';
795
+ }
796
+ const argsString = args === undefined || args.length === 0 ? '' : `(${serializeArguments(args)})`;
797
+ const seenFields = {};
798
+ const serializedFields = [];
799
+ for (let i = 0; i < luvioSelections.length; i++) {
800
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
801
+ const { name: fieldName } = sel;
802
+ seenFields[fieldName] = true;
803
+ if (fieldName === PROPERTY_NAME_PAGE_INFO) {
804
+ serializedFields.push(serializePageInfo(sel, state));
805
+ }
806
+ else if (fieldName === PROPERTY_NAME_EDGES) {
807
+ serializedFields.push(serializeEdges(sel, state));
808
+ }
809
+ else {
810
+ serializedFields.push(serializeFieldNode(sel, state));
811
+ }
812
+ }
813
+ appendRequiredConnectionFields(seenFields, serializedFields);
814
+ return `${serializeFieldNodeName(def)}${argsString} { ${serializedFields.join(' ')} }`;
815
+ }
816
+ function serializeEdges(node, state) {
817
+ if (!isLuvioFieldNodeObjectFieldNode(node)) {
818
+ if (process.env.NODE_ENV !== 'production') {
819
+ throw new Error('PageInfo must be an ObjectFieldNode');
820
+ }
821
+ return '';
822
+ }
823
+ const { luvioSelections } = node;
824
+ if (luvioSelections === undefined)
825
+ return '';
826
+ const seenFields = {};
827
+ const serializedFields = [];
828
+ for (let i = 0; i < luvioSelections.length; i++) {
829
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
830
+ seenFields[sel.name] = true;
831
+ serializedFields.push(serializeFieldNode(sel, state));
832
+ }
833
+ appendRequiredFields(EDGE_REQUIRED_FIELDS, seenFields, serializedFields);
834
+ insertTypeName(seenFields, serializedFields);
835
+ return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
836
+ }
837
+ function serializePageInfo(node, state) {
838
+ if (!isLuvioFieldNodeObjectFieldNode(node)) {
839
+ if (process.env.NODE_ENV !== 'production') {
840
+ throw new Error('PageInfo must be an ObjectFieldNode');
841
+ }
842
+ return '';
843
+ }
844
+ const { luvioSelections } = node;
845
+ if (luvioSelections === undefined)
846
+ return '';
847
+ const seenFields = {};
848
+ const serializedFields = [];
849
+ for (let i = 0; i < luvioSelections.length; i++) {
850
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
851
+ seenFields[sel.name] = true;
852
+ serializedFields.push(serializeFieldNode(sel, state));
853
+ }
854
+ appendRequiredFields(PAGE_INFO_REQUIRED_FIELDS, seenFields, serializedFields);
855
+ return `${serializeFieldNodeName(node)} { ${serializedFields.join(' ')} }`;
856
+ }
857
+ function appendRequiredFields(requiredFields, seenFields, result) {
858
+ for (let i = 0; i < requiredFields.length; i++) {
859
+ const fieldName = requiredFields[i];
860
+ if (seenFields[fieldName] !== true) {
861
+ result.push(fieldName);
862
+ }
863
+ }
864
+ }
865
+ function appendRequiredConnectionFields(seenFields, result) {
866
+ if (seenFields[PROPERTY_NAME_PAGE_INFO] !== true) {
867
+ result.push('pageInfo { hasNextPage hasPreviousPage }');
868
+ }
869
+ if (seenFields[PROPERTY_NAME_TOTAL_COUNT] !== true) {
870
+ result.push(PROPERTY_NAME_TOTAL_COUNT);
871
+ }
872
+ insertTypeName(seenFields, result);
873
+ }
874
+ function insertTypeName(seenFields, result) {
875
+ if (seenFields[TYPENAME_FIELD$1] !== true) {
876
+ result.unshift(TYPENAME_FIELD$1);
877
+ }
878
878
  }
879
879
 
880
- function createCustomFieldRead(luvio, sel, variables) {
881
- if (sel.type === 'Connection') {
882
- return createRead$2(luvio, sel, variables);
883
- }
884
- return createRead$3(luvio, sel, variables);
885
- }
886
- function createRead$1(luvio, ast, variables) {
887
- if (ast.kind === 'CustomFieldSelection') {
888
- return createCustomFieldRead(luvio, ast, variables);
889
- }
890
- if (ast.kind === 'FragmentSpread' ||
891
- ast.kind === 'InlineFragment' ||
892
- ast.kind === 'ScalarFieldSelection') {
893
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
894
- throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
895
- }
896
- return genericCreateRead(luvio, ast, variables);
897
- }
898
- const genericCreateRead = (luvio, ast, variables) => {
899
- const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
900
- return (source, builder) => {
901
- const sink = {};
902
- for (let i = 0, len = selections.length; i < len; i += 1) {
903
- const sel = getLuvioFieldNodeSelection(selections[i]);
904
- const { name: fieldName, alias } = sel;
905
- const propertyName = alias === undefined ? fieldName : alias;
906
- builder.enterPath(fieldName);
907
- switch (sel.kind) {
908
- case 'ScalarFieldSelection':
909
- readScalarFieldSelection(builder, source, fieldName, sink);
910
- break;
911
- default: {
912
- const data = followLink(luvio, sel, builder, source[render(sel, variables)], variables);
913
- builder.assignNonScalar(sink, propertyName, data);
914
- }
915
- }
916
- builder.exitPath();
917
- }
918
- return sink;
919
- };
880
+ function createCustomFieldRead(luvio, sel, variables) {
881
+ if (sel.type === 'Connection') {
882
+ return createRead$2(luvio, sel, variables);
883
+ }
884
+ return createRead$3(luvio, sel, variables);
885
+ }
886
+ function createRead$1(luvio, ast, variables) {
887
+ if (ast.kind === 'CustomFieldSelection') {
888
+ return createCustomFieldRead(luvio, ast, variables);
889
+ }
890
+ if (ast.kind === 'FragmentSpread' ||
891
+ ast.kind === 'InlineFragment' ||
892
+ ast.kind === 'ScalarFieldSelection') {
893
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
894
+ throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
895
+ }
896
+ return genericCreateRead(luvio, ast, variables);
897
+ }
898
+ const genericCreateRead = (luvio, ast, variables) => {
899
+ const selections = ast.luvioSelections === undefined ? [] : ast.luvioSelections;
900
+ return (source, builder) => {
901
+ const sink = {};
902
+ for (let i = 0, len = selections.length; i < len; i += 1) {
903
+ const sel = getLuvioFieldNodeSelection(selections[i]);
904
+ const { name: fieldName, alias } = sel;
905
+ const propertyName = alias === undefined ? fieldName : alias;
906
+ builder.enterPath(fieldName);
907
+ switch (sel.kind) {
908
+ case 'ScalarFieldSelection':
909
+ readScalarFieldSelection(builder, source, fieldName, sink);
910
+ break;
911
+ default: {
912
+ const data = followLink(luvio, sel, builder, source[render(sel, variables)], variables);
913
+ builder.assignNonScalar(sink, propertyName, data);
914
+ }
915
+ }
916
+ builder.exitPath();
917
+ }
918
+ return sink;
919
+ };
920
920
  };
921
921
 
922
- var PropertyLookupResultState;
923
- (function (PropertyLookupResultState) {
924
- PropertyLookupResultState[PropertyLookupResultState["Missing"] = 0] = "Missing";
925
- PropertyLookupResultState[PropertyLookupResultState["Present"] = 1] = "Present";
926
- })(PropertyLookupResultState || (PropertyLookupResultState = {}));
927
- const objectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty;
928
- function propertyLookup(builder, key, source) {
929
- if (objectPrototypeHasOwnProperty.call(source, key) === false) {
930
- builder.markMissing();
931
- return {
932
- state: PropertyLookupResultState.Missing,
933
- };
934
- }
935
- return {
936
- state: PropertyLookupResultState.Present,
937
- value: source[key],
938
- };
939
- }
940
- function markStoreResolveResultSeen(builder, state) {
941
- const { redirects, resolvedKey } = state;
942
- builder.markSeenId(resolvedKey);
943
- const { length: len } = redirects;
944
- if (len === 0) {
945
- return;
946
- }
947
- for (let i = 0; i < len; i += 1) {
948
- builder.markSeenId(redirects[i]);
949
- }
950
- }
951
- function resolveKey(builder, key) {
952
- const { StoreResolveResultState } = builder;
953
- const lookup = builder.storeLookup(key);
954
- markStoreResolveResultSeen(builder, lookup);
955
- switch (lookup.state) {
956
- case StoreResolveResultState.NotPresent:
957
- builder.markMissingLink(key);
958
- return;
959
- case StoreResolveResultState.Stale:
960
- builder.markStale();
961
- return lookup;
962
- case StoreResolveResultState.Error:
963
- if (process.env.NODE_ENV !== 'production') {
964
- throw new Error('TODO: Implement error links');
965
- }
966
- else {
967
- return;
968
- }
969
- }
970
- return lookup;
971
- }
972
- function resolveLink(builder, storeLink) {
973
- const { StoreLinkStateValues } = builder;
974
- const linkState = builder.getLinkState(storeLink);
975
- switch (linkState.state) {
976
- case StoreLinkStateValues.RefNotPresent:
977
- case StoreLinkStateValues.NotPresent:
978
- case StoreLinkStateValues.Missing:
979
- builder.markMissing();
980
- return;
981
- case StoreLinkStateValues.Pending:
982
- builder.markPending();
983
- return;
984
- case StoreLinkStateValues.Null:
985
- if (process.env.NODE_ENV !== 'production') {
986
- throw new Error(`TODO: Invalid Link State. Link on "${builder.currentPath.fullPath}"`);
987
- }
988
- else {
989
- return;
990
- }
991
- }
992
- const { key: __ref } = linkState;
993
- return resolveKey(builder, __ref);
994
- }
995
- function followLink(luvio, sel, builder, storeLink, variables) {
996
- const linkState = resolveLink(builder, storeLink);
997
- if (linkState === undefined) {
998
- return;
999
- }
1000
- const { value } = linkState;
1001
- return createRead$1(luvio, sel, variables)(value, builder);
1002
- }
1003
- function getLuvioFieldNodeSelection(ast) {
1004
- const { kind } = ast;
1005
- if (kind === 'FragmentSpread' || kind === 'InlineFragment') {
1006
- if (process.env.NODE_ENV !== 'production') {
1007
- throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
1008
- }
1009
- }
1010
- return ast;
922
+ var PropertyLookupResultState;
923
+ (function (PropertyLookupResultState) {
924
+ PropertyLookupResultState[PropertyLookupResultState["Missing"] = 0] = "Missing";
925
+ PropertyLookupResultState[PropertyLookupResultState["Present"] = 1] = "Present";
926
+ })(PropertyLookupResultState || (PropertyLookupResultState = {}));
927
+ const objectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty;
928
+ function propertyLookup(builder, key, source) {
929
+ if (objectPrototypeHasOwnProperty.call(source, key) === false) {
930
+ builder.markMissing();
931
+ return {
932
+ state: PropertyLookupResultState.Missing,
933
+ };
934
+ }
935
+ return {
936
+ state: PropertyLookupResultState.Present,
937
+ value: source[key],
938
+ };
939
+ }
940
+ function markStoreResolveResultSeen(builder, state) {
941
+ const { redirects, resolvedKey } = state;
942
+ builder.markSeenId(resolvedKey);
943
+ const { length: len } = redirects;
944
+ if (len === 0) {
945
+ return;
946
+ }
947
+ for (let i = 0; i < len; i += 1) {
948
+ builder.markSeenId(redirects[i]);
949
+ }
950
+ }
951
+ function resolveKey(builder, key) {
952
+ const { StoreResolveResultState } = builder;
953
+ const lookup = builder.storeLookup(key);
954
+ markStoreResolveResultSeen(builder, lookup);
955
+ switch (lookup.state) {
956
+ case StoreResolveResultState.NotPresent:
957
+ builder.markMissingLink(key);
958
+ return;
959
+ case StoreResolveResultState.Stale:
960
+ builder.markStale();
961
+ return lookup;
962
+ case StoreResolveResultState.Error:
963
+ if (process.env.NODE_ENV !== 'production') {
964
+ throw new Error('TODO: Implement error links');
965
+ }
966
+ else {
967
+ return;
968
+ }
969
+ }
970
+ return lookup;
971
+ }
972
+ function resolveLink(builder, storeLink) {
973
+ const { StoreLinkStateValues } = builder;
974
+ const linkState = builder.getLinkState(storeLink);
975
+ switch (linkState.state) {
976
+ case StoreLinkStateValues.RefNotPresent:
977
+ case StoreLinkStateValues.NotPresent:
978
+ case StoreLinkStateValues.Missing:
979
+ builder.markMissing();
980
+ return;
981
+ case StoreLinkStateValues.Pending:
982
+ builder.markPending();
983
+ return;
984
+ case StoreLinkStateValues.Null:
985
+ if (process.env.NODE_ENV !== 'production') {
986
+ throw new Error(`TODO: Invalid Link State. Link on "${builder.currentPath.fullPath}"`);
987
+ }
988
+ else {
989
+ return;
990
+ }
991
+ }
992
+ const { key: __ref } = linkState;
993
+ return resolveKey(builder, __ref);
994
+ }
995
+ function followLink(luvio, sel, builder, storeLink, variables) {
996
+ const linkState = resolveLink(builder, storeLink);
997
+ if (linkState === undefined) {
998
+ return;
999
+ }
1000
+ const { value } = linkState;
1001
+ return createRead$1(luvio, sel, variables)(value, builder);
1002
+ }
1003
+ function getLuvioFieldNodeSelection(ast) {
1004
+ const { kind } = ast;
1005
+ if (kind === 'FragmentSpread' || kind === 'InlineFragment') {
1006
+ if (process.env.NODE_ENV !== 'production') {
1007
+ throw new Error('"FragmentSpread" and "InlineFragment" currently not supported');
1008
+ }
1009
+ }
1010
+ return ast;
1011
1011
  }
1012
1012
 
1013
- const TYPENAME_FIELD = '__typename';
1014
- const KIND_OBJECT_FIELD_SELECTION = 'ObjectFieldSelection';
1015
- function serializeFieldNodeName(node) {
1016
- const { name, alias } = node;
1017
- return alias === undefined ? `${name}` : `${alias}: ${name}`;
1018
- }
1019
- function serializeSelections(selections, state) {
1020
- if (selections === undefined) {
1021
- return '';
1022
- }
1023
- let str = '';
1024
- for (let i = 0, len = selections.length; i < len; i += 1) {
1025
- const def = serializeFieldNode(selections[i], state);
1026
- str = `${str}${def}`;
1027
- }
1028
- return str;
1029
- }
1030
- function serializeFieldNode(def, state) {
1031
- const { kind } = def;
1032
- switch (kind) {
1033
- case 'ObjectFieldSelection':
1034
- return serializeObjectFieldNode(def, state);
1035
- case 'CustomFieldSelection':
1036
- return serializeCustomFieldNode(def, state);
1037
- case 'ScalarFieldSelection':
1038
- return serializeScalarFieldNode(def);
1039
- }
1040
- if (process.env.NODE_ENV !== 'production') {
1041
- throw new Error(`Unable to serialize graphql query, unsupported field node "${kind}"`);
1042
- }
1043
- return '';
1044
- }
1045
- function serializeObjectFieldNode(def, state) {
1046
- const { luvioSelections, arguments: defArgs } = def;
1047
- const args = defArgs === undefined ? '' : `(${serializeArguments(defArgs)})`;
1048
- return `${serializeFieldNodeName(def)}${args} { ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1049
- }
1050
- function serializeCustomFieldNode(def, state) {
1051
- const { type } = def;
1052
- switch (type) {
1053
- case 'Connection':
1054
- return serialize(def, state);
1055
- case 'Record':
1056
- return serializeCustomFieldRecord(def, state);
1057
- }
1058
- if (process.env.NODE_ENV !== 'production') {
1059
- throw new Error(`Unable to serialize graphql query, unsupported CustomField type "${type}"`);
1060
- }
1061
- return '';
1062
- }
1063
- function serializeScalarFieldNode(def) {
1064
- return `${serializeFieldNodeName(def)}, `;
1065
- }
1066
- function serializeRecordSelections(selections, state) {
1067
- if (selections === undefined) {
1068
- return '';
1069
- }
1070
- let str = '';
1071
- for (let i = 0, len = selections.length; i < len; i += 1) {
1072
- const sel = getLuvioFieldNodeSelection(selections[i]);
1073
- const def = isLuvioFieldNodeObjectFieldNode(sel)
1074
- ? serializeObjectFieldNodeUnderRecord(sel)
1075
- : serializeFieldNode(sel, state);
1076
- str = `${str}${def}`;
1077
- }
1078
- return str;
1079
- }
1080
- function isLuvioFieldNodeObjectFieldNode(node) {
1081
- return node.kind === KIND_OBJECT_FIELD_SELECTION;
1082
- }
1083
- function serializeObjectFieldNodeUnderRecord(node) {
1084
- const { luvioSelections, arguments: nodeArgs, name: nodeName } = node;
1085
- const fields = {};
1086
- let result = ``;
1087
- if (luvioSelections === undefined) {
1088
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1089
- throw new Error('selection should not be empty for ObjectFieldNodeUnderRecord');
1090
- }
1091
- const luvioSelectionsLength = luvioSelections.length;
1092
- for (let i = 0; i < luvioSelectionsLength; i++) {
1093
- const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
1094
- const { name } = sel;
1095
- if (sel.kind !== 'ScalarFieldSelection') {
1096
- if (process.env.NODE_ENV !== 'production') {
1097
- throw new Error(`Invalid selection for ${nodeName}. ${nodeName} appears to be a Record, but is missing @resource(type: "Record")`);
1098
- }
1099
- }
1100
- if (RECORD_DEFAULT_FIELD_VALUES.indexOf(name) === -1) {
1101
- if (process.env.NODE_ENV !== 'production') {
1102
- throw new Error(`Invalid selection for "${nodeName}.${name}". Only ${RECORD_DEFAULT_FIELD_VALUES.join(', ')} are supported. If "${nodeName}" is a spanning Record, please include @resource(type: "Record") directive.`);
1103
- }
1104
- }
1105
- fields[name] = true;
1106
- result = `${result}${serializeScalarFieldNode(sel)}`;
1107
- }
1108
- result = appendRecordDefaultFieldValues(result, fields);
1109
- const args = nodeArgs === undefined ? '' : `(${serializeArguments(nodeArgs)})`;
1110
- return `${serializeFieldNodeName(node)}${args} { ${TYPENAME_FIELD} ${result} }`;
1111
- }
1112
- function appendRecordDefaultFieldValues(fieldValues, fieldValuesMap) {
1113
- let str = fieldValues;
1114
- for (let i = 0, len = RECORD_DEFAULT_FIELD_VALUES.length; i < len; i++) {
1115
- const defaultField = RECORD_DEFAULT_FIELD_VALUES[i];
1116
- if (fieldValuesMap[defaultField] !== true) {
1117
- str = `${str}${defaultField}, `;
1118
- }
1119
- }
1120
- return str;
1121
- }
1122
- function appendSpanningRecordIds(luvioSelections) {
1123
- if (luvioSelections === undefined) {
1124
- return undefined;
1125
- }
1126
- //add record ref ids
1127
- let spanningRecordIdFields = [];
1128
- let selections = luvioSelections;
1129
- //Find all fields with a record type declaration and add the corresponding
1130
- //reference ID.
1131
- // TODO [W-11342283]: This approach uses a naming pattern that is brittle and not
1132
- // guaranteed to work in the long run. A more correct approach is to thread through
1133
- // ObjectInfo schemas and use its mapping definitions.
1134
- for (let i = 0; i < selections.length; i++) {
1135
- const selection = selections[i];
1136
- if (selection.kind === 'CustomFieldSelection' && selection.type === 'Record') {
1137
- const customFieldMatches = selection.name.match(/(.*__)r$/);
1138
- if (customFieldMatches) {
1139
- // For `FSL__Related_Service__r {...}`, inject `FSL__Related_Service__c { value } as a peer field`
1140
- const [, captureGroup] = customFieldMatches;
1141
- spanningRecordIdFields.push(`${captureGroup}c`);
1142
- }
1143
- else {
1144
- // For `Owner {...}`, inject `OwnerId { value } as a peer field`
1145
- spanningRecordIdFields.push(`${selection.name}Id`);
1146
- }
1147
- }
1148
- }
1149
- //Add all missing reference IDs to the set of selections
1150
- for (let i = 0; i < spanningRecordIdFields.length; i++) {
1151
- const idField = spanningRecordIdFields[i];
1152
- if (selections.findIndex((e) => e.kind === 'ObjectFieldSelection' && e.name === idField) >
1153
- -1) {
1154
- continue;
1155
- }
1156
- selections.push({
1157
- kind: 'ObjectFieldSelection',
1158
- name: idField,
1159
- luvioSelections: [{ kind: 'ScalarFieldSelection', name: 'value' }],
1160
- });
1161
- }
1162
- return selections;
1163
- }
1164
- function serializeCustomFieldRecord(def, state) {
1165
- const { luvioSelections } = def;
1166
- if (state.fragments[defaultRecordFieldsFragmentName] === undefined) {
1167
- state.fragments[defaultRecordFieldsFragmentName] = defaultRecordFieldsFragment;
1168
- }
1169
- const selections = appendSpanningRecordIds(luvioSelections);
1170
- return `${serializeFieldNodeName(def)} { ${serializeRecordSelections(selections, state)} ...${defaultRecordFieldsFragmentName} }`;
1171
- }
1172
- function serializeArguments(argDefinitions) {
1173
- if (argDefinitions === undefined) {
1174
- return '';
1175
- }
1176
- let str = '';
1177
- for (let i = 0, len = argDefinitions.length; i < len; i += 1) {
1178
- let def = serializeArgument(argDefinitions[i]);
1179
- if (i !== 0) {
1180
- def = ` ${def}`;
1181
- }
1182
- str = `${str}${def}`;
1183
- }
1184
- return str;
1185
- }
1186
- function serializeArgument(argDefinition) {
1187
- const { name, value } = argDefinition;
1188
- return `${name}: ${serializeValueNode(value)}`;
1013
+ const TYPENAME_FIELD = '__typename';
1014
+ const KIND_OBJECT_FIELD_SELECTION = 'ObjectFieldSelection';
1015
+ function serializeFieldNodeName(node) {
1016
+ const { name, alias } = node;
1017
+ return alias === undefined ? `${name}` : `${alias}: ${name}`;
1018
+ }
1019
+ function serializeSelections(selections, state) {
1020
+ if (selections === undefined) {
1021
+ return '';
1022
+ }
1023
+ let str = '';
1024
+ for (let i = 0, len = selections.length; i < len; i += 1) {
1025
+ const def = serializeFieldNode(selections[i], state);
1026
+ str = `${str}${def}`;
1027
+ }
1028
+ return str;
1029
+ }
1030
+ function serializeFieldNode(def, state) {
1031
+ const { kind } = def;
1032
+ switch (kind) {
1033
+ case 'ObjectFieldSelection':
1034
+ return serializeObjectFieldNode(def, state);
1035
+ case 'CustomFieldSelection':
1036
+ return serializeCustomFieldNode(def, state);
1037
+ case 'ScalarFieldSelection':
1038
+ return serializeScalarFieldNode(def);
1039
+ }
1040
+ if (process.env.NODE_ENV !== 'production') {
1041
+ throw new Error(`Unable to serialize graphql query, unsupported field node "${kind}"`);
1042
+ }
1043
+ return '';
1044
+ }
1045
+ function serializeObjectFieldNode(def, state) {
1046
+ const { luvioSelections, arguments: defArgs } = def;
1047
+ const args = defArgs === undefined ? '' : `(${serializeArguments(defArgs)})`;
1048
+ return `${serializeFieldNodeName(def)}${args} { ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1049
+ }
1050
+ function serializeCustomFieldNode(def, state) {
1051
+ const { type } = def;
1052
+ switch (type) {
1053
+ case 'Connection':
1054
+ return serialize(def, state);
1055
+ case 'Record':
1056
+ return serializeCustomFieldRecord(def, state);
1057
+ }
1058
+ if (process.env.NODE_ENV !== 'production') {
1059
+ throw new Error(`Unable to serialize graphql query, unsupported CustomField type "${type}"`);
1060
+ }
1061
+ return '';
1062
+ }
1063
+ function serializeScalarFieldNode(def) {
1064
+ return `${serializeFieldNodeName(def)}, `;
1065
+ }
1066
+ function serializeRecordSelections(selections, state) {
1067
+ if (selections === undefined) {
1068
+ return '';
1069
+ }
1070
+ let str = '';
1071
+ for (let i = 0, len = selections.length; i < len; i += 1) {
1072
+ const sel = getLuvioFieldNodeSelection(selections[i]);
1073
+ const def = isLuvioFieldNodeObjectFieldNode(sel)
1074
+ ? serializeObjectFieldNodeUnderRecord(sel)
1075
+ : serializeFieldNode(sel, state);
1076
+ str = `${str}${def}`;
1077
+ }
1078
+ return str;
1079
+ }
1080
+ function isLuvioFieldNodeObjectFieldNode(node) {
1081
+ return node.kind === KIND_OBJECT_FIELD_SELECTION;
1082
+ }
1083
+ function serializeObjectFieldNodeUnderRecord(node) {
1084
+ const { luvioSelections, arguments: nodeArgs, name: nodeName } = node;
1085
+ const fields = {};
1086
+ let result = ``;
1087
+ if (luvioSelections === undefined) {
1088
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1089
+ throw new Error('selection should not be empty for ObjectFieldNodeUnderRecord');
1090
+ }
1091
+ const luvioSelectionsLength = luvioSelections.length;
1092
+ for (let i = 0; i < luvioSelectionsLength; i++) {
1093
+ const sel = getLuvioFieldNodeSelection(luvioSelections[i]);
1094
+ const { name } = sel;
1095
+ if (sel.kind !== 'ScalarFieldSelection') {
1096
+ if (process.env.NODE_ENV !== 'production') {
1097
+ throw new Error(`Invalid selection for ${nodeName}. ${nodeName} appears to be a Record, but is missing @resource(type: "Record")`);
1098
+ }
1099
+ }
1100
+ if (RECORD_DEFAULT_FIELD_VALUES.indexOf(name) === -1) {
1101
+ if (process.env.NODE_ENV !== 'production') {
1102
+ throw new Error(`Invalid selection for "${nodeName}.${name}". Only ${RECORD_DEFAULT_FIELD_VALUES.join(', ')} are supported. If "${nodeName}" is a spanning Record, please include @resource(type: "Record") directive.`);
1103
+ }
1104
+ }
1105
+ fields[name] = true;
1106
+ result = `${result}${serializeScalarFieldNode(sel)}`;
1107
+ }
1108
+ result = appendRecordDefaultFieldValues(result, fields);
1109
+ const args = nodeArgs === undefined ? '' : `(${serializeArguments(nodeArgs)})`;
1110
+ return `${serializeFieldNodeName(node)}${args} { ${TYPENAME_FIELD} ${result} }`;
1111
+ }
1112
+ function appendRecordDefaultFieldValues(fieldValues, fieldValuesMap) {
1113
+ let str = fieldValues;
1114
+ for (let i = 0, len = RECORD_DEFAULT_FIELD_VALUES.length; i < len; i++) {
1115
+ const defaultField = RECORD_DEFAULT_FIELD_VALUES[i];
1116
+ if (fieldValuesMap[defaultField] !== true) {
1117
+ str = `${str}${defaultField}, `;
1118
+ }
1119
+ }
1120
+ return str;
1121
+ }
1122
+ function appendSpanningRecordIds(luvioSelections) {
1123
+ if (luvioSelections === undefined) {
1124
+ return undefined;
1125
+ }
1126
+ //add record ref ids
1127
+ let spanningRecordIdFields = [];
1128
+ let selections = luvioSelections;
1129
+ //Find all fields with a record type declaration and add the corresponding
1130
+ //reference ID.
1131
+ // TODO [W-11342283]: This approach uses a naming pattern that is brittle and not
1132
+ // guaranteed to work in the long run. A more correct approach is to thread through
1133
+ // ObjectInfo schemas and use its mapping definitions.
1134
+ for (let i = 0; i < selections.length; i++) {
1135
+ const selection = selections[i];
1136
+ if (selection.kind === 'CustomFieldSelection' && selection.type === 'Record') {
1137
+ const customFieldMatches = selection.name.match(/(.*__)r$/);
1138
+ if (customFieldMatches) {
1139
+ // For `FSL__Related_Service__r {...}`, inject `FSL__Related_Service__c { value } as a peer field`
1140
+ const [, captureGroup] = customFieldMatches;
1141
+ spanningRecordIdFields.push(`${captureGroup}c`);
1142
+ }
1143
+ else {
1144
+ // For `Owner {...}`, inject `OwnerId { value } as a peer field`
1145
+ spanningRecordIdFields.push(`${selection.name}Id`);
1146
+ }
1147
+ }
1148
+ }
1149
+ //Add all missing reference IDs to the set of selections
1150
+ for (let i = 0; i < spanningRecordIdFields.length; i++) {
1151
+ const idField = spanningRecordIdFields[i];
1152
+ if (selections.findIndex((e) => e.kind === 'ObjectFieldSelection' && e.name === idField) >
1153
+ -1) {
1154
+ continue;
1155
+ }
1156
+ selections.push({
1157
+ kind: 'ObjectFieldSelection',
1158
+ name: idField,
1159
+ luvioSelections: [{ kind: 'ScalarFieldSelection', name: 'value' }],
1160
+ });
1161
+ }
1162
+ return selections;
1163
+ }
1164
+ function serializeCustomFieldRecord(def, state) {
1165
+ const { luvioSelections } = def;
1166
+ if (state.fragments[defaultRecordFieldsFragmentName] === undefined) {
1167
+ state.fragments[defaultRecordFieldsFragmentName] = defaultRecordFieldsFragment;
1168
+ }
1169
+ const selections = appendSpanningRecordIds(luvioSelections);
1170
+ return `${serializeFieldNodeName(def)} { ${serializeRecordSelections(selections, state)} ...${defaultRecordFieldsFragmentName} }`;
1171
+ }
1172
+ function serializeArguments(argDefinitions) {
1173
+ if (argDefinitions === undefined) {
1174
+ return '';
1175
+ }
1176
+ let str = '';
1177
+ for (let i = 0, len = argDefinitions.length; i < len; i += 1) {
1178
+ let def = serializeArgument(argDefinitions[i]);
1179
+ if (i !== 0) {
1180
+ def = ` ${def}`;
1181
+ }
1182
+ str = `${str}${def}`;
1183
+ }
1184
+ return str;
1185
+ }
1186
+ function serializeArgument(argDefinition) {
1187
+ const { name, value } = argDefinition;
1188
+ return `${name}: ${serializeValueNode(value)}`;
1189
1189
  }
1190
1190
 
1191
- function serializeValueNode(valueDefinition) {
1192
- const { kind } = valueDefinition;
1193
- switch (kind) {
1194
- case 'ObjectValue':
1195
- return serializeObjectValueNode(valueDefinition);
1196
- case 'StringValue':
1197
- return serializeStringValueNode(valueDefinition);
1198
- case 'NullValue':
1199
- return 'null';
1200
- case 'FloatValue':
1201
- case 'IntValue':
1202
- case 'BooleanValue':
1203
- case 'EnumValue':
1204
- return valueDefinition.value;
1205
- case 'Variable':
1206
- return serializeVariableNode(valueDefinition);
1207
- case 'ListValue':
1208
- return serializeListValueNode(valueDefinition);
1209
- }
1210
- if (process.env.NODE_ENV !== 'production') {
1211
- throw new Error(`Unable to serialize graphql query, unsupported value node "${kind}"`);
1212
- }
1213
- }
1214
- function serializeVariableNode(variableNode) {
1215
- return `$${variableNode.name}`;
1216
- }
1217
- function serializeListValueNode(listNode) {
1218
- const { values } = listNode;
1219
- if (values.length === 0) {
1220
- return '';
1221
- }
1222
- let str = '';
1223
- for (let i = 0, len = values.length; i < len; i += 1) {
1224
- str = `${str}${serializeValueNode(values[i])}, `;
1225
- }
1226
- return `[${str.substring(0, str.length - 2)}]`;
1227
- }
1228
- function serializeStringValueNode(literalValueNode) {
1229
- return `"${literalValueNode.value}"`;
1230
- }
1231
- function serializeObjectValueNode(objectValueDefinition) {
1232
- const { fields } = objectValueDefinition;
1233
- let str = [];
1234
- const fieldKeys = keys(fields);
1235
- for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
1236
- const fieldKey = fieldKeys[i];
1237
- str.push(`${fieldKey}: ${serializeValueNode(fields[fieldKey])}`);
1238
- }
1239
- return `{ ${str.join(', ')} }`;
1240
- }
1241
- function serializeVariableDefinitions(definitons) {
1242
- if (definitons === undefined || definitons.length === 0) {
1243
- return '';
1244
- }
1245
- let str = '';
1246
- for (let i = 0, len = definitons.length; i < len; i += 1) {
1247
- const def = serializeVariableDefinitionNode(definitons[i]);
1248
- str = `${str}${def}, `;
1249
- }
1250
- return ` (${str.substring(0, str.length - 2)})`;
1251
- }
1252
- function serializeVariableDefinitionNode(def) {
1253
- const { variable, type, defaultValue } = def;
1254
- return defaultValue === undefined
1255
- ? `$${variable.name}: ${serializeTypeNode(type)}`
1256
- : `$${variable.name}: ${serializeTypeNode(type)} = ${serializeValueNode(defaultValue)}`;
1257
- }
1258
- function serializeTypeNode(type) {
1259
- const { kind } = type;
1260
- switch (kind) {
1261
- case 'NamedType':
1262
- return serializeNamedTypeNode(type);
1263
- case 'ListType':
1264
- return serializeListTypeNode(type);
1265
- }
1266
- if (process.env.NODE_ENV !== 'production') {
1267
- throw new Error(`Unable to serialize graphql query, unsupported variable definition type node "${type.kind}"`);
1268
- }
1269
- return '';
1270
- }
1271
- function serializeNamedTypeNode(type) {
1272
- return type.name;
1273
- }
1274
- function serializeListTypeNode(type) {
1275
- return `[${serializeTypeNode(type.type)}]`;
1276
- }
1277
- function serializeOperationNode(def, state) {
1278
- const { kind } = def;
1279
- switch (kind) {
1280
- case 'OperationDefinition':
1281
- return serializeOperationDefinition(def, state);
1282
- }
1283
- if (process.env.NODE_ENV !== 'production') {
1284
- throw new Error(`Unable to serialize graphql query, unsupported OperationDefinition type "${kind}"`);
1285
- }
1286
- }
1287
- function serializeOperationDefinition(def, state) {
1288
- const { operation, luvioSelections, name, variableDefinitions } = def;
1289
- const nameStr = name === undefined ? ' ' : ` ${name} `;
1290
- return `${operation}${nameStr}${serializeVariableDefinitions(variableDefinitions)}{ ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1291
- }
1292
- function applyFragments(str, fragments) {
1293
- let appliedString = str;
1294
- const fragmentNames = Object.keys(fragments);
1295
- for (let i = 0, len = fragmentNames.length; i < len; i += 1) {
1296
- const name = fragmentNames[i];
1297
- appliedString = `${appliedString} ${fragments[name]}`;
1298
- }
1299
- return appliedString;
1300
- }
1301
- function astToString(ast) {
1302
- const { definitions } = ast;
1303
- const state = {
1304
- fragments: {},
1305
- };
1306
- let str = '';
1307
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1308
- const def = serializeOperationNode(definitions[i], state);
1309
- str = `${str}${def}`;
1310
- }
1311
- return applyFragments(str, state.fragments);
1191
+ function serializeValueNode(valueDefinition) {
1192
+ const { kind } = valueDefinition;
1193
+ switch (kind) {
1194
+ case 'ObjectValue':
1195
+ return serializeObjectValueNode(valueDefinition);
1196
+ case 'StringValue':
1197
+ return serializeStringValueNode(valueDefinition);
1198
+ case 'NullValue':
1199
+ return 'null';
1200
+ case 'FloatValue':
1201
+ case 'IntValue':
1202
+ case 'BooleanValue':
1203
+ case 'EnumValue':
1204
+ return valueDefinition.value;
1205
+ case 'Variable':
1206
+ return serializeVariableNode(valueDefinition);
1207
+ case 'ListValue':
1208
+ return serializeListValueNode(valueDefinition);
1209
+ }
1210
+ if (process.env.NODE_ENV !== 'production') {
1211
+ throw new Error(`Unable to serialize graphql query, unsupported value node "${kind}"`);
1212
+ }
1213
+ }
1214
+ function serializeVariableNode(variableNode) {
1215
+ return `$${variableNode.name}`;
1216
+ }
1217
+ function serializeListValueNode(listNode) {
1218
+ const { values } = listNode;
1219
+ if (values.length === 0) {
1220
+ return '';
1221
+ }
1222
+ let str = '';
1223
+ for (let i = 0, len = values.length; i < len; i += 1) {
1224
+ str = `${str}${serializeValueNode(values[i])}, `;
1225
+ }
1226
+ return `[${str.substring(0, str.length - 2)}]`;
1227
+ }
1228
+ function serializeStringValueNode(literalValueNode) {
1229
+ return `"${literalValueNode.value}"`;
1230
+ }
1231
+ function serializeObjectValueNode(objectValueDefinition) {
1232
+ const { fields } = objectValueDefinition;
1233
+ let str = [];
1234
+ const fieldKeys = keys(fields);
1235
+ for (let i = 0, len = fieldKeys.length; i < len; i += 1) {
1236
+ const fieldKey = fieldKeys[i];
1237
+ str.push(`${fieldKey}: ${serializeValueNode(fields[fieldKey])}`);
1238
+ }
1239
+ return `{ ${str.join(', ')} }`;
1240
+ }
1241
+ function serializeVariableDefinitions(definitons) {
1242
+ if (definitons === undefined || definitons.length === 0) {
1243
+ return '';
1244
+ }
1245
+ let str = '';
1246
+ for (let i = 0, len = definitons.length; i < len; i += 1) {
1247
+ const def = serializeVariableDefinitionNode(definitons[i]);
1248
+ str = `${str}${def}, `;
1249
+ }
1250
+ return ` (${str.substring(0, str.length - 2)})`;
1251
+ }
1252
+ function serializeVariableDefinitionNode(def) {
1253
+ const { variable, type, defaultValue } = def;
1254
+ return defaultValue === undefined
1255
+ ? `$${variable.name}: ${serializeTypeNode(type)}`
1256
+ : `$${variable.name}: ${serializeTypeNode(type)} = ${serializeValueNode(defaultValue)}`;
1257
+ }
1258
+ function serializeTypeNode(type) {
1259
+ const { kind } = type;
1260
+ switch (kind) {
1261
+ case 'NamedType':
1262
+ return serializeNamedTypeNode(type);
1263
+ case 'ListType':
1264
+ return serializeListTypeNode(type);
1265
+ }
1266
+ if (process.env.NODE_ENV !== 'production') {
1267
+ throw new Error(`Unable to serialize graphql query, unsupported variable definition type node "${type.kind}"`);
1268
+ }
1269
+ return '';
1270
+ }
1271
+ function serializeNamedTypeNode(type) {
1272
+ return type.name;
1273
+ }
1274
+ function serializeListTypeNode(type) {
1275
+ return `[${serializeTypeNode(type.type)}]`;
1276
+ }
1277
+ function serializeOperationNode(def, state) {
1278
+ const { kind } = def;
1279
+ switch (kind) {
1280
+ case 'OperationDefinition':
1281
+ return serializeOperationDefinition(def, state);
1282
+ }
1283
+ if (process.env.NODE_ENV !== 'production') {
1284
+ throw new Error(`Unable to serialize graphql query, unsupported OperationDefinition type "${kind}"`);
1285
+ }
1286
+ }
1287
+ function serializeOperationDefinition(def, state) {
1288
+ const { operation, luvioSelections, name, variableDefinitions } = def;
1289
+ const nameStr = name === undefined ? ' ' : ` ${name} `;
1290
+ return `${operation}${nameStr}${serializeVariableDefinitions(variableDefinitions)}{ ${TYPENAME_FIELD} ${serializeSelections(luvioSelections, state)} }`;
1291
+ }
1292
+ function applyFragments(str, fragments) {
1293
+ let appliedString = str;
1294
+ const fragmentNames = Object.keys(fragments);
1295
+ for (let i = 0, len = fragmentNames.length; i < len; i += 1) {
1296
+ const name = fragmentNames[i];
1297
+ appliedString = `${appliedString} ${fragments[name]}`;
1298
+ }
1299
+ return appliedString;
1300
+ }
1301
+ function astToString(ast) {
1302
+ const { definitions } = ast;
1303
+ const state = {
1304
+ fragments: {},
1305
+ };
1306
+ let str = '';
1307
+ for (let i = 0, len = definitions.length; i < len; i += 1) {
1308
+ const def = serializeOperationNode(definitions[i], state);
1309
+ str = `${str}${def}`;
1310
+ }
1311
+ return applyFragments(str, state.fragments);
1312
1312
  }
1313
1313
 
1314
- function isGraphQLVariables(unknown) {
1315
- return untrustedIsObject(unknown);
1316
- }
1317
- function validateVariableDefinitions(definitons, variables) {
1318
- const errors = [];
1319
- for (let i = 0, len = definitons.length; i < len; i += 1) {
1320
- const { variable, type, defaultValue } = definitons[i];
1321
- const value = getVariableValue(variable.name, variables, defaultValue);
1322
- if (value === undefined) {
1323
- errors.push(`Variable $${variable.name} has an undefined value provided for it.`);
1324
- }
1325
- if (type.kind === 'NonNullType' && value === null) {
1326
- errors.push(`Expected a non-null value to be provided as value for $${variable.name}`);
1327
- }
1328
- if (type.kind === 'ListType' && value !== null && !Array.isArray(value)) {
1329
- errors.push(`Expected a list to be provided as value for $${variable.name}`);
1330
- }
1331
- }
1332
- return errors;
1333
- }
1334
- function getVariableValue(name, variables, defaultValue) {
1335
- if (name in variables) {
1336
- return variables[name];
1337
- }
1338
- if (defaultValue === undefined) {
1339
- return null;
1340
- }
1341
- return defaultValue;
1314
+ function isGraphQLVariables(unknown) {
1315
+ return untrustedIsObject(unknown);
1316
+ }
1317
+ function validateVariableDefinitions(definitons, variables) {
1318
+ const errors = [];
1319
+ for (let i = 0, len = definitons.length; i < len; i += 1) {
1320
+ const { variable, type, defaultValue } = definitons[i];
1321
+ const value = getVariableValue(variable.name, variables, defaultValue);
1322
+ if (value === undefined) {
1323
+ errors.push(`Variable $${variable.name} has an undefined value provided for it.`);
1324
+ }
1325
+ if (type.kind === 'NonNullType' && value === null) {
1326
+ errors.push(`Expected a non-null value to be provided as value for $${variable.name}`);
1327
+ }
1328
+ if (type.kind === 'ListType' && value !== null && !Array.isArray(value)) {
1329
+ errors.push(`Expected a list to be provided as value for $${variable.name}`);
1330
+ }
1331
+ }
1332
+ return errors;
1333
+ }
1334
+ function getVariableValue(name, variables, defaultValue) {
1335
+ if (name in variables) {
1336
+ return variables[name];
1337
+ }
1338
+ if (defaultValue === undefined) {
1339
+ return null;
1340
+ }
1341
+ return defaultValue;
1342
1342
  }
1343
1343
 
1344
- function validate$1(ast, variables) {
1345
- const { variableDefinitions } = ast;
1346
- const errors = [];
1347
- if (variableDefinitions !== undefined) {
1348
- errors.push(...validateVariableDefinitions(variableDefinitions, variables));
1349
- }
1350
- return errors;
1344
+ function validate$1(ast, variables) {
1345
+ const { variableDefinitions } = ast;
1346
+ const errors = [];
1347
+ if (variableDefinitions !== undefined) {
1348
+ errors.push(...validateVariableDefinitions(variableDefinitions, variables));
1349
+ }
1350
+ return errors;
1351
1351
  }
1352
1352
 
1353
- function isLuvioDocumentNode(unknown) {
1354
- if (untrustedIsObject(unknown) === true &&
1355
- hasOwnProperty.call(unknown, 'kind') === true &&
1356
- hasOwnProperty.call(unknown, 'definitions') === true) {
1357
- return (typeof unknown.kind === 'string' &&
1358
- isArray(unknown.definitions));
1359
- }
1360
- return false;
1361
- }
1362
- const createRead = (luvio, ast, variables) => {
1363
- const definitions = ast.definitions === undefined ? [] : ast.definitions;
1364
- return (source, builder) => {
1365
- builder.enterPath('data');
1366
- let sink = {};
1367
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1368
- const def = definitions[i];
1369
- if (def.kind !== 'OperationDefinition') {
1370
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1371
- throw new Error(`Unsupported document definition "${def.kind}"`);
1372
- }
1373
- const data = createRead$1(luvio, def, variables)(source, builder);
1374
- sink = {
1375
- ...sink,
1376
- ...data,
1377
- };
1378
- }
1379
- const gqlData = {};
1380
- builder.assignNonScalar(gqlData, 'data', sink);
1381
- builder.exitPath();
1382
- builder.enterPath('errors');
1383
- builder.assignNonScalar(gqlData, 'errors', []);
1384
- builder.exitPath();
1385
- return gqlData;
1386
- };
1387
- };
1388
- function createIngest(ast, variables) {
1389
- const definitions = ast.definitions === undefined ? [] : ast.definitions;
1390
- return (data, path, luvio, store, timestamp) => {
1391
- const key = path.fullPath;
1392
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1393
- const def = definitions[i];
1394
- if (def.kind !== 'OperationDefinition') {
1395
- // eslint-disable-next-line @salesforce/lds/no-error-in-production
1396
- throw new Error(`Unsupported document definition "${def.kind}"`);
1397
- }
1398
- createIngest$2(def, variables)(data, {
1399
- parent: null,
1400
- fullPath: key,
1401
- propertyName: null,
1402
- }, luvio, store, timestamp);
1403
- }
1404
- return {
1405
- __ref: key,
1406
- };
1407
- };
1408
- }
1409
- function validate(ast, variables) {
1410
- const errors = [];
1411
- const { definitions } = ast;
1412
- for (let i = 0, len = definitions.length; i < len; i += 1) {
1413
- const def = definitions[i];
1414
- if (def.kind !== 'OperationDefinition') {
1415
- errors.push(`Unsupported document definition "${def.kind}"`);
1416
- }
1417
- else {
1418
- errors.push(...validate$1(def, variables));
1419
- }
1420
- }
1421
- return errors;
1353
+ function isLuvioDocumentNode(unknown) {
1354
+ if (untrustedIsObject(unknown) === true &&
1355
+ hasOwnProperty.call(unknown, 'kind') === true &&
1356
+ hasOwnProperty.call(unknown, 'definitions') === true) {
1357
+ return (typeof unknown.kind === 'string' &&
1358
+ isArray(unknown.definitions));
1359
+ }
1360
+ return false;
1361
+ }
1362
+ const createRead = (luvio, ast, variables) => {
1363
+ const definitions = ast.definitions === undefined ? [] : ast.definitions;
1364
+ return (source, builder) => {
1365
+ builder.enterPath('data');
1366
+ let sink = {};
1367
+ for (let i = 0, len = definitions.length; i < len; i += 1) {
1368
+ const def = definitions[i];
1369
+ if (def.kind !== 'OperationDefinition') {
1370
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1371
+ throw new Error(`Unsupported document definition "${def.kind}"`);
1372
+ }
1373
+ const data = createRead$1(luvio, def, variables)(source, builder);
1374
+ sink = {
1375
+ ...sink,
1376
+ ...data,
1377
+ };
1378
+ }
1379
+ const gqlData = {};
1380
+ builder.assignNonScalar(gqlData, 'data', sink);
1381
+ builder.exitPath();
1382
+ builder.enterPath('errors');
1383
+ builder.assignNonScalar(gqlData, 'errors', []);
1384
+ builder.exitPath();
1385
+ return gqlData;
1386
+ };
1387
+ };
1388
+ function createIngest(ast, variables) {
1389
+ const definitions = ast.definitions === undefined ? [] : ast.definitions;
1390
+ return (data, path, luvio, store, timestamp) => {
1391
+ const key = path.fullPath;
1392
+ for (let i = 0, len = definitions.length; i < len; i += 1) {
1393
+ const def = definitions[i];
1394
+ if (def.kind !== 'OperationDefinition') {
1395
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1396
+ throw new Error(`Unsupported document definition "${def.kind}"`);
1397
+ }
1398
+ createIngest$2(def, variables)(data, {
1399
+ parent: null,
1400
+ fullPath: key,
1401
+ propertyName: null,
1402
+ }, luvio, store, timestamp);
1403
+ }
1404
+ return {
1405
+ __ref: key,
1406
+ };
1407
+ };
1408
+ }
1409
+ function validate(ast, variables) {
1410
+ const errors = [];
1411
+ const { definitions } = ast;
1412
+ for (let i = 0, len = definitions.length; i < len; i += 1) {
1413
+ const def = definitions[i];
1414
+ if (def.kind !== 'OperationDefinition') {
1415
+ errors.push(`Unsupported document definition "${def.kind}"`);
1416
+ }
1417
+ else {
1418
+ errors.push(...validate$1(def, variables));
1419
+ }
1420
+ }
1421
+ return errors;
1422
1422
  }
1423
1423
 
1424
- let storeEval = undefined;
1425
- const configuration = {
1426
- setStoreEval: function (storeEvalArg) {
1427
- storeEval = storeEvalArg;
1428
- },
1424
+ let storeEval = undefined;
1425
+ const configuration = {
1426
+ setStoreEval: function (storeEvalArg) {
1427
+ storeEval = storeEvalArg;
1428
+ },
1429
1429
  };
1430
1430
 
1431
- const assignedToMe = {
1432
- kind: 'CustomFieldSelection',
1433
- name: 'ServiceResources',
1434
- type: 'Connection',
1435
- luvioSelections: [
1436
- {
1437
- kind: 'ObjectFieldSelection',
1438
- name: 'edges',
1439
- luvioSelections: [
1440
- {
1441
- kind: 'CustomFieldSelection',
1442
- name: 'node',
1443
- type: 'Record',
1444
- luvioSelections: [
1445
- {
1446
- kind: 'ObjectFieldSelection',
1447
- name: 'ServiceResourceId',
1448
- luvioSelections: [
1449
- {
1450
- kind: 'ScalarFieldSelection',
1451
- name: 'value',
1452
- },
1453
- ],
1454
- },
1455
- {
1456
- kind: 'ObjectFieldSelection',
1457
- name: 'ServiceAppointmentId',
1458
- luvioSelections: [
1459
- {
1460
- kind: 'ScalarFieldSelection',
1461
- name: 'value',
1462
- },
1463
- ],
1464
- },
1465
- {
1466
- kind: 'CustomFieldSelection',
1467
- name: 'ServiceResource',
1468
- type: 'Record',
1469
- luvioSelections: [
1470
- {
1471
- kind: 'ScalarFieldSelection',
1472
- name: 'Id',
1473
- },
1474
- {
1475
- kind: 'ObjectFieldSelection',
1476
- name: 'RelatedRecordId',
1477
- luvioSelections: [
1478
- {
1479
- kind: 'ScalarFieldSelection',
1480
- name: 'value',
1481
- },
1482
- ],
1483
- },
1484
- ],
1485
- },
1486
- ],
1487
- },
1488
- ],
1489
- },
1490
- ],
1491
- };
1492
- function shouldInjectFields(ast) {
1493
- let injectScope = false;
1494
- const recordNodes = findRecordSelections(ast);
1495
- if (recordNodes !== undefined && recordNodes.length > 0) {
1496
- for (const recordNode of recordNodes) {
1497
- if (recordNode.arguments !== undefined) {
1498
- for (const argument of recordNode.arguments) {
1499
- if (argument.name === 'scope' &&
1500
- argument.value.kind === 'EnumValue' &&
1501
- argument.value.value === 'ASSIGNEDTOME') {
1502
- injectScope = true;
1503
- break;
1504
- }
1505
- }
1506
- }
1507
- }
1508
- }
1509
- return injectScope;
1510
- }
1511
- function injectFieldsGQL(ast) {
1512
- return injectScopeFields(ast);
1513
- }
1514
- function injectScopeFields(ast) {
1515
- const modifiedDocumentNode = {
1516
- kind: 'Document',
1517
- definitions: [
1518
- {
1519
- kind: 'OperationDefinition',
1520
- operation: 'query',
1521
- luvioSelections: [
1522
- {
1523
- kind: 'ObjectFieldSelection',
1524
- name: 'uiapi',
1525
- luvioSelections: [
1526
- {
1527
- kind: 'ObjectFieldSelection',
1528
- name: 'query',
1529
- luvioSelections: [],
1530
- },
1531
- ],
1532
- },
1533
- ],
1534
- },
1535
- ],
1536
- };
1537
- const modifiedSelections = [];
1538
- const recordNodes = findRecordSelections(ast);
1539
- if (recordNodes !== undefined && recordNodes.length > 0) {
1540
- // each record node represent a connection
1541
- for (const recordNode of recordNodes) {
1542
- modifiedSelections.push(injectConnectionForScope(recordNode));
1543
- }
1544
- }
1545
- const queryNode = modifiedDocumentNode.definitions
1546
- .filter(isOperationDefinition)
1547
- .reduce(flatMap(luvioSelections), [])
1548
- .filter(isObjectFieldSelection)
1549
- .filter(named('uiapi'))
1550
- .reduce(flatMap(luvioSelections), [])
1551
- .filter(isObjectFieldSelection)
1552
- .filter(named('query'))[0];
1553
- queryNode.luvioSelections.push(...modifiedSelections);
1554
- return ast;
1555
- }
1556
- function injectConnectionForScope(connectionNode) {
1557
- if (connectionNode.name === 'ServiceAppointment') {
1558
- if (connectionNode.arguments !== undefined) {
1559
- for (const argument of connectionNode.arguments) {
1560
- if (argument.name === 'scope' &&
1561
- argument.value.kind === 'EnumValue' &&
1562
- argument.value.value === 'ASSIGNEDTOME') {
1563
- const injectedConnctionNode = {
1564
- ...connectionNode,
1565
- };
1566
- if (injectedConnctionNode.luvioSelections !== undefined) {
1567
- const injectedNodes = injectedConnctionNode.luvioSelections
1568
- .filter(isObjectFieldSelection)
1569
- .filter(named('edges'))
1570
- .reduce(flatMap(luvioSelections), [])
1571
- .filter(isCustomFieldNode)
1572
- .filter(named('node'));
1573
- if (injectedNodes !== undefined && injectedNodes.length > 0) {
1574
- const injectedNode = injectedNodes[0];
1575
- if (injectedNode.luvioSelections !== undefined) {
1576
- injectedNode.luvioSelections = mergeSelectionNodes(injectedNode.luvioSelections, [assignedToMe]);
1577
- }
1578
- }
1579
- }
1580
- return injectedConnctionNode;
1581
- }
1582
- }
1583
- }
1584
- }
1585
- return { ...connectionNode };
1586
- }
1587
- function mergeSelectionNodes(group1, group2) {
1588
- let sameFields1 = [];
1589
- let sameFields2 = [];
1590
- let results = [];
1591
- for (const node2 of group2) {
1592
- if (isCustomFieldNode(node2)) {
1593
- const nodes1SameLevel = group1
1594
- .filter(isCustomFieldNode)
1595
- .filter((node1) => node1.name === node2.name && node1.type === node2.type);
1596
- if (nodes1SameLevel.length > 0) {
1597
- sameFields1.push(...nodes1SameLevel);
1598
- sameFields2.push(node2);
1599
- const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), node2);
1600
- results.push(mergedNode);
1601
- }
1602
- }
1603
- else if (isObjectFieldSelection(node2)) {
1604
- const nodes1SameLevel = group1
1605
- .filter(isObjectFieldSelection)
1606
- .filter((node1) => node1.name === node2.name);
1607
- if (nodes1SameLevel.length > 0) {
1608
- sameFields1.push(...nodes1SameLevel);
1609
- sameFields2.push(node2);
1610
- const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), node2);
1611
- results.push(mergedNode);
1612
- }
1613
- }
1614
- }
1615
- if (sameFields1.length > 0) {
1616
- const differentNodes1 = group1.filter((node) => !sameFields1.includes(node));
1617
- results.push(...differentNodes1);
1618
- const differentNodes2 = group2.filter((node) => !sameFields2.includes(node));
1619
- results.push(...differentNodes2);
1620
- }
1621
- else {
1622
- return group1.concat(group2);
1623
- }
1624
- return results;
1625
- }
1626
- function mergeCustomFieldNodes(node1, node2) {
1627
- let result = node1;
1628
- if (node1.name === node2.name && node1.kind === node2.kind && node1.type === node2.type) {
1629
- result = {
1630
- kind: node1.kind,
1631
- name: node1.name,
1632
- type: node1.type,
1633
- luvioSelections: [],
1634
- };
1635
- let selections = [];
1636
- let sameCustomFields1 = [];
1637
- let sameCustomFields2 = [];
1638
- let sameObjectFields1 = [];
1639
- let sameObjectFields2 = [];
1640
- let sameScalarFields1 = [];
1641
- let sameScalarFields2 = [];
1642
- if (node1.luvioSelections && node2.luvioSelections) {
1643
- sameCustomFields1 = node1.luvioSelections
1644
- .filter(isCustomFieldNode)
1645
- .filter((childNode1) => {
1646
- if (node2.luvioSelections) {
1647
- const sames = node2.luvioSelections
1648
- .filter(isCustomFieldNode)
1649
- .filter((childNode2) => childNode2.name === childNode1.name);
1650
- if (sames.length > 0) {
1651
- const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1652
- selections.push(mergedNode);
1653
- result = {
1654
- ...result,
1655
- luvioSelections: selections,
1656
- };
1657
- sameCustomFields2.push(...sames);
1658
- return true;
1659
- }
1660
- }
1661
- return false;
1662
- });
1663
- sameObjectFields1 = node1.luvioSelections
1664
- .filter(isObjectFieldSelection)
1665
- .filter((childNode1) => {
1666
- if (node2.luvioSelections) {
1667
- const sames = node2.luvioSelections
1668
- .filter(isObjectFieldSelection)
1669
- .filter((childNode2) => childNode2.name === childNode1.name);
1670
- if (sames.length > 0) {
1671
- const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1672
- selections.push(mergedNode);
1673
- result = {
1674
- ...result,
1675
- luvioSelections: selections,
1676
- };
1677
- sameObjectFields2.push(...sames);
1678
- return true;
1679
- }
1680
- }
1681
- return false;
1682
- });
1683
- sameScalarFields1 = node1.luvioSelections
1684
- .filter(isScalarFieldNode)
1685
- .filter((childNode1) => {
1686
- if (node2.luvioSelections) {
1687
- const sames = node2.luvioSelections
1688
- .filter(isScalarFieldNode)
1689
- .filter((childNode2) => childNode2.name === childNode1.name);
1690
- if (sames.length > 0) {
1691
- const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1692
- selections.push(mergedNode);
1693
- result = {
1694
- ...result,
1695
- luvioSelections: selections,
1696
- };
1697
- sameScalarFields2.push(...sames);
1698
- return true;
1699
- }
1700
- }
1701
- return false;
1702
- });
1703
- if (sameCustomFields1.length > 0 ||
1704
- sameObjectFields1.length > 0 ||
1705
- sameScalarFields1.length > 0) {
1706
- const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1707
- !sameObjectFields1.includes(node) &&
1708
- !sameScalarFields1.includes(node));
1709
- selections.push(...diffNodes1);
1710
- const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1711
- !sameObjectFields2.includes(node) &&
1712
- !sameScalarFields2.includes(node));
1713
- selections.push(...diffNodes2);
1714
- result = {
1715
- ...result,
1716
- luvioSelections: selections,
1717
- };
1718
- }
1719
- else {
1720
- selections.push(...node1.luvioSelections);
1721
- selections.push(...node2.luvioSelections);
1722
- result = {
1723
- ...result,
1724
- luvioSelections: selections,
1725
- };
1726
- }
1727
- }
1728
- else {
1729
- if (node1.luvioSelections) {
1730
- return node1;
1731
- }
1732
- if (node2.luvioSelections) {
1733
- return node2;
1734
- }
1735
- }
1736
- return result;
1737
- }
1738
- else {
1739
- // eslint-disable-next-line
1740
- throw new Error('The fields name needs to be same to be merged');
1741
- }
1742
- }
1743
- function mergeObjectFieldNodes(node1, node2) {
1744
- let result = node1;
1745
- if (node1.name === node2.name && node1.kind === node2.kind) {
1746
- result = {
1747
- kind: node1.kind,
1748
- name: node1.name,
1749
- directives: node1.directives,
1750
- luvioSelections: [],
1751
- };
1752
- let selections = [];
1753
- let sameCustomFields1 = [];
1754
- let sameCustomFields2 = [];
1755
- let sameObjectFields1 = [];
1756
- let sameObjectFields2 = [];
1757
- let sameScalarFields1 = [];
1758
- let sameScalarFields2 = [];
1759
- if (node1.luvioSelections && node2.luvioSelections) {
1760
- sameCustomFields1 = node1.luvioSelections
1761
- .filter(isCustomFieldNode)
1762
- .filter((childNode1) => {
1763
- if (node2.luvioSelections) {
1764
- const sames = node2.luvioSelections
1765
- .filter(isCustomFieldNode)
1766
- .filter((childNode2) => childNode2.name === childNode1.name);
1767
- if (sames.length > 0) {
1768
- const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1769
- selections.push(mergedNode);
1770
- result = {
1771
- ...result,
1772
- luvioSelections: selections,
1773
- };
1774
- sameCustomFields2.push(...sames);
1775
- return true;
1776
- }
1777
- }
1778
- return false;
1779
- });
1780
- sameObjectFields1 = node1.luvioSelections
1781
- .filter(isObjectFieldSelection)
1782
- .filter((childNode1) => {
1783
- if (node2.luvioSelections) {
1784
- const sames = node2.luvioSelections
1785
- .filter(isObjectFieldSelection)
1786
- .filter((childNode2) => childNode2.name === childNode1.name);
1787
- if (sames.length > 0) {
1788
- const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1789
- selections.push(mergedNode);
1790
- result = {
1791
- ...result,
1792
- luvioSelections: selections,
1793
- };
1794
- sameObjectFields2.push(...sames);
1795
- return true;
1796
- }
1797
- }
1798
- return false;
1799
- });
1800
- sameScalarFields1 = node1.luvioSelections
1801
- .filter(isScalarFieldNode)
1802
- .filter((childNode1) => {
1803
- if (node2.luvioSelections) {
1804
- const sames = node2.luvioSelections
1805
- .filter(isScalarFieldNode)
1806
- .filter((childNode2) => childNode2.name === childNode1.name);
1807
- if (sames.length > 0) {
1808
- const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1809
- selections.push(mergedNode);
1810
- result = {
1811
- ...result,
1812
- luvioSelections: selections,
1813
- };
1814
- sameScalarFields2.push(...sames);
1815
- return true;
1816
- }
1817
- }
1818
- return false;
1819
- });
1820
- if (sameCustomFields1.length > 0 ||
1821
- sameObjectFields1.length > 0 ||
1822
- sameScalarFields1.length > 0) {
1823
- const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1824
- !sameObjectFields1.includes(node) &&
1825
- !sameScalarFields1.includes(node));
1826
- selections.push(...diffNodes1);
1827
- const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1828
- !sameObjectFields2.includes(node) &&
1829
- !sameScalarFields2.includes(node));
1830
- selections.push(...diffNodes2);
1831
- result = {
1832
- ...result,
1833
- luvioSelections: selections,
1834
- };
1835
- }
1836
- else {
1837
- selections.push(...node1.luvioSelections);
1838
- selections.push(...node2.luvioSelections);
1839
- result = {
1840
- ...result,
1841
- luvioSelections: selections,
1842
- };
1843
- }
1844
- }
1845
- else {
1846
- if (node1.luvioSelections) {
1847
- return node1;
1848
- }
1849
- if (node2.luvioSelections) {
1850
- return node2;
1851
- }
1852
- }
1853
- return result;
1854
- }
1855
- else {
1856
- // eslint-disable-next-line
1857
- throw new Error('The fields name needs to be same to be merged');
1858
- }
1859
- }
1860
- function mergeScalarFieldNode(node1, node2) {
1861
- if (node1.kind === node1.kind && node1.name === node2.name) {
1862
- return { ...node1 };
1863
- }
1864
- // eslint-disable-next-line
1865
- throw new Error('The fields name needs to be same to be merged');
1866
- }
1867
- function findRecordSelections(document) {
1868
- return document.definitions
1869
- .filter(isOperationDefinition)
1870
- .reduce(flatMap(luvioSelections), [])
1871
- .filter(isObjectFieldSelection)
1872
- .filter(named('uiapi'))
1873
- .reduce(flatMap(luvioSelections), [])
1874
- .filter(isObjectFieldSelection)
1875
- .filter(named('query'))
1876
- .reduce(flatMap(luvioSelections), [])
1877
- .filter(isCustomFieldNode);
1878
- }
1879
- function isOperationDefinition(node) {
1880
- return node.kind === 'OperationDefinition';
1881
- }
1882
- function isObjectFieldSelection(node) {
1883
- return node !== undefined && node.kind === 'ObjectFieldSelection';
1884
- }
1885
- function isCustomFieldNode(node) {
1886
- return node !== undefined && node.kind === 'CustomFieldSelection';
1887
- }
1888
- function isScalarFieldNode(node) {
1889
- return node !== undefined && node.kind === 'ScalarFieldSelection';
1890
- }
1891
- function flatMap(transform) {
1892
- return (acc, current) => {
1893
- const mapped = transform(current);
1894
- return acc.concat(mapped);
1895
- };
1896
- }
1897
- function luvioSelections(node) {
1898
- return node.luvioSelections === undefined ? [] : node.luvioSelections;
1899
- }
1900
- function named(name) {
1901
- return (node) => node.name === name;
1431
+ const assignedToMe = {
1432
+ kind: 'CustomFieldSelection',
1433
+ name: 'ServiceResources',
1434
+ type: 'Connection',
1435
+ luvioSelections: [
1436
+ {
1437
+ kind: 'ObjectFieldSelection',
1438
+ name: 'edges',
1439
+ luvioSelections: [
1440
+ {
1441
+ kind: 'CustomFieldSelection',
1442
+ name: 'node',
1443
+ type: 'Record',
1444
+ luvioSelections: [
1445
+ {
1446
+ kind: 'ObjectFieldSelection',
1447
+ name: 'ServiceResourceId',
1448
+ luvioSelections: [
1449
+ {
1450
+ kind: 'ScalarFieldSelection',
1451
+ name: 'value',
1452
+ },
1453
+ ],
1454
+ },
1455
+ {
1456
+ kind: 'ObjectFieldSelection',
1457
+ name: 'ServiceAppointmentId',
1458
+ luvioSelections: [
1459
+ {
1460
+ kind: 'ScalarFieldSelection',
1461
+ name: 'value',
1462
+ },
1463
+ ],
1464
+ },
1465
+ {
1466
+ kind: 'CustomFieldSelection',
1467
+ name: 'ServiceResource',
1468
+ type: 'Record',
1469
+ luvioSelections: [
1470
+ {
1471
+ kind: 'ScalarFieldSelection',
1472
+ name: 'Id',
1473
+ },
1474
+ {
1475
+ kind: 'ObjectFieldSelection',
1476
+ name: 'RelatedRecordId',
1477
+ luvioSelections: [
1478
+ {
1479
+ kind: 'ScalarFieldSelection',
1480
+ name: 'value',
1481
+ },
1482
+ ],
1483
+ },
1484
+ ],
1485
+ },
1486
+ ],
1487
+ },
1488
+ ],
1489
+ },
1490
+ ],
1491
+ };
1492
+ function shouldInjectFields(ast) {
1493
+ let injectScope = false;
1494
+ const recordNodes = findRecordSelections(ast);
1495
+ if (recordNodes !== undefined && recordNodes.length > 0) {
1496
+ for (const recordNode of recordNodes) {
1497
+ if (recordNode.arguments !== undefined) {
1498
+ for (const argument of recordNode.arguments) {
1499
+ if (argument.name === 'scope' &&
1500
+ argument.value.kind === 'EnumValue' &&
1501
+ argument.value.value === 'ASSIGNEDTOME') {
1502
+ injectScope = true;
1503
+ break;
1504
+ }
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+ return injectScope;
1510
+ }
1511
+ function injectFieldsGQL(ast) {
1512
+ return injectScopeFields(ast);
1513
+ }
1514
+ function injectScopeFields(ast) {
1515
+ const modifiedDocumentNode = {
1516
+ kind: 'Document',
1517
+ definitions: [
1518
+ {
1519
+ kind: 'OperationDefinition',
1520
+ operation: 'query',
1521
+ luvioSelections: [
1522
+ {
1523
+ kind: 'ObjectFieldSelection',
1524
+ name: 'uiapi',
1525
+ luvioSelections: [
1526
+ {
1527
+ kind: 'ObjectFieldSelection',
1528
+ name: 'query',
1529
+ luvioSelections: [],
1530
+ },
1531
+ ],
1532
+ },
1533
+ ],
1534
+ },
1535
+ ],
1536
+ };
1537
+ const modifiedSelections = [];
1538
+ const recordNodes = findRecordSelections(ast);
1539
+ if (recordNodes !== undefined && recordNodes.length > 0) {
1540
+ // each record node represent a connection
1541
+ for (const recordNode of recordNodes) {
1542
+ modifiedSelections.push(injectConnectionForScope(recordNode));
1543
+ }
1544
+ }
1545
+ const queryNode = modifiedDocumentNode.definitions
1546
+ .filter(isOperationDefinition)
1547
+ .reduce(flatMap(luvioSelections), [])
1548
+ .filter(isObjectFieldSelection)
1549
+ .filter(named('uiapi'))
1550
+ .reduce(flatMap(luvioSelections), [])
1551
+ .filter(isObjectFieldSelection)
1552
+ .filter(named('query'))[0];
1553
+ queryNode.luvioSelections.push(...modifiedSelections);
1554
+ return ast;
1555
+ }
1556
+ function injectConnectionForScope(connectionNode) {
1557
+ if (connectionNode.name === 'ServiceAppointment') {
1558
+ if (connectionNode.arguments !== undefined) {
1559
+ for (const argument of connectionNode.arguments) {
1560
+ if (argument.name === 'scope' &&
1561
+ argument.value.kind === 'EnumValue' &&
1562
+ argument.value.value === 'ASSIGNEDTOME') {
1563
+ const injectedConnctionNode = {
1564
+ ...connectionNode,
1565
+ };
1566
+ if (injectedConnctionNode.luvioSelections !== undefined) {
1567
+ const injectedNodes = injectedConnctionNode.luvioSelections
1568
+ .filter(isObjectFieldSelection)
1569
+ .filter(named('edges'))
1570
+ .reduce(flatMap(luvioSelections), [])
1571
+ .filter(isCustomFieldNode)
1572
+ .filter(named('node'));
1573
+ if (injectedNodes !== undefined && injectedNodes.length > 0) {
1574
+ const injectedNode = injectedNodes[0];
1575
+ if (injectedNode.luvioSelections !== undefined) {
1576
+ injectedNode.luvioSelections = mergeSelectionNodes(injectedNode.luvioSelections, [assignedToMe]);
1577
+ }
1578
+ }
1579
+ }
1580
+ return injectedConnctionNode;
1581
+ }
1582
+ }
1583
+ }
1584
+ }
1585
+ return { ...connectionNode };
1586
+ }
1587
+ function mergeSelectionNodes(group1, group2) {
1588
+ let sameFields1 = [];
1589
+ let sameFields2 = [];
1590
+ let results = [];
1591
+ for (const node2 of group2) {
1592
+ if (isCustomFieldNode(node2)) {
1593
+ const nodes1SameLevel = group1
1594
+ .filter(isCustomFieldNode)
1595
+ .filter((node1) => node1.name === node2.name && node1.type === node2.type);
1596
+ if (nodes1SameLevel.length > 0) {
1597
+ sameFields1.push(...nodes1SameLevel);
1598
+ sameFields2.push(node2);
1599
+ const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), node2);
1600
+ results.push(mergedNode);
1601
+ }
1602
+ }
1603
+ else if (isObjectFieldSelection(node2)) {
1604
+ const nodes1SameLevel = group1
1605
+ .filter(isObjectFieldSelection)
1606
+ .filter((node1) => node1.name === node2.name);
1607
+ if (nodes1SameLevel.length > 0) {
1608
+ sameFields1.push(...nodes1SameLevel);
1609
+ sameFields2.push(node2);
1610
+ const mergedNode = nodes1SameLevel.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), node2);
1611
+ results.push(mergedNode);
1612
+ }
1613
+ }
1614
+ }
1615
+ if (sameFields1.length > 0) {
1616
+ const differentNodes1 = group1.filter((node) => !sameFields1.includes(node));
1617
+ results.push(...differentNodes1);
1618
+ const differentNodes2 = group2.filter((node) => !sameFields2.includes(node));
1619
+ results.push(...differentNodes2);
1620
+ }
1621
+ else {
1622
+ return group1.concat(group2);
1623
+ }
1624
+ return results;
1625
+ }
1626
+ function mergeCustomFieldNodes(node1, node2) {
1627
+ let result = node1;
1628
+ if (node1.name === node2.name && node1.kind === node2.kind && node1.type === node2.type) {
1629
+ result = {
1630
+ kind: node1.kind,
1631
+ name: node1.name,
1632
+ type: node1.type,
1633
+ luvioSelections: [],
1634
+ };
1635
+ let selections = [];
1636
+ let sameCustomFields1 = [];
1637
+ let sameCustomFields2 = [];
1638
+ let sameObjectFields1 = [];
1639
+ let sameObjectFields2 = [];
1640
+ let sameScalarFields1 = [];
1641
+ let sameScalarFields2 = [];
1642
+ if (node1.luvioSelections && node2.luvioSelections) {
1643
+ sameCustomFields1 = node1.luvioSelections
1644
+ .filter(isCustomFieldNode)
1645
+ .filter((childNode1) => {
1646
+ if (node2.luvioSelections) {
1647
+ const sames = node2.luvioSelections
1648
+ .filter(isCustomFieldNode)
1649
+ .filter((childNode2) => childNode2.name === childNode1.name);
1650
+ if (sames.length > 0) {
1651
+ const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1652
+ selections.push(mergedNode);
1653
+ result = {
1654
+ ...result,
1655
+ luvioSelections: selections,
1656
+ };
1657
+ sameCustomFields2.push(...sames);
1658
+ return true;
1659
+ }
1660
+ }
1661
+ return false;
1662
+ });
1663
+ sameObjectFields1 = node1.luvioSelections
1664
+ .filter(isObjectFieldSelection)
1665
+ .filter((childNode1) => {
1666
+ if (node2.luvioSelections) {
1667
+ const sames = node2.luvioSelections
1668
+ .filter(isObjectFieldSelection)
1669
+ .filter((childNode2) => childNode2.name === childNode1.name);
1670
+ if (sames.length > 0) {
1671
+ const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1672
+ selections.push(mergedNode);
1673
+ result = {
1674
+ ...result,
1675
+ luvioSelections: selections,
1676
+ };
1677
+ sameObjectFields2.push(...sames);
1678
+ return true;
1679
+ }
1680
+ }
1681
+ return false;
1682
+ });
1683
+ sameScalarFields1 = node1.luvioSelections
1684
+ .filter(isScalarFieldNode)
1685
+ .filter((childNode1) => {
1686
+ if (node2.luvioSelections) {
1687
+ const sames = node2.luvioSelections
1688
+ .filter(isScalarFieldNode)
1689
+ .filter((childNode2) => childNode2.name === childNode1.name);
1690
+ if (sames.length > 0) {
1691
+ const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1692
+ selections.push(mergedNode);
1693
+ result = {
1694
+ ...result,
1695
+ luvioSelections: selections,
1696
+ };
1697
+ sameScalarFields2.push(...sames);
1698
+ return true;
1699
+ }
1700
+ }
1701
+ return false;
1702
+ });
1703
+ if (sameCustomFields1.length > 0 ||
1704
+ sameObjectFields1.length > 0 ||
1705
+ sameScalarFields1.length > 0) {
1706
+ const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1707
+ !sameObjectFields1.includes(node) &&
1708
+ !sameScalarFields1.includes(node));
1709
+ selections.push(...diffNodes1);
1710
+ const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1711
+ !sameObjectFields2.includes(node) &&
1712
+ !sameScalarFields2.includes(node));
1713
+ selections.push(...diffNodes2);
1714
+ result = {
1715
+ ...result,
1716
+ luvioSelections: selections,
1717
+ };
1718
+ }
1719
+ else {
1720
+ selections.push(...node1.luvioSelections);
1721
+ selections.push(...node2.luvioSelections);
1722
+ result = {
1723
+ ...result,
1724
+ luvioSelections: selections,
1725
+ };
1726
+ }
1727
+ }
1728
+ else {
1729
+ if (node1.luvioSelections) {
1730
+ return node1;
1731
+ }
1732
+ if (node2.luvioSelections) {
1733
+ return node2;
1734
+ }
1735
+ }
1736
+ return result;
1737
+ }
1738
+ else {
1739
+ // eslint-disable-next-line
1740
+ throw new Error('The fields name needs to be same to be merged');
1741
+ }
1742
+ }
1743
+ function mergeObjectFieldNodes(node1, node2) {
1744
+ let result = node1;
1745
+ if (node1.name === node2.name && node1.kind === node2.kind) {
1746
+ result = {
1747
+ kind: node1.kind,
1748
+ name: node1.name,
1749
+ directives: node1.directives,
1750
+ luvioSelections: [],
1751
+ };
1752
+ let selections = [];
1753
+ let sameCustomFields1 = [];
1754
+ let sameCustomFields2 = [];
1755
+ let sameObjectFields1 = [];
1756
+ let sameObjectFields2 = [];
1757
+ let sameScalarFields1 = [];
1758
+ let sameScalarFields2 = [];
1759
+ if (node1.luvioSelections && node2.luvioSelections) {
1760
+ sameCustomFields1 = node1.luvioSelections
1761
+ .filter(isCustomFieldNode)
1762
+ .filter((childNode1) => {
1763
+ if (node2.luvioSelections) {
1764
+ const sames = node2.luvioSelections
1765
+ .filter(isCustomFieldNode)
1766
+ .filter((childNode2) => childNode2.name === childNode1.name);
1767
+ if (sames.length > 0) {
1768
+ const mergedNode = sames.reduce((accu, cur) => mergeCustomFieldNodes(accu, cur), childNode1);
1769
+ selections.push(mergedNode);
1770
+ result = {
1771
+ ...result,
1772
+ luvioSelections: selections,
1773
+ };
1774
+ sameCustomFields2.push(...sames);
1775
+ return true;
1776
+ }
1777
+ }
1778
+ return false;
1779
+ });
1780
+ sameObjectFields1 = node1.luvioSelections
1781
+ .filter(isObjectFieldSelection)
1782
+ .filter((childNode1) => {
1783
+ if (node2.luvioSelections) {
1784
+ const sames = node2.luvioSelections
1785
+ .filter(isObjectFieldSelection)
1786
+ .filter((childNode2) => childNode2.name === childNode1.name);
1787
+ if (sames.length > 0) {
1788
+ const mergedNode = sames.reduce((accu, cur) => mergeObjectFieldNodes(accu, cur), childNode1);
1789
+ selections.push(mergedNode);
1790
+ result = {
1791
+ ...result,
1792
+ luvioSelections: selections,
1793
+ };
1794
+ sameObjectFields2.push(...sames);
1795
+ return true;
1796
+ }
1797
+ }
1798
+ return false;
1799
+ });
1800
+ sameScalarFields1 = node1.luvioSelections
1801
+ .filter(isScalarFieldNode)
1802
+ .filter((childNode1) => {
1803
+ if (node2.luvioSelections) {
1804
+ const sames = node2.luvioSelections
1805
+ .filter(isScalarFieldNode)
1806
+ .filter((childNode2) => childNode2.name === childNode1.name);
1807
+ if (sames.length > 0) {
1808
+ const mergedNode = sames.reduce((accu, cur) => mergeScalarFieldNode(accu, cur), childNode1);
1809
+ selections.push(mergedNode);
1810
+ result = {
1811
+ ...result,
1812
+ luvioSelections: selections,
1813
+ };
1814
+ sameScalarFields2.push(...sames);
1815
+ return true;
1816
+ }
1817
+ }
1818
+ return false;
1819
+ });
1820
+ if (sameCustomFields1.length > 0 ||
1821
+ sameObjectFields1.length > 0 ||
1822
+ sameScalarFields1.length > 0) {
1823
+ const diffNodes1 = node1.luvioSelections.filter((node) => !sameCustomFields1.includes(node) &&
1824
+ !sameObjectFields1.includes(node) &&
1825
+ !sameScalarFields1.includes(node));
1826
+ selections.push(...diffNodes1);
1827
+ const diffNodes2 = node2.luvioSelections.filter((node) => !sameCustomFields2.includes(node) &&
1828
+ !sameObjectFields2.includes(node) &&
1829
+ !sameScalarFields2.includes(node));
1830
+ selections.push(...diffNodes2);
1831
+ result = {
1832
+ ...result,
1833
+ luvioSelections: selections,
1834
+ };
1835
+ }
1836
+ else {
1837
+ selections.push(...node1.luvioSelections);
1838
+ selections.push(...node2.luvioSelections);
1839
+ result = {
1840
+ ...result,
1841
+ luvioSelections: selections,
1842
+ };
1843
+ }
1844
+ }
1845
+ else {
1846
+ if (node1.luvioSelections) {
1847
+ return node1;
1848
+ }
1849
+ if (node2.luvioSelections) {
1850
+ return node2;
1851
+ }
1852
+ }
1853
+ return result;
1854
+ }
1855
+ else {
1856
+ // eslint-disable-next-line
1857
+ throw new Error('The fields name needs to be same to be merged');
1858
+ }
1859
+ }
1860
+ function mergeScalarFieldNode(node1, node2) {
1861
+ if (node1.kind === node1.kind && node1.name === node2.name) {
1862
+ return { ...node1 };
1863
+ }
1864
+ // eslint-disable-next-line
1865
+ throw new Error('The fields name needs to be same to be merged');
1866
+ }
1867
+ function findRecordSelections(document) {
1868
+ return document.definitions
1869
+ .filter(isOperationDefinition)
1870
+ .reduce(flatMap(luvioSelections), [])
1871
+ .filter(isObjectFieldSelection)
1872
+ .filter(named('uiapi'))
1873
+ .reduce(flatMap(luvioSelections), [])
1874
+ .filter(isObjectFieldSelection)
1875
+ .filter(named('query'))
1876
+ .reduce(flatMap(luvioSelections), [])
1877
+ .filter(isCustomFieldNode);
1878
+ }
1879
+ function isOperationDefinition(node) {
1880
+ return node.kind === 'OperationDefinition';
1881
+ }
1882
+ function isObjectFieldSelection(node) {
1883
+ return node !== undefined && node.kind === 'ObjectFieldSelection';
1884
+ }
1885
+ function isCustomFieldNode(node) {
1886
+ return node !== undefined && node.kind === 'CustomFieldSelection';
1887
+ }
1888
+ function isScalarFieldNode(node) {
1889
+ return node !== undefined && node.kind === 'ScalarFieldSelection';
1890
+ }
1891
+ function flatMap(transform) {
1892
+ return (acc, current) => {
1893
+ const mapped = transform(current);
1894
+ return acc.concat(mapped);
1895
+ };
1896
+ }
1897
+ function luvioSelections(node) {
1898
+ return node.luvioSelections === undefined ? [] : node.luvioSelections;
1899
+ }
1900
+ function named(name) {
1901
+ return (node) => node.name === name;
1902
1902
  }
1903
1903
 
1904
- const adapterName = 'graphQL';
1905
- const RECORD_REPRESENTATION_NAME = 'RecordRepresentation';
1906
- const GRAPHQL_ROOT_KEY = `${namespace}::${representationName}`;
1907
- function buildSnapshotRefresh(luvio, config, fragment) {
1908
- return {
1909
- config,
1910
- resolve: () => buildNetworkSnapshot(luvio, config, fragment),
1911
- };
1912
- }
1913
- function createFragment(luvio, query, variables) {
1914
- return {
1915
- kind: 'Fragment',
1916
- synthetic: false,
1917
- reader: true,
1918
- version: GRAPHQL_INGEST_VERSION,
1919
- read: createRead(luvio, query, variables),
1920
- };
1921
- }
1922
- function onFetchResponseSuccess(luvio, config, response, fragment) {
1923
- const { query, variables } = config;
1924
- const { body } = response;
1925
- if (body.errors && body.errors.length > 0) {
1926
- return Promise.resolve(luvio.storeLookup({
1927
- recordId: representationName,
1928
- node: {
1929
- kind: 'Fragment',
1930
- synthetic: true,
1931
- reader: true,
1932
- read: (reader) => {
1933
- const sink = {};
1934
- reader.enterPath('data');
1935
- reader.assignNonScalar(sink, 'data', body.data);
1936
- reader.exitPath();
1937
- reader.enterPath('errors');
1938
- reader.assignNonScalar(sink, 'errors', deepFreeze(body.errors));
1939
- reader.exitPath();
1940
- return sink;
1941
- },
1942
- },
1943
- variables: {},
1944
- }));
1945
- }
1946
- const ingest = createIngest(query, variables);
1947
- luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, body.data);
1948
- const snapshot = luvio.storeLookup({
1949
- recordId: GRAPHQL_ROOT_KEY,
1950
- node: fragment,
1951
- variables: {},
1952
- }, buildSnapshotRefresh(luvio, config, fragment));
1953
- return luvio.storeBroadcast().then(() => snapshot);
1954
- }
1955
- function getResponseCacheKeys(luvio, config, response, fragment) {
1956
- // TODO [W-10147827]: make this more efficient
1957
- // for now we will get the cache keys by actually ingesting then looking at
1958
- // the seenRecords + recordId
1959
- const { query, variables } = config;
1960
- const { body } = response;
1961
- if (body.errors && body.errors.length > 0) {
1962
- return new StoreKeyMap();
1963
- }
1964
- const ingest = createIngest(query, variables);
1965
- // ingest mutates the response so we have to make a copy
1966
- const dataCopy = parse(stringify(body.data));
1967
- luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, dataCopy);
1968
- const snapshot = luvio.storeLookup({
1969
- recordId: GRAPHQL_ROOT_KEY,
1970
- node: fragment,
1971
- variables: {},
1972
- }, buildSnapshotRefresh(luvio, config, fragment));
1973
- if (snapshot.state === 'Error') {
1974
- return new StoreKeyMap();
1975
- }
1976
- const keys = [...snapshot.seenRecords.keysAsArray(), snapshot.recordId];
1977
- const keySet = new StoreKeyMap();
1978
- for (let i = 0, len = keys.length; i < len; i++) {
1979
- const key = keys[i];
1980
- const keyNamespace = key.split('::')[0];
1981
- const representationName = key.split('::')[1].split(':')[0];
1982
- keySet.set(key, {
1983
- namespace: keyNamespace,
1984
- representationName,
1985
- mergeable: keyNamespace === namespace || representationName === RECORD_REPRESENTATION_NAME,
1986
- });
1987
- }
1988
- return keySet;
1989
- }
1990
- function onFetchResponseError(luvio, config, response) {
1991
- const errorSnapshot = luvio.errorSnapshot(response);
1992
- luvio.storeIngestError(GRAPHQL_ROOT_KEY, errorSnapshot);
1993
- return luvio.storeBroadcast().then(() => errorSnapshot);
1994
- }
1995
- function buildNetworkSnapshot(luvio, config, fragment, options) {
1996
- const { variables: queryVariables, query } = config;
1997
- const request = {
1998
- baseUri: '/services/data/v58.0',
1999
- basePath: '/graphql',
2000
- method: 'post',
2001
- priority: 'normal',
2002
- body: {
2003
- query: astToString(query),
2004
- variables: queryVariables,
2005
- },
2006
- queryParams: {},
2007
- urlParams: {},
2008
- headers: {},
2009
- };
2010
- return luvio.dispatchResourceRequest(request, options).then((resp) => {
2011
- return luvio.handleSuccessResponse(() => onFetchResponseSuccess(luvio, config, resp, fragment), () => getResponseCacheKeys(luvio, config, resp, fragment));
2012
- }, (errorResponse) => {
2013
- return luvio.handleErrorResponse(() => onFetchResponseError(luvio, config, errorResponse));
2014
- });
2015
- }
2016
- function validateGraphQlConfig(untrustedConfig) {
2017
- if (!untrustedIsObject(untrustedConfig)) {
2018
- return {
2019
- validatedConfig: null,
2020
- errors: ["Invalid Config provided isn't an object"],
2021
- };
2022
- }
2023
- if (!('variables' in untrustedConfig && 'query' in untrustedConfig)) {
2024
- return {
2025
- validatedConfig: null,
2026
- errors: [
2027
- 'Missing one or both of the required config parameters "query" and "variables"',
2028
- ],
2029
- };
2030
- }
2031
- const { variables, query } = untrustedConfig;
2032
- const validationErrors = [];
2033
- if (isLuvioDocumentNode(query) === false) {
2034
- validationErrors.push('The config parameter "query" isn\'t a valid LuvioDocumentNode');
2035
- }
2036
- const ast = query;
2037
- if (isGraphQLVariables(variables) === false) {
2038
- validationErrors.push('The config parameter "variables" isn\'t an object');
2039
- }
2040
- if (validationErrors.length > 0) {
2041
- return {
2042
- validatedConfig: null,
2043
- errors: validationErrors,
2044
- };
2045
- }
2046
- validationErrors.push(...validate(ast, variables));
2047
- const { useUiApiAdapter } = untrustedConfig;
2048
- if (useUiApiAdapter !== undefined && typeof useUiApiAdapter !== 'boolean') {
2049
- validationErrors.push('The config parameter "useUiApiAdapter" isn\'t a boolean');
2050
- }
2051
- if (validationErrors.length > 0) {
2052
- return {
2053
- validatedConfig: null,
2054
- errors: validationErrors,
2055
- };
2056
- }
2057
- return {
2058
- validatedConfig: {
2059
- variables,
2060
- query,
2061
- useUiApiAdapter,
2062
- },
2063
- errors: [],
2064
- };
2065
- }
2066
- function buildCachedSnapshot(context, storeLookup) {
2067
- return buildInMemorySnapshot(context, storeLookup);
2068
- }
2069
- function buildInMemorySnapshot(context, storeLookup) {
2070
- const { config, fragment, luvio } = context;
2071
- const selector = {
2072
- recordId: GRAPHQL_ROOT_KEY,
2073
- node: fragment,
2074
- variables: {},
2075
- };
2076
- return storeLookup(selector, buildSnapshotRefresh(luvio, config, fragment));
2077
- }
2078
- function buildNetworkSnapshotCachePolicy(context, coercedAdapterRequestContext) {
2079
- const { config, fragment, luvio } = context;
2080
- const { networkPriority, requestCorrelator, eventObservers } = coercedAdapterRequestContext;
2081
- const dispatchOptions = {
2082
- resourceRequestContext: {
2083
- requestCorrelator,
2084
- },
2085
- eventObservers,
2086
- };
2087
- if (networkPriority !== 'normal') {
2088
- dispatchOptions.overrides = {
2089
- priority: networkPriority,
2090
- };
2091
- }
2092
- return buildNetworkSnapshot(luvio, config, fragment, dispatchOptions);
2093
- }
2094
- const graphQLAdapterFactory = (luvio) => {
2095
- const uiApiGraphQLAdapter = graphqlAdapterFactory(luvio);
2096
- function graphql(untrustedConfig, requestContext) {
2097
- const { validatedConfig, errors } = validateGraphQlConfig(untrustedConfig);
2098
- if (errors.length > 0 || validatedConfig === null) {
2099
- if (process.env.NODE_ENV !== 'production') {
2100
- throw new Error(errors.join(', '));
2101
- }
2102
- return null;
2103
- }
2104
- const { query, variables, useUiApiAdapter } = validatedConfig;
2105
- if (useUiApiAdapter === undefined || useUiApiAdapter === true) {
2106
- // Forward to new adapters
2107
- const resolvedQuery = astResolver(query);
2108
- if (resolvedQuery === undefined) {
2109
- if (process.env.NODE_ENV !== 'production') {
2110
- throw new Error('Could not resolve standard AST');
2111
- }
2112
- return null;
2113
- }
2114
- return uiApiGraphQLAdapter({
2115
- query: resolvedQuery,
2116
- variables,
2117
- }, requestContext);
2118
- }
2119
- else {
2120
- const fieldInjectionRequired = shouldInjectFields(query);
2121
- const validatedConfigWithInjection = fieldInjectionRequired
2122
- ? graphqlConfigWithInjectedAST(validatedConfig)
2123
- : validatedConfig;
2124
- const fragment = createFragment(luvio, validatedConfigWithInjection.query, variables);
2125
- const context = {
2126
- config: validatedConfigWithInjection,
2127
- fragment,
2128
- luvio,
2129
- };
2130
- const snapshotOrPromiseFromCachePolicy = luvio.applyCachePolicy(requestContext || {}, context, buildCachedSnapshot, buildNetworkSnapshotCachePolicy);
2131
- if (storeEval !== undefined) {
2132
- const observers = requestContext && requestContext.eventObservers
2133
- ? requestContext.eventObservers
2134
- : [];
2135
- // uses the original ast to do the eval to avoid fields not needed by users
2136
- return storeEval(validatedConfig, snapshotOrPromiseFromCachePolicy, observers);
2137
- }
2138
- return snapshotOrPromiseFromCachePolicy;
2139
- }
2140
- }
2141
- return graphql;
2142
- };
2143
- function graphqlConfigWithInjectedAST(graphqlConfig) {
2144
- const { query } = graphqlConfig;
2145
- const astCopy = parse(stringify(query));
2146
- const modifiedAST = injectFieldsGQL(astCopy);
2147
- return {
2148
- ...graphqlConfig,
2149
- query: modifiedAST,
2150
- };
2151
- }
2152
- // make sure to register the configuration whenever this module loads
1904
+ const adapterName = 'graphQL';
1905
+ const RECORD_REPRESENTATION_NAME = 'RecordRepresentation';
1906
+ const GRAPHQL_ROOT_KEY = `${namespace}::${representationName}`;
1907
+ function buildSnapshotRefresh(luvio, config, fragment) {
1908
+ return {
1909
+ config,
1910
+ resolve: () => buildNetworkSnapshot(luvio, config, fragment),
1911
+ };
1912
+ }
1913
+ function createFragment(luvio, query, variables) {
1914
+ return {
1915
+ kind: 'Fragment',
1916
+ synthetic: false,
1917
+ reader: true,
1918
+ version: GRAPHQL_INGEST_VERSION,
1919
+ read: createRead(luvio, query, variables),
1920
+ };
1921
+ }
1922
+ function onFetchResponseSuccess(luvio, config, response, fragment) {
1923
+ const { query, variables } = config;
1924
+ const { body } = response;
1925
+ if (body.errors && body.errors.length > 0) {
1926
+ return Promise.resolve(luvio.storeLookup({
1927
+ recordId: representationName,
1928
+ node: {
1929
+ kind: 'Fragment',
1930
+ synthetic: true,
1931
+ reader: true,
1932
+ read: (reader) => {
1933
+ const sink = {};
1934
+ reader.enterPath('data');
1935
+ reader.assignNonScalar(sink, 'data', body.data);
1936
+ reader.exitPath();
1937
+ reader.enterPath('errors');
1938
+ reader.assignNonScalar(sink, 'errors', deepFreeze(body.errors));
1939
+ reader.exitPath();
1940
+ return sink;
1941
+ },
1942
+ },
1943
+ variables: {},
1944
+ }));
1945
+ }
1946
+ const ingest = createIngest(query, variables);
1947
+ luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, body.data);
1948
+ const snapshot = luvio.storeLookup({
1949
+ recordId: GRAPHQL_ROOT_KEY,
1950
+ node: fragment,
1951
+ variables: {},
1952
+ }, buildSnapshotRefresh(luvio, config, fragment));
1953
+ return luvio.storeBroadcast().then(() => snapshot);
1954
+ }
1955
+ function getResponseCacheKeys(luvio, config, response, fragment) {
1956
+ // TODO [W-10147827]: make this more efficient
1957
+ // for now we will get the cache keys by actually ingesting then looking at
1958
+ // the seenRecords + recordId
1959
+ const { query, variables } = config;
1960
+ const { body } = response;
1961
+ if (body.errors && body.errors.length > 0) {
1962
+ return new StoreKeyMap();
1963
+ }
1964
+ const ingest = createIngest(query, variables);
1965
+ // ingest mutates the response so we have to make a copy
1966
+ const dataCopy = parse(stringify(body.data));
1967
+ luvio.storeIngest(GRAPHQL_ROOT_KEY, ingest, dataCopy);
1968
+ const snapshot = luvio.storeLookup({
1969
+ recordId: GRAPHQL_ROOT_KEY,
1970
+ node: fragment,
1971
+ variables: {},
1972
+ }, buildSnapshotRefresh(luvio, config, fragment));
1973
+ if (snapshot.state === 'Error') {
1974
+ return new StoreKeyMap();
1975
+ }
1976
+ const keys = [...snapshot.seenRecords.keysAsArray(), snapshot.recordId];
1977
+ const keySet = new StoreKeyMap();
1978
+ for (let i = 0, len = keys.length; i < len; i++) {
1979
+ const key = keys[i];
1980
+ const keyNamespace = key.split('::')[0];
1981
+ const representationName = key.split('::')[1].split(':')[0];
1982
+ keySet.set(key, {
1983
+ namespace: keyNamespace,
1984
+ representationName,
1985
+ mergeable: keyNamespace === namespace || representationName === RECORD_REPRESENTATION_NAME,
1986
+ });
1987
+ }
1988
+ return keySet;
1989
+ }
1990
+ function onFetchResponseError(luvio, config, response) {
1991
+ const errorSnapshot = luvio.errorSnapshot(response);
1992
+ luvio.storeIngestError(GRAPHQL_ROOT_KEY, errorSnapshot);
1993
+ return luvio.storeBroadcast().then(() => errorSnapshot);
1994
+ }
1995
+ function buildNetworkSnapshot(luvio, config, fragment, options) {
1996
+ const { variables: queryVariables, query } = config;
1997
+ const request = {
1998
+ baseUri: '/services/data/v58.0',
1999
+ basePath: '/graphql',
2000
+ method: 'post',
2001
+ priority: 'normal',
2002
+ body: {
2003
+ query: astToString(query),
2004
+ variables: queryVariables,
2005
+ },
2006
+ queryParams: {},
2007
+ urlParams: {},
2008
+ headers: {},
2009
+ };
2010
+ return luvio.dispatchResourceRequest(request, options).then((resp) => {
2011
+ return luvio.handleSuccessResponse(() => onFetchResponseSuccess(luvio, config, resp, fragment), () => getResponseCacheKeys(luvio, config, resp, fragment));
2012
+ }, (errorResponse) => {
2013
+ return luvio.handleErrorResponse(() => onFetchResponseError(luvio, config, errorResponse));
2014
+ });
2015
+ }
2016
+ function validateGraphQlConfig(untrustedConfig) {
2017
+ if (!untrustedIsObject(untrustedConfig)) {
2018
+ return {
2019
+ validatedConfig: null,
2020
+ errors: ["Invalid Config provided isn't an object"],
2021
+ };
2022
+ }
2023
+ if (!('variables' in untrustedConfig && 'query' in untrustedConfig)) {
2024
+ return {
2025
+ validatedConfig: null,
2026
+ errors: [
2027
+ 'Missing one or both of the required config parameters "query" and "variables"',
2028
+ ],
2029
+ };
2030
+ }
2031
+ const { variables, query } = untrustedConfig;
2032
+ const validationErrors = [];
2033
+ if (isLuvioDocumentNode(query) === false) {
2034
+ validationErrors.push('The config parameter "query" isn\'t a valid LuvioDocumentNode');
2035
+ }
2036
+ const ast = query;
2037
+ if (isGraphQLVariables(variables) === false) {
2038
+ validationErrors.push('The config parameter "variables" isn\'t an object');
2039
+ }
2040
+ if (validationErrors.length > 0) {
2041
+ return {
2042
+ validatedConfig: null,
2043
+ errors: validationErrors,
2044
+ };
2045
+ }
2046
+ validationErrors.push(...validate(ast, variables));
2047
+ const { useUiApiAdapter } = untrustedConfig;
2048
+ if (useUiApiAdapter !== undefined && typeof useUiApiAdapter !== 'boolean') {
2049
+ validationErrors.push('The config parameter "useUiApiAdapter" isn\'t a boolean');
2050
+ }
2051
+ if (validationErrors.length > 0) {
2052
+ return {
2053
+ validatedConfig: null,
2054
+ errors: validationErrors,
2055
+ };
2056
+ }
2057
+ return {
2058
+ validatedConfig: {
2059
+ variables,
2060
+ query,
2061
+ useUiApiAdapter,
2062
+ },
2063
+ errors: [],
2064
+ };
2065
+ }
2066
+ function buildCachedSnapshot(context, storeLookup) {
2067
+ return buildInMemorySnapshot(context, storeLookup);
2068
+ }
2069
+ function buildInMemorySnapshot(context, storeLookup) {
2070
+ const { config, fragment, luvio } = context;
2071
+ const selector = {
2072
+ recordId: GRAPHQL_ROOT_KEY,
2073
+ node: fragment,
2074
+ variables: {},
2075
+ };
2076
+ return storeLookup(selector, buildSnapshotRefresh(luvio, config, fragment));
2077
+ }
2078
+ function buildNetworkSnapshotCachePolicy(context, coercedAdapterRequestContext) {
2079
+ const { config, fragment, luvio } = context;
2080
+ const { networkPriority, requestCorrelator, eventObservers } = coercedAdapterRequestContext;
2081
+ const dispatchOptions = {
2082
+ resourceRequestContext: {
2083
+ requestCorrelator,
2084
+ },
2085
+ eventObservers,
2086
+ };
2087
+ if (networkPriority !== 'normal') {
2088
+ dispatchOptions.overrides = {
2089
+ priority: networkPriority,
2090
+ };
2091
+ }
2092
+ return buildNetworkSnapshot(luvio, config, fragment, dispatchOptions);
2093
+ }
2094
+ const graphQLAdapterFactory = (luvio) => {
2095
+ const uiApiGraphQLAdapter = graphqlAdapterFactory(luvio);
2096
+ function graphql(untrustedConfig, requestContext) {
2097
+ const { validatedConfig, errors } = validateGraphQlConfig(untrustedConfig);
2098
+ if (errors.length > 0 || validatedConfig === null) {
2099
+ if (process.env.NODE_ENV !== 'production') {
2100
+ throw new Error(errors.join(', '));
2101
+ }
2102
+ return null;
2103
+ }
2104
+ const { query, variables, useUiApiAdapter } = validatedConfig;
2105
+ if (useUiApiAdapter === undefined || useUiApiAdapter === true) {
2106
+ // Forward to new adapters
2107
+ const resolvedQuery = astResolver(query);
2108
+ if (resolvedQuery === undefined) {
2109
+ if (process.env.NODE_ENV !== 'production') {
2110
+ throw new Error('Could not resolve standard AST');
2111
+ }
2112
+ return null;
2113
+ }
2114
+ return uiApiGraphQLAdapter({
2115
+ query: resolvedQuery,
2116
+ variables,
2117
+ }, requestContext);
2118
+ }
2119
+ else {
2120
+ const fieldInjectionRequired = shouldInjectFields(query);
2121
+ const validatedConfigWithInjection = fieldInjectionRequired
2122
+ ? graphqlConfigWithInjectedAST(validatedConfig)
2123
+ : validatedConfig;
2124
+ const fragment = createFragment(luvio, validatedConfigWithInjection.query, variables);
2125
+ const context = {
2126
+ config: validatedConfigWithInjection,
2127
+ fragment,
2128
+ luvio,
2129
+ };
2130
+ const snapshotOrPromiseFromCachePolicy = luvio.applyCachePolicy(requestContext || {}, context, buildCachedSnapshot, buildNetworkSnapshotCachePolicy);
2131
+ if (storeEval !== undefined) {
2132
+ const observers = requestContext && requestContext.eventObservers
2133
+ ? requestContext.eventObservers
2134
+ : [];
2135
+ // uses the original ast to do the eval to avoid fields not needed by users
2136
+ return storeEval(validatedConfig, snapshotOrPromiseFromCachePolicy, observers);
2137
+ }
2138
+ return snapshotOrPromiseFromCachePolicy;
2139
+ }
2140
+ }
2141
+ return graphql;
2142
+ };
2143
+ function graphqlConfigWithInjectedAST(graphqlConfig) {
2144
+ const { query } = graphqlConfig;
2145
+ const astCopy = parse(stringify(query));
2146
+ const modifiedAST = injectFieldsGQL(astCopy);
2147
+ return {
2148
+ ...graphqlConfig,
2149
+ query: modifiedAST,
2150
+ };
2151
+ }
2152
+ // make sure to register the configuration whenever this module loads
2153
2153
  register({ id: '@salesforce/lds-adapters-graphql', configuration });
2154
2154
 
2155
2155
  export { adapterName, buildCachedSnapshot, keyBuilder as connectionKeyBuilder, graphQLAdapterFactory, namespace, representationName };