payload 4.0.0-beta.3 → 4.0.0-beta.5
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/adapters/router.d.ts +1 -1
- package/dist/admin/adapters/router.d.ts.map +1 -1
- package/dist/admin/adapters/router.js.map +1 -1
- package/dist/admin/initAdminContext.js.map +1 -1
- package/dist/auth/getFieldsToSign.js.map +1 -1
- package/dist/auth/loginWithCookie.js.map +1 -1
- package/dist/auth/operations/resetPassword.d.ts.map +1 -1
- package/dist/auth/operations/resetPassword.js +50 -1
- package/dist/auth/operations/resetPassword.js.map +1 -1
- package/dist/auth/serverFunctions/cookies.js.map +1 -1
- package/dist/auth/serverFunctions/login.js.map +1 -1
- package/dist/cli/defineCLICommand.js +1 -1
- package/dist/cli/defineCLICommand.js.map +1 -1
- package/dist/collections/config/client.js.map +1 -1
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/collections/operations/findVersionByID.js.map +1 -1
- package/dist/collections/operations/findVersions.js.map +1 -1
- package/dist/collections/operations/local/findDistinct.js.map +1 -1
- package/dist/collections/operations/renameFile.js +1 -1
- package/dist/collections/operations/renameFile.js.map +1 -1
- package/dist/collections/operations/utilities/update.js +1 -1
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/collections/operations/validate.js +4 -4
- package/dist/collections/operations/validate.js.map +1 -1
- package/dist/config/definePlugin.js +3 -1
- package/dist/config/definePlugin.js.map +1 -1
- package/dist/config/sanitize.js +2 -2
- package/dist/config/sanitize.js.map +1 -1
- package/dist/exports/build-config.d.ts +9 -0
- package/dist/exports/build-config.d.ts.map +1 -0
- package/dist/exports/build-config.js +38 -0
- package/dist/exports/build-config.js.map +1 -0
- package/dist/exports/internal.d.ts +1 -1
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js +1 -1
- package/dist/exports/internal.js.map +1 -1
- package/dist/fields/config/client.js.map +1 -1
- package/dist/fields/hooks/afterChange/promise.js.map +1 -1
- package/dist/fields/validations.d.ts.map +1 -1
- package/dist/fields/validations.js +4 -1
- package/dist/fields/validations.js.map +1 -1
- package/dist/globals/operations/local/findOne.js.map +1 -1
- package/dist/globals/operations/local/update.js.map +1 -1
- package/dist/globals/operations/restoreVersion.d.ts +2 -3
- package/dist/globals/operations/restoreVersion.d.ts.map +1 -1
- package/dist/globals/operations/restoreVersion.js +22 -15
- package/dist/globals/operations/restoreVersion.js.map +1 -1
- package/dist/globals/operations/validate.js +1 -1
- package/dist/globals/operations/validate.js.map +1 -1
- package/dist/hierarchy/createFolderField.js.map +1 -1
- package/dist/hierarchy/resolveHierarchyCollections.js +2 -2
- package/dist/hierarchy/resolveHierarchyCollections.js.map +1 -1
- package/dist/hierarchy/utils/computePaths.d.ts.map +1 -1
- package/dist/hierarchy/utils/computePaths.js.map +1 -1
- package/dist/index.bundled.d.ts +17 -4
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js +1 -1
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js.map +1 -1
- package/dist/uploads/clientUploadReceipt.d.ts +15 -1
- package/dist/uploads/clientUploadReceipt.d.ts.map +1 -1
- package/dist/uploads/clientUploadReceipt.js +35 -6
- package/dist/uploads/clientUploadReceipt.js.map +1 -1
- package/dist/uploads/fileVersioning/archive.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/getFileFromUploadInstructions.d.ts.map +1 -1
- package/dist/uploads/getFileFromUploadInstructions.js +42 -0
- package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
- package/dist/uploads/safeFetch.js.map +1 -1
- package/dist/uploads/stagedUpload.js.map +1 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.js +11 -2
- package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
- package/dist/uploads/types.d.ts +5 -1
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.d.ts.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js +0 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js.map +1 -1
- package/dist/utilities/appendDateTimezoneSelectFields.js.map +1 -1
- package/dist/utilities/cloneValidationRequest.js.map +1 -1
- package/dist/utilities/createPayloadRequest.js.map +1 -1
- package/dist/utilities/deepCopyObject.js.map +1 -1
- package/dist/utilities/documentMatchingWhereExists.js +1 -1
- package/dist/utilities/documentMatchingWhereExists.js.map +1 -1
- package/dist/utilities/filterDataToSelectedLocales.js.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.d.ts.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js +1 -0
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
- package/dist/utilities/parseParams/index.js.map +1 -1
- package/dist/utilities/parseValidationLocale.js.map +1 -1
- package/dist/utilities/sanitizePopulateParam.js.map +1 -1
- package/dist/utilities/telemetry/featureInfo/getFeatureInfo.js.map +1 -1
- package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
- package/package.json +11 -9
- package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { UserSession } from '../../../auth/types.js'\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { removeExpiredSessions } from '../../../auth/sessions.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { ValidationError } from '../../../errors/index.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { runLocalFileUpdate } from '../../../uploads/fileVersioning/archive.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport { getTopLevelFieldNames } from '../../../utilities/getTopLevelFieldNames.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { resolvePublishAllLocales } from '../../../utilities/resolvePublishAllLocales.js'\nimport {\n buildAllLocalesPublicationHookDoc,\n getAllLocalesPublicationStatus,\n hasAuthorizedAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../../versions/allLocalesPublicationStatus.js'\nimport { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js'\nimport { validateLocalWithLocaleKeyedData } from '../local/validate.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n select: SelectType\n shouldManageLocalFiles: boolean\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n} & Pick<Required<SharedLocalAPIOptions>, 'overrideAccess'>\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n req,\n select,\n shouldManageLocalFiles,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const nextFileData =\n collectionConfig.upload && shouldManageLocalFiles && !collectionConfig.upload.fileOperations\n ? deepCopyObjectSimple(data)\n : undefined\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const publishAllLocales = resolvePublishAllLocales({\n draft: draftArg,\n hasLocalizeStatusEnabled: hasLocalizeStatusEnabled(collectionConfig),\n locale,\n publishAllLocalesArg,\n })\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const allLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(config.localization && hasLocalizeStatusEnabled(collectionConfig)),\n publishAllLocales,\n unpublishAllLocales,\n })\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n if (allLocalesPublicationStatus || isSavingDraft) {\n data._status = allLocalesPublicationStatus ?? 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n const shouldLimitValidationToSubmittedFields =\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n unpublishAllLocales\n const submittedTopLevelFieldNames = shouldLimitValidationToSubmittedFields\n ? getTopLevelFieldNames(data)\n : undefined\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it during the update would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n const hasManagedLocalUpload =\n filesToUpload.length > 0 &&\n Boolean(data.original) &&\n !collectionConfig.upload.disableLocalStorage\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n let statusFieldAccess = false\n const publicationFieldPolicyDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status: data._status === allLocalesPublicationStatus ? allLocalesPublicationStatus : undefined,\n })\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n docForHooks: publicationFieldPolicyDoc,\n global: null,\n onFieldAccess: ({ accessResult, path }) => {\n if (path === '_status') {\n statusFieldAccess = accessResult\n }\n },\n operation: 'update',\n overrideAccess,\n req,\n })\n\n const password = data?.password\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n const publicationHookDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status:\n statusFieldAccess && data._status === allLocalesPublicationStatus\n ? allLocalesPublicationStatus\n : undefined,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n const publicationData = { ...data }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: publicationHookDoc,\n docWithLocales,\n fieldsToValidate: submittedTopLevelFieldNames,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n // only skip validation for drafts when draft validation is false\n skipValidation: isSavingDraft && !hasDraftValidationEnabled(collectionConfig),\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let statusFieldValue: unknown\n\n let result: JsonObject = await beforeChange({\n ...beforeChangeArgs,\n onDataProcessed: (processedData) => {\n statusFieldValue = processedData._status\n },\n })\n\n const hasAuthorizedPublicationStatus = hasAuthorizedAllLocalesPublicationStatus({\n data: publicationData,\n fieldAccessDenied: !statusFieldAccess,\n fieldValue: statusFieldValue,\n status: allLocalesPublicationStatus,\n })\n\n if (\n allLocalesPublicationStatus &&\n !hasAuthorizedPublicationStatus &&\n typeof statusFieldValue === 'undefined' &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n }\n\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n\n if (\n hasAuthorizedPublicationStatus &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n } else {\n result._status = {}\n }\n\n if (!hasAuthorizedPublicationStatus) {\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\n if (hasAuthorizedPublicationStatus) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (\n !isSavingDraft &&\n result._status &&\n typeof result._status === 'object' &&\n !Array.isArray(result._status) &&\n (result._status as Record<string, unknown>)[locale] === 'published'\n ) {\n const currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n })\n\n localizedPublishData = buildLocalizedPublishData({\n config,\n currentDoc: currentDoc as JsonObject,\n fields: collectionConfig.fields,\n locale,\n result,\n })\n }\n }\n }\n\n if (\n config.localization &&\n hasDraftsEnabled(collectionConfig) &&\n publishAllLocales &&\n !unpublishAllLocales &&\n (!hasLocalizeStatusEnabled(collectionConfig) || hasAuthorizedPublicationStatus)\n ) {\n const validationResult = await validateLocalWithLocaleKeyedData({\n operation: 'update',\n options: {\n id,\n collection: collectionConfig.slug,\n data: result,\n draft: true,\n locale: 'all',\n overrideAccess,\n req,\n },\n payload,\n sourceData: {\n docWithLocales,\n originalDoc: publicationHookDoc,\n originalLocale: locale,\n },\n trash: Boolean(originalDoc?.deletedAt),\n })\n\n if (!validationResult.valid) {\n throw new ValidationError(\n {\n id,\n collection: collectionConfig.slug,\n errors: validationResult.errors,\n req,\n },\n req.t,\n )\n }\n }\n\n // File deletion and writes must occur after the final publish validation. Validation failures\n // leave both the persisted upload and local files untouched.\n if (!isDraftOverPublished && !hasManagedLocalUpload) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n if (!collectionConfig.upload.disableLocalStorage && !hasManagedLocalUpload) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n const writeDocument = async (): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const dataToUpdate: JsonObject = { ...(localizedPublishData ?? result) }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n\n if (collectionConfig.auth?.useSessions) {\n const currentSid =\n req.user?.collection === collectionConfig.slug && String(req.user.id) === String(id)\n ? req.user._sid\n : undefined\n const existingSessions = removeExpiredSessions(\n (docWithLocales.sessions as undefined | UserSession[]) ?? [],\n )\n\n dataToUpdate.sessions = currentSid\n ? existingSessions.filter((session) => session.id === currentSid)\n : []\n }\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n if (localizedPublishData) {\n // Single-locale publish: save filtered data to main doc but keep full locale data for\n // the version so draft fetches (replaceWithDraftIfAvailable) return complete data.\n await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n resultWithLocales = { ...result, updatedAt: dataToUpdate.updatedAt }\n } else {\n resultWithLocales = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n req,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: resultWithLocales,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n select,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n }\n\n if (!nextFileData) {\n return writeDocument()\n }\n\n return runLocalFileUpdate({\n id,\n collection: collectionConfig,\n current: docWithLocales,\n files: hasManagedLocalUpload ? filesToUpload : [],\n next: nextFileData as JsonObject,\n req,\n write: writeDocument,\n })\n}\n"],"names":["ensureUsernameOrEmail","removeExpiredSessions","generatePasswordSaltHash","ValidationError","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","saveVersion","deleteAssociatedFiles","runLocalFileUpdate","uploadFiles","checkDocumentLockStatus","getTopLevelFieldNames","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","resolvePublishAllLocales","buildAllLocalesPublicationHookDoc","getAllLocalesPublicationStatus","hasAuthorizedAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","buildLocalizedPublishData","validateLocalWithLocaleKeyedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","req","select","shouldManageLocalFiles","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","nextFileData","upload","fileOperations","undefined","draft","allLocalesPublicationStatus","hasLocalizedStatus","Boolean","localization","isSavingDraft","_status","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","global","isRestoringDraftFromTrash","deletedAt","shouldLimitValidationToSubmittedFields","trash","submittedTopLevelFieldNames","auth","authOptions","operation","isDraftOverPublished","hasManagedLocalUpload","length","original","disableLocalStorage","statusFieldAccess","publicationFieldPolicyDoc","status","docForHooks","onFieldAccess","accessResult","path","password","shouldSavePassword","disableLocalStrategy","enableFields","publicationHookDoc","hooks","hook","publicationData","beforeChangeArgs","fieldsToValidate","skipValidation","statusFieldValue","result","onDataProcessed","processedData","hasAuthorizedPublicationStatus","fieldAccessDenied","fieldValue","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","validationResult","options","sourceData","originalLocale","valid","errors","t","files","overrideDelete","writeDocument","dataToUpdate","hash","salt","useSessions","currentSid","user","String","_sid","existingSessions","sessions","filter","session","resultWithLocales","updatedAt","Date","toISOString","updateOne","unpublish","previousDoc","current","next","write"],"mappings":"AA0BA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,qBAAqB,QAAQ,4BAA2B;AACjE,SAASC,wBAAwB,QAAQ,6DAA4D;AACrG,SAASC,eAAe,QAAQ,2BAA0B;AAC1D,SAASC,WAAW,QAAQ,6CAA4C;AACxE,SAASC,SAAS,QAAQ,2CAA0C;AACpE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,QAAQ,gDAA+C;AAC9E,SAASC,oBAAoB,EAAEC,WAAW,QAAQ,oBAAmB;AACrE,SAASC,qBAAqB,QAAQ,4CAA2C;AACjF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,uBAAuB,QAAQ,gDAA+C;AACvF,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SACEC,gBAAgB,EAChBC,yBAAyB,EACzBC,wBAAwB,QACnB,0CAAyC;AAChD,SAASC,wBAAwB,QAAQ,iDAAgD;AACzF,SAC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ACjB,OAAOqF;IACT;IAEA,OAAO3H,mBAAmB;QACxBe;QACAsC,YAAYpC;QACZ8H,SAAS1H;QACToG,OAAOvD,wBAAwB1C,gBAAgB,EAAE;QACjDwH,MAAM1G;QACNN;QACAiH,OAAOtB;IACT;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/utilities/update.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { UserSession } from '../../../auth/types.js'\nimport type { Args } from '../../../fields/hooks/beforeChange/index.js'\nimport type {\n CollectionSlug,\n FileToSave,\n SanitizedConfig,\n TypedFallbackLocale,\n} from '../../../index.js'\nimport type {\n JsonObject,\n Payload,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../../types/index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type {\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../../auth/ensureUsernameOrEmail.js'\nimport { removeExpiredSessions } from '../../../auth/sessions.js'\nimport { generatePasswordSaltHash } from '../../../auth/strategies/local/generatePasswordSaltHash.js'\nimport { ValidationError } from '../../../errors/index.js'\nimport { afterChange } from '../../../fields/hooks/afterChange/index.js'\nimport { afterRead } from '../../../fields/hooks/afterRead/index.js'\nimport { beforeChange } from '../../../fields/hooks/beforeChange/index.js'\nimport { beforeValidate } from '../../../fields/hooks/beforeValidate/index.js'\nimport { deepCopyObjectSimple, saveVersion } from '../../../index.js'\nimport { deleteAssociatedFiles } from '../../../uploads/deleteAssociatedFiles.js'\nimport { runLocalFileUpdate } from '../../../uploads/fileVersioning/archive.js'\nimport { uploadFiles } from '../../../uploads/uploadFiles.js'\nimport { checkDocumentLockStatus } from '../../../utilities/checkDocumentLockStatus.js'\nimport { getTopLevelFieldNames } from '../../../utilities/getTopLevelFieldNames.js'\nimport {\n hasDraftsEnabled,\n hasDraftValidationEnabled,\n hasLocalizeStatusEnabled,\n} from '../../../utilities/getVersionsConfig.js'\nimport { resolvePublishAllLocales } from '../../../utilities/resolvePublishAllLocales.js'\nimport {\n buildAllLocalesPublicationHookDoc,\n getAllLocalesPublicationStatus,\n hasAuthorizedAllLocalesPublicationStatus,\n validateAllLocalesPublicationFlags,\n} from '../../../versions/allLocalesPublicationStatus.js'\nimport { buildLocalizedPublishData } from '../../../versions/buildSingleLocalePublishData.js'\nimport { validateLocalWithLocaleKeyedData } from '../local/validate.js'\nexport type SharedUpdateDocumentArgs<TSlug extends CollectionSlug> = {\n autosave: boolean\n collectionConfig: SanitizedCollectionConfig\n config: SanitizedConfig\n data: DeepPartial<DataFromCollectionSlug<TSlug>>\n depth: number\n docWithLocales: JsonObject & TypeWithID\n draftArg: boolean\n fallbackLocale: TypedFallbackLocale\n filesToUpload: FileToSave[]\n id: number | string\n locale: string\n overrideLock: boolean\n payload: Payload\n populate?: PopulateType\n publishAllLocales?: boolean\n req: PayloadRequest\n select: SelectType\n shouldManageLocalFiles: boolean\n showHiddenFields: boolean\n unpublishAllLocales?: boolean\n} & Pick<Required<SharedLocalAPIOptions>, 'overrideAccess'>\n\n/**\n * This function is used to update a document in the DB and return the result.\n *\n * It runs the following hooks in order:\n * - beforeValidate - Fields\n * - beforeValidate - Collection\n * - beforeChange - Collection\n * - beforeChange - Fields\n * - afterRead - Fields\n * - afterRead - Collection\n * - afterChange - Fields\n * - afterChange - Collection\n */\nexport const updateDocument = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug> = SelectType,\n>({\n id,\n autosave,\n collectionConfig,\n config,\n data,\n depth,\n docWithLocales,\n draftArg,\n fallbackLocale,\n filesToUpload,\n locale,\n overrideAccess,\n overrideLock,\n payload,\n populate,\n publishAllLocales: publishAllLocalesArg,\n req,\n select,\n shouldManageLocalFiles,\n showHiddenFields,\n unpublishAllLocales: unpublishAllLocalesArg,\n}: SharedUpdateDocumentArgs<TSlug>): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const nextFileData =\n collectionConfig.upload && shouldManageLocalFiles && !collectionConfig.upload.fileOperations\n ? deepCopyObjectSimple(data)\n : undefined\n\n validateAllLocalesPublicationFlags({\n publishAllLocales: publishAllLocalesArg,\n unpublishAllLocales: unpublishAllLocalesArg,\n })\n\n const publishAllLocales = resolvePublishAllLocales({\n draft: draftArg,\n hasLocalizeStatusEnabled: hasLocalizeStatusEnabled(collectionConfig),\n locale,\n publishAllLocalesArg,\n })\n const unpublishAllLocales =\n typeof unpublishAllLocalesArg === 'string'\n ? unpublishAllLocalesArg === 'true'\n : !!unpublishAllLocalesArg\n const allLocalesPublicationStatus = getAllLocalesPublicationStatus({\n hasLocalizedStatus: Boolean(config.localization && hasLocalizeStatusEnabled(collectionConfig)),\n publishAllLocales,\n unpublishAllLocales,\n })\n const isSavingDraft =\n Boolean(draftArg && hasDraftsEnabled(collectionConfig)) &&\n data._status !== 'published' &&\n !publishAllLocales\n if (allLocalesPublicationStatus || isSavingDraft) {\n data._status = allLocalesPublicationStatus ?? 'draft'\n }\n\n // /////////////////////////////////////\n // Handle potentially locked documents\n // /////////////////////////////////////\n\n await checkDocumentLockStatus({\n id,\n collectionSlug: collectionConfig.slug,\n lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,\n overrideLock,\n req,\n })\n\n const originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft: draftArg,\n fallbackLocale: id ? null : fallbackLocale,\n global: null,\n locale,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n const isRestoringDraftFromTrash = Boolean(originalDoc?.deletedAt) && data?._status !== 'published'\n const shouldLimitValidationToSubmittedFields =\n (collectionConfig.trash && (Boolean(data?.deletedAt) || isRestoringDraftFromTrash)) ||\n unpublishAllLocales\n const submittedTopLevelFieldNames = shouldLimitValidationToSubmittedFields\n ? getTopLevelFieldNames(data)\n : undefined\n\n if (collectionConfig.auth) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n\n // When saving a draft on a document whose latest version is published, the file\n // referenced by docWithLocales is still actively used by the published main document.\n // Deleting it during the update would break the published document's file even though no publish\n // is happening. Only skip deletion in this case; when the latest version is already a\n // draft, it is safe to delete the old draft file as it is being replaced.\n const isDraftOverPublished = isSavingDraft && docWithLocales._status === 'published'\n\n const hasManagedLocalUpload =\n filesToUpload.length > 0 &&\n Boolean(data.original) &&\n !collectionConfig.upload.disableLocalStorage\n\n // /////////////////////////////////////\n // beforeValidate - Fields\n // /////////////////////////////////////\n\n let statusFieldAccess = false\n const publicationFieldPolicyDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status: data._status === allLocalesPublicationStatus ? allLocalesPublicationStatus : undefined,\n })\n\n data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({\n id,\n collection: collectionConfig,\n context: req.context,\n data,\n doc: originalDoc,\n docForHooks: publicationFieldPolicyDoc,\n global: null,\n onFieldAccess: ({ accessResult, path }) => {\n if (path === '_status') {\n statusFieldAccess = accessResult\n }\n },\n operation: 'update',\n overrideAccess,\n req,\n })\n\n const password = data?.password\n const shouldSavePassword = Boolean(\n password &&\n collectionConfig.auth &&\n (!collectionConfig.auth.disableLocalStrategy ||\n (typeof collectionConfig.auth.disableLocalStrategy === 'object' &&\n collectionConfig.auth.disableLocalStrategy.enableFields)) &&\n !isSavingDraft,\n )\n\n const publicationHookDoc = buildAllLocalesPublicationHookDoc({\n doc: originalDoc,\n docWithLocales,\n status:\n statusFieldAccess && data._status === allLocalesPublicationStatus\n ? allLocalesPublicationStatus\n : undefined,\n })\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n // /////////////////////////////////////\n // beforeChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeChange?.length) {\n for (const hook of collectionConfig.hooks.beforeChange) {\n data =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n operation: 'update',\n originalDoc: publicationHookDoc,\n req,\n })) || data\n }\n }\n\n const publicationData = { ...data }\n\n // /////////////////////////////////////\n // beforeChange - Fields\n // /////////////////////////////////////\n\n const beforeChangeArgs: Args<DataFromCollectionSlug<TSlug>> = {\n id,\n collection: collectionConfig,\n context: req.context,\n data: { ...data, id },\n doc: publicationHookDoc,\n docWithLocales,\n fieldsToValidate: submittedTopLevelFieldNames,\n global: null,\n operation: 'update',\n overrideAccess,\n req,\n // only skip validation for drafts when draft validation is false\n skipValidation: isSavingDraft && !hasDraftValidationEnabled(collectionConfig),\n }\n\n // /////////////////////////////////////\n // Handle Localized Data Merging\n // /////////////////////////////////////\n\n let statusFieldValue: unknown\n\n let result: JsonObject = await beforeChange({\n ...beforeChangeArgs,\n onDataProcessed: (processedData) => {\n statusFieldValue = processedData._status\n },\n })\n\n const hasAuthorizedPublicationStatus = hasAuthorizedAllLocalesPublicationStatus({\n data: publicationData,\n fieldAccessDenied: !statusFieldAccess,\n fieldValue: statusFieldValue,\n status: allLocalesPublicationStatus,\n })\n\n if (\n allLocalesPublicationStatus &&\n !hasAuthorizedPublicationStatus &&\n typeof statusFieldValue === 'undefined' &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n }\n\n if (\n config.localization &&\n hasLocalizeStatusEnabled(collectionConfig) &&\n typeof result._status === 'string'\n ) {\n const statusStr = result._status\n\n if (\n hasAuthorizedPublicationStatus &&\n typeof docWithLocales._status === 'object' &&\n docWithLocales._status !== null\n ) {\n result._status = { ...docWithLocales._status }\n } else {\n result._status = {}\n }\n\n if (!hasAuthorizedPublicationStatus) {\n for (const localeCode of config.localization.localeCodes) {\n ;(result._status as Record<string, unknown>)[localeCode] = statusStr\n }\n }\n }\n\n let localizedPublishData: JsonObject | null = null\n\n if (config.localization && collectionConfig.versions) {\n if (hasLocalizeStatusEnabled(collectionConfig)) {\n if (hasAuthorizedPublicationStatus) {\n let accessibleLocaleCodes = config.localization.localeCodes\n\n if (config.localization.filterAvailableLocales) {\n const filteredLocales = await config.localization.filterAvailableLocales({\n locales: config.localization.locales,\n req,\n })\n accessibleLocaleCodes = filteredLocales.map((locale) =>\n typeof locale === 'string' ? locale : locale.code,\n )\n }\n\n if (typeof result._status !== 'object' || result._status === null) {\n result._status = {}\n }\n\n for (const localeCode of accessibleLocaleCodes) {\n result._status[localeCode] = unpublishAllLocales ? 'draft' : 'published'\n }\n } else if (\n !isSavingDraft &&\n result._status &&\n typeof result._status === 'object' &&\n !Array.isArray(result._status) &&\n (result._status as Record<string, unknown>)[locale] === 'published'\n ) {\n const currentDoc = await payload.db.findOne<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n locale: 'all',\n req,\n where: { id: { equals: id } },\n })\n\n localizedPublishData = buildLocalizedPublishData({\n config,\n currentDoc,\n fields: collectionConfig.fields,\n locale,\n result,\n })\n }\n }\n }\n\n if (\n config.localization &&\n hasDraftsEnabled(collectionConfig) &&\n publishAllLocales &&\n !unpublishAllLocales &&\n (!hasLocalizeStatusEnabled(collectionConfig) || hasAuthorizedPublicationStatus)\n ) {\n const validationResult = await validateLocalWithLocaleKeyedData({\n operation: 'update',\n options: {\n id,\n collection: collectionConfig.slug,\n data: result,\n draft: true,\n locale: 'all',\n overrideAccess,\n req,\n },\n payload,\n sourceData: {\n docWithLocales,\n originalDoc: publicationHookDoc,\n originalLocale: locale,\n },\n trash: Boolean(originalDoc?.deletedAt),\n })\n\n if (!validationResult.valid) {\n throw new ValidationError(\n {\n id,\n collection: collectionConfig.slug,\n errors: validationResult.errors,\n req,\n },\n req.t,\n )\n }\n }\n\n // File deletion and writes must occur after the final publish validation. Validation failures\n // leave both the persisted upload and local files untouched.\n if (!isDraftOverPublished && !hasManagedLocalUpload) {\n await deleteAssociatedFiles({\n collectionConfig,\n config,\n doc: docWithLocales,\n files: filesToUpload,\n overrideDelete: false,\n req,\n })\n }\n\n if (!collectionConfig.upload.disableLocalStorage && !hasManagedLocalUpload) {\n await uploadFiles(payload, filesToUpload, req)\n }\n\n const writeDocument = async (): Promise<TransformCollectionWithSelect<TSlug, TSelect>> => {\n const dataToUpdate: JsonObject = { ...(localizedPublishData ?? result) }\n\n // /////////////////////////////////////\n // Handle potential password update\n // /////////////////////////////////////\n\n if (shouldSavePassword && typeof password === 'string') {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password,\n req,\n })\n dataToUpdate.salt = salt\n dataToUpdate.hash = hash\n delete dataToUpdate.password\n delete data.password\n\n if (collectionConfig.auth?.useSessions) {\n const currentSid =\n req.user?.collection === collectionConfig.slug && String(req.user.id) === String(id)\n ? req.user._sid\n : undefined\n const existingSessions = removeExpiredSessions(\n (docWithLocales.sessions as undefined | UserSession[]) ?? [],\n )\n\n dataToUpdate.sessions = currentSid\n ? existingSessions.filter((session) => session.id === currentSid)\n : []\n }\n }\n\n // /////////////////////////////////////\n // Update\n // /////////////////////////////////////\n\n let resultWithLocales: JsonObject = result\n\n if (!isSavingDraft) {\n // Ensure updatedAt date is always updated\n dataToUpdate.updatedAt = new Date().toISOString()\n if (localizedPublishData) {\n // Single-locale publish: save filtered data to main doc but keep full locale data for\n // the version so draft fetches (replaceWithDraftIfAvailable) return complete data.\n await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n resultWithLocales = { ...result, updatedAt: dataToUpdate.updatedAt }\n } else {\n resultWithLocales = await req.payload.db.updateOne({\n id,\n collection: collectionConfig.slug,\n data: dataToUpdate,\n locale,\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Create version\n // /////////////////////////////////////\n\n if (collectionConfig.versions) {\n resultWithLocales = await saveVersion({\n id,\n autosave,\n collection: collectionConfig,\n docWithLocales: resultWithLocales,\n draft: isSavingDraft,\n operation: 'update',\n payload,\n req,\n unpublish: unpublishAllLocales,\n })\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth,\n doc: resultWithLocales,\n draft: draftArg,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterRead?.length) {\n for (const hook of collectionConfig.hooks.afterRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterChange - Fields\n // /////////////////////////////////////\n\n result = await afterChange({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n global: null,\n operation: 'update',\n previousDoc: originalDoc,\n req,\n })\n\n // /////////////////////////////////////\n // afterChange - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterChange?.length) {\n for (const hook of collectionConfig.hooks.afterChange) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n data,\n doc: result,\n operation: 'update',\n overrideAccess,\n previousDoc: originalDoc,\n req,\n select,\n })) || result\n }\n }\n\n return result as TransformCollectionWithSelect<TSlug, TSelect>\n }\n\n if (!nextFileData) {\n return writeDocument()\n }\n\n return runLocalFileUpdate({\n id,\n collection: collectionConfig,\n current: docWithLocales,\n files: hasManagedLocalUpload ? filesToUpload : [],\n next: nextFileData,\n req,\n write: writeDocument,\n })\n}\n"],"names":["ensureUsernameOrEmail","removeExpiredSessions","generatePasswordSaltHash","ValidationError","afterChange","afterRead","beforeChange","beforeValidate","deepCopyObjectSimple","saveVersion","deleteAssociatedFiles","runLocalFileUpdate","uploadFiles","checkDocumentLockStatus","getTopLevelFieldNames","hasDraftsEnabled","hasDraftValidationEnabled","hasLocalizeStatusEnabled","resolvePublishAllLocales","buildAllLocalesPublicationHookDoc","getAllLocalesPublicationStatus","hasAuthorizedAllLocalesPublicationStatus","validateAllLocalesPublicationFlags","buildLocalizedPublishData","validateLocalWithLocaleKeyedData","updateDocument","id","autosave","collectionConfig","config","data","depth","docWithLocales","draftArg","fallbackLocale","filesToUpload","locale","overrideAccess","overrideLock","payload","populate","publishAllLocales","publishAllLocalesArg","req","select","shouldManageLocalFiles","showHiddenFields","unpublishAllLocales","unpublishAllLocalesArg","nextFileData","upload","fileOperations","undefined","draft","allLocalesPublicationStatus","hasLocalizedStatus","Boolean","localization","isSavingDraft","_status","collectionSlug","slug","lockErrorMessage","originalDoc","collection","context","doc","global","isRestoringDraftFromTrash","deletedAt","shouldLimitValidationToSubmittedFields","trash","submittedTopLevelFieldNames","auth","authOptions","operation","isDraftOverPublished","hasManagedLocalUpload","length","original","disableLocalStorage","statusFieldAccess","publicationFieldPolicyDoc","status","docForHooks","onFieldAccess","accessResult","path","password","shouldSavePassword","disableLocalStrategy","enableFields","publicationHookDoc","hooks","hook","publicationData","beforeChangeArgs","fieldsToValidate","skipValidation","statusFieldValue","result","onDataProcessed","processedData","hasAuthorizedPublicationStatus","fieldAccessDenied","fieldValue","statusStr","localeCode","localeCodes","localizedPublishData","versions","accessibleLocaleCodes","filterAvailableLocales","filteredLocales","locales","map","code","Array","isArray","currentDoc","db","findOne","where","equals","fields","validationResult","options","sourceData","originalLocale","valid","errors","t","files","overrideDelete","writeDocument","dataToUpdate","hash","salt","useSessions","currentSid","user","String","_sid","existingSessions","sessions","filter","session","resultWithLocales","updatedAt","Date","toISOString","updateOne","unpublish","previousDoc","current","next","write"],"mappings":"AA0BA,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,qBAAqB,QAAQ,4BAA2B;AACjE,SAASC,wBAAwB,QAAQ,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,YAAYpC;YACZqC,SAAStB,IAAIsB,OAAO;YACpBnC;YACAoC,KAAKkC;YACLjC,QAAQ;YACRQ,WAAW;YACX8E,aAAa1F;YACbpB;QACF;QAEA,wCAAwC;QACxC,2BAA2B;QAC3B,wCAAwC;QAExC,IAAIf,iBAAiBiE,KAAK,EAAEzF,aAAa0E,QAAQ;YAC/C,KAAK,MAAMgB,QAAQlE,iBAAiBiE,KAAK,CAACzF,WAAW,CAAE;gBACrDgG,SACE,AAAC,MAAMN,KAAK;oBACV9B,YAAYpC;oBACZqC,SAAStB,IAAIsB,OAAO;oBACpBnC;oBACAoC,KAAKkC;oBACLzB,WAAW;oBACXtC;oBACAoH,aAAa1F;oBACbpB;oBACAC;gBACF,MAAOwD;YACX;QACF;QAEA,OAAOA;IACT;IAEA,IAAI,CAACnD,cAAc;QACjB,OAAOqF;IACT;IAEA,OAAO3H,mBAAmB;QACxBe;QACAsC,YAAYpC;QACZ8H,SAAS1H;QACToG,OAAOvD,wBAAwB1C,gBAAgB,EAAE;QACjDwH,MAAM1G;QACNN;QACAiH,OAAOtB;IACT;AACF,EAAC"}
|
|
@@ -128,7 +128,7 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
128
128
|
ensureUsernameOrEmail({
|
|
129
129
|
authOptions: collectionConfig.auth,
|
|
130
130
|
collectionSlug: collectionConfig.slug,
|
|
131
|
-
data
|
|
131
|
+
data,
|
|
132
132
|
operation: 'create',
|
|
133
133
|
req
|
|
134
134
|
});
|
|
@@ -136,9 +136,9 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
136
136
|
ensureUsernameOrEmail({
|
|
137
137
|
authOptions: collectionConfig.auth,
|
|
138
138
|
collectionSlug: collectionConfig.slug,
|
|
139
|
-
data
|
|
139
|
+
data,
|
|
140
140
|
operation: 'update',
|
|
141
|
-
originalDoc
|
|
141
|
+
originalDoc,
|
|
142
142
|
req
|
|
143
143
|
});
|
|
144
144
|
}
|
|
@@ -146,7 +146,7 @@ async function validateOperationWithScopedRequest({ id, collection, data: incomi
|
|
|
146
146
|
collection: collectionConfig,
|
|
147
147
|
docWithLocales,
|
|
148
148
|
global: null,
|
|
149
|
-
incomingData
|
|
149
|
+
incomingData,
|
|
150
150
|
onValidationData,
|
|
151
151
|
originalDoc,
|
|
152
152
|
overrideAccess,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/validate.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JsonObject } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ValidationResult } from '../../types/validation.js'\nimport type { ValidationSourceData } from '../../utilities/runValidationLifecycle.js'\nimport type { Collection, RequiredDataFromCollectionSlug, TypeWithID } from '../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../auth/ensureUsernameOrEmail.js'\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { deepCopyObjectSimple } from '../../utilities/deepCopyObject.js'\nimport { flattenDataByLocale } from '../../utilities/flattenDataByLocale.js'\nimport { runValidationLifecycle } from '../../utilities/runValidationLifecycle.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { validateUniqueConstraints } from './utilities/validateUniqueConstraints.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data?: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n draft: boolean\n id?: number | string\n onValidationData?: (data: JsonObject) => void\n overrideAccess: boolean\n req: PayloadRequest\n skipAccessControl?: boolean\n skipMutationHooks?: boolean\n sourceData?: ValidationSourceData\n trash?: boolean\n validationOperation?: 'create' | 'update' | 'validate'\n}\n\nexport async function validateOperation<TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<ValidationResult> {\n const previousOperation = args.req.operation\n args.req.operation = args.validationOperation ?? 'validate'\n\n try {\n return await validateOperationWithScopedRequest(args)\n } finally {\n args.req.operation = previousOperation\n }\n}\n\nasync function validateOperationWithScopedRequest<TSlug extends CollectionSlug>({\n id,\n collection,\n data: incomingData,\n draft,\n onValidationData,\n overrideAccess,\n req,\n skipAccessControl = false,\n skipMutationHooks = false,\n sourceData,\n trash = false,\n validationOperation = 'validate',\n}: Arguments<TSlug>): Promise<ValidationResult> {\n const collectionConfig = collection.config\n\n const accessResult =\n !skipAccessControl && !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, data: incomingData, req },\n collectionConfig.access.validate,\n )\n : true\n const hasWherePolicy = hasWhereAccessResult(accessResult)\n\n if (id === undefined && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n\n let docWithLocales: JsonObject = sourceData ? deepCopyObjectSimple(sourceData.docWithLocales) : {}\n\n if (id !== undefined && !sourceData) {\n const idWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: { id: { equals: id } },\n })\n const where = combineQueries(idWhere, accessResult)\n const query: FindOneArgs = {\n collection: collectionConfig.slug,\n locale: req.locale!,\n req,\n where,\n }\n\n let storedDocument: (RequiredDataFromCollectionSlug<TSlug> & TypeWithID) | undefined\n\n if (draft && collectionConfig.versions?.drafts) {\n const { docs } = await req.payload.db.queryDrafts<\n RequiredDataFromCollectionSlug<TSlug> & TypeWithID\n >({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n where: appendVersionToQueryKey(where),\n })\n\n storedDocument = docs[0]\n\n if (!storedDocument && hasWherePolicy) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(idWhere),\n })\n\n if (existingVersions[0]) {\n throw new Forbidden(req.t)\n }\n }\n }\n\n if (!storedDocument) {\n storedDocument =\n (await req.payload.db.findOne<RequiredDataFromCollectionSlug<TSlug> & TypeWithID>({\n ...query,\n req,\n })) ?? undefined\n }\n\n if (!storedDocument && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n if (!storedDocument) {\n throw new NotFound(req.t)\n }\n\n docWithLocales = deepCopyObjectSimple(storedDocument)\n }\n\n let originalDoc: JsonObject\n\n if (id === undefined) {\n originalDoc = docWithLocales\n } else if (!sourceData) {\n originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft,\n fallbackLocale: null,\n global: null,\n locale: req.locale!,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n } else if (req.locale === sourceData.originalLocale) {\n originalDoc = deepCopyObjectSimple(sourceData.originalDoc)\n } else {\n originalDoc = flattenDataByLocale({\n configBlockReferences: req.payload.config.blocks,\n docWithLocales,\n fields: collectionConfig.fields,\n locale: req.locale!,\n })\n }\n\n return runValidationLifecycle({\n id,\n beforeValidation: ({ data }) => {\n if (!collectionConfig.auth) {\n return\n }\n\n if (id === undefined) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data: data as RequiredDataFromCollectionSlug<TSlug>,\n operation: 'create',\n req,\n })\n } else {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data: data as RequiredDataFromCollectionSlug<TSlug>,\n operation: 'update',\n originalDoc: originalDoc as RequiredDataFromCollectionSlug<TSlug>,\n req,\n })\n }\n },\n collection: collectionConfig,\n docWithLocales,\n global: null,\n incomingData: incomingData as JsonObject | undefined,\n onValidationData,\n originalDoc,\n overrideAccess,\n req,\n skipMutationHooks,\n validateData: ({ data }) =>\n validateUniqueConstraints({\n id,\n collection: collectionConfig,\n data,\n req,\n }),\n validationOperation,\n })\n}\n"],"names":["ensureUsernameOrEmail","executeAccess","hasWhereAccessResult","combineQueries","Forbidden","NotFound","afterRead","appendNonTrashedFilter","deepCopyObjectSimple","flattenDataByLocale","runValidationLifecycle","appendVersionToQueryKey","validateUniqueConstraints","validateOperation","args","previousOperation","req","operation","validationOperation","validateOperationWithScopedRequest","id","collection","data","incomingData","draft","onValidationData","overrideAccess","skipAccessControl","skipMutationHooks","sourceData","trash","collectionConfig","config","accessResult","slug","access","validate","hasWherePolicy","undefined","t","docWithLocales","idWhere","enableTrash","where","equals","query","locale","storedDocument","versions","drafts","docs","payload","db","queryDrafts","limit","pagination","existingVersions","select","parent","findOne","originalDoc","context","depth","doc","fallbackLocale","global","showHiddenFields","originalLocale","configBlockReferences","blocks","fields","beforeValidation","auth","authOptions","collectionSlug","validateData"],"mappings":"AASA,SAASA,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AAC3D,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,oBAAoB,QAAQ,oCAAmC;AACxE,SAASC,mBAAmB,QAAQ,yCAAwC;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,yBAAyB,QAAQ,2CAA0C;AAiBpF,OAAO,eAAeC,kBACpBC,IAAsB;IAEtB,MAAMC,oBAAoBD,KAAKE,GAAG,CAACC,SAAS;IAC5CH,KAAKE,GAAG,CAACC,SAAS,GAAGH,KAAKI,mBAAmB,IAAI;IAEjD,IAAI;QACF,OAAO,MAAMC,mCAAmCL;IAClD,SAAU;QACRA,KAAKE,GAAG,CAACC,SAAS,GAAGF;IACvB;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cAAcnD,oBAAoB;YAChC2D,uBAAuBpD,IAAImC,OAAO,CAACnB,MAAM,CAACqC,MAAM;YAChD7B;YACA8B,QAAQvC,iBAAiBuC,MAAM;YAC/BxB,QAAQ9B,IAAI8B,MAAM;QACpB;IACF;IAEA,OAAOpC,uBAAuB;QAC5BU;QACAmD,kBAAkB,CAAC,EAAEjD,IAAI,EAAE;YACzB,IAAI,CAACS,iBAAiByC,IAAI,EAAE;gBAC1B;YACF;YAEA,IAAIpD,OAAOkB,WAAW;gBACpBtC,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ,MAAMA;oBACNL,WAAW;oBACXD;gBACF;YACF,OAAO;gBACLhB,sBAA6B;oBAC3ByE,aAAa1C,iBAAiByC,IAAI;oBAClCE,gBAAgB3C,iBAAiBG,IAAI;oBACrCZ,MAAMA;oBACNL,WAAW;oBACX2C,aAAaA;oBACb5C;gBACF;YACF;QACF;QACAK,YAAYU;QACZS;QACAyB,QAAQ;QACR1C,cAAcA;QACdE;QACAmC;QACAlC;QACAV;QACAY;QACA+C,cAAc,CAAC,EAAErD,IAAI,EAAE,GACrBV,0BAA0B;gBACxBQ;gBACAC,YAAYU;gBACZT;gBACAN;YACF;QACFE;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/validate.ts"],"sourcesContent":["import type { DeepPartial } from 'ts-essentials'\n\nimport type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JsonObject } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { ValidationResult } from '../../types/validation.js'\nimport type { ValidationSourceData } from '../../utilities/runValidationLifecycle.js'\nimport type { Collection, RequiredDataFromCollectionSlug, TypeWithID } from '../config/types.js'\n\nimport { ensureUsernameOrEmail } from '../../auth/ensureUsernameOrEmail.js'\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { hasWhereAccessResult } from '../../auth/types.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { deepCopyObjectSimple } from '../../utilities/deepCopyObject.js'\nimport { flattenDataByLocale } from '../../utilities/flattenDataByLocale.js'\nimport { runValidationLifecycle } from '../../utilities/runValidationLifecycle.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { validateUniqueConstraints } from './utilities/validateUniqueConstraints.js'\n\nexport type Arguments<TSlug extends CollectionSlug> = {\n collection: Collection\n data?: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n draft: boolean\n id?: number | string\n onValidationData?: (data: JsonObject) => void\n overrideAccess: boolean\n req: PayloadRequest\n skipAccessControl?: boolean\n skipMutationHooks?: boolean\n sourceData?: ValidationSourceData\n trash?: boolean\n validationOperation?: 'create' | 'update' | 'validate'\n}\n\nexport async function validateOperation<TSlug extends CollectionSlug>(\n args: Arguments<TSlug>,\n): Promise<ValidationResult> {\n const previousOperation = args.req.operation\n args.req.operation = args.validationOperation ?? 'validate'\n\n try {\n return await validateOperationWithScopedRequest(args)\n } finally {\n args.req.operation = previousOperation\n }\n}\n\nasync function validateOperationWithScopedRequest<TSlug extends CollectionSlug>({\n id,\n collection,\n data: incomingData,\n draft,\n onValidationData,\n overrideAccess,\n req,\n skipAccessControl = false,\n skipMutationHooks = false,\n sourceData,\n trash = false,\n validationOperation = 'validate',\n}: Arguments<TSlug>): Promise<ValidationResult> {\n const collectionConfig = collection.config\n\n const accessResult =\n !skipAccessControl && !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, data: incomingData, req },\n collectionConfig.access.validate,\n )\n : true\n const hasWherePolicy = hasWhereAccessResult(accessResult)\n\n if (id === undefined && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n\n let docWithLocales: JsonObject = sourceData ? deepCopyObjectSimple(sourceData.docWithLocales) : {}\n\n if (id !== undefined && !sourceData) {\n const idWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: { id: { equals: id } },\n })\n const where = combineQueries(idWhere, accessResult)\n const query: FindOneArgs = {\n collection: collectionConfig.slug,\n locale: req.locale!,\n req,\n where,\n }\n\n let storedDocument: (RequiredDataFromCollectionSlug<TSlug> & TypeWithID) | undefined\n\n if (draft && collectionConfig.versions?.drafts) {\n const { docs } = await req.payload.db.queryDrafts<\n RequiredDataFromCollectionSlug<TSlug> & TypeWithID\n >({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n where: appendVersionToQueryKey(where),\n })\n\n storedDocument = docs[0]\n\n if (!storedDocument && hasWherePolicy) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: req.locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(idWhere),\n })\n\n if (existingVersions[0]) {\n throw new Forbidden(req.t)\n }\n }\n }\n\n if (!storedDocument) {\n storedDocument =\n (await req.payload.db.findOne<RequiredDataFromCollectionSlug<TSlug> & TypeWithID>({\n ...query,\n req,\n })) ?? undefined\n }\n\n if (!storedDocument && hasWherePolicy) {\n throw new Forbidden(req.t)\n }\n if (!storedDocument) {\n throw new NotFound(req.t)\n }\n\n docWithLocales = deepCopyObjectSimple(storedDocument)\n }\n\n let originalDoc: JsonObject\n\n if (id === undefined) {\n originalDoc = docWithLocales\n } else if (!sourceData) {\n originalDoc = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: 0,\n doc: deepCopyObjectSimple(docWithLocales),\n draft,\n fallbackLocale: null,\n global: null,\n locale: req.locale!,\n overrideAccess: true,\n req,\n showHiddenFields: true,\n })\n } else if (req.locale === sourceData.originalLocale) {\n originalDoc = deepCopyObjectSimple(sourceData.originalDoc)\n } else {\n originalDoc = flattenDataByLocale({\n configBlockReferences: req.payload.config.blocks,\n docWithLocales,\n fields: collectionConfig.fields,\n locale: req.locale!,\n })\n }\n\n return runValidationLifecycle({\n id,\n beforeValidation: ({ data }) => {\n if (!collectionConfig.auth) {\n return\n }\n\n if (id === undefined) {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'create',\n req,\n })\n } else {\n ensureUsernameOrEmail<TSlug>({\n authOptions: collectionConfig.auth,\n collectionSlug: collectionConfig.slug,\n data,\n operation: 'update',\n originalDoc,\n req,\n })\n }\n },\n collection: collectionConfig,\n docWithLocales,\n global: null,\n incomingData,\n onValidationData,\n originalDoc,\n overrideAccess,\n req,\n skipMutationHooks,\n validateData: ({ data }) =>\n validateUniqueConstraints({\n id,\n collection: collectionConfig,\n data,\n req,\n }),\n validationOperation,\n })\n}\n"],"names":["ensureUsernameOrEmail","executeAccess","hasWhereAccessResult","combineQueries","Forbidden","NotFound","afterRead","appendNonTrashedFilter","deepCopyObjectSimple","flattenDataByLocale","runValidationLifecycle","appendVersionToQueryKey","validateUniqueConstraints","validateOperation","args","previousOperation","req","operation","validationOperation","validateOperationWithScopedRequest","id","collection","data","incomingData","draft","onValidationData","overrideAccess","skipAccessControl","skipMutationHooks","sourceData","trash","collectionConfig","config","accessResult","slug","access","validate","hasWherePolicy","undefined","t","docWithLocales","idWhere","enableTrash","where","equals","query","locale","storedDocument","versions","drafts","docs","payload","db","queryDrafts","limit","pagination","existingVersions","select","parent","findOne","originalDoc","context","depth","doc","fallbackLocale","global","showHiddenFields","originalLocale","configBlockReferences","blocks","fields","beforeValidation","auth","authOptions","collectionSlug","validateData"],"mappings":"AASA,SAASA,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AAC3D,SAASC,SAAS,QAAQ,w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YACF;QACFE;IACF;AACF"}
|
|
@@ -11,9 +11,11 @@ function buildPluginsMap(plugins) {
|
|
|
11
11
|
}
|
|
12
12
|
export function definePlugin(descriptor) {
|
|
13
13
|
return (options)=>{
|
|
14
|
+
// Read `pluginFn.options` when the plugin runs, so other plugins can edit or replace it, even
|
|
15
|
+
// when the plugin was registered without options
|
|
14
16
|
const pluginFn = (config)=>descriptor.plugin({
|
|
15
17
|
config,
|
|
16
|
-
options: options,
|
|
18
|
+
options: pluginFn.options,
|
|
17
19
|
plugins: buildPluginsMap(config.plugins)
|
|
18
20
|
});
|
|
19
21
|
if (options !== undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map
|
|
1
|
+
{"version":3,"sources":["../../src/config/definePlugin.ts"],"sourcesContent":["import type { Config, Plugin, PluginsMap } from './types.js'\n\nfunction buildPluginsMap(plugins: Plugin[] | undefined): PluginsMap {\n const map: Record<string, Plugin | undefined> = {}\n if (plugins) {\n for (const p of plugins) {\n if (p.slug) {\n map[p.slug] = p\n }\n }\n }\n return map\n}\n\n/**\n * Helper for authoring plugins with order, slug, and typed options.\n * Eliminates boilerplate and ensures metadata is always set consistently.\n *\n * The `plugin` function receives `config`, `plugins` (a slug-keyed map of other\n * plugins), and the user-provided `options`.\n *\n * @experimental\n *\n * @example\n * // With options:\n * export const seoPlugin = definePlugin<SEOPluginConfig>({\n * slug: 'plugin-seo',\n * plugin: ({ config, options }) => ({ ...config }),\n * })\n *\n * // Without options:\n * export const myPlugin = definePlugin({\n * slug: 'my-plugin',\n * plugin: ({ config }) => ({ ...config }),\n * })\n */\nexport function definePlugin(descriptor: {\n order?: number\n plugin: (args: { config: Config; plugins: PluginsMap }) => Config | Promise<Config>\n slug: string\n}): () => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): undefined extends TOptions ? (options?: TOptions) => Plugin : (options: TOptions) => Plugin\nexport function definePlugin<TOptions>(descriptor: {\n order?: number\n plugin: (args: {\n config: Config\n options: TOptions\n plugins: PluginsMap\n }) => Config | Promise<Config>\n slug: string\n}): (options: TOptions) => Plugin {\n return (options?: TOptions): Plugin => {\n // Read `pluginFn.options` when the plugin runs, so other plugins can edit or replace it, even\n // when the plugin was registered without options\n const pluginFn: Plugin = (config) =>\n descriptor.plugin({\n config,\n options: pluginFn.options as TOptions,\n plugins: buildPluginsMap(config.plugins),\n })\n\n if (options !== undefined) {\n pluginFn.options = options as Record<string, unknown>\n }\n pluginFn.slug = descriptor.slug\n if (descriptor.order !== undefined) {\n pluginFn.order = descriptor.order\n }\n\n return pluginFn\n }\n}\n"],"names":["buildPluginsMap","plugins","map","p","slug","definePlugin","descriptor","options","pluginFn","config","plugin","undefined","order"],"mappings":"AAEA,SAASA,gBAAgBC,OAA6B;IACpD,MAAMC,MAA0C,CAAC;IACjD,IAAID,SAAS;QACX,KAAK,MAAME,KAAKF,QAAS;YACvB,IAAIE,EAAEC,IAAI,EAAE;gBACVF,GAAG,CAACC,EAAEC,IAAI,CAAC,GAAGD;YAChB;QACF;IACF;IACA,OAAOD;AACT;AAsCA,OAAO,SAASG,aAAuBC,UAQtC;IACC,OAAO,CAACC;QACN,8FAA8F;QAC9F,iDAAiD;QACjD,MAAMC,WAAmB,CAACC,SACxBH,WAAWI,MAAM,CAAC;gBAChBD;gBACAF,SAASC,SAASD,OAAO;gBACzBN,SAASD,gBAAgBS,OAAOR,OAAO;YACzC;QAEF,IAAIM,YAAYI,WAAW;YACzBH,SAASD,OAAO,GAAGA;QACrB;QACAC,SAASJ,IAAI,GAAGE,WAAWF,IAAI;QAC/B,IAAIE,WAAWM,KAAK,KAAKD,WAAW;YAClCH,SAASI,KAAK,GAAGN,WAAWM,KAAK;QACnC;QAEA,OAAOJ;IACT;AACF"}
|
package/dist/config/sanitize.js
CHANGED
|
@@ -141,7 +141,7 @@ const addDefaultDashboardWidgets = ({ config, richTextSanitizers, validRelations
|
|
|
141
141
|
components: {
|
|
142
142
|
// Presents an inclusion filter (all collections checked by default) while persisting the
|
|
143
143
|
// inverse as an exclusion list, so collections added later stay visible by default.
|
|
144
|
-
Field: '@payloadcms/ui#
|
|
144
|
+
Field: '@payloadcms/ui#CollectionFilter'
|
|
145
145
|
},
|
|
146
146
|
description: ({ t })=>t('dashboard:widgetRecentlyViewedFilterDescription')
|
|
147
147
|
},
|
|
@@ -191,7 +191,7 @@ const addDefaultDashboardWidgets = ({ config, richTextSanitizers, validRelations
|
|
|
191
191
|
});
|
|
192
192
|
dashboard.widgets.push({
|
|
193
193
|
slug: 'activity',
|
|
194
|
-
Component: '@payloadcms/ui/rsc#
|
|
194
|
+
Component: '@payloadcms/ui/rsc#ActivityWidget',
|
|
195
195
|
fields: sanitizeFields({
|
|
196
196
|
config: config,
|
|
197
197
|
existingFieldNames: new Set(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/sanitize.ts"],"sourcesContent":["import type { AcceptedLanguages } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\n\nimport type { RichTextSanitizer } from '../fields/config/sanitize.js'\nimport type { OrderableJoinInfo } from '../fields/config/sanitizeJoinField.js'\nimport type { CollectionSlug, GlobalSlug, SanitizedCollectionConfig } from '../index.js'\nimport type { SanitizedJobsConfig } from '../queues/config/types/index.js'\nimport type {\n Config,\n DashboardConfig,\n LocalizationConfigWithLabels,\n LocalizationConfigWithNoLabels,\n SanitizedConfig,\n Timezone,\n Widget,\n WidgetInstance,\n} from './types.js'\n\nimport { defaultUserCollection } from '../auth/defaultUser.js'\nimport { authRootEndpoints } from '../auth/endpoints/index.js'\nimport { sanitizeCollection } from '../collections/config/sanitize.js'\nimport { migrationsCollection } from '../database/migrations/migrationsCollection.js'\nimport { DuplicateCollection, InvalidConfiguration } from '../errors/index.js'\nimport { defaultTimezones } from '../fields/baseFields/timezone/defaultTimezones.js'\nimport { sanitizeGlobal } from '../globals/config/sanitize.js'\nimport { resolveHierarchyCollections } from '../hierarchy/resolveHierarchyCollections.js'\nimport { baseBlockFields, formatLabels, sanitizeFields } from '../index.js'\nimport { addLLMInstructions } from '../llm-instructions/addLLMInstructions.js'\nimport {\n getLockedDocumentsCollection,\n lockedDocumentsCollectionSlug,\n} from '../locked-documents/config.js'\nimport { getPreferencesCollection, preferencesCollectionSlug } from '../preferences/config.js'\nimport { getQueryPresetsConfig, queryPresetsCollectionSlug } from '../query-presets/config.js'\nimport { getDefaultJobsCollection, jobsCollectionSlug } from '../queues/config/collection.js'\nimport { getJobStatsGlobal } from '../queues/config/global.js'\nimport {\n stagedUploadEndpoints,\n uploadInstructionsEndpoint,\n} from '../uploads/endpoints/uploadInstructions.js'\nimport { flattenAllFields, flattenBlock } from '../utilities/flattenAllFields.js'\nimport { hasScheduledPublishEnabled } from '../utilities/getVersionsConfig.js'\nimport { validateTimezones } from '../utilities/validateTimezones.js'\nimport { getSchedulePublishTask } from '../versions/schedule/job.js'\nimport { addDefaultsToConfig } from './defaults.js'\nimport { addOrderableEndpoint, addOrderableFieldsAndHook } from './orderable/index.js'\n\nconst sanitizeAdminConfig = (configToSanitize: Config): Partial<SanitizedConfig> => {\n const sanitizedConfig = { ...configToSanitize }\n\n // default logging level will be 'error' if not provided\n sanitizedConfig.loggingLevels = {\n Forbidden: 'info',\n Locked: 'info',\n MissingFile: 'info',\n NotFound: 'info',\n ValidationError: 'info',\n ...(sanitizedConfig.loggingLevels || {}),\n }\n // add default user collection if none provided\n if (!sanitizedConfig?.admin?.user) {\n const firstCollectionWithAuth = sanitizedConfig.collections!.find(({ auth }) => Boolean(auth))\n\n if (firstCollectionWithAuth) {\n sanitizedConfig.admin!.user = firstCollectionWithAuth.slug\n } else {\n sanitizedConfig.admin!.user = defaultUserCollection.slug\n sanitizedConfig.collections!.push(defaultUserCollection)\n }\n }\n\n const authCollections = sanitizedConfig.collections!.filter(({ auth }) => Boolean(auth))\n\n const userCollection = authCollections.find(({ slug }) => slug === sanitizedConfig.admin!.user)\n\n if (!userCollection || !userCollection.auth) {\n throw new InvalidConfiguration(\n `${sanitizedConfig.admin!.user} is not a valid admin user collection`,\n )\n }\n\n if (sanitizedConfig?.admin?.timezones) {\n if (typeof configToSanitize?.admin?.timezones?.supportedTimezones === 'function') {\n sanitizedConfig.admin.timezones.supportedTimezones =\n configToSanitize.admin.timezones.supportedTimezones({ defaultTimezones })\n }\n\n if (!sanitizedConfig?.admin?.timezones?.supportedTimezones) {\n sanitizedConfig.admin.timezones.supportedTimezones = defaultTimezones\n }\n } else {\n sanitizedConfig.admin!.timezones = {\n supportedTimezones: defaultTimezones,\n }\n }\n\n validateTimezones({\n source: 'admin.timezones.supportedTimezones',\n timezones: sanitizedConfig.admin!.timezones.supportedTimezones as Timezone[],\n })\n\n return sanitizedConfig as unknown as Partial<SanitizedConfig>\n}\n\nconst addDefaultDashboardWidgets = ({\n config,\n richTextSanitizers,\n validRelationships,\n}: {\n config: Partial<SanitizedConfig>\n richTextSanitizers: RichTextSanitizer[]\n validRelationships: string[]\n}): void => {\n const collectionQueryFields: NonNullable<Widget['fields']> = [\n {\n name: 'title',\n type: 'text',\n label: ({ t }) => t('dashboard:widgetTitleLabel'),\n },\n {\n name: 'relatedCollection',\n type: 'select',\n label: ({ t }) => t('general:collection'),\n // Only offer collections that are visible in the admin UI. Collections hidden via a function\n // are kept since they may still be visible for some users.\n options: (config.collections ?? [])\n .filter((collection) => collection.admin?.hidden !== true)\n .map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n required: true,\n },\n {\n name: 'where',\n type: 'json',\n admin: {\n components: {\n Field: '@payloadcms/ui#QueryPresetsWhereField',\n },\n },\n label: ({ t }) => t('general:filters'),\n },\n {\n name: 'sortField',\n type: 'text',\n admin: {\n components: {\n Field: '@payloadcms/ui#CollectionQuerySortField',\n },\n },\n label: ({ t }) => t('dashboard:widgetSortFieldLabel'),\n },\n {\n name: 'sortDirection',\n type: 'select',\n defaultValue: 'desc',\n label: ({ t }) => t('dashboard:widgetSortDirectionLabel'),\n options: [\n {\n label: ({ t }) => t('general:ascending'),\n value: 'asc',\n },\n {\n label: ({ t }) => t('general:descending'),\n value: 'desc',\n },\n ],\n },\n {\n name: 'limit',\n type: 'number',\n defaultValue: 5,\n label: ({ t }) => t('dashboard:widgetLimitLabel'),\n max: 25,\n min: 1,\n },\n ]\n\n const recentlyViewedFields: NonNullable<Widget['fields']> = [\n {\n name: 'excludedCollections',\n type: 'select',\n admin: {\n components: {\n // Presents an inclusion filter (all collections checked by default) while persisting the\n // inverse as an exclusion list, so collections added later stay visible by default.\n Field: '@payloadcms/ui#RecentlyViewedCollectionsField',\n },\n description: ({ t }) => t('dashboard:widgetRecentlyViewedFilterDescription'),\n },\n hasMany: true,\n label: ({ t }) => t('general:collections'),\n // Exclusion list, so an empty value shows every collection and newly added collections are\n // included by default. Hidden collections are never offered as options.\n options: (config.collections ?? [])\n .filter((collection) => collection.admin?.hidden !== true)\n .map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n },\n ]\n\n const uploadCollections = (config.collections ?? []).filter(\n (collection) =>\n collection.upload &&\n collection.upload.bulkUpload !== false &&\n collection.admin?.hidden !== true,\n )\n\n const adminConfig: NonNullable<Config['admin']> = config.admin ?? { dashboard: { widgets: [] } }\n const dashboard: DashboardConfig = (adminConfig.dashboard ??= { widgets: [] })\n\n dashboard.widgets.push({\n slug: 'welcome',\n Component: '@payloadcms/ui/rsc#WelcomeWidget',\n label: ({ t }) => t('general:welcome'),\n maxWidth: 'full',\n minWidth: 'full',\n })\n dashboard.widgets.push({\n slug: 'collections',\n Component: '@payloadcms/ui/rsc#CollectionCards',\n minWidth: 'full',\n })\n dashboard.widgets.push({\n slug: 'collection-query',\n Component: '@payloadcms/ui/rsc#CollectionQueryWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: collectionQueryFields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n minWidth: 'x-small',\n })\n dashboard.widgets.push({\n slug: 'activity',\n Component: '@payloadcms/ui/rsc#RecentlyViewedWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: recentlyViewedFields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n label: ({ t }) => t('dashboard:widgetRecentsAndPinned'),\n minWidth: 'small',\n })\n if (uploadCollections.length > 0) {\n dashboard.widgets.push({\n slug: 'upload-dropzone',\n Component: '@payloadcms/ui/rsc#UploadDropzoneWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: [\n {\n name: 'excludedCollections',\n type: 'select',\n admin: {\n components: {\n Field: '@payloadcms/ui#UploadDropzoneCollectionsField',\n },\n },\n hasMany: true,\n label: ({ t }) => t('general:collections'),\n options: uploadCollections.map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n },\n ],\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n label: ({ t }) => t('dashboard:widgetUploadFiles'),\n minWidth: 'x-small',\n })\n }\n dashboard.defaultLayout ??= [\n {\n widgetSlug: 'welcome',\n width: 'full',\n } satisfies WidgetInstance,\n {\n widgetSlug: 'activity',\n width: 'full',\n } satisfies WidgetInstance,\n {\n widgetSlug: 'collections',\n width: 'full',\n } satisfies WidgetInstance,\n ]\n}\n\nexport const sanitizeConfig = (incomingConfig: Config): SanitizedConfig => {\n const configWithDefaults = addDefaultsToConfig(incomingConfig)\n const { duration, safetyBuffer } = configWithDefaults.jobs!.processingLease!\n if (!(safetyBuffer! >= 0 && safetyBuffer! < duration!)) {\n throw new InvalidConfiguration(\n '`jobs.processingLease.safetyBuffer` must be non-negative and less than `jobs.processingLease.duration`.',\n )\n }\n\n const config: Partial<SanitizedConfig> = sanitizeAdminConfig(configWithDefaults)\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n if (configWithDefaults.collections?.some(({ upload }) => upload)) {\n config.endpoints.push(uploadInstructionsEndpoint, ...stagedUploadEndpoints)\n }\n\n for (const endpoint of authRootEndpoints) {\n config.endpoints.push(endpoint)\n }\n\n if (config.localization) {\n // clone localization config so to not break everything\n const firstLocale = config.localization.locales[0]\n if (typeof firstLocale === 'string') {\n config.localization.localeCodes = [\n ...(config.localization as unknown as LocalizationConfigWithNoLabels).locales,\n ]\n\n // is string[], so convert to Locale[]\n config.localization.locales = (\n config.localization as unknown as LocalizationConfigWithNoLabels\n ).locales.map((locale) => ({\n code: locale,\n label: locale,\n rtl: false,\n toString: () => locale,\n }))\n } else {\n // is Locale[], so convert to string[] for localeCodes\n config.localization.localeCodes = config.localization.locales.map((locale) => locale.code)\n\n config.localization.locales = (\n config.localization as LocalizationConfigWithLabels\n ).locales.map((locale) => ({\n ...locale,\n toString: () => locale.code,\n }))\n }\n\n // Default fallback to true if not provided\n config.localization.fallback = config.localization?.fallback ?? true\n }\n\n const i18nConfig: SanitizedConfig['i18n'] = {\n fallbackLanguage: 'en',\n supportedLanguages: {\n en,\n },\n translations: {},\n }\n\n if (incomingConfig?.i18n) {\n i18nConfig.supportedLanguages =\n incomingConfig.i18n?.supportedLanguages || i18nConfig.supportedLanguages\n\n const supportedLangKeys = <AcceptedLanguages[]>Object.keys(i18nConfig.supportedLanguages)\n const fallbackLang = incomingConfig.i18n?.fallbackLanguage || i18nConfig.fallbackLanguage\n\n i18nConfig.fallbackLanguage = supportedLangKeys.includes(fallbackLang)\n ? fallbackLang\n : supportedLangKeys[0]!\n i18nConfig.translations =\n (incomingConfig.i18n?.translations as SanitizedConfig['i18n']['translations']) ||\n i18nConfig.translations\n }\n\n config.i18n = i18nConfig\n\n const richTextSanitizers: RichTextSanitizer[] = []\n\n const schedulePublishCollections: CollectionSlug[] = []\n\n const queryPresetsCollections: CollectionSlug[] = []\n\n const schedulePublishGlobals: GlobalSlug[] = []\n\n const collectionSlugs = new Set<CollectionSlug>()\n\n const validRelationships = [\n ...(config.collections?.map((c) => c.slug) ?? []),\n jobsCollectionSlug,\n lockedDocumentsCollectionSlug,\n preferencesCollectionSlug,\n ]\n\n const dashboardWidgets = config.admin?.dashboard?.widgets ?? ([] as Widget[])\n\n for (const widget of dashboardWidgets) {\n if (widget.fields?.length) {\n widget.fields = sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: widget.fields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n })\n }\n }\n\n /**\n * Blocks sanitization needs to happen before collections, as collection/global join field sanitization needs config.blocks\n * to be populated with the sanitized blocks\n */\n config.blocks = []\n\n if (incomingConfig.blocks?.length) {\n for (const block of incomingConfig.blocks) {\n const sanitizedBlock = block\n\n if (sanitizedBlock._sanitized === true) {\n continue\n }\n sanitizedBlock._sanitized = true\n\n sanitizedBlock.fields = sanitizedBlock.fields.concat(baseBlockFields)\n\n sanitizedBlock.labels = !sanitizedBlock.labels\n ? formatLabels(sanitizedBlock.slug)\n : sanitizedBlock.labels\n\n sanitizedBlock.fields = sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: sanitizedBlock.fields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n })\n\n const flattenedSanitizedBlock = flattenBlock({ block })\n\n config.blocks.push(flattenedSanitizedBlock)\n }\n }\n\n // Track orderable join fields during sanitization\n const orderableJoins: OrderableJoinInfo[] = []\n\n for (let i = 0; i < config.collections!.length; i++) {\n if (collectionSlugs.has(config.collections![i]!.slug)) {\n throw new DuplicateCollection('slug', config.collections![i]!.slug)\n }\n\n collectionSlugs.add(config.collections![i]!.slug)\n\n const draftsConfig = config.collections![i]?.versions?.drafts\n\n if (typeof draftsConfig === 'object' && draftsConfig.schedulePublish) {\n schedulePublishCollections.push(config.collections![i]!.slug)\n }\n\n if (config.collections![i]!.enableQueryPresets) {\n queryPresetsCollections.push(config.collections![i]!.slug)\n\n if (!validRelationships.includes(queryPresetsCollectionSlug)) {\n validRelationships.push(queryPresetsCollectionSlug)\n }\n }\n\n config.collections![i] = sanitizeCollection(\n config as unknown as Config,\n config.collections![i]!,\n richTextSanitizers,\n validRelationships,\n orderableJoins,\n )\n }\n\n // Process orderable features after all collections are sanitized\n const fieldsToAdd = new Map<SanitizedCollectionConfig, string[]>()\n const joinFieldPathsByCollection = new Map<string, Map<string, string>>()\n\n // Handle collection.orderable\n for (const collection of config.collections!) {\n if (collection.orderable) {\n const currentFields = fieldsToAdd.get(collection) || []\n fieldsToAdd.set(collection, [...currentFields, '_order'])\n collection.defaultSort = collection.defaultSort ?? '_order'\n }\n }\n\n // Handle orderable join fields (tracked during sanitization)\n for (const joinInfo of orderableJoins) {\n const targetCollection = config.collections!.find(\n (c) => c.slug === joinInfo.targetCollectionSlug,\n )\n if (targetCollection) {\n const currentFields = fieldsToAdd.get(targetCollection) || []\n fieldsToAdd.set(targetCollection, [...currentFields, joinInfo.orderFieldName])\n\n const currentJoinFieldPaths =\n joinFieldPathsByCollection.get(targetCollection.slug) || new Map<string, string>()\n currentJoinFieldPaths.set(joinInfo.orderFieldName, joinInfo.joinFieldOn)\n joinFieldPathsByCollection.set(targetCollection.slug, currentJoinFieldPaths)\n }\n }\n\n // Add fields, hooks, and update flattenedFields\n for (const [collection, orderableFields] of fieldsToAdd) {\n addOrderableFieldsAndHook(\n collection,\n config as unknown as Config,\n orderableFields,\n joinFieldPathsByCollection,\n )\n // Regenerate flattenedFields since we added new fields\n collection.flattenedFields = flattenAllFields({ fields: collection.fields })\n }\n\n // Add endpoint if any orderable features exist\n if (fieldsToAdd.size > 0) {\n addOrderableEndpoint(config as SanitizedConfig, joinFieldPathsByCollection)\n }\n\n if (config.globals!.length > 0) {\n for (let i = 0; i < config.globals!.length; i++) {\n if (hasScheduledPublishEnabled(config.globals![i]!)) {\n schedulePublishGlobals.push(config.globals![i]!.slug)\n }\n\n config.globals![i] = sanitizeGlobal(\n config as unknown as Config,\n config.globals![i]!,\n richTextSanitizers,\n validRelationships,\n )\n }\n }\n\n // Resolve hierarchy relationships across collections (also adds sidebar tabs)\n resolveHierarchyCollections(config as unknown as Config)\n\n if (schedulePublishCollections.length || schedulePublishGlobals.length) {\n ;((config.jobs ??= {} as SanitizedJobsConfig).tasks ??= []).push(\n getSchedulePublishTask({\n authCollectionSlugs: config\n .collections!.filter(({ auth }) => Boolean(auth))\n .map(({ slug }) => slug),\n collections: schedulePublishCollections,\n globals: schedulePublishGlobals,\n }),\n )\n }\n\n ;(config.jobs ??= {} as SanitizedJobsConfig).enabled = Boolean(\n (Array.isArray(configWithDefaults.jobs?.tasks) && configWithDefaults.jobs?.tasks?.length) ||\n (Array.isArray(configWithDefaults.jobs?.workflows) &&\n configWithDefaults.jobs?.workflows?.length),\n )\n config.jobs.hasConcurrency = Boolean(\n config.jobs.tasks?.some((task) => task.concurrency) ||\n config.jobs.workflows?.some((workflow) => workflow.concurrency),\n )\n\n // Need to add default jobs collection before locked documents collections\n if (config.jobs.enabled) {\n // Check for schedule property in both tasks and workflows\n const hasScheduleProperty =\n (config?.jobs?.tasks?.length && config.jobs.tasks.some((task) => task.schedule)) ||\n (config?.jobs?.workflows?.length &&\n config.jobs.workflows.some((workflow) => workflow.schedule))\n\n if (hasScheduleProperty) {\n config.jobs.scheduling = true\n }\n\n // Add payload-jobs-stats global for tracking job system metadata.\n ;(config.globals ??= []).push(\n sanitizeGlobal(\n config as unknown as Config,\n getJobStatsGlobal(),\n richTextSanitizers,\n validRelationships,\n ),\n )\n\n let defaultJobsCollection = getDefaultJobsCollection(config.jobs)\n\n if (typeof config.jobs.jobsCollectionOverrides === 'function') {\n defaultJobsCollection = config.jobs.jobsCollectionOverrides({\n defaultJobsCollection,\n })\n }\n const sanitizedJobsCollection = sanitizeCollection(\n config as unknown as Config,\n defaultJobsCollection,\n richTextSanitizers,\n validRelationships,\n )\n\n ;(config.collections ??= []).push(sanitizedJobsCollection)\n }\n\n const lockedDocumentsCollection = getLockedDocumentsCollection(config as unknown as Config)\n\n if (lockedDocumentsCollection) {\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n lockedDocumentsCollection,\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n getPreferencesCollection(config as unknown as Config),\n richTextSanitizers,\n validRelationships,\n ),\n )\n\n const migrations = sanitizeCollection(\n config as unknown as Config,\n migrationsCollection,\n richTextSanitizers,\n validRelationships,\n )\n\n // @ts-expect-error indexSortableFields is only valid for @payloadcms/db-mongodb\n if (config?.db?.indexSortableFields) {\n migrations.indexes = [\n {\n fields: ['batch', 'name'],\n unique: false,\n },\n ]\n }\n configWithDefaults.collections!.push(migrations)\n\n if (queryPresetsCollections.length > 0) {\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n getQueryPresetsConfig(config as unknown as Config),\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n addDefaultDashboardWidgets({\n config,\n richTextSanitizers,\n validRelationships,\n })\n\n if (config.serverURL !== '') {\n config.csrf!.push(config.serverURL!)\n }\n\n if (!config.storage) {\n config.storage = []\n }\n\n if (!config.upload) {\n config.upload = { adapters: [], transformers: [] }\n }\n\n config.upload.adapters = Array.from(\n new Set(config.collections!.map((c) => c.upload?.adapter).filter(Boolean) as string[]),\n )\n config.upload.transformers = config.upload.transformers ?? []\n\n // Pass through the email config as is so adapters don't break\n if (incomingConfig.email) {\n config.email = incomingConfig.email\n }\n\n if (typeof incomingConfig.editor === 'function') {\n config.editor = incomingConfig.editor({\n config: config as SanitizedConfig,\n isRoot: true,\n parentIsLocalized: false,\n })\n }\n\n if (config.llmInstructions !== false) {\n const instructionsCollection = addLLMInstructions({ config: config as SanitizedConfig })\n\n config.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n instructionsCollection,\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n for (const sanitizeRichText of richTextSanitizers) {\n sanitizeRichText(config as SanitizedConfig)\n }\n\n return config as SanitizedConfig\n}\n"],"names":["en","defaultUserCollection","authRootEndpoints","sanitizeCollection","migrationsCollection","DuplicateCollection","InvalidConfiguration","defaultTimezones","sanitizeGlobal","resolveHierarchyCollections","baseBlockFields","formatLabels","sanitizeFields","addLLMInstructions","getLockedDocumentsCollection","lockedDocumentsCollectionSlug","getPreferencesCollection","preferencesCollectionSlug","getQueryPresetsConfig","queryPresetsCollectionSlug","getDefaultJobsCollection","jobsCollectionSlug","getJobStatsGlobal","stagedUploadEndpoints","uploadInstructionsEndpoint","flattenAllFields","flattenBlock","hasScheduledPublishEnabled","validateTimezones","getSchedulePublishTask","addDefaultsToConfig","addOrderableEndpoint","addOrderableFieldsAndHook","sanitizeAdminConfig","configToSanitize","sanitizedConfig","loggingLevels","Forbidden","Locked","MissingFile","NotFound","ValidationError","admin","user","firstCollectionWithAuth","collections","find","auth","Boolean","slug","push","authCollections","filter","userCollection","timezones","supportedTimezones","source","addDefaultDashboardWidgets","config","richTextSanitizers","validRelationships","collectionQueryFields","name","type","label","t","options","collection","hidden","map","labels","plural","value","required","components","Field","defaultValue","max","min","recentlyViewedFields","description","hasMany","uploadCollections","upload","bulkUpload","adminConfig","dashboard","widgets","Component","maxWidth","minWidth","fields","existingFieldNames","Set","parentIsLocalized","length","defaultLayout","widgetSlug","width","sanitizeConfig","incomingConfig","configWithDefaults","duration","safetyBuffer","jobs","processingLease","endpoints","some","endpoint","localization","firstLocale","locales","localeCodes","locale","code","rtl","toString","fallback","i18nConfig","fallbackLanguage","supportedLanguages","translations","i18n","supportedLangKeys","Object","keys","fallbackLang","includes","schedulePublishCollections","queryPresetsCollections","schedulePublishGlobals","collectionSlugs","c","dashboardWidgets","widget","blocks","block","sanitizedBlock","_sanitized","concat","flattenedSanitizedBlock","orderableJoins","i","has","add","draftsConfig","versions","drafts","schedulePublish","enableQueryPresets","fieldsToAdd","Map","joinFieldPathsByCollection","orderable","currentFields","get","set","defaultSort","joinInfo","targetCollection","targetCollectionSlug","orderFieldName","currentJoinFieldPaths","joinFieldOn","orderableFields","flattenedFields","size","globals","tasks","authCollectionSlugs","enabled","Array","isArray","workflows","hasConcurrency","task","concurrency","workflow","hasScheduleProperty","schedule","scheduling","defaultJobsCollection","jobsCollectionOverrides","sanitizedJobsCollection","lockedDocumentsCollection","migrations","db","indexSortableFields","indexes","unique","serverURL","csrf","storage","adapters","transformers","from","adapter","email","editor","isRoot","llmInstructions","instructionsCollection","sanitizeRichText"],"mappings":"AAEA,SAASA,EAAE,QAAQ,wCAAuC;AAiB1D,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,kBAAkB,QAAQ,oCAAmC;AACtE,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,qBAAoB;AAC9E,SAASC,gBAAgB,QAAQ,oDAAmD;AACpF,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,eAAe,EAAEC,YAAY,EAAEC,cAAc,QAAQ,cAAa;AAC3E,SAASC,kBAAkB,QAAQ,4CAA2C;AAC9E,SACEC,4BAA4B,EAC5BC,6BAA6B,QACxB,gCAA+B;AACtC,SAASC,wBAAwB,EAAEC,yBAAyB,QAAQ,2BAA0B;AAC9F,SAASC,qBAAqB,EAAEC,0BAA0B,QAAQ,6BAA4B;AAC9F,SAASC,wBAAwB,EAAEC,kBAAkB,QAAQ,iCAAgC;AAC7F,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SACEC,qBAAqB,EACrBC,0BAA0B,QACrB,6CAA4C;AACnD,SAASC,gBAAgB,EAAEC,YAAY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IAAI,CAAE7I,IAAI,CAACQ,OAAOoI,SAAS;IACpC;IAEA,IAAI,CAACpI,OAAOsI,OAAO,EAAE;QACnBtI,OAAOsI,OAAO,GAAG,EAAE;IACrB;IAEA,IAAI,CAACtI,OAAOyB,MAAM,EAAE;QAClBzB,OAAOyB,MAAM,GAAG;YAAE8G,UAAU,EAAE;YAAEC,cAAc,EAAE;QAAC;IACnD;IAEAxI,OAAOyB,MAAM,CAAC8G,QAAQ,GAAGtB,MAAMwB,IAAI,CACjC,IAAItG,IAAInC,OAAOb,WAAW,CAAEwB,GAAG,CAAC,CAAC+D,IAAMA,EAAEjD,MAAM,EAAEiH,SAAShJ,MAAM,CAACJ;IAEnEU,OAAOyB,MAAM,CAAC+G,YAAY,GAAGxI,OAAOyB,MAAM,CAAC+G,YAAY,IAAI,EAAE;IAE7D,8DAA8D;IAC9D,IAAI9F,eAAeiG,KAAK,EAAE;QACxB3I,OAAO2I,KAAK,GAAGjG,eAAeiG,KAAK;IACrC;IAEA,IAAI,OAAOjG,eAAekG,MAAM,KAAK,YAAY;QAC/C5I,OAAO4I,MAAM,GAAGlG,eAAekG,MAAM,CAAC;YACpC5I,QAAQA;YACR6I,QAAQ;YACRzG,mBAAmB;QACrB;IACF;IAEA,IAAIpC,OAAO8I,eAAe,KAAK,OAAO;QACpC,MAAMC,yBAAyB5L,mBAAmB;YAAE6C,QAAQA;QAA0B;QAEtFA,OAAOb,WAAW,CAAEK,IAAI,CACtB/C,mBACEuD,QACA+I,wBACA9I,oBACAC;IAGN;IAEA,KAAK,MAAM8I,oBAAoB/I,mBAAoB;QACjD+I,iBAAiBhJ;IACnB;IAEA,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/config/sanitize.ts"],"sourcesContent":["import type { AcceptedLanguages } from '@payloadcms/translations'\n\nimport { en } from '@payloadcms/translations/languages/en'\n\nimport type { RichTextSanitizer } from '../fields/config/sanitize.js'\nimport type { OrderableJoinInfo } from '../fields/config/sanitizeJoinField.js'\nimport type { CollectionSlug, GlobalSlug, SanitizedCollectionConfig } from '../index.js'\nimport type { SanitizedJobsConfig } from '../queues/config/types/index.js'\nimport type {\n Config,\n DashboardConfig,\n LocalizationConfigWithLabels,\n LocalizationConfigWithNoLabels,\n SanitizedConfig,\n Timezone,\n Widget,\n WidgetInstance,\n} from './types.js'\n\nimport { defaultUserCollection } from '../auth/defaultUser.js'\nimport { authRootEndpoints } from '../auth/endpoints/index.js'\nimport { sanitizeCollection } from '../collections/config/sanitize.js'\nimport { migrationsCollection } from '../database/migrations/migrationsCollection.js'\nimport { DuplicateCollection, InvalidConfiguration } from '../errors/index.js'\nimport { defaultTimezones } from '../fields/baseFields/timezone/defaultTimezones.js'\nimport { sanitizeGlobal } from '../globals/config/sanitize.js'\nimport { resolveHierarchyCollections } from '../hierarchy/resolveHierarchyCollections.js'\nimport { baseBlockFields, formatLabels, sanitizeFields } from '../index.js'\nimport { addLLMInstructions } from '../llm-instructions/addLLMInstructions.js'\nimport {\n getLockedDocumentsCollection,\n lockedDocumentsCollectionSlug,\n} from '../locked-documents/config.js'\nimport { getPreferencesCollection, preferencesCollectionSlug } from '../preferences/config.js'\nimport { getQueryPresetsConfig, queryPresetsCollectionSlug } from '../query-presets/config.js'\nimport { getDefaultJobsCollection, jobsCollectionSlug } from '../queues/config/collection.js'\nimport { getJobStatsGlobal } from '../queues/config/global.js'\nimport {\n stagedUploadEndpoints,\n uploadInstructionsEndpoint,\n} from '../uploads/endpoints/uploadInstructions.js'\nimport { flattenAllFields, flattenBlock } from '../utilities/flattenAllFields.js'\nimport { hasScheduledPublishEnabled } from '../utilities/getVersionsConfig.js'\nimport { validateTimezones } from '../utilities/validateTimezones.js'\nimport { getSchedulePublishTask } from '../versions/schedule/job.js'\nimport { addDefaultsToConfig } from './defaults.js'\nimport { addOrderableEndpoint, addOrderableFieldsAndHook } from './orderable/index.js'\n\nconst sanitizeAdminConfig = (configToSanitize: Config): Partial<SanitizedConfig> => {\n const sanitizedConfig = { ...configToSanitize }\n\n // default logging level will be 'error' if not provided\n sanitizedConfig.loggingLevels = {\n Forbidden: 'info',\n Locked: 'info',\n MissingFile: 'info',\n NotFound: 'info',\n ValidationError: 'info',\n ...(sanitizedConfig.loggingLevels || {}),\n }\n // add default user collection if none provided\n if (!sanitizedConfig?.admin?.user) {\n const firstCollectionWithAuth = sanitizedConfig.collections!.find(({ auth }) => Boolean(auth))\n\n if (firstCollectionWithAuth) {\n sanitizedConfig.admin!.user = firstCollectionWithAuth.slug\n } else {\n sanitizedConfig.admin!.user = defaultUserCollection.slug\n sanitizedConfig.collections!.push(defaultUserCollection)\n }\n }\n\n const authCollections = sanitizedConfig.collections!.filter(({ auth }) => Boolean(auth))\n\n const userCollection = authCollections.find(({ slug }) => slug === sanitizedConfig.admin!.user)\n\n if (!userCollection || !userCollection.auth) {\n throw new InvalidConfiguration(\n `${sanitizedConfig.admin!.user} is not a valid admin user collection`,\n )\n }\n\n if (sanitizedConfig?.admin?.timezones) {\n if (typeof configToSanitize?.admin?.timezones?.supportedTimezones === 'function') {\n sanitizedConfig.admin.timezones.supportedTimezones =\n configToSanitize.admin.timezones.supportedTimezones({ defaultTimezones })\n }\n\n if (!sanitizedConfig?.admin?.timezones?.supportedTimezones) {\n sanitizedConfig.admin.timezones.supportedTimezones = defaultTimezones\n }\n } else {\n sanitizedConfig.admin!.timezones = {\n supportedTimezones: defaultTimezones,\n }\n }\n\n validateTimezones({\n source: 'admin.timezones.supportedTimezones',\n timezones: sanitizedConfig.admin!.timezones.supportedTimezones as Timezone[],\n })\n\n return sanitizedConfig as unknown as Partial<SanitizedConfig>\n}\n\nconst addDefaultDashboardWidgets = ({\n config,\n richTextSanitizers,\n validRelationships,\n}: {\n config: Partial<SanitizedConfig>\n richTextSanitizers: RichTextSanitizer[]\n validRelationships: string[]\n}): void => {\n const collectionQueryFields: NonNullable<Widget['fields']> = [\n {\n name: 'title',\n type: 'text',\n label: ({ t }) => t('dashboard:widgetTitleLabel'),\n },\n {\n name: 'relatedCollection',\n type: 'select',\n label: ({ t }) => t('general:collection'),\n // Only offer collections that are visible in the admin UI. Collections hidden via a function\n // are kept since they may still be visible for some users.\n options: (config.collections ?? [])\n .filter((collection) => collection.admin?.hidden !== true)\n .map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n required: true,\n },\n {\n name: 'where',\n type: 'json',\n admin: {\n components: {\n Field: '@payloadcms/ui#QueryPresetsWhereField',\n },\n },\n label: ({ t }) => t('general:filters'),\n },\n {\n name: 'sortField',\n type: 'text',\n admin: {\n components: {\n Field: '@payloadcms/ui#CollectionQuerySortField',\n },\n },\n label: ({ t }) => t('dashboard:widgetSortFieldLabel'),\n },\n {\n name: 'sortDirection',\n type: 'select',\n defaultValue: 'desc',\n label: ({ t }) => t('dashboard:widgetSortDirectionLabel'),\n options: [\n {\n label: ({ t }) => t('general:ascending'),\n value: 'asc',\n },\n {\n label: ({ t }) => t('general:descending'),\n value: 'desc',\n },\n ],\n },\n {\n name: 'limit',\n type: 'number',\n defaultValue: 5,\n label: ({ t }) => t('dashboard:widgetLimitLabel'),\n max: 25,\n min: 1,\n },\n ]\n\n const recentlyViewedFields: NonNullable<Widget['fields']> = [\n {\n name: 'excludedCollections',\n type: 'select',\n admin: {\n components: {\n // Presents an inclusion filter (all collections checked by default) while persisting the\n // inverse as an exclusion list, so collections added later stay visible by default.\n Field: '@payloadcms/ui#CollectionFilter',\n },\n description: ({ t }) => t('dashboard:widgetRecentlyViewedFilterDescription'),\n },\n hasMany: true,\n label: ({ t }) => t('general:collections'),\n // Exclusion list, so an empty value shows every collection and newly added collections are\n // included by default. Hidden collections are never offered as options.\n options: (config.collections ?? [])\n .filter((collection) => collection.admin?.hidden !== true)\n .map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n },\n ]\n\n const uploadCollections = (config.collections ?? []).filter(\n (collection) =>\n collection.upload &&\n collection.upload.bulkUpload !== false &&\n collection.admin?.hidden !== true,\n )\n\n const adminConfig: NonNullable<Config['admin']> = config.admin ?? { dashboard: { widgets: [] } }\n const dashboard: DashboardConfig = (adminConfig.dashboard ??= { widgets: [] })\n\n dashboard.widgets.push({\n slug: 'welcome',\n Component: '@payloadcms/ui/rsc#WelcomeWidget',\n label: ({ t }) => t('general:welcome'),\n maxWidth: 'full',\n minWidth: 'full',\n })\n dashboard.widgets.push({\n slug: 'collections',\n Component: '@payloadcms/ui/rsc#CollectionCards',\n minWidth: 'full',\n })\n dashboard.widgets.push({\n slug: 'collection-query',\n Component: '@payloadcms/ui/rsc#CollectionQueryWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: collectionQueryFields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n minWidth: 'x-small',\n })\n dashboard.widgets.push({\n slug: 'activity',\n Component: '@payloadcms/ui/rsc#ActivityWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: recentlyViewedFields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n label: ({ t }) => t('dashboard:widgetRecentsAndPinned'),\n minWidth: 'small',\n })\n if (uploadCollections.length > 0) {\n dashboard.widgets.push({\n slug: 'upload-dropzone',\n Component: '@payloadcms/ui/rsc#UploadDropzoneWidget',\n fields: sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: [\n {\n name: 'excludedCollections',\n type: 'select',\n admin: {\n components: {\n Field: '@payloadcms/ui#UploadDropzoneCollectionsField',\n },\n },\n hasMany: true,\n label: ({ t }) => t('general:collections'),\n options: uploadCollections.map((collection) => ({\n label: collection.labels?.plural || collection.slug,\n value: collection.slug,\n })),\n },\n ],\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n }),\n label: ({ t }) => t('dashboard:widgetUploadFiles'),\n minWidth: 'x-small',\n })\n }\n dashboard.defaultLayout ??= [\n {\n widgetSlug: 'welcome',\n width: 'full',\n } satisfies WidgetInstance,\n {\n widgetSlug: 'activity',\n width: 'full',\n } satisfies WidgetInstance,\n {\n widgetSlug: 'collections',\n width: 'full',\n } satisfies WidgetInstance,\n ]\n}\n\nexport const sanitizeConfig = (incomingConfig: Config): SanitizedConfig => {\n const configWithDefaults = addDefaultsToConfig(incomingConfig)\n const { duration, safetyBuffer } = configWithDefaults.jobs!.processingLease!\n if (!(safetyBuffer! >= 0 && safetyBuffer! < duration!)) {\n throw new InvalidConfiguration(\n '`jobs.processingLease.safetyBuffer` must be non-negative and less than `jobs.processingLease.duration`.',\n )\n }\n\n const config: Partial<SanitizedConfig> = sanitizeAdminConfig(configWithDefaults)\n\n if (!config.endpoints) {\n config.endpoints = []\n }\n\n if (configWithDefaults.collections?.some(({ upload }) => upload)) {\n config.endpoints.push(uploadInstructionsEndpoint, ...stagedUploadEndpoints)\n }\n\n for (const endpoint of authRootEndpoints) {\n config.endpoints.push(endpoint)\n }\n\n if (config.localization) {\n // clone localization config so to not break everything\n const firstLocale = config.localization.locales[0]\n if (typeof firstLocale === 'string') {\n config.localization.localeCodes = [\n ...(config.localization as unknown as LocalizationConfigWithNoLabels).locales,\n ]\n\n // is string[], so convert to Locale[]\n config.localization.locales = (\n config.localization as unknown as LocalizationConfigWithNoLabels\n ).locales.map((locale) => ({\n code: locale,\n label: locale,\n rtl: false,\n toString: () => locale,\n }))\n } else {\n // is Locale[], so convert to string[] for localeCodes\n config.localization.localeCodes = config.localization.locales.map((locale) => locale.code)\n\n config.localization.locales = (\n config.localization as LocalizationConfigWithLabels\n ).locales.map((locale) => ({\n ...locale,\n toString: () => locale.code,\n }))\n }\n\n // Default fallback to true if not provided\n config.localization.fallback = config.localization?.fallback ?? true\n }\n\n const i18nConfig: SanitizedConfig['i18n'] = {\n fallbackLanguage: 'en',\n supportedLanguages: {\n en,\n },\n translations: {},\n }\n\n if (incomingConfig?.i18n) {\n i18nConfig.supportedLanguages =\n incomingConfig.i18n?.supportedLanguages || i18nConfig.supportedLanguages\n\n const supportedLangKeys = <AcceptedLanguages[]>Object.keys(i18nConfig.supportedLanguages)\n const fallbackLang = incomingConfig.i18n?.fallbackLanguage || i18nConfig.fallbackLanguage\n\n i18nConfig.fallbackLanguage = supportedLangKeys.includes(fallbackLang)\n ? fallbackLang\n : supportedLangKeys[0]!\n i18nConfig.translations =\n (incomingConfig.i18n?.translations as SanitizedConfig['i18n']['translations']) ||\n i18nConfig.translations\n }\n\n config.i18n = i18nConfig\n\n const richTextSanitizers: RichTextSanitizer[] = []\n\n const schedulePublishCollections: CollectionSlug[] = []\n\n const queryPresetsCollections: CollectionSlug[] = []\n\n const schedulePublishGlobals: GlobalSlug[] = []\n\n const collectionSlugs = new Set<CollectionSlug>()\n\n const validRelationships = [\n ...(config.collections?.map((c) => c.slug) ?? []),\n jobsCollectionSlug,\n lockedDocumentsCollectionSlug,\n preferencesCollectionSlug,\n ]\n\n const dashboardWidgets = config.admin?.dashboard?.widgets ?? ([] as Widget[])\n\n for (const widget of dashboardWidgets) {\n if (widget.fields?.length) {\n widget.fields = sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: widget.fields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n })\n }\n }\n\n /**\n * Blocks sanitization needs to happen before collections, as collection/global join field sanitization needs config.blocks\n * to be populated with the sanitized blocks\n */\n config.blocks = []\n\n if (incomingConfig.blocks?.length) {\n for (const block of incomingConfig.blocks) {\n const sanitizedBlock = block\n\n if (sanitizedBlock._sanitized === true) {\n continue\n }\n sanitizedBlock._sanitized = true\n\n sanitizedBlock.fields = sanitizedBlock.fields.concat(baseBlockFields)\n\n sanitizedBlock.labels = !sanitizedBlock.labels\n ? formatLabels(sanitizedBlock.slug)\n : sanitizedBlock.labels\n\n sanitizedBlock.fields = sanitizeFields({\n config: config as unknown as Config,\n existingFieldNames: new Set(),\n fields: sanitizedBlock.fields,\n parentIsLocalized: false,\n richTextSanitizers,\n validRelationships,\n })\n\n const flattenedSanitizedBlock = flattenBlock({ block })\n\n config.blocks.push(flattenedSanitizedBlock)\n }\n }\n\n // Track orderable join fields during sanitization\n const orderableJoins: OrderableJoinInfo[] = []\n\n for (let i = 0; i < config.collections!.length; i++) {\n if (collectionSlugs.has(config.collections![i]!.slug)) {\n throw new DuplicateCollection('slug', config.collections![i]!.slug)\n }\n\n collectionSlugs.add(config.collections![i]!.slug)\n\n const draftsConfig = config.collections![i]?.versions?.drafts\n\n if (typeof draftsConfig === 'object' && draftsConfig.schedulePublish) {\n schedulePublishCollections.push(config.collections![i]!.slug)\n }\n\n if (config.collections![i]!.enableQueryPresets) {\n queryPresetsCollections.push(config.collections![i]!.slug)\n\n if (!validRelationships.includes(queryPresetsCollectionSlug)) {\n validRelationships.push(queryPresetsCollectionSlug)\n }\n }\n\n config.collections![i] = sanitizeCollection(\n config as unknown as Config,\n config.collections![i]!,\n richTextSanitizers,\n validRelationships,\n orderableJoins,\n )\n }\n\n // Process orderable features after all collections are sanitized\n const fieldsToAdd = new Map<SanitizedCollectionConfig, string[]>()\n const joinFieldPathsByCollection = new Map<string, Map<string, string>>()\n\n // Handle collection.orderable\n for (const collection of config.collections!) {\n if (collection.orderable) {\n const currentFields = fieldsToAdd.get(collection) || []\n fieldsToAdd.set(collection, [...currentFields, '_order'])\n collection.defaultSort = collection.defaultSort ?? '_order'\n }\n }\n\n // Handle orderable join fields (tracked during sanitization)\n for (const joinInfo of orderableJoins) {\n const targetCollection = config.collections!.find(\n (c) => c.slug === joinInfo.targetCollectionSlug,\n )\n if (targetCollection) {\n const currentFields = fieldsToAdd.get(targetCollection) || []\n fieldsToAdd.set(targetCollection, [...currentFields, joinInfo.orderFieldName])\n\n const currentJoinFieldPaths =\n joinFieldPathsByCollection.get(targetCollection.slug) || new Map<string, string>()\n currentJoinFieldPaths.set(joinInfo.orderFieldName, joinInfo.joinFieldOn)\n joinFieldPathsByCollection.set(targetCollection.slug, currentJoinFieldPaths)\n }\n }\n\n // Add fields, hooks, and update flattenedFields\n for (const [collection, orderableFields] of fieldsToAdd) {\n addOrderableFieldsAndHook(\n collection,\n config as unknown as Config,\n orderableFields,\n joinFieldPathsByCollection,\n )\n // Regenerate flattenedFields since we added new fields\n collection.flattenedFields = flattenAllFields({ fields: collection.fields })\n }\n\n // Add endpoint if any orderable features exist\n if (fieldsToAdd.size > 0) {\n addOrderableEndpoint(config as SanitizedConfig, joinFieldPathsByCollection)\n }\n\n if (config.globals!.length > 0) {\n for (let i = 0; i < config.globals!.length; i++) {\n if (hasScheduledPublishEnabled(config.globals![i]!)) {\n schedulePublishGlobals.push(config.globals![i]!.slug)\n }\n\n config.globals![i] = sanitizeGlobal(\n config as unknown as Config,\n config.globals![i]!,\n richTextSanitizers,\n validRelationships,\n )\n }\n }\n\n // Resolve hierarchy relationships across collections (also adds sidebar tabs)\n resolveHierarchyCollections(config as unknown as Config)\n\n if (schedulePublishCollections.length || schedulePublishGlobals.length) {\n ;((config.jobs ??= {} as SanitizedJobsConfig).tasks ??= []).push(\n getSchedulePublishTask({\n authCollectionSlugs: config\n .collections!.filter(({ auth }) => Boolean(auth))\n .map(({ slug }) => slug),\n collections: schedulePublishCollections,\n globals: schedulePublishGlobals,\n }),\n )\n }\n\n ;(config.jobs ??= {} as SanitizedJobsConfig).enabled = Boolean(\n (Array.isArray(configWithDefaults.jobs?.tasks) && configWithDefaults.jobs?.tasks?.length) ||\n (Array.isArray(configWithDefaults.jobs?.workflows) &&\n configWithDefaults.jobs?.workflows?.length),\n )\n config.jobs.hasConcurrency = Boolean(\n config.jobs.tasks?.some((task) => task.concurrency) ||\n config.jobs.workflows?.some((workflow) => workflow.concurrency),\n )\n\n // Need to add default jobs collection before locked documents collections\n if (config.jobs.enabled) {\n // Check for schedule property in both tasks and workflows\n const hasScheduleProperty =\n (config?.jobs?.tasks?.length && config.jobs.tasks.some((task) => task.schedule)) ||\n (config?.jobs?.workflows?.length &&\n config.jobs.workflows.some((workflow) => workflow.schedule))\n\n if (hasScheduleProperty) {\n config.jobs.scheduling = true\n }\n\n // Add payload-jobs-stats global for tracking job system metadata.\n ;(config.globals ??= []).push(\n sanitizeGlobal(\n config as unknown as Config,\n getJobStatsGlobal(),\n richTextSanitizers,\n validRelationships,\n ),\n )\n\n let defaultJobsCollection = getDefaultJobsCollection(config.jobs)\n\n if (typeof config.jobs.jobsCollectionOverrides === 'function') {\n defaultJobsCollection = config.jobs.jobsCollectionOverrides({\n defaultJobsCollection,\n })\n }\n const sanitizedJobsCollection = sanitizeCollection(\n config as unknown as Config,\n defaultJobsCollection,\n richTextSanitizers,\n validRelationships,\n )\n\n ;(config.collections ??= []).push(sanitizedJobsCollection)\n }\n\n const lockedDocumentsCollection = getLockedDocumentsCollection(config as unknown as Config)\n\n if (lockedDocumentsCollection) {\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n lockedDocumentsCollection,\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n getPreferencesCollection(config as unknown as Config),\n richTextSanitizers,\n validRelationships,\n ),\n )\n\n const migrations = sanitizeCollection(\n config as unknown as Config,\n migrationsCollection,\n richTextSanitizers,\n validRelationships,\n )\n\n // @ts-expect-error indexSortableFields is only valid for @payloadcms/db-mongodb\n if (config?.db?.indexSortableFields) {\n migrations.indexes = [\n {\n fields: ['batch', 'name'],\n unique: false,\n },\n ]\n }\n configWithDefaults.collections!.push(migrations)\n\n if (queryPresetsCollections.length > 0) {\n configWithDefaults.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n getQueryPresetsConfig(config as unknown as Config),\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n addDefaultDashboardWidgets({\n config,\n richTextSanitizers,\n validRelationships,\n })\n\n if (config.serverURL !== '') {\n config.csrf!.push(config.serverURL!)\n }\n\n if (!config.storage) {\n config.storage = []\n }\n\n if (!config.upload) {\n config.upload = { adapters: [], transformers: [] }\n }\n\n config.upload.adapters = Array.from(\n new Set(config.collections!.map((c) => c.upload?.adapter).filter(Boolean) as string[]),\n )\n config.upload.transformers = config.upload.transformers ?? []\n\n // Pass through the email config as is so adapters don't break\n if (incomingConfig.email) {\n config.email = incomingConfig.email\n }\n\n if (typeof incomingConfig.editor === 'function') {\n config.editor = incomingConfig.editor({\n config: config as SanitizedConfig,\n isRoot: true,\n parentIsLocalized: false,\n })\n }\n\n if (config.llmInstructions !== false) {\n const instructionsCollection = addLLMInstructions({ config: config as SanitizedConfig })\n\n config.collections!.push(\n sanitizeCollection(\n config as unknown as Config,\n instructionsCollection,\n richTextSanitizers,\n validRelationships,\n ),\n )\n }\n\n for (const sanitizeRichText of richTextSanitizers) {\n sanitizeRichText(config as SanitizedConfig)\n }\n\n return config as SanitizedConfig\n}\n"],"names":["en","defaultUserCollection","authRootEndpoints","sanitizeCollection","migrationsCollection","DuplicateCollection","InvalidConfiguration","defaultTimezones","sanitizeGlobal","resolveHierarchyCollections","baseBlockFields","formatLabels","sanitizeFields","addLLMInstructions","getLockedDocumentsCollection","lockedDocumentsCollectionSlug","getPreferencesCollection","preferencesCollectionSlug","getQueryPresetsConfig","queryPresetsCollectionSlug","getDefaultJobsCollection","jobsCollectionSlug","getJobStatsGlobal","stagedUploadEndpoints","uploadInstructionsEndpoint","flattenAllFields","flattenBlock","hasScheduledPublishEnabled","validateTimezones","getSchedulePublishTask","addDefaultsToConfig","addOrderableEndpoint","addOrderableFieldsAndHook","sanitizeAdminConfig","configToSanitize","sanitizedConfig","loggingLevels","Forbidden","Locked","MissingFile","NotFound","ValidationError","admin","user","firstCollectionWithAuth","collections","find","auth","Boolean","slug","push","authCollections","filter","userCollection","timezones","supportedTimezones","source","addDefaultDashboardWidgets","config","richTextSanitizers","validRelationships","collectionQueryFields","name","type","label","t","options","collection","hidden","map","labels","plural","value","required","components","Field","defaultValue","max","min","recentlyViewedFields","description","hasMany","uploadCollections","upload","bulkUpload","adminConfig","dashboard","widgets","Component","maxWidth","minWidth","fields","existingFieldNames","Set","parentIsLocalized","length","defaultLayout","widgetSlug","width","sanitizeConfig","incomingConfig","configWithDefaults","duration","safetyBuffer","jobs","processingLease","endpoints","some","endpoint","localization","firstLocale","locales","localeCodes","locale","code","rtl","toString","fallback","i18nConfig","fallbackLanguage","supportedLanguages","translations","i18n","supportedLangKeys","Object","keys","fallbackLang","includes","schedulePublishCollections","queryPresetsCollections","schedulePublishGlobals","collectionSlugs","c","dashboardWidgets","widget","blocks","block","sanitizedBlock","_sanitized","concat","flattenedSanitizedBlock","orderableJoins","i","has","add","draftsConfig","versions","drafts","schedulePublish","enableQueryPresets","fieldsToAdd","Map","joinFieldPathsByCollection","orderable","currentFields","get","set","defaultSort","joinInfo","targetCollection","targetCollectionSlug","orderFieldName","currentJoinFieldPaths","joinFieldOn","orderableFields","flattenedFields","size","globals","tasks","authCollectionSlugs","enabled","Array","isArray","workflows","hasConcurrency","task","concurrency","workflow","hasScheduleProperty","schedule","scheduling","defaultJobsCollection","jobsCollectionOverrides","sanitizedJobsCollection","lockedDocumentsCollection","migrations","db","indexSortableFields","indexes","unique","serverURL","csrf","storage","adapters","transformers","from","adapter","email","editor","isRoot","llmInstructions","instructionsCollection","sanitizeRichText"],"mappings":"AAEA,SAASA,EAAE,QAAQ,wCAAuC;AAiB1D,SAASC,qBAAqB,QAAQ,yBAAwB;AAC9D,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,kBAAkB,QAAQ,oCAAmC;AACtE,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,qBAAoB;AAC9E,SAASC,gBAAgB,QAAQ,oDAAmD;AACpF,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SAASC,2BAA2B,QAAQ,8CAA6C;AACzF,SAASC,eAAe,EAAEC,YAAY,EAAEC,cAAc,QAAQ,cAAa;AAC3E,SAASC,kBAAkB,QAAQ,4CAA2C;AAC9E,SACEC,4BAA4B,EAC5BC,6BAA6B,QACxB,gCAA+B;AACtC,SAASC,wBAAwB,EAAE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BAAoB;QACjD+I,iBAAiBhJ;IACnB;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-only Payload packages that can skip development transforms.
|
|
3
|
+
* Packages with client components loaded by the import map must remain bundled.
|
|
4
|
+
* Production bundling preserves tree-shaking and avoids duplicate dependencies.
|
|
5
|
+
*/
|
|
6
|
+
export declare const devServerExternalPackages: string[];
|
|
7
|
+
/** Third-party packages that both framework adapters externalize in development and production. */
|
|
8
|
+
export declare const serverExternalPackages: string[];
|
|
9
|
+
//# sourceMappingURL=build-config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-config.d.ts","sourceRoot":"","sources":["../../src/exports/build-config.js"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,UAmBrC,CAAA;AAED,mGAAmG;AACnG,eAAO,MAAM,sBAAsB,UAWlC,CAAA"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-only Payload packages that can skip development transforms.
|
|
3
|
+
* Packages with client components loaded by the import map must remain bundled.
|
|
4
|
+
* Production bundling preserves tree-shaking and avoids duplicate dependencies.
|
|
5
|
+
*/ export const devServerExternalPackages = [
|
|
6
|
+
'payload',
|
|
7
|
+
'@payloadcms/db-mongodb',
|
|
8
|
+
'@payloadcms/db-postgres',
|
|
9
|
+
'@payloadcms/db-sqlite',
|
|
10
|
+
'@payloadcms/db-vercel-postgres',
|
|
11
|
+
'@payloadcms/db-d1-sqlite',
|
|
12
|
+
'@payloadcms/drizzle',
|
|
13
|
+
'@payloadcms/email-nodemailer',
|
|
14
|
+
'@payloadcms/email-resend',
|
|
15
|
+
'@payloadcms/graphql',
|
|
16
|
+
'@payloadcms/kv-redis',
|
|
17
|
+
'@payloadcms/payload-cloud',
|
|
18
|
+
// Its `/client` entry has no exports, so the import map never loads anything from it.
|
|
19
|
+
'@payloadcms/plugin-mcp',
|
|
20
|
+
'@payloadcms/plugin-nested-docs',
|
|
21
|
+
'@payloadcms/plugin-redirects',
|
|
22
|
+
'@payloadcms/transformer-sharp',
|
|
23
|
+
'@payloadcms/translations'
|
|
24
|
+
];
|
|
25
|
+
/** Third-party packages that both framework adapters externalize in development and production. */ export const serverExternalPackages = [
|
|
26
|
+
// GraphQL requires a single runtime instance across bundled and external packages.
|
|
27
|
+
'graphql',
|
|
28
|
+
'drizzle-kit',
|
|
29
|
+
'drizzle-kit/api',
|
|
30
|
+
'sharp',
|
|
31
|
+
'libsql',
|
|
32
|
+
'require-in-the-middle',
|
|
33
|
+
'json-schema-to-typescript',
|
|
34
|
+
// Bundling pino's thread-stream dependency causes Turbopack build errors.
|
|
35
|
+
'pino'
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=build-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/exports/build-config.js"],"sourcesContent":["/**\n * Server-only Payload packages that can skip development transforms.\n * Packages with client components loaded by the import map must remain bundled.\n * Production bundling preserves tree-shaking and avoids duplicate dependencies.\n */\nexport const devServerExternalPackages = [\n 'payload',\n '@payloadcms/db-mongodb',\n '@payloadcms/db-postgres',\n '@payloadcms/db-sqlite',\n '@payloadcms/db-vercel-postgres',\n '@payloadcms/db-d1-sqlite',\n '@payloadcms/drizzle',\n '@payloadcms/email-nodemailer',\n '@payloadcms/email-resend',\n '@payloadcms/graphql',\n '@payloadcms/kv-redis',\n '@payloadcms/payload-cloud',\n // Its `/client` entry has no exports, so the import map never loads anything from it.\n '@payloadcms/plugin-mcp',\n '@payloadcms/plugin-nested-docs',\n '@payloadcms/plugin-redirects',\n '@payloadcms/transformer-sharp',\n '@payloadcms/translations',\n]\n\n/** Third-party packages that both framework adapters externalize in development and production. */\nexport const serverExternalPackages = [\n // GraphQL requires a single runtime instance across bundled and external packages.\n 'graphql',\n 'drizzle-kit',\n 'drizzle-kit/api',\n 'sharp',\n 'libsql',\n 'require-in-the-middle',\n 'json-schema-to-typescript',\n // Bundling pino's thread-stream dependency causes Turbopack build errors.\n 'pino',\n]\n"],"names":["devServerExternalPackages","serverExternalPackages"],"mappings":"AAAA;;;;CAIC,GACD,OAAO,MAAMA,4BAA4B;IACvC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,sFAAsF;IACtF;IACA;IACA;IACA;IACA;CACD,CAAA;AAED,iGAAiG,GACjG,OAAO,MAAMC,yBAAyB;IACpC,mFAAmF;IACnF;IACA;IACA;IACA;IACA;IACA;IACA;IACA,0EAA0E;IAC1E;CACD,CAAA"}
|