relay-runtime 9.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/handlers/RelayDefaultHandlerProvider.js.flow +34 -0
  2. package/handlers/connection/ConnectionHandler.js.flow +549 -0
  3. package/handlers/connection/ConnectionInterface.js.flow +92 -0
  4. package/index.js +1 -1
  5. package/index.js.flow +314 -0
  6. package/lib/handlers/connection/ConnectionHandler.js +1 -3
  7. package/lib/index.js +1 -2
  8. package/lib/mutations/RelayDeclarativeMutationConfig.js +22 -45
  9. package/lib/mutations/RelayRecordProxy.js +1 -3
  10. package/lib/mutations/RelayRecordSourceMutator.js +1 -3
  11. package/lib/mutations/RelayRecordSourceProxy.js +1 -3
  12. package/lib/mutations/RelayRecordSourceSelectorProxy.js +1 -3
  13. package/lib/mutations/commitMutation.js +2 -0
  14. package/lib/mutations/validateMutation.js +13 -4
  15. package/lib/network/RelayObservable.js +9 -9
  16. package/lib/network/RelayQueryResponseCache.js +8 -6
  17. package/lib/query/fetchQueryInternal.js +1 -8
  18. package/lib/store/DataChecker.js +23 -51
  19. package/lib/store/RelayConcreteVariables.js +6 -2
  20. package/lib/store/RelayModernEnvironment.js +30 -12
  21. package/lib/store/RelayModernFragmentSpecResolver.js +9 -13
  22. package/lib/store/RelayModernQueryExecutor.js +73 -37
  23. package/lib/store/RelayModernRecord.js +14 -9
  24. package/lib/store/RelayModernStore.js +107 -70
  25. package/lib/store/RelayOperationTracker.js +35 -78
  26. package/lib/store/RelayOptimisticRecordSource.js +7 -5
  27. package/lib/store/RelayPublishQueue.js +1 -3
  28. package/lib/store/RelayReader.js +1 -3
  29. package/lib/store/RelayRecordSource.js +1 -3
  30. package/lib/store/RelayRecordSourceMapImpl.js +13 -18
  31. package/lib/store/RelayReferenceMarker.js +2 -6
  32. package/lib/store/RelayResponseNormalizer.js +9 -10
  33. package/lib/store/StoreInspector.js +7 -5
  34. package/lib/store/normalizeRelayPayload.js +6 -2
  35. package/lib/subscription/requestSubscription.js +4 -2
  36. package/lib/util/RelayFeatureFlags.js +1 -1
  37. package/lib/util/RelayReplaySubject.js +1 -3
  38. package/lib/util/createPayloadFor3DField.js +7 -2
  39. package/mutations/RelayDeclarativeMutationConfig.js.flow +380 -0
  40. package/mutations/RelayRecordProxy.js.flow +165 -0
  41. package/mutations/RelayRecordSourceMutator.js.flow +238 -0
  42. package/mutations/RelayRecordSourceProxy.js.flow +164 -0
  43. package/mutations/RelayRecordSourceSelectorProxy.js.flow +119 -0
  44. package/mutations/applyOptimisticMutation.js.flow +76 -0
  45. package/mutations/commitLocalUpdate.js.flow +24 -0
  46. package/mutations/commitMutation.js.flow +184 -0
  47. package/mutations/validateMutation.js.flow +211 -0
  48. package/network/ConvertToExecuteFunction.js.flow +49 -0
  49. package/network/RelayNetwork.js.flow +84 -0
  50. package/network/RelayNetworkTypes.js.flow +123 -0
  51. package/network/RelayObservable.js.flow +634 -0
  52. package/network/RelayQueryResponseCache.js.flow +111 -0
  53. package/package.json +1 -1
  54. package/query/GraphQLTag.js.flow +166 -0
  55. package/query/fetchQuery.js.flow +47 -0
  56. package/query/fetchQueryInternal.js.flow +349 -0
  57. package/relay-runtime.js +2 -2
  58. package/relay-runtime.min.js +2 -2
  59. package/store/ClientID.js.flow +43 -0
  60. package/store/DataChecker.js.flow +426 -0
  61. package/store/RelayConcreteVariables.js.flow +96 -0
  62. package/store/RelayModernEnvironment.js.flow +526 -0
  63. package/store/RelayModernFragmentSpecResolver.js.flow +426 -0
  64. package/store/RelayModernOperationDescriptor.js.flow +88 -0
  65. package/store/RelayModernQueryExecutor.js.flow +1327 -0
  66. package/store/RelayModernRecord.js.flow +403 -0
  67. package/store/RelayModernSelector.js.flow +444 -0
  68. package/store/RelayModernStore.js.flow +757 -0
  69. package/store/RelayOperationTracker.js.flow +164 -0
  70. package/store/RelayOptimisticRecordSource.js.flow +119 -0
  71. package/store/RelayPublishQueue.js.flow +401 -0
  72. package/store/RelayReader.js.flow +376 -0
  73. package/store/RelayRecordSource.js.flow +29 -0
  74. package/store/RelayRecordSourceMapImpl.js.flow +87 -0
  75. package/store/RelayRecordState.js.flow +37 -0
  76. package/store/RelayReferenceMarker.js.flow +236 -0
  77. package/store/RelayResponseNormalizer.js.flow +556 -0
  78. package/store/RelayStoreTypes.js.flow +873 -0
  79. package/store/RelayStoreUtils.js.flow +218 -0
  80. package/store/StoreInspector.js.flow +173 -0
  81. package/store/ViewerPattern.js.flow +26 -0
  82. package/store/cloneRelayHandleSourceField.js.flow +66 -0
  83. package/store/createFragmentSpecResolver.js.flow +55 -0
  84. package/store/createRelayContext.js.flow +44 -0
  85. package/store/defaultGetDataID.js.flow +27 -0
  86. package/store/hasOverlappingIDs.js.flow +34 -0
  87. package/store/isRelayModernEnvironment.js.flow +27 -0
  88. package/store/normalizeRelayPayload.js.flow +51 -0
  89. package/store/readInlineData.js.flow +75 -0
  90. package/subscription/requestSubscription.js.flow +100 -0
  91. package/util/JSResourceTypes.flow.js.flow +20 -0
  92. package/util/NormalizationNode.js.flow +191 -0
  93. package/util/ReaderNode.js.flow +208 -0
  94. package/util/RelayConcreteNode.js.flow +80 -0
  95. package/util/RelayDefaultHandleKey.js.flow +17 -0
  96. package/util/RelayError.js.flow +33 -0
  97. package/util/RelayFeatureFlags.js.flow +30 -0
  98. package/util/RelayProfiler.js.flow +284 -0
  99. package/util/RelayReplaySubject.js.flow +134 -0
  100. package/util/RelayRuntimeTypes.js.flow +70 -0
  101. package/util/createPayloadFor3DField.js.flow +43 -0
  102. package/util/deepFreeze.js.flow +36 -0
  103. package/util/generateID.js.flow +21 -0
  104. package/util/getFragmentIdentifier.js.flow +52 -0
  105. package/util/getRelayHandleKey.js.flow +41 -0
  106. package/util/getRequestIdentifier.js.flow +41 -0
  107. package/util/isPromise.js.flow +21 -0
  108. package/util/isScalarAndEqual.js.flow +26 -0
  109. package/util/recycleNodesInto.js.flow +80 -0
  110. package/util/resolveImmediate.js.flow +30 -0
  111. package/util/stableCopy.js.flow +35 -0
