@salesforce/lds-drafts 0.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1718 @@
1
+ /**
2
+ * Copyright (c) 2022, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ import { HttpStatusCode, StoreKeyMap } from '@luvio/engine';
8
+ import { AsyncWorkerPool } from '@salesforce/lds-utils-adapters';
9
+
10
+ var DraftActionStatus;
11
+ (function (DraftActionStatus) {
12
+ DraftActionStatus["Pending"] = "pending";
13
+ DraftActionStatus["Uploading"] = "uploading";
14
+ DraftActionStatus["Error"] = "error";
15
+ DraftActionStatus["Completed"] = "completed";
16
+ })(DraftActionStatus || (DraftActionStatus = {}));
17
+ function isDraftError(draft) {
18
+ return draft.status === DraftActionStatus.Error;
19
+ }
20
+ function isDraftQueueStateChangeEvent(event) {
21
+ return event.type === DraftQueueEventType.QueueStateChanged;
22
+ }
23
+ var ProcessActionResult;
24
+ (function (ProcessActionResult) {
25
+ // non-2xx network error, requires user intervention
26
+ ProcessActionResult["ACTION_ERRORED"] = "ERROR";
27
+ // upload succeeded
28
+ ProcessActionResult["ACTION_SUCCEEDED"] = "SUCCESS";
29
+ // queue is empty
30
+ ProcessActionResult["NO_ACTION_TO_PROCESS"] = "NO_ACTION_TO_PROCESS";
31
+ // network request is in flight
32
+ ProcessActionResult["ACTION_ALREADY_PROCESSING"] = "ACTION_ALREADY_PROCESSING";
33
+ // network call failed (offline)
34
+ ProcessActionResult["NETWORK_ERROR"] = "NETWORK_ERROR";
35
+ // queue is blocked on an error that requires user intervention
36
+ ProcessActionResult["BLOCKED_ON_ERROR"] = "BLOCKED_ON_ERROR";
37
+ //waiting for user to execute custom action
38
+ ProcessActionResult["CUSTOM_ACTION_WAITING"] = "CUSTOM_ACTION_WAITING";
39
+ })(ProcessActionResult || (ProcessActionResult = {}));
40
+ var DraftQueueState;
41
+ (function (DraftQueueState) {
42
+ /** Currently processing an item in the queue or queue is empty and waiting to process the next item. */
43
+ DraftQueueState["Started"] = "started";
44
+ /**
45
+ * The queue is stopped and will not attempt to upload any drafts until startDraftQueue() is called.
46
+ * This is the initial state when the DraftQueue gets instantiated.
47
+ */
48
+ DraftQueueState["Stopped"] = "stopped";
49
+ /**
50
+ * The queue is stopped due to a blocking error from the last upload attempt.
51
+ * The queue will not run again until startDraftQueue() is called.
52
+ */
53
+ DraftQueueState["Error"] = "error";
54
+ /**
55
+ * There was a network error and the queue will attempt to upload again shortly.
56
+ * To attempt to force an upload now call startDraftQueue().
57
+ */
58
+ DraftQueueState["Waiting"] = "waiting";
59
+ })(DraftQueueState || (DraftQueueState = {}));
60
+ var DraftQueueEventType;
61
+ (function (DraftQueueEventType) {
62
+ /**
63
+ * Triggered after an action had been added to the queue
64
+ */
65
+ DraftQueueEventType["ActionAdded"] = "added";
66
+ /**
67
+ * Triggered once an action failed
68
+ */
69
+ DraftQueueEventType["ActionFailed"] = "failed";
70
+ /**
71
+ * Triggered after an action has been deleted from the queue
72
+ */
73
+ DraftQueueEventType["ActionDeleted"] = "deleted";
74
+ /**
75
+ * Triggered after an action has been completed and after it has been removed from the queue
76
+ */
77
+ DraftQueueEventType["ActionCompleted"] = "completed";
78
+ /**
79
+ * Triggered after an action has been updated by the updateAction API
80
+ */
81
+ DraftQueueEventType["ActionUpdated"] = "updated";
82
+ /**
83
+ * Triggered after the Draft Queue state changes
84
+ */
85
+ DraftQueueEventType["QueueStateChanged"] = "state";
86
+ })(DraftQueueEventType || (DraftQueueEventType = {}));
87
+ var QueueOperationType;
88
+ (function (QueueOperationType) {
89
+ QueueOperationType["Add"] = "add";
90
+ QueueOperationType["Delete"] = "delete";
91
+ QueueOperationType["Update"] = "update";
92
+ })(QueueOperationType || (QueueOperationType = {}));
93
+
94
+ class DraftSynthesisError extends Error {
95
+ constructor(message, errorType) {
96
+ super(message);
97
+ this.errorType = errorType;
98
+ }
99
+ }
100
+ function isDraftSynthesisError(error) {
101
+ return error.errorType !== undefined;
102
+ }
103
+
104
+ const DRAFT_ERROR_CODE = 'DRAFT_ERROR';
105
+ class DraftFetchResponse {
106
+ constructor(status, body) {
107
+ this.headers = {};
108
+ this.status = status;
109
+ this.body = body;
110
+ }
111
+ get statusText() {
112
+ const { status } = this;
113
+ switch (status) {
114
+ case HttpStatusCode.Ok:
115
+ return 'OK';
116
+ case HttpStatusCode.Created:
117
+ return 'Created';
118
+ case HttpStatusCode.NoContent:
119
+ return 'No Content';
120
+ case HttpStatusCode.BadRequest:
121
+ return 'Bad Request';
122
+ case HttpStatusCode.ServerError:
123
+ return 'Server Error';
124
+ default:
125
+ return `Unexpected HTTP Status Code: ${status}`;
126
+ }
127
+ }
128
+ get ok() {
129
+ return this.status >= 200 && this.status < 300;
130
+ }
131
+ }
132
+ class DraftErrorFetchResponse {
133
+ constructor(status, body) {
134
+ this.ok = false;
135
+ this.headers = {};
136
+ this.errorType = 'fetchResponse';
137
+ this.status = status;
138
+ this.body = body;
139
+ }
140
+ get statusText() {
141
+ const { status } = this;
142
+ switch (status) {
143
+ case HttpStatusCode.BadRequest:
144
+ return 'Bad Request';
145
+ case HttpStatusCode.ServerError:
146
+ return 'Server Error';
147
+ case HttpStatusCode.NotFound:
148
+ return 'Not Found';
149
+ default:
150
+ return `Unexpected HTTP Status Code: ${status}`;
151
+ }
152
+ }
153
+ }
154
+ function createOkResponse(body) {
155
+ return new DraftFetchResponse(HttpStatusCode.Ok, body);
156
+ }
157
+ function createBadRequestResponse(body) {
158
+ return new DraftErrorFetchResponse(HttpStatusCode.BadRequest, body);
159
+ }
160
+ function createNotFoundResponse(body) {
161
+ return new DraftErrorFetchResponse(HttpStatusCode.NotFound, body);
162
+ }
163
+ function transformErrorToDraftSynthesisError(error) {
164
+ if (isDraftSynthesisError(error)) {
165
+ const { errorType, message } = error;
166
+ return createDraftSynthesisErrorResponse(message, errorType);
167
+ }
168
+ return createDraftSynthesisErrorResponse(error.message);
169
+ }
170
+ function createDraftSynthesisErrorResponse(message = 'failed to synthesize draft response', errorType) {
171
+ const error = {
172
+ errorCode: DRAFT_ERROR_CODE,
173
+ message: message,
174
+ };
175
+ if (errorType !== undefined) {
176
+ error.errorType = errorType;
177
+ }
178
+ return new DraftErrorFetchResponse(HttpStatusCode.BadRequest, error);
179
+ }
180
+ function createDeletedResponse() {
181
+ return new DraftFetchResponse(HttpStatusCode.NoContent, undefined);
182
+ }
183
+ function createInternalErrorResponse() {
184
+ return new DraftErrorFetchResponse(HttpStatusCode.ServerError, undefined);
185
+ }
186
+
187
+ const { keys, create, assign, values } = Object;
188
+ const { stringify, parse } = JSON;
189
+ const { isArray } = Array;
190
+
191
+ function buildLuvioOverrideForDraftAdapters(luvio, handler, extractTargetIdFromCacheKey, options = {}) {
192
+ // override this to create and enqueue a new draft action, and return synthetic response
193
+ const dispatchResourceRequest = async function (resourceRequest, _context) {
194
+ const { data } = await handler.enqueue(resourceRequest).catch((err) => {
195
+ throw transformErrorToDraftSynthesisError(err);
196
+ });
197
+ if (data === undefined) {
198
+ return Promise.reject(createDraftSynthesisErrorResponse());
199
+ }
200
+ return createOkResponse(data);
201
+ };
202
+ // override this to use an infinitely large ttl so the cache entry never expires
203
+ const publishStoreMetadata = function (key, storeMetadataParams) {
204
+ // if we aren't publishing a draft then use base luvio method
205
+ const id = extractTargetIdFromCacheKey(key);
206
+ if (id === undefined || !handler.isDraftId(id)) {
207
+ return luvio.publishStoreMetadata(key, storeMetadataParams);
208
+ }
209
+ return luvio.publishStoreMetadata(key, {
210
+ ...storeMetadataParams,
211
+ ttl: Number.MAX_SAFE_INTEGER,
212
+ });
213
+ };
214
+ if (options.forDeleteAdapter === true) {
215
+ // delete adapters attempt to evict the record on successful network response,
216
+ // since draft-aware delete adapters do soft-delete (record stays in cache
217
+ // with a "drafts.deleted" property) we want storeEvict to just be a no-op
218
+ const storeEvict = function (_key) {
219
+ // no-op
220
+ };
221
+ return create(luvio, {
222
+ dispatchResourceRequest: { value: dispatchResourceRequest },
223
+ publishStoreMetadata: { value: publishStoreMetadata },
224
+ storeEvict: { value: storeEvict },
225
+ });
226
+ }
227
+ return create(luvio, {
228
+ dispatchResourceRequest: { value: dispatchResourceRequest },
229
+ publishStoreMetadata: { value: publishStoreMetadata },
230
+ });
231
+ }
232
+
233
+ const DraftIdMappingKeyPrefix240 = 'DraftIdMapping::';
234
+ const DRAFT_ID_MAPPINGS_SEGMENT = 'DRAFT_ID_MAPPINGS';
235
+ function isLegacyDraftIdMapping(key, data) {
236
+ return key.startsWith(DraftIdMappingKeyPrefix240);
237
+ }
238
+ // TODO [W-11677776]: in 242 we changed the format to store keys instead of ids
239
+ // this can be removed when we drop support for id storing
240
+ function getRecordKeyForId(id) {
241
+ return `UiApi::RecordRepresentation:${id}`;
242
+ }
243
+ /**
244
+ *
245
+ * @param mappingIds (optional) requested mapping ids, if undefined all will be retrieved
246
+ */
247
+ async function getDraftIdMappings(durableStore, mappingIds) {
248
+ const mappings = [];
249
+ let durableStoreOperation;
250
+ if (mappingIds === undefined) {
251
+ durableStoreOperation =
252
+ durableStore.getAllEntries(DRAFT_ID_MAPPINGS_SEGMENT);
253
+ }
254
+ else {
255
+ durableStoreOperation = durableStore.getEntries(mappingIds, DRAFT_ID_MAPPINGS_SEGMENT);
256
+ }
257
+ const entries = await durableStoreOperation;
258
+ if (entries === undefined) {
259
+ return mappings;
260
+ }
261
+ const keys$1 = keys(entries);
262
+ for (const key of keys$1) {
263
+ const entry = entries[key].data;
264
+ if (isLegacyDraftIdMapping(key)) {
265
+ mappings.push({
266
+ draftKey: getRecordKeyForId(entry.draftId),
267
+ canonicalKey: getRecordKeyForId(entry.canonicalId),
268
+ });
269
+ }
270
+ else {
271
+ mappings.push(entry);
272
+ }
273
+ }
274
+ return mappings;
275
+ }
276
+ async function clearDraftIdSegment(durableStore) {
277
+ const entries = await durableStore.getAllEntries(DRAFT_ID_MAPPINGS_SEGMENT);
278
+ if (entries) {
279
+ const keys$1 = keys(entries);
280
+ if (keys$1.length > 0) {
281
+ await durableStore.evictEntries(keys$1, DRAFT_ID_MAPPINGS_SEGMENT);
282
+ }
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Generates a time-ordered, unique id to associate with a DraftAction. Ensures
288
+ * no collisions with existing draft action IDs.
289
+ */
290
+ function generateUniqueDraftActionId(existingIds) {
291
+ // new id in milliseconds with some extra digits for collisions
292
+ let newId = new Date().getTime() * 100;
293
+ const existingAsNumbers = existingIds
294
+ .map((id) => parseInt(id, 10))
295
+ .filter((parsed) => !isNaN(parsed));
296
+ let counter = 0;
297
+ while (existingAsNumbers.includes(newId)) {
298
+ newId += 1;
299
+ counter += 1;
300
+ // if the counter is 100+ then somehow this method has been called 100
301
+ // times in one millisecond
302
+ if (counter >= 100) {
303
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
304
+ throw new Error('Unable to generate unique new draft ID');
305
+ }
306
+ }
307
+ return newId.toString();
308
+ }
309
+
310
+ var CustomActionResultType;
311
+ (function (CustomActionResultType) {
312
+ CustomActionResultType["SUCCESS"] = "SUCCESS";
313
+ CustomActionResultType["FAILURE"] = "FAILURE";
314
+ })(CustomActionResultType || (CustomActionResultType = {}));
315
+ var CustomActionErrorType;
316
+ (function (CustomActionErrorType) {
317
+ CustomActionErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
318
+ CustomActionErrorType["CLIENT_ERROR"] = "CLIENT_ERROR";
319
+ })(CustomActionErrorType || (CustomActionErrorType = {}));
320
+ function isCustomActionSuccess(result) {
321
+ return result.type === CustomActionResultType.SUCCESS;
322
+ }
323
+ function isCustomActionFailed(result) {
324
+ return result.type === CustomActionResultType.FAILURE;
325
+ }
326
+ function customActionHandler(executor, id, draftQueue) {
327
+ const handle = (action, actionCompleted, actionErrored) => {
328
+ notifyCustomActionToExecute(action, actionCompleted, actionErrored);
329
+ return Promise.resolve(ProcessActionResult.CUSTOM_ACTION_WAITING);
330
+ };
331
+ const notifyCustomActionToExecute = (action, actionCompleted, actionErrored) => {
332
+ if (executor !== undefined) {
333
+ executor(action, executorCompleted(action, actionCompleted, actionErrored));
334
+ }
335
+ };
336
+ const executorCompleted = (action, actionCompleted, actionErrored) => (result) => {
337
+ if (isCustomActionSuccess(result)) {
338
+ actionCompleted({
339
+ ...action,
340
+ status: DraftActionStatus.Completed,
341
+ response: createOkResponse(undefined),
342
+ });
343
+ }
344
+ else if (isCustomActionFailed(result)) {
345
+ actionErrored({
346
+ ...action,
347
+ status: DraftActionStatus.Error,
348
+ error: result.error.message,
349
+ }, result.error.type === CustomActionErrorType.NETWORK_ERROR);
350
+ }
351
+ };
352
+ const buildPendingAction = (action, queue) => {
353
+ const { data, tag, targetId, handler } = action;
354
+ const id = generateUniqueDraftActionId(queue.map((a) => a.id));
355
+ return Promise.resolve({
356
+ id,
357
+ targetId,
358
+ status: DraftActionStatus.Pending,
359
+ data,
360
+ tag,
361
+ timestamp: Date.now(),
362
+ metadata: data,
363
+ handler,
364
+ });
365
+ };
366
+ const getQueueOperationsForCompletingDrafts = (_queue, action) => {
367
+ const { id } = action;
368
+ const queueOperations = [];
369
+ queueOperations.push({
370
+ type: QueueOperationType.Delete,
371
+ id: id,
372
+ });
373
+ return queueOperations;
374
+ };
375
+ return {
376
+ handlerId: id,
377
+ enqueue: (data) => {
378
+ return draftQueue.enqueue(id, data);
379
+ },
380
+ handleAction: handle,
381
+ buildPendingAction,
382
+ getQueueOperationsForCompletingDrafts: getQueueOperationsForCompletingDrafts,
383
+ handleReplaceAction: () => {
384
+ throw Error('replaceAction not supported for custom actions');
385
+ },
386
+ handleActionRemoved: () => Promise.resolve(),
387
+ handleActionCompleted: () => Promise.resolve(),
388
+ handleActionEnqueued: () => Promise.resolve(),
389
+ getDataForAction: () => Promise.resolve(undefined),
390
+ getDraftMetadata: () => {
391
+ throw Error('getDraftMetadata not supported for custom actions');
392
+ },
393
+ applyDraftsToIncomingData: () => {
394
+ throw Error('applyDraftsToIncomingData not supported for custom actions');
395
+ },
396
+ shouldDeleteActionByTagOnRemoval: () => false,
397
+ updateMetadata: (existing, incoming) => incoming,
398
+ canHandlePublish: () => false,
399
+ canRepresentationContainDraftMetadata: () => false,
400
+ mergeActions: () => {
401
+ throw Error('mergeActions not supported for custom actions');
402
+ },
403
+ };
404
+ }
405
+
406
+ const DRAFT_SEGMENT = 'DRAFT';
407
+ class DurableDraftQueue {
408
+ getHandler(id) {
409
+ const handler = this.handlers[id];
410
+ if (handler === undefined) {
411
+ throw Error(`No handler registered for ${id}`);
412
+ }
413
+ return handler;
414
+ }
415
+ constructor(draftStore) {
416
+ this.retryIntervalMilliseconds = 0;
417
+ this.minimumRetryInterval = 250;
418
+ this.maximumRetryInterval = 32000;
419
+ this.draftQueueChangedListeners = [];
420
+ this.state = DraftQueueState.Stopped;
421
+ this.userState = DraftQueueState.Stopped;
422
+ this.uploadingActionId = undefined;
423
+ this.timeoutHandler = undefined;
424
+ this.handlers = {};
425
+ this.draftStore = draftStore;
426
+ this.workerPool = new AsyncWorkerPool(1);
427
+ }
428
+ addHandler(handler) {
429
+ const id = handler.handlerId;
430
+ if (this.handlers[id] !== undefined) {
431
+ return Promise.reject(`Unable to add handler to id: ${id} because it already exists.`);
432
+ }
433
+ this.handlers[id] = handler;
434
+ return Promise.resolve();
435
+ }
436
+ removeHandler(id) {
437
+ delete this.handlers[id];
438
+ return Promise.resolve();
439
+ }
440
+ addCustomHandler(id, executor) {
441
+ const handler = customActionHandler(executor, id, this);
442
+ return this.addHandler(handler);
443
+ }
444
+ getQueueState() {
445
+ return this.state;
446
+ }
447
+ async startQueue() {
448
+ this.userState = DraftQueueState.Started;
449
+ if (this.state === DraftQueueState.Started) {
450
+ // Do nothing if the queue state is already started
451
+ return;
452
+ }
453
+ if (this.replacingAction !== undefined) {
454
+ // If we're replacing an action do nothing
455
+ // replace will restart the queue for us as long as the user
456
+ // has last set the queue to be started
457
+ return;
458
+ }
459
+ this.retryIntervalMilliseconds = 0;
460
+ this.state = DraftQueueState.Started;
461
+ await this.notifyChangedListeners({
462
+ type: DraftQueueEventType.QueueStateChanged,
463
+ state: this.state,
464
+ });
465
+ const result = await this.processNextAction();
466
+ switch (result) {
467
+ case ProcessActionResult.BLOCKED_ON_ERROR:
468
+ this.state = DraftQueueState.Error;
469
+ return Promise.reject();
470
+ default:
471
+ return Promise.resolve();
472
+ }
473
+ }
474
+ stopQueue() {
475
+ this.userState = DraftQueueState.Stopped;
476
+ if (this.state === DraftQueueState.Stopped) {
477
+ // Do nothing if the queue state is already stopped
478
+ return Promise.resolve();
479
+ }
480
+ this.stopQueueManually();
481
+ return this.notifyChangedListeners({
482
+ type: DraftQueueEventType.QueueStateChanged,
483
+ state: DraftQueueState.Stopped,
484
+ });
485
+ }
486
+ /**
487
+ * Used to stop the queue within DraftQueue without user interaction
488
+ */
489
+ stopQueueManually() {
490
+ if (this.timeoutHandler) {
491
+ clearTimeout(this.timeoutHandler);
492
+ this.timeoutHandler = undefined;
493
+ }
494
+ this.state = DraftQueueState.Stopped;
495
+ }
496
+ async getQueueActions() {
497
+ const drafts = (await this.draftStore.getAllDrafts());
498
+ const queue = [];
499
+ if (drafts === undefined) {
500
+ return queue;
501
+ }
502
+ drafts.forEach((draft) => {
503
+ if (draft.id === this.uploadingActionId) {
504
+ draft.status = DraftActionStatus.Uploading;
505
+ }
506
+ queue.push(draft);
507
+ });
508
+ return queue.sort((a, b) => {
509
+ const aTime = parseInt(a.id, 10);
510
+ const bTime = parseInt(b.id, 10);
511
+ // safety check
512
+ if (isNaN(aTime)) {
513
+ return 1;
514
+ }
515
+ if (isNaN(bTime)) {
516
+ return -1;
517
+ }
518
+ return aTime - bTime;
519
+ });
520
+ }
521
+ async enqueue(handlerId, data) {
522
+ return this.workerPool.push({
523
+ workFn: async () => {
524
+ let queue = await this.getQueueActions();
525
+ const handler = this.getHandler(handlerId);
526
+ const pendingAction = (await handler.buildPendingAction(data, queue));
527
+ await this.draftStore.writeAction(pendingAction);
528
+ queue = await this.getQueueActions();
529
+ await this.notifyChangedListeners({
530
+ type: DraftQueueEventType.ActionAdded,
531
+ action: pendingAction,
532
+ });
533
+ await handler.handleActionEnqueued(pendingAction, queue);
534
+ if (this.state === DraftQueueState.Started) {
535
+ this.processNextAction();
536
+ }
537
+ const actionData = (await handler.getDataForAction(pendingAction));
538
+ return {
539
+ action: pendingAction,
540
+ data: actionData,
541
+ };
542
+ },
543
+ });
544
+ }
545
+ registerOnChangedListener(listener) {
546
+ this.draftQueueChangedListeners.push(listener);
547
+ return () => {
548
+ this.draftQueueChangedListeners = this.draftQueueChangedListeners.filter((l) => {
549
+ return l !== listener;
550
+ });
551
+ return Promise.resolve();
552
+ };
553
+ }
554
+ async actionCompleted(action) {
555
+ return this.workerPool.push({
556
+ workFn: async () => {
557
+ const handler = this.getHandler(action.handler);
558
+ let queue = await this.getQueueActions();
559
+ const queueOperations = handler.getQueueOperationsForCompletingDrafts(queue, action);
560
+ // write the queue operations to the store prior to ingesting the result
561
+ await this.draftStore.completeAction(queueOperations);
562
+ await handler.handleActionCompleted(action, queueOperations, values(this.handlers));
563
+ this.retryIntervalMilliseconds = 0;
564
+ this.uploadingActionId = undefined;
565
+ await this.notifyChangedListeners({
566
+ type: DraftQueueEventType.ActionCompleted,
567
+ action,
568
+ });
569
+ if (this.state === DraftQueueState.Started) {
570
+ this.processNextAction();
571
+ }
572
+ },
573
+ });
574
+ }
575
+ async actionFailed(action, retry) {
576
+ this.uploadingActionId = undefined;
577
+ if (retry && this.state !== DraftQueueState.Stopped) {
578
+ this.state = DraftQueueState.Waiting;
579
+ this.scheduleRetry();
580
+ }
581
+ else if (isDraftError(action)) {
582
+ return this.handleServerError(action, action.error);
583
+ }
584
+ }
585
+ handle(action) {
586
+ const handler = this.getHandler(action.handler);
587
+ if (handler === undefined) {
588
+ return Promise.reject(`No handler for ${action.handler}.`);
589
+ }
590
+ return handler.handleAction(action, this.actionCompleted.bind(this), this.actionFailed.bind(this));
591
+ }
592
+ async processNextAction() {
593
+ if (this.processingAction !== undefined) {
594
+ return this.processingAction;
595
+ }
596
+ const queue = await this.getQueueActions();
597
+ const action = queue[0];
598
+ if (action === undefined) {
599
+ this.processingAction = undefined;
600
+ return ProcessActionResult.NO_ACTION_TO_PROCESS;
601
+ }
602
+ const { status, id } = action;
603
+ if (status === DraftActionStatus.Error) {
604
+ this.state = DraftQueueState.Error;
605
+ this.processingAction = undefined;
606
+ return ProcessActionResult.BLOCKED_ON_ERROR;
607
+ }
608
+ if (id === this.uploadingActionId) {
609
+ this.state = DraftQueueState.Started;
610
+ this.processingAction = undefined;
611
+ return ProcessActionResult.ACTION_ALREADY_PROCESSING;
612
+ }
613
+ this.uploadingActionId = id;
614
+ this.processingAction = undefined;
615
+ if (this.state === DraftQueueState.Waiting) {
616
+ this.state = DraftQueueState.Started;
617
+ }
618
+ return this.handle(action);
619
+ }
620
+ async handleServerError(action, error) {
621
+ const queue = await this.getQueueActions();
622
+ const localAction = queue.filter((qAction) => qAction.id === action.id)[0];
623
+ let newMetadata = {};
624
+ if (localAction !== undefined) {
625
+ newMetadata = localAction.metadata || {};
626
+ }
627
+ const errorAction = {
628
+ ...action,
629
+ status: DraftActionStatus.Error,
630
+ error,
631
+ metadata: newMetadata,
632
+ };
633
+ await this.draftStore.writeAction(errorAction);
634
+ this.state = DraftQueueState.Error;
635
+ return this.notifyChangedListeners({
636
+ type: DraftQueueEventType.ActionFailed,
637
+ action: errorAction,
638
+ });
639
+ }
640
+ async notifyChangedListeners(event) {
641
+ const results = [];
642
+ const { draftQueueChangedListeners } = this;
643
+ const { length: draftQueueLen } = draftQueueChangedListeners;
644
+ for (let i = 0; i < draftQueueLen; i++) {
645
+ const listener = draftQueueChangedListeners[i];
646
+ results.push(listener(event));
647
+ }
648
+ await Promise.all(results);
649
+ }
650
+ /**
651
+ * only starts the queue if user state is "Started" and if queue not already
652
+ * started
653
+ */
654
+ async startQueueSafe() {
655
+ if (this.userState === DraftQueueState.Started && this.state !== DraftQueueState.Started) {
656
+ await this.startQueue();
657
+ }
658
+ }
659
+ async removeDraftAction(actionId) {
660
+ const queue = await this.getQueueActions();
661
+ //Get the store key for the removed action
662
+ const actions = queue.filter((action) => action.id === actionId);
663
+ if (actions.length === 0) {
664
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
665
+ throw new Error(`No removable action with id ${actionId}`);
666
+ }
667
+ const action = actions[0];
668
+ if (action.id === this.uploadingActionId) {
669
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
670
+ throw new Error(`Cannot remove an uploading draft action with ID ${actionId}`);
671
+ }
672
+ const handler = this.getHandler(action.handler);
673
+ const shouldDeleteRelated = handler.shouldDeleteActionByTagOnRemoval(action);
674
+ if (shouldDeleteRelated) {
675
+ await this.draftStore.deleteByTag(action.tag);
676
+ }
677
+ else {
678
+ await this.draftStore.deleteDraft(action.id);
679
+ }
680
+ await handler.handleActionRemoved(action, queue.filter((x) => x.id !== actionId));
681
+ await this.notifyChangedListeners({
682
+ type: DraftQueueEventType.ActionDeleted,
683
+ action,
684
+ });
685
+ if (this.userState === DraftQueueState.Started &&
686
+ this.state !== DraftQueueState.Started &&
687
+ this.replacingAction === undefined) {
688
+ await this.startQueue();
689
+ }
690
+ }
691
+ replaceAction(targetActionId, sourceActionId) {
692
+ return this.replaceOrMergeActions(targetActionId, sourceActionId, false);
693
+ }
694
+ mergeActions(targetActionId, sourceActionId) {
695
+ return this.replaceOrMergeActions(targetActionId, sourceActionId, true);
696
+ }
697
+ async setMetadata(actionId, metadata) {
698
+ const keys$1 = keys(metadata);
699
+ const compatibleKeys = keys$1.filter((key) => {
700
+ const value = metadata[key];
701
+ return typeof key === 'string' && typeof value === 'string';
702
+ });
703
+ if (keys$1.length !== compatibleKeys.length) {
704
+ return Promise.reject('Cannot save incompatible metadata');
705
+ }
706
+ const queue = await this.getQueueActions();
707
+ const actions = queue.filter((action) => action.id === actionId);
708
+ if (actions.length === 0) {
709
+ return Promise.reject('cannot save metadata to non-existent action');
710
+ }
711
+ const action = actions[0];
712
+ const handler = this.getHandler(action.handler);
713
+ action.metadata = handler.updateMetadata(action.metadata, metadata);
714
+ await this.draftStore.writeAction(action);
715
+ await this.notifyChangedListeners({
716
+ type: DraftQueueEventType.ActionUpdated,
717
+ action: action,
718
+ });
719
+ return action;
720
+ }
721
+ scheduleRetry() {
722
+ const newInterval = this.retryIntervalMilliseconds * 2;
723
+ this.retryIntervalMilliseconds = Math.min(Math.max(newInterval, this.minimumRetryInterval), this.maximumRetryInterval);
724
+ this.timeoutHandler = setTimeout(() => {
725
+ if (this.state !== DraftQueueState.Stopped) {
726
+ this.processNextAction();
727
+ }
728
+ }, this.retryIntervalMilliseconds);
729
+ }
730
+ async getActionsForReplaceOrMerge(targetActionId, sourceActionId) {
731
+ const actions = await this.getQueueActions();
732
+ const target = actions.find((action) => action.id === targetActionId);
733
+ if (target === undefined) {
734
+ this.replacingAction = undefined;
735
+ await this.startQueueSafe();
736
+ throw Error(`targetActionId ${targetActionId} not found in the draft queue.`);
737
+ }
738
+ const source = actions.find((action) => action.id === sourceActionId);
739
+ if (source === undefined) {
740
+ this.replacingAction = undefined;
741
+ await this.startQueueSafe();
742
+ throw Error(`sourceActionId ${sourceActionId} not found in the draft queue.`);
743
+ }
744
+ return { target, source };
745
+ }
746
+ assertReplaceOrMergePrerequisites(target, source) {
747
+ // ensure actions are in a state to be replaced/merged
748
+ const { targetId: targetCacheKey, tag: targetTag, status: targetStatus, version: targetVersion, } = target;
749
+ const { targetId: sourceCacheKey, tag: sourceTag, status: sourceStatus, version: sourceVersion, } = source;
750
+ if (targetCacheKey !== sourceCacheKey) {
751
+ throw Error('Cannot replace/merge actions for different targetIds.');
752
+ }
753
+ if (targetTag !== sourceTag) {
754
+ throw Error('Cannot replace/merge actions for different tags.');
755
+ }
756
+ if (targetStatus === DraftActionStatus.Completed ||
757
+ targetStatus === DraftActionStatus.Uploading) {
758
+ throw Error(`Cannot replace/merge actions when targetAction is in ${targetStatus} status.`);
759
+ }
760
+ if (sourceStatus !== DraftActionStatus.Pending) {
761
+ throw Error(`Cannot replace/merge actions when sourceAction is in ${sourceStatus} status.`);
762
+ }
763
+ if (targetVersion !== sourceVersion) {
764
+ throw Error('Cannot replace/merge actions with different versions.');
765
+ }
766
+ }
767
+ async replaceOrMergeActions(targetActionId, sourceActionId, merge) {
768
+ // ids must be unique
769
+ if (targetActionId === sourceActionId) {
770
+ throw Error('targetActionId and sourceActionId cannot be the same.');
771
+ }
772
+ // cannot have a replace action already in progress
773
+ if (this.replacingAction !== undefined) {
774
+ throw Error('Cannot replace/merge actions while a replace/merge action operation is in progress.');
775
+ }
776
+ this.stopQueueManually();
777
+ const promise = this.getActionsForReplaceOrMerge(targetActionId, sourceActionId).then(async ({ target, source }) => {
778
+ // put in a try/finally block so we don't leave this.replacingAction
779
+ // indefinitely set
780
+ let updatedTarget;
781
+ try {
782
+ this.assertReplaceOrMergePrerequisites(target, source);
783
+ const handler = this.getHandler(target.handler);
784
+ updatedTarget = merge
785
+ ? handler.mergeActions(target, source)
786
+ : handler.handleReplaceAction(target, source);
787
+ // update the target
788
+ await this.draftStore.writeAction(updatedTarget);
789
+ await this.notifyChangedListeners({
790
+ type: DraftQueueEventType.ActionUpdated,
791
+ action: updatedTarget,
792
+ });
793
+ // remove the source from queue
794
+ await this.removeDraftAction(sourceActionId);
795
+ }
796
+ finally {
797
+ this.replacingAction = undefined;
798
+ await this.startQueueSafe();
799
+ }
800
+ return updatedTarget;
801
+ });
802
+ this.replacingAction = promise;
803
+ return promise;
804
+ }
805
+ }
806
+
807
+ const DRAFT_ACTION_KEY_JUNCTION = '__DraftAction__';
808
+ function buildDraftDurableStoreKey(recordKey, draftActionId) {
809
+ return `${recordKey}${DRAFT_ACTION_KEY_JUNCTION}${draftActionId}`;
810
+ }
811
+ /**
812
+ * Implements a write-through InMemoryStore for Drafts, storing all drafts in a
813
+ * in-memory store with a write through to the DurableStore.
814
+ *
815
+ * Before any reads or writes come in from the draft queue, we need to revive the draft
816
+ * queue into memory. During this initial revive, any writes are queued up and operated on the
817
+ * queue once it's in memory. Similarly any reads are delayed until the queue is in memory.
818
+ *
819
+ */
820
+ class DurableDraftStore {
821
+ constructor(durableStore) {
822
+ this.draftStore = {};
823
+ // queue of writes that were made during the initial sync
824
+ this.writeQueue = [];
825
+ this.durableStore = durableStore;
826
+ this.resyncDraftStore();
827
+ }
828
+ writeAction(action) {
829
+ const addAction = () => {
830
+ const { id, tag } = action;
831
+ this.draftStore[id] = action;
832
+ const durableEntryKey = buildDraftDurableStoreKey(tag, id);
833
+ const entry = {
834
+ data: action,
835
+ };
836
+ const entries = { [durableEntryKey]: entry };
837
+ return this.durableStore.setEntries(entries, DRAFT_SEGMENT);
838
+ };
839
+ return this.enqueueAction(addAction);
840
+ }
841
+ getAllDrafts() {
842
+ const waitForOngoingSync = this.syncPromise || Promise.resolve();
843
+ return waitForOngoingSync.then(() => {
844
+ const { draftStore } = this;
845
+ const keys$1 = keys(draftStore);
846
+ const actionArray = [];
847
+ for (let i = 0, len = keys$1.length; i < len; i++) {
848
+ const key = keys$1[i];
849
+ actionArray.push(draftStore[key]);
850
+ }
851
+ return actionArray;
852
+ });
853
+ }
854
+ deleteDraft(id) {
855
+ const deleteAction = () => {
856
+ const draft = this.draftStore[id];
857
+ if (draft !== undefined) {
858
+ delete this.draftStore[id];
859
+ const durableKey = buildDraftDurableStoreKey(draft.tag, draft.id);
860
+ return this.durableStore.evictEntries([durableKey], DRAFT_SEGMENT);
861
+ }
862
+ return Promise.resolve();
863
+ };
864
+ return this.enqueueAction(deleteAction);
865
+ }
866
+ deleteByTag(tag) {
867
+ const deleteAction = () => {
868
+ const { draftStore } = this;
869
+ const keys$1 = keys(draftStore);
870
+ const durableKeys = [];
871
+ for (let i = 0, len = keys$1.length; i < len; i++) {
872
+ const key = keys$1[i];
873
+ const action = draftStore[key];
874
+ if (action.tag === tag) {
875
+ delete draftStore[action.id];
876
+ durableKeys.push(buildDraftDurableStoreKey(action.tag, action.id));
877
+ }
878
+ }
879
+ return this.durableStore.evictEntries(durableKeys, DRAFT_SEGMENT);
880
+ };
881
+ return this.enqueueAction(deleteAction);
882
+ }
883
+ completeAction(queueOperations) {
884
+ const action = () => {
885
+ const durableStoreOperations = [];
886
+ const { draftStore } = this;
887
+ for (let i = 0, len = queueOperations.length; i < len; i++) {
888
+ const operation = queueOperations[i];
889
+ if (operation.type === QueueOperationType.Delete) {
890
+ const action = draftStore[operation.id];
891
+ if (action !== undefined) {
892
+ delete draftStore[operation.id];
893
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
894
+ durableStoreOperations.push({
895
+ ids: [key],
896
+ type: 'evictEntries',
897
+ segment: DRAFT_SEGMENT,
898
+ });
899
+ }
900
+ }
901
+ else {
902
+ const { action } = operation;
903
+ const key = buildDraftDurableStoreKey(action.tag, action.id);
904
+ draftStore[action.id] = action;
905
+ durableStoreOperations.push({
906
+ type: 'setEntries',
907
+ segment: DRAFT_SEGMENT,
908
+ entries: {
909
+ [key]: {
910
+ data: operation.action,
911
+ },
912
+ },
913
+ });
914
+ }
915
+ }
916
+ return this.durableStore.batchOperations(durableStoreOperations);
917
+ };
918
+ return this.enqueueAction(action);
919
+ }
920
+ /**
921
+ * Runs a write operation against the draft store, if the initial
922
+ * revive is still in progress, the action gets enqueued to run once the
923
+ * initial revive is complete
924
+ * @param action
925
+ * @returns a promise that is resolved once the action has run
926
+ */
927
+ enqueueAction(action) {
928
+ const { syncPromise, writeQueue: pendingMerges } = this;
929
+ // if the initial sync is done and existing operations have been run, no need to queue, just run
930
+ if (syncPromise === undefined && pendingMerges.length === 0) {
931
+ return action();
932
+ }
933
+ const deferred = new Promise((resolve, reject) => {
934
+ this.writeQueue.push(() => {
935
+ return action()
936
+ .then((x) => {
937
+ resolve(x);
938
+ })
939
+ .catch((err) => reject(err));
940
+ });
941
+ });
942
+ return deferred;
943
+ }
944
+ /**
945
+ * Revives the draft store from the durable store. Once the draft store is
946
+ * revived, executes any queued up draft store operations that came in while
947
+ * reviving
948
+ */
949
+ resyncDraftStore() {
950
+ const sync = () => {
951
+ this.syncPromise = this.durableStore
952
+ .getAllEntries(DRAFT_SEGMENT)
953
+ .then((durableEntries) => {
954
+ if (durableEntries === undefined) {
955
+ this.draftStore = {};
956
+ return this.runQueuedOperations();
957
+ }
958
+ const { draftStore } = this;
959
+ const keys$1 = keys(durableEntries);
960
+ for (let i = 0, len = keys$1.length; i < len; i++) {
961
+ const entry = durableEntries[keys$1[i]];
962
+ const action = entry.data;
963
+ if (action !== undefined) {
964
+ if (process.env.NODE_ENV !== 'production') {
965
+ // the `version` property was introduced in 242, we should assert version
966
+ // exists once we are sure there are no durable stores that contain
967
+ // versionless actions
968
+ if (action.version && action.version !== '242.0.0') {
969
+ return Promise.reject('Unexpected draft action version found in the durable store');
970
+ }
971
+ }
972
+ draftStore[action.id] = action;
973
+ }
974
+ else {
975
+ if (process.env.NODE_ENV !== 'production') {
976
+ const err = new Error('Expected draft action to be defined in the durable store');
977
+ return Promise.reject(err);
978
+ }
979
+ }
980
+ }
981
+ return this.runQueuedOperations();
982
+ })
983
+ .finally(() => {
984
+ this.syncPromise = undefined;
985
+ });
986
+ return this.syncPromise;
987
+ };
988
+ // if there's an ongoing sync populating the in memory store, wait for it to complete before re-syncing
989
+ const { syncPromise } = this;
990
+ if (syncPromise === undefined) {
991
+ return sync();
992
+ }
993
+ return syncPromise.then(() => {
994
+ return sync();
995
+ });
996
+ }
997
+ /**
998
+ * Runs the operations that were queued up while reviving the
999
+ * draft store from the durable store
1000
+ */
1001
+ runQueuedOperations() {
1002
+ const { writeQueue } = this;
1003
+ if (writeQueue.length > 0) {
1004
+ const queueItem = writeQueue.shift();
1005
+ if (queueItem !== undefined) {
1006
+ return queueItem().then(() => {
1007
+ return this.runQueuedOperations();
1008
+ });
1009
+ }
1010
+ }
1011
+ return Promise.resolve();
1012
+ }
1013
+ }
1014
+
1015
+ class AbstractResourceRequestActionHandler {
1016
+ constructor(draftQueue, networkAdapter, getLuvio) {
1017
+ this.draftQueue = draftQueue;
1018
+ this.networkAdapter = networkAdapter;
1019
+ this.getLuvio = getLuvio;
1020
+ // NOTE[W-12567340]: This property stores in-memory mappings between draft
1021
+ // ids and canonical ids for the current session. Having a local copy of
1022
+ // these mappings is necessary to avoid a race condition between publishing
1023
+ // new mappings to the durable store and those mappings being loaded into
1024
+ // the luvio store redirect table, during which a new draft might be enqueued
1025
+ // which would not see a necessary mapping.
1026
+ this.ephemeralRedirects = {};
1027
+ }
1028
+ enqueue(data) {
1029
+ return this.draftQueue.enqueue(this.handlerId, data);
1030
+ }
1031
+ async handleAction(action, actionCompleted, actionErrored) {
1032
+ const { data: request } = action;
1033
+ // no context is stored in draft action
1034
+ try {
1035
+ const response = await this.networkAdapter(request, {});
1036
+ if (response.ok) {
1037
+ await actionCompleted({
1038
+ ...action,
1039
+ response,
1040
+ status: DraftActionStatus.Completed,
1041
+ });
1042
+ return ProcessActionResult.ACTION_SUCCEEDED;
1043
+ }
1044
+ await actionErrored({
1045
+ ...action,
1046
+ error: response,
1047
+ status: DraftActionStatus.Error,
1048
+ }, false);
1049
+ return ProcessActionResult.ACTION_ERRORED;
1050
+ }
1051
+ catch (_a) {
1052
+ await actionErrored(action, true);
1053
+ return ProcessActionResult.NETWORK_ERROR;
1054
+ }
1055
+ }
1056
+ async buildPendingAction(request, queue) {
1057
+ const targetId = await this.getIdFromRequest(request);
1058
+ if (targetId === undefined) {
1059
+ return Promise.reject(new Error('Cannot determine target id from the resource request'));
1060
+ }
1061
+ const tag = this.buildTagForTargetId(targetId);
1062
+ const handlerActions = queue.filter((x) => x.handler === this.handlerId);
1063
+ if (request.method === 'post' && actionsForTag(tag, handlerActions).length > 0) {
1064
+ return Promise.reject(new Error('Cannot enqueue a POST draft action with an existing tag'));
1065
+ }
1066
+ if (deleteActionsForTag(tag, handlerActions).length > 0) {
1067
+ return Promise.reject(new Error('Cannot enqueue a draft action for a deleted record'));
1068
+ }
1069
+ return {
1070
+ handler: this.handlerId,
1071
+ targetId,
1072
+ tag,
1073
+ data: request,
1074
+ status: DraftActionStatus.Pending,
1075
+ id: generateUniqueDraftActionId(queue.map((x) => x.id)),
1076
+ timestamp: Date.now(),
1077
+ metadata: {},
1078
+ version: '242.0.0',
1079
+ };
1080
+ }
1081
+ async handleActionEnqueued(action) {
1082
+ const { method } = action.data;
1083
+ // delete adapters don't get a value back to ingest so
1084
+ // we ingest it for them here
1085
+ if (method === 'delete') {
1086
+ await this.reingestRecord(action);
1087
+ }
1088
+ }
1089
+ handleActionRemoved(action) {
1090
+ return this.reingestRecord(action);
1091
+ }
1092
+ getQueueOperationsForCompletingDrafts(queue, action) {
1093
+ const queueOperations = [];
1094
+ const redirects = this.getRedirectMappings(action);
1095
+ if (redirects !== undefined) {
1096
+ const { length } = queue;
1097
+ for (let i = 0; i < length; i++) {
1098
+ const queueAction = queue[i];
1099
+ // if this queueAction is the action that is completing we can move on,
1100
+ // it is about to be deleted and won't have the draft ID in it
1101
+ if (queueAction.id === action.id) {
1102
+ continue;
1103
+ }
1104
+ if (isResourceRequestAction(queueAction)) {
1105
+ let queueOperationMutated = false;
1106
+ let updatedActionTag = undefined;
1107
+ let updatedActionTargetId = undefined;
1108
+ const { tag: queueActionTag, data: queueActionRequest, id: queueActionId, } = queueAction;
1109
+ let { basePath, body } = queueActionRequest;
1110
+ let stringifiedBody = stringify(body);
1111
+ // for each redirected ID/key we loop over the operation to see if it needs
1112
+ // to be updated
1113
+ for (const { draftId, draftKey, canonicalId, canonicalKey } of redirects) {
1114
+ if (basePath.search(draftId) >= 0 || stringifiedBody.search(draftId) >= 0) {
1115
+ basePath = basePath.replace(draftId, canonicalId);
1116
+ stringifiedBody = stringifiedBody.replace(draftId, canonicalId);
1117
+ queueOperationMutated = true;
1118
+ }
1119
+ // if the action is performed on a previous draft id, we need to replace the action
1120
+ // with a new one at the updated canonical key
1121
+ if (queueActionTag === draftKey) {
1122
+ updatedActionTag = canonicalKey;
1123
+ updatedActionTargetId = canonicalId;
1124
+ }
1125
+ }
1126
+ if (queueOperationMutated) {
1127
+ if (updatedActionTag !== undefined && updatedActionTargetId !== undefined) {
1128
+ const updatedAction = {
1129
+ ...queueAction,
1130
+ tag: updatedActionTag,
1131
+ targetId: updatedActionTargetId,
1132
+ data: {
1133
+ ...queueActionRequest,
1134
+ basePath: basePath,
1135
+ body: parse(stringifiedBody),
1136
+ },
1137
+ };
1138
+ // item needs to be replaced with a new item at the new record key
1139
+ queueOperations.push({
1140
+ type: QueueOperationType.Delete,
1141
+ id: queueActionId,
1142
+ });
1143
+ queueOperations.push({
1144
+ type: QueueOperationType.Add,
1145
+ action: updatedAction,
1146
+ });
1147
+ }
1148
+ else {
1149
+ const updatedAction = {
1150
+ ...queueAction,
1151
+ data: {
1152
+ ...queueActionRequest,
1153
+ basePath: basePath,
1154
+ body: parse(stringifiedBody),
1155
+ },
1156
+ };
1157
+ // item needs to be updated
1158
+ queueOperations.push({
1159
+ type: QueueOperationType.Update,
1160
+ id: queueActionId,
1161
+ action: updatedAction,
1162
+ });
1163
+ }
1164
+ }
1165
+ }
1166
+ }
1167
+ }
1168
+ // delete completed action
1169
+ queueOperations.push({
1170
+ type: QueueOperationType.Delete,
1171
+ id: action.id,
1172
+ });
1173
+ return queueOperations;
1174
+ }
1175
+ getRedirectMappings(action) {
1176
+ if (action.data.method !== 'post') {
1177
+ return undefined;
1178
+ }
1179
+ const body = action.response.body;
1180
+ const canonicalId = this.getIdFromResponseBody(body);
1181
+ const draftId = action.targetId;
1182
+ if (draftId !== undefined && canonicalId !== undefined && draftId !== canonicalId) {
1183
+ this.ephemeralRedirects[draftId] = canonicalId;
1184
+ }
1185
+ return [
1186
+ {
1187
+ draftId,
1188
+ canonicalId,
1189
+ draftKey: this.buildTagForTargetId(draftId),
1190
+ canonicalKey: this.buildTagForTargetId(canonicalId),
1191
+ },
1192
+ ];
1193
+ }
1194
+ async handleActionCompleted(action, queueOperations, allHandlers) {
1195
+ const { data: request, tag } = action;
1196
+ const { method } = request;
1197
+ if (method === 'delete') {
1198
+ return this.evictKey(tag);
1199
+ }
1200
+ const recordsToIngest = [];
1201
+ recordsToIngest.push({
1202
+ response: action.response.body,
1203
+ synchronousIngest: this.synchronousIngest.bind(this),
1204
+ buildCacheKeysForResponse: this.buildCacheKeysFromResponse.bind(this),
1205
+ });
1206
+ const recordsNeedingReplay = queueOperations.filter((x) => x.type === QueueOperationType.Update);
1207
+ for (const recordNeedingReplay of recordsNeedingReplay) {
1208
+ const { action } = recordNeedingReplay;
1209
+ if (isResourceRequestAction(action)) {
1210
+ // We can't assume the queue operation is for our handler, have to find the handler.
1211
+ const handler = allHandlers.find((h) => h.handlerId === action.handler);
1212
+ if (handler !== undefined) {
1213
+ const record = await handler.getDataForAction(action);
1214
+ if (record !== undefined) {
1215
+ recordsToIngest.push({
1216
+ response: record,
1217
+ synchronousIngest: handler.synchronousIngest.bind(handler),
1218
+ buildCacheKeysForResponse: handler.buildCacheKeysFromResponse.bind(handler),
1219
+ });
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ await this.ingestResponses(recordsToIngest, action);
1225
+ }
1226
+ handleReplaceAction(targetAction, sourceAction) {
1227
+ //reject if the action to replace is a POST action
1228
+ const pendingAction = targetAction;
1229
+ if (pendingAction.data.method === 'post') {
1230
+ throw Error('Cannot replace a POST action');
1231
+ }
1232
+ if (this.isActionOfType(targetAction) &&
1233
+ this.isActionOfType(sourceAction)) {
1234
+ targetAction.status = DraftActionStatus.Pending;
1235
+ targetAction.data = sourceAction.data;
1236
+ return targetAction;
1237
+ }
1238
+ else {
1239
+ throw Error('Incompatible Action types to replace one another');
1240
+ }
1241
+ }
1242
+ mergeActions(targetAction, sourceAction) {
1243
+ const { id: targetId, data: targetData, metadata: targetMetadata, timestamp: targetTimestamp, } = targetAction;
1244
+ const { method: targetMethod, body: targetBody } = targetData;
1245
+ const { data: sourceData, metadata: sourceMetadata } = sourceAction;
1246
+ const { method: sourceMethod, body: sourceBody } = sourceData;
1247
+ if (targetMethod.toLowerCase() === 'delete' || sourceMethod.toLowerCase() === 'delete') {
1248
+ throw Error('Cannot merge DELETE actions.');
1249
+ }
1250
+ if (targetMethod.toLowerCase() === 'patch' && sourceMethod.toLowerCase() === 'post') {
1251
+ // overlaying a POST over a PATCH is not supported
1252
+ throw Error('Cannot merge a POST action over top of a PATCH action.');
1253
+ }
1254
+ // overlay top-level properties, maintain target's timestamp and id
1255
+ const merged = {
1256
+ ...targetAction,
1257
+ ...sourceAction,
1258
+ timestamp: targetTimestamp,
1259
+ id: targetId,
1260
+ };
1261
+ // overlay data
1262
+ // NOTE: we stick to the target's ResourceRequest properties (except body
1263
+ // which is merged) because we don't want to overwrite a POST with a PATCH
1264
+ // (all other cases should be fine or wouldn't have passed pre-requisites)
1265
+ merged.data = {
1266
+ ...targetData,
1267
+ body: this.mergeRequestBody(targetBody, sourceBody),
1268
+ };
1269
+ // overlay metadata
1270
+ merged.metadata = { ...targetMetadata, ...sourceMetadata };
1271
+ // put status back to pending to auto upload if queue is active and targed is at the head.
1272
+ merged.status = DraftActionStatus.Pending;
1273
+ return merged;
1274
+ }
1275
+ shouldDeleteActionByTagOnRemoval(action) {
1276
+ return action.data.method === 'post';
1277
+ }
1278
+ updateMetadata(_existingMetadata, incomingMetadata) {
1279
+ return incomingMetadata;
1280
+ }
1281
+ isActionOfType(action) {
1282
+ return action.handler === this.handlerId;
1283
+ }
1284
+ async reingestRecord(action) {
1285
+ const record = await this.getDataForAction(action);
1286
+ if (record !== undefined) {
1287
+ await this.ingestResponses([
1288
+ {
1289
+ response: record,
1290
+ synchronousIngest: this.synchronousIngest.bind(this),
1291
+ buildCacheKeysForResponse: this.buildCacheKeysFromResponse.bind(this),
1292
+ },
1293
+ ], action);
1294
+ }
1295
+ else {
1296
+ await this.evictKey(action.tag);
1297
+ }
1298
+ }
1299
+ // Given an action for this handler this method should return the draft IDs.
1300
+ // Most of the time it will simply be the targetId, but certain handlers might
1301
+ // have multiple draft-created IDs so they would override this to return them.
1302
+ getDraftIdsFromAction(action) {
1303
+ return [action.targetId];
1304
+ }
1305
+ async ingestResponses(responses, action) {
1306
+ const luvio = this.getLuvio();
1307
+ await luvio.handleSuccessResponse(() => {
1308
+ if (action.status === DraftActionStatus.Completed) {
1309
+ const mappings = this.getRedirectMappings(action);
1310
+ if (mappings) {
1311
+ mappings.forEach((mapping) => {
1312
+ luvio.storeRedirect(mapping.draftKey, mapping.canonicalKey);
1313
+ });
1314
+ }
1315
+ }
1316
+ for (const entry of responses) {
1317
+ const { response, synchronousIngest } = entry;
1318
+ synchronousIngest(response, action);
1319
+ }
1320
+ return luvio.storeBroadcast();
1321
+ },
1322
+ // getTypeCacheKeysRecord uses the response, not the full path factory
1323
+ // so 2nd parameter will be unused
1324
+ () => {
1325
+ const keySet = new StoreKeyMap();
1326
+ for (const entry of responses) {
1327
+ const { response, buildCacheKeysForResponse } = entry;
1328
+ const set = buildCacheKeysForResponse(response);
1329
+ for (const key of set.keys()) {
1330
+ const value = set.get(key);
1331
+ if (value !== undefined) {
1332
+ keySet.set(key, value);
1333
+ }
1334
+ }
1335
+ }
1336
+ return keySet;
1337
+ });
1338
+ }
1339
+ async evictKey(key) {
1340
+ const luvio = this.getLuvio();
1341
+ await luvio.handleSuccessResponse(() => {
1342
+ luvio.storeEvict(key);
1343
+ return luvio.storeBroadcast();
1344
+ }, () => {
1345
+ return new StoreKeyMap();
1346
+ });
1347
+ }
1348
+ }
1349
+ function actionsForTag(tag, queue) {
1350
+ return queue.filter((action) => action.tag === tag);
1351
+ }
1352
+ function deleteActionsForTag(tag, queue) {
1353
+ return queue.filter((action) => action.tag === tag && action.data.method === 'delete');
1354
+ }
1355
+ function isResourceRequestAction(action) {
1356
+ const dataAsAny = action.data;
1357
+ return (dataAsAny !== undefined && dataAsAny.method !== undefined && dataAsAny.body !== undefined);
1358
+ }
1359
+
1360
+ /**
1361
+ * Denotes what kind of operation a DraftQueueItem represents.
1362
+ */
1363
+ var DraftActionOperationType;
1364
+ (function (DraftActionOperationType) {
1365
+ DraftActionOperationType["Create"] = "create";
1366
+ DraftActionOperationType["Update"] = "update";
1367
+ DraftActionOperationType["Delete"] = "delete";
1368
+ DraftActionOperationType["Custom"] = "custom";
1369
+ })(DraftActionOperationType || (DraftActionOperationType = {}));
1370
+ var DraftQueueOperationType;
1371
+ (function (DraftQueueOperationType) {
1372
+ DraftQueueOperationType["ItemAdded"] = "added";
1373
+ DraftQueueOperationType["ItemDeleted"] = "deleted";
1374
+ DraftQueueOperationType["ItemCompleted"] = "completed";
1375
+ DraftQueueOperationType["ItemFailed"] = "failed";
1376
+ DraftQueueOperationType["ItemUpdated"] = "updated";
1377
+ DraftQueueOperationType["QueueStarted"] = "started";
1378
+ DraftQueueOperationType["QueueStopped"] = "stopped";
1379
+ })(DraftQueueOperationType || (DraftQueueOperationType = {}));
1380
+ /**
1381
+ * Converts the internal DraftAction's ResourceRequest into
1382
+ * a DraftActionOperationType.
1383
+ * Returns a DraftActionOperationType as long as the http request is a
1384
+ * valid method type for DraftQueue or else it is undefined.
1385
+ * @param action
1386
+ */
1387
+ function getOperationTypeFrom(action) {
1388
+ if (isResourceRequestAction(action)) {
1389
+ if (action.data !== undefined && action.data.method !== undefined) {
1390
+ switch (action.data.method) {
1391
+ case 'put':
1392
+ case 'patch':
1393
+ return DraftActionOperationType.Update;
1394
+ case 'post':
1395
+ return DraftActionOperationType.Create;
1396
+ case 'delete':
1397
+ return DraftActionOperationType.Delete;
1398
+ default:
1399
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1400
+ throw new Error(`${action.data.method} is an unsupported request method type for DraftQueue.`);
1401
+ }
1402
+ }
1403
+ else {
1404
+ // eslint-disable-next-line @salesforce/lds/no-error-in-production
1405
+ throw new Error(`action has no data found`);
1406
+ }
1407
+ }
1408
+ else {
1409
+ return DraftActionOperationType.Custom;
1410
+ }
1411
+ }
1412
+ function toQueueState(queue) {
1413
+ return (states) => {
1414
+ return {
1415
+ queueState: queue.getQueueState(),
1416
+ items: states,
1417
+ };
1418
+ };
1419
+ }
1420
+ class DraftManager {
1421
+ constructor(draftQueue) {
1422
+ this.listeners = [];
1423
+ this.draftQueue = draftQueue;
1424
+ draftQueue.registerOnChangedListener((event) => {
1425
+ if (this.shouldEmitDraftEvent(event)) {
1426
+ return this.callListeners(event);
1427
+ }
1428
+ return Promise.resolve();
1429
+ });
1430
+ }
1431
+ shouldEmitDraftEvent(event) {
1432
+ const { type } = event;
1433
+ return [
1434
+ DraftQueueEventType.ActionAdded,
1435
+ DraftQueueEventType.ActionCompleted,
1436
+ DraftQueueEventType.ActionDeleted,
1437
+ DraftQueueEventType.ActionFailed,
1438
+ DraftQueueEventType.ActionUpdated,
1439
+ DraftQueueEventType.QueueStateChanged,
1440
+ ].includes(type);
1441
+ }
1442
+ draftQueueEventTypeToOperationType(type) {
1443
+ switch (type) {
1444
+ case DraftQueueEventType.ActionAdded:
1445
+ return DraftQueueOperationType.ItemAdded;
1446
+ case DraftQueueEventType.ActionCompleted:
1447
+ return DraftQueueOperationType.ItemCompleted;
1448
+ case DraftQueueEventType.ActionDeleted:
1449
+ return DraftQueueOperationType.ItemDeleted;
1450
+ case DraftQueueEventType.ActionFailed:
1451
+ return DraftQueueOperationType.ItemFailed;
1452
+ case DraftQueueEventType.ActionUpdated:
1453
+ return DraftQueueOperationType.ItemUpdated;
1454
+ default:
1455
+ throw Error('Unsupported event type');
1456
+ }
1457
+ }
1458
+ draftQueueStateToOperationType(state) {
1459
+ switch (state) {
1460
+ case DraftQueueState.Started:
1461
+ return DraftQueueOperationType.QueueStarted;
1462
+ case DraftQueueState.Stopped:
1463
+ return DraftQueueOperationType.QueueStopped;
1464
+ default:
1465
+ throw Error('Unsupported event type');
1466
+ }
1467
+ }
1468
+ /**
1469
+ * Enqueue a custom action on the DraftQueue for a handler
1470
+ * @param handler the handler's id
1471
+ * @param targetId
1472
+ * @param tag - the key to group with in durable store
1473
+ * @param metadata
1474
+ * @returns
1475
+ */
1476
+ addCustomAction(handler, targetId, tag, metadata) {
1477
+ return this.draftQueue
1478
+ .enqueue(handler, {
1479
+ data: metadata,
1480
+ handler,
1481
+ targetId,
1482
+ tag,
1483
+ })
1484
+ .then((result) => {
1485
+ return this.buildDraftQueueItem(result.action);
1486
+ });
1487
+ }
1488
+ /**
1489
+ * Get the current state of each of the DraftActions in the DraftQueue
1490
+ * @returns A promise of an array of the state of each item in the DraftQueue
1491
+ */
1492
+ getQueue() {
1493
+ return this.draftQueue
1494
+ .getQueueActions()
1495
+ .then((queueActions) => {
1496
+ return queueActions.map(this.buildDraftQueueItem);
1497
+ })
1498
+ .then(toQueueState(this.draftQueue));
1499
+ }
1500
+ /**
1501
+ * Starts the draft queue and begins processing the first item in the queue.
1502
+ */
1503
+ startQueue() {
1504
+ return this.draftQueue.startQueue();
1505
+ }
1506
+ /**
1507
+ * Stops the draft queue from processing more draft items after any current
1508
+ * in progress items are finished.
1509
+ */
1510
+ stopQueue() {
1511
+ return this.draftQueue.stopQueue();
1512
+ }
1513
+ /**
1514
+ * Subscribes the listener to changes to the draft queue.
1515
+ *
1516
+ * Returns a closure to invoke in order to unsubscribe the listener
1517
+ * from changes to the draft queue.
1518
+ *
1519
+ * @param listener The listener closure to subscribe to changes
1520
+ */
1521
+ registerDraftQueueChangedListener(listener) {
1522
+ this.listeners.push(listener);
1523
+ return () => {
1524
+ this.listeners = this.listeners.filter((l) => {
1525
+ return l !== listener;
1526
+ });
1527
+ return Promise.resolve();
1528
+ };
1529
+ }
1530
+ /**
1531
+ * Creates a custom action handler for the given handler
1532
+ * @param handlerId
1533
+ * @param executor
1534
+ * @returns
1535
+ */
1536
+ setCustomActionExecutor(handlerId, executor) {
1537
+ return this.draftQueue
1538
+ .addCustomHandler(handlerId, (action, completed) => {
1539
+ executor(this.buildDraftQueueItem(action), completed);
1540
+ })
1541
+ .then(() => {
1542
+ return () => {
1543
+ this.draftQueue.removeHandler(handlerId);
1544
+ return Promise.resolve();
1545
+ };
1546
+ });
1547
+ }
1548
+ buildDraftQueueItem(action) {
1549
+ const operationType = getOperationTypeFrom(action);
1550
+ const { id, status, timestamp, targetId, metadata } = action;
1551
+ const item = {
1552
+ id,
1553
+ targetId,
1554
+ state: status,
1555
+ timestamp,
1556
+ operationType,
1557
+ metadata,
1558
+ };
1559
+ if (isDraftError(action)) {
1560
+ // We should always return an array, if the body is just a dictionary,
1561
+ // stick it in an array
1562
+ const body = isArray(action.error.body) ? action.error.body : [action.error.body];
1563
+ const bodyString = stringify(body);
1564
+ item.error = {
1565
+ status: action.error.status || 0,
1566
+ ok: action.error.ok || false,
1567
+ headers: action.error.headers || {},
1568
+ statusText: action.error.statusText || '',
1569
+ bodyString,
1570
+ };
1571
+ }
1572
+ return item;
1573
+ }
1574
+ async callListeners(event) {
1575
+ if (this.listeners.length < 1) {
1576
+ return;
1577
+ }
1578
+ const managerState = await this.getQueue();
1579
+ let operationType, item;
1580
+ if (isDraftQueueStateChangeEvent(event)) {
1581
+ operationType = this.draftQueueStateToOperationType(event.state);
1582
+ }
1583
+ else {
1584
+ const { action, type } = event;
1585
+ item = this.buildDraftQueueItem(action);
1586
+ operationType = this.draftQueueEventTypeToOperationType(type);
1587
+ }
1588
+ for (let i = 0, len = this.listeners.length; i < len; i++) {
1589
+ const listener = this.listeners[i];
1590
+ listener(managerState, operationType, item);
1591
+ }
1592
+ }
1593
+ /**
1594
+ * Removes the draft action identified by actionId from the draft queue.
1595
+ *
1596
+ * @param actionId The action identifier
1597
+ *
1598
+ * @returns The current state of the draft queue
1599
+ */
1600
+ removeDraftAction(actionId) {
1601
+ return this.draftQueue.removeDraftAction(actionId).then(() => this.getQueue());
1602
+ }
1603
+ /**
1604
+ * Replaces the resource request of `withAction` for the resource request
1605
+ * of `actionId`. Action ids cannot be equal. Both actions must be acting
1606
+ * on the same target object, and neither can currently be in progress.
1607
+ *
1608
+ * @param actionId The id of the draft action to replace
1609
+ * @param withActionId The id of the draft action that will replace the other
1610
+ */
1611
+ replaceAction(actionId, withActionId) {
1612
+ return this.draftQueue.replaceAction(actionId, withActionId).then((replaced) => {
1613
+ return this.buildDraftQueueItem(replaced);
1614
+ });
1615
+ }
1616
+ /**
1617
+ * Merges two actions into a single target action. The target action maintains
1618
+ * its position in the queue, while the source action is removed from the queue.
1619
+ * Action ids cannot be equal. Both actions must be acting on the same target
1620
+ * object, and neither can currently be in progress.
1621
+ *
1622
+ * @param targetActionId The draft action id of the target action. This action
1623
+ * will be replaced with the merged result.
1624
+ * @param sourceActionId The draft action id to merge onto the target. This
1625
+ * action will be removed after the merge.
1626
+ */
1627
+ mergeActions(targetActionId, sourceActionId) {
1628
+ return this.draftQueue.mergeActions(targetActionId, sourceActionId).then((merged) => {
1629
+ return this.buildDraftQueueItem(merged);
1630
+ });
1631
+ }
1632
+ /**
1633
+ * Sets the metadata object of the specified action to the
1634
+ * provided metadata
1635
+ * @param actionId The id of the action to set the metadata on
1636
+ * @param metadata The metadata to set on the specified action
1637
+ */
1638
+ setMetadata(actionId, metadata) {
1639
+ return this.draftQueue.setMetadata(actionId, metadata).then((updatedAction) => {
1640
+ return this.buildDraftQueueItem(updatedAction);
1641
+ });
1642
+ }
1643
+ }
1644
+
1645
+ function makeEnvironmentDraftAware(luvio, env, durableStore, handlers, draftQueue) {
1646
+ const draftMetadata = {};
1647
+ // in 246 luvio took charge of persisting redirect mappings, this needs to stick around
1648
+ // for a couple of releases to support older environments
1649
+ // setup existing store redirects when bootstrapping the environment
1650
+ (async () => {
1651
+ const mappings = await getDraftIdMappings(durableStore);
1652
+ mappings.forEach((mapping) => {
1653
+ const { draftKey, canonicalKey } = mapping;
1654
+ env.storeRedirect(draftKey, canonicalKey);
1655
+ });
1656
+ await env.storeBroadcast(env.rebuildSnapshot, env.snapshotAvailable);
1657
+ await clearDraftIdSegment(durableStore);
1658
+ })();
1659
+ const handleSuccessResponse = async function (ingestAndBroadcastFunc, getResponseCacheKeysFunc) {
1660
+ const queue = await draftQueue.getQueueActions();
1661
+ if (queue.length === 0) {
1662
+ return env.handleSuccessResponse(ingestAndBroadcastFunc, getResponseCacheKeysFunc);
1663
+ }
1664
+ const cacheKeySet = getResponseCacheKeysFunc();
1665
+ for (const possibleKey of cacheKeySet.keys()) {
1666
+ const key = typeof possibleKey === 'string' ? possibleKey : '';
1667
+ const cacheKey = cacheKeySet.get(key);
1668
+ for (const handler of handlers) {
1669
+ if (cacheKey !== undefined &&
1670
+ handler.canRepresentationContainDraftMetadata(cacheKey.representationName)) {
1671
+ const metadata = await handler.getDraftMetadata(key);
1672
+ if (metadata !== undefined) {
1673
+ // if this key is related to a draft then mark it mergeable so
1674
+ // base environment revives it to staging store before ingestion
1675
+ cacheKey.mergeable = true;
1676
+ const existing = draftMetadata[key];
1677
+ if (existing === undefined) {
1678
+ draftMetadata[key] = { metadata, refCount: 1 };
1679
+ }
1680
+ else {
1681
+ draftMetadata[key] = { metadata, refCount: existing.refCount + 1 };
1682
+ }
1683
+ }
1684
+ break;
1685
+ }
1686
+ }
1687
+ }
1688
+ return env.handleSuccessResponse(ingestAndBroadcastFunc, () => cacheKeySet);
1689
+ };
1690
+ const storePublish = function (key, data) {
1691
+ const draftMetadataForKey = draftMetadata[key];
1692
+ for (const handler of handlers) {
1693
+ if (handler.canHandlePublish(key)) {
1694
+ handler.applyDraftsToIncomingData(key, data, draftMetadataForKey && draftMetadataForKey.metadata, env.storePublish);
1695
+ return;
1696
+ }
1697
+ }
1698
+ if (draftMetadataForKey !== undefined) {
1699
+ // WARNING: this code depends on the fact that RecordRepresentation
1700
+ // fields get published before the root record.
1701
+ if (draftMetadataForKey.refCount === 1) {
1702
+ delete draftMetadata[key];
1703
+ }
1704
+ else {
1705
+ draftMetadataForKey.refCount--;
1706
+ }
1707
+ }
1708
+ // no handler could handle it so publish
1709
+ env.storePublish(key, data);
1710
+ };
1711
+ // note the makeEnvironmentUiApiRecordDraftAware will eventually go away once the adapters become draft aware
1712
+ return create(env, {
1713
+ storePublish: { value: storePublish },
1714
+ handleSuccessResponse: { value: handleSuccessResponse },
1715
+ });
1716
+ }
1717
+
1718
+ export { AbstractResourceRequestActionHandler, CustomActionResultType, DRAFT_ERROR_CODE, DRAFT_ID_MAPPINGS_SEGMENT, DRAFT_SEGMENT, DraftActionOperationType, DraftActionStatus, DraftErrorFetchResponse, DraftFetchResponse, DraftManager, DraftQueueEventType, DraftQueueState, DraftSynthesisError, DurableDraftQueue, DurableDraftStore, ProcessActionResult, buildLuvioOverrideForDraftAdapters, createBadRequestResponse, createDeletedResponse, createDraftSynthesisErrorResponse, createInternalErrorResponse, createNotFoundResponse, createOkResponse, generateUniqueDraftActionId, isDraftSynthesisError, makeEnvironmentDraftAware, transformErrorToDraftSynthesisError };