payload 4.0.0-beta.11 → 4.0.0-beta.12
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/admin/forms/Form.d.ts +0 -7
- package/dist/admin/forms/Form.d.ts.map +1 -1
- package/dist/admin/forms/Form.js.map +1 -1
- package/dist/collections/operations/count.d.ts.map +1 -1
- package/dist/collections/operations/count.js +3 -1
- package/dist/collections/operations/count.js.map +1 -1
- package/dist/collections/operations/countVersions.d.ts.map +1 -1
- package/dist/collections/operations/countVersions.js +3 -1
- package/dist/collections/operations/countVersions.js.map +1 -1
- package/dist/collections/operations/delete.d.ts.map +1 -1
- package/dist/collections/operations/delete.js +9 -7
- package/dist/collections/operations/delete.js.map +1 -1
- package/dist/collections/operations/find.d.ts.map +1 -1
- package/dist/collections/operations/find.js +9 -15
- package/dist/collections/operations/find.js.map +1 -1
- package/dist/collections/operations/findDistinct.d.ts.map +1 -1
- package/dist/collections/operations/findDistinct.js +3 -1
- package/dist/collections/operations/findDistinct.js.map +1 -1
- package/dist/collections/operations/findVersions.d.ts.map +1 -1
- package/dist/collections/operations/findVersions.js +10 -8
- package/dist/collections/operations/findVersions.js.map +1 -1
- package/dist/collections/operations/renameFile.d.ts.map +1 -1
- package/dist/collections/operations/renameFile.js +16 -9
- package/dist/collections/operations/renameFile.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +9 -15
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/database/cloneWhere.d.ts +10 -0
- package/dist/database/cloneWhere.d.ts.map +1 -0
- package/dist/database/cloneWhere.js +31 -0
- package/dist/database/cloneWhere.js.map +1 -0
- package/dist/database/nestedRelationshipReadConstraint.d.ts +20 -0
- package/dist/database/nestedRelationshipReadConstraint.d.ts.map +1 -0
- package/dist/database/nestedRelationshipReadConstraint.js +33 -0
- package/dist/database/nestedRelationshipReadConstraint.js.map +1 -0
- package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSearchParams.js +36 -1
- package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
- package/dist/database/queryValidation/validateSortQuery.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSortQuery.js +4 -2
- package/dist/database/queryValidation/validateSortQuery.js.map +1 -1
- package/dist/exports/internal.d.ts +1 -0
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js +1 -0
- package/dist/exports/internal.js.map +1 -1
- package/dist/fields/hooks/beforeChange/index.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/index.js +6 -0
- package/dist/fields/hooks/beforeChange/index.js.map +1 -1
- package/dist/globals/operations/countGlobalVersions.d.ts.map +1 -1
- package/dist/globals/operations/countGlobalVersions.js +3 -1
- package/dist/globals/operations/countGlobalVersions.js.map +1 -1
- package/dist/globals/operations/findVersions.d.ts.map +1 -1
- package/dist/globals/operations/findVersions.js +10 -8
- package/dist/globals/operations/findVersions.js.map +1 -1
- package/dist/index.bundled.d.ts +0 -7
- package/dist/uploads/fileVersioning/archive.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/archive.js +5 -13
- package/dist/uploads/fileVersioning/archive.js.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.js +6 -7
- package/dist/uploads/fileVersioning/cloudStorage.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js +48 -48
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/fileVersioning/restore.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restore.js +7 -9
- package/dist/uploads/fileVersioning/restore.js.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.js +22 -36
- package/dist/uploads/fileVersioning/restoreRequestTime.js.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.d.ts +39 -8
- package/dist/uploads/fileVersioning/storedFiles.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.js +150 -93
- package/dist/uploads/fileVersioning/storedFiles.js.map +1 -1
- package/dist/uploads/fileVersioning/types.d.ts +13 -1
- package/dist/uploads/fileVersioning/types.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/types.js.map +1 -1
- package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
- package/dist/utilities/configToJSONSchema.js +6 -0
- package/dist/utilities/configToJSONSchema.js.map +1 -1
- package/dist/utilities/sanitizeUpdateData.d.ts +5 -0
- package/dist/utilities/sanitizeUpdateData.d.ts.map +1 -0
- package/dist/utilities/sanitizeUpdateData.js +10 -0
- package/dist/utilities/sanitizeUpdateData.js.map +1 -0
- package/package.json +2 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import { executeAccess } from '../../auth/executeAccess.js';
|
|
3
|
+
import { cloneWhere } from '../../database/cloneWhere.js';
|
|
3
4
|
import { combineQueries } from '../../database/combineQueries.js';
|
|
4
5
|
import { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js';
|
|
5
6
|
import { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js';
|
|
@@ -25,7 +26,6 @@ import { killTransaction } from '../../utilities/killTransaction.js';
|
|
|
25
26
|
import { resolveSelect } from '../../utilities/resolveSelect.js';
|
|
26
27
|
import { sanitizeSelect } from '../../utilities/sanitizeSelect.js';
|
|
27
28
|
import { getAllLocalesPublicationStatus, normalizeAllLocalesPublicationStatus, reconcileAllLocalesPublicationStatus, validateAllLocalesPublicationFlags } from '../../versions/allLocalesPublicationStatus.js';
|
|
28
|
-
import { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js';
|
|
29
29
|
import { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js';
|
|
30
30
|
import { getQueryDraftsSort } from '../../versions/drafts/getQueryDraftsSort.js';
|
|
31
31
|
import { buildAfterOperation } from './utilities/buildAfterOperation.js';
|
|
@@ -89,7 +89,8 @@ export const updateOperation = async (incomingArgs)=>{
|
|
|
89
89
|
operation: 'update',
|
|
90
90
|
overrideAccess: args.overrideAccess
|
|
91
91
|
});
|
|
92
|
-
const { autosave = false, collection: { config: collectionConfig }, collection, depth, draft: draftArg = false, limit = 0, overrideAccess, overrideLock, overwriteExistingFiles = false, populate, publishAllLocales: publishAllLocalesArg, req: { fallbackLocale, locale, payload: { config }, payload }, req, select: incomingSelect, showHiddenFields, sort: incomingSort, trash = false, unpublishAllLocales: unpublishAllLocalesArg, where } = args;
|
|
92
|
+
const { autosave = false, collection: { config: collectionConfig }, collection, depth, draft: draftArg = false, limit = 0, overrideAccess, overrideLock, overwriteExistingFiles = false, populate, publishAllLocales: publishAllLocalesArg, req: { fallbackLocale, locale, payload: { config }, payload }, req, select: incomingSelect, showHiddenFields, sort: incomingSort, trash = false, unpublishAllLocales: unpublishAllLocalesArg, where: incomingWhere } = args;
|
|
93
|
+
const where = cloneWhere(incomingWhere);
|
|
93
94
|
if (!where) {
|
|
94
95
|
throw new APIError("Missing 'where' query of documents to update.", httpStatus.BAD_REQUEST);
|
|
95
96
|
}
|
|
@@ -123,12 +124,6 @@ export const updateOperation = async (incomingArgs)=>{
|
|
|
123
124
|
req
|
|
124
125
|
}, collectionConfig.access.update);
|
|
125
126
|
}
|
|
126
|
-
await validateQueryPaths({
|
|
127
|
-
collectionConfig,
|
|
128
|
-
overrideAccess: overrideAccess,
|
|
129
|
-
req,
|
|
130
|
-
where
|
|
131
|
-
});
|
|
132
127
|
// /////////////////////////////////////
|
|
133
128
|
// Retrieve documents
|
|
134
129
|
// /////////////////////////////////////
|
|
@@ -155,6 +150,12 @@ export const updateOperation = async (incomingArgs)=>{
|
|
|
155
150
|
payload,
|
|
156
151
|
where: fullWhere
|
|
157
152
|
});
|
|
153
|
+
await validateQueryPaths({
|
|
154
|
+
collectionConfig,
|
|
155
|
+
overrideAccess: overrideAccess,
|
|
156
|
+
req,
|
|
157
|
+
where
|
|
158
|
+
});
|
|
158
159
|
const sort = sanitizeSortQuery({
|
|
159
160
|
fields: collection.config.flattenedFields,
|
|
160
161
|
sort: incomingSort || collectionConfig.defaultSort
|
|
@@ -168,13 +169,6 @@ export const updateOperation = async (incomingArgs)=>{
|
|
|
168
169
|
let docs;
|
|
169
170
|
if (hasDraftsEnabled(collectionConfig) && (shouldSaveDraft || isTrashAttempt)) {
|
|
170
171
|
const versionsWhere = appendVersionToQueryKey(fullWhere);
|
|
171
|
-
await validateQueryPaths({
|
|
172
|
-
collectionConfig: collection.config,
|
|
173
|
-
overrideAccess: overrideAccess,
|
|
174
|
-
req,
|
|
175
|
-
versionFields: buildVersionCollectionFields(payload.config, collection.config, true),
|
|
176
|
-
where: appendVersionToQueryKey(where)
|
|
177
|
-
});
|
|
178
172
|
const query = await payload.db.queryDrafts({
|
|
179
173
|
collection: collectionConfig.slug,
|
|
180
174
|
limit,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport fs from 'node:fs/promises'\n\nimport type { AccessResult } from '../../config/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type {\n BulkOperationResult,\n Collection,\n DataFromCollectionSlug,\n RequiredDataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { APIError } from '../../errors/index.js'\nimport { type CollectionSlug, type FindOptions } from '../../index.js'\nimport { copyTempFileForDocument } from '../../uploads/copyTempFileForDocument.js'\nimport { createSharedClientUploadDownload } from '../../uploads/createSharedClientUploadDownload.js'\nimport { runCloudFileUpdate } from '../../uploads/fileVersioning/cloudStorage.js'\nimport {\n abortFileOperationScope,\n beginFileOperationScope,\n completeFileOperationScope,\n shareFileOperationScope,\n} from '../../uploads/fileVersioning/fileOperationManager.js'\nimport { withLegacyCloudUploadFileData } from '../../uploads/fileVersioning/storedFiles.js'\nimport { generateFileData } from '../../uploads/generateFileData/index.js'\nimport {\n getLocalizedUploadProperties,\n getUploadDestination,\n mergeUploadDataWithDocument,\n sanitizeUploadData,\n} from '../../uploads/sanitizeUploadData.js'\nimport { unlinkTempFiles } from '../../uploads/unlinkTempFiles.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { hasDraftsEnabled, hasLocalizeStatusEnabled } from '../../utilities/getVersionsConfig.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { isErrorPublic } from '../../utilities/isErrorPublic.js'\nimport { isolateObjectProperty } from '../../utilities/isolateObjectProperty.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport {\n getAllLocalesPublicationStatus,\n normalizeAllLocalesPublicationStatus,\n reconcileAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../versions/allLocalesPublicationStatus.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSort } from '../../versions/drafts/getQueryDraftsSort.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { copyDataWithFreshRowIDs } from './utilities/copyDataWithFreshRowIDs.js'\nimport { sanitizeSortQuery } from './utilities/sanitizeSortQuery.js'\nimport { updateDocument } from './utilities/update.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n autosave?: boolean\n collection: Collection\n data: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n depth?: number\n disableTransaction?: boolean\n disableVerificationEmail?: boolean\n draft?: boolean\n limit?: number\n overrideAccess?: boolean\n overrideLock?: boolean\n overwriteExistingFiles?: boolean\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n trash?: boolean\n unpublishAllLocales?: boolean\n where: Where\n} & Pick<FindOptions<TSlug, SelectType>, 'select'>\n\nexport const updateOperation = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments<TSlug>,\n): Promise<BulkOperationResult<TSlug, TSelect>> => {\n let args = incomingArgs\n const hasFileOperationScope = Boolean(args.collection.config.upload)\n\n assertNoValidationWrite(args.req)\n\n if (args.collection.config.disableBulkEdit && !args.overrideAccess) {\n throw new APIError(`Collection ${args.collection.config.slug} has disabled bulk edit`, 403)\n }\n\n if (hasFileOperationScope) {\n beginFileOperationScope({ req: args.req })\n }\n\n try {\n const shouldCommit = !args.disableTransaction && (await initTransaction(args.req))\n\n if (args.collection.config.upload && !args.overrideAccess) {\n const { objectKey, prefix } = getUploadDestination({ data: args.data, file: args.req.file })\n const data = sanitizeUploadData(args.data, 'update')\n\n args = {\n ...args,\n data:\n typeof data === 'object' && data !== null\n ? {\n ...data,\n ...(prefix !== undefined ? { prefix } : {}),\n ...(objectKey !== undefined ? { _objectKey: objectKey } : {}),\n }\n : data,\n }\n }\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: args.publishAllLocales,\n unpublishAllLocales: args.unpublishAllLocales,\n })\n\n const initialCollectionConfig = args.collection.config\n const initialAllLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(\n args.req.payload.config.localization && hasLocalizeStatusEnabled(initialCollectionConfig),\n ),\n publishAllLocales:\n !args.draft &&\n (args.publishAllLocales ??\n !(hasLocalizeStatusEnabled(initialCollectionConfig) && args.req.locale !== 'all')),\n unpublishAllLocales: Boolean(args.unpublishAllLocales),\n })\n\n const initialAllLocalesPublicationIntent = normalizeAllLocalesPublicationStatus({\n data: args.data,\n status: initialAllLocalesPublicationStatus,\n })\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'update',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n autosave = false,\n collection: { config: collectionConfig },\n collection,\n depth,\n draft: draftArg = false,\n limit = 0,\n overrideAccess,\n overrideLock,\n overwriteExistingFiles = false,\n populate,\n publishAllLocales: publishAllLocalesArg,\n req: {\n fallbackLocale,\n locale,\n payload: { config },\n payload,\n },\n req,\n select: incomingSelect,\n showHiddenFields,\n sort: incomingSort,\n trash = false,\n unpublishAllLocales: unpublishAllLocalesArg,\n where,\n } = args\n\n if (!where) {\n throw new APIError(\"Missing 'where' query of documents to update.\", httpStatus.BAD_REQUEST)\n }\n\n const { data: bulkUpdateData } = args\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const requestedAllLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(\n config.localization && hasLocalizeStatusEnabled(collectionConfig),\n ),\n publishAllLocales:\n !draftArg &&\n (publishAllLocalesArg ?? !(hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all')),\n unpublishAllLocales: Boolean(unpublishAllLocalesArg),\n })\n const allLocalesPublicationStatus = reconcileAllLocalesPublicationStatus({\n data: bulkUpdateData,\n intent: initialAllLocalesPublicationIntent,\n status: requestedAllLocalesPublicationStatus,\n })\n const publicationIntentSurvivedBeforeOperation =\n !requestedAllLocalesPublicationStatus || Boolean(allLocalesPublicationStatus)\n const publishAllLocales = publicationIntentSurvivedBeforeOperation\n ? publishAllLocalesArg\n : false\n const unpublishAllLocales = publicationIntentSurvivedBeforeOperation\n ? unpublishAllLocalesArg\n : false\n\n const shouldSaveDraft = Boolean(draftArg && hasDraftsEnabled(collectionConfig))\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n if (!overrideAccess) {\n accessResult = await executeAccess(\n { slug: collectionConfig.slug, data: bulkUpdateData, req },\n collectionConfig.access.update,\n )\n }\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n where,\n })\n\n // /////////////////////////////////////\n // Retrieve documents\n // /////////////////////////////////////\n\n let fullWhere = combineQueries(where, accessResult!)\n\n const isTrashAttempt =\n collectionConfig.trash &&\n typeof bulkUpdateData === 'object' &&\n bulkUpdateData !== null &&\n 'deletedAt' in bulkUpdateData &&\n bulkUpdateData.deletedAt != null\n\n // Enforce delete access if performing a soft-delete (trash)\n if (isTrashAttempt && !overrideAccess) {\n // Pass data so access function can check data.deletedAt to know it's a trash attempt\n const deleteAccessResult = await executeAccess(\n { slug: collectionConfig.slug, data: bulkUpdateData, req },\n collectionConfig.access.delete,\n )\n fullWhere = combineQueries(fullWhere, deleteAccessResult)\n }\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: collectionConfig.flattenedFields, payload, where: fullWhere })\n\n const sort = sanitizeSortQuery({\n fields: collection.config.flattenedFields,\n sort: incomingSort || collectionConfig.defaultSort,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n })\n\n let docs\n\n if (hasDraftsEnabled(collectionConfig) && (shouldSaveDraft || isTrashAttempt)) {\n const versionsWhere = appendVersionToQueryKey(fullWhere)\n\n await validateQueryPaths({\n collectionConfig: collection.config,\n overrideAccess: overrideAccess!,\n req,\n versionFields: buildVersionCollectionFields(payload.config, collection.config, true),\n where: appendVersionToQueryKey(where),\n })\n\n const query = await payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n limit,\n locale: locale!,\n pagination: false,\n req,\n sort: getQueryDraftsSort({ collectionConfig, sort }),\n where: versionsWhere,\n })\n\n docs = query.docs\n } else {\n const query = await payload.db.find({\n collection: collectionConfig.slug,\n limit,\n locale: locale!,\n pagination: false,\n req,\n sort,\n where: fullWhere,\n })\n\n docs = query.docs\n }\n\n const sharedGeneratedFileData = !collectionConfig.upload\n ? await generateFileData({\n collection,\n config,\n data: bulkUpdateData,\n operation: 'update',\n overwriteExistingFiles,\n req,\n throwOnMissingFile: false,\n })\n : null\n\n const errors: BulkOperationResult<TSlug, TSelect>['errors'] = []\n const sharedClientUploadDownload = createSharedClientUploadDownload()\n\n const processDocument = async (incomingDoc: (typeof docs)[number]) => {\n let docWithLocales = incomingDoc\n const { id } = docWithLocales\n let documentTempFilePath: string | undefined\n let documentReq = req\n\n try {\n // Each document gets its own transaction when singleTransaction is enabled\n let docShouldCommit = false\n if (req.payload.db.bulkOperationsSingleTransaction) {\n docShouldCommit = await initTransaction(req)\n }\n\n const documentFile = req.file ? { ...req.file } : undefined\n if (collectionConfig.upload && documentFile?.tempFilePath) {\n documentTempFilePath = await copyTempFileForDocument({\n tempFilePath: documentFile.tempFilePath,\n })\n documentFile.tempFilePath = documentTempFilePath\n }\n\n if (collectionConfig.upload && sharedGeneratedFileData === null) {\n documentReq = isolateObjectProperty(req, ['file', 'payloadUploadSizes'])\n // A document that commits its own transaction must not roll back files committed by\n // earlier documents, so it only shares the operation's file scope inside one transaction.\n if (!docShouldCommit) {\n shareFileOperationScope({ owner: req, req: documentReq })\n }\n documentReq.file = documentFile\n documentReq.payloadUploadSizes = {}\n }\n if (collectionConfig.upload?.fileOperations) {\n docWithLocales = await withLegacyCloudUploadFileData({\n collection: collectionConfig,\n doc: docWithLocales,\n req: documentReq,\n })\n }\n const generatedFileData =\n sharedGeneratedFileData ??\n (await generateFileData({\n collection,\n config,\n data: mergeUploadDataWithDocument(bulkUpdateData, docWithLocales, {\n locale:\n locale === 'all' || !locale\n ? config.localization\n ? config.localization.defaultLocale\n : undefined\n : locale,\n localizedProperties: getLocalizedUploadProperties(collectionConfig.flattenedFields),\n }),\n fetchFullClientUpload: sharedClientUploadDownload.fetchFullClientUpload,\n operation: 'update',\n originalDoc: docWithLocales,\n overwriteExistingFiles,\n req: documentReq,\n throwOnMissingFile: false,\n }))\n\n const select = sanitizeSelect({\n fields: collectionConfig.flattenedFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'update',\n req,\n select: incomingSelect,\n }),\n })\n\n // ///////////////////////////////////////////////\n // Update document, runs all document level hooks\n // ///////////////////////////////////////////////\n const documentData = copyDataWithFreshRowIDs({\n config,\n data: generatedFileData.data,\n existingDoc: docWithLocales,\n fields: collectionConfig.fields,\n })\n const updateArgs = {\n id,\n autosave,\n collectionConfig,\n config,\n data: documentData,\n depth: depth!,\n docWithLocales,\n draftArg,\n fallbackLocale: fallbackLocale!,\n filesToUpload: generatedFileData.files,\n locale: locale!,\n overrideAccess: overrideAccess!,\n overrideLock: overrideLock!,\n payload,\n populate,\n publishAllLocales,\n req: documentReq,\n select: select!,\n shouldManageLocalFiles: true,\n showHiddenFields: showHiddenFields!,\n unpublishAllLocales,\n } as const\n const write = () => updateDocument(updateArgs)\n let updatedDoc = collectionConfig.upload.fileOperations\n ? await runCloudFileUpdate({\n id,\n collection: collectionConfig,\n current: incomingDoc,\n data: updateArgs.data,\n files: generatedFileData.files,\n req: documentReq,\n write,\n })\n : await write()\n\n // /////////////////////////////////////\n // Add collection property for auth collections\n // /////////////////////////////////////\n\n if (collectionConfig.auth) {\n updatedDoc = { ...updatedDoc, collection: collectionConfig.slug }\n }\n\n if (docShouldCommit) {\n await commitTransaction(documentReq)\n }\n\n return updatedDoc\n } catch (error) {\n const isPublic = error instanceof Error ? isErrorPublic(error, config) : false\n\n if (req.payload.db.bulkOperationsSingleTransaction) {\n await killTransaction(documentReq)\n }\n errors.push({\n id,\n isPublic,\n message: error instanceof Error ? error.message : 'Unknown error',\n })\n } finally {\n // generateFileData can replace the document's file with its copy of the shared client\n // upload download. That copy is only on the document's request, so the operation\n // cleanup misses it.\n const downloadedTempFilePath =\n documentReq !== req ? documentReq.file?.tempFilePath : undefined\n\n for (const tempFilePath of new Set([documentTempFilePath, downloadedTempFilePath])) {\n if (tempFilePath) {\n await fs.rm(tempFilePath, { force: true }).catch((error) => {\n req.payload.logger.error({ err: error, msg: 'Failed to remove temp file copy' })\n })\n }\n }\n }\n return null\n }\n\n // Upload processing may mutate its temp file while cropping, so each document must finish\n // before the next document starts. This only applies when an actual file is being written\n // (`req.file`); metadata-only bulk updates use isolated per-document request state and can\n // stay parallel. Other bulk updates retain their existing parallel behavior.\n const processSequentially =\n req.payload.db.bulkOperationsSingleTransaction || Boolean(collectionConfig.upload && req.file)\n let awaitedDocs: (DataFromCollectionSlug<TSlug> | null)[]\n try {\n if (processSequentially) {\n awaitedDocs = []\n for (const doc of docs) {\n awaitedDocs.push(await processDocument(doc))\n }\n } else {\n awaitedDocs = await Promise.all(docs.map(processDocument))\n }\n } finally {\n // Each document removes its own copy; the shared download is removed once here.\n await sharedClientUploadDownload.removeSharedDownload().catch((error) => {\n req.payload.logger.error({ err: error, msg: 'Failed to remove temp file' })\n })\n }\n\n await unlinkTempFiles({\n collectionConfig,\n config,\n req,\n }).catch((unlinkError) => {\n req.payload.logger.error({ err: unlinkError, msg: 'Failed to remove temp file' })\n })\n\n let result = {\n docs: awaitedDocs.filter(Boolean),\n errors,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'update',\n overrideAccess,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n if (hasFileOperationScope) {\n await completeFileOperationScope({ req })\n }\n\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return result\n } catch (error: unknown) {\n await unlinkTempFiles({\n collectionConfig: args.collection.config,\n config: args.req.payload.config,\n req: args.req,\n }).catch((unlinkError) => {\n args.req.payload.logger.error({ err: unlinkError, msg: 'Failed to remove temp file' })\n })\n await killTransaction(args.req)\n if (hasFileOperationScope) {\n await abortFileOperationScope({ req: args.req })\n }\n throw error\n }\n}\n"],"names":["fs","executeAccess","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","APIError","copyTempFileForDocument","createSharedClientUploadDownload","runCloudFileUpdate","abortFileOperationScope","beginFileOperationScope","completeFileOperationScope","shareFileOperationScope","withLegacyCloudUploadFileData","generateFileData","getLocalizedUploadProperties","getUploadDestination","mergeUploadDataWithDocument","sanitizeUploadData","unlinkTempFiles","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","hasDraftsEnabled","hasLocalizeStatusEnabled","httpStatus","initTransaction","isErrorPublic","isolateObjectProperty","killTransaction","resolveSelect","sanitizeSelect","getAllLocalesPublicationStatus","normalizeAllLocalesPublicationStatus","reconcileAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","buildVersionCollectionFields","appendVersionToQueryKey","getQueryDraftsSort","buildAfterOperation","buildBeforeOperation","copyDataWithFreshRowIDs","sanitizeSortQuery","updateDocument","updateOperation","incomingArgs","args","hasFileOperationScope","Boolean","collection","config","upload","req","disableBulkEdit","overrideAccess","slug","shouldCommit","disableTransaction","objectKey","prefix","data","file","undefined","_objectKey","publishAllLocales","unpublishAllLocales","initialCollectionConfig","initialAllLocalesPublicationStatus","hasLocalizedStatus","payload","localization","draft","locale","initialAllLocalesPublicationIntent","status","operation","autosave","collectionConfig","depth","draftArg","limit","overrideLock","overwriteExistingFiles","populate","publishAllLocalesArg","fallbackLocale","select","incomingSelect","showHiddenFields","sort","incomingSort","trash","unpublishAllLocalesArg","where","BAD_REQUEST","bulkUpdateData","requestedAllLocalesPublicationStatus","allLocalesPublicationStatus","intent","publicationIntentSurvivedBeforeOperation","shouldSaveDraft","accessResult","access","update","fullWhere","isTrashAttempt","deletedAt","deleteAccessResult","delete","enableTrash","fields","flattenedFields","defaultSort","docs","versionsWhere","versionFields","query","db","queryDrafts","pagination","find","sharedGeneratedFileData","throwOnMissingFile","errors","sharedClientUploadDownload","processDocument","incomingDoc","docWithLocales","id","documentTempFilePath","documentReq","docShouldCommit","bulkOperationsSingleTransaction","documentFile","tempFilePath","owner","payloadUploadSizes","fileOperations","doc","generatedFileData","defaultLocale","localizedProperties","fetchFullClientUpload","originalDoc","documentData","existingDoc","updateArgs","filesToUpload","files","shouldManageLocalFiles","write","updatedDoc","current","auth","error","isPublic","Error","push","message","downloadedTempFilePath","Set","rm","force","catch","logger","err","msg","processSequentially","awaitedDocs","Promise","all","map","removeSharedDownload","unlinkError","result","filter"],"mappings":"AAEA,OAAOA,QAAQ,mBAAkB;AAYjC,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,QAAQ,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAEhD,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,gCAAgC,QAAQ,oDAAmD;AACpG,SAASC,kBAAkB,QAAQ,+CAA8C;AACjF,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,0BAA0B,EAC1BC,uBAAuB,QAClB,uDAAsD;AAC7D,SAASC,6BAA6B,QAAQ,8CAA6C;AAC3F,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,SACEC,4BAA4B,E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AG+G,KAAK,CAAC,CAACU;YACRzH,IAAIiB,OAAO,CAAC+F,MAAM,CAACV,KAAK,CAAC;gBAAEW,KAAKQ;gBAAaP,KAAK;YAA6B;QACjF;QAEA,IAAIQ,SAAS;YACX7D,MAAMuD,YAAYO,MAAM,CAAC/H;YACzB2E;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCmD,SAAS,MAAMvI,oBAAoB;YACjCO;YACAG,YAAY4B;YACZF,WAAW;YACXrB;YACA,oFAAoF;YACpFwH;QACF;QAEA,IAAItH,cAAc;YAChB,MAAMlC,kBAAkB8B;QAC1B;QAEA,IAAIL,uBAAuB;YACzB,MAAMpC,2BAA2B;gBAAEyC;YAAI;QACzC;QAEA,oFAAoF;QACpF,OAAO0H;IACT,EAAE,OAAOpB,OAAgB;QACvB,MAAMvI,gBAAgB;YACpB0D,kBAAkB/B,KAAKG,UAAU,CAACC,MAAM;YACxCA,QAAQJ,KAAKM,GAAG,CAACiB,OAAO,CAACnB,MAAM;YAC/BE,KAAKN,KAAKM,GAAG;QACf,GAAG+G,KAAK,CAAC,CAACU;YACR/H,KAAKM,GAAG,CAACiB,OAAO,CAAC+F,MAAM,CAACV,KAAK,CAAC;gBAAEW,KAAKQ;gBAAaP,KAAK;YAA6B;QACtF;QACA,MAAMzI,gBAAgBiB,KAAKM,GAAG;QAC9B,IAAIL,uBAAuB;YACzB,MAAMtC,wBAAwB;gBAAE2C,KAAKN,KAAKM,GAAG;YAAC;QAChD;QACA,MAAMsG;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport fs from 'node:fs/promises'\n\nimport type { AccessResult } from '../../config/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type {\n BulkOperationResult,\n Collection,\n DataFromCollectionSlug,\n RequiredDataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { cloneWhere } from '../../database/cloneWhere.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { APIError } from '../../errors/index.js'\nimport { type CollectionSlug, type FindOptions } from '../../index.js'\nimport { copyTempFileForDocument } from '../../uploads/copyTempFileForDocument.js'\nimport { createSharedClientUploadDownload } from '../../uploads/createSharedClientUploadDownload.js'\nimport { runCloudFileUpdate } from '../../uploads/fileVersioning/cloudStorage.js'\nimport {\n abortFileOperationScope,\n beginFileOperationScope,\n completeFileOperationScope,\n shareFileOperationScope,\n} from '../../uploads/fileVersioning/fileOperationManager.js'\nimport { withLegacyCloudUploadFileData } from '../../uploads/fileVersioning/storedFiles.js'\nimport { generateFileData } from '../../uploads/generateFileData/index.js'\nimport {\n getLocalizedUploadProperties,\n getUploadDestination,\n mergeUploadDataWithDocument,\n sanitizeUploadData,\n} from '../../uploads/sanitizeUploadData.js'\nimport { unlinkTempFiles } from '../../uploads/unlinkTempFiles.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../../utilities/assertNoValidationWrite.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { hasDraftsEnabled, hasLocalizeStatusEnabled } from '../../utilities/getVersionsConfig.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { isErrorPublic } from '../../utilities/isErrorPublic.js'\nimport { isolateObjectProperty } from '../../utilities/isolateObjectProperty.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport {\n getAllLocalesPublicationStatus,\n normalizeAllLocalesPublicationStatus,\n reconcileAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../versions/allLocalesPublicationStatus.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSort } from '../../versions/drafts/getQueryDraftsSort.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { copyDataWithFreshRowIDs } from './utilities/copyDataWithFreshRowIDs.js'\nimport { sanitizeSortQuery } from './utilities/sanitizeSortQuery.js'\nimport { updateDocument } from './utilities/update.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n autosave?: boolean\n collection: Collection\n data: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n depth?: number\n disableTransaction?: boolean\n disableVerificationEmail?: boolean\n draft?: boolean\n limit?: number\n overrideAccess?: boolean\n overrideLock?: boolean\n overwriteExistingFiles?: boolean\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n trash?: boolean\n unpublishAllLocales?: boolean\n where: Where\n} & Pick<FindOptions<TSlug, SelectType>, 'select'>\n\nexport const updateOperation = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments<TSlug>,\n): Promise<BulkOperationResult<TSlug, TSelect>> => {\n let args = incomingArgs\n const hasFileOperationScope = Boolean(args.collection.config.upload)\n\n assertNoValidationWrite(args.req)\n\n if (args.collection.config.disableBulkEdit && !args.overrideAccess) {\n throw new APIError(`Collection ${args.collection.config.slug} has disabled bulk edit`, 403)\n }\n\n if (hasFileOperationScope) {\n beginFileOperationScope({ req: args.req })\n }\n\n try {\n const shouldCommit = !args.disableTransaction && (await initTransaction(args.req))\n\n if (args.collection.config.upload && !args.overrideAccess) {\n const { objectKey, prefix } = getUploadDestination({ data: args.data, file: args.req.file })\n const data = sanitizeUploadData(args.data, 'update')\n\n args = {\n ...args,\n data:\n typeof data === 'object' && data !== null\n ? {\n ...data,\n ...(prefix !== undefined ? { prefix } : {}),\n ...(objectKey !== undefined ? { _objectKey: objectKey } : {}),\n }\n : data,\n }\n }\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: args.publishAllLocales,\n unpublishAllLocales: args.unpublishAllLocales,\n })\n\n const initialCollectionConfig = args.collection.config\n const initialAllLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(\n args.req.payload.config.localization && hasLocalizeStatusEnabled(initialCollectionConfig),\n ),\n publishAllLocales:\n !args.draft &&\n (args.publishAllLocales ??\n !(hasLocalizeStatusEnabled(initialCollectionConfig) && args.req.locale !== 'all')),\n unpublishAllLocales: Boolean(args.unpublishAllLocales),\n })\n\n const initialAllLocalesPublicationIntent = normalizeAllLocalesPublicationStatus({\n data: args.data,\n status: initialAllLocalesPublicationStatus,\n })\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'update',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n autosave = false,\n collection: { config: collectionConfig },\n collection,\n depth,\n draft: draftArg = false,\n limit = 0,\n overrideAccess,\n overrideLock,\n overwriteExistingFiles = false,\n populate,\n publishAllLocales: publishAllLocalesArg,\n req: {\n fallbackLocale,\n locale,\n payload: { config },\n payload,\n },\n req,\n select: incomingSelect,\n showHiddenFields,\n sort: incomingSort,\n trash = false,\n unpublishAllLocales: unpublishAllLocalesArg,\n where: incomingWhere,\n } = args\n\n const where = cloneWhere(incomingWhere)\n\n if (!where) {\n throw new APIError(\"Missing 'where' query of documents to update.\", httpStatus.BAD_REQUEST)\n }\n\n const { data: bulkUpdateData } = args\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const requestedAllLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(\n config.localization && hasLocalizeStatusEnabled(collectionConfig),\n ),\n publishAllLocales:\n !draftArg &&\n (publishAllLocalesArg ?? !(hasLocalizeStatusEnabled(collectionConfig) && locale !== 'all')),\n unpublishAllLocales: Boolean(unpublishAllLocalesArg),\n })\n const allLocalesPublicationStatus = reconcileAllLocalesPublicationStatus({\n data: bulkUpdateData,\n intent: initialAllLocalesPublicationIntent,\n status: requestedAllLocalesPublicationStatus,\n })\n const publicationIntentSurvivedBeforeOperation =\n !requestedAllLocalesPublicationStatus || Boolean(allLocalesPublicationStatus)\n const publishAllLocales = publicationIntentSurvivedBeforeOperation\n ? publishAllLocalesArg\n : false\n const unpublishAllLocales = publicationIntentSurvivedBeforeOperation\n ? unpublishAllLocalesArg\n : false\n\n const shouldSaveDraft = Boolean(draftArg && hasDraftsEnabled(collectionConfig))\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n if (!overrideAccess) {\n accessResult = await executeAccess(\n { slug: collectionConfig.slug, data: bulkUpdateData, req },\n collectionConfig.access.update,\n )\n }\n\n // /////////////////////////////////////\n // Retrieve documents\n // /////////////////////////////////////\n\n let fullWhere = combineQueries(where, accessResult!)\n\n const isTrashAttempt =\n collectionConfig.trash &&\n typeof bulkUpdateData === 'object' &&\n bulkUpdateData !== null &&\n 'deletedAt' in bulkUpdateData &&\n bulkUpdateData.deletedAt != null\n\n // Enforce delete access if performing a soft-delete (trash)\n if (isTrashAttempt && !overrideAccess) {\n // Pass data so access function can check data.deletedAt to know it's a trash attempt\n const deleteAccessResult = await executeAccess(\n { slug: collectionConfig.slug, data: bulkUpdateData, req },\n collectionConfig.access.delete,\n )\n fullWhere = combineQueries(fullWhere, deleteAccessResult)\n }\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: collectionConfig.flattenedFields, payload, where: fullWhere })\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n where,\n })\n\n const sort = sanitizeSortQuery({\n fields: collection.config.flattenedFields,\n sort: incomingSort || collectionConfig.defaultSort,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n })\n\n let docs\n\n if (hasDraftsEnabled(collectionConfig) && (shouldSaveDraft || isTrashAttempt)) {\n const versionsWhere = appendVersionToQueryKey(fullWhere)\n\n const query = await payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n limit,\n locale: locale!,\n pagination: false,\n req,\n sort: getQueryDraftsSort({ collectionConfig, sort }),\n where: versionsWhere,\n })\n\n docs = query.docs\n } else {\n const query = await payload.db.find({\n collection: collectionConfig.slug,\n limit,\n locale: locale!,\n pagination: false,\n req,\n sort,\n where: fullWhere,\n })\n\n docs = query.docs\n }\n\n const sharedGeneratedFileData = !collectionConfig.upload\n ? await generateFileData({\n collection,\n config,\n data: bulkUpdateData,\n operation: 'update',\n overwriteExistingFiles,\n req,\n throwOnMissingFile: false,\n })\n : null\n\n const errors: BulkOperationResult<TSlug, TSelect>['errors'] = []\n const sharedClientUploadDownload = createSharedClientUploadDownload()\n\n const processDocument = async (incomingDoc: (typeof docs)[number]) => {\n let docWithLocales = incomingDoc\n const { id } = docWithLocales\n let documentTempFilePath: string | undefined\n let documentReq = req\n\n try {\n // Each document gets its own transaction when singleTransaction is enabled\n let docShouldCommit = false\n if (req.payload.db.bulkOperationsSingleTransaction) {\n docShouldCommit = await initTransaction(req)\n }\n\n const documentFile = req.file ? { ...req.file } : undefined\n if (collectionConfig.upload && documentFile?.tempFilePath) {\n documentTempFilePath = await copyTempFileForDocument({\n tempFilePath: documentFile.tempFilePath,\n })\n documentFile.tempFilePath = documentTempFilePath\n }\n\n if (collectionConfig.upload && sharedGeneratedFileData === null) {\n documentReq = isolateObjectProperty(req, ['file', 'payloadUploadSizes'])\n // A document that commits its own transaction must not roll back files committed by\n // earlier documents, so it only shares the operation's file scope inside one transaction.\n if (!docShouldCommit) {\n shareFileOperationScope({ owner: req, req: documentReq })\n }\n documentReq.file = documentFile\n documentReq.payloadUploadSizes = {}\n }\n if (collectionConfig.upload?.fileOperations) {\n docWithLocales = await withLegacyCloudUploadFileData({\n collection: collectionConfig,\n doc: docWithLocales,\n req: documentReq,\n })\n }\n const generatedFileData =\n sharedGeneratedFileData ??\n (await generateFileData({\n collection,\n config,\n data: mergeUploadDataWithDocument(bulkUpdateData, docWithLocales, {\n locale:\n locale === 'all' || !locale\n ? config.localization\n ? config.localization.defaultLocale\n : undefined\n : locale,\n localizedProperties: getLocalizedUploadProperties(collectionConfig.flattenedFields),\n }),\n fetchFullClientUpload: sharedClientUploadDownload.fetchFullClientUpload,\n operation: 'update',\n originalDoc: docWithLocales,\n overwriteExistingFiles,\n req: documentReq,\n throwOnMissingFile: false,\n }))\n\n const select = sanitizeSelect({\n fields: collectionConfig.flattenedFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'update',\n req,\n select: incomingSelect,\n }),\n })\n\n // ///////////////////////////////////////////////\n // Update document, runs all document level hooks\n // ///////////////////////////////////////////////\n const documentData = copyDataWithFreshRowIDs({\n config,\n data: generatedFileData.data,\n existingDoc: docWithLocales,\n fields: collectionConfig.fields,\n })\n const updateArgs = {\n id,\n autosave,\n collectionConfig,\n config,\n data: documentData,\n depth: depth!,\n docWithLocales,\n draftArg,\n fallbackLocale: fallbackLocale!,\n filesToUpload: generatedFileData.files,\n locale: locale!,\n overrideAccess: overrideAccess!,\n overrideLock: overrideLock!,\n payload,\n populate,\n publishAllLocales,\n req: documentReq,\n select: select!,\n shouldManageLocalFiles: true,\n showHiddenFields: showHiddenFields!,\n unpublishAllLocales,\n } as const\n const write = () => updateDocument(updateArgs)\n let updatedDoc = collectionConfig.upload.fileOperations\n ? await runCloudFileUpdate({\n id,\n collection: collectionConfig,\n current: incomingDoc,\n data: updateArgs.data,\n files: generatedFileData.files,\n req: documentReq,\n write,\n })\n : await write()\n\n // /////////////////////////////////////\n // Add collection property for auth collections\n // /////////////////////////////////////\n\n if (collectionConfig.auth) {\n updatedDoc = { ...updatedDoc, collection: collectionConfig.slug }\n }\n\n if (docShouldCommit) {\n await commitTransaction(documentReq)\n }\n\n return updatedDoc\n } catch (error) {\n const isPublic = error instanceof Error ? isErrorPublic(error, config) : false\n\n if (req.payload.db.bulkOperationsSingleTransaction) {\n await killTransaction(documentReq)\n }\n errors.push({\n id,\n isPublic,\n message: error instanceof Error ? error.message : 'Unknown error',\n })\n } finally {\n // generateFileData can replace the document's file with its copy of the shared client\n // upload download. That copy is only on the document's request, so the operation\n // cleanup misses it.\n const downloadedTempFilePath =\n documentReq !== req ? documentReq.file?.tempFilePath : undefined\n\n for (const tempFilePath of new Set([documentTempFilePath, downloadedTempFilePath])) {\n if (tempFilePath) {\n await fs.rm(tempFilePath, { force: true }).catch((error) => {\n req.payload.logger.error({ err: error, msg: 'Failed to remove temp file copy' })\n })\n }\n }\n }\n return null\n }\n\n // Upload processing may mutate its temp file while cropping, so each document must finish\n // before the next document starts. This only applies when an actual file is being written\n // (`req.file`); metadata-only bulk updates use isolated per-document request state and can\n // stay parallel. Other bulk updates retain their existing parallel behavior.\n const processSequentially =\n req.payload.db.bulkOperationsSingleTransaction || Boolean(collectionConfig.upload && req.file)\n let awaitedDocs: (DataFromCollectionSlug<TSlug> | null)[]\n try {\n if (processSequentially) {\n awaitedDocs = []\n for (const doc of docs) {\n awaitedDocs.push(await processDocument(doc))\n }\n } else {\n awaitedDocs = await Promise.all(docs.map(processDocument))\n }\n } finally {\n // Each document removes its own copy; the shared download is removed once here.\n await sharedClientUploadDownload.removeSharedDownload().catch((error) => {\n req.payload.logger.error({ err: error, msg: 'Failed to remove temp file' })\n })\n }\n\n await unlinkTempFiles({\n collectionConfig,\n config,\n req,\n }).catch((unlinkError) => {\n req.payload.logger.error({ err: unlinkError, msg: 'Failed to remove temp file' })\n })\n\n let result = {\n docs: awaitedDocs.filter(Boolean),\n errors,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'update',\n overrideAccess,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n if (hasFileOperationScope) {\n await completeFileOperationScope({ req })\n }\n\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return result\n } catch (error: unknown) {\n await unlinkTempFiles({\n collectionConfig: args.collection.config,\n config: args.req.payload.config,\n req: args.req,\n }).catch((unlinkError) => {\n args.req.payload.logger.error({ err: unlinkError, msg: 'Failed to remove temp file' })\n })\n await killTransaction(args.req)\n if (hasFileOperationScope) {\n await abortFileOperationScope({ req: args.req })\n }\n throw error\n }\n}\n"],"names":["fs","executeAccess","cloneWhere","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","APIError","copyTempFileForDocument","createSharedClientUploadDownload","runCloudFileUpdate","abortFileOperationScope","beginFileOperationScope","completeFileOperationScope","shareFileOperationScope","withLegacyCloudUploadFileData","generateFileData","getLocalizedUploadProperties","getUploadDestination","mergeUploadDataWithDocument","sanitizeUploadData","unlinkTempFiles","appendNonTrashedFilter","assertNoValidationWrite","commitTransaction","hasDraftsEnabled","hasLocalizeStatusEnabled","httpStatus","initTransaction","isErrorPublic","isolateObjectProperty","killTransaction","resolveSelect","sanitizeSelect","getAllLocalesPublicationStatus","normalizeAllLocalesPublicationStatus","reconcileAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","appendVersionToQueryKey","getQueryDraftsSort","buildAfterOperation","buildBeforeOperation","copyDataWithFreshRowIDs","sanitizeSortQuery","updateDocument","updateOperation","incomingArgs","args","hasFileOperationScope","Boolean","collection","config","upload","req","disableBulkEdit","overrideAccess","slug","shouldCommit","disableTransaction","objectKey","prefix","data","file","undefined","_objectKey","publishAllLocales","unpublishAllLocales","initialCollectionConfig","initialAllLocalesPublicationStatus","hasLocalizedStatus","payload","localization","draft","locale","initialAllLocalesPublicationIntent","status","operation","autosave","collectionConfig","depth","draftArg","limit","overrideLock","overwriteExistingFiles","populate","publishAllLocalesArg","fallbackLocale","select","incomingSelect","showHiddenFields","sort","incomingSort","trash","unpublishAllLocalesArg","where","incomingWhere","BAD_REQUEST","bulkUpdateData","requestedAllLocalesPublicationStatus","allLocalesPublicationStatus","intent","publicationIntentSurvivedBeforeOperation","shouldSaveDraft","accessResult","access","update","fullWhere","isTrashAttempt","deletedAt","deleteAccessResult","delete","enableTrash","fields","flattenedFields","defaultSort","docs","versionsWhere","query","db","queryDrafts","pagination","find","sharedGeneratedFileData","throwOnMissingFile","errors","sharedClientUploadDownload","processDocument","incomingDoc","docWithLocales","id","documentTempFilePath","documentReq","docShouldCommit","bulkOperationsSingleTransaction","documentFile","tempFilePath","owner","payloadUploadSizes","fileOperations","doc","generatedFileData","defaultLocale","localizedProperties","fetchFullClientUpload","originalDoc","documentData","existingDoc","updateArgs","filesToUpload","files","shouldManageLocalFiles","write","updatedDoc","current","auth","error","isPublic","Error","push","message","downloadedTempFilePath","Set","rm","force","catch","logger","err","msg","processSequentially","awaitedDocs","Promise","all","map","removeSharedDownload","unlinkError","result","filter"],"mappings":"AAEA,OAAOA,QAAQ,mBAAkB;AAYjC,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,UAAU,QAAQ,+BAA8B;AACzD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,QAAQ,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAEhD,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,gCAA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QAEA,MAAMlJ,gBAAgB;YACpByD;YACA3B;YACAE;QACF,GAAG+G,KAAK,CAAC,CAACU;YACRzH,IAAIiB,OAAO,CAAC+F,MAAM,CAACV,KAAK,CAAC;gBAAEW,KAAKQ;gBAAaP,KAAK;YAA6B;QACjF;QAEA,IAAIQ,SAAS;YACX5D,MAAMsD,YAAYO,MAAM,CAAC/H;YACzB2E;QACF;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCmD,SAAS,MAAMvI,oBAAoB;YACjCO;YACAG,YAAY4B;YACZF,WAAW;YACXrB;YACA,oFAAoF;YACpFwH;QACF;QAEA,IAAItH,cAAc;YAChB,MAAMjC,kBAAkB6B;QAC1B;QAEA,IAAIL,uBAAuB;YACzB,MAAMnC,2BAA2B;gBAAEwC;YAAI;QACzC;QAEA,oFAAoF;QACpF,OAAO0H;IACT,EAAE,OAAOpB,OAAgB;QACvB,MAAMtI,gBAAgB;YACpByD,kBAAkB/B,KAAKG,UAAU,CAACC,MAAM;YACxCA,QAAQJ,KAAKM,GAAG,CAACiB,OAAO,CAACnB,MAAM;YAC/BE,KAAKN,KAAKM,GAAG;QACf,GAAG+G,KAAK,CAAC,CAACU;YACR/H,KAAKM,GAAG,CAACiB,OAAO,CAAC+F,MAAM,CAACV,KAAK,CAAC;gBAAEW,KAAKQ;gBAAaP,KAAK;YAA6B;QACtF;QACA,MAAMxI,gBAAgBgB,KAAKM,GAAG;QAC9B,IAAIL,uBAAuB;YACzB,MAAMrC,wBAAwB;gBAAE0C,KAAKN,KAAKM,GAAG;YAAC;QAChD;QACA,MAAMsG;IACR;AACF,EAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Where } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Copies the plain objects and arrays that make up a `where` query. Every other value, such as a
|
|
4
|
+
* `Date` or a MongoDB `ObjectId`, is kept by reference.
|
|
5
|
+
*
|
|
6
|
+
* Query validation rewrites the query it validates in place to apply access constraints, so
|
|
7
|
+
* operations validate and run a copy. This leaves the caller's object untouched and safe to reuse.
|
|
8
|
+
*/
|
|
9
|
+
export declare function cloneWhere<TWhere extends undefined | Where>(where: TWhere): TWhere;
|
|
10
|
+
//# sourceMappingURL=cloneWhere.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloneWhere.d.ts","sourceRoot":"","sources":["../../src/database/cloneWhere.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAE9C;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,MAAM,SAAS,SAAS,GAAG,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAElF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copies the plain objects and arrays that make up a `where` query. Every other value, such as a
|
|
3
|
+
* `Date` or a MongoDB `ObjectId`, is kept by reference.
|
|
4
|
+
*
|
|
5
|
+
* Query validation rewrites the query it validates in place to apply access constraints, so
|
|
6
|
+
* operations validate and run a copy. This leaves the caller's object untouched and safe to reuse.
|
|
7
|
+
*/ export function cloneWhere(where) {
|
|
8
|
+
return cloneQueryValue(where);
|
|
9
|
+
}
|
|
10
|
+
function cloneQueryValue(value) {
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
return value.map(cloneQueryValue);
|
|
13
|
+
}
|
|
14
|
+
if (isPlainObject(value)) {
|
|
15
|
+
const copy = {};
|
|
16
|
+
for (const key of Object.keys(value)){
|
|
17
|
+
copy[key] = cloneQueryValue(value[key]);
|
|
18
|
+
}
|
|
19
|
+
return copy;
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function isPlainObject(value) {
|
|
24
|
+
if (typeof value !== 'object' || value === null) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
const prototype = Object.getPrototypeOf(value);
|
|
28
|
+
return prototype === Object.prototype || prototype === null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=cloneWhere.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/database/cloneWhere.ts"],"sourcesContent":["import type { Where } from '../types/index.js'\n\n/**\n * Copies the plain objects and arrays that make up a `where` query. Every other value, such as a\n * `Date` or a MongoDB `ObjectId`, is kept by reference.\n *\n * Query validation rewrites the query it validates in place to apply access constraints, so\n * operations validate and run a copy. This leaves the caller's object untouched and safe to reuse.\n */\nexport function cloneWhere<TWhere extends undefined | Where>(where: TWhere): TWhere {\n return cloneQueryValue(where) as TWhere\n}\n\nfunction cloneQueryValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(cloneQueryValue)\n }\n\n if (isPlainObject(value)) {\n const copy: Record<string, unknown> = {}\n\n for (const key of Object.keys(value)) {\n copy[key] = cloneQueryValue(value[key])\n }\n\n return copy\n }\n\n return value\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false\n }\n\n const prototype = Object.getPrototypeOf(value)\n\n return prototype === Object.prototype || prototype === null\n}\n"],"names":["cloneWhere","where","cloneQueryValue","value","Array","isArray","map","isPlainObject","copy","key","Object","keys","prototype","getPrototypeOf"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,SAASA,WAA6CC,KAAa;IACxE,OAAOC,gBAAgBD;AACzB;AAEA,SAASC,gBAAgBC,KAAc;IACrC,IAAIC,MAAMC,OAAO,CAACF,QAAQ;QACxB,OAAOA,MAAMG,GAAG,CAACJ;IACnB;IAEA,IAAIK,cAAcJ,QAAQ;QACxB,MAAMK,OAAgC,CAAC;QAEvC,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACR,OAAQ;YACpCK,IAAI,CAACC,IAAI,GAAGP,gBAAgBC,KAAK,CAACM,IAAI;QACxC;QAEA,OAAOD;IACT;IAEA,OAAOL;AACT;AAEA,SAASI,cAAcJ,KAAc;IACnC,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;QAC/C,OAAO;IACT;IAEA,MAAMS,YAAYF,OAAOG,cAAc,CAACV;IAExC,OAAOS,cAAcF,OAAOE,SAAS,IAAIA,cAAc;AACzD"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Where } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Scopes a nested has-many relationship query to the related documents the caller can read.
|
|
4
|
+
*
|
|
5
|
+
* The returned query matches related documents that satisfy both the caller's query and the
|
|
6
|
+
* related collection's read constraint. The read constraint is also attached on its own, so a
|
|
7
|
+
* database adapter can evaluate `equals` against readable related documents only. Without it,
|
|
8
|
+
* any related document the caller cannot read would make `equals` fail.
|
|
9
|
+
*
|
|
10
|
+
* The constraint is stored under a symbol, which a REST or GraphQL query cannot supply.
|
|
11
|
+
*/
|
|
12
|
+
export declare function constrainNestedRelationshipQuery({ readConstraint, where, }: {
|
|
13
|
+
readConstraint: Where;
|
|
14
|
+
where: Where;
|
|
15
|
+
}): Where;
|
|
16
|
+
/**
|
|
17
|
+
* Returns the read constraint attached by `constrainNestedRelationshipQuery`, if any.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getNestedRelationshipReadConstraint(where: unknown): undefined | Where;
|
|
20
|
+
//# sourceMappingURL=nestedRelationshipReadConstraint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nestedRelationshipReadConstraint.d.ts","sourceRoot":"","sources":["../../src/database/nestedRelationshipReadConstraint.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAI9C;;;;;;;;;GASG;AACH,wBAAgB,gCAAgC,CAAC,EAC/C,cAAc,EACd,KAAK,GACN,EAAE;IACD,cAAc,EAAE,KAAK,CAAA;IACrB,KAAK,EAAE,KAAK,CAAA;CACb,GAAG,KAAK,CASR;AAED;;GAEG;AACH,wBAAgB,mCAAmC,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,GAAG,KAAK,CAMrF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const readConstraintKey = Symbol.for('payload.nestedRelationshipReadConstraint');
|
|
2
|
+
/**
|
|
3
|
+
* Scopes a nested has-many relationship query to the related documents the caller can read.
|
|
4
|
+
*
|
|
5
|
+
* The returned query matches related documents that satisfy both the caller's query and the
|
|
6
|
+
* related collection's read constraint. The read constraint is also attached on its own, so a
|
|
7
|
+
* database adapter can evaluate `equals` against readable related documents only. Without it,
|
|
8
|
+
* any related document the caller cannot read would make `equals` fail.
|
|
9
|
+
*
|
|
10
|
+
* The constraint is stored under a symbol, which a REST or GraphQL query cannot supply.
|
|
11
|
+
*/ export function constrainNestedRelationshipQuery({ readConstraint, where }) {
|
|
12
|
+
const constrainedWhere = {
|
|
13
|
+
and: [
|
|
14
|
+
where,
|
|
15
|
+
readConstraint
|
|
16
|
+
]
|
|
17
|
+
};
|
|
18
|
+
Object.defineProperty(constrainedWhere, readConstraintKey, {
|
|
19
|
+
enumerable: false,
|
|
20
|
+
value: readConstraint
|
|
21
|
+
});
|
|
22
|
+
return constrainedWhere;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Returns the read constraint attached by `constrainNestedRelationshipQuery`, if any.
|
|
26
|
+
*/ export function getNestedRelationshipReadConstraint(where) {
|
|
27
|
+
if (typeof where !== 'object' || where === null) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
return where[readConstraintKey];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=nestedRelationshipReadConstraint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/database/nestedRelationshipReadConstraint.ts"],"sourcesContent":["import type { Where } from '../types/index.js'\n\nconst readConstraintKey = Symbol.for('payload.nestedRelationshipReadConstraint')\n\n/**\n * Scopes a nested has-many relationship query to the related documents the caller can read.\n *\n * The returned query matches related documents that satisfy both the caller's query and the\n * related collection's read constraint. The read constraint is also attached on its own, so a\n * database adapter can evaluate `equals` against readable related documents only. Without it,\n * any related document the caller cannot read would make `equals` fail.\n *\n * The constraint is stored under a symbol, which a REST or GraphQL query cannot supply.\n */\nexport function constrainNestedRelationshipQuery({\n readConstraint,\n where,\n}: {\n readConstraint: Where\n where: Where\n}): Where {\n const constrainedWhere: Where = { and: [where, readConstraint] }\n\n Object.defineProperty(constrainedWhere, readConstraintKey, {\n enumerable: false,\n value: readConstraint,\n })\n\n return constrainedWhere\n}\n\n/**\n * Returns the read constraint attached by `constrainNestedRelationshipQuery`, if any.\n */\nexport function getNestedRelationshipReadConstraint(where: unknown): undefined | Where {\n if (typeof where !== 'object' || where === null) {\n return undefined\n }\n\n return (where as { [readConstraintKey]?: Where })[readConstraintKey]\n}\n"],"names":["readConstraintKey","Symbol","for","constrainNestedRelationshipQuery","readConstraint","where","constrainedWhere","and","Object","defineProperty","enumerable","value","getNestedRelationshipReadConstraint","undefined"],"mappings":"AAEA,MAAMA,oBAAoBC,OAAOC,GAAG,CAAC;AAErC;;;;;;;;;CASC,GACD,OAAO,SAASC,iCAAiC,EAC/CC,cAAc,EACdC,KAAK,EAIN;IACC,MAAMC,mBAA0B;QAAEC,KAAK;YAACF;YAAOD;SAAe;IAAC;IAE/DI,OAAOC,cAAc,CAACH,kBAAkBN,mBAAmB;QACzDU,YAAY;QACZC,OAAOP;IACT;IAEA,OAAOE;AACT;AAEA;;CAEC,GACD,OAAO,SAASM,oCAAoCP,KAAc;IAChE,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;QAC/C,OAAOQ;IACT;IAEA,OAAO,AAACR,KAAyC,CAACL,kBAAkB;AACtE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateSearchParams.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAClE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"validateSearchParams.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAClE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAEV,cAAc,EAEd,UAAU,EACX,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EAAE,cAAc,EAAe,MAAM,YAAY,CAAA;AAa7D,KAAK,IAAI,GAAG;IACV,gBAAgB,CAAC,EAAE,yBAAyB,CAAA;IAC5C,UAAU,EAAE,UAAU,CAAA;IACtB,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC1B,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,YAAY,CAAC,EAAE,qBAAqB,CAAA;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,IAAI,EAAE,MAAM,CAAA;IAEZ,QAAQ,EAAE,cAAc,CAAA;IACxB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,GAAG,EAAE,cAAc,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,GAAG,EAAE,OAAO,CAAA;IACZ,aAAa,CAAC,EAAE,cAAc,EAAE,CAAA;CACjC,CAAA;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,gBAAgB,EAChB,UAAU,EACV,MAAM,EACN,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,cAAc,EACd,iBAAiB,EACjB,IAAI,EAAE,YAAY,EAClB,QAAQ,EACR,eAAe,EACf,GAAG,EACH,gBAAgB,EAChB,GAAG,EACH,aAAa,GACd,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAiUtB"}
|
|
@@ -4,6 +4,7 @@ import { getEntityPermissions } from '../../utilities/getEntityPermissions/getEn
|
|
|
4
4
|
import { isolateObjectProperty } from '../../utilities/isolateObjectProperty.js';
|
|
5
5
|
import { getLocalizedPaths } from '../getLocalizedPaths.js';
|
|
6
6
|
import { isNestedRelationshipQuery } from '../isNestedRelationshipQuery.js';
|
|
7
|
+
import { constrainNestedRelationshipQuery } from '../nestedRelationshipReadConstraint.js';
|
|
7
8
|
import { prefixWherePaths } from '../prefixWherePaths.js';
|
|
8
9
|
import { hasReadAccessToQueryPath } from './hasReadAccessToQueryPath.js';
|
|
9
10
|
import { validateQueryPaths } from './validateQueryPaths.js';
|
|
@@ -61,9 +62,43 @@ import { validateQueryPaths } from './validateQueryPaths.js';
|
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
64
|
if (isNestedHasManyQuery && relatedCollectionSlug) {
|
|
65
|
+
const relatedCollectionConfig = req.payload.collections[relatedCollectionSlug].config;
|
|
66
|
+
// Resolve permissions before starting the nested validation below, so a rejection from it
|
|
67
|
+
// cannot occur while this function is still awaiting and before `Promise.all` observes it.
|
|
68
|
+
if (!overrideAccess) {
|
|
69
|
+
if (!policies.collections[relatedCollectionSlug]) {
|
|
70
|
+
policies.collections[relatedCollectionSlug] = await getEntityPermissions({
|
|
71
|
+
blockReferencesPermissions,
|
|
72
|
+
entity: relatedCollectionConfig,
|
|
73
|
+
entityType: 'collection',
|
|
74
|
+
fetchData: false,
|
|
75
|
+
operations: [
|
|
76
|
+
'read'
|
|
77
|
+
],
|
|
78
|
+
req: isolateObjectProperty(req, 'transactionID')
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const relatedCollectionReadPermission = policies.collections[relatedCollectionSlug].read;
|
|
82
|
+
if (!relatedCollectionReadPermission?.permission) {
|
|
83
|
+
errors.push({
|
|
84
|
+
path: incomingPath
|
|
85
|
+
});
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
// The nested query runs directly against the related collection, so its read access
|
|
89
|
+
// constraint must be applied to the same related documents the user's query matches.
|
|
90
|
+
// Otherwise the nested query can match documents the user cannot read.
|
|
91
|
+
if (relatedCollectionReadPermission.where) {
|
|
92
|
+
const mutableConstraint = constraint;
|
|
93
|
+
mutableConstraint[incomingPath][operator] = constrainNestedRelationshipQuery({
|
|
94
|
+
readConstraint: relatedCollectionReadPermission.where,
|
|
95
|
+
where: val
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
64
99
|
// Validate the nested query against the related collection.
|
|
65
100
|
promises.push(validateQueryPaths({
|
|
66
|
-
collectionConfig:
|
|
101
|
+
collectionConfig: relatedCollectionConfig,
|
|
67
102
|
errors,
|
|
68
103
|
overrideAccess,
|
|
69
104
|
policies,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { FlattenedField } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { HasManyRelationshipOperator, PayloadRequest, WhereField } from '../../types/index.js'\nimport type { EntityPolicies, PathToQuery } from './types.js'\n\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { hasManyRelationshipOperatorSet, SAFE_FIELD_PATH_REGEX } from '../../types/constants.js'\nimport { getEntityPermissions } from '../../utilities/getEntityPermissions/getEntityPermissions.js'\nimport { isolateObjectProperty } from '../../utilities/isolateObjectProperty.js'\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { isNestedRelationshipQuery } from '../isNestedRelationshipQuery.js'\nimport { prefixWherePaths } from '../prefixWherePaths.js'\nimport { hasReadAccessToQueryPath } from './hasReadAccessToQueryPath.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n collectionConfig?: SanitizedCollectionConfig\n constraint: WhereField\n errors: { path: string }[]\n fields: FlattenedField[]\n globalConfig?: SanitizedGlobalConfig\n operator: string\n overrideAccess: boolean\n parentIsLocalized?: boolean\n path: string\n // TODO: Rename to permissions or entityPermissions in 4.0\n policies: EntityPolicies\n polymorphicJoin?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n val: unknown\n versionFields?: FlattenedField[]\n}\n\n/**\n * Validate the Payload key / value / operator\n */\nexport async function validateSearchParam({\n collectionConfig,\n constraint,\n errors,\n fields,\n globalConfig,\n operator,\n overrideAccess,\n parentIsLocalized,\n path: incomingPath,\n policies,\n polymorphicJoin,\n req,\n showHiddenFields,\n val,\n versionFields,\n}: Args): Promise<void> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath\n if (incomingPath === '_id') {\n sanitizedPath = 'id'\n } else {\n sanitizedPath = incomingPath.replace(/__/g, '.')\n }\n let paths: PathToQuery[] = []\n const { slug } = (collectionConfig || globalConfig)!\n\n const blockReferencesPermissions = {}\n\n if (globalConfig && !policies.globals![slug]) {\n policies.globals![slug] = await getEntityPermissions({\n blockReferencesPermissions,\n entity: globalConfig,\n entityType: 'global',\n fetchData: false,\n operations: ['read'],\n req,\n })\n }\n\n if (sanitizedPath !== 'id') {\n paths = getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: sanitizedPath,\n locale: req.locale!,\n overrideAccess,\n parentIsLocalized,\n payload: req.payload,\n showHiddenFields,\n })\n }\n const promises: Promise<void>[] = []\n\n const relationshipField = paths.length === 1 ? paths[0]?.field : undefined\n const hasNestedWhere = isNestedRelationshipQuery(val)\n const relatedCollectionSlug =\n relationshipField &&\n (relationshipField.type === 'relationship' || relationshipField.type === 'upload') &&\n relationshipField.hasMany &&\n typeof relationshipField.relationTo === 'string'\n ? relationshipField.relationTo\n : undefined\n const isNestedHasManyQuery =\n hasManyRelationshipOperatorSet.has(operator as HasManyRelationshipOperator) &&\n hasNestedWhere &&\n Boolean(relatedCollectionSlug)\n\n if (operator === 'like' || operator === 'not_like' || operator === 'contains') {\n const isLegitimateNestedContains = operator === 'contains' && isNestedHasManyQuery\n const containsPlainObject =\n hasNestedWhere ||\n (Array.isArray(val) && val.some((entry) => isNestedRelationshipQuery(entry)))\n\n if (containsPlainObject && !isLegitimateNestedContains) {\n errors.push({ path: incomingPath })\n return\n }\n }\n\n if (isNestedHasManyQuery && relatedCollectionSlug) {\n // Validate the nested query against the related collection.\n promises.push(\n validateQueryPaths({\n collectionConfig: req.payload.collections[relatedCollectionSlug]!.config,\n errors,\n overrideAccess,\n policies,\n req,\n showHiddenFields,\n where: val,\n }),\n )\n }\n\n // Sanitize relation.otherRelation.id to relation.otherRelation\n if (paths.at(-1)?.path === 'id') {\n const previousField = paths.at(-2)?.field\n if (\n previousField &&\n (previousField.type === 'relationship' || previousField.type === 'upload') &&\n typeof previousField.relationTo === 'string'\n ) {\n paths.pop()\n }\n }\n\n promises.push(\n ...paths.map(async ({ collectionSlug, field, invalid, path }, i) => {\n if (invalid) {\n const isUnknownPolymorphicJoinField =\n polymorphicJoin && !field && SAFE_FIELD_PATH_REGEX.test(incomingPath)\n\n if (!isUnknownPolymorphicJoinField) {\n errors.push({ path })\n }\n\n return\n }\n\n // where: { relatedPosts: { equals: 1}} -> { 'relatedPosts.id': { equals: 1}}\n if (field.type === 'join' && path === incomingPath) {\n const mutableConstraint = constraint as Record<string, unknown>\n\n mutableConstraint[`${path}.id`] = mutableConstraint[path]\n delete mutableConstraint[path]\n }\n\n if ('virtual' in field && field.virtual) {\n if (field.virtual === true) {\n errors.push({ path })\n }\n }\n\n if (polymorphicJoin && path === 'relationTo') {\n return\n }\n\n if (!overrideAccess && fieldAffectsData(field)) {\n if (collectionSlug) {\n if (!policies.collections![collectionSlug]) {\n policies.collections![collectionSlug] = await getEntityPermissions({\n blockReferencesPermissions,\n entity: req.payload.collections[collectionSlug]!.config,\n entityType: 'collection',\n fetchData: false,\n operations: ['read'],\n req: isolateObjectProperty(req, 'transactionID'),\n })\n }\n\n if (\n ['hash', 'salt'].includes(incomingPath) &&\n collectionConfig!.auth &&\n !collectionConfig!.auth?.disableLocalStrategy\n ) {\n errors.push({ path: incomingPath })\n }\n\n const relatedCollectionReadPermission = policies.collections![collectionSlug].read\n const previousSegment = paths[i - 1]\n const traversedField = previousSegment?.field\n const isRelationshipHop =\n Boolean(traversedField) &&\n (traversedField!.type === 'relationship' ||\n traversedField!.type === 'upload' ||\n traversedField!.type === 'join')\n\n if (\n isRelationshipHop &&\n relatedCollectionReadPermission &&\n typeof relatedCollectionReadPermission === 'object' &&\n relatedCollectionReadPermission.where\n ) {\n const relationshipPath = paths\n .slice(0, i)\n .map(({ path: pathToRelationship }) => pathToRelationship)\n .join('.')\n\n const mutableWhere = constraint as Record<string, unknown>\n const existingAnd = Array.isArray(mutableWhere.and) ? mutableWhere.and : []\n\n // Has-many relationships and joins can point to many related documents, so the user's\n // filter and the access constraint must be satisfied by the SAME related document.\n // Scoping both into a single `contains` prevents a different, readable document from\n // masking one the user cannot read (a related-document oracle).\n const isHasManyRelationship =\n (traversedField!.type === 'relationship' || traversedField!.type === 'upload') &&\n traversedField!.hasMany\n const isJoin = traversedField!.type === 'join'\n\n if (isHasManyRelationship || isJoin) {\n const relatedFieldPath = paths.at(-1)?.path\n\n if (relatedFieldPath) {\n mutableWhere.and = [\n ...existingAnd,\n {\n [relationshipPath]: {\n contains: {\n and: [\n {\n [relatedFieldPath]: {\n [operator]: val,\n },\n },\n relatedCollectionReadPermission.where,\n ],\n },\n },\n },\n ]\n\n // The scoped `contains` above fully replaces the user's original filter;\n // so we can remove it from the top-level where clause\n delete mutableWhere[incomingPath]\n }\n } else {\n const accessWhere = prefixWherePaths({\n prefix: relationshipPath,\n where: relatedCollectionReadPermission.where,\n })\n\n mutableWhere.and = [...existingAnd, accessWhere]\n }\n }\n }\n let fieldPath = path\n // remove locale from end of path\n if (path.endsWith(`.${req.locale}`)) {\n fieldPath = path.slice(0, -(req.locale!.length + 1))\n }\n // remove \".value\" from ends of polymorphic relationship paths\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(field.relationTo)\n ) {\n fieldPath = fieldPath.replace('.value', '')\n }\n\n const entityType: 'collections' | 'globals' = collectionSlug ? 'collections' : 'globals'\n const entitySlug = collectionSlug || globalConfig!.slug\n const segments = fieldPath.split('.')\n\n if (versionFields && ['latest', 'parent', 'snapshot', 'version'].includes(segments[0]!)) {\n segments.shift()\n }\n\n const entity = collectionSlug\n ? req.payload.collections[collectionSlug]!.config\n : globalConfig!\n\n if (\n segments.length &&\n hasReadAccessToQueryPath({\n fields: entity.flattenedFields,\n permissions: policies[entityType]![entitySlug]!.fields,\n req,\n resolvedField: field,\n segments,\n shouldShowHiddenFields: showHiddenFields,\n }) !== true\n ) {\n errors.push({ path: fieldPath })\n }\n }\n\n if (!isNestedHasManyQuery && i > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n pathsToQuery.forEach(\n ({ collectionSlug: pathCollectionSlug, path: subPath }, pathToQueryIndex) => {\n // On the \"deepest\" collection,\n // validate query of the relationship\n if (pathToQueryIndex === 0) {\n promises.push(\n validateQueryPaths({\n collectionConfig: req.payload.collections[pathCollectionSlug!]!.config,\n errors,\n globalConfig: undefined,\n overrideAccess,\n policies,\n req,\n showHiddenFields,\n where: {\n [subPath]: {\n [operator]: val,\n },\n },\n }),\n )\n }\n },\n )\n }\n }),\n )\n await Promise.all(promises)\n}\n"],"names":["fieldAffectsData","hasManyRelationshipOperatorSet","SAFE_FIELD_PATH_REGEX","getEntityPermissions","isolateObjectProperty","getLocalizedPaths","isNestedRelationshipQuery","prefixWherePaths","hasReadAccessToQueryPath","validateQueryPaths","validateSearchParam","collectionConfig","constraint","errors","fields","globalConfig","operator","overrideAccess","parentIsLocalized","path","incomingPath","policies","polymorphicJoin","req","showHiddenFields","val","versionFields","sanitizedPath","replace","paths","slug","blockReferencesPermissions","globals","entity","entityType","fetchData","operations","collectionSlug","globalSlug","locale","payload","promises","relationshipField","length","field","undefined","hasNestedWhere","relatedCollectionSlug","type","hasMany","relationTo","isNestedHasManyQuery","has","Boolean","isLegitimateNestedContains","containsPlainObject","Array","isArray","some","entry","push","collections","config","where","at","previousField","pop","map","invalid","i","isUnknownPolymorphicJoinField","test","mutableConstraint","virtual","includes","auth","disableLocalStrategy","relatedCollectionReadPermission","read","previousSegment","traversedField","isRelationshipHop","relationshipPath","slice","pathToRelationship","join","mutableWhere","existingAnd","and","isHasManyRelationship","isJoin","relatedFieldPath","contains","accessWhere","prefix","fieldPath","endsWith","entitySlug","segments","split","shift","flattenedFields","permissions","resolvedField","shouldShowHiddenFields","pathsToQuery","reverse","forEach","pathCollectionSlug","subPath","pathToQueryIndex","Promise","all"],"mappings":"AAMA,SAASA,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,8BAA8B,EAAEC,qBAAqB,QAAQ,2BAA0B;AAChG,SAASC,oBAAoB,QAAQ,+DAA8D;AACnG,SAASC,qBAAqB,QAAQ,2CAA0C;AAChF,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,yBAAyB,QAAQ,kCAAiC;AAC3E,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,kBAAkB,QAAQ,0BAAyB;AAqB5D;;CAEC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,gBAAgB,EAChBC,UAAU,EACVC,MAAM,EACNC,MAAM,EACNC,YAAY,EACZC,QAAQ,EACRC,cAAc,EACdC,iBAAiB,EACjBC,MAAMC,YAAY,EAClBC,QAAQ,EACRC,eAAe,EACfC,GAAG,EACHC,gBAAgB,EAChBC,GAAG,EACHC,aAAa,EACR;IACL,4DAA4D;IAC5D,IAAIC;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ACF;gBAEJ;YACF;QAEJ;IACF;IAEF,MAAMsF,QAAQC,GAAG,CAACvE;AACpB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { FlattenedField } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type {\n HasManyRelationshipOperator,\n PayloadRequest,\n Where,\n WhereField,\n} from '../../types/index.js'\nimport type { EntityPolicies, PathToQuery } from './types.js'\n\nimport { fieldAffectsData } from '../../fields/config/types.js'\nimport { hasManyRelationshipOperatorSet, SAFE_FIELD_PATH_REGEX } from '../../types/constants.js'\nimport { getEntityPermissions } from '../../utilities/getEntityPermissions/getEntityPermissions.js'\nimport { isolateObjectProperty } from '../../utilities/isolateObjectProperty.js'\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { isNestedRelationshipQuery } from '../isNestedRelationshipQuery.js'\nimport { constrainNestedRelationshipQuery } from '../nestedRelationshipReadConstraint.js'\nimport { prefixWherePaths } from '../prefixWherePaths.js'\nimport { hasReadAccessToQueryPath } from './hasReadAccessToQueryPath.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n collectionConfig?: SanitizedCollectionConfig\n constraint: WhereField\n errors: { path: string }[]\n fields: FlattenedField[]\n globalConfig?: SanitizedGlobalConfig\n operator: string\n overrideAccess: boolean\n parentIsLocalized?: boolean\n path: string\n // TODO: Rename to permissions or entityPermissions in 4.0\n policies: EntityPolicies\n polymorphicJoin?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n val: unknown\n versionFields?: FlattenedField[]\n}\n\n/**\n * Validate the Payload key / value / operator\n */\nexport async function validateSearchParam({\n collectionConfig,\n constraint,\n errors,\n fields,\n globalConfig,\n operator,\n overrideAccess,\n parentIsLocalized,\n path: incomingPath,\n policies,\n polymorphicJoin,\n req,\n showHiddenFields,\n val,\n versionFields,\n}: Args): Promise<void> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath\n if (incomingPath === '_id') {\n sanitizedPath = 'id'\n } else {\n sanitizedPath = incomingPath.replace(/__/g, '.')\n }\n let paths: PathToQuery[] = []\n const { slug } = (collectionConfig || globalConfig)!\n\n const blockReferencesPermissions = {}\n\n if (globalConfig && !policies.globals![slug]) {\n policies.globals![slug] = await getEntityPermissions({\n blockReferencesPermissions,\n entity: globalConfig,\n entityType: 'global',\n fetchData: false,\n operations: ['read'],\n req,\n })\n }\n\n if (sanitizedPath !== 'id') {\n paths = getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: sanitizedPath,\n locale: req.locale!,\n overrideAccess,\n parentIsLocalized,\n payload: req.payload,\n showHiddenFields,\n })\n }\n const promises: Promise<void>[] = []\n\n const relationshipField = paths.length === 1 ? paths[0]?.field : undefined\n const hasNestedWhere = isNestedRelationshipQuery(val)\n const relatedCollectionSlug =\n relationshipField &&\n (relationshipField.type === 'relationship' || relationshipField.type === 'upload') &&\n relationshipField.hasMany &&\n typeof relationshipField.relationTo === 'string'\n ? relationshipField.relationTo\n : undefined\n const isNestedHasManyQuery =\n hasManyRelationshipOperatorSet.has(operator as HasManyRelationshipOperator) &&\n hasNestedWhere &&\n Boolean(relatedCollectionSlug)\n\n if (operator === 'like' || operator === 'not_like' || operator === 'contains') {\n const isLegitimateNestedContains = operator === 'contains' && isNestedHasManyQuery\n const containsPlainObject =\n hasNestedWhere ||\n (Array.isArray(val) && val.some((entry) => isNestedRelationshipQuery(entry)))\n\n if (containsPlainObject && !isLegitimateNestedContains) {\n errors.push({ path: incomingPath })\n return\n }\n }\n\n if (isNestedHasManyQuery && relatedCollectionSlug) {\n const relatedCollectionConfig = req.payload.collections[relatedCollectionSlug]!.config\n\n // Resolve permissions before starting the nested validation below, so a rejection from it\n // cannot occur while this function is still awaiting and before `Promise.all` observes it.\n if (!overrideAccess) {\n if (!policies.collections![relatedCollectionSlug]) {\n policies.collections![relatedCollectionSlug] = await getEntityPermissions({\n blockReferencesPermissions,\n entity: relatedCollectionConfig,\n entityType: 'collection',\n fetchData: false,\n operations: ['read'],\n req: isolateObjectProperty(req, 'transactionID'),\n })\n }\n\n const relatedCollectionReadPermission = policies.collections![relatedCollectionSlug].read\n\n if (!relatedCollectionReadPermission?.permission) {\n errors.push({ path: incomingPath })\n return\n }\n\n // The nested query runs directly against the related collection, so its read access\n // constraint must be applied to the same related documents the user's query matches.\n // Otherwise the nested query can match documents the user cannot read.\n if (relatedCollectionReadPermission.where) {\n const mutableConstraint = constraint as Record<string, Record<string, unknown>>\n\n mutableConstraint[incomingPath]![operator] = constrainNestedRelationshipQuery({\n readConstraint: relatedCollectionReadPermission.where,\n where: val as Where,\n })\n }\n }\n\n // Validate the nested query against the related collection.\n promises.push(\n validateQueryPaths({\n collectionConfig: relatedCollectionConfig,\n errors,\n overrideAccess,\n policies,\n req,\n showHiddenFields,\n where: val,\n }),\n )\n }\n\n // Sanitize relation.otherRelation.id to relation.otherRelation\n if (paths.at(-1)?.path === 'id') {\n const previousField = paths.at(-2)?.field\n if (\n previousField &&\n (previousField.type === 'relationship' || previousField.type === 'upload') &&\n typeof previousField.relationTo === 'string'\n ) {\n paths.pop()\n }\n }\n\n promises.push(\n ...paths.map(async ({ collectionSlug, field, invalid, path }, i) => {\n if (invalid) {\n const isUnknownPolymorphicJoinField =\n polymorphicJoin && !field && SAFE_FIELD_PATH_REGEX.test(incomingPath)\n\n if (!isUnknownPolymorphicJoinField) {\n errors.push({ path })\n }\n\n return\n }\n\n // where: { relatedPosts: { equals: 1}} -> { 'relatedPosts.id': { equals: 1}}\n if (field.type === 'join' && path === incomingPath) {\n const mutableConstraint = constraint as Record<string, unknown>\n\n mutableConstraint[`${path}.id`] = mutableConstraint[path]\n delete mutableConstraint[path]\n }\n\n if ('virtual' in field && field.virtual) {\n if (field.virtual === true) {\n errors.push({ path })\n }\n }\n\n if (polymorphicJoin && path === 'relationTo') {\n return\n }\n\n if (!overrideAccess && fieldAffectsData(field)) {\n if (collectionSlug) {\n if (!policies.collections![collectionSlug]) {\n policies.collections![collectionSlug] = await getEntityPermissions({\n blockReferencesPermissions,\n entity: req.payload.collections[collectionSlug]!.config,\n entityType: 'collection',\n fetchData: false,\n operations: ['read'],\n req: isolateObjectProperty(req, 'transactionID'),\n })\n }\n\n if (\n ['hash', 'salt'].includes(incomingPath) &&\n collectionConfig!.auth &&\n !collectionConfig!.auth?.disableLocalStrategy\n ) {\n errors.push({ path: incomingPath })\n }\n\n const relatedCollectionReadPermission = policies.collections![collectionSlug].read\n const previousSegment = paths[i - 1]\n const traversedField = previousSegment?.field\n const isRelationshipHop =\n Boolean(traversedField) &&\n (traversedField!.type === 'relationship' ||\n traversedField!.type === 'upload' ||\n traversedField!.type === 'join')\n\n if (\n isRelationshipHop &&\n relatedCollectionReadPermission &&\n typeof relatedCollectionReadPermission === 'object' &&\n relatedCollectionReadPermission.where\n ) {\n const relationshipPath = paths\n .slice(0, i)\n .map(({ path: pathToRelationship }) => pathToRelationship)\n .join('.')\n\n const mutableWhere = constraint as Record<string, unknown>\n const existingAnd = Array.isArray(mutableWhere.and) ? mutableWhere.and : []\n\n // Has-many relationships and joins can point to many related documents, so the user's\n // filter and the access constraint must be satisfied by the SAME related document.\n // Scoping both into a single `contains` prevents a different, readable document from\n // masking one the user cannot read (a related-document oracle).\n const isHasManyRelationship =\n (traversedField!.type === 'relationship' || traversedField!.type === 'upload') &&\n traversedField!.hasMany\n const isJoin = traversedField!.type === 'join'\n\n if (isHasManyRelationship || isJoin) {\n const relatedFieldPath = paths.at(-1)?.path\n\n if (relatedFieldPath) {\n mutableWhere.and = [\n ...existingAnd,\n {\n [relationshipPath]: {\n contains: {\n and: [\n {\n [relatedFieldPath]: {\n [operator]: val,\n },\n },\n relatedCollectionReadPermission.where,\n ],\n },\n },\n },\n ]\n\n // The scoped `contains` above fully replaces the user's original filter;\n // so we can remove it from the top-level where clause\n delete mutableWhere[incomingPath]\n }\n } else {\n const accessWhere = prefixWherePaths({\n prefix: relationshipPath,\n where: relatedCollectionReadPermission.where,\n })\n\n mutableWhere.and = [...existingAnd, accessWhere]\n }\n }\n }\n let fieldPath = path\n // remove locale from end of path\n if (path.endsWith(`.${req.locale}`)) {\n fieldPath = path.slice(0, -(req.locale!.length + 1))\n }\n // remove \".value\" from ends of polymorphic relationship paths\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(field.relationTo)\n ) {\n fieldPath = fieldPath.replace('.value', '')\n }\n\n const entityType: 'collections' | 'globals' = collectionSlug ? 'collections' : 'globals'\n const entitySlug = collectionSlug || globalConfig!.slug\n const segments = fieldPath.split('.')\n\n if (versionFields && ['latest', 'parent', 'snapshot', 'version'].includes(segments[0]!)) {\n segments.shift()\n }\n\n const entity = collectionSlug\n ? req.payload.collections[collectionSlug]!.config\n : globalConfig!\n\n if (\n segments.length &&\n hasReadAccessToQueryPath({\n fields: entity.flattenedFields,\n permissions: policies[entityType]![entitySlug]!.fields,\n req,\n resolvedField: field,\n segments,\n shouldShowHiddenFields: showHiddenFields,\n }) !== true\n ) {\n errors.push({ path: fieldPath })\n }\n }\n\n if (!isNestedHasManyQuery && i > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n pathsToQuery.forEach(\n ({ collectionSlug: pathCollectionSlug, path: subPath }, pathToQueryIndex) => {\n // On the \"deepest\" collection,\n // validate query of the relationship\n if (pathToQueryIndex === 0) {\n promises.push(\n validateQueryPaths({\n collectionConfig: req.payload.collections[pathCollectionSlug!]!.config,\n errors,\n globalConfig: undefined,\n overrideAccess,\n policies,\n req,\n showHiddenFields,\n where: {\n [subPath]: {\n [operator]: val,\n },\n },\n }),\n )\n }\n },\n )\n }\n }),\n )\n await Promise.all(promises)\n}\n"],"names":["fieldAffectsData","hasManyRelationshipOperatorSet","SAFE_FIELD_PATH_REGEX","getEntityPermissions","isolateObjectProperty","getLocalizedPaths","isNestedRelationshipQuery","constrainNestedRelationshipQuery","prefixWherePaths","hasReadAccessToQueryPath","validateQueryPaths","validateSearchParam","collectionConfig","constraint","errors","fields","globalConfig","operator","overrideAccess","parentIsLocalized","path","incomingPath","policies","polymorphicJoin","req","showHiddenFields","val","versionFields","sanitizedPath","replace","paths","slug","blockReferencesPermissions","globals","entity","entityType","fetchData","operations","collectionSlug","globalSlug","locale","payload","promises","relationshipField","length","field","undefined","hasNestedWhere","relatedCollectionSlug","type","hasMany","relationTo","isNestedHasManyQuery","has","Boolean","isLegitimateNestedContains","containsPlainObject","Array","isArray","some","entry","push","relatedCollectionConfig","collections","config","relatedCollectionReadPermission","read","permission","where","mutableConstraint","readConstraint","at","previousField","pop","map","invalid","i","isUnknownPolymorphicJoinField","test","virtual","includes","auth","disableLocalStrategy","previousSegment","traversedField","isRelationshipHop","relationshipPath","slice","pathToRelationship","join","mutableWhere","existingAnd","and","isHasManyRelationship","isJoin","relatedFieldPath","contains","accessWhere","prefix","fieldPath","endsWith","entitySlug","segments","split","shift","flattenedFields","permissions","resolvedField","shouldShowHiddenFields","pathsToQuery","reverse","forEach","pathCollectionSlug","subPath","pathToQueryIndex","Promise","all"],"mappings":"AAWA,SAASA,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,8BAA8B,EAAEC,qBAAqB,QAAQ,2BAA0B;AAChG,SAASC,oBAAoB,QAAQ,+DAA8D;AACnG,SAASC,qBAAqB,QAAQ,2CAA0C;AAChF,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,yBAAyB,QAAQ,kCAAiC;AAC3E,SAASC,gCAAgC,QAAQ,yCAAwC;AACzF,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,kBAAkB,QAAQ,0BAAyB;AAqB5D;;CAEC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,gBAAgB,EAChBC,UAAU,EACVC,MAAM,EACNC,MAAM,EACNC,YAA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AK;YAChB;YAEA,MAAMtE,SAASI,iBACXd,IAAIiB,OAAO,CAACsB,WAAW,CAACzB,eAAe,CAAE0B,MAAM,GAC/ChD;YAEJ,IACEsF,SAAS1D,MAAM,IACfnC,yBAAyB;gBACvBM,QAAQmB,OAAOuE,eAAe;gBAC9BC,aAAapF,QAAQ,CAACa,WAAW,AAAC,CAACkE,WAAW,CAAEtF,MAAM;gBACtDS;gBACAmF,eAAe9D;gBACfyD;gBACAM,wBAAwBnF;YAC1B,OAAO,MACP;gBACAX,OAAO+C,IAAI,CAAC;oBAAEzC,MAAM+E;gBAAU;YAChC;QACF;QAEA,IAAI,CAAC/C,wBAAwBwB,IAAI,GAAG;YAClC,0CAA0C;YAC1C,6BAA6B;YAC7B,MAAMiC,eAAe/E,MAAMyD,KAAK,CAAC,GAAGuB,OAAO;YAE3CD,aAAaE,OAAO,CAClB,CAAC,EAAEzE,gBAAgB0E,kBAAkB,EAAE5F,MAAM6F,OAAO,EAAE,EAAEC;gBACtD,+BAA+B;gBAC/B,qCAAqC;gBACrC,IAAIA,qBAAqB,GAAG;oBAC1BxE,SAASmB,IAAI,CACXnD,mBAAmB;wBACjBE,kBAAkBY,IAAIiB,OAAO,CAACsB,WAAW,CAACiD,mBAAoB,CAAEhD,MAAM;wBACtElD;wBACAE,cAAc8B;wBACd5B;wBACAI;wBACAE;wBACAC;wBACA2C,OAAO;4BACL,CAAC6C,QAAQ,EAAE;gCACT,CAAChG,SAAS,EAAES;4BACd;wBACF;oBACF;gBAEJ;YACF;QAEJ;IACF;IAEF,MAAMyF,QAAQC,GAAG,CAAC1E;AACpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateSortQuery.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSortQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAClE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAS,MAAM,sBAAsB,CAAA;AAKvE,KAAK,IAAI,GAAG;IACV,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,aAAa,CAAC,EAAE,cAAc,EAAE,CAAA;CACjC,GAAG,CACA;IACE,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,YAAY,CAAC,EAAE,SAAS,CAAA;CACzB,GACD;IACE,gBAAgB,CAAC,EAAE,SAAS,CAAA;IAC5B,YAAY,EAAE,qBAAqB,CAAA;CACpC,CACJ,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,kFAO3B,IAAI,KAAG,OAAO,CAAC,IAAI,
|
|
1
|
+
{"version":3,"file":"validateSortQuery.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSortQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAClE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAS,MAAM,sBAAsB,CAAA;AAKvE,KAAK,IAAI,GAAG;IACV,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,aAAa,CAAC,EAAE,cAAc,EAAE,CAAA;CACjC,GAAG,CACA;IACE,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,YAAY,CAAC,EAAE,SAAS,CAAA;CACzB,GACD;IACE,gBAAgB,CAAC,EAAE,SAAS,CAAA;IAC5B,YAAY,EAAE,qBAAqB,CAAA;CACpC,CACJ,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,kFAO3B,IAAI,KAAG,OAAO,CAAC,IAAI,CAiDrB,CAAA"}
|
|
@@ -14,14 +14,16 @@ import { validateQueryPaths } from './validateQueryPaths.js';
|
|
|
14
14
|
const where = {};
|
|
15
15
|
for (const sortField of sortFields){
|
|
16
16
|
const path = sortField.replace(/^-/, '').replace(/__/g, '.');
|
|
17
|
+
// Hidden fields must resolve here, including across relationships, so that
|
|
18
|
+
// validateQueryPaths can reject them instead of the sort path being skipped.
|
|
17
19
|
const paths = getLocalizedPaths({
|
|
18
20
|
collectionSlug: collectionConfig?.slug,
|
|
19
21
|
fields,
|
|
20
22
|
globalSlug: globalConfig?.slug,
|
|
21
23
|
incomingPath: path,
|
|
22
24
|
locale: req.locale,
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
payload: req.payload,
|
|
26
|
+
showHiddenFields: true
|
|
25
27
|
});
|
|
26
28
|
if (path !== 'id' && path !== '_id' && paths.every(({ invalid })=>!invalid)) {
|
|
27
29
|
where[path] = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/database/queryValidation/validateSortQuery.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { FlattenedField } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { PayloadRequest, Sort, Where } from '../../types/index.js'\n\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n overrideAccess: boolean\n req: PayloadRequest\n sort?: Sort\n versionFields?: FlattenedField[]\n} & (\n | {\n collectionConfig: SanitizedCollectionConfig\n globalConfig?: undefined\n }\n | {\n collectionConfig?: undefined\n globalConfig: SanitizedGlobalConfig\n }\n)\n\n/**\n * Ensures sort paths are subject to the same field-read access checks as query `where` paths,\n * since database sorting happens before response-time field redaction.\n */\nexport const validateSortQuery = async ({\n collectionConfig,\n globalConfig,\n overrideAccess,\n req,\n sort,\n versionFields,\n}: Args): Promise<void> => {\n if (overrideAccess || !sort) {\n return\n }\n\n const fields = versionFields || (globalConfig || collectionConfig).flattenedFields\n const sortFields = Array.isArray(sort) ? sort : [sort]\n const where: Where = {}\n\n for (const sortField of sortFields) {\n const path = sortField.replace(/^-/, '').replace(/__/g, '.')\n const paths = getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: path,\n locale: req.locale!,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/database/queryValidation/validateSortQuery.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { FlattenedField } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { PayloadRequest, Sort, Where } from '../../types/index.js'\n\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n overrideAccess: boolean\n req: PayloadRequest\n sort?: Sort\n versionFields?: FlattenedField[]\n} & (\n | {\n collectionConfig: SanitizedCollectionConfig\n globalConfig?: undefined\n }\n | {\n collectionConfig?: undefined\n globalConfig: SanitizedGlobalConfig\n }\n)\n\n/**\n * Ensures sort paths are subject to the same field-read access checks as query `where` paths,\n * since database sorting happens before response-time field redaction.\n */\nexport const validateSortQuery = async ({\n collectionConfig,\n globalConfig,\n overrideAccess,\n req,\n sort,\n versionFields,\n}: Args): Promise<void> => {\n if (overrideAccess || !sort) {\n return\n }\n\n const fields = versionFields || (globalConfig || collectionConfig).flattenedFields\n const sortFields = Array.isArray(sort) ? sort : [sort]\n const where: Where = {}\n\n for (const sortField of sortFields) {\n const path = sortField.replace(/^-/, '').replace(/__/g, '.')\n // Hidden fields must resolve here, including across relationships, so that\n // validateQueryPaths can reject them instead of the sort path being skipped.\n const paths = getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: path,\n locale: req.locale!,\n payload: req.payload,\n showHiddenFields: true,\n })\n\n if (path !== 'id' && path !== '_id' && paths.every(({ invalid }) => !invalid)) {\n where[path] = { exists: true }\n }\n }\n\n if (Object.keys(where).length === 0) {\n return\n }\n\n if (collectionConfig) {\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n versionFields,\n where,\n })\n } else {\n await validateQueryPaths({\n globalConfig,\n overrideAccess,\n req,\n versionFields,\n where,\n })\n }\n}\n"],"names":["getLocalizedPaths","validateQueryPaths","validateSortQuery","collectionConfig","globalConfig","overrideAccess","req","sort","versionFields","fields","flattenedFields","sortFields","Array","isArray","where","sortField","path","replace","paths","collectionSlug","slug","globalSlug","incomingPath","locale","payload","showHiddenFields","every","invalid","exists","Object","keys","length"],"mappings":"AAKA,SAASA,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,kBAAkB,QAAQ,0BAAyB;AAkB5D;;;CAGC,GACD,OAAO,MAAMC,oBAAoB,OAAO,EACtCC,gBAAgB,EAChBC,YAAY,EACZC,cAAc,EACdC,GAAG,EACHC,IAAI,EACJC,aAAa,EACR;IACL,IAAIH,kBAAkB,CAACE,MAAM;QAC3B;IACF;IAEA,MAAME,SAASD,iBAAiB,AAACJ,CAAAA,gBAAgBD,gBAAe,EAAGO,eAAe;IAClF,MAAMC,aAAaC,MAAMC,OAAO,CAACN,QAAQA,OAAO;QAACA;KAAK;IACtD,MAAMO,QAAe,CAAC;IAEtB,KAAK,MAAMC,aAAaJ,WAAY;QAClC,MAAMK,OAAOD,UAAUE,OAAO,CAAC,MAAM,IAAIA,OAAO,CAAC,OAAO;QACxD,2EAA2E;QAC3E,6EAA6E;QAC7E,MAAMC,QAAQlB,kBAAkB;YAC9BmB,gBAAgBhB,kBAAkBiB;YAClCX;YACAY,YAAYjB,cAAcgB;YAC1BE,cAAcN;YACdO,QAAQjB,IAAIiB,MAAM;YAClBC,SAASlB,IAAIkB,OAAO;YACpBC,kBAAkB;QACpB;QAEA,IAAIT,SAAS,QAAQA,SAAS,SAASE,MAAMQ,KAAK,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAK,CAACA,UAAU;YAC7Eb,KAAK,CAACE,KAAK,GAAG;gBAAEY,QAAQ;YAAK;QAC/B;IACF;IAEA,IAAIC,OAAOC,IAAI,CAAChB,OAAOiB,MAAM,KAAK,GAAG;QACnC;IACF;IAEA,IAAI5B,kBAAkB;QACpB,MAAMF,mBAAmB;YACvBE;YACAE;YACAC;YACAE;YACAM;QACF;IACF,OAAO;QACL,MAAMb,mBAAmB;YACvBG;YACAC;YACAC;YACAE;YACAM;QACF;IACF;AACF,EAAC"}
|
|
@@ -7,6 +7,7 @@ export { createCLI } from '../cli/index.js';
|
|
|
7
7
|
export { getCommandInput } from '../cli/runtime/getCommandInput.js';
|
|
8
8
|
export { createSchemaBuildContext } from '../database/createSchemaBuildContext.js';
|
|
9
9
|
export type { SchemaBuildContext } from '../database/createSchemaBuildContext.js';
|
|
10
|
+
export { getNestedRelationshipReadConstraint } from '../database/nestedRelationshipReadConstraint.js';
|
|
10
11
|
export { getLLMInstructions } from '../llm-instructions/getInstructions.js';
|
|
11
12
|
export { assertClientUploadAccess } from '../uploads/assertClientUploadAccess.js';
|
|
12
13
|
export { assertClientUploadAllowed } from '../uploads/assertClientUploadAllowed.js';
|