@sanity/sdk 3.18.0-next.20261201154713 → 3.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { c as cleanupTimer, f as isReleasePerspective, h as isMediaLibraryResource, i as bindActionGlobally, m as isDatasetResource, n as bindActionByResource, o as UPSTREAM_CLOSE_DELAY_MS, p as isCanvasResource, r as bindActionByResourceAndPerspective, s as defineStore, t as createStateSourceAction, u as setCleanupTimeout } from "./createStateSourceAction-Bn0po7Z3.js";
|
|
2
|
-
import { $ as DEFAULT_BASE, C as retryRead, D as DocumentInaccessibleError, E as OutOfSyncError, F as createLoggedInAuthState, G as AuthStateType, H as getDefaultStorage, I as getAuthCode, J as configureLogging$1, K as getAuthLogger, L as getCleanedUrl, M as SUBMISSION_RETRY_BASE_DELAY, N as SUBMISSION_RETRY_MAX_DELAY, O as ACL_RETRY_MAX_DELAY, Q as DEFAULT_API_VERSION, S as retryOnCredentialChange, U as getTokenFromLocation, V as getDefaultLocation, W as resolveRequestTagPrefix, Y as createLogger, _ as toOAuthTokens, a as getClientAuthState, b as buildQuery, c as getLoginUrlState, d as runOAuthTokenRefresh, f as appendResourceIndicator, g as serializeTokens, h as postTokenRequest, i as getAuthState, j as EDIT_BATCH_INTERVAL, k as API_VERSION$8, l as getTokenState, m as getOAuthOptions, o as getCurrentUserState, p as createOAuthClient, s as getIsInDashboardState, t as authStore, u as setAuthToken, v as AuthError, w as retryWithCredential, y as toAuthError } from "./authStore-C9ZFvN7U.js";
|
|
2
|
+
import { $ as DEFAULT_BASE, A as DOCUMENT_STATE_CLEAR_DELAY, C as retryRead, D as DocumentInaccessibleError, E as OutOfSyncError, F as createLoggedInAuthState, G as AuthStateType, H as getDefaultStorage, I as getAuthCode, J as configureLogging$1, K as getAuthLogger, L as getCleanedUrl, M as SUBMISSION_RETRY_BASE_DELAY, N as SUBMISSION_RETRY_MAX_DELAY, O as ACL_RETRY_MAX_DELAY, P as UNVERIFIED_REVISION_RETENTION_TIME, Q as DEFAULT_API_VERSION, S as retryOnCredentialChange, U as getTokenFromLocation, V as getDefaultLocation, W as resolveRequestTagPrefix, Y as createLogger, _ as toOAuthTokens, a as getClientAuthState, b as buildQuery, c as getLoginUrlState, d as runOAuthTokenRefresh, f as appendResourceIndicator, g as serializeTokens, h as postTokenRequest, i as getAuthState, j as EDIT_BATCH_INTERVAL, k as API_VERSION$8, l as getTokenState, m as getOAuthOptions, o as getCurrentUserState, p as createOAuthClient, s as getIsInDashboardState, t as authStore, u as setAuthToken, v as AuthError, w as retryWithCredential, y as toAuthError } from "./authStore-C9ZFvN7U.js";
|
|
3
3
|
import { a as getDashboardMessageBus, h as randomUuid, m as randomId, n as getDashboardOrganizationId, r as getTopicState } from "./topicStore-B3xCclrk.js";
|
|
4
4
|
import { n as isObject, r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
|
|
5
5
|
import { n as getClient, r as getClientState } from "./clientStore-B_AT0A7B.js";
|
|
6
6
|
import { i as definePagedFetcher, n as defineFetcher, r as defineMutation, t as toCommentFieldPath } from "./commentFieldPath-DkiKA0H9.js";
|
|
7
7
|
import { a as compareProjectOrganization, i as projects, n as threadComments, o as observeAppOrganizationId, r as project } from "./buildCommentThreads-Bn8mApZ2.js";
|
|
8
|
-
import { A as
|
|
8
|
+
import { A as checkGrant, D as ActionError, F as processMutations, L as getProjectAccessErrorProjectId, M as preserveNumericOperations, N as getId, O as PermissionActionError, P as patchOperations, S as toPreferenceError, T as setFavorite, _ as setUsersError, b as USERS_STATE_CLEAR_DELAY, c as getActiveReleasesState, d as cancelRequest, f as getUsersKey, g as setUsersData, h as removeSubscription, i as getQueryState, j as createMutationApplier, k as applySingleDocPatch, l as getAllReleasesState, m as parseUsersKey, o as resolveQuery, p as initializeRequest, s as getPerspectiveState, t as CORE_SDK_VERSION, u as addSubscription, v as updateLastLoadMoreRequest, w as favorites, x as PreferenceError, y as PROJECT_API_VERSION } from "./version-CnBDPBaC.js";
|
|
9
9
|
import { ClientError, CorsOriginError } from "@sanity/client";
|
|
10
10
|
import { BehaviorSubject, EMPTY, NEVER, Observable, ReplaySubject, Subject, Subscription, auditTime, catchError, combineLatest, concat, concatMap, debounceTime, defer, distinctUntilChanged, filter, first, firstValueFrom, from, fromEvent, groupBy, map, merge, mergeMap, of, pairwise, partition, race, share, skip, startWith, switchMap, take, takeUntil, tap, throwError, timer, withLatestFrom } from "rxjs";
|
|
11
11
|
import "@sanity/types";
|
|
@@ -14,8 +14,9 @@ import { DocumentId, getDraftId, getPublishedId, getVersionId, isDraftId, isPubl
|
|
|
14
14
|
import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, jsonMatch as jsonMatch$1, slicePath, stringifyPath } from "@sanity/json-match";
|
|
15
15
|
import { SanityEncoder } from "@sanity/mutate";
|
|
16
16
|
import { createDocumentLoaderFromClient } from "@sanity/mutate/_unstable_store";
|
|
17
|
-
import "groq-js";
|
|
17
|
+
import { parse } from "groq-js";
|
|
18
18
|
import { catchError as catchError$1, distinctUntilChanged as distinctUntilChanged$1, map as map$1, mergeMap as mergeMap$1, retry as retry$1, scan, share as share$1, switchMap as switchMap$1 } from "rxjs/operators";
|
|
19
|
+
import { diffValue } from "@sanity/diff-patch";
|
|
19
20
|
import { fromUrl } from "@sanity/bifur-client";
|
|
20
21
|
/**
|
|
21
22
|
* Creates a new Sanity resource instance
|
|
@@ -1758,6 +1759,27 @@ function deleteRelease(handle) {
|
|
|
1758
1759
|
...handle
|
|
1759
1760
|
};
|
|
1760
1761
|
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Returns the full release document ID for the given release name.
|
|
1764
|
+
* e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`
|
|
1765
|
+
* @beta
|
|
1766
|
+
*/
|
|
1767
|
+
function getReleaseDocumentId(releaseId) {
|
|
1768
|
+
return `_.releases.${releaseId}`;
|
|
1769
|
+
}
|
|
1770
|
+
const RELEASE_ACTION_TYPES = /* @__PURE__ */ new Set([
|
|
1771
|
+
"release.create",
|
|
1772
|
+
"release.edit",
|
|
1773
|
+
"release.publish",
|
|
1774
|
+
"release.schedule",
|
|
1775
|
+
"release.unschedule",
|
|
1776
|
+
"release.archive",
|
|
1777
|
+
"release.unarchive",
|
|
1778
|
+
"release.delete"
|
|
1779
|
+
]);
|
|
1780
|
+
function isReleaseAction(action) {
|
|
1781
|
+
return RELEASE_ACTION_TYPES.has(action.type);
|
|
1782
|
+
}
|
|
1761
1783
|
var DeadlineExceededError = class extends OutOfSyncError {
|
|
1762
1784
|
constructor(message, state) {
|
|
1763
1785
|
super(message, state), this.name = "DeadlineExceededError";
|
|
@@ -1877,7 +1899,1183 @@ const listen = ({ state }, documentId) => {
|
|
|
1877
1899
|
...previousRev && { previousRev }
|
|
1878
1900
|
};
|
|
1879
1901
|
}));
|
|
1880
|
-
}
|
|
1902
|
+
};
|
|
1903
|
+
var MultiKeyWeakMap = class MultiKeyWeakMap {
|
|
1904
|
+
#rootMap = /* @__PURE__ */ new WeakMap();
|
|
1905
|
+
static #globalIdCounter = 0;
|
|
1906
|
+
#idCache = /* @__PURE__ */ new WeakMap();
|
|
1907
|
+
/**
|
|
1908
|
+
* Assigns a numeric ID to the key.
|
|
1909
|
+
*/
|
|
1910
|
+
#assignId(key) {
|
|
1911
|
+
let cachedId = this.#idCache.get(key);
|
|
1912
|
+
if (cachedId !== void 0) return cachedId;
|
|
1913
|
+
let id = MultiKeyWeakMap.#globalIdCounter;
|
|
1914
|
+
return this.#idCache.set(key, id), MultiKeyWeakMap.#globalIdCounter++, id;
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* Remove duplicate keys and arrange them in a consistent order
|
|
1918
|
+
* by sorting according to their assigned IDs.
|
|
1919
|
+
*/
|
|
1920
|
+
#arrangeKeys(keys) {
|
|
1921
|
+
let keyed = Array.from(new Set(keys)).map((key) => [this.#assignId(key), key]);
|
|
1922
|
+
return keyed.sort((a, b) => a[0] - b[0]), keyed.map(([, key]) => key);
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Recursively search the nested WeakMap structure for the value.
|
|
1926
|
+
*/
|
|
1927
|
+
#getDeep(keys, map) {
|
|
1928
|
+
if (keys.length === 0) return;
|
|
1929
|
+
let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
|
|
1930
|
+
if (node) return restKeys.length === 0 ? node.value : this.#getDeep(restKeys, node.next);
|
|
1931
|
+
}
|
|
1932
|
+
/**
|
|
1933
|
+
* Recursively create nodes along the key chain until the final key
|
|
1934
|
+
* is reached, then assign the value.
|
|
1935
|
+
*/
|
|
1936
|
+
#setDeep(keys, map, value) {
|
|
1937
|
+
if (keys.length === 0) return;
|
|
1938
|
+
let [firstKey, ...restKeys] = keys, node = map.get(firstKey);
|
|
1939
|
+
node || (node = {
|
|
1940
|
+
value: void 0,
|
|
1941
|
+
next: /* @__PURE__ */ new WeakMap()
|
|
1942
|
+
}, map.set(firstKey, node)), restKeys.length === 0 ? node.value = value : this.#setDeep(restKeys, node.next, value);
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Retrieves the value associated with the array of keys.
|
|
1946
|
+
* The keys are de-duplicated and sorted so that the order does not matter.
|
|
1947
|
+
*/
|
|
1948
|
+
get(keys) {
|
|
1949
|
+
let arrangedKeys = this.#arrangeKeys(keys);
|
|
1950
|
+
return this.#getDeep(arrangedKeys, this.#rootMap);
|
|
1951
|
+
}
|
|
1952
|
+
/**
|
|
1953
|
+
* Associates the value with the given array of keys.
|
|
1954
|
+
*/
|
|
1955
|
+
set(keys, value) {
|
|
1956
|
+
let arrangedKeys = this.#arrangeKeys(keys);
|
|
1957
|
+
this.#setDeep(arrangedKeys, this.#rootMap, value);
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
function createGrantsLookup(datasetAcl) {
|
|
1961
|
+
let filtersByGrant = {
|
|
1962
|
+
create: /* @__PURE__ */ new Set(),
|
|
1963
|
+
history: /* @__PURE__ */ new Set(),
|
|
1964
|
+
read: /* @__PURE__ */ new Set(),
|
|
1965
|
+
update: /* @__PURE__ */ new Set()
|
|
1966
|
+
};
|
|
1967
|
+
for (let entry of datasetAcl) for (let grant of entry.permissions) {
|
|
1968
|
+
let set = filtersByGrant[grant];
|
|
1969
|
+
set && (set.add(entry.filter), filtersByGrant[grant] = set);
|
|
1970
|
+
}
|
|
1971
|
+
return Object.fromEntries(Object.entries(filtersByGrant).map(([grant, filters]) => {
|
|
1972
|
+
let combinedFilter = Array.from(filters).map((i) => `(${i})`).join("||");
|
|
1973
|
+
return combinedFilter ? [grant, parse(`$document {"_": ${combinedFilter}}._`)] : [grant, parse("false")];
|
|
1974
|
+
}));
|
|
1975
|
+
}
|
|
1976
|
+
const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new WeakMap(), nullReplacer = {}, documentsSelector = createSelector([({ state: { documentStates } }) => documentStates, (_context, { actions }) => actions], (documentStates, actions) => {
|
|
1977
|
+
let documentIds = new Set(actions.map((action) => {
|
|
1978
|
+
if (typeof action.documentId != "string") return [];
|
|
1979
|
+
if (action.liveEdit) return [action.documentId];
|
|
1980
|
+
let ids = [getPublishedId(DocumentId(action.documentId)), getDraftId(DocumentId(action.documentId))];
|
|
1981
|
+
return isReleasePerspective(action.perspective) && ids.push(getVersionId(DocumentId(action.documentId), action.perspective.releaseName)), ids;
|
|
1982
|
+
}).flat());
|
|
1983
|
+
throwDocumentError(documentStates, documentIds);
|
|
1984
|
+
let documents = {};
|
|
1985
|
+
for (let documentId of documentIds) {
|
|
1986
|
+
let local = documentStates[documentId]?.local;
|
|
1987
|
+
if (local === void 0) return;
|
|
1988
|
+
documents[documentId] = local;
|
|
1989
|
+
}
|
|
1990
|
+
let keys = Object.values(documents).map((doc) => doc === null ? nullReplacer : doc);
|
|
1991
|
+
return documentsCache.get(keys) || (documentsCache.set(keys, documents), documents);
|
|
1992
|
+
}), memoizedActionsSelector = createSelector([documentsSelector, (_state, { actions }) => actions], (documents, actions) => {
|
|
1993
|
+
if (!documents) return;
|
|
1994
|
+
let nestedCache = actionsCache.get(documents);
|
|
1995
|
+
nestedCache || (nestedCache = /* @__PURE__ */ new Map(), actionsCache.set(documents, nestedCache));
|
|
1996
|
+
let normalizedActions = Array.isArray(actions) ? actions : [actions], actionsKey = JSON.stringify(normalizedActions);
|
|
1997
|
+
return nestedCache.get(actionsKey) || (nestedCache.set(actionsKey, normalizedActions), normalizedActions);
|
|
1998
|
+
}), enNarrowConjunction = new Intl.ListFormat("en", {
|
|
1999
|
+
style: "narrow",
|
|
2000
|
+
type: "conjunction"
|
|
2001
|
+
});
|
|
2002
|
+
function calculatePermissions(...args) {
|
|
2003
|
+
return _calculatePermissions(...args);
|
|
2004
|
+
}
|
|
2005
|
+
const _calculatePermissions = createSelector([
|
|
2006
|
+
({ state: { grants } }) => grants,
|
|
2007
|
+
({ state: { identity } }) => identity,
|
|
2008
|
+
documentsSelector,
|
|
2009
|
+
memoizedActionsSelector
|
|
2010
|
+
], (grants, identity, documents, actions) => {
|
|
2011
|
+
if (!documents || !grants || !actions) return;
|
|
2012
|
+
let timestamp = (/* @__PURE__ */ new Date()).toISOString(), reasons = [];
|
|
2013
|
+
try {
|
|
2014
|
+
processActions({
|
|
2015
|
+
actions,
|
|
2016
|
+
transactionId: randomId(16),
|
|
2017
|
+
working: documents,
|
|
2018
|
+
base: documents,
|
|
2019
|
+
timestamp,
|
|
2020
|
+
grants,
|
|
2021
|
+
identity
|
|
2022
|
+
});
|
|
2023
|
+
} catch (error) {
|
|
2024
|
+
if (error instanceof PermissionActionError) reasons.push({
|
|
2025
|
+
message: error.message,
|
|
2026
|
+
documentId: error.documentId,
|
|
2027
|
+
type: "access"
|
|
2028
|
+
});
|
|
2029
|
+
else if (error instanceof ActionError) reasons.push({
|
|
2030
|
+
message: error.message,
|
|
2031
|
+
documentId: error.documentId,
|
|
2032
|
+
type: "precondition"
|
|
2033
|
+
});
|
|
2034
|
+
else throw error;
|
|
2035
|
+
}
|
|
2036
|
+
for (let action of actions) if (action.type === "document.edit" && !action.patches?.length) {
|
|
2037
|
+
let docId = action.documentId, doc;
|
|
2038
|
+
doc = action.liveEdit ? documents[docId] : isReleasePerspective(action.perspective) ? documents[getVersionId(DocumentId(docId), action.perspective.releaseName)] : documents[getDraftId(DocumentId(docId))] ?? documents[getPublishedId(DocumentId(docId))], doc ? checkGrant(grants.update, doc, identity) || reasons.push({
|
|
2039
|
+
type: "access",
|
|
2040
|
+
message: `You are not allowed to edit the document with ID "${docId}".`,
|
|
2041
|
+
documentId: docId
|
|
2042
|
+
}) : isReleasePerspective(action.perspective) ? reasons.push({
|
|
2043
|
+
type: "precondition",
|
|
2044
|
+
message: `The version document with ID "${docId}" could not be found. Please create it or add it to the release first.`,
|
|
2045
|
+
documentId: docId
|
|
2046
|
+
}) : reasons.push({
|
|
2047
|
+
type: "precondition",
|
|
2048
|
+
message: `The document with ID "${docId}" could not be found. Please check that it exists before editing.`,
|
|
2049
|
+
documentId: docId
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
let allowed = reasons.length === 0;
|
|
2053
|
+
if (allowed) return { allowed };
|
|
2054
|
+
let sortedReasons = reasons.map((reason, index) => ({
|
|
2055
|
+
...reason,
|
|
2056
|
+
index
|
|
2057
|
+
})).sort((a, b) => a.type === b.type ? a.message.localeCompare(b.message, "en-US") : a.type === "access" ? -1 : 1).map(({ index: _index, ...reason }) => reason);
|
|
2058
|
+
return {
|
|
2059
|
+
allowed,
|
|
2060
|
+
reasons: sortedReasons,
|
|
2061
|
+
message: enNarrowConjunction.format(sortedReasons.map((i) => i.message))
|
|
2062
|
+
};
|
|
2063
|
+
});
|
|
2064
|
+
function handleCreate(action, ctx) {
|
|
2065
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
|
|
2066
|
+
if (action.liveEdit) {
|
|
2067
|
+
if (working[documentId]) throw new ActionError({
|
|
2068
|
+
documentId,
|
|
2069
|
+
transactionId,
|
|
2070
|
+
message: "This document already exists."
|
|
2071
|
+
});
|
|
2072
|
+
let newDocBase = {
|
|
2073
|
+
_type: action.documentType,
|
|
2074
|
+
_id: documentId,
|
|
2075
|
+
...action.initialValue
|
|
2076
|
+
}, mutations = [{ create: {
|
|
2077
|
+
_type: action.documentType,
|
|
2078
|
+
_id: documentId,
|
|
2079
|
+
...action.initialValue
|
|
2080
|
+
} }];
|
|
2081
|
+
if (base = processMutations({
|
|
2082
|
+
documents: base,
|
|
2083
|
+
transactionId,
|
|
2084
|
+
mutations: [{ create: newDocBase }],
|
|
2085
|
+
timestamp
|
|
2086
|
+
}), working = processMutations({
|
|
2087
|
+
documents: working,
|
|
2088
|
+
transactionId,
|
|
2089
|
+
mutations,
|
|
2090
|
+
timestamp
|
|
2091
|
+
}), !checkGrant(grants.create, working[documentId], identity)) throw new PermissionActionError({
|
|
2092
|
+
documentId,
|
|
2093
|
+
transactionId,
|
|
2094
|
+
message: `You do not have permission to create document "${documentId}".`
|
|
2095
|
+
});
|
|
2096
|
+
return outgoingMutations.push(...mutations), {
|
|
2097
|
+
base,
|
|
2098
|
+
working
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : void 0, draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
|
|
2102
|
+
if (versionId ? working[versionId] : working[draftId]) {
|
|
2103
|
+
let errorDocType = versionId ? "release version" : "draft";
|
|
2104
|
+
throw new ActionError({
|
|
2105
|
+
documentId,
|
|
2106
|
+
transactionId,
|
|
2107
|
+
message: `A ${errorDocType} of this document already exists. Please use or discard the existing ${errorDocType} before creating a new one.`
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
let newDocBase = {
|
|
2111
|
+
...base[draftId] ?? base[publishedId],
|
|
2112
|
+
_type: action.documentType,
|
|
2113
|
+
_id: versionId ?? draftId,
|
|
2114
|
+
...action.initialValue
|
|
2115
|
+
}, newDocWorking = {
|
|
2116
|
+
...working[draftId] ?? working[publishedId],
|
|
2117
|
+
_type: action.documentType,
|
|
2118
|
+
_id: versionId ?? draftId,
|
|
2119
|
+
...action.initialValue
|
|
2120
|
+
}, mutations = [{ create: newDocWorking }];
|
|
2121
|
+
if (base = processMutations({
|
|
2122
|
+
documents: base,
|
|
2123
|
+
transactionId,
|
|
2124
|
+
mutations: [{ create: newDocBase }],
|
|
2125
|
+
timestamp
|
|
2126
|
+
}), working = processMutations({
|
|
2127
|
+
documents: working,
|
|
2128
|
+
transactionId,
|
|
2129
|
+
mutations,
|
|
2130
|
+
timestamp
|
|
2131
|
+
}), versionId && !checkGrant(grants.create, working[versionId], identity)) throw new PermissionActionError({
|
|
2132
|
+
documentId,
|
|
2133
|
+
transactionId,
|
|
2134
|
+
message: `You do not have permission to create a release version for document "${documentId}".`
|
|
2135
|
+
});
|
|
2136
|
+
if (!versionId && !checkGrant(grants.create, working[draftId], identity)) throw new PermissionActionError({
|
|
2137
|
+
documentId,
|
|
2138
|
+
transactionId,
|
|
2139
|
+
message: `You do not have permission to create a draft for document "${documentId}".`
|
|
2140
|
+
});
|
|
2141
|
+
return outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2142
|
+
actionType: "sanity.action.document.version.create",
|
|
2143
|
+
publishedId,
|
|
2144
|
+
attributes: newDocWorking
|
|
2145
|
+
}), {
|
|
2146
|
+
base,
|
|
2147
|
+
working
|
|
2148
|
+
};
|
|
2149
|
+
}
|
|
2150
|
+
function handleDelete(action, ctx) {
|
|
2151
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = action.documentId;
|
|
2152
|
+
if (isReleasePerspective(action.perspective)) throw new ActionError({
|
|
2153
|
+
documentId,
|
|
2154
|
+
transactionId,
|
|
2155
|
+
message: "Cannot delete a version document. You may want to use the \"unpublish\" or \"discard\" actions instead."
|
|
2156
|
+
});
|
|
2157
|
+
if (action.liveEdit) {
|
|
2158
|
+
if (!working[documentId]) throw new ActionError({
|
|
2159
|
+
documentId,
|
|
2160
|
+
transactionId,
|
|
2161
|
+
message: "The document you are trying to delete does not exist."
|
|
2162
|
+
});
|
|
2163
|
+
if (!checkGrant(grants.update, working[documentId], identity)) throw new PermissionActionError({
|
|
2164
|
+
documentId,
|
|
2165
|
+
transactionId,
|
|
2166
|
+
message: "You do not have permission to delete this document."
|
|
2167
|
+
});
|
|
2168
|
+
let mutations = [{ delete: { id: documentId } }];
|
|
2169
|
+
return base = processMutations({
|
|
2170
|
+
documents: base,
|
|
2171
|
+
transactionId,
|
|
2172
|
+
mutations,
|
|
2173
|
+
timestamp
|
|
2174
|
+
}), working = processMutations({
|
|
2175
|
+
documents: working,
|
|
2176
|
+
transactionId,
|
|
2177
|
+
mutations,
|
|
2178
|
+
timestamp
|
|
2179
|
+
}), outgoingMutations.push(...mutations), {
|
|
2180
|
+
base,
|
|
2181
|
+
working
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
|
|
2185
|
+
if (!working[publishedId]) throw new ActionError({
|
|
2186
|
+
documentId,
|
|
2187
|
+
transactionId,
|
|
2188
|
+
message: working[draftId] ? "Cannot delete a document without a published version." : "The document you are trying to delete does not exist."
|
|
2189
|
+
});
|
|
2190
|
+
let cantDeleteDraft = working[draftId] && !checkGrant(grants.update, working[draftId], identity), cantDeletePublished = working[publishedId] && !checkGrant(grants.update, working[publishedId], identity);
|
|
2191
|
+
if (cantDeleteDraft || cantDeletePublished) throw new PermissionActionError({
|
|
2192
|
+
documentId,
|
|
2193
|
+
transactionId,
|
|
2194
|
+
message: "You do not have permission to delete this document."
|
|
2195
|
+
});
|
|
2196
|
+
let mutations = [{ delete: { id: publishedId } }, { delete: { id: draftId } }], includeDrafts = working[draftId] ? [draftId] : void 0;
|
|
2197
|
+
return base = processMutations({
|
|
2198
|
+
documents: base,
|
|
2199
|
+
transactionId,
|
|
2200
|
+
mutations,
|
|
2201
|
+
timestamp
|
|
2202
|
+
}), working = processMutations({
|
|
2203
|
+
documents: working,
|
|
2204
|
+
transactionId,
|
|
2205
|
+
mutations,
|
|
2206
|
+
timestamp
|
|
2207
|
+
}), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2208
|
+
actionType: "sanity.action.document.delete",
|
|
2209
|
+
publishedId,
|
|
2210
|
+
...includeDrafts ? { includeDrafts } : {}
|
|
2211
|
+
}), {
|
|
2212
|
+
base,
|
|
2213
|
+
working
|
|
2214
|
+
};
|
|
2215
|
+
}
|
|
2216
|
+
function handleDiscard(action, ctx) {
|
|
2217
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
|
|
2218
|
+
if (action.liveEdit) throw new ActionError({
|
|
2219
|
+
documentId,
|
|
2220
|
+
transactionId,
|
|
2221
|
+
message: `Cannot discard changes for liveEdit document "${documentId}". LiveEdit documents do not support drafts.`
|
|
2222
|
+
});
|
|
2223
|
+
let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : getDraftId(DocumentId(documentId)), mutations = [{ delete: { id: versionId } }];
|
|
2224
|
+
if (!working[versionId]) throw new ActionError({
|
|
2225
|
+
documentId,
|
|
2226
|
+
transactionId,
|
|
2227
|
+
message: `There is no draft or version available to discard for document "${documentId}".`
|
|
2228
|
+
});
|
|
2229
|
+
if (!checkGrant(grants.update, working[versionId], identity)) throw new PermissionActionError({
|
|
2230
|
+
documentId,
|
|
2231
|
+
transactionId,
|
|
2232
|
+
message: `You do not have permission to discard changes for document "${documentId}".`
|
|
2233
|
+
});
|
|
2234
|
+
return base = processMutations({
|
|
2235
|
+
documents: base,
|
|
2236
|
+
transactionId,
|
|
2237
|
+
mutations,
|
|
2238
|
+
timestamp
|
|
2239
|
+
}), working = processMutations({
|
|
2240
|
+
documents: working,
|
|
2241
|
+
transactionId,
|
|
2242
|
+
mutations,
|
|
2243
|
+
timestamp
|
|
2244
|
+
}), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2245
|
+
actionType: "sanity.action.document.version.discard",
|
|
2246
|
+
versionId
|
|
2247
|
+
}), {
|
|
2248
|
+
base,
|
|
2249
|
+
working
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
function handleEdit(action, ctx) {
|
|
2253
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
|
|
2254
|
+
if (action.liveEdit) {
|
|
2255
|
+
let result = applySingleDocPatch({
|
|
2256
|
+
base,
|
|
2257
|
+
working,
|
|
2258
|
+
documentId,
|
|
2259
|
+
patches: action.patches,
|
|
2260
|
+
transactionId,
|
|
2261
|
+
timestamp,
|
|
2262
|
+
grants,
|
|
2263
|
+
identity,
|
|
2264
|
+
preserveOperations: action.preserveOperations
|
|
2265
|
+
});
|
|
2266
|
+
return outgoingMutations.push(...result.workingMutations), {
|
|
2267
|
+
base: result.base,
|
|
2268
|
+
working: result.working
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
let versionId = isReleasePerspective(action.perspective) ? getVersionId(DocumentId(documentId), action.perspective.releaseName) : void 0, draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId)), patchDocumentId = isReleasePerspective(action.perspective) ? versionId : draftId, userPatches = action.patches?.map((patch) => ({ patch: {
|
|
2272
|
+
id: patchDocumentId,
|
|
2273
|
+
...patch
|
|
2274
|
+
} }));
|
|
2275
|
+
if (!userPatches?.length) return {
|
|
2276
|
+
base,
|
|
2277
|
+
working
|
|
2278
|
+
};
|
|
2279
|
+
if (isReleasePerspective(action.perspective)) {
|
|
2280
|
+
if (!working[versionId] && !base[versionId]) throw new ActionError({
|
|
2281
|
+
documentId,
|
|
2282
|
+
transactionId,
|
|
2283
|
+
message: "This document does not exist in the release. Please create it or add it to the release first."
|
|
2284
|
+
});
|
|
2285
|
+
} else if (!working[draftId] && !working[publishedId] || !base[draftId] && !base[publishedId]) throw new ActionError({
|
|
2286
|
+
documentId,
|
|
2287
|
+
transactionId,
|
|
2288
|
+
message: "Cannot edit document because it does not exist in draft or published form."
|
|
2289
|
+
});
|
|
2290
|
+
let applyMutations = createMutationApplier({
|
|
2291
|
+
documentId,
|
|
2292
|
+
transactionId,
|
|
2293
|
+
timestamp,
|
|
2294
|
+
preserveOperations: action.preserveOperations
|
|
2295
|
+
}), baseMutations = [];
|
|
2296
|
+
!isReleasePerspective(action.perspective) && !base[draftId] && base[publishedId] && baseMutations.push({ create: {
|
|
2297
|
+
...base[publishedId],
|
|
2298
|
+
_id: draftId
|
|
2299
|
+
} });
|
|
2300
|
+
let baseBefore = base[patchDocumentId] ?? base[publishedId];
|
|
2301
|
+
userPatches && baseMutations.push(...userPatches), base = applyMutations(base, baseMutations, "base");
|
|
2302
|
+
let baseAfter = base[patchDocumentId], patches = action.preserveOperations ? action.patches ?? [] : preserveNumericOperations(baseBefore, action.patches, diffValue(baseBefore, baseAfter)), workingMutations = [];
|
|
2303
|
+
if (!isReleasePerspective(action.perspective) && !working[draftId] && working[publishedId]) {
|
|
2304
|
+
let newDraftFromPublished = {
|
|
2305
|
+
...working[publishedId],
|
|
2306
|
+
_id: draftId
|
|
2307
|
+
};
|
|
2308
|
+
if (!checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
|
|
2309
|
+
documentId,
|
|
2310
|
+
transactionId,
|
|
2311
|
+
message: "You do not have permission to create a draft for editing this document."
|
|
2312
|
+
});
|
|
2313
|
+
workingMutations.push({ create: newDraftFromPublished });
|
|
2314
|
+
}
|
|
2315
|
+
let workingBefore = working[patchDocumentId] ?? working[publishedId];
|
|
2316
|
+
if (!checkGrant(grants.update, workingBefore, identity)) throw new PermissionActionError({
|
|
2317
|
+
documentId,
|
|
2318
|
+
transactionId,
|
|
2319
|
+
message: `You do not have permission to edit document "${documentId}".`
|
|
2320
|
+
});
|
|
2321
|
+
return workingMutations.push(...patches.map((patch) => ({ patch: {
|
|
2322
|
+
id: patchDocumentId,
|
|
2323
|
+
...patch
|
|
2324
|
+
} }))), working = applyMutations(working, workingMutations, "working"), outgoingMutations.push(...workingMutations), outgoingActions.push(...patches.map((patch) => ({
|
|
2325
|
+
actionType: "sanity.action.document.edit",
|
|
2326
|
+
draftId: patchDocumentId,
|
|
2327
|
+
publishedId,
|
|
2328
|
+
patch
|
|
2329
|
+
}))), {
|
|
2330
|
+
base,
|
|
2331
|
+
working
|
|
2332
|
+
};
|
|
2333
|
+
}
|
|
2334
|
+
function handlePublish(action, ctx) {
|
|
2335
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
|
|
2336
|
+
if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
|
|
2337
|
+
documentId,
|
|
2338
|
+
transactionId,
|
|
2339
|
+
message: "Cannot publish this document. Publishing is not supported for liveEdit or version (release) documents."
|
|
2340
|
+
});
|
|
2341
|
+
let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId)), workingDraft = working[draftId], baseDraft = base[draftId];
|
|
2342
|
+
if (!workingDraft || !baseDraft) throw new ActionError({
|
|
2343
|
+
documentId,
|
|
2344
|
+
transactionId,
|
|
2345
|
+
message: `Cannot publish because no draft version was found for document "${documentId}".`
|
|
2346
|
+
});
|
|
2347
|
+
if (!isDeepEqual(workingDraft, baseDraft)) throw new ActionError({
|
|
2348
|
+
documentId,
|
|
2349
|
+
transactionId,
|
|
2350
|
+
message: "Publish aborted: The document has changed elsewhere. Please try again."
|
|
2351
|
+
});
|
|
2352
|
+
let newPublishedFromDraft = {
|
|
2353
|
+
...strengthenOnPublish(workingDraft),
|
|
2354
|
+
_id: publishedId
|
|
2355
|
+
}, mutations = [{ delete: { id: draftId } }, { createOrReplace: newPublishedFromDraft }];
|
|
2356
|
+
if (working[draftId] && !checkGrant(grants.update, working[draftId], identity)) throw new PermissionActionError({
|
|
2357
|
+
documentId,
|
|
2358
|
+
transactionId,
|
|
2359
|
+
message: `Publish failed: You do not have permission to update the draft for "${documentId}".`
|
|
2360
|
+
});
|
|
2361
|
+
if (working[publishedId] && !checkGrant(grants.update, newPublishedFromDraft, identity)) throw new PermissionActionError({
|
|
2362
|
+
documentId,
|
|
2363
|
+
transactionId,
|
|
2364
|
+
message: `Publish failed: You do not have permission to update the published version of "${documentId}".`
|
|
2365
|
+
});
|
|
2366
|
+
if (!working[publishedId] && !checkGrant(grants.create, newPublishedFromDraft, identity)) throw new PermissionActionError({
|
|
2367
|
+
documentId,
|
|
2368
|
+
transactionId,
|
|
2369
|
+
message: `Publish failed: You do not have permission to publish a new version of "${documentId}".`
|
|
2370
|
+
});
|
|
2371
|
+
return base = processMutations({
|
|
2372
|
+
documents: base,
|
|
2373
|
+
transactionId,
|
|
2374
|
+
mutations,
|
|
2375
|
+
timestamp
|
|
2376
|
+
}), working = processMutations({
|
|
2377
|
+
documents: working,
|
|
2378
|
+
transactionId,
|
|
2379
|
+
mutations,
|
|
2380
|
+
timestamp
|
|
2381
|
+
}), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2382
|
+
actionType: "sanity.action.document.publish",
|
|
2383
|
+
draftId,
|
|
2384
|
+
publishedId
|
|
2385
|
+
}), {
|
|
2386
|
+
base,
|
|
2387
|
+
working
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
function strengthenOnPublish(draft) {
|
|
2391
|
+
let isStrengthenReference = (value) => "_strengthenOnPublish" in value;
|
|
2392
|
+
function strengthen(value) {
|
|
2393
|
+
if (typeof value != "object" || !value) return value;
|
|
2394
|
+
if (isStrengthenReference(value)) {
|
|
2395
|
+
let { _strengthenOnPublish, _weak, ...rest } = value;
|
|
2396
|
+
return {
|
|
2397
|
+
...rest,
|
|
2398
|
+
..._strengthenOnPublish.weak && { _weak: !0 }
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, strengthen(v)]));
|
|
2402
|
+
}
|
|
2403
|
+
return strengthen(draft);
|
|
2404
|
+
}
|
|
2405
|
+
function handleReleaseArchive(action, ctx) {
|
|
2406
|
+
let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2407
|
+
if (!existing) throw new ActionError({
|
|
2408
|
+
documentId: releaseDocumentId,
|
|
2409
|
+
transactionId,
|
|
2410
|
+
message: `Cannot archive release "${action.releaseId}" because it does not exist.`
|
|
2411
|
+
});
|
|
2412
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2413
|
+
documentId: releaseDocumentId,
|
|
2414
|
+
transactionId,
|
|
2415
|
+
message: `You do not have permission to archive release "${action.releaseId}".`
|
|
2416
|
+
});
|
|
2417
|
+
return outgoingActions.push({
|
|
2418
|
+
actionType: "sanity.action.release.archive",
|
|
2419
|
+
releaseId: action.releaseId
|
|
2420
|
+
}), {
|
|
2421
|
+
base,
|
|
2422
|
+
working
|
|
2423
|
+
};
|
|
2424
|
+
}
|
|
2425
|
+
function handleReleaseUnarchive(action, ctx) {
|
|
2426
|
+
let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2427
|
+
if (!existing) throw new ActionError({
|
|
2428
|
+
documentId: releaseDocumentId,
|
|
2429
|
+
transactionId,
|
|
2430
|
+
message: `Cannot unarchive release "${action.releaseId}" because it does not exist.`
|
|
2431
|
+
});
|
|
2432
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2433
|
+
documentId: releaseDocumentId,
|
|
2434
|
+
transactionId,
|
|
2435
|
+
message: `You do not have permission to unarchive release "${action.releaseId}".`
|
|
2436
|
+
});
|
|
2437
|
+
return outgoingActions.push({
|
|
2438
|
+
actionType: "sanity.action.release.unarchive",
|
|
2439
|
+
releaseId: action.releaseId
|
|
2440
|
+
}), {
|
|
2441
|
+
base,
|
|
2442
|
+
working
|
|
2443
|
+
};
|
|
2444
|
+
}
|
|
2445
|
+
function handleReleaseCreate(action, ctx) {
|
|
2446
|
+
let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
|
|
2447
|
+
if (working[releaseDocumentId] || base[releaseDocumentId]) throw new ActionError({
|
|
2448
|
+
documentId: releaseDocumentId,
|
|
2449
|
+
transactionId,
|
|
2450
|
+
message: `A release with id "${action.releaseId}" already exists.`
|
|
2451
|
+
});
|
|
2452
|
+
let mutations = [{ create: {
|
|
2453
|
+
_id: releaseDocumentId,
|
|
2454
|
+
_type: "system.release",
|
|
2455
|
+
name: action.releaseId,
|
|
2456
|
+
state: "active",
|
|
2457
|
+
metadata: action.metadata
|
|
2458
|
+
} }];
|
|
2459
|
+
if (base = processMutations({
|
|
2460
|
+
documents: base,
|
|
2461
|
+
transactionId,
|
|
2462
|
+
mutations,
|
|
2463
|
+
timestamp
|
|
2464
|
+
}), working = processMutations({
|
|
2465
|
+
documents: working,
|
|
2466
|
+
transactionId,
|
|
2467
|
+
mutations,
|
|
2468
|
+
timestamp
|
|
2469
|
+
}), !checkGrant(grants.create, working[releaseDocumentId], identity)) throw new PermissionActionError({
|
|
2470
|
+
documentId: releaseDocumentId,
|
|
2471
|
+
transactionId,
|
|
2472
|
+
message: `You do not have permission to create release "${action.releaseId}".`
|
|
2473
|
+
});
|
|
2474
|
+
return outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2475
|
+
actionType: "sanity.action.release.create",
|
|
2476
|
+
releaseId: action.releaseId,
|
|
2477
|
+
metadata: action.metadata
|
|
2478
|
+
}), {
|
|
2479
|
+
base,
|
|
2480
|
+
working
|
|
2481
|
+
};
|
|
2482
|
+
}
|
|
2483
|
+
const DELETABLE_STATES = /* @__PURE__ */ new Set(["archived", "published"]);
|
|
2484
|
+
function handleReleaseDelete(action, ctx) {
|
|
2485
|
+
let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2486
|
+
if (!existing) throw new ActionError({
|
|
2487
|
+
documentId: releaseDocumentId,
|
|
2488
|
+
transactionId,
|
|
2489
|
+
message: `Cannot delete release "${action.releaseId}" because it does not exist.`
|
|
2490
|
+
});
|
|
2491
|
+
let state = existing.state;
|
|
2492
|
+
if (state && typeof state == "string" && !DELETABLE_STATES.has(state)) throw new ActionError({
|
|
2493
|
+
documentId: releaseDocumentId,
|
|
2494
|
+
transactionId,
|
|
2495
|
+
message: `Cannot delete release "${action.releaseId}" while it is "${state}". Archive it first.`
|
|
2496
|
+
});
|
|
2497
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2498
|
+
documentId: releaseDocumentId,
|
|
2499
|
+
transactionId,
|
|
2500
|
+
message: `You do not have permission to delete release "${action.releaseId}".`
|
|
2501
|
+
});
|
|
2502
|
+
let mutations = [{ delete: { id: releaseDocumentId } }];
|
|
2503
|
+
return base = processMutations({
|
|
2504
|
+
documents: base,
|
|
2505
|
+
transactionId,
|
|
2506
|
+
mutations,
|
|
2507
|
+
timestamp
|
|
2508
|
+
}), working = processMutations({
|
|
2509
|
+
documents: working,
|
|
2510
|
+
transactionId,
|
|
2511
|
+
mutations,
|
|
2512
|
+
timestamp
|
|
2513
|
+
}), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2514
|
+
actionType: "sanity.action.release.delete",
|
|
2515
|
+
releaseId: action.releaseId
|
|
2516
|
+
}), {
|
|
2517
|
+
base,
|
|
2518
|
+
working
|
|
2519
|
+
};
|
|
2520
|
+
}
|
|
2521
|
+
function handleReleaseEdit(action, ctx) {
|
|
2522
|
+
let { transactionId, timestamp, grants, outgoingActions, outgoingMutations, identity } = ctx, { base, working } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), result = applySingleDocPatch({
|
|
2523
|
+
base,
|
|
2524
|
+
working,
|
|
2525
|
+
documentId: releaseDocumentId,
|
|
2526
|
+
patches: [action.patch],
|
|
2527
|
+
transactionId,
|
|
2528
|
+
timestamp,
|
|
2529
|
+
grants,
|
|
2530
|
+
identity,
|
|
2531
|
+
notFoundMessage: `Cannot edit release "${action.releaseId}" because it does not exist.`,
|
|
2532
|
+
permissionMessage: `You do not have permission to edit release "${action.releaseId}".`
|
|
2533
|
+
});
|
|
2534
|
+
return outgoingMutations.push(...result.workingMutations), outgoingActions.push(...result.diffedPatches.map((patch) => ({
|
|
2535
|
+
actionType: "sanity.action.release.edit",
|
|
2536
|
+
releaseId: action.releaseId,
|
|
2537
|
+
patch
|
|
2538
|
+
}))), {
|
|
2539
|
+
base: result.base,
|
|
2540
|
+
working: result.working
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
function handleReleasePublish(action, ctx) {
|
|
2544
|
+
let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2545
|
+
if (!existing) throw new ActionError({
|
|
2546
|
+
documentId: releaseDocumentId,
|
|
2547
|
+
transactionId,
|
|
2548
|
+
message: `Cannot publish release "${action.releaseId}" because it does not exist.`
|
|
2549
|
+
});
|
|
2550
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2551
|
+
documentId: releaseDocumentId,
|
|
2552
|
+
transactionId,
|
|
2553
|
+
message: `You do not have permission to publish release "${action.releaseId}".`
|
|
2554
|
+
});
|
|
2555
|
+
return outgoingActions.push({
|
|
2556
|
+
actionType: "sanity.action.release.publish",
|
|
2557
|
+
releaseId: action.releaseId
|
|
2558
|
+
}), {
|
|
2559
|
+
base,
|
|
2560
|
+
working
|
|
2561
|
+
};
|
|
2562
|
+
}
|
|
2563
|
+
function handleReleaseSchedule(action, ctx) {
|
|
2564
|
+
let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId);
|
|
2565
|
+
if (Number.isNaN(Date.parse(action.publishAt))) throw new ActionError({
|
|
2566
|
+
documentId: releaseDocumentId,
|
|
2567
|
+
transactionId,
|
|
2568
|
+
message: `Cannot schedule release "${action.releaseId}": "publishAt" must be a valid ISO 8601 timestamp (received "${action.publishAt}").`
|
|
2569
|
+
});
|
|
2570
|
+
let existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2571
|
+
if (!existing) throw new ActionError({
|
|
2572
|
+
documentId: releaseDocumentId,
|
|
2573
|
+
transactionId,
|
|
2574
|
+
message: `Cannot schedule release "${action.releaseId}" because it does not exist.`
|
|
2575
|
+
});
|
|
2576
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2577
|
+
documentId: releaseDocumentId,
|
|
2578
|
+
transactionId,
|
|
2579
|
+
message: `You do not have permission to schedule release "${action.releaseId}".`
|
|
2580
|
+
});
|
|
2581
|
+
return outgoingActions.push({
|
|
2582
|
+
actionType: "sanity.action.release.schedule",
|
|
2583
|
+
releaseId: action.releaseId,
|
|
2584
|
+
publishAt: action.publishAt
|
|
2585
|
+
}), {
|
|
2586
|
+
base,
|
|
2587
|
+
working
|
|
2588
|
+
};
|
|
2589
|
+
}
|
|
2590
|
+
function handleReleaseUnschedule(action, ctx) {
|
|
2591
|
+
let { base, working, grants, outgoingActions, transactionId, identity } = ctx, releaseDocumentId = getReleaseDocumentId(action.releaseId), existing = working[releaseDocumentId] ?? base[releaseDocumentId];
|
|
2592
|
+
if (!existing) throw new ActionError({
|
|
2593
|
+
documentId: releaseDocumentId,
|
|
2594
|
+
transactionId,
|
|
2595
|
+
message: `Cannot unschedule release "${action.releaseId}" because it does not exist.`
|
|
2596
|
+
});
|
|
2597
|
+
if (!checkGrant(grants.update, existing, identity)) throw new PermissionActionError({
|
|
2598
|
+
documentId: releaseDocumentId,
|
|
2599
|
+
transactionId,
|
|
2600
|
+
message: `You do not have permission to unschedule release "${action.releaseId}".`
|
|
2601
|
+
});
|
|
2602
|
+
return outgoingActions.push({
|
|
2603
|
+
actionType: "sanity.action.release.unschedule",
|
|
2604
|
+
releaseId: action.releaseId
|
|
2605
|
+
}), {
|
|
2606
|
+
base,
|
|
2607
|
+
working
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
function handleUnpublish(action, ctx) {
|
|
2611
|
+
let { transactionId, timestamp, grants, identity, outgoingActions, outgoingMutations } = ctx, { base, working } = ctx, documentId = getId(action.documentId);
|
|
2612
|
+
if (action.liveEdit || isReleasePerspective(action.perspective)) throw new ActionError({
|
|
2613
|
+
documentId,
|
|
2614
|
+
transactionId,
|
|
2615
|
+
message: "Cannot unpublish this document. Unpublishing is not supported for liveEdit or version (release) documents."
|
|
2616
|
+
});
|
|
2617
|
+
let draftId = getDraftId(DocumentId(documentId)), publishedId = getPublishedId(DocumentId(documentId));
|
|
2618
|
+
if (!working[publishedId] && !base[publishedId]) throw new ActionError({
|
|
2619
|
+
documentId,
|
|
2620
|
+
transactionId,
|
|
2621
|
+
message: `Cannot unpublish because the document "${documentId}" is not currently published.`
|
|
2622
|
+
});
|
|
2623
|
+
let sourceDoc = working[publishedId] ?? base[publishedId], newDraftFromPublished = {
|
|
2624
|
+
...sourceDoc,
|
|
2625
|
+
_id: draftId
|
|
2626
|
+
}, mutations = [{ delete: { id: publishedId } }, { createIfNotExists: newDraftFromPublished }];
|
|
2627
|
+
if (!checkGrant(grants.update, sourceDoc, identity)) throw new PermissionActionError({
|
|
2628
|
+
documentId,
|
|
2629
|
+
transactionId,
|
|
2630
|
+
message: `You do not have permission to unpublish the document "${documentId}".`
|
|
2631
|
+
});
|
|
2632
|
+
if (!working[draftId] && !checkGrant(grants.create, newDraftFromPublished, identity)) throw new PermissionActionError({
|
|
2633
|
+
documentId,
|
|
2634
|
+
transactionId,
|
|
2635
|
+
message: `You do not have permission to create a draft from the published version of "${documentId}".`
|
|
2636
|
+
});
|
|
2637
|
+
return base = processMutations({
|
|
2638
|
+
documents: base,
|
|
2639
|
+
transactionId,
|
|
2640
|
+
mutations: [{ delete: { id: publishedId } }, { createIfNotExists: {
|
|
2641
|
+
...base[publishedId] ?? sourceDoc,
|
|
2642
|
+
_id: draftId
|
|
2643
|
+
} }],
|
|
2644
|
+
timestamp
|
|
2645
|
+
}), working = processMutations({
|
|
2646
|
+
documents: working,
|
|
2647
|
+
transactionId,
|
|
2648
|
+
mutations,
|
|
2649
|
+
timestamp
|
|
2650
|
+
}), outgoingMutations.push(...mutations), outgoingActions.push({
|
|
2651
|
+
actionType: "sanity.action.document.unpublish",
|
|
2652
|
+
draftId,
|
|
2653
|
+
publishedId
|
|
2654
|
+
}), {
|
|
2655
|
+
base,
|
|
2656
|
+
working
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
/**
|
|
2660
|
+
* Applies the given set of actions to the working set of documents and converts
|
|
2661
|
+
* high-level actions into lower-level outgoing mutations/actions that respect
|
|
2662
|
+
* the current state of the working documents.
|
|
2663
|
+
*
|
|
2664
|
+
* Supports a "base" and "working" set of documents to allow actions to be
|
|
2665
|
+
* applied on top of a different working set of documents in a 3-way merge
|
|
2666
|
+
*
|
|
2667
|
+
* Actions are applied to the base set of documents first. The difference
|
|
2668
|
+
* between the base before and after is used to create a patch. This patch is
|
|
2669
|
+
* then applied to the working set of documents and is set as the outgoing patch
|
|
2670
|
+
* sent to the server.
|
|
2671
|
+
*/
|
|
2672
|
+
function processActions({ actions, transactionId, working: initialWorking, base: initialBase, timestamp, grants, identity }) {
|
|
2673
|
+
let base = { ...initialBase }, working = { ...initialWorking }, outgoingActions = [], outgoingMutations = [], liveEditAction = actions.find((action) => !isReleaseAction(action) && action.liveEdit), otherAction = actions.find((action) => isReleaseAction(action) || !action.liveEdit);
|
|
2674
|
+
if (liveEditAction && otherAction) throw new ActionError({
|
|
2675
|
+
documentId: liveEditAction.documentId,
|
|
2676
|
+
transactionId,
|
|
2677
|
+
message: "Cannot combine liveEdit document actions with other actions in the same transaction. Submit them as separate transactions."
|
|
2678
|
+
});
|
|
2679
|
+
for (let action of actions) {
|
|
2680
|
+
let result = dispatch(action, {
|
|
2681
|
+
base,
|
|
2682
|
+
working,
|
|
2683
|
+
transactionId,
|
|
2684
|
+
timestamp,
|
|
2685
|
+
grants,
|
|
2686
|
+
identity,
|
|
2687
|
+
outgoingActions,
|
|
2688
|
+
outgoingMutations
|
|
2689
|
+
});
|
|
2690
|
+
base = result.base, working = result.working;
|
|
2691
|
+
}
|
|
2692
|
+
let previousRevs = Object.fromEntries(Object.entries(initialWorking).map(([id, doc]) => [id, doc?._rev]));
|
|
2693
|
+
return {
|
|
2694
|
+
working,
|
|
2695
|
+
outgoingActions,
|
|
2696
|
+
outgoingMutations,
|
|
2697
|
+
previous: initialWorking,
|
|
2698
|
+
previousRevs
|
|
2699
|
+
};
|
|
2700
|
+
}
|
|
2701
|
+
function dispatch(action, ctx) {
|
|
2702
|
+
switch (action.type) {
|
|
2703
|
+
case "document.create": return handleCreate(action, ctx);
|
|
2704
|
+
case "document.delete": return handleDelete(action, ctx);
|
|
2705
|
+
case "document.discard": return handleDiscard(action, ctx);
|
|
2706
|
+
case "document.edit": return handleEdit(action, ctx);
|
|
2707
|
+
case "document.publish": return handlePublish(action, ctx);
|
|
2708
|
+
case "document.unpublish": return handleUnpublish(action, ctx);
|
|
2709
|
+
case "release.create": return handleReleaseCreate(action, ctx);
|
|
2710
|
+
case "release.edit": return handleReleaseEdit(action, ctx);
|
|
2711
|
+
case "release.publish": return handleReleasePublish(action, ctx);
|
|
2712
|
+
case "release.schedule": return handleReleaseSchedule(action, ctx);
|
|
2713
|
+
case "release.unschedule": return handleReleaseUnschedule(action, ctx);
|
|
2714
|
+
case "release.archive": return handleReleaseArchive(action, ctx);
|
|
2715
|
+
case "release.unarchive": return handleReleaseUnarchive(action, ctx);
|
|
2716
|
+
case "release.delete": return handleReleaseDelete(action, ctx);
|
|
2717
|
+
default: throw Error(`Unknown action type: "${action.type}". Please contact support if this issue persists.`);
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
const EMPTY_REVISIONS = {};
|
|
2721
|
+
function queueTransaction(prev, transaction) {
|
|
2722
|
+
let { transactionId, actions } = transaction;
|
|
2723
|
+
return {
|
|
2724
|
+
...getDocumentIdsFromHandleLikes(actions).reduce((acc, id) => addSubscriptionIdToDocument(acc, id, transactionId), prev),
|
|
2725
|
+
queued: [...prev.queued, transaction]
|
|
2726
|
+
};
|
|
2727
|
+
}
|
|
2728
|
+
function removeQueuedTransaction(prev, transactionId) {
|
|
2729
|
+
let transaction = prev.queued.find((t) => t.transactionId === transactionId);
|
|
2730
|
+
return transaction ? {
|
|
2731
|
+
...getDocumentIdsFromHandleLikes(transaction.actions).reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId), prev),
|
|
2732
|
+
queued: prev.queued.filter((t) => transactionId !== t.transactionId)
|
|
2733
|
+
} : prev;
|
|
2734
|
+
}
|
|
2735
|
+
function applyFirstQueuedTransaction(prev) {
|
|
2736
|
+
let queued = prev.queued.at(0);
|
|
2737
|
+
if (!queued || !prev.grants) return prev;
|
|
2738
|
+
let ids = getDocumentIdsFromHandleLikes(queued.actions);
|
|
2739
|
+
if (ids.some((id) => prev.documentStates[id]?.local === void 0)) return prev;
|
|
2740
|
+
let working = ids.reduce((acc, id) => (acc[id] = prev.documentStates[id]?.local, acc), {}), timestamp = (/* @__PURE__ */ new Date()).toISOString(), result = processActions({
|
|
2741
|
+
...queued,
|
|
2742
|
+
working,
|
|
2743
|
+
base: working,
|
|
2744
|
+
timestamp,
|
|
2745
|
+
grants: prev.grants,
|
|
2746
|
+
identity: prev.identity
|
|
2747
|
+
}), applied = {
|
|
2748
|
+
...queued,
|
|
2749
|
+
...result,
|
|
2750
|
+
base: result.previous,
|
|
2751
|
+
timestamp
|
|
2752
|
+
};
|
|
2753
|
+
return {
|
|
2754
|
+
...prev,
|
|
2755
|
+
applied: [...prev.applied, applied],
|
|
2756
|
+
queued: prev.queued.filter((t) => t.transactionId !== queued.transactionId),
|
|
2757
|
+
documentStates: Object.entries(result.working).reduce((acc, [id, next]) => {
|
|
2758
|
+
let prevDoc = acc[id];
|
|
2759
|
+
return prevDoc && (acc[id] = {
|
|
2760
|
+
...prevDoc,
|
|
2761
|
+
local: next
|
|
2762
|
+
}), acc;
|
|
2763
|
+
}, { ...prev.documentStates })
|
|
2764
|
+
};
|
|
2765
|
+
}
|
|
2766
|
+
/** Whether a transaction can be combined with adjacent edits in the submission queue. */
|
|
2767
|
+
function isBatchableTransaction(transaction) {
|
|
2768
|
+
return !transaction.disableBatching && transaction.actions.length === 1 && transaction.actions[0].type === "document.edit";
|
|
2769
|
+
}
|
|
2770
|
+
function batchAppliedTransactions([curr, ...rest]) {
|
|
2771
|
+
if (!curr) return;
|
|
2772
|
+
if (!curr.actions.length) return batchAppliedTransactions(rest);
|
|
2773
|
+
if (!isBatchableTransaction(curr)) return {
|
|
2774
|
+
...curr,
|
|
2775
|
+
disableBatching: !0,
|
|
2776
|
+
batchedTransactionIds: [curr.transactionId]
|
|
2777
|
+
};
|
|
2778
|
+
let [action] = curr.actions, editAction = {
|
|
2779
|
+
...curr,
|
|
2780
|
+
actions: [action],
|
|
2781
|
+
disableBatching: !1,
|
|
2782
|
+
batchedTransactionIds: [curr.transactionId]
|
|
2783
|
+
};
|
|
2784
|
+
if (!rest.length) return editAction;
|
|
2785
|
+
let next = batchAppliedTransactions(rest);
|
|
2786
|
+
if (!next || next.disableBatching) return editAction;
|
|
2787
|
+
let nextFirst = next.actions[0], nextLiveEdit = nextFirst && "liveEdit" in nextFirst ? nextFirst.liveEdit : !1;
|
|
2788
|
+
return !!action.liveEdit == !!nextLiveEdit ? {
|
|
2789
|
+
disableBatching: !1,
|
|
2790
|
+
transactionId: next.transactionId,
|
|
2791
|
+
actions: [action, ...next.actions],
|
|
2792
|
+
outgoingActions: [...curr.outgoingActions, ...next.outgoingActions],
|
|
2793
|
+
batchedTransactionIds: [curr.transactionId, ...next.batchedTransactionIds],
|
|
2794
|
+
outgoingMutations: [...curr.outgoingMutations, ...next.outgoingMutations],
|
|
2795
|
+
working: {
|
|
2796
|
+
...curr.working,
|
|
2797
|
+
...next.working
|
|
2798
|
+
},
|
|
2799
|
+
previousRevs: {
|
|
2800
|
+
...next.previousRevs,
|
|
2801
|
+
...curr.previousRevs
|
|
2802
|
+
},
|
|
2803
|
+
previous: {
|
|
2804
|
+
...next.previous,
|
|
2805
|
+
...curr.previous
|
|
2806
|
+
},
|
|
2807
|
+
base: {
|
|
2808
|
+
...next.base,
|
|
2809
|
+
...curr.base
|
|
2810
|
+
},
|
|
2811
|
+
timestamp: curr.timestamp ?? next.timestamp
|
|
2812
|
+
} : editAction;
|
|
2813
|
+
}
|
|
2814
|
+
function transitionAppliedTransactionsToOutgoing(prev) {
|
|
2815
|
+
if (prev.outgoing) return prev;
|
|
2816
|
+
let transaction = batchAppliedTransactions(prev.applied);
|
|
2817
|
+
if (!transaction) return prev;
|
|
2818
|
+
let { transactionId, previousRevs, working, batchedTransactionIds: consumedTransactions } = transaction, timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
2819
|
+
return {
|
|
2820
|
+
...prev,
|
|
2821
|
+
outgoing: transaction,
|
|
2822
|
+
applied: prev.applied.filter((i) => !consumedTransactions.includes(i.transactionId)),
|
|
2823
|
+
documentStates: Object.entries(previousRevs).reduce((acc, [documentId, previousRev]) => {
|
|
2824
|
+
if (working[documentId]?._rev === previousRev) return acc;
|
|
2825
|
+
let documentState = prev.documentStates[documentId];
|
|
2826
|
+
return documentState && (acc[documentId] = {
|
|
2827
|
+
...documentState,
|
|
2828
|
+
unverifiedRevisions: {
|
|
2829
|
+
...documentState.unverifiedRevisions,
|
|
2830
|
+
[transactionId]: {
|
|
2831
|
+
documentId,
|
|
2832
|
+
previousRev,
|
|
2833
|
+
transactionId,
|
|
2834
|
+
timestamp
|
|
2835
|
+
}
|
|
2836
|
+
},
|
|
2837
|
+
recentOwnTransactionIds: [...(documentState.recentOwnTransactionIds ?? []).slice(-49), transactionId]
|
|
2838
|
+
}), acc;
|
|
2839
|
+
}, { ...prev.documentStates })
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
function cleanupOutgoingTransaction(prev) {
|
|
2843
|
+
let { outgoing } = prev;
|
|
2844
|
+
if (!outgoing) return prev;
|
|
2845
|
+
let next = prev, ids = getDocumentIdsFromHandleLikes(outgoing.actions);
|
|
2846
|
+
for (let transactionId of outgoing.batchedTransactionIds) for (let documentId of ids) next = removeSubscriptionIdFromDocument(next, documentId, transactionId);
|
|
2847
|
+
return {
|
|
2848
|
+
...next,
|
|
2849
|
+
outgoing: void 0,
|
|
2850
|
+
documentStates: evictOrphanedDocumentStates(next.documentStates)
|
|
2851
|
+
};
|
|
2852
|
+
}
|
|
2853
|
+
function revertOutgoingTransaction(prev) {
|
|
2854
|
+
if (!prev.grants) return prev;
|
|
2855
|
+
let base = prev;
|
|
2856
|
+
if (prev.outgoing) {
|
|
2857
|
+
let ids = getDocumentIdsFromHandleLikes(prev.outgoing.actions);
|
|
2858
|
+
for (let transactionId of prev.outgoing.batchedTransactionIds) for (let documentId of ids) base = removeSubscriptionIdFromDocument(base, documentId, transactionId);
|
|
2859
|
+
}
|
|
2860
|
+
let working = Object.fromEntries(Object.entries(base.documentStates).map(([documentId, documentState]) => [documentId, documentState?.remote])), nextApplied = [];
|
|
2861
|
+
for (let t of prev.applied) try {
|
|
2862
|
+
let next = processActions({
|
|
2863
|
+
...t,
|
|
2864
|
+
working,
|
|
2865
|
+
grants: prev.grants,
|
|
2866
|
+
identity: prev.identity
|
|
2867
|
+
});
|
|
2868
|
+
working = next.working, nextApplied.push({
|
|
2869
|
+
...t,
|
|
2870
|
+
...next
|
|
2871
|
+
});
|
|
2872
|
+
} catch (error) {
|
|
2873
|
+
if (error instanceof ActionError) continue;
|
|
2874
|
+
throw error;
|
|
2875
|
+
}
|
|
2876
|
+
return {
|
|
2877
|
+
...base,
|
|
2878
|
+
applied: nextApplied,
|
|
2879
|
+
outgoing: void 0,
|
|
2880
|
+
documentStates: evictOrphanedDocumentStates(Object.fromEntries(Object.entries(base.documentStates).filter((e) => !!e[1]).map(([documentId, documentState]) => {
|
|
2881
|
+
let { unverifiedRevisions = {} } = documentState, next = {
|
|
2882
|
+
...documentState,
|
|
2883
|
+
unverifiedRevisions: prev.outgoing && prev.outgoing.transactionId in unverifiedRevisions ? omitProperty(unverifiedRevisions, prev.outgoing.transactionId) : unverifiedRevisions
|
|
2884
|
+
};
|
|
2885
|
+
return !next.subscriptions.length && isAwaitingOwnEcho(next) ? [documentId, next] : [documentId, {
|
|
2886
|
+
...next,
|
|
2887
|
+
local: documentId in working ? working[documentId] : next.local
|
|
2888
|
+
}];
|
|
2889
|
+
})))
|
|
2890
|
+
};
|
|
2891
|
+
}
|
|
2892
|
+
/**
|
|
2893
|
+
* Extracts the patch operations addressed to the given document from a set of
|
|
2894
|
+
* raw listener mutations, stripping the mutation-level `id` addressing so the
|
|
2895
|
+
* patches are rooted at the document. A transaction can carry mutations for
|
|
2896
|
+
* other documents, so anything not explicitly id-addressed to this document
|
|
2897
|
+
* (including query-addressed patches) is dropped.
|
|
2898
|
+
*/
|
|
2899
|
+
function extractPatchOperations(mutations, documentId) {
|
|
2900
|
+
return mutations ? mutations.flatMap((mutation) => {
|
|
2901
|
+
if (!("patch" in mutation) || !mutation.patch) return [];
|
|
2902
|
+
let { id, ...operations } = mutation.patch;
|
|
2903
|
+
return id === documentId ? [operations] : [];
|
|
2904
|
+
}) : [];
|
|
2905
|
+
}
|
|
2906
|
+
function applyRemoteDocument(prev, { document, documentId, previousRev, revision, timestamp, type, mutations }, events) {
|
|
2907
|
+
if (!prev.grants) return prev;
|
|
2908
|
+
let prevDocState = prev.documentStates[documentId];
|
|
2909
|
+
if (!prevDocState) return prev;
|
|
2910
|
+
let prevUnverifiedRevisions = prevDocState.unverifiedRevisions, revisionToVerify = revision ? prevUnverifiedRevisions?.[revision] : void 0, unverifiedRevisions = prevUnverifiedRevisions ?? EMPTY_REVISIONS;
|
|
2911
|
+
if (revision && revisionToVerify && (unverifiedRevisions = omitProperty(prevUnverifiedRevisions, revision)), type === "mutation" && revision) {
|
|
2912
|
+
let patches = extractPatchOperations(mutations, documentId);
|
|
2913
|
+
if (patches.length) {
|
|
2914
|
+
let isOwnTransaction = !!revisionToVerify || (prevDocState.recentOwnTransactionIds?.includes(revision) ?? !1);
|
|
2915
|
+
events.next({
|
|
2916
|
+
type: "remote-patches",
|
|
2917
|
+
documentId,
|
|
2918
|
+
transactionId: revision,
|
|
2919
|
+
previousRev,
|
|
2920
|
+
timestamp,
|
|
2921
|
+
patches,
|
|
2922
|
+
origin: isOwnTransaction ? "local" : "remote"
|
|
2923
|
+
});
|
|
2924
|
+
}
|
|
2925
|
+
}
|
|
2926
|
+
if (type === "sync" && (unverifiedRevisions = Object.fromEntries(Object.entries(unverifiedRevisions).filter(([, unverifiedRevision]) => unverifiedRevision ? new Date(timestamp).getTime() <= new Date(unverifiedRevision.timestamp).getTime() : !1))), revisionToVerify && revisionToVerify.previousRev === previousRev) {
|
|
2927
|
+
let modifiesDocument = (transaction) => transaction.working[documentId]?._rev !== transaction.previousRevs[documentId], local = !prev.applied.some(modifiesDocument) && (!prev.outgoing || prev.outgoing.transactionId === revision || !modifiesDocument(prev.outgoing)) && !isDeepEqual(prevDocState.local, document) ? document : prevDocState.local;
|
|
2928
|
+
return {
|
|
2929
|
+
...prev,
|
|
2930
|
+
documentStates: evictOrphanedDocumentStates({
|
|
2931
|
+
...prev.documentStates,
|
|
2932
|
+
[documentId]: {
|
|
2933
|
+
...prevDocState,
|
|
2934
|
+
remote: document,
|
|
2935
|
+
remoteRev: revision,
|
|
2936
|
+
local,
|
|
2937
|
+
unverifiedRevisions
|
|
2938
|
+
}
|
|
2939
|
+
})
|
|
2940
|
+
};
|
|
2941
|
+
}
|
|
2942
|
+
let working = {
|
|
2943
|
+
...prev.applied.at(0)?.previous,
|
|
2944
|
+
[documentId]: document
|
|
2945
|
+
}, nextApplied = [];
|
|
2946
|
+
for (let curr of prev.applied) try {
|
|
2947
|
+
let next = processActions({
|
|
2948
|
+
...curr,
|
|
2949
|
+
working,
|
|
2950
|
+
grants: prev.grants,
|
|
2951
|
+
identity: prev.identity
|
|
2952
|
+
});
|
|
2953
|
+
working = next.working, nextApplied.push({
|
|
2954
|
+
...curr,
|
|
2955
|
+
...next
|
|
2956
|
+
});
|
|
2957
|
+
} catch (error) {
|
|
2958
|
+
if (error instanceof ActionError) {
|
|
2959
|
+
events.next({
|
|
2960
|
+
type: "rebase-error",
|
|
2961
|
+
transactionId: error.transactionId,
|
|
2962
|
+
documentId: error.documentId,
|
|
2963
|
+
message: error.message,
|
|
2964
|
+
error
|
|
2965
|
+
});
|
|
2966
|
+
continue;
|
|
2967
|
+
}
|
|
2968
|
+
throw error;
|
|
2969
|
+
}
|
|
2970
|
+
let nextLocal = working[documentId], local = isDeepEqual(prevDocState.local, nextLocal) ? prevDocState.local : nextLocal;
|
|
2971
|
+
return {
|
|
2972
|
+
...prev,
|
|
2973
|
+
applied: nextApplied,
|
|
2974
|
+
documentStates: evictOrphanedDocumentStates({
|
|
2975
|
+
...prev.documentStates,
|
|
2976
|
+
[documentId]: {
|
|
2977
|
+
...prevDocState,
|
|
2978
|
+
remote: document,
|
|
2979
|
+
remoteRev: revision,
|
|
2980
|
+
local,
|
|
2981
|
+
unverifiedRevisions
|
|
2982
|
+
}
|
|
2983
|
+
})
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
2986
|
+
function addSubscriptionIdToDocument(prev, documentId, subscriptionId) {
|
|
2987
|
+
let prevDocState = prev.documentStates?.[documentId], prevSubscriptions = prevDocState?.subscriptions ?? [];
|
|
2988
|
+
return {
|
|
2989
|
+
...prev,
|
|
2990
|
+
documentStates: {
|
|
2991
|
+
...prev.documentStates,
|
|
2992
|
+
[documentId]: {
|
|
2993
|
+
...prevDocState,
|
|
2994
|
+
id: documentId,
|
|
2995
|
+
subscriptions: [...prevSubscriptions, subscriptionId]
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
};
|
|
2999
|
+
}
|
|
3000
|
+
function removeSubscriptionIdFromDocument(prev, documentId, subscriptionId) {
|
|
3001
|
+
let prevDocState = prev.documentStates?.[documentId];
|
|
3002
|
+
if (!prevDocState) return prev;
|
|
3003
|
+
let subscriptions = prevDocState.subscriptions.filter((id) => id !== subscriptionId);
|
|
3004
|
+
return !subscriptions.length && !isAwaitingOwnEcho(prevDocState) ? {
|
|
3005
|
+
...prev,
|
|
3006
|
+
documentStates: omitProperty(prev.documentStates, documentId)
|
|
3007
|
+
} : {
|
|
3008
|
+
...prev,
|
|
3009
|
+
documentStates: {
|
|
3010
|
+
...prev.documentStates,
|
|
3011
|
+
[documentId]: {
|
|
3012
|
+
...prevDocState,
|
|
3013
|
+
subscriptions
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
};
|
|
3017
|
+
}
|
|
3018
|
+
/**
|
|
3019
|
+
* Whether this document still expects the listener echo of one of its own
|
|
3020
|
+
* submitted transactions. That expectation is the only reason a document state
|
|
3021
|
+
* with no subscribers is kept around.
|
|
3022
|
+
*
|
|
3023
|
+
* Revisions stop counting after `UNVERIFIED_REVISION_RETENTION_TIME` because an
|
|
3024
|
+
* echo is not guaranteed to arrive at all: Content Lake records no transaction
|
|
3025
|
+
* when every operation resolves to a no-op (e.g. a keyed path that no longer
|
|
3026
|
+
* exists), while the client bumps `_rev` regardless and so tracks a revision
|
|
3027
|
+
* for it. Without the expiry, such a document (and the listener keyed off its
|
|
3028
|
+
* state) would be pinned for the lifetime of the store.
|
|
3029
|
+
*
|
|
3030
|
+
* `recentOwnTransactionIds` deliberately does not extend the wait: it is capped
|
|
3031
|
+
* rather than drained, so honoring it would keep every edited document alive.
|
|
3032
|
+
*/
|
|
3033
|
+
function isAwaitingOwnEcho(documentState) {
|
|
3034
|
+
let expiresAfter = Date.now() - UNVERIFIED_REVISION_RETENTION_TIME;
|
|
3035
|
+
return Object.values(documentState.unverifiedRevisions ?? {}).some((revision) => !!revision && new Date(revision.timestamp).getTime() > expiresAfter);
|
|
3036
|
+
}
|
|
3037
|
+
/**
|
|
3038
|
+
* Removes every document state that has no subscribers left and no own
|
|
3039
|
+
* transaction still awaiting its echo.
|
|
3040
|
+
*
|
|
3041
|
+
* This is a sweep rather than a decision made where the last subscriber leaves
|
|
3042
|
+
* because `removeSubscriptionIdFromDocument` defers that eviction while an echo
|
|
3043
|
+
* is in flight, and both halves of the condition can change without a
|
|
3044
|
+
* subscriber going anywhere: the echo can verify, be dropped by a sync, be
|
|
3045
|
+
* discarded by a revert, or simply never arrive. Every reducer that can settle
|
|
3046
|
+
* an in-flight transaction sweeps, so the deferred decision is always re-made.
|
|
3047
|
+
*
|
|
3048
|
+
* Note this can evict the very document whose remote event is being processed,
|
|
3049
|
+
* which synchronously unsubscribes that document's listener from inside its own
|
|
3050
|
+
* emission (see `subscribeToSubscriptionsAndListenToDocuments`).
|
|
3051
|
+
*/
|
|
3052
|
+
function evictOrphanedDocumentStates(documentStates) {
|
|
3053
|
+
let next = documentStates;
|
|
3054
|
+
for (let [documentId, documentState] of Object.entries(documentStates)) documentState && (documentState.subscriptions.length || isAwaitingOwnEcho(documentState) || (next = omitProperty(next, documentId)));
|
|
3055
|
+
return next;
|
|
3056
|
+
}
|
|
3057
|
+
function manageSubscriberIds({ state }, handles) {
|
|
3058
|
+
let documentIds = getDocumentIdsFromHandleLikes(handles), subscriptionId = randomId(16);
|
|
3059
|
+
return state.set("addSubscribers", (prev) => documentIds.reduce((acc, id) => addSubscriptionIdToDocument(acc, id, subscriptionId), prev)), () => {
|
|
3060
|
+
setCleanupTimeout(() => {
|
|
3061
|
+
state.set("removeSubscribers", (prev) => documentIds.reduce((acc, id) => removeSubscriptionIdFromDocument(acc, id, subscriptionId), prev));
|
|
3062
|
+
}, DOCUMENT_STATE_CLEAR_DELAY);
|
|
3063
|
+
};
|
|
3064
|
+
}
|
|
3065
|
+
function throwDocumentError(documentStates, documentIds) {
|
|
3066
|
+
for (let documentId of documentIds) {
|
|
3067
|
+
let documentError = documentStates[documentId]?.error;
|
|
3068
|
+
if (documentError) throw documentError;
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
3071
|
+
function getDocumentIdsFromHandleLikes(handles) {
|
|
3072
|
+
return handles.flatMap((handle) => {
|
|
3073
|
+
if ("type" in handle && isReleaseAction(handle)) return [getReleaseDocumentId(handle.releaseId)];
|
|
3074
|
+
let idsForDocument = [];
|
|
3075
|
+
return handle.documentId ? handle.liveEdit ? [handle.documentId] : (isReleasePerspective(handle.perspective) && idsForDocument.push(getVersionId(DocumentId(handle.documentId), handle.perspective.releaseName)), idsForDocument.push(getDraftId(DocumentId(handle.documentId))), idsForDocument.push(getPublishedId(DocumentId(handle.documentId))), idsForDocument) : [];
|
|
3076
|
+
});
|
|
3077
|
+
}
|
|
3078
|
+
const actionMap = {
|
|
1881
3079
|
"document.create": "created",
|
|
1882
3080
|
"document.delete": "deleted",
|
|
1883
3081
|
"document.discard": "discarded",
|