payload 4.0.0-internal.40de3ec → 4.0.0-internal.4cbdd50
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/bin.js +11 -0
- package/dist/admin/fields/Row.d.ts +2 -2
- package/dist/admin/fields/Row.d.ts.map +1 -1
- package/dist/admin/fields/Row.js.map +1 -1
- package/dist/admin/forms/Description.d.ts +2 -2
- package/dist/admin/forms/Description.d.ts.map +1 -1
- package/dist/admin/forms/Description.js.map +1 -1
- package/dist/admin/forms/Field.d.ts +1 -3
- package/dist/admin/forms/Field.d.ts.map +1 -1
- package/dist/admin/forms/Field.js.map +1 -1
- package/dist/admin/types.d.ts +1 -1
- package/dist/admin/types.d.ts.map +1 -1
- package/dist/admin/types.js.map +1 -1
- package/dist/admin/views/document.d.ts +0 -4
- package/dist/admin/views/document.d.ts.map +1 -1
- package/dist/admin/views/document.js.map +1 -1
- package/dist/admin/views/list.d.ts +5 -0
- package/dist/admin/views/list.d.ts.map +1 -1
- package/dist/admin/views/list.js.map +1 -1
- package/dist/auth/baseFields/apiKey.d.ts +10 -2
- package/dist/auth/baseFields/apiKey.d.ts.map +1 -1
- package/dist/auth/baseFields/apiKey.js +35 -24
- package/dist/auth/baseFields/apiKey.js.map +1 -1
- package/dist/auth/getAuthFields.js +2 -2
- package/dist/auth/getAuthFields.js.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.d.ts.map +1 -1
- package/dist/bin/generateImportMap/iterateCollections.js +1 -0
- package/dist/bin/generateImportMap/iterateCollections.js.map +1 -1
- package/dist/bin/generateImportMap/iterateConfig.d.ts.map +1 -1
- package/dist/bin/generateImportMap/iterateConfig.js +12 -0
- package/dist/bin/generateImportMap/iterateConfig.js.map +1 -1
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.d.ts.map +1 -1
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.js +11 -3
- package/dist/bin/generateImportMap/utilities/resolveImportMapFilePath.js.map +1 -1
- package/dist/collections/config/sanitize.d.ts.map +1 -1
- package/dist/collections/config/sanitize.js +1 -11
- package/dist/collections/config/sanitize.js.map +1 -1
- package/dist/collections/config/types.d.ts +1 -0
- package/dist/collections/config/types.d.ts.map +1 -1
- package/dist/collections/config/types.js.map +1 -1
- package/dist/collections/endpoints/create.d.ts.map +1 -1
- package/dist/collections/endpoints/create.js +0 -2
- package/dist/collections/endpoints/create.js.map +1 -1
- package/dist/collections/endpoints/updateByID.d.ts.map +1 -1
- package/dist/collections/endpoints/updateByID.js +1 -2
- package/dist/collections/endpoints/updateByID.js.map +1 -1
- package/dist/collections/operations/count.d.ts.map +1 -1
- package/dist/collections/operations/count.js +1 -0
- package/dist/collections/operations/count.js.map +1 -1
- package/dist/collections/operations/create.d.ts +0 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +14 -6
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/local/update.d.ts +4 -8
- package/dist/collections/operations/local/update.d.ts.map +1 -1
- package/dist/collections/operations/local/update.js +1 -2
- package/dist/collections/operations/local/update.js.map +1 -1
- package/dist/collections/operations/update.d.ts +0 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +8 -4
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.d.ts +0 -1
- package/dist/collections/operations/updateByID.d.ts.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -5
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.d.ts +9 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.d.ts.map +1 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.js +170 -0
- package/dist/collections/operations/utilities/copyDataWithFreshRowIDs.js.map +1 -0
- package/dist/collections/operations/utilities/update.d.ts +1 -2
- package/dist/collections/operations/utilities/update.d.ts.map +1 -1
- package/dist/collections/operations/utilities/update.js +48 -57
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/config/orderable/index.d.ts.map +1 -1
- package/dist/config/orderable/index.js +23 -0
- package/dist/config/orderable/index.js.map +1 -1
- package/dist/config/types.d.ts +14 -17
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js +1 -0
- package/dist/config/types.js.map +1 -1
- package/dist/errors/ValidationError.d.ts +1 -0
- package/dist/errors/ValidationError.d.ts.map +1 -1
- package/dist/errors/ValidationError.js.map +1 -1
- package/dist/exports/migrations.d.ts +5 -13
- package/dist/exports/migrations.d.ts.map +1 -1
- package/dist/exports/migrations.js +5 -13
- package/dist/exports/migrations.js.map +1 -1
- package/dist/exports/shared.d.ts +1 -1
- package/dist/exports/shared.d.ts.map +1 -1
- package/dist/exports/shared.js +1 -1
- package/dist/exports/shared.js.map +1 -1
- package/dist/fields/config/client.d.ts.map +1 -1
- package/dist/fields/config/client.js +10 -3
- package/dist/fields/config/client.js.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
- package/dist/globals/config/sanitize.d.ts.map +1 -1
- package/dist/globals/config/sanitize.js +1 -6
- package/dist/globals/config/sanitize.js.map +1 -1
- package/dist/globals/endpoints/update.d.ts.map +1 -1
- package/dist/globals/endpoints/update.js +0 -2
- package/dist/globals/endpoints/update.js.map +1 -1
- package/dist/globals/operations/local/update.d.ts +4 -6
- package/dist/globals/operations/local/update.d.ts.map +1 -1
- package/dist/globals/operations/local/update.js +1 -2
- package/dist/globals/operations/local/update.js.map +1 -1
- package/dist/globals/operations/update.d.ts +0 -1
- package/dist/globals/operations/update.d.ts.map +1 -1
- package/dist/globals/operations/update.js +52 -58
- package/dist/globals/operations/update.js.map +1 -1
- package/dist/index.bundled.d.ts +123 -107
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/query-presets/config.d.ts.map +1 -1
- package/dist/query-presets/config.js +73 -34
- package/dist/query-presets/config.js.map +1 -1
- package/dist/query-presets/constraints.d.ts.map +1 -1
- package/dist/query-presets/constraints.js +2 -1
- package/dist/query-presets/constraints.js.map +1 -1
- package/dist/utilities/createPayloadRequest.d.ts.map +1 -1
- package/dist/utilities/createPayloadRequest.js +1 -0
- package/dist/utilities/createPayloadRequest.js.map +1 -1
- package/dist/utilities/deepCopyObject.d.ts.map +1 -1
- package/dist/utilities/deepCopyObject.js +8 -0
- package/dist/utilities/deepCopyObject.js.map +1 -1
- package/dist/utilities/getFieldByPath.d.ts.map +1 -1
- package/dist/utilities/getFieldByPath.js.map +1 -1
- package/dist/utilities/getVersionsConfig.js.map +1 -1
- package/dist/utilities/mergeLocalizedData.d.ts +14 -4
- package/dist/utilities/mergeLocalizedData.d.ts.map +1 -1
- package/dist/utilities/mergeLocalizedData.js +49 -34
- package/dist/utilities/mergeLocalizedData.js.map +1 -1
- package/dist/utilities/mergeLocalizedData.spec.js +23 -23
- package/dist/utilities/mergeLocalizedData.spec.js.map +1 -1
- package/dist/utilities/parseParams/index.d.ts +2 -5
- package/dist/utilities/parseParams/index.d.ts.map +1 -1
- package/dist/utilities/parseParams/index.js.map +1 -1
- package/dist/utilities/parseParams/index.spec.js +0 -9
- package/dist/utilities/parseParams/index.spec.js.map +1 -1
- package/dist/utilities/traverseFields.d.ts.map +1 -1
- package/dist/utilities/traverseFields.js.map +1 -1
- package/dist/versions/baseFields.d.ts +1 -2
- package/dist/versions/baseFields.d.ts.map +1 -1
- package/dist/versions/baseFields.js +0 -13
- package/dist/versions/baseFields.js.map +1 -1
- package/dist/versions/buildCollectionFields.d.ts.map +1 -1
- package/dist/versions/buildCollectionFields.js +0 -2
- package/dist/versions/buildCollectionFields.js.map +1 -1
- package/dist/versions/buildGlobalFields.d.ts.map +1 -1
- package/dist/versions/buildGlobalFields.js +0 -2
- package/dist/versions/buildGlobalFields.js.map +1 -1
- package/dist/versions/buildSingleLocalePublishData.d.ts +32 -0
- package/dist/versions/buildSingleLocalePublishData.d.ts.map +1 -0
- package/dist/versions/buildSingleLocalePublishData.js +37 -0
- package/dist/versions/buildSingleLocalePublishData.js.map +1 -0
- package/dist/versions/saveVersion.d.ts +0 -2
- package/dist/versions/saveVersion.d.ts.map +1 -1
- package/dist/versions/saveVersion.js +12 -17
- package/dist/versions/saveVersion.js.map +1 -1
- package/dist/versions/schedule/job.d.ts.map +1 -1
- package/dist/versions/schedule/job.js +2 -9
- package/dist/versions/schedule/job.js.map +1 -1
- package/dist/versions/types.d.ts +2 -15
- package/dist/versions/types.d.ts.map +1 -1
- package/dist/versions/types.js.map +1 -1
- package/package.json +3 -3
- package/dist/database/migrations/templates/localizeStatus.d.ts +0 -10
- package/dist/database/migrations/templates/localizeStatus.d.ts.map +0 -1
- package/dist/database/migrations/templates/localizeStatus.js +0 -54
- package/dist/database/migrations/templates/localizeStatus.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/index.d.ts +0 -12
- package/dist/versions/migrations/localizeStatus/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/index.js +0 -33
- package/dist/versions/migrations/localizeStatus/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/down.d.ts +0 -9
- package/dist/versions/migrations/localizeStatus/mongo/down.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/down.js +0 -112
- package/dist/versions/migrations/localizeStatus/mongo/down.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/index.d.ts +0 -8
- package/dist/versions/migrations/localizeStatus/mongo/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/index.js +0 -8
- package/dist/versions/migrations/localizeStatus/mongo/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/up.d.ts +0 -9
- package/dist/versions/migrations/localizeStatus/mongo/up.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/mongo/up.js +0 -220
- package/dist/versions/migrations/localizeStatus/mongo/up.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/down.d.ts +0 -11
- package/dist/versions/migrations/localizeStatus/sql/down.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/down.js +0 -213
- package/dist/versions/migrations/localizeStatus/sql/down.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/index.d.ts +0 -8
- package/dist/versions/migrations/localizeStatus/sql/index.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/index.js +0 -8
- package/dist/versions/migrations/localizeStatus/sql/index.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.d.ts +0 -13
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js +0 -51
- package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.d.ts +0 -13
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js +0 -54
- package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/up.d.ts +0 -11
- package/dist/versions/migrations/localizeStatus/sql/up.d.ts.map +0 -1
- package/dist/versions/migrations/localizeStatus/sql/up.js +0 -277
- package/dist/versions/migrations/localizeStatus/sql/up.js.map +0 -1
- package/dist/versions/saveSnapshot.d.ts +0 -18
- package/dist/versions/saveSnapshot.d.ts.map +0 -1
- package/dist/versions/saveSnapshot.js +0 -38
- package/dist/versions/saveSnapshot.js.map +0 -1
|
@@ -4,12 +4,12 @@ import { afterChange } from '../../../fields/hooks/afterChange/index.js';
|
|
|
4
4
|
import { afterRead } from '../../../fields/hooks/afterRead/index.js';
|
|
5
5
|
import { beforeChange } from '../../../fields/hooks/beforeChange/index.js';
|
|
6
6
|
import { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js';
|
|
7
|
-
import { deepCopyObjectSimple,
|
|
7
|
+
import { deepCopyObjectSimple, saveVersion } from '../../../index.js';
|
|
8
8
|
import { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js';
|
|
9
9
|
import { uploadFiles } from '../../../uploads/uploadFiles.js';
|
|
10
10
|
import { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js';
|
|
11
11
|
import { hasDraftsEnabled, hasDraftValidationEnabled, hasLocalizeStatusEnabled } from '../../../utilities/getVersionsConfig.js';
|
|
12
|
-
import {
|
|
12
|
+
import { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js';
|
|
13
13
|
/**
|
|
14
14
|
* This function is used to update a document in the DB and return the result.
|
|
15
15
|
*
|
|
@@ -22,9 +22,9 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
22
22
|
* - afterRead - Collection
|
|
23
23
|
* - afterChange - Fields
|
|
24
24
|
* - afterChange - Collection
|
|
25
|
-
*/ export const updateDocument = async ({ id, autosave, collectionConfig, config, data, depth, docWithLocales, draftArg, fallbackLocale, filesToUpload, locale, overrideAccess, overrideLock, payload, populate, publishAllLocales: publishAllLocalesArg,
|
|
25
|
+
*/ export const updateDocument = async ({ id, autosave, collectionConfig, config, data, depth, docWithLocales, draftArg, fallbackLocale, filesToUpload, locale, overrideAccess, overrideLock, payload, populate, publishAllLocales: publishAllLocalesArg, req, select, showHiddenFields, unpublishAllLocales: unpublishAllLocalesArg })=>{
|
|
26
26
|
const password = data?.password;
|
|
27
|
-
const publishAllLocales = !draftArg && (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true));
|
|
27
|
+
const publishAllLocales = !draftArg && (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all' ? false : true));
|
|
28
28
|
const unpublishAllLocales = typeof unpublishAllLocalesArg === 'string' ? unpublishAllLocalesArg === 'true' : !!unpublishAllLocalesArg;
|
|
29
29
|
const isSavingDraft = Boolean(draftArg && hasDraftsEnabled(collectionConfig)) && data._status !== 'published' && !publishAllLocales;
|
|
30
30
|
const shouldSavePassword = Boolean(password && collectionConfig.auth && (!collectionConfig.auth.disableLocalStrategy || typeof collectionConfig.auth.disableLocalStrategy === 'object' && collectionConfig.auth.disableLocalStrategy.enableFields) && !isSavingDraft);
|
|
@@ -160,11 +160,17 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
160
160
|
// Handle Localized Data Merging
|
|
161
161
|
// /////////////////////////////////////
|
|
162
162
|
let result = await beforeChange(beforeChangeArgs);
|
|
163
|
-
|
|
163
|
+
if (config.localization && hasLocalizeStatusEnabled(collectionConfig) && typeof result._status === 'string') {
|
|
164
|
+
const statusStr = result._status;
|
|
165
|
+
result._status = {};
|
|
166
|
+
for (const localeCode of config.localization.localeCodes){
|
|
167
|
+
;
|
|
168
|
+
result._status[localeCode] = statusStr;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
let localizedPublishData = null;
|
|
164
172
|
if (config.localization && collectionConfig.versions) {
|
|
165
|
-
|
|
166
|
-
let currentDoc;
|
|
167
|
-
if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {
|
|
173
|
+
if (hasLocalizeStatusEnabled(collectionConfig)) {
|
|
168
174
|
if (publishAllLocales || unpublishAllLocales) {
|
|
169
175
|
let accessibleLocaleCodes = config.localization.localeCodes;
|
|
170
176
|
if (config.localization.filterAvailableLocales) {
|
|
@@ -180,10 +186,10 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
180
186
|
for (const localeCode of accessibleLocaleCodes){
|
|
181
187
|
result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published';
|
|
182
188
|
}
|
|
183
|
-
} else if (!isSavingDraft) {
|
|
184
|
-
|
|
185
|
-
currentDoc = await payload.db.findOne({
|
|
189
|
+
} else if (!isSavingDraft && result._status && typeof result._status === 'object' && !Array.isArray(result._status) && result._status[locale] === 'published') {
|
|
190
|
+
const currentDoc = await payload.db.findOne({
|
|
186
191
|
collection: collectionConfig.slug,
|
|
192
|
+
locale: 'all',
|
|
187
193
|
req,
|
|
188
194
|
where: {
|
|
189
195
|
id: {
|
|
@@ -191,47 +197,18 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
191
197
|
}
|
|
192
198
|
}
|
|
193
199
|
});
|
|
194
|
-
|
|
200
|
+
localizedPublishData = buildLocalizedPublishData({
|
|
201
|
+
config,
|
|
202
|
+
currentDoc: currentDoc,
|
|
203
|
+
fields: collectionConfig.fields,
|
|
204
|
+
locale,
|
|
205
|
+
result
|
|
206
|
+
});
|
|
195
207
|
}
|
|
196
|
-
} else if (publishSpecificLocale) {
|
|
197
|
-
// previous way of publishing a single locale
|
|
198
|
-
currentDoc = await getLatestCollectionVersion({
|
|
199
|
-
id,
|
|
200
|
-
config: collectionConfig,
|
|
201
|
-
payload,
|
|
202
|
-
published: true,
|
|
203
|
-
query: {
|
|
204
|
-
collection: collectionConfig.slug,
|
|
205
|
-
locale: 'all',
|
|
206
|
-
req,
|
|
207
|
-
where: {
|
|
208
|
-
id: {
|
|
209
|
-
equals: id
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
},
|
|
213
|
-
req
|
|
214
|
-
});
|
|
215
|
-
snapshotData = {
|
|
216
|
-
...result,
|
|
217
|
-
_status: 'draft'
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
if (snapshotData) {
|
|
221
|
-
snapshotToSave = deepCopyObjectSimple(snapshotData || {});
|
|
222
|
-
result = mergeLocalizedData({
|
|
223
|
-
configBlockReferences: config.blocks,
|
|
224
|
-
dataWithLocales: result || {},
|
|
225
|
-
docWithLocales: currentDoc || {},
|
|
226
|
-
fields: collectionConfig.fields,
|
|
227
|
-
selectedLocales: [
|
|
228
|
-
locale
|
|
229
|
-
]
|
|
230
|
-
});
|
|
231
208
|
}
|
|
232
209
|
}
|
|
233
210
|
const dataToUpdate = {
|
|
234
|
-
...result
|
|
211
|
+
...localizedPublishData ?? result
|
|
235
212
|
};
|
|
236
213
|
// /////////////////////////////////////
|
|
237
214
|
// Handle potential password update
|
|
@@ -254,13 +231,29 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
254
231
|
if (!isSavingDraft) {
|
|
255
232
|
// Ensure updatedAt date is always updated
|
|
256
233
|
dataToUpdate.updatedAt = new Date().toISOString();
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
234
|
+
if (localizedPublishData) {
|
|
235
|
+
// Single-locale publish: save filtered data to main doc but keep full locale data for
|
|
236
|
+
// the version so draft fetches (replaceWithDraftIfAvailable) return complete data.
|
|
237
|
+
await req.payload.db.updateOne({
|
|
238
|
+
id,
|
|
239
|
+
collection: collectionConfig.slug,
|
|
240
|
+
data: dataToUpdate,
|
|
241
|
+
locale,
|
|
242
|
+
req
|
|
243
|
+
});
|
|
244
|
+
resultWithLocales = {
|
|
245
|
+
...result,
|
|
246
|
+
updatedAt: dataToUpdate.updatedAt
|
|
247
|
+
};
|
|
248
|
+
} else {
|
|
249
|
+
resultWithLocales = await req.payload.db.updateOne({
|
|
250
|
+
id,
|
|
251
|
+
collection: collectionConfig.slug,
|
|
252
|
+
data: dataToUpdate,
|
|
253
|
+
locale,
|
|
254
|
+
req
|
|
255
|
+
});
|
|
256
|
+
}
|
|
264
257
|
}
|
|
265
258
|
// /////////////////////////////////////
|
|
266
259
|
// Create version
|
|
@@ -274,9 +267,7 @@ import { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js';
|
|
|
274
267
|
draft: isSavingDraft,
|
|
275
268
|
operation: 'update',
|
|
276
269
|
payload,
|
|
277
|
-
publishSpecificLocale,
|
|
278
270
|
req,
|
|
279
|
-
snapshot: snapshotToSave,
|
|
280
271
|
unpublish: unpublishAllLocales
|
|
281
272
|
});
|
|
282
273
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, getLatestCollectionVersion, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { mergeLocalizedData } from '../../../utilities/mergeLocalizedData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n publishSpecificLocale?: string\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n publishSpecificLocale,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ?? (hasLocalizeStatusEnabled(collectionConfig) ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it here would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n if (!isDraftOverPublished) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n // Skip validation for unpublish operations — they only change _status, not document data\n unpublishAllLocales,\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n let snapshotToSave: JsonObject | undefined\n\n if (config.localization && collectionConfig.versions) {\n let snapshotData: JsonObject | undefined\n let currentDoc\n\n if (collectionConfig.versions.drafts && collectionConfig.versions.drafts.localizeStatus) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (!isSavingDraft) {\n // publishing a single locale\n currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n req,\n where: { id: { equals: id } },\n })\n snapshotData = result\n }\n } else if (publishSpecificLocale) {\n // previous way of publishing a single locale\n currentDoc = await getLatestCollectionVersion({\n id,\n config: collectionConfig,\n payload,\n published: true,\n query: {\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n snapshotData = {\n ...result,\n _status: 'draft',\n }\n }\n\n if (snapshotData) {\n snapshotToSave = deepCopyObjectSimple(snapshotData || {})\n\n result = mergeLocalizedData({\n configBlockReferences: config.blocks,\n dataWithLocales: result || {},\n docWithLocales: currentDoc || {},\n fields: collectionConfig.fields,\n selectedLocales: [locale],\n })\n }\n }\n\n const dataToUpdate: JsonObject = { ...result }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n resultWithLocales = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n publishSpecificLocale,\n req,\n snapshot: snapshotToSave,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: resultWithLocales,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","getLatestCollectionVersion","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","mergeLocalizedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","publishSpecificLocale","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","isDraftOverPublished","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","snapshotToSave","localization","versions","snapshotData","currentDoc","drafts","localizeStatus","accessibleLocaleCodes","localeCodes","filterAvailableLocales","filteredLocales","locales","map","code","localeCode","db","findOne","where","equals","published","query","configBlockReferences","blocks","dataWithLocales","fields","selectedLocales","dataToUpdate","hash","salt","resultWithLocales","updatedAt","Date","toISOString","updateOne","snapshot","unpublish","previousDoc"],"mappings":"AAwBA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,0BAA0B,EAAEC,WAAW,QAAQ,oBAAmB;AACjG,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,kBAAkB,QAAQ,2CAA0C;AAyB7E;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,iBAAiB,OAG5B,EACAC,EAAE,EACFC,QAAQ,EACRC,gBAAgB,EAChBC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,cAAc,EACdC,QAAQ,EACRC,cAAc,EACdC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,YAAY,EACZC,OAAO,EACPC,QAAQ,EACRC,mBAAmBC,oBAAoB,EACvCC,qBAAqB,EACrBC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,qBAAqBC,sBAAsB,EACX;IAChC,MAAMC,WAAWnB,MAAMmB;IACvB,MAAMR,oBACJ,CAACR,YACAS,CAAAA,wBAAyBnB,CAAAA,yBAAyBK,oBAAoB,QAAQ,IAAG,CAAC;IACrF,MAAMmB,sBACJ,OAAOC,2BAA2B,WAC9BA,2BAA2B,SAC3B,CAAC,CAACA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/C,KAAK,MAAMC,QAAQ/C,iBAAiB6C,KAAK,CAAC9D,WAAW,CAAE;YACrDsE,SACE,AAAC,MAAMN,KAAK;gBACVd,YAAYjC;gBACZkC,SAASlB,IAAIkB,OAAO;gBACpBhC;gBACAiC,KAAKkB;gBACLZ,WAAW;gBACXhC;gBACAiF,aAAa1D;gBACbhB;YACF,MAAOqC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideAccess: boolean\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n select: SelectType\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n}\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n req,\n select,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const password = data?.password\n const publishAllLocales =\n !draftArg &&\n (publishAllLocalesArg ??\n (hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all' ? false : true))\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n if (isSavingDraft) {\n data._status = 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // /////////////////////////////////////\n // Delete any associated files\n // /////////////////////////////////////\n\n // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it here would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n if (!isDraftOverPublished) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // Write files to local storage\n // /////////////////////////////////////\n\n if (!collectionConfig.upload.disableLocalStorage) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: originalDoc,\n docWithLocales,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n skipValidation:\n // only skip validation for drafts when draft validation is false\n (isSavingDraft && !hasDraftValidationEnabled(collectionConfig)) ||\n // Skip validation for trash operations since they're just metadata updates\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n // Skip validation for unpublish operations — they only change _status, not document data\n unpublishAllLocales,\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let result: JsonObject = await beforeChange(beforeChangeArgs)\n\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n result._status = {}\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\n if (publishAllLocales || unpublishAllLocales) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (\n !isSavingDraft &&\n result._status &&\n typeof result._status === 'object' &&\n !Array.isArray(result._status) &&\n (result._status as Record<string, unknown>)[locale] === 'published'\n ) {\n const currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n })\n\n localizedPublishData = buildLocalizedPublishData({\n config,\n currentDoc: currentDoc as JsonObject,\n fields: collectionConfig.fields,\n locale,\n result,\n })\n }\n }\n }\n\n const dataToUpdate: JsonObject = { ...(localizedPublishData ?? result) }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n if (localizedPublishData) {\n // Single-locale publish: save filtered data to main doc but keep full locale data for\n // the version so draft fetches (replaceWithDraftIfAvailable) return complete data.\n await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n resultWithLocales = { ...result, updatedAt: dataToUpdate.updatedAt }\n } else {\n resultWithLocales = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n req,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: resultWithLocales,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n}\n"],"names":["ensureUsernameOrEmail","generatePasswordSaltHash","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","saveVersion","deleteAssociatedFiles","uploadFiles","checkDocumentLockStatus","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","buildLocalizedPublishData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","req","select","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","password","isSavingDraft","Boolean","_status","shouldSavePassword","auth","disableLocalStrategy","enableFields","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","draft","global","isRestoringDraftFromTrash","deletedAt","authOptions","operation","isDraftOverPublished","files","overrideDelete","hooks","length","hook","upload","disableLocalStorage","beforeChangeArgs","skipValidation","trash","result","localization","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","dataToUpdate","hash","salt","resultWithLocales","updatedAt","Date","toISOString","updateOne","unpublish","previousDoc"],"mappings":"AAwBA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,WAAW,QAAQ,oBAAmB;AACrE,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,yBAAyB,QAAQ,oDAAmD;AAwB7F;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,iBAAiB,OAG5B,EACAC,EAAE,EACFC,QAAQ,EACRC,gBAAgB,EAChBC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,cAAc,EACdC,QAAQ,EACRC,cAAc,EACdC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,YAAY,EACZC,OAAO,EACPC,QAAQ,EACRC,mBAAmBC,oBAAoB,EACvCC,GAAG,EACHC,MAAM,EACNC,gBAAgB,EAChBC,qBAAq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gBACAM;YACF,MAAOqC;QACX;IACF;IAEA,wCAAwC;IACxC,uBAAuB;IACvB,wCAAwC;IAExCA,SAAS,MAAMpE,YAAY;QACzBgD,YAAYhC;QACZiC,SAASlB,IAAIkB,OAAO;QACpB/B;QACAgC,KAAKkB;QACLhB,QAAQ;QACRI,WAAW;QACX0C,aAAanD;QACbhB;IACF;IAEA,wCAAwC;IACxC,2BAA2B;IAC3B,wCAAwC;IAExC,IAAIf,iBAAiB4C,KAAK,EAAE5D,aAAa6D,QAAQ;QAC/C,KAAK,MAAMC,QAAQ9C,iBAAiB4C,KAAK,CAAC5D,WAAW,CAAE;YACrDoE,SACE,AAAC,MAAMN,KAAK;gBACVd,YAAYhC;gBACZiC,SAASlB,IAAIkB,OAAO;gBACpB/B;gBACAgC,KAAKkB;gBACLZ,WAAW;gBACX/B;gBACAyE,aAAanD;gBACbhB;YACF,MAAOqC;QACX;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/orderable/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/config/orderable/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAEnD,OAAO,KAAK,EAA4B,eAAe,EAAE,MAAM,aAAa,CAAA;AAgB5E,eAAO,MAAM,yBAAyB,GACpC,YAAY,gBAAgB,EAC5B,QAAQ,MAAM,EACd,qBAAqB,MAAM,EAAE,EAC7B,6BAA6B,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,kBAuF9D,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,cAAc,EAAE,MAAM,CAAA;IACtB,UAAU,EAAE,MAAM,EAAE,CAAA;IACpB,YAAY,EAAE,SAAS,GAAG,MAAM,CAAA;IAChC,kBAAkB,EAAE,MAAM,CAAA;IAC1B,MAAM,EAAE;QACN,EAAE,EAAE,MAAM,CAAA;QACV,GAAG,EAAE,MAAM,CAAA;KACZ,CAAA;CACF,CAAA;AAED,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,eAAe,EACvB,4BAA4B,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,SAiN7D,CAAA"}
|
|
@@ -4,8 +4,10 @@ import { APIError } from '../../errors/index.js';
|
|
|
4
4
|
import { sanitizeField } from '../../fields/config/sanitize.js';
|
|
5
5
|
import { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js';
|
|
6
6
|
import { commitTransaction } from '../../utilities/commitTransaction.js';
|
|
7
|
+
import { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js';
|
|
7
8
|
import { initTransaction } from '../../utilities/initTransaction.js';
|
|
8
9
|
import { killTransaction } from '../../utilities/killTransaction.js';
|
|
10
|
+
import { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js';
|
|
9
11
|
import { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js';
|
|
10
12
|
import { getJoinScopeContext } from './utils/getJoinScopeContext.js';
|
|
11
13
|
import { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js';
|
|
@@ -255,8 +257,28 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
255
257
|
// Currently N (= docsToMove.length) is always 1. Maybe in the future we will
|
|
256
258
|
// allow dragging and reordering multiple documents at once via the UI.
|
|
257
259
|
const orderValues = newKeyWillBe === 'greater' ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length) : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length);
|
|
260
|
+
const draftsEnabled = hasDraftsEnabled(collection);
|
|
258
261
|
// Update each document with its new order value
|
|
259
262
|
for (const [index, id] of docsToMove.entries()){
|
|
263
|
+
let draft;
|
|
264
|
+
if (draftsEnabled) {
|
|
265
|
+
const latestVersion = await getLatestCollectionVersion({
|
|
266
|
+
id,
|
|
267
|
+
config: collection,
|
|
268
|
+
payload: req.payload,
|
|
269
|
+
query: {
|
|
270
|
+
collection: collection.slug,
|
|
271
|
+
req,
|
|
272
|
+
where: {
|
|
273
|
+
id: {
|
|
274
|
+
equals: id
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
req
|
|
279
|
+
});
|
|
280
|
+
draft = latestVersion?._status === 'draft';
|
|
281
|
+
}
|
|
260
282
|
await req.payload.update({
|
|
261
283
|
id,
|
|
262
284
|
collection: collection.slug,
|
|
@@ -264,6 +286,7 @@ export const addOrderableEndpoint = (config, joinFieldPathsByCollection)=>{
|
|
|
264
286
|
[orderableFieldName]: orderValues[index]
|
|
265
287
|
},
|
|
266
288
|
depth: 0,
|
|
289
|
+
draft,
|
|
267
290
|
req
|
|
268
291
|
});
|
|
269
292
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/orderable/index.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { BeforeChangeHook, CollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { Field, TextField } from '../../fields/config/types.js'\nimport type { Endpoint, PayloadHandler, SanitizedConfig } from '../types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { APIError } from '../../errors/index.js'\nimport { sanitizeField } from '../../fields/config/sanitize.js'\nimport { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js'\nimport { getJoinScopeContext } from './utils/getJoinScopeContext.js'\nimport { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js'\nimport { resolvePendingTargetKey } from './utils/resolvePendingTargetKey.js'\n\nexport const addOrderableFieldsAndHook = async (\n collection: CollectionConfig,\n config: Config,\n orderableFieldNames: string[],\n joinFieldPathsByCollection?: Map<string, Map<string, string>>,\n) => {\n // 1. Add fields\n for (const orderableFieldName of orderableFieldNames) {\n const orderField: TextField = {\n name: orderableFieldName,\n type: 'text',\n admin: {\n disabled: true,\n hidden: true,\n readOnly: true,\n },\n hooks: {\n beforeDuplicate: [\n ({ siblingData }) => {\n delete siblingData[orderableFieldName]\n },\n ],\n },\n index: true,\n }\n\n // Sanitize the field using the standard sanitization logic\n await sanitizeField({\n collectionConfig: collection,\n config,\n existingFieldNames: new Set(),\n field: orderField,\n index: 0,\n isTopLevelField: true,\n joinPath: '',\n parentIndexPath: '',\n parentIsLocalized: false,\n parentSchemaPath: '',\n requireFieldLevelRichTextEditor: false,\n validRelationships: null,\n })\n\n collection.fields.unshift(orderField)\n }\n\n // 2. Add hook\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.beforeChange) {\n collection.hooks.beforeChange = []\n }\n\n const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => {\n for (const orderableFieldName of orderableFieldNames) {\n if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) {\n const joinScopeWhere = getJoinScopeWhereFromDocData({\n collectionSlug: collection.slug,\n data,\n joinFieldPathsByCollection,\n orderableFieldName,\n originalDoc,\n })\n\n const lastDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n\n const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null\n data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)\n }\n }\n\n return data\n }\n\n collection.hooks.beforeChange.push(orderBeforeChangeHook)\n}\n\n/**\n * The body of the reorder endpoint.\n * @internal\n */\nexport type OrderableEndpointBody = {\n collectionSlug: string\n docsToMove: string[]\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: string\n }\n}\n\nexport const addOrderableEndpoint = (\n config: SanitizedConfig,\n joinFieldPathsByCollection: Map<string, Map<string, string>>,\n) => {\n // 3. Add endpoint\n const reorderHandler: PayloadHandler = async (req) => {\n const body = (await req.json?.()) as OrderableEndpointBody\n\n const { collectionSlug, docsToMove, newKeyWillBe, orderableFieldName, target } = body\n\n if (!Array.isArray(docsToMove) || docsToMove.length === 0) {\n return new Response(JSON.stringify({ error: 'docsToMove must be a non-empty array' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (newKeyWillBe !== 'greater' && newKeyWillBe !== 'less') {\n return new Response(JSON.stringify({ error: 'newKeyWillBe must be \"greater\" or \"less\"' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n const collection = config.collections.find((c) => c.slug === collectionSlug)\n if (!collection) {\n return new Response(JSON.stringify({ error: `Collection ${collectionSlug} not found` }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (typeof orderableFieldName !== 'string') {\n return new Response(JSON.stringify({ error: 'orderableFieldName must be a string' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const { joinScopeWhere, targetDoc } = await getJoinScopeContext({\n collectionSlug: collection.slug,\n joinFieldPathsByCollection,\n orderableFieldName,\n req,\n target,\n })\n\n // Prevent reordering if user doesn't have editing permissions\n if (collection.access?.update) {\n await executeAccess(\n {\n // Currently only one doc can be moved at a time. We should review this if we want to allow\n // multiple docs to be moved at once in the future.\n id: docsToMove[0],\n data: {},\n req,\n },\n collection.access.update,\n )\n }\n /**\n * If there is no target.key, we can assume the user enabled `orderable`\n * on a collection with existing documents, and that this is the first\n * time they tried to reorder them. Therefore, we perform a one-time\n * migration by setting the key value for all documents. We do this\n * instead of enforcing `required` and `unique` at the database schema\n * level, so that users don't have to run a migration when they enable\n * `orderable` on a collection with existing documents.\n */\n if (!target.key) {\n const { docs } = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 0,\n req,\n select: { [orderableFieldName]: true },\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n await initTransaction(req)\n // We cannot update all documents in a single operation with `payload.update`,\n // because they would all end up with the same order key (`a0`).\n try {\n for (const doc of docs) {\n await req.payload.update({\n id: doc.id,\n collection: collection.slug,\n data: {\n // no data needed since the order hooks will handle this\n },\n depth: 0,\n req,\n })\n await commitTransaction(req)\n }\n } catch (e) {\n await killTransaction(req)\n if (e instanceof Error) {\n throw new APIError(e.message, httpStatus.INTERNAL_SERVER_ERROR)\n }\n }\n\n return new Response(JSON.stringify({ message: 'initial migration', success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n if (\n typeof target !== 'object' ||\n typeof target.id === 'undefined' ||\n typeof target.key !== 'string'\n ) {\n return new Response(JSON.stringify({ error: 'target must be an object with id' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const targetId = target.id\n const targetKey = await resolvePendingTargetKey({\n collectionSlug: collection.slug,\n orderableFieldName,\n req,\n targetDoc,\n targetID: targetId,\n targetKey: target.key,\n })\n\n // The reason the endpoint does not receive this docId as an argument is that there\n // are situations where the user may not see or know what the next or previous one is. For\n // example, access control restrictions, if docBefore is the last one on the page, etc.\n const adjacentDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n select: { [orderableFieldName]: true },\n sort: newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: targetKey,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n const adjacentDocKey = adjacentDoc.docs?.[0]?.[orderableFieldName] || null\n\n // Currently N (= docsToMove.length) is always 1. Maybe in the future we will\n // allow dragging and reordering multiple documents at once via the UI.\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length)\n\n // Update each document with its new order value\n for (const [index, id] of docsToMove.entries()) {\n await req.payload.update({\n id,\n collection: collection.slug,\n data: {\n [orderableFieldName]: orderValues[index],\n },\n depth: 0,\n req,\n })\n }\n\n return new Response(JSON.stringify({ orderValues, success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n const reorderEndpoint: Endpoint = {\n handler: reorderHandler,\n method: 'post',\n path: '/reorder',\n }\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n config.endpoints.push(reorderEndpoint)\n}\n"],"names":["status","httpStatus","executeAccess","APIError","sanitizeField","combineWhereConstraints","commitTransaction","initTransaction","killTransaction","generateKeyBetween","generateNKeysBetween","getJoinScopeContext","getJoinScopeWhereFromDocData","resolvePendingTargetKey","addOrderableFieldsAndHook","collection","config","orderableFieldNames","joinFieldPathsByCollection","orderableFieldName","orderField","name","type","admin","disabled","hidden","readOnly","hooks","beforeDuplicate","siblingData","index","collectionConfig","existingFieldNames","Set","field","isTopLevelField","joinPath","parentIndexPath","parentIsLocalized","parentSchemaPath","requireFieldLevelRichTextEditor","validRelationships","fields","unshift","beforeChange","orderBeforeChangeHook","data","originalDoc","req","joinScopeWhere","collectionSlug","slug","lastDoc","payload","find","depth","limit","pagination","select","sort","where","exists","undefined","lastOrderValue","docs","push","addOrderableEndpoint","reorderHandler","body","json","docsToMove","newKeyWillBe","target","Array","isArray","length","Response","JSON","stringify","error","headers","collections","c","targetDoc","access","update","id","key","doc","e","Error","message","INTERNAL_SERVER_ERROR","success","targetId","targetKey","targetID","adjacentDoc","adjacentDocKey","orderValues","entries","reorderEndpoint","handler","method","path","endpoints"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAOlD,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,aAAa,QAAQ,kCAAiC;AAC/D,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,2BAA0B;AACnF,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,uBAAuB,QAAQ,qCAAoC;AAE5E,OAAO,MAAMC,4BAA4B,OACvCC,YACAC,QACAC,qBACAC;IAEA,gBAAgB;IAChB,KAAK,MAAMC,sBAAsBF,oBAAqB;QACpD,MAAMG,aAAwB;YAC5BC,MAAMF;YACNG,MAAM;YACNC,OAAO;gBACLC,UAAU;gBACVC,QAAQ;gBACRC,UAAU;YACZ;YACAC,OAAO;gBACLC,iBAAiB;oBACf,CAAC,EAAEC,WAAW,EAAE;wBACd,OAAOA,WAAW,CAACV,mBAAmB;oBACxC;iBACD;YACH;YACAW,OAAO;QACT;QAEA,2DAA2D;QAC3D,MAAM1B,cAAc;YAClB2B,kBAAkBhB;YAClBC;YACAgB,oBAAoB,IAAIC;YACxBC,OAAOd;YACPU,OAAO;YACPK,iBAAiB;YACjBC,UAAU;YACVC,iBAAiB;YACjBC,mBAAmB;YACnBC,kBAAkB;YAClBC,iCAAiC;YACjCC,oBAAoB;QACtB;QAEA1B,WAAW2B,MAA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YACF;QACF;QAEA,OAAO,IAAI4B,SAASC,KAAKC,SAAS,CAAC;YAAEqB;YAAaN,SAAS;QAAK,IAAI;YAClEb,SAAS;gBAAE,gBAAgB;YAAmB;YAC9ChF,QAAQ;QACV;IACF;IAEA,MAAMqG,kBAA4B;QAChCC,SAASnC;QACToC,QAAQ;QACRC,MAAM;IACR;IAEA,IAAI,CAACxF,OAAOyF,SAAS,EAAE;QACrBzF,OAAOyF,SAAS,GAAG,EAAE;IACvB;IAEAzF,OAAOyF,SAAS,CAACxC,IAAI,CAACoC;AACxB,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/config/orderable/index.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { BeforeChangeHook, CollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { Field, TextField } from '../../fields/config/types.js'\nimport type { Endpoint, PayloadHandler, SanitizedConfig } from '../types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { APIError } from '../../errors/index.js'\nimport { sanitizeField } from '../../fields/config/sanitize.js'\nimport { combineWhereConstraints } from '../../utilities/combineWhereConstraints.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { getLatestCollectionVersion } from '../../versions/getLatestCollectionVersion.js'\nimport { generateKeyBetween, generateNKeysBetween } from './fractional-indexing.js'\nimport { getJoinScopeContext } from './utils/getJoinScopeContext.js'\nimport { getJoinScopeWhereFromDocData } from './utils/getJoinScopeWhereFromDocData.js'\nimport { resolvePendingTargetKey } from './utils/resolvePendingTargetKey.js'\n\nexport const addOrderableFieldsAndHook = async (\n collection: CollectionConfig,\n config: Config,\n orderableFieldNames: string[],\n joinFieldPathsByCollection?: Map<string, Map<string, string>>,\n) => {\n // 1. Add fields\n for (const orderableFieldName of orderableFieldNames) {\n const orderField: TextField = {\n name: orderableFieldName,\n type: 'text',\n admin: {\n disabled: true,\n hidden: true,\n readOnly: true,\n },\n hooks: {\n beforeDuplicate: [\n ({ siblingData }) => {\n delete siblingData[orderableFieldName]\n },\n ],\n },\n index: true,\n }\n\n // Sanitize the field using the standard sanitization logic\n await sanitizeField({\n collectionConfig: collection,\n config,\n existingFieldNames: new Set(),\n field: orderField,\n index: 0,\n isTopLevelField: true,\n joinPath: '',\n parentIndexPath: '',\n parentIsLocalized: false,\n parentSchemaPath: '',\n requireFieldLevelRichTextEditor: false,\n validRelationships: null,\n })\n\n collection.fields.unshift(orderField)\n }\n\n // 2. Add hook\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.beforeChange) {\n collection.hooks.beforeChange = []\n }\n\n const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => {\n for (const orderableFieldName of orderableFieldNames) {\n if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) {\n const joinScopeWhere = getJoinScopeWhereFromDocData({\n collectionSlug: collection.slug,\n data,\n joinFieldPathsByCollection,\n orderableFieldName,\n originalDoc,\n })\n\n const lastDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n req,\n select: { [orderableFieldName]: true },\n sort: `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: true,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n\n const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null\n data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)\n }\n }\n\n return data\n }\n\n collection.hooks.beforeChange.push(orderBeforeChangeHook)\n}\n\n/**\n * The body of the reorder endpoint.\n * @internal\n */\nexport type OrderableEndpointBody = {\n collectionSlug: string\n docsToMove: string[]\n newKeyWillBe: 'greater' | 'less'\n orderableFieldName: string\n target: {\n id: string\n key: string\n }\n}\n\nexport const addOrderableEndpoint = (\n config: SanitizedConfig,\n joinFieldPathsByCollection: Map<string, Map<string, string>>,\n) => {\n // 3. Add endpoint\n const reorderHandler: PayloadHandler = async (req) => {\n const body = (await req.json?.()) as OrderableEndpointBody\n\n const { collectionSlug, docsToMove, newKeyWillBe, orderableFieldName, target } = body\n\n if (!Array.isArray(docsToMove) || docsToMove.length === 0) {\n return new Response(JSON.stringify({ error: 'docsToMove must be a non-empty array' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (newKeyWillBe !== 'greater' && newKeyWillBe !== 'less') {\n return new Response(JSON.stringify({ error: 'newKeyWillBe must be \"greater\" or \"less\"' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n const collection = config.collections.find((c) => c.slug === collectionSlug)\n if (!collection) {\n return new Response(JSON.stringify({ error: `Collection ${collectionSlug} not found` }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n if (typeof orderableFieldName !== 'string') {\n return new Response(JSON.stringify({ error: 'orderableFieldName must be a string' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const { joinScopeWhere, targetDoc } = await getJoinScopeContext({\n collectionSlug: collection.slug,\n joinFieldPathsByCollection,\n orderableFieldName,\n req,\n target,\n })\n\n // Prevent reordering if user doesn't have editing permissions\n if (collection.access?.update) {\n await executeAccess(\n {\n // Currently only one doc can be moved at a time. We should review this if we want to allow\n // multiple docs to be moved at once in the future.\n id: docsToMove[0],\n data: {},\n req,\n },\n collection.access.update,\n )\n }\n /**\n * If there is no target.key, we can assume the user enabled `orderable`\n * on a collection with existing documents, and that this is the first\n * time they tried to reorder them. Therefore, we perform a one-time\n * migration by setting the key value for all documents. We do this\n * instead of enforcing `required` and `unique` at the database schema\n * level, so that users don't have to run a migration when they enable\n * `orderable` on a collection with existing documents.\n */\n if (!target.key) {\n const { docs } = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 0,\n req,\n select: { [orderableFieldName]: true },\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n exists: false,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n await initTransaction(req)\n // We cannot update all documents in a single operation with `payload.update`,\n // because they would all end up with the same order key (`a0`).\n try {\n for (const doc of docs) {\n await req.payload.update({\n id: doc.id,\n collection: collection.slug,\n data: {\n // no data needed since the order hooks will handle this\n },\n depth: 0,\n req,\n })\n await commitTransaction(req)\n }\n } catch (e) {\n await killTransaction(req)\n if (e instanceof Error) {\n throw new APIError(e.message, httpStatus.INTERNAL_SERVER_ERROR)\n }\n }\n\n return new Response(JSON.stringify({ message: 'initial migration', success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n if (\n typeof target !== 'object' ||\n typeof target.id === 'undefined' ||\n typeof target.key !== 'string'\n ) {\n return new Response(JSON.stringify({ error: 'target must be an object with id' }), {\n headers: { 'Content-Type': 'application/json' },\n status: 400,\n })\n }\n\n const targetId = target.id\n const targetKey = await resolvePendingTargetKey({\n collectionSlug: collection.slug,\n orderableFieldName,\n req,\n targetDoc,\n targetID: targetId,\n targetKey: target.key,\n })\n\n // The reason the endpoint does not receive this docId as an argument is that there\n // are situations where the user may not see or know what the next or previous one is. For\n // example, access control restrictions, if docBefore is the last one on the page, etc.\n const adjacentDoc = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n limit: 1,\n pagination: false,\n select: { [orderableFieldName]: true },\n sort: newKeyWillBe === 'greater' ? orderableFieldName : `-${orderableFieldName}`,\n where: combineWhereConstraints([\n {\n [orderableFieldName]: {\n [newKeyWillBe === 'greater' ? 'greater_than' : 'less_than']: targetKey,\n },\n },\n joinScopeWhere ?? undefined,\n ]),\n })\n const adjacentDocKey = adjacentDoc.docs?.[0]?.[orderableFieldName] || null\n\n // Currently N (= docsToMove.length) is always 1. Maybe in the future we will\n // allow dragging and reordering multiple documents at once via the UI.\n const orderValues =\n newKeyWillBe === 'greater'\n ? generateNKeysBetween(targetKey, adjacentDocKey, docsToMove.length)\n : generateNKeysBetween(adjacentDocKey, targetKey, docsToMove.length)\n\n const draftsEnabled = hasDraftsEnabled(collection)\n\n // Update each document with its new order value\n for (const [index, id] of docsToMove.entries()) {\n let draft: boolean | undefined\n\n if (draftsEnabled) {\n const latestVersion = await getLatestCollectionVersion({\n id,\n config: collection,\n payload: req.payload,\n query: {\n collection: collection.slug,\n req,\n where: { id: { equals: id } },\n },\n req,\n })\n\n draft = latestVersion?._status === 'draft'\n }\n\n await req.payload.update({\n id,\n collection: collection.slug,\n data: {\n [orderableFieldName]: orderValues[index],\n },\n depth: 0,\n draft,\n req,\n })\n }\n\n return new Response(JSON.stringify({ orderValues, success: true }), {\n headers: { 'Content-Type': 'application/json' },\n status: 200,\n })\n }\n\n const reorderEndpoint: Endpoint = {\n handler: reorderHandler,\n method: 'post',\n path: '/reorder',\n }\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n config.endpoints.push(reorderEndpoint)\n}\n"],"names":["status","httpStatus","executeAccess","APIError","sanitizeField","combineWhereConstraints","commitTransaction","hasDraftsEnabled","initTransaction","killTransaction","getLatestCollectionVersion","generateKeyBetween","generateNKeysBetween","getJoinScopeContext","getJoinScopeWhereFromDocData","resolvePendingTargetKey","addOrderableFieldsAndHook","collection","config","orderableFieldNames","joinFieldPathsByCollection","orderableFieldName","orderField","name","type","admin","disabled","hidden","readOnly","hooks","beforeDuplicate","siblingData","index","collectionConfig","existingFieldNames","Set","field","isTopLevelField","joinPath","parentIndexPath","parentIsLocalized","parentSchemaPath","requireFieldLevelRichTextEditor","validRelationships","fields","unshift","beforeChange","orderBeforeChangeHook","data","originalDoc","req","joinScopeWhere","collectionSlug","slug","lastDoc","payload","find","depth","limit","pagination","select","sort","where","exists","undefined","lastOrderValue","docs","push","addOrderableEndpoint","reorderHandler","body","json","docsToMove","newKeyWillBe","target","Array","isArray","length","Response","JSON","stringify","error","headers","collections","c","targetDoc","access","update","id","key","doc","e","Error","message","INTERNAL_SERVER_ERROR","success","targetId","targetKey","targetID","adjacentDoc","adjacentDocKey","orderValues","draftsEnabled","entries","draft","latestVersion","query","equals","_status","reorderEndpoint","handler","method","path","endpoints"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAOlD,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,aAAa,QAAQ,kCAAiC;AAC/D,SAASC,uBAAuB,QAAQ,6CAA4C;AACpF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,0BAA0B,QAAQ,+CAA8C;AACzF,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,2BAA0B;AACnF,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,uBAAuB,QAAQ,qCAAoC;AAE5E,OAAO,MAAMC,4BAA4B,OACvCC,YACAC,QACAC,qBACAC;IAEA,gBAAgB;IAChB,KAAK,MAAMC,sBAAsBF,oBAAqB;QACpD,MAAMG,aAAwB;YAC5BC,MAAMF;YACNG,MAAM;YACNC,OAAO;gBACLC,UAAU;gBACVC,QAAQ;gBACRC,UAAU;YACZ;YACAC,OAAO;gBACLC,iBAAiB;oBACf,CAAC,EAAEC,WAAW,EAAE;wBACd,OAAOA,WAAW,CAACV,mBAAmB;oBACxC;iBACD;YACH;YACAW,OAAO;QACT;QAEA,2DAA2D;QAC3D,MAAM5B,cAAc;YAClB6B,kBAAkBhB;YAClBC;YACAgB,oBAAoB,IAAIC;YACxBC,OAAOd;YACPU,OAAO;YACPK,iBAAiB;YACjBC,UAAU;YACVC,iBAAiB;YACjBC,mBAAmB;YACnBC,kBAAkB;YAClBC,iCAAiC;YACjCC,oBAAoB;QACtB;QAEA1B,WAAW2B,MAAM,CAACC,OAAO,CAACvB;IAC5B;IAEA,cAAc;IACd,IAAI,CAACL,WAAWY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I;gCAAEmB,QAAQnB;4BAAG;wBAAE;oBAC9B;oBACAtC;gBACF;gBAEAsD,QAAQC,eAAeG,YAAY;YACrC;YAEA,MAAM1D,IAAIK,OAAO,CAACgC,MAAM,CAAC;gBACvBC;gBACAvE,YAAYA,WAAWoC,IAAI;gBAC3BL,MAAM;oBACJ,CAAC3B,mBAAmB,EAAEgF,WAAW,CAACrE,MAAM;gBAC1C;gBACAyB,OAAO;gBACP+C;gBACAtD;YACF;QACF;QAEA,OAAO,IAAI4B,SAASC,KAAKC,SAAS,CAAC;YAAEqB;YAAaN,SAAS;QAAK,IAAI;YAClEb,SAAS;gBAAE,gBAAgB;YAAmB;YAC9ClF,QAAQ;QACV;IACF;IAEA,MAAM6G,kBAA4B;QAChCC,SAASzC;QACT0C,QAAQ;QACRC,MAAM;IACR;IAEA,IAAI,CAAC9F,OAAO+F,SAAS,EAAE;QACrB/F,OAAO+F,SAAS,GAAG,EAAE;IACvB;IAEA/F,OAAO+F,SAAS,CAAC9C,IAAI,CAAC0C;AACxB,EAAC"}
|
package/dist/config/types.d.ts
CHANGED
|
@@ -393,6 +393,12 @@ type SanitizedTimezoneConfig = {
|
|
|
393
393
|
supportedTimezones: Timezone[];
|
|
394
394
|
} & Omit<TimezonesConfig, 'supportedTimezones'>;
|
|
395
395
|
export type CustomComponent<TAdditionalProps extends object = Record<string, any>> = PayloadComponent<ServerProps & TAdditionalProps, TAdditionalProps>;
|
|
396
|
+
export type UserMenuSettingsGroup = {
|
|
397
|
+
group: LabelFunction | StaticLabel;
|
|
398
|
+
items: CustomComponent[];
|
|
399
|
+
};
|
|
400
|
+
export type UserMenuSettingsItem = CustomComponent | UserMenuSettingsGroup;
|
|
401
|
+
export declare const isUserMenuSettingsGroup: (userMenuSettingsItem: UserMenuSettingsItem) => userMenuSettingsItem is UserMenuSettingsGroup;
|
|
396
402
|
export type Locale = {
|
|
397
403
|
/**
|
|
398
404
|
* value of supported locale
|
|
@@ -812,6 +818,12 @@ export type Config = {
|
|
|
812
818
|
/** Extensible tab system */
|
|
813
819
|
tabs?: SidebarTab[];
|
|
814
820
|
};
|
|
821
|
+
/**
|
|
822
|
+
* Add custom items to the user menu popup in the admin panel header.
|
|
823
|
+
* These components will be rendered in the Settings sub-popup of the user menu.
|
|
824
|
+
* When empty or absent, the Settings sub-trigger is not shown.
|
|
825
|
+
*/
|
|
826
|
+
userMenuSettingsItems?: UserMenuSettingsItem[];
|
|
815
827
|
/**
|
|
816
828
|
* Replace or modify top-level admin routes, or add new ones:
|
|
817
829
|
* + `Account` - `/admin/account`
|
|
@@ -1036,22 +1048,6 @@ export type Config = {
|
|
|
1036
1048
|
email?: EmailAdapter | Promise<EmailAdapter>;
|
|
1037
1049
|
/** Custom REST endpoints */
|
|
1038
1050
|
endpoints?: Endpoint[];
|
|
1039
|
-
/**
|
|
1040
|
-
* Experimental features may be unstable or change in future versions.
|
|
1041
|
-
*/
|
|
1042
|
-
experimental?: {
|
|
1043
|
-
/**
|
|
1044
|
-
* Enable per-locale status for documents.
|
|
1045
|
-
*
|
|
1046
|
-
* Requires:
|
|
1047
|
-
* - `localization` enabled
|
|
1048
|
-
* - `versions.drafts` enabled
|
|
1049
|
-
* - `versions.drafts.localizeStatus` set at collection or global level
|
|
1050
|
-
*
|
|
1051
|
-
* @experimental
|
|
1052
|
-
*/
|
|
1053
|
-
localizeStatus?: boolean;
|
|
1054
|
-
};
|
|
1055
1051
|
/**
|
|
1056
1052
|
* @see https://payloadcms.com/docs/configuration/globals#global-configs
|
|
1057
1053
|
*/
|
|
@@ -1545,6 +1541,7 @@ export type SharedEntityViews = {
|
|
|
1545
1541
|
[key: string]: {
|
|
1546
1542
|
actions?: CustomComponent[];
|
|
1547
1543
|
Component?: PayloadComponent;
|
|
1544
|
+
NoResults?: CustomComponent;
|
|
1548
1545
|
} | AdminViewConfig | EditConfig | undefined;
|
|
1549
1546
|
/**
|
|
1550
1547
|
* Replace, modify, or add new "document" views.
|
|
@@ -1569,7 +1566,7 @@ export type SharedAdminComponents = {
|
|
|
1569
1566
|
views?: SharedEntityViews;
|
|
1570
1567
|
};
|
|
1571
1568
|
export type EntityDescriptionFunction = ({ t }: {
|
|
1572
|
-
t: TFunction
|
|
1569
|
+
t: TFunction<ClientTranslationKeys>;
|
|
1573
1570
|
}) => string;
|
|
1574
1571
|
export type EntityDescription = EntityDescriptionFunction | Record<string, string> | string;
|
|
1575
1572
|
export type { EmailAdapter, SendEmailOptions };
|