@@ -0,0 +1,873 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ // flowlint ambiguous-object-type:error
12
+
13
+ 'use strict';
14
+
15
+ import type {
16
+ GraphQLResponse,
17
+ INetwork,
18
+ PayloadData,
19
+ PayloadError,
20
+ UploadableMap,
21
+ } from '../network/RelayNetworkTypes';
22
+ import type RelayObservable from '../network/RelayObservable';
23
+ import type {
24
+ NormalizationLinkedField,
25
+ NormalizationScalarField,
26
+ NormalizationSelectableNode,
27
+ NormalizationSplitOperation,
28
+ } from '../util/NormalizationNode';
29
+ import type {ReaderFragment} from '../util/ReaderNode';
30
+ import type {
31
+ ConcreteRequest,
32
+ RequestParameters,
33
+ } from '../util/RelayConcreteNode';
34
+ import type {
35
+ CacheConfig,
36
+ DataID,
37
+ Disposable,
38
+ RenderPolicy,
39
+ Variables,
40
+ } from '../util/RelayRuntimeTypes';
41
+ import type {RequestIdentifier} from '../util/getRequestIdentifier';
42
+ import type {InvalidationState} from './RelayModernStore';
43
+ import type RelayOperationTracker from './RelayOperationTracker';
44
+ import type {RecordState} from './RelayRecordState';
45
+
46
+ export opaque type FragmentReference = empty;
47
+ export type OperationTracker = RelayOperationTracker;
48
+
49
+ /*
50
+ * An individual cached graph object.
51
+ */
52
+ export type Record = {[key: string]: mixed, ...};
53
+
54
+ /**
55
+ * A collection of records keyed by id.
56
+ */
57
+ export type RecordMap = {[dataID: DataID]: ?Record, ...};
58
+
59
+ export type FragmentMap = {[key: string]: ReaderFragment, ...};
60
+
61
+ /**
62
+ * The results of a selector given a store/RecordSource.
63
+ */
64
+ export type SelectorData = {[key: string]: mixed, ...};
65
+
66
+ export type SingularReaderSelector = {|
67
+ +kind: 'SingularReaderSelector',
68
+ +dataID: DataID,
69
+ +node: ReaderFragment,
70
+ +owner: RequestDescriptor,
71
+ +variables: Variables,
72
+ |};
73
+
74
+ export type ReaderSelector = SingularReaderSelector | PluralReaderSelector;
75
+
76
+ export type PluralReaderSelector = {|
77
+ +kind: 'PluralReaderSelector',
78
+ +selectors: $ReadOnlyArray<SingularReaderSelector>,
79
+ |};
80
+
81
+ export type RequestDescriptor = {|
82
+ +identifier: RequestIdentifier,
83
+ +node: ConcreteRequest,
84
+ +variables: Variables,
85
+ |};
86
+
87
+ /**
88
+ * A selector defines the starting point for a traversal into the graph for the
89
+ * purposes of targeting a subgraph.
90
+ */
91
+ export type NormalizationSelector = {|
92
+ +dataID: DataID,
93
+ +node: NormalizationSelectableNode,
94
+ +variables: Variables,
95
+ |};
96
+
97
+ /**
98
+ * A representation of a selector and its results at a particular point in time.
99
+ */
100
+ export type TypedSnapshot<TData> = {|
101
+ +data: TData,
102
+ +isMissingData: boolean,
103
+ +seenRecords: RecordMap,
104
+ +selector: SingularReaderSelector,
105
+ |};
106
+ export type Snapshot = TypedSnapshot<?SelectorData>;
107
+
108
+ /**
109
+ * An operation selector describes a specific instance of a GraphQL operation
110
+ * with variables applied.
111
+ *
112
+ * - `root`: a selector intended for processing server results or retaining
113
+ * response data in the store.
114
+ * - `fragment`: a selector intended for use in reading or subscribing to
115
+ * the results of the the operation.
116
+ */
117
+ export type OperationDescriptor = {|
118
+ +fragment: SingularReaderSelector,
119
+ +request: RequestDescriptor,
120
+ +root: NormalizationSelector,
121
+ |};
122
+
123
+ /**
124
+ * Arbitrary data e.g. received by a container as props.
125
+ */
126
+ export type Props = {[key: string]: mixed, ...};
127
+
128
+ /**
129
+ * The type of the `relay` property set on React context by the React/Relay
130
+ * integration layer (e.g. QueryRenderer, FragmentContainer, etc).
131
+ */
132
+ export type RelayContext = {|
133
+ environment: IEnvironment,
134
+ |};
135
+
136
+ /**
137
+ * The results of reading the results of a FragmentMap given some input
138
+ * `Props`.
139
+ */
140
+ export type FragmentSpecResults = {[key: string]: mixed, ...};
141
+
142
+ /**
143
+ * A utility for resolving and subscribing to the results of a fragment spec
144
+ * (key -> fragment mapping) given some "props" that determine the root ID
145
+ * and variables to use when reading each fragment. When props are changed via
146
+ * `setProps()`, the resolver will update its results and subscriptions
147
+ * accordingly. Internally, the resolver:
148
+ * - Converts the fragment map & props map into a map of `Selector`s.
149
+ * - Removes any resolvers for any props that became null.
150
+ * - Creates resolvers for any props that became non-null.
151
+ * - Updates resolvers with the latest props.
152
+ */
153
+ export interface FragmentSpecResolver {
154
+ /**
155
+ * Stop watching for changes to the results of the fragments.
156
+ */
157
+ dispose(): void;
158
+
159
+ /**
160
+ * Get the current results.
161
+ */
162
+ resolve(): FragmentSpecResults;
163
+
164
+ /**
165
+ * Update the resolver with new inputs. Call `resolve()` to get the updated
166
+ * results.
167
+ */
168
+ setProps(props: Props): void;
169
+
170
+ /**
171
+ * Override the variables used to read the results of the fragments. Call
172
+ * `resolve()` to get the updated results.
173
+ */
174
+ setVariables(variables: Variables, node: ConcreteRequest): void;
175
+
176
+ /**
177
+ * Subscribe to resolver updates.
178
+ * Overrides existing callback (if one has been specified).
179
+ */
180
+ setCallback(callback: () => void): void;
181
+ }
182
+
183
+ /**
184
+ * A read-only interface for accessing cached graph data.
185
+ */
186
+ export interface RecordSource {
187
+ get(dataID: DataID): ?Record;
188
+ getRecordIDs(): Array<DataID>;
189
+ getStatus(dataID: DataID): RecordState;
190
+ has(dataID: DataID): boolean;
191
+ size(): number;
192
+ toJSON(): {[DataID]: ?Record, ...};
193
+ }
194
+
195
+ /**
196
+ * A read/write interface for accessing and updating graph data.
197
+ */
198
+ export interface MutableRecordSource extends RecordSource {
199
+ clear(): void;
200
+ delete(dataID: DataID): void;
201
+ remove(dataID: DataID): void;
202
+ set(dataID: DataID, record: Record): void;
203
+ }
204
+
205
+ export type CheckOptions = {|
206
+ target: MutableRecordSource,
207
+ handlers: $ReadOnlyArray<MissingFieldHandler>,
208
+ |};
209
+
210
+ export type OperationAvailability =
211
+ | {|status: 'available', fetchTime: ?number|}
212
+ | {|status: 'stale'|}
213
+ | {|status: 'missing'|};
214
+
215
+ export type {InvalidationState} from './RelayModernStore';
216
+
217
+ /**
218
+ * An interface for keeping multiple views of data consistent across an
219
+ * application.
220
+ */
221
+ export interface Store {
222
+ /**
223
+ * Get a read-only view of the store's internal RecordSource.
224
+ */
225
+ getSource(): RecordSource;
226
+
227
+ /**
228
+ * Determine if the operation can be resolved with data in the store (i.e. no
229
+ * fields are missing).
230
+ */
231
+ check(
232
+ operation: OperationDescriptor,
233
+ options?: CheckOptions,
234
+ ): OperationAvailability;
235
+
236
+ /**
237
+ * Read the results of a selector from in-memory records in the store.
238
+ * Optionally takes an owner, corresponding to the operation that
239
+ * owns this selector (fragment).
240
+ */
241
+ lookup(selector: SingularReaderSelector): Snapshot;
242
+
243
+ /**
244
+ * Notify subscribers (see `subscribe`) of any data that was published
245
+ * (`publish()`) since the last time `notify` was called.
246
+ * Optionally provide an OperationDescriptor indicating the source operation
247
+ * that was being processed to produce this run.
248
+ *
249
+ * This method should return an array of the affected fragment owners
250
+ */
251
+ notify(
252
+ sourceOperation?: OperationDescriptor,
253
+ invalidateStore?: boolean,
254
+ ): $ReadOnlyArray<RequestDescriptor>;
255
+
256
+ /**
257
+ * Publish new information (e.g. from the network) to the store, updating its
258
+ * internal record source. Subscribers are not immediately notified - this
259
+ * occurs when `notify()` is called.
260
+ */
261
+ publish(source: RecordSource, idsMarkedForInvalidation?: Set<DataID>): void;
262
+
263
+ /**
264
+ * Ensure that all the records necessary to fulfill the given selector are
265
+ * retained in-memory. The records will not be eligible for garbage collection
266
+ * until the returned reference is disposed.
267
+ */
268
+ retain(operation: OperationDescriptor): Disposable;
269
+
270
+ /**
271
+ * Subscribe to changes to the results of a selector. The callback is called
272
+ * when `notify()` is called *and* records have been published that affect the
273
+ * selector results relative to the last `notify()`.
274
+ */
275
+ subscribe(
276
+ snapshot: Snapshot,
277
+ callback: (snapshot: Snapshot) => void,
278
+ ): Disposable;
279
+
280
+ /**
281
+ * The method should disable garbage collection until
282
+ * the returned reference is disposed.
283
+ */
284
+ holdGC(): Disposable;
285
+
286
+ /**
287
+ * Record a backup/snapshot of the current state of the store, including
288
+ * records and derived data such as fragment subscriptions.
289
+ * This state can be restored with restore().
290
+ */
291
+ snapshot(): void;
292
+
293
+ /**
294
+ * Reset the state of the store to the point that snapshot() was last called.
295
+ */
296
+ restore(): void;
297
+
298
+ /**
299
+ * Will return an opaque snapshot of the current invalidation state of
300
+ * the data ids that were provided.
301
+ */
302
+ lookupInvalidationState(dataIDs: $ReadOnlyArray<DataID>): InvalidationState;
303
+
304
+ /**
305
+ * Given the previous invalidation state for those
306
+ * ids, this function will return:
307
+ * - false, if the invalidation state for those ids is the same, meaning
308
+ * **it has not changed**
309
+ * - true, if the invalidation state for the given ids has changed
310
+ */
311
+ checkInvalidationState(previousInvalidationState: InvalidationState): boolean;
312
+
313
+ /**
314
+ * Will subscribe the provided callback to the invalidation state of the
315
+ * given data ids. Whenever the invalidation state for any of the provided
316
+ * ids changes, the callback will be called, and provide the latest
317
+ * invalidation state.
318
+ * Disposing of the returned disposable will remove the subscription.
319
+ */
320
+ subscribeToInvalidationState(
321
+ invalidationState: InvalidationState,
322
+ callback: () => void,
323
+ ): Disposable;
324
+ }
325
+
326
+ /**
327
+ * A type that accepts a callback and schedules it to run at some future time.
328
+ * By convention, implementations should not execute the callback immediately.
329
+ */
330
+ export type Scheduler = (() => void) => void;
331
+
332
+ /**
333
+ * An interface for imperatively getting/setting properties of a `Record`. This interface
334
+ * is designed to allow the appearance of direct Record manipulation while
335
+ * allowing different implementations that may e.g. create a changeset of
336
+ * the modifications.
337
+ */
338
+ export interface RecordProxy {
339
+ copyFieldsFrom(source: RecordProxy): void;
340
+ getDataID(): DataID;
341
+ getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
342
+ getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
343
+ getOrCreateLinkedRecord(
344
+ name: string,
345
+ typeName: string,
346
+ args?: ?Variables,
347
+ ): RecordProxy;
348
+ getType(): string;
349
+ getValue(name: string, args?: ?Variables): mixed;
350
+ setLinkedRecord(
351
+ record: RecordProxy,
352
+ name: string,
353
+ args?: ?Variables,
354
+ ): RecordProxy;
355
+ setLinkedRecords(
356
+ records: Array<?RecordProxy>,
357
+ name: string,
358
+ args?: ?Variables,
359
+ ): RecordProxy;
360
+ setValue(value: mixed, name: string, args?: ?Variables): RecordProxy;
361
+ invalidateRecord(): void;
362
+ }
363
+
364
+ export interface ReadOnlyRecordProxy {
365
+ getDataID(): DataID;
366
+ getLinkedRecord(name: string, args?: ?Variables): ?RecordProxy;
367
+ getLinkedRecords(name: string, args?: ?Variables): ?Array<?RecordProxy>;
368
+ getType(): string;
369
+ getValue(name: string, args?: ?Variables): mixed;
370
+ }
371
+
372
+ /**
373
+ * An interface for imperatively getting/setting properties of a `RecordSource`. This interface
374
+ * is designed to allow the appearance of direct RecordSource manipulation while
375
+ * allowing different implementations that may e.g. create a changeset of
376
+ * the modifications.
377
+ */
378
+ export interface RecordSourceProxy {
379
+ create(dataID: DataID, typeName: string): RecordProxy;
380
+ delete(dataID: DataID): void;
381
+ get(dataID: DataID): ?RecordProxy;
382
+ getRoot(): RecordProxy;
383
+ invalidateStore(): void;
384
+ }
385
+
386
+ export interface ReadOnlyRecordSourceProxy {
387
+ get(dataID: DataID): ?ReadOnlyRecordProxy;
388
+ getRoot(): ReadOnlyRecordProxy;
389
+ }
390
+
391
+ /**
392
+ * Extends the RecordSourceProxy interface with methods for accessing the root
393
+ * fields of a Selector.
394
+ */
395
+ export interface RecordSourceSelectorProxy extends RecordSourceProxy {
396
+ getRootField(fieldName: string): ?RecordProxy;
397
+ getPluralRootField(fieldName: string): ?Array<?RecordProxy>;
398
+ invalidateStore(): void;
399
+ }
400
+
401
+ export type LogEvent =
402
+ | {|
403
+ +name: 'queryresource.fetch',
404
+ // ID of this query resource request and will be the same
405
+ // if there is an associated queryresource.retain event.
406
+ +resourceID: number,
407
+ +operation: OperationDescriptor,
408
+ // value from ProfilerContext
409
+ +profilerContext: mixed,
410
+ // FetchPolicy from relay-experimental
411
+ +fetchPolicy: string,
412
+ // RenderPolicy from relay-experimental
413
+ +renderPolicy: string,
414
+ +queryAvailability: OperationAvailability,
415
+ +shouldFetch: boolean,
416
+ |}
417
+ | {|
418
+ +name: 'queryresource.retain',
419
+ +resourceID: number,
420
+ // value from ProfilerContext
421
+ +profilerContext: mixed,
422
+ |}
423
+ | {|
424
+ +name: 'execute.info',
425
+ +transactionID: number,
426
+ +info: mixed,
427
+ |}
428
+ | {|
429
+ +name: 'execute.start',
430
+ +transactionID: number,
431
+ +params: RequestParameters,
432
+ +variables: Variables,
433
+ |}
434
+ | {|
435
+ +name: 'execute.next',
436
+ +transactionID: number,
437
+ +response: GraphQLResponse,
438
+ |}
439
+ | {|
440
+ +name: 'execute.error',
441
+ +transactionID: number,
442
+ +error: Error,
443
+ |}
444
+ | {|
445
+ +name: 'execute.complete',
446
+ +transactionID: number,
447
+ |}
448
+ | {|
449
+ +name: 'execute.unsubscribe',
450
+ +transactionID: number,
451
+ |};
452
+ export type LogFunction = LogEvent => void;
453
+ export type LogRequestInfoFunction = mixed => void;
454
+
455
+ /**
456
+ * The public API of Relay core. Represents an encapsulated environment with its
457
+ * own in-memory cache.
458
+ */
459
+ export interface IEnvironment {
460
+ /**
461
+ * Extra information attached to the environment instance
462
+ */
463
+ +options: mixed;
464
+
465
+ /**
466
+ * **UNSTABLE** Event based logging API thats scoped to the environment.
467
+ */
468
+ __log: LogFunction;
469
+
470
+ /**
471
+ * Determine if the operation can be resolved with data in the store (i.e. no
472
+ * fields are missing).
473
+ *
474
+ * Note that this operation effectively "executes" the selector against the
475
+ * cache and therefore takes time proportional to the size/complexity of the
476
+ * selector.
477
+ */
478
+ check(operation: OperationDescriptor): OperationAvailability;
479
+
480
+ /**
481
+ * Subscribe to changes to the results of a selector. The callback is called
482
+ * when data has been committed to the store that would cause the results of
483
+ * the snapshot's selector to change.
484
+ */
485
+ subscribe(
486
+ snapshot: Snapshot,
487
+ callback: (snapshot: Snapshot) => void,
488
+ ): Disposable;
489
+
490
+ /**
491
+ * Ensure that all the records necessary to fulfill the given selector are
492
+ * retained in-memory. The records will not be eligible for garbage collection
493
+ * until the returned reference is disposed.
494
+ */
495
+ retain(operation: OperationDescriptor): Disposable;
496
+
497
+ /**
498
+ * Apply an optimistic update to the environment. The mutation can be reverted
499
+ * by calling `dispose()` on the returned value.
500
+ */
501
+ applyUpdate(optimisticUpdate: OptimisticUpdateFunction): Disposable;
502
+
503
+ /**
504
+ * Apply an optimistic mutation response and/or updater. The mutation can be
505
+ * reverted by calling `dispose()` on the returned value.
506
+ */
507
+ applyMutation(optimisticConfig: OptimisticResponseConfig): Disposable;
508
+
509
+ /**
510
+ * Commit an updater to the environment. This mutation cannot be reverted and
511
+ * should therefore not be used for optimistic updates. This is mainly
512
+ * intended for updating fields from client schema extensions.
513
+ */
514
+ commitUpdate(updater: StoreUpdater): void;
515
+
516
+ /**
517
+ * Commit a payload to the environment using the given operation selector.
518
+ */
519
+ commitPayload(
520
+ operationDescriptor: OperationDescriptor,
521
+ payload: PayloadData,
522
+ ): void;
523
+
524
+ /**
525
+ * Get the environment's internal Network.
526
+ */
527
+ getNetwork(): INetwork;
528
+
529
+ /**
530
+ * Get the environment's internal Store.
531
+ */
532
+ getStore(): Store;
533
+
534
+ /**
535
+ * Returns the environment specific OperationTracker.
536
+ */
537
+ getOperationTracker(): RelayOperationTracker;
538
+
539
+ /**
540
+ * EXPERIMENTAL
541
+ * Returns the default render policy to use when rendering a query
542
+ * that uses Relay Hooks
543
+ */
544
+ UNSTABLE_getDefaultRenderPolicy(): RenderPolicy;
545
+
546
+ /**
547
+ * Read the results of a selector from in-memory records in the store.
548
+ * Optionally takes an owner, corresponding to the operation that
549
+ * owns this selector (fragment).
550
+ */
551
+ lookup(selector: SingularReaderSelector): Snapshot;
552
+
553
+ /**
554
+ * Send a query to the server with Observer semantics: one or more
555
+ * responses may be returned (via `next`) over time followed by either
556
+ * the request completing (`completed`) or an error (`error`).
557
+ *
558
+ * Networks/servers that support subscriptions may choose to hold the
559
+ * subscription open indefinitely such that `complete` is not called.
560
+ *
561
+ * Note: Observables are lazy, so calling this method will do nothing until
562
+ * the result is subscribed to: environment.execute({...}).subscribe({...}).
563
+ */
564
+ execute(config: {|
565
+ operation: OperationDescriptor,
566
+ cacheConfig?: ?CacheConfig,
567
+ updater?: ?SelectorStoreUpdater,
568
+ |}): RelayObservable<GraphQLResponse>;
569
+
570
+ /**
571
+ * Returns an Observable of GraphQLResponse resulting from executing the
572
+ * provided Mutation operation, the result of which is then normalized and
573
+ * committed to the publish queue along with an optional optimistic response
574
+ * or updater.
575
+ *
576
+ * Note: Observables are lazy, so calling this method will do nothing until
577
+ * the result is subscribed to:
578
+ * environment.executeMutation({...}).subscribe({...}).
579
+ */
580
+ executeMutation({|
581
+ cacheConfig?: ?CacheConfig,
582
+ operation: OperationDescriptor,
583
+ optimisticUpdater?: ?SelectorStoreUpdater,
584
+ optimisticResponse?: ?Object,
585
+ updater?: ?SelectorStoreUpdater,
586
+ uploadables?: ?UploadableMap,
587
+ |}): RelayObservable<GraphQLResponse>;
588
+
589
+ /**
590
+ * Returns an Observable of GraphQLResponse resulting from executing the
591
+ * provided Query or Subscription operation responses, the result of which is
592
+ * then normalized and comitted to the publish queue.
593
+ *
594
+ * Note: Observables are lazy, so calling this method will do nothing until
595
+ * the result is subscribed to:
596
+ * environment.executeWithSource({...}).subscribe({...}).
597
+ */
598
+ executeWithSource({|
599
+ operation: OperationDescriptor,
600
+ source: RelayObservable<GraphQLResponse>,
601
+ |}): RelayObservable<GraphQLResponse>;
602
+
603
+ /**
604
+ * Returns true if a request is currently "active", meaning it's currently
605
+ * actively receiving payloads or downloading modules, and has not received
606
+ * a final payload yet. Note that a request might still be pending (or "in flight")
607
+ * without actively receiving payload, for example a live query or an
608
+ * active GraphQL subscription
609
+ */
610
+ isRequestActive(requestIdentifier: string): boolean;
611
+
612
+ /**
613
+ * Returns true if the environment is for use during server side rendering.
614
+ * functions like getQueryResource key off of this in order to determine
615
+ * whether we need to set up certain caches and timeout's.
616
+ */
617
+ isServer(): boolean;
618
+ }
619
+
620
+ /**
621
+ * The results of reading data for a fragment. This is similar to a `Selector`,
622
+ * but references the (fragment) node by name rather than by value.
623
+ */
624
+ export type FragmentPointer = {
625
+ __id: DataID,
626
+ __fragments: {[fragmentName: string]: Variables, ...},
627
+ __fragmentOwner: RequestDescriptor,
628
+ ...
629
+ };
630
+
631
+ /**
632
+ * The partial shape of an object with a '...Fragment @module(name: "...")'
633
+ * selection
634
+ */
635
+ export type ModuleImportPointer = {
636
+ +__fragmentPropName: ?string,
637
+ +__module_component: mixed,
638
+ +$fragmentRefs: mixed,
639
+ ...
640
+ };
641
+
642
+ /**
643
+ * A map of records affected by an update operation.
644
+ */
645
+ export type UpdatedRecords = {[dataID: DataID]: boolean, ...};
646
+
647
+ /**
648
+ * A function that updates a store (via a proxy) given the results of a "handle"
649
+ * field payload.
650
+ */
651
+ export type Handler = {
652
+ update: (store: RecordSourceProxy, fieldPayload: HandleFieldPayload) => void,
653
+ ...
654
+ };
655
+
656
+ /**
657
+ * A payload that is used to initialize or update a "handle" field with
658
+ * information from the server.
659
+ */
660
+ export type HandleFieldPayload = {|
661
+ // The arguments that were fetched.
662
+ +args: Variables,
663
+ // The __id of the record containing the source/handle field.
664
+ +dataID: DataID,
665
+ // The (storage) key at which the original server data was written.
666
+ +fieldKey: string,
667
+ // The name of the handle.
668
+ +handle: string,
669
+ // The (storage) key at which the handle's data should be written by the
670
+ // handler.
671
+ +handleKey: string,
672
+ |};
673
+
674
+ /**
675
+ * A payload that represents data necessary to process the results of an object
676
+ * with a `@module` fragment spread:
677
+ * - data: The GraphQL response value for the @match field.
678
+ * - dataID: The ID of the store object linked to by the @match field.
679
+ * - operationReference: A reference to a generated module containing the
680
+ * SplitOperation with which to normalize the field's `data`.
681
+ * - variables: Query variables.
682
+ * - typeName: the type that matched.
683
+ *
684
+ * The dataID, variables, and fragmentName can be used to create a Selector
685
+ * which can in turn be used to normalize and publish the data. The dataID and
686
+ * typeName can also be used to construct a root record for normalization.
687
+ */
688
+ export type ModuleImportPayload = {|
689
+ +data: PayloadData,
690
+ +dataID: DataID,
691
+ +operationReference: mixed,
692
+ +path: $ReadOnlyArray<string>,
693
+ +typeName: string,
694
+ +variables: Variables,
695
+ |};
696
+
697
+ /**
698
+ * Data emitted after processing a Defer or Stream node during normalization
699
+ * that describes how to process the corresponding response chunk when it
700
+ * arrives.
701
+ */
702
+ export type DeferPlaceholder = {|
703
+ +kind: 'defer',
704
+ +data: PayloadData,
705
+ +label: string,
706
+ +path: $ReadOnlyArray<string>,
707
+ +selector: NormalizationSelector,
708
+ +typeName: string,
709
+ |};
710
+ export type StreamPlaceholder = {|
711
+ +kind: 'stream',
712
+ +label: string,
713
+ +path: $ReadOnlyArray<string>,
714
+ +parentID: DataID,
715
+ +node: NormalizationSelectableNode,
716
+ +variables: Variables,
717
+ |};
718
+ export type IncrementalDataPlaceholder = DeferPlaceholder | StreamPlaceholder;
719
+
720
+ /**
721
+ * A user-supplied object to load a generated operation (SplitOperation) AST
722
+ * by a module reference. The exact format of a module reference is left to
723
+ * the application, but it must be a plain JavaScript value (string, number,
724
+ * or object/array of same).
725
+ */
726
+ export type OperationLoader = {|
727
+ /**
728
+ * Synchronously load an operation, returning either the node or null if it
729
+ * cannot be resolved synchronously.
730
+ */
731
+ get(reference: mixed): ?NormalizationSplitOperation,
732
+
733
+ /**
734
+ * Asynchronously load an operation.
735
+ */
736
+ load(reference: mixed): Promise<?NormalizationSplitOperation>,
737
+ |};
738
+
739
+ /**
740
+ * A function that receives a proxy over the store and may trigger side-effects
741
+ * (indirectly) by calling `set*` methods on the store or its record proxies.
742
+ */
743
+ export type StoreUpdater = (store: RecordSourceProxy) => void;
744
+
745
+ /**
746
+ * Similar to StoreUpdater, but accepts a proxy tied to a specific selector in
747
+ * order to easily access the root fields of a query/mutation as well as a
748
+ * second argument of the response object of the mutation.
749
+ */
750
+ export type SelectorStoreUpdater = (
751
+ store: RecordSourceSelectorProxy,
752
+ // Actually SelectorData, but mixed is inconvenient to access deeply in
753
+ // product code.
754
+ data: $FlowFixMe,
755
+ ) => void;
756
+
757
+ /**
758
+ * A set of configs that can be used to apply an optimistic update into the
759
+ * store.
760
+ */
761
+ export type OptimisticUpdate =
762
+ | OptimisticUpdateFunction
763
+ | OptimisticUpdateRelayPayload;
764
+
765
+ export type OptimisticUpdateFunction = {|
766
+ +storeUpdater: StoreUpdater,
767
+ |};
768
+
769
+ export type OptimisticUpdateRelayPayload = {|
770
+ +operation: OperationDescriptor,
771
+ +payload: RelayResponsePayload,
772
+ +updater: ?SelectorStoreUpdater,
773
+ |};
774
+
775
+ export type OptimisticResponseConfig = {|
776
+ +operation: OperationDescriptor,
777
+ +response: ?PayloadData,
778
+ +updater: ?SelectorStoreUpdater,
779
+ |};
780
+
781
+ /**
782
+ * A set of handlers that can be used to provide substitute data for missing
783
+ * fields when reading a selector from a source.
784
+ */
785
+ export type MissingFieldHandler =
786
+ | {|
787
+ kind: 'scalar',
788
+ handle: (
789
+ field: NormalizationScalarField,
790
+ record: ?Record,
791
+ args: Variables,
792
+ store: ReadOnlyRecordSourceProxy,
793
+ ) => mixed,
794
+ |}
795
+ | {|
796
+ kind: 'linked',
797
+ handle: (
798
+ field: NormalizationLinkedField,
799
+ record: ?Record,
800
+ args: Variables,
801
+ store: ReadOnlyRecordSourceProxy,
802
+ ) => ?DataID,
803
+ |}
804
+ | {|
805
+ kind: 'pluralLinked',
806
+ handle: (
807
+ field: NormalizationLinkedField,
808
+ record: ?Record,
809
+ args: Variables,
810
+ store: ReadOnlyRecordSourceProxy,
811
+ ) => ?Array<?DataID>,
812
+ |};
813
+
814
+ /**
815
+ * The results of normalizing a query.
816
+ */
817
+ export type RelayResponsePayload = {|
818
+ +errors: ?Array<PayloadError>,
819
+ +fieldPayloads: ?Array<HandleFieldPayload>,
820
+ +incrementalPlaceholders: ?Array<IncrementalDataPlaceholder>,
821
+ +moduleImportPayloads: ?Array<ModuleImportPayload>,
822
+ +source: MutableRecordSource,
823
+ +isFinal: boolean,
824
+ |};
825
+
826
+ /**
827
+ * Public interface for Publish Queue
828
+ */
829
+ export interface PublishQueue {
830
+ /**
831
+ * Schedule applying an optimistic updates on the next `run()`.
832
+ */
833
+ applyUpdate(updater: OptimisticUpdate): void;
834
+
835
+ /**
836
+ * Schedule reverting an optimistic updates on the next `run()`.
837
+ */
838
+ revertUpdate(updater: OptimisticUpdate): void;
839
+
840
+ /**
841
+ * Schedule a revert of all optimistic updates on the next `run()`.
842
+ */
843
+ revertAll(): void;
844
+
845
+ /**
846
+ * Schedule applying a payload to the store on the next `run()`.
847
+ */
848
+ commitPayload(
849
+ operation: OperationDescriptor,
850
+ payload: RelayResponsePayload,
851
+ updater?: ?SelectorStoreUpdater,
852
+ ): void;
853
+
854
+ /**
855
+ * Schedule an updater to mutate the store on the next `run()` typically to
856
+ * update client schema fields.
857
+ */
858
+ commitUpdate(updater: StoreUpdater): void;
859
+
860
+ /**
861
+ * Schedule a publish to the store from the provided source on the next
862
+ * `run()`. As an example, to update the store with substituted fields that
863
+ * are missing in the store.
864
+ */
865
+ commitSource(source: RecordSource): void;
866
+
867
+ /**
868
+ * Execute all queued up operations from the other public methods.
869
+ * Optionally provide an OperationDescriptor indicating the source operation
870
+ * that was being processed to produce this run.
871
+ */
872
+ run(sourceOperation?: OperationDescriptor): $ReadOnlyArray<RequestDescriptor>;
873
+ }