payload 4.0.0-beta.2 → 4.0.0-beta.4
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/serverFunctions/cookies.js.map +1 -1
- package/dist/auth/serverFunctions/login.js.map +1 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli/commands/data/utilities.d.ts +1 -1
- package/dist/cli/commands/data/utilities.d.ts.map +1 -1
- package/dist/cli/commands/data/utilities.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/config/types.d.ts.map +1 -1
- package/dist/collections/config/types.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.map +1 -1
- package/dist/config/sanitize.js +2 -2
- package/dist/config/sanitize.js.map +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/database/types.d.ts +4 -0
- package/dist/database/types.d.ts.map +1 -1
- package/dist/database/types.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/fields/config/client.js.map +1 -1
- package/dist/fields/config/reservedFieldNames.d.ts.map +1 -1
- package/dist/fields/config/reservedFieldNames.js.map +1 -1
- package/dist/fields/config/types.d.ts.map +1 -1
- package/dist/fields/config/types.js.map +1 -1
- package/dist/fields/hooks/afterChange/promise.js.map +1 -1
- package/dist/fields/hooks/afterRead/promise.js.map +1 -1
- package/dist/fields/hooks/beforeChange/flattenValidationData.d.ts +14 -0
- package/dist/fields/hooks/beforeChange/flattenValidationData.d.ts.map +1 -0
- package/dist/fields/hooks/beforeChange/flattenValidationData.js +36 -0
- package/dist/fields/hooks/beforeChange/flattenValidationData.js.map +1 -0
- package/dist/fields/hooks/beforeChange/promise.d.ts +2 -1
- package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.js +96 -22
- package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
- package/dist/fields/hooks/beforeChange/traverseFields.d.ts +2 -1
- package/dist/fields/hooks/beforeChange/traverseFields.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/traverseFields.js +2 -1
- package/dist/fields/hooks/beforeChange/traverseFields.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/config/types.d.ts.map +1 -1
- package/dist/globals/config/types.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 +18 -4
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js +1 -1
- package/dist/queues/operations/runJobs/runJob/getRunTaskFunction.js.map +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/uploads/fileVersioning/archive.js.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.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/getFileContentRequirement.js.map +1 -1
- 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/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/entityInputSchema/validateEntityData.d.ts.map +1 -1
- package/dist/utilities/entityInputSchema/validateEntityData.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/getVersionsConfig.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/conf/index.d.ts +4 -1
- package/dist/utilities/telemetry/conf/index.d.ts.map +1 -1
- package/dist/utilities/telemetry/conf/index.js.map +1 -1
- package/dist/utilities/telemetry/featureInfo/getFeatureInfo.js.map +1 -1
- package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
- package/dist/versions/isInheritedReadVersionsAccess.js.map +1 -1
- package/package.json +29 -27
- package/skills/payload/reference/ENDPOINTS.md +3 -9
- package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/config/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { GraphQLInputObjectType, GraphQLNonNull, GraphQLObjectType } from 'graphql'\nimport type { IsAny, MarkOptional } from 'ts-essentials'\n\nimport type { CustomUpload, ViewTypes } from '../../admin/types.js'\nimport type { Arguments as MeArguments } from '../../auth/operations/me.js'\nimport type {\n Arguments as RefreshArguments,\n Result as RefreshResult,\n} from '../../auth/operations/refresh.js'\nimport type { Auth, IncomingAuthType } from '../../auth/types.js'\nimport type {\n Access,\n AfterErrorHookArgs,\n AfterErrorResult,\n CustomComponent,\n Endpoint,\n EntityDescription,\n GeneratePreviewURL,\n LabelFunction,\n LivePreviewConfig,\n MetaConfig,\n PayloadComponent,\n SharedAdminComponents,\n SharedEditViewComponents,\n SharedEntityViews,\n StaticLabel,\n} from '../../config/types.js'\nimport type { DBIdentifierName } from '../../database/types.js'\nimport type { Authorship, SanitizedAuthorship } from '../../fields/baseFields/authorship/types.js'\nimport type {\n Field,\n FlattenedField,\n JoinField,\n RelationshipField,\n UploadField,\n} from '../../fields/config/types.js'\nimport type {\n HierarchyConfig,\n HierarchyJoinFieldConfig,\n SanitizedHierarchyConfig,\n} from '../../hierarchy/types.js'\nimport type {\n CollectionAdminCustom,\n CollectionCustom,\n CollectionSlug,\n GeneratedTypes,\n JsonObject,\n RequestContext,\n TypedAuthOperations,\n TypedCollection,\n TypedCollectionSelect,\n TypedLocale,\n} from '../../index.js'\nimport type {\n PayloadRequest,\n SelectIncludeType,\n SelectType,\n Sort,\n TransformCollectionWithSelect,\n Where,\n WithSelectFn,\n} from '../../types/index.js'\nimport type { SanitizedUploadConfig, UploadConfig } from '../../uploads/types.js'\nimport type {\n IncomingCollectionVersions,\n SanitizedCollectionVersions,\n} from '../../versions/types.js'\nimport type {\n AfterOperationArg,\n BeforeOperationArg,\n OperationMap,\n} from '../operations/utilities/types.js'\n\nexport type DataFromCollectionSlug<TSlug extends CollectionSlug> =\n TypedCollection[string extends CollectionSlug ? CollectionSlug : TSlug]\n\n/**\n * The ID type of a given collection (e.g. `string` or `number`), taken from its generated type.\n * Use this instead of the project-wide {@link DefaultDocumentIDType} when the collection slug is\n * known, since each collection can have its own ID type.\n */\nexport type IDTypeForCollectionSlug<TSlug extends CollectionSlug> =\n DataFromCollectionSlug<TSlug>['id']\n\nexport type SelectFromCollectionSlug<TSlug extends CollectionSlug> = TypedCollectionSelect[TSlug]\n\n/**\n * Collection slugs that do not have drafts enabled.\n * Detects collections without drafts by checking for the absence of the `_status` field.\n */\nexport type CollectionsWithoutDrafts = {\n [TSlug in CollectionSlug]: DataFromCollectionSlug<TSlug> extends { _status?: any } ? never : TSlug\n}[CollectionSlug]\n\n/**\n * Conditionally allows or forbids the `draft` property based on collection configuration.\n * When `strictDraftTypes` is enabled, the `draft` property is forbidden on collections without drafts.\n */\nexport type DraftFlagFromCollectionSlug<TSlug extends CollectionSlug> = GeneratedTypes extends {\n strictDraftTypes: true\n}\n ? TSlug extends CollectionsWithoutDrafts\n ? {\n /**\n * The `draft` property is not allowed because this collection does not have `versions.drafts` enabled.\n */\n draft?: never\n }\n : {\n /**\n * Whether the document(s) should be queried from the versions table/collection or not. [More](https://payloadcms.com/docs/versions/drafts#draft-api)\n */\n draft?: boolean\n }\n : {\n /**\n * Whether the document(s) should be queried from the versions table/collection or not. [More](https://payloadcms.com/docs/versions/drafts#draft-api)\n */\n draft?: boolean\n }\n\nexport type AuthOperationsFromCollectionSlug<TSlug extends CollectionSlug> =\n TypedAuthOperations[TSlug]\n\nexport type RequiredDataFromCollection<TData extends JsonObject> = MarkOptional<\n TData,\n 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt'\n>\n\nexport type RequiredDataFromCollectionSlug<TSlug extends CollectionSlug> =\n RequiredDataFromCollection<DataFromCollectionSlug<TSlug>>\n\n/**\n * Helper type for draft data INPUT (e.g., create operations) - makes all fields optional except system fields\n * When creating a draft, required fields don't need to be provided as validation is skipped\n * The id field is optional since it's auto-generated\n */\nexport type DraftDataFromCollection<TData extends JsonObject> = Partial<\n Omit<TData, 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>\n> &\n Partial<Pick<TData, 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>>\n\nexport type DraftDataFromCollectionSlug<TSlug extends CollectionSlug> = DraftDataFromCollection<\n DataFromCollectionSlug<TSlug>\n>\n\n/**\n * Helper type for draft data OUTPUT (e.g., query results) - makes user fields optional but keeps id required\n * When querying drafts, required fields may be null/undefined as validation is skipped, but system fields like id are always present\n */\nexport type QueryDraftDataFromCollection<TData extends JsonObject> = Partial<\n Omit<TData, 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>\n> &\n Partial<Pick<TData, 'createdAt' | 'deletedAt' | 'updatedAt' | 'variants'>> &\n Pick<TData, 'id'>\n\nexport type QueryDraftDataFromCollectionSlug<TSlug extends CollectionSlug> =\n QueryDraftDataFromCollection<DataFromCollectionSlug<TSlug>>\n\nexport type HookOperationType =\n | 'autosave'\n | 'count'\n | 'countVersions'\n | 'create'\n | 'delete'\n | 'forgotPassword'\n | 'login'\n | 'read'\n | 'readDistinct'\n | 'refresh'\n | 'resetPassword'\n | 'restoreVersion'\n | 'update'\n | 'validate'\n\ntype CreateOrUpdateOperation = Extract<HookOperationType, 'create' | 'update'>\ntype CreateUpdateOrValidateOperation = Extract<HookOperationType, 'create' | 'update' | 'validate'>\n\nexport type BeforeOperationHook<TOperationGeneric extends CollectionSlug = string> = (\n arg: BeforeOperationArg<TOperationGeneric>,\n) =>\n | Parameters<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>[0]\n | Promise<Parameters<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>[0]>\n | Promise<void>\n | void\n\nexport type BeforeValidateHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data?: Partial<T>\n /**\n * Hook operation being performed\n */\n operation: CreateUpdateOrValidateOperation\n /**\n * Original document before change\n *\n * `undefined` on 'create' operation\n */\n originalDoc?: T\n req: PayloadRequest\n}) => any\n\nexport type BeforeChangeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data: Partial<T>\n /**\n * Hook operation being performed\n */\n operation: CreateUpdateOrValidateOperation\n /**\n * Original document before change\n *\n * `undefined` on 'create' operation\n */\n originalDoc?: T\n req: PayloadRequest\n}) => any\n\nexport type AfterChangeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data: Partial<T>\n doc: T\n /**\n * Hook operation being performed\n */\n operation: CreateOrUpdateOperation\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n previousDoc: T\n req: PayloadRequest\n /** Resolved field selection for the operation's response. */\n select?: SelectType\n}) => any\n\nexport type BeforeReadHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n query: { [key: string]: any }\n req: PayloadRequest\n}) => any\n\nexport type AfterReadHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n findMany?: boolean\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n query?: { [key: string]: any }\n req: PayloadRequest\n}) => any\n\nexport type BeforeDeleteHook = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n id: number | string\n req: PayloadRequest\n}) => any\n\nexport type AfterDeleteHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n id: number | string\n req: PayloadRequest\n}) => any\n\nexport type AfterOperationHook<TOperationGeneric extends CollectionSlug = string> = (\n arg: AfterOperationArg<TOperationGeneric>,\n) =>\n | Awaited<ReturnType<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>>\n | Promise<\n Awaited<ReturnType<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>>\n >\n\nexport type BeforeLoginHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n user: T\n}) => any\n\nexport type AfterLoginHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n token: string\n user: T\n}) => any\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterLogoutHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n}) => any\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterMeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n response: unknown\n}) => any\n\nexport type RefreshHook<T extends TypeWithID = any> = (args: {\n args: RefreshArguments\n user: T\n}) => Promise<RefreshResult | void> | (RefreshResult | void)\n\nexport type MeHook<T extends TypeWithID = any> = (args: {\n args: MeArguments\n user: T\n}) => ({ exp: number; user: T } | void) | Promise<{ exp: number; user: T } | void>\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterRefreshHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n exp: number\n req: PayloadRequest\n token: string\n}) => any\n\nexport type AfterErrorHook = (\n args: { collection: SanitizedCollectionConfig } & AfterErrorHookArgs,\n) => AfterErrorResult | Promise<AfterErrorResult>\n\nexport type AfterForgotPasswordHook = (args: {\n args?: any\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n}) => any\n\nexport type EnableFoldersOptions = {\n // Displays the folder collection and parentFolder field in the document view\n debug?: boolean\n}\n\n/**\n * Configuration options for folder hierarchy preset.\n * Subset of HierarchyConfig with folder-appropriate defaults applied.\n */\nexport type FoldersConfig = {\n admin?: {\n components?: {\n Icon?: PayloadComponent\n }\n injectSidebarTab?: boolean\n treeLimit?: number\n useHeaderButton?: boolean\n }\n collectionSpecific?:\n | {\n fieldName?: string\n }\n | boolean\n joinField?: HierarchyJoinFieldConfig\n parentFieldName?: string\n slugField?: string\n slugify?: (text: string) => string\n slugPathFieldName?: string\n titlePathFieldName?: string\n}\n\n/**\n * Configuration options for tags hierarchy preset.\n * Same as FoldersConfig but allowHasMany can be overridden.\n */\nexport type TagsConfig = {\n allowHasMany?: boolean\n} & FoldersConfig\n\nexport type BaseFilter = (args: {\n limit: number\n locale?: TypedLocale\n page: number\n req: PayloadRequest\n sort: string\n}) => null | Promise<null | Where> | Where\n\n/**\n * @deprecated Use `BaseFilter` instead.\n */\nexport type BaseListFilter = BaseFilter\n\nexport type CollectionAdminOptions = {\n /**\n * Defines a default base filter which will be applied in the following parts of the admin panel:\n * - List View\n * - Relationship fields for internal links within the Lexical editor\n *\n * This is especially useful for plugins like multi-tenant. For example,\n * a user may have access to multiple tenants, but should only see content\n * related to the currently active or selected tenant in those places.\n */\n baseFilter?: BaseFilter\n /**\n * @deprecated Use `baseFilter` instead. If both are defined,\n * `baseFilter` will take precedence. This property remains only\n * for backward compatibility and may be removed in a future version.\n *\n * Originally, `baseListFilter` was intended to filter only the List View\n * in the admin panel. However, base filtering is often required in other areas\n * such as internal link relationships in the Lexical editor.\n */\n baseListFilter?: BaseListFilter\n /**\n * Custom admin components\n */\n components?: {\n afterList?: CustomComponent[]\n afterListTable?: CustomComponent[]\n beforeList?: CustomComponent[]\n beforeListTable?: CustomComponent[]\n /**\n * Components within the edit view\n */\n edit?: {\n /**\n * Replaces the \"Upload\" section\n * + upload must be enabled\n */\n Upload?: CustomUpload\n } & SharedEditViewComponents\n listMenuItems?: CustomComponent[]\n views?: {\n /**\n * Replace or modify the \"list\" view.\n * @link https://payloadcms.com/docs/custom-components/list-view\n */\n list?: {\n actions?: CustomComponent[]\n Component?: PayloadComponent\n NoResults?: CustomComponent\n }\n } & SharedEntityViews\n } & Omit<SharedAdminComponents, 'edit' | 'views'>\n /** Extension point to add your custom data. Available in server and client. */\n custom?: CollectionAdminCustom\n /**\n * Default columns to show in list view\n */\n defaultColumns?: string[]\n /**\n * Custom description for collection. This will also be used as JSDoc for the generated types\n */\n description?: EntityDescription\n /**\n * Disable the Copy To Locale button in the edit document view\n * @default false\n */\n disableCopyToLocale?: boolean\n enableRichTextLink?: boolean\n enableRichTextRelationship?: boolean\n /**\n * Function to format the URL for document links in the list view.\n * Return null to disable linking for that document.\n * Return a string to customize the link destination.\n * If not provided, uses the default admin edit URL.\n */\n formatDocURL?: (args: {\n collectionSlug: string\n /**\n * The default URL that would normally be used for this document link.\n * You can return this as-is, modify it, or completely replace it.\n */\n defaultURL: string\n doc: Record<string, unknown>\n req: PayloadRequest\n /**\n * The current view context where the link is being generated.\n * Most relevant values for document linking are 'list' and 'trash'.\n */\n viewType?: ViewTypes\n }) => null | string\n /**\n * Specify a navigational group for collections in the admin sidebar.\n * - Provide a string to place the entity in a custom group.\n * - Provide a record to define localized group names.\n * - Set to `false` to exclude the collection from the sidebar, command palette, dashboard collection cards,\n * and pin picker, and its documents from both the Pinned and Recently viewed dashboard tabs, including existing pins.\n * This does not disable routes or change access control or rich text link and relationship eligibility.\n * Use `enableRichTextLink` and `enableRichTextRelationship` to configure rich text eligibility separately.\n */\n group?: false | Record<string, string> | string\n /**\n * Exclude the collection from the admin nav and routes\n */\n hidden?: ((args: { user: PayloadRequest['user'] }) => boolean) | boolean\n /**\n * Additional fields to be searched via the full text search\n */\n listSearchableFields?: string[]\n /**\n * Live Preview options.\n *\n * @see https://payloadcms.com/docs/live-preview/overview\n */\n livePreview?: LivePreviewConfig\n meta?: MetaConfig\n pagination?: {\n defaultLimit?: number\n limits?: number[]\n }\n /**\n * Function to generate custom preview URL\n */\n preview?: GeneratePreviewURL\n /**\n * Field to use as the thumbnail image in grid/card views. Defaults to the first field of type `upload`.\n */\n useAsThumbnail?: string\n /**\n * Field to use as title in Edit View and first column in List view\n */\n useAsTitle?: string\n}\n\nexport type CollectionAccess<TData = any> = {\n admin?: ({ slug, req }: { req: PayloadRequest; slug: string }) => boolean | Promise<boolean>\n create?: Access<TData>\n delete?: Access<TData>\n read?: Access<TData>\n readVersions?: Access<TData>\n unlock?: Access<TData>\n update?: Access<TData>\n /**\n * Controls on-demand validation for this collection.\n * Falls back to `update` access when omitted.\n * The access function receives `req.operation === 'validate'`.\n * @see https://payloadcms.com/docs/validation/overview#access-control-and-hooks\n */\n validate?: Access<TData>\n}\n\ntype CollectionHooks<TSlug extends CollectionSlug = any> = {\n afterChange?: AfterChangeHook[]\n afterDelete?: AfterDeleteHook[]\n afterError?: AfterErrorHook[]\n afterForgotPassword?: AfterForgotPasswordHook[]\n afterLogin?: AfterLoginHook[]\n afterLogout?: AfterLogoutHook[]\n afterMe?: AfterMeHook[]\n afterOperation?: AfterOperationHook<TSlug>[]\n afterRead?: AfterReadHook[]\n afterRefresh?: AfterRefreshHook[]\n beforeChange?: BeforeChangeHook[]\n beforeDelete?: BeforeDeleteHook[]\n beforeLogin?: BeforeLoginHook[]\n beforeOperation?: BeforeOperationHook<TSlug>[]\n beforeRead?: BeforeReadHook[]\n beforeValidate?: BeforeValidateHook[]\n /**\n /**\n * Use the `me` hook to control the `me` operation.\n * Here, you can optionally instruct the me operation to return early,\n * and skip its default logic.\n */\n me?: MeHook[]\n /**\n * Use the `refresh` hook to control the refresh operation.\n * Here, you can optionally instruct the refresh operation to return early,\n * and skip its default logic.\n */\n refresh?: RefreshHook[]\n}\n\n/** Manage all aspects of a data collection */\nexport type CollectionConfig<TSlug extends CollectionSlug = any> = {\n /**\n * Do not set this property manually. This is set to true during sanitization, to avoid\n * sanitizing the same collection multiple times.\n */\n _sanitized?: boolean\n /**\n * Access control\n */\n access?: CollectionAccess\n /**\n * Collection admin options\n */\n admin?: CollectionAdminOptions\n /**\n * Collection login options\n *\n * Use `true` to enable with default options\n */\n auth?: boolean | IncomingAuthType\n /**\n * Automatically track the user that created and last updated each document via\n * polymorphic `createdBy` / `updatedBy` relationship fields to your auth collections.\n *\n * Use `true` (default) to enable both, `false` to disable both, or an object to\n * toggle each field independently, e.g. `{ updatedBy: false }`.\n *\n * @default true\n */\n authorship?: Authorship | boolean\n /**\n * Configuration for bulk operations\n */\n /** Extension point to add your custom data. Server only. */\n custom?: CollectionCustom\n /**\n * Used to override the default naming of the database table or collection with your using a function or string\n * @WARNING: If you change this property with existing data, you will need to handle the renaming of the table in your database or by using migrations\n */\n dbName?: DBIdentifierName\n defaultPopulate?: IsAny<SelectFromCollectionSlug<TSlug>> extends true\n ? SelectType\n : SelectFromCollectionSlug<TSlug>\n /**\n * Default field to sort by in collection list view\n */\n defaultSort?: Sort\n /**\n * Disable the bulk delete operation for the collection in the admin panel and the API\n */\n disableBulkDelete?: boolean\n /**\n * Disable the bulk edit operation for the collection in the admin panel and the API\n */\n disableBulkEdit?: boolean\n /**\n * When true, do not show the \"Duplicate\" button while editing documents within this collection and prevent `duplicate` from all APIs\n */\n disableDuplicate?: boolean\n /**\n * Opt-in to enable query presets for this collection.\n * @see https://payloadcms.com/docs/query-presets/overview\n */\n enableQueryPresets?: boolean\n /**\n * Custom rest api endpoints, set false to disable all rest endpoints for this collection.\n */\n endpoints?: false | Omit<Endpoint, 'root'>[]\n fields: Field[]\n /**\n * Enable folder hierarchy preset for this collection.\n * Sets hierarchy with folder defaults: allowHasMany: false, FolderIcon, useHeaderButton: true\n *\n * Use `true` for defaults, or object for customization.\n * Cannot be used together with `tags` or `hierarchy`.\n */\n folders?: boolean | FoldersConfig\n /**\n * GraphQL configuration\n */\n graphQL?:\n | {\n disableMutations?: true\n disableQueries?: true\n pluralName?: string\n singularName?: string\n }\n | false\n /**\n * Enable hierarchical tree structure for this collection\n *\n * Use `true` to enable with defaults (auto-detects parent field)\n * or provide configuration object\n *\n * @example\n * // Enable with defaults\n * hierarchy: true\n *\n * @example\n * // Customize field names and slugify function\n * hierarchy: {\n * parentFieldName: 'parent',\n * slugify: (text) => customSlugify(text),\n * slugPathFieldName: '_breadcrumbPath'\n * }\n */\n hierarchy?: boolean | HierarchyConfig\n /**\n * Hooks to modify Payload functionality\n */\n hooks?: CollectionHooks<TSlug>\n /**\n * Define compound indexes for this collection.\n * This can be used to either speed up querying/sorting by 2 or more fields at the same time or\n * to ensure uniqueness between several fields.\n * Specify field paths\n * @example\n * [{ unique: true, fields: ['title', 'group.name'] }]\n * @default []\n */\n indexes?: CompoundIndex[]\n /**\n * Label configuration\n */\n labels?: {\n plural?: LabelFunction | StaticLabel\n singular?: LabelFunction | StaticLabel\n }\n /** Read-only Markdown instructions included in this collection's MCP and CLI schema responses. */\n llmInstructions?: string\n /**\n * Enables / Disables the ability to lock documents while editing\n * @default true\n */\n lockDocuments?:\n | {\n duration: number\n }\n | false\n /**\n * If true, enables custom ordering for the collection, and documents in the listView can be reordered via drag and drop.\n * New documents are inserted at the end of the list according to this parameter.\n *\n * Under the hood, a field with {@link https://payloadcms.com/docs/configuration/collections#fractional-indexing|fractional indexing} is used to optimize inserts and reorderings.\n *\n * @default false\n *\n * @experimental There may be frequent breaking changes to this API\n */\n orderable?: boolean\n slug: string\n /**\n * Enable tags hierarchy preset for this collection.\n * Sets hierarchy with tag defaults: allowHasMany: true, TagIcon\n *\n * Use `true` for defaults, or object for customization.\n * Cannot be used together with `folders` or `hierarchy`.\n */\n tags?: boolean | TagsConfig\n /**\n * Add `createdAt`, `deletedAt` and `updatedAt` fields\n *\n * @default true\n */\n timestamps?: boolean\n /**\n * Enables trash support for this collection.\n *\n * When enabled, documents will include a `deletedAt` timestamp field.\n * This allows documents to be marked as deleted without being permanently removed.\n * The `deletedAt` field will be set to the current date and time when a document is trashed.\n *\n * @default false\n */\n trash?: boolean\n /**\n * Options used in typescript generation\n */\n typescript?: {\n /**\n * Typescript generation name given to the interface type\n */\n interface?: string\n }\n /**\n * Customize the handling of incoming file uploads\n *\n * @default false // disable uploads\n */\n upload?: boolean | UploadConfig\n /**\n * Enable versioning. Set it to true to enable default versions settings,\n * or customize versions options by setting the property equal to an object\n * containing the version options.\n *\n * @default false // disable versioning\n */\n versions?: boolean | IncomingCollectionVersions\n} & Pick<\n WithSelectFn<\n IsAny<SelectFromCollectionSlug<TSlug>> extends true\n ? SelectIncludeType\n : SelectFromCollectionSlug<TSlug>\n >,\n 'select'\n>\n\nexport type SanitizedJoin = {\n /**\n * The field configuration defining the join\n */\n field: JoinField\n getForeignPath?(args: { locale?: TypedLocale }): string\n /**\n * The path of the join field in dot notation\n */\n joinPath: string\n /**\n * `parentIsLocalized` is true if any parent field of the\n * field configuration defining the join is localized\n */\n parentIsLocalized: boolean\n targetField: RelationshipField | UploadField\n}\n\nexport type SanitizedJoins = {\n [collectionSlug: string]: SanitizedJoin[]\n}\n\n/**\n * Properties populated during sanitization are redefined below. All other collection properties\n * preserve their incoming optionality.\n */\nexport interface SanitizedCollectionConfig\n extends Omit<\n CollectionConfig,\n | '_sanitized'\n | 'access'\n | 'admin'\n | 'auth'\n | 'authorship'\n | 'custom'\n | 'endpoints'\n | 'folder'\n | 'folders'\n | 'hierarchy'\n | 'hooks'\n | 'indexes'\n | 'labels'\n | 'slug'\n | 'tags'\n | 'timestamps'\n | 'upload'\n | 'versions'\n >,\n Required<Pick<CollectionConfig, 'admin' | 'custom' | 'indexes' | 'timestamps'>> {\n _sanitized: true\n access: Pick<CollectionAccess, 'admin'> &\n Required<\n Pick<\n CollectionAccess,\n 'create' | 'delete' | 'read' | 'readVersions' | 'unlock' | 'update' | 'validate'\n >\n >\n auth: Auth\n authorship: SanitizedAuthorship\n endpoints: Endpoint[] | false\n /**\n * Fields in the database schema structure\n * Rows / collapsible / tabs w/o name `fields` merged to top, UIs are excluded\n */\n flattenedFields: FlattenedField[]\n /**\n * Hierarchy configuration (when collection is a hierarchy type like folders or tags)\n */\n hierarchy: false | SanitizedHierarchyConfig\n hooks: Required<CollectionHooks>\n /**\n * Object of collections to join 'Join Fields object keyed by collection\n */\n joins: SanitizedJoins\n labels: Required<NonNullable<CollectionConfig['labels']>>\n /**\n * List of all polymorphic join fields\n */\n polymorphicJoins: SanitizedJoin[]\n\n sanitizedIndexes: SanitizedCompoundIndex[]\n\n slug: CollectionSlug\n\n upload: SanitizedUploadConfig\n versions?: SanitizedCollectionVersions\n}\n\nexport type Collection = {\n config: SanitizedCollectionConfig\n customIDType?: 'number' | 'text'\n graphQL?: {\n countType: GraphQLObjectType\n JWT: GraphQLObjectType\n mutationInputType: GraphQLNonNull<any>\n paginatedType: GraphQLObjectType\n type: GraphQLObjectType\n updateMutationInputType: GraphQLNonNull<any>\n versionType: GraphQLObjectType\n whereInputType: GraphQLInputObjectType\n }\n}\n\nexport type BulkOperationResult<TSlug extends CollectionSlug, TSelect extends SelectType> = {\n docs: TransformCollectionWithSelect<TSlug, TSelect>[]\n errors: {\n id: DataFromCollectionSlug<TSlug>['id']\n isPublic: boolean\n message: string\n }[]\n}\n\nexport type AuthCollection = {\n config: SanitizedCollectionConfig\n}\n\nexport type LocalizedMeta = {\n [locale: string]: {\n status: 'draft' | 'published'\n updatedAt: string\n }\n}\n\nexport type TypeWithID = {\n id: number | string\n}\n\nexport type TypeWithTimestamps = {\n [key: string]: unknown\n createdAt: string\n deletedAt?: null | string\n id: number | string\n updatedAt: string\n}\n\nexport type CompoundIndex = {\n fields: string[]\n unique?: boolean\n}\n\nexport type SanitizedCompoundIndex = {\n fields: {\n field: FlattenedField\n localizedPath: string\n path: string\n pathHasLocalized: boolean\n }[]\n unique: boolean\n}\n"],"names":[],"mappings":"AAAA,qDAAqD,GA86BrD,WAQC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/config/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { GraphQLInputObjectType, GraphQLNonNull, GraphQLObjectType } from 'graphql'\nimport type { IsAny, MarkOptional } from 'ts-essentials'\n\nimport type { CustomUpload, ViewTypes } from '../../admin/types.js'\nimport type { Arguments as MeArguments } from '../../auth/operations/me.js'\nimport type {\n Arguments as RefreshArguments,\n Result as RefreshResult,\n} from '../../auth/operations/refresh.js'\nimport type { Auth, IncomingAuthType } from '../../auth/types.js'\nimport type {\n Access,\n AfterErrorHookArgs,\n AfterErrorResult,\n CustomComponent,\n Endpoint,\n EntityDescription,\n GeneratePreviewURL,\n LabelFunction,\n LivePreviewConfig,\n MetaConfig,\n PayloadComponent,\n SharedAdminComponents,\n SharedEditViewComponents,\n SharedEntityViews,\n StaticLabel,\n} from '../../config/types.js'\nimport type { DBIdentifierName } from '../../database/types.js'\nimport type { Authorship, SanitizedAuthorship } from '../../fields/baseFields/authorship/types.js'\nimport type {\n Field,\n FlattenedField,\n JoinField,\n RelationshipField,\n UploadField,\n} from '../../fields/config/types.js'\nimport type {\n HierarchyConfig,\n HierarchyJoinFieldConfig,\n SanitizedHierarchyConfig,\n} from '../../hierarchy/types.js'\nimport type {\n CollectionAdminCustom,\n CollectionCustom,\n CollectionSlug,\n GeneratedTypes,\n JsonObject,\n RequestContext,\n TypedAuthOperations,\n TypedCollection,\n TypedCollectionSelect,\n TypedLocale,\n} from '../../index.js'\nimport type {\n PayloadRequest,\n SelectIncludeType,\n SelectType,\n Sort,\n TransformCollectionWithSelect,\n Where,\n WithSelectFn,\n} from '../../types/index.js'\nimport type { SanitizedUploadConfig, UploadConfig } from '../../uploads/types.js'\nimport type {\n IncomingCollectionVersions,\n SanitizedCollectionVersions,\n} from '../../versions/types.js'\nimport type {\n AfterOperationArg,\n BeforeOperationArg,\n OperationMap,\n} from '../operations/utilities/types.js'\n\nexport type DataFromCollectionSlug<TSlug extends CollectionSlug> =\n TypedCollection[string extends CollectionSlug ? CollectionSlug : TSlug]\n\n/**\n * The ID type of a given collection (e.g. `string` or `number`), taken from its generated type.\n * Use this instead of the project-wide {@link DefaultDocumentIDType} when the collection slug is\n * known, since each collection can have its own ID type.\n */\nexport type IDTypeForCollectionSlug<TSlug extends CollectionSlug> =\n DataFromCollectionSlug<TSlug>['id']\n\nexport type SelectFromCollectionSlug<TSlug extends CollectionSlug> = TypedCollectionSelect[TSlug]\n\n/**\n * Collection slugs that do not have drafts enabled.\n * Detects collections without drafts by checking for the absence of the `_status` field.\n */\nexport type CollectionsWithoutDrafts = {\n [TSlug in CollectionSlug]: DataFromCollectionSlug<TSlug> extends { _status?: any } ? never : TSlug\n}[CollectionSlug]\n\n/**\n * Conditionally allows or forbids the `draft` property based on collection configuration.\n * When `strictDraftTypes` is enabled, the `draft` property is forbidden on collections without drafts.\n */\nexport type DraftFlagFromCollectionSlug<TSlug extends CollectionSlug> = GeneratedTypes extends {\n strictDraftTypes: true\n}\n ? TSlug extends CollectionsWithoutDrafts\n ? {\n /**\n * The `draft` property is not allowed because this collection does not have `versions.drafts` enabled.\n */\n draft?: never\n }\n : {\n /**\n * Whether the document(s) should be queried from the versions table/collection or not. [More](https://payloadcms.com/docs/versions/drafts#draft-api)\n */\n draft?: boolean\n }\n : {\n /**\n * Whether the document(s) should be queried from the versions table/collection or not. [More](https://payloadcms.com/docs/versions/drafts#draft-api)\n */\n draft?: boolean\n }\n\nexport type AuthOperationsFromCollectionSlug<TSlug extends CollectionSlug> =\n TypedAuthOperations[TSlug]\n\nexport type RequiredDataFromCollection<TData extends JsonObject> = MarkOptional<\n TData,\n 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt'\n>\n\nexport type RequiredDataFromCollectionSlug<TSlug extends CollectionSlug> =\n RequiredDataFromCollection<DataFromCollectionSlug<TSlug>>\n\n/**\n * Helper type for draft data INPUT (e.g., create operations) - makes all fields optional except system fields\n * When creating a draft, required fields don't need to be provided as validation is skipped\n * The id field is optional since it's auto-generated\n */\nexport type DraftDataFromCollection<TData extends JsonObject> = Partial<\n Omit<TData, 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>\n> &\n Partial<Pick<TData, 'collection' | 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>>\n\nexport type DraftDataFromCollectionSlug<TSlug extends CollectionSlug> = DraftDataFromCollection<\n DataFromCollectionSlug<TSlug>\n>\n\n/**\n * Helper type for draft data OUTPUT (e.g., query results) - makes user fields optional but keeps id required\n * When querying drafts, required fields may be null/undefined as validation is skipped, but system fields like id are always present\n */\nexport type QueryDraftDataFromCollection<TData extends JsonObject> = Partial<\n Omit<TData, 'createdAt' | 'deletedAt' | 'id' | 'updatedAt' | 'variants'>\n> &\n Partial<Pick<TData, 'createdAt' | 'deletedAt' | 'updatedAt' | 'variants'>> &\n Pick<TData, 'id'>\n\nexport type QueryDraftDataFromCollectionSlug<TSlug extends CollectionSlug> =\n QueryDraftDataFromCollection<DataFromCollectionSlug<TSlug>>\n\nexport type HookOperationType =\n | 'autosave'\n | 'count'\n | 'countVersions'\n | 'create'\n | 'delete'\n | 'forgotPassword'\n | 'login'\n | 'read'\n | 'readDistinct'\n | 'refresh'\n | 'resetPassword'\n | 'restoreVersion'\n | 'update'\n | 'validate'\n\ntype CreateOrUpdateOperation = Extract<HookOperationType, 'create' | 'update'>\ntype CreateUpdateOrValidateOperation = Extract<HookOperationType, 'create' | 'update' | 'validate'>\n\nexport type BeforeOperationHook<TOperationGeneric extends CollectionSlug = string> = (\n arg: BeforeOperationArg<TOperationGeneric>,\n) =>\n | Parameters<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>[0]\n | Promise<Parameters<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>[0]>\n | Promise<void>\n | void\n\nexport type BeforeValidateHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data?: Partial<T>\n /**\n * Hook operation being performed\n */\n operation: CreateUpdateOrValidateOperation\n /**\n * Original document before change\n *\n * `undefined` on 'create' operation\n */\n originalDoc?: T\n req: PayloadRequest\n}) => any\n\nexport type BeforeChangeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data: Partial<T>\n /**\n * Hook operation being performed\n */\n operation: CreateUpdateOrValidateOperation\n /**\n * Original document before change\n *\n * `undefined` on 'create' operation\n */\n originalDoc?: T\n req: PayloadRequest\n}) => any\n\nexport type AfterChangeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n data: Partial<T>\n doc: T\n /**\n * Hook operation being performed\n */\n operation: CreateOrUpdateOperation\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n previousDoc: T\n req: PayloadRequest\n /** Resolved field selection for the operation's response. */\n select?: SelectType\n}) => any\n\nexport type BeforeReadHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n query: { [key: string]: any }\n req: PayloadRequest\n}) => any\n\nexport type AfterReadHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n findMany?: boolean\n /**\n * Whether access control is being overridden for this operation\n */\n overrideAccess?: boolean\n query?: { [key: string]: any }\n req: PayloadRequest\n}) => any\n\nexport type BeforeDeleteHook = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n id: number | string\n req: PayloadRequest\n}) => any\n\nexport type AfterDeleteHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n doc: T\n id: number | string\n req: PayloadRequest\n}) => any\n\nexport type AfterOperationHook<TOperationGeneric extends CollectionSlug = string> = (\n arg: AfterOperationArg<TOperationGeneric>,\n) =>\n | Awaited<ReturnType<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>>\n | Promise<\n Awaited<ReturnType<OperationMap<TOperationGeneric>[keyof OperationMap<TOperationGeneric>]>>\n >\n\nexport type BeforeLoginHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n user: T\n}) => any\n\nexport type AfterLoginHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n token: string\n user: T\n}) => any\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterLogoutHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n}) => any\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterMeHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n req: PayloadRequest\n response: unknown\n}) => any\n\nexport type RefreshHook<T extends TypeWithID = any> = (args: {\n args: RefreshArguments\n user: T\n}) => Promise<RefreshResult | void> | (RefreshResult | void)\n\nexport type MeHook<T extends TypeWithID = any> = (args: {\n args: MeArguments\n user: T\n}) => ({ exp: number; user: T } | void) | Promise<{ exp: number; user: T } | void>\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type AfterRefreshHook<T extends TypeWithID = any> = (args: {\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n exp: number\n req: PayloadRequest\n token: string\n}) => any\n\nexport type AfterErrorHook = (\n args: { collection: SanitizedCollectionConfig } & AfterErrorHookArgs,\n) => AfterErrorResult | Promise<AfterErrorResult>\n\nexport type AfterForgotPasswordHook = (args: {\n args?: any\n /** The collection which this hook is being run on */\n collection: SanitizedCollectionConfig\n context: RequestContext\n}) => any\n\nexport type EnableFoldersOptions = {\n // Displays the folder collection and parentFolder field in the document view\n debug?: boolean\n}\n\n/**\n * Configuration options for folder hierarchy preset.\n * Subset of HierarchyConfig with folder-appropriate defaults applied.\n */\nexport type FoldersConfig = {\n admin?: {\n components?: {\n Icon?: PayloadComponent\n }\n injectSidebarTab?: boolean\n treeLimit?: number\n useHeaderButton?: boolean\n }\n collectionSpecific?:\n | {\n fieldName?: string\n }\n | boolean\n joinField?: HierarchyJoinFieldConfig\n parentFieldName?: string\n slugField?: string\n slugify?: (text: string) => string\n slugPathFieldName?: string\n titlePathFieldName?: string\n}\n\n/**\n * Configuration options for tags hierarchy preset.\n * Same as FoldersConfig but allowHasMany can be overridden.\n */\nexport type TagsConfig = {\n allowHasMany?: boolean\n} & FoldersConfig\n\nexport type BaseFilter = (args: {\n limit: number\n locale?: TypedLocale\n page: number\n req: PayloadRequest\n sort: string\n}) => null | Promise<null | Where> | Where\n\n/**\n * @deprecated Use `BaseFilter` instead.\n */\nexport type BaseListFilter = BaseFilter\n\nexport type CollectionAdminOptions = {\n /**\n * Defines a default base filter which will be applied in the following parts of the admin panel:\n * - List View\n * - Relationship fields for internal links within the Lexical editor\n *\n * This is especially useful for plugins like multi-tenant. For example,\n * a user may have access to multiple tenants, but should only see content\n * related to the currently active or selected tenant in those places.\n */\n baseFilter?: BaseFilter\n /**\n * @deprecated Use `baseFilter` instead. If both are defined,\n * `baseFilter` will take precedence. This property remains only\n * for backward compatibility and may be removed in a future version.\n *\n * Originally, `baseListFilter` was intended to filter only the List View\n * in the admin panel. However, base filtering is often required in other areas\n * such as internal link relationships in the Lexical editor.\n */\n baseListFilter?: BaseListFilter\n /**\n * Custom admin components\n */\n components?: {\n afterList?: CustomComponent[]\n afterListTable?: CustomComponent[]\n beforeList?: CustomComponent[]\n beforeListTable?: CustomComponent[]\n /**\n * Components within the edit view\n */\n edit?: {\n /**\n * Replaces the \"Upload\" section\n * + upload must be enabled\n */\n Upload?: CustomUpload\n } & SharedEditViewComponents\n listMenuItems?: CustomComponent[]\n views?: {\n /**\n * Replace or modify the \"list\" view.\n * @link https://payloadcms.com/docs/custom-components/list-view\n */\n list?: {\n actions?: CustomComponent[]\n Component?: PayloadComponent\n NoResults?: CustomComponent\n }\n } & SharedEntityViews\n } & Omit<SharedAdminComponents, 'edit' | 'views'>\n /** Extension point to add your custom data. Available in server and client. */\n custom?: CollectionAdminCustom\n /**\n * Default columns to show in list view\n */\n defaultColumns?: string[]\n /**\n * Custom description for collection. This will also be used as JSDoc for the generated types\n */\n description?: EntityDescription\n /**\n * Disable the Copy To Locale button in the edit document view\n * @default false\n */\n disableCopyToLocale?: boolean\n enableRichTextLink?: boolean\n enableRichTextRelationship?: boolean\n /**\n * Function to format the URL for document links in the list view.\n * Return null to disable linking for that document.\n * Return a string to customize the link destination.\n * If not provided, uses the default admin edit URL.\n */\n formatDocURL?: (args: {\n collectionSlug: string\n /**\n * The default URL that would normally be used for this document link.\n * You can return this as-is, modify it, or completely replace it.\n */\n defaultURL: string\n doc: Record<string, unknown>\n req: PayloadRequest\n /**\n * The current view context where the link is being generated.\n * Most relevant values for document linking are 'list' and 'trash'.\n */\n viewType?: ViewTypes\n }) => null | string\n /**\n * Specify a navigational group for collections in the admin sidebar.\n * - Provide a string to place the entity in a custom group.\n * - Provide a record to define localized group names.\n * - Set to `false` to exclude the collection from the sidebar, command palette, dashboard collection cards,\n * and pin picker, and its documents from both the Pinned and Recently viewed dashboard tabs, including existing pins.\n * This does not disable routes or change access control or rich text link and relationship eligibility.\n * Use `enableRichTextLink` and `enableRichTextRelationship` to configure rich text eligibility separately.\n */\n group?: false | Record<string, string> | string\n /**\n * Exclude the collection from the admin nav and routes\n */\n hidden?: ((args: { user: PayloadRequest['user'] }) => boolean) | boolean\n /**\n * Additional fields to be searched via the full text search\n */\n listSearchableFields?: string[]\n /**\n * Live Preview options.\n *\n * @see https://payloadcms.com/docs/live-preview/overview\n */\n livePreview?: LivePreviewConfig\n meta?: MetaConfig\n pagination?: {\n defaultLimit?: number\n limits?: number[]\n }\n /**\n * Function to generate custom preview URL\n */\n preview?: GeneratePreviewURL\n /**\n * Field to use as the thumbnail image in grid/card views. Defaults to the first field of type `upload`.\n */\n useAsThumbnail?: string\n /**\n * Field to use as title in Edit View and first column in List view\n */\n useAsTitle?: string\n}\n\nexport type CollectionAccess<TData = any> = {\n admin?: ({ slug, req }: { req: PayloadRequest; slug: string }) => boolean | Promise<boolean>\n create?: Access<TData>\n delete?: Access<TData>\n read?: Access<TData>\n readVersions?: Access<TData>\n unlock?: Access<TData>\n update?: Access<TData>\n /**\n * Controls on-demand validation for this collection.\n * Falls back to `update` access when omitted.\n * The access function receives `req.operation === 'validate'`.\n * @see https://payloadcms.com/docs/validation/overview#access-control-and-hooks\n */\n validate?: Access<TData>\n}\n\ntype CollectionHooks<TSlug extends CollectionSlug = any> = {\n afterChange?: AfterChangeHook[]\n afterDelete?: AfterDeleteHook[]\n afterError?: AfterErrorHook[]\n afterForgotPassword?: AfterForgotPasswordHook[]\n afterLogin?: AfterLoginHook[]\n afterLogout?: AfterLogoutHook[]\n afterMe?: AfterMeHook[]\n afterOperation?: AfterOperationHook<TSlug>[]\n afterRead?: AfterReadHook[]\n afterRefresh?: AfterRefreshHook[]\n beforeChange?: BeforeChangeHook[]\n beforeDelete?: BeforeDeleteHook[]\n beforeLogin?: BeforeLoginHook[]\n beforeOperation?: BeforeOperationHook<TSlug>[]\n beforeRead?: BeforeReadHook[]\n beforeValidate?: BeforeValidateHook[]\n /**\n /**\n * Use the `me` hook to control the `me` operation.\n * Here, you can optionally instruct the me operation to return early,\n * and skip its default logic.\n */\n me?: MeHook[]\n /**\n * Use the `refresh` hook to control the refresh operation.\n * Here, you can optionally instruct the refresh operation to return early,\n * and skip its default logic.\n */\n refresh?: RefreshHook[]\n}\n\n/** Manage all aspects of a data collection */\nexport type CollectionConfig<TSlug extends CollectionSlug = any> = {\n /**\n * Do not set this property manually. This is set to true during sanitization, to avoid\n * sanitizing the same collection multiple times.\n */\n _sanitized?: boolean\n /**\n * Access control\n */\n access?: CollectionAccess\n /**\n * Collection admin options\n */\n admin?: CollectionAdminOptions\n /**\n * Collection login options\n *\n * Use `true` to enable with default options\n */\n auth?: boolean | IncomingAuthType\n /**\n * Automatically track the user that created and last updated each document via\n * polymorphic `createdBy` / `updatedBy` relationship fields to your auth collections.\n *\n * Use `true` (default) to enable both, `false` to disable both, or an object to\n * toggle each field independently, e.g. `{ updatedBy: false }`.\n *\n * @default true\n */\n authorship?: Authorship | boolean\n /**\n * Configuration for bulk operations\n */\n /** Extension point to add your custom data. Server only. */\n custom?: CollectionCustom\n /**\n * Used to override the default naming of the database table or collection with your using a function or string\n * @WARNING: If you change this property with existing data, you will need to handle the renaming of the table in your database or by using migrations\n */\n dbName?: DBIdentifierName\n defaultPopulate?: IsAny<SelectFromCollectionSlug<TSlug>> extends true\n ? SelectType\n : SelectFromCollectionSlug<TSlug>\n /**\n * Default field to sort by in collection list view\n */\n defaultSort?: Sort\n /**\n * Disable the bulk delete operation for the collection in the admin panel and the API\n */\n disableBulkDelete?: boolean\n /**\n * Disable the bulk edit operation for the collection in the admin panel and the API\n */\n disableBulkEdit?: boolean\n /**\n * When true, do not show the \"Duplicate\" button while editing documents within this collection and prevent `duplicate` from all APIs\n */\n disableDuplicate?: boolean\n /**\n * Opt-in to enable query presets for this collection.\n * @see https://payloadcms.com/docs/query-presets/overview\n */\n enableQueryPresets?: boolean\n /**\n * Custom rest api endpoints, set false to disable all rest endpoints for this collection.\n */\n endpoints?: false | Omit<Endpoint, 'root'>[]\n fields: Field[]\n /**\n * Enable folder hierarchy preset for this collection.\n * Sets hierarchy with folder defaults: allowHasMany: false, FolderIcon, useHeaderButton: true\n *\n * Use `true` for defaults, or object for customization.\n * Cannot be used together with `tags` or `hierarchy`.\n */\n folders?: boolean | FoldersConfig\n /**\n * GraphQL configuration\n */\n graphQL?:\n | {\n disableMutations?: true\n disableQueries?: true\n pluralName?: string\n singularName?: string\n }\n | false\n /**\n * Enable hierarchical tree structure for this collection\n *\n * Use `true` to enable with defaults (auto-detects parent field)\n * or provide configuration object\n *\n * @example\n * // Enable with defaults\n * hierarchy: true\n *\n * @example\n * // Customize field names and slugify function\n * hierarchy: {\n * parentFieldName: 'parent',\n * slugify: (text) => customSlugify(text),\n * slugPathFieldName: '_breadcrumbPath'\n * }\n */\n hierarchy?: boolean | HierarchyConfig\n /**\n * Hooks to modify Payload functionality\n */\n hooks?: CollectionHooks<TSlug>\n /**\n * Define compound indexes for this collection.\n * This can be used to either speed up querying/sorting by 2 or more fields at the same time or\n * to ensure uniqueness between several fields.\n * Specify field paths\n * @example\n * [{ unique: true, fields: ['title', 'group.name'] }]\n * @default []\n */\n indexes?: CompoundIndex[]\n /**\n * Label configuration\n */\n labels?: {\n plural?: LabelFunction | StaticLabel\n singular?: LabelFunction | StaticLabel\n }\n /** Read-only Markdown instructions included in this collection's MCP and CLI schema responses. */\n llmInstructions?: string\n /**\n * Enables / Disables the ability to lock documents while editing\n * @default true\n */\n lockDocuments?:\n | {\n duration: number\n }\n | false\n /**\n * If true, enables custom ordering for the collection, and documents in the listView can be reordered via drag and drop.\n * New documents are inserted at the end of the list according to this parameter.\n *\n * Under the hood, a field with {@link https://payloadcms.com/docs/configuration/collections#fractional-indexing|fractional indexing} is used to optimize inserts and reorderings.\n *\n * @default false\n *\n * @experimental There may be frequent breaking changes to this API\n */\n orderable?: boolean\n slug: string\n /**\n * Enable tags hierarchy preset for this collection.\n * Sets hierarchy with tag defaults: allowHasMany: true, TagIcon\n *\n * Use `true` for defaults, or object for customization.\n * Cannot be used together with `folders` or `hierarchy`.\n */\n tags?: boolean | TagsConfig\n /**\n * Add `createdAt`, `deletedAt` and `updatedAt` fields\n *\n * @default true\n */\n timestamps?: boolean\n /**\n * Enables trash support for this collection.\n *\n * When enabled, documents will include a `deletedAt` timestamp field.\n * This allows documents to be marked as deleted without being permanently removed.\n * The `deletedAt` field will be set to the current date and time when a document is trashed.\n *\n * @default false\n */\n trash?: boolean\n /**\n * Options used in typescript generation\n */\n typescript?: {\n /**\n * Typescript generation name given to the interface type\n */\n interface?: string\n }\n /**\n * Customize the handling of incoming file uploads\n *\n * @default false // disable uploads\n */\n upload?: boolean | UploadConfig\n /**\n * Enable versioning. Set it to true to enable default versions settings,\n * or customize versions options by setting the property equal to an object\n * containing the version options.\n *\n * @default false // disable versioning\n */\n versions?: boolean | IncomingCollectionVersions\n} & Pick<\n WithSelectFn<\n IsAny<SelectFromCollectionSlug<TSlug>> extends true\n ? SelectIncludeType\n : SelectFromCollectionSlug<TSlug>\n >,\n 'select'\n>\n\nexport type SanitizedJoin = {\n /**\n * The field configuration defining the join\n */\n field: JoinField\n getForeignPath?(args: { locale?: TypedLocale }): string\n /**\n * The path of the join field in dot notation\n */\n joinPath: string\n /**\n * `parentIsLocalized` is true if any parent field of the\n * field configuration defining the join is localized\n */\n parentIsLocalized: boolean\n targetField: RelationshipField | UploadField\n}\n\nexport type SanitizedJoins = {\n [collectionSlug: string]: SanitizedJoin[]\n}\n\n/**\n * Properties populated during sanitization are redefined below. All other collection properties\n * preserve their incoming optionality.\n */\nexport interface SanitizedCollectionConfig\n extends\n Omit<\n CollectionConfig,\n | '_sanitized'\n | 'access'\n | 'admin'\n | 'auth'\n | 'authorship'\n | 'custom'\n | 'endpoints'\n | 'folder'\n | 'folders'\n | 'hierarchy'\n | 'hooks'\n | 'indexes'\n | 'labels'\n | 'slug'\n | 'tags'\n | 'timestamps'\n | 'upload'\n | 'versions'\n >,\n Required<Pick<CollectionConfig, 'admin' | 'custom' | 'indexes' | 'timestamps'>> {\n _sanitized: true\n access: Pick<CollectionAccess, 'admin'> &\n Required<\n Pick<\n CollectionAccess,\n 'create' | 'delete' | 'read' | 'readVersions' | 'unlock' | 'update' | 'validate'\n >\n >\n auth: Auth\n authorship: SanitizedAuthorship\n endpoints: Endpoint[] | false\n /**\n * Fields in the database schema structure\n * Rows / collapsible / tabs w/o name `fields` merged to top, UIs are excluded\n */\n flattenedFields: FlattenedField[]\n /**\n * Hierarchy configuration (when collection is a hierarchy type like folders or tags)\n */\n hierarchy: false | SanitizedHierarchyConfig\n hooks: Required<CollectionHooks>\n /**\n * Object of collections to join 'Join Fields object keyed by collection\n */\n joins: SanitizedJoins\n labels: Required<NonNullable<CollectionConfig['labels']>>\n /**\n * List of all polymorphic join fields\n */\n polymorphicJoins: SanitizedJoin[]\n\n sanitizedIndexes: SanitizedCompoundIndex[]\n\n slug: CollectionSlug\n\n upload: SanitizedUploadConfig\n versions?: SanitizedCollectionVersions\n}\n\nexport type Collection = {\n config: SanitizedCollectionConfig\n customIDType?: 'number' | 'text'\n graphQL?: {\n countType: GraphQLObjectType\n JWT: GraphQLObjectType\n mutationInputType: GraphQLNonNull<any>\n paginatedType: GraphQLObjectType\n type: GraphQLObjectType\n updateMutationInputType: GraphQLNonNull<any>\n versionType: GraphQLObjectType\n whereInputType: GraphQLInputObjectType\n }\n}\n\nexport type BulkOperationResult<TSlug extends CollectionSlug, TSelect extends SelectType> = {\n docs: TransformCollectionWithSelect<TSlug, TSelect>[]\n errors: {\n id: DataFromCollectionSlug<TSlug>['id']\n isPublic: boolean\n message: string\n }[]\n}\n\nexport type AuthCollection = {\n config: SanitizedCollectionConfig\n}\n\nexport type LocalizedMeta = {\n [locale: string]: {\n status: 'draft' | 'published'\n updatedAt: string\n }\n}\n\nexport type TypeWithID = {\n id: number | string\n}\n\nexport type TypeWithTimestamps = {\n [key: string]: unknown\n createdAt: string\n deletedAt?: null | string\n id: number | string\n updatedAt: string\n}\n\nexport type CompoundIndex = {\n fields: string[]\n unique?: boolean\n}\n\nexport type SanitizedCompoundIndex = {\n fields: {\n field: FlattenedField\n localizedPath: string\n path: string\n pathHasLocalized: boolean\n }[]\n unique: boolean\n}\n"],"names":[],"mappings":"AAAA,qDAAqD,GA+6BrD,WAQC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/findByID.ts"],"sourcesContent":["import type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, FindOptions, JoinQuery } from '../../index.js'\nimport type {\n ApplyDisableErrors,\n JsonObject,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { sanitizeJoinQuery } from '../../database/sanitizeJoinQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead, type AfterReadArgs } from '../../fields/hooks/afterRead/index.js'\nimport { validateQueryPaths } from '../../index.js'\nimport { lockedDocumentsCollectionSlug } from '../../locked-documents/config.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { getSelectMode } from '../../utilities/getSelectMode.js'\nimport { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSelect } from '../../versions/drafts/getQueryDraftsSelect.js'\nimport { replaceWithDraftIfAvailable } from '../../versions/drafts/replaceWithDraftIfAvailable.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type FindByIDArgs = {\n collection: Collection\n currentDepth?: number\n /**\n * You may pass the document data directly which will skip the `db.findOne` database query.\n * This is useful if you want to use this endpoint solely for running hooks and populating data.\n */\n data?: Record<string, unknown>\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n id: number | string\n includeLockStatus?: boolean\n joins?: JoinQuery\n overrideAccess?: boolean\n populate?: PopulateType\n req: PayloadRequest\n showHiddenFields?: boolean\n trash?: boolean\n} & Pick<AfterReadArgs<JsonObject>, 'flattenLocales'> &\n Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findByIDOperation = async <\n TSlug extends CollectionSlug,\n TDisableErrors extends boolean,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: FindByIDArgs,\n): Promise<ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>> => {\n let args = incomingArgs\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'read',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n draft: replaceWithVersion = false,\n flattenLocales,\n includeLockStatus: includeLockStatusFromArgs,\n joins,\n overrideAccess = false,\n populate,\n req: { fallbackLocale, locale, t },\n req,\n select: incomingSelect,\n showHiddenFields,\n trash = false,\n } = args\n\n const includeLockStatus =\n includeLockStatusFromArgs && req.payload.collections?.[lockedDocumentsCollectionSlug]\n\n const select = sanitizeSelect({\n fields: collectionConfig.flattenedFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n })\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResult = !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, disableErrors, req },\n collectionConfig.access.read,\n )\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResult === false) {\n return null!\n }\n\n const isValidID =\n (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && Number.isFinite(id))\n\n if (!isValidID) {\n throw new NotFound(t)\n }\n\n const where = { id: { equals: id } }\n\n let fullWhere = combineQueries(where, accessResult)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({\n fields: collectionConfig.flattenedFields,\n payload: args.req.payload,\n where: fullWhere,\n })\n\n const sanitizedJoins = await sanitizeJoinQuery({\n collectionConfig,\n joins,\n overrideAccess,\n req,\n })\n\n // execute only if there's a custom ID and potentially overwriten access on id\n if (req.payload.collections[collectionConfig.slug]!.customIDType) {\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n where,\n })\n }\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n const shouldQueryDrafts = !args.data && replaceWithVersion && hasDraftsEnabled(collectionConfig)\n let docWithLocales: DataFromCollectionSlug<TSlug> | null | undefined\n let query = fullWhere\n\n let dbSelect = select\n\n if (\n collectionConfig.versions?.drafts &&\n replaceWithVersion &&\n select &&\n getSelectMode(select) === 'include'\n ) {\n dbSelect = { ...select, createdAt: true, updatedAt: true }\n }\n\n const findOneArgs: FindOneArgs = {\n collection: collectionConfig.slug,\n draftsEnabled: replaceWithVersion,\n joins: req.payloadAPI === 'GraphQL' ? false : sanitizedJoins,\n locale: locale!,\n req: {\n transactionID: req.transactionID,\n } as PayloadRequest,\n select: dbSelect,\n where: fullWhere,\n }\n\n if (shouldQueryDrafts) {\n query = appendVersionToQueryKey(fullWhere)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n versionFields: buildVersionCollectionFields(req.payload.config, collectionConfig, true),\n where: appendVersionToQueryKey(where),\n })\n\n const { docs } = await req.payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : sanitizedJoins,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select: getQueryDraftsSelect({ select }),\n where: query,\n })\n\n docWithLocales = docs[0]\n\n if (!docWithLocales) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(where),\n })\n\n if (!existingVersions[0]) {\n query = fullWhere\n docWithLocales = await req.payload.db.findOne(findOneArgs)\n }\n }\n } else {\n docWithLocales = await req.payload.db.findOne(findOneArgs)\n }\n\n if (!docWithLocales && !args.data) {\n if (!disableErrors) {\n throw new NotFound(req.t)\n }\n return null!\n }\n\n let result: DataFromCollectionSlug<TSlug> =\n (args.data as DataFromCollectionSlug<TSlug>) ?? docWithLocales!\n\n // /////////////////////////////////////\n // Add collection property for auth collections\n // /////////////////////////////////////\n\n if (collectionConfig.auth) {\n result = { ...result, collection: collectionConfig.slug }\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n\n if (includeLockStatus && id) {\n let lockStatus: (JsonObject & TypeWithID) | null = null\n\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocument = await req.payload.find({\n collection: lockedDocumentsCollectionSlug,\n depth: 1,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n equals: id,\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n if (lockedDocument && lockedDocument.docs.length > 0) {\n lockStatus = lockedDocument.docs[0]!\n }\n } catch {\n // swallow error\n }\n\n result._isLocked = !!lockStatus\n result._userEditing = lockStatus?.user?.value ?? null\n }\n\n // /////////////////////////////////////\n // Replace document with draft if available\n // /////////////////////////////////////\n\n if (!shouldQueryDrafts && replaceWithVersion && hasDraftsEnabled(collectionConfig)) {\n result = await replaceWithDraftIfAvailable({\n accessResult,\n doc: result,\n entity: collectionConfig,\n entityType: 'collection',\n overrideAccess,\n req,\n select,\n })\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n query,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth: depth!,\n doc: result,\n draft: replaceWithVersion,\n fallbackLocale: fallbackLocale!,\n flattenLocales,\n global: null,\n locale: locale!,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields: 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 query,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findByID',\n overrideAccess,\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>\n}\n"],"names":["executeAccess","combineQueries","sanitizeJoinQuery","sanitizeWhereQuery","NotFound","afterRead","validateQueryPaths","lockedDocumentsCollectionSlug","appendNonTrashedFilter","getSelectMode","hasDraftsEnabled","resolveSelect","sanitizeSelect","buildVersionCollectionFields","appendVersionToQueryKey","getQueryDraftsSelect","replaceWithDraftIfAvailable","buildAfterOperation","buildBeforeOperation","findByIDOperation","incomingArgs","args","collection","config","operation","overrideAccess","id","collectionConfig","currentDepth","depth","disableErrors","draft","replaceWithVersion","flattenLocales","includeLockStatus","includeLockStatusFromArgs","joins","populate","req","fallbackLocale","locale","t","select","incomingSelect","showHiddenFields","trash","payload","collections","fields","flattenedFields","accessResult","slug","access","read","isValidID","length","Number","isFinite","where","equals","fullWhere","enableTrash","sanitizedJoins","customIDType","shouldQueryDrafts","data","docWithLocales","query","dbSelect","versions","drafts","createdAt","updatedAt","findOneArgs","draftsEnabled","payloadAPI","transactionID","versionFields","docs","db","queryDrafts","limit","pagination","existingVersions","parent","findOne","result","auth","lockStatus","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocument","find","and","greater_than","Date","getTime","_isLocked","_userEditing","user","value","doc","entity","entityType","hooks","beforeRead","hook","context","global"],"mappings":"AAiBA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAA4B,wCAAuC;AACrF,SAASC,kBAAkB,QAAQ,iBAAgB;AACnD,SAASC,6BAA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;gBACA0C;gBACA7B;YACF,MAAOgD;QACX;IACF;IAEA,wCAAwC;IACxC,8BAA8B;IAC9B,wCAAwC;IAExCA,SAAS,MAAMrE,oBAAoB;QACjCI;QACAC,YAAYK;QACZH,WAAW;QACXC;QACA6D;IACF;IAEA,wCAAwC;IACxC,iBAAiB;IACjB,wCAAwC;IAExC,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/findByID.ts"],"sourcesContent":["import type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, FindOptions, JoinQuery } from '../../index.js'\nimport type {\n ApplyDisableErrors,\n JsonObject,\n PayloadRequest,\n PopulateType,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n TypeWithID,\n} from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { sanitizeJoinQuery } from '../../database/sanitizeJoinQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead, type AfterReadArgs } from '../../fields/hooks/afterRead/index.js'\nimport { validateQueryPaths } from '../../index.js'\nimport { lockedDocumentsCollectionSlug } from '../../locked-documents/config.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { getSelectMode } from '../../utilities/getSelectMode.js'\nimport { hasDraftsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSelect } from '../../versions/drafts/getQueryDraftsSelect.js'\nimport { replaceWithDraftIfAvailable } from '../../versions/drafts/replaceWithDraftIfAvailable.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type FindByIDArgs = {\n collection: Collection\n currentDepth?: number\n /**\n * You may pass the document data directly which will skip the `db.findOne` database query.\n * This is useful if you want to use this endpoint solely for running hooks and populating data.\n */\n data?: Record<string, unknown>\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n id: number | string\n includeLockStatus?: boolean\n joins?: JoinQuery\n overrideAccess?: boolean\n populate?: PopulateType\n req: PayloadRequest\n showHiddenFields?: boolean\n trash?: boolean\n} & Pick<AfterReadArgs<JsonObject>, 'flattenLocales'> &\n Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findByIDOperation = async <\n TSlug extends CollectionSlug,\n TDisableErrors extends boolean,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: FindByIDArgs,\n): Promise<ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>> => {\n let args = incomingArgs\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'read',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n draft: replaceWithVersion = false,\n flattenLocales,\n includeLockStatus: includeLockStatusFromArgs,\n joins,\n overrideAccess = false,\n populate,\n req: { fallbackLocale, locale, t },\n req,\n select: incomingSelect,\n showHiddenFields,\n trash = false,\n } = args\n\n const includeLockStatus =\n includeLockStatusFromArgs && req.payload.collections?.[lockedDocumentsCollectionSlug]\n\n const select = sanitizeSelect({\n fields: collectionConfig.flattenedFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n })\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResult = !overrideAccess\n ? await executeAccess(\n { id, slug: collectionConfig.slug, disableErrors, req },\n collectionConfig.access.read,\n )\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResult === false) {\n return null!\n }\n\n const isValidID =\n (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && Number.isFinite(id))\n\n if (!isValidID) {\n throw new NotFound(t)\n }\n\n const where = { id: { equals: id } }\n\n let fullWhere = combineQueries(where, accessResult)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({\n fields: collectionConfig.flattenedFields,\n payload: args.req.payload,\n where: fullWhere,\n })\n\n const sanitizedJoins = await sanitizeJoinQuery({\n collectionConfig,\n joins,\n overrideAccess,\n req,\n })\n\n // execute only if there's a custom ID and potentially overwriten access on id\n if (req.payload.collections[collectionConfig.slug]!.customIDType) {\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n where,\n })\n }\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n const shouldQueryDrafts = !args.data && replaceWithVersion && hasDraftsEnabled(collectionConfig)\n let docWithLocales: DataFromCollectionSlug<TSlug> | null | undefined\n let query = fullWhere\n\n let dbSelect = select\n\n if (\n collectionConfig.versions?.drafts &&\n replaceWithVersion &&\n select &&\n getSelectMode(select) === 'include'\n ) {\n dbSelect = { ...select, createdAt: true, updatedAt: true }\n }\n\n const findOneArgs: FindOneArgs = {\n collection: collectionConfig.slug,\n draftsEnabled: replaceWithVersion,\n joins: req.payloadAPI === 'GraphQL' ? false : sanitizedJoins,\n locale: locale!,\n req: {\n transactionID: req.transactionID,\n },\n select: dbSelect,\n where: fullWhere,\n }\n\n if (shouldQueryDrafts) {\n query = appendVersionToQueryKey(fullWhere)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n versionFields: buildVersionCollectionFields(req.payload.config, collectionConfig, true),\n where: appendVersionToQueryKey(where),\n })\n\n const { docs } = await req.payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : sanitizedJoins,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select: getQueryDraftsSelect({ select }),\n where: query,\n })\n\n docWithLocales = docs[0]\n\n if (!docWithLocales) {\n const { docs: existingVersions } = await req.payload.db.queryDrafts({\n collection: collectionConfig.slug,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select: { parent: true },\n where: appendVersionToQueryKey(where),\n })\n\n if (!existingVersions[0]) {\n query = fullWhere\n docWithLocales = await req.payload.db.findOne(findOneArgs)\n }\n }\n } else {\n docWithLocales = await req.payload.db.findOne(findOneArgs)\n }\n\n if (!docWithLocales && !args.data) {\n if (!disableErrors) {\n throw new NotFound(req.t)\n }\n return null!\n }\n\n let result: DataFromCollectionSlug<TSlug> =\n (args.data as DataFromCollectionSlug<TSlug>) ?? docWithLocales!\n\n // /////////////////////////////////////\n // Add collection property for auth collections\n // /////////////////////////////////////\n\n if (collectionConfig.auth) {\n result = { ...result, collection: collectionConfig.slug }\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n\n if (includeLockStatus && id) {\n let lockStatus: (JsonObject & TypeWithID) | null = null\n\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocument = await req.payload.find({\n collection: lockedDocumentsCollectionSlug,\n depth: 1,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n equals: id,\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n if (lockedDocument && lockedDocument.docs.length > 0) {\n lockStatus = lockedDocument.docs[0]!\n }\n } catch {\n // swallow error\n }\n\n result._isLocked = !!lockStatus\n result._userEditing = lockStatus?.user?.value ?? null\n }\n\n // /////////////////////////////////////\n // Replace document with draft if available\n // /////////////////////////////////////\n\n if (!shouldQueryDrafts && replaceWithVersion && hasDraftsEnabled(collectionConfig)) {\n result = await replaceWithDraftIfAvailable({\n accessResult,\n doc: result,\n entity: collectionConfig,\n entityType: 'collection',\n overrideAccess,\n req,\n select,\n })\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n overrideAccess,\n query,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth: depth!,\n doc: result,\n draft: replaceWithVersion,\n fallbackLocale: fallbackLocale!,\n flattenLocales,\n global: null,\n locale: locale!,\n overrideAccess,\n populate,\n req,\n select,\n showHiddenFields: 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 query,\n req,\n })) || result\n }\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findByID',\n overrideAccess,\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>\n}\n"],"names":["executeAccess","combineQueries","sanitizeJoinQuery","sanitizeWhereQuery","NotFound","afterRead","validateQueryPaths","lockedDocumentsCollectionSlug","appendNonTrashedFilter","getSelectMode","hasDraftsEnabled","resolveSelect","sanitizeSelect","buildVersionCollectionFields","appendVersionToQueryKey","getQueryDraftsSelect","replaceWithDraftIfAvailable","buildAfterOperation","buildBeforeOperation","findByIDOperation","incomingArgs","args","collection","config","operation","overrideAccess","id","collectionConfig","currentDepth","depth","disableErrors","draft","replaceWithVersion","flattenLocales","includeLockStatus","includeLockStatusFromArgs","joins","populate","req","fallbackLocale","locale","t","select","incomingSelect","showHiddenFields","trash","payload","collections","fields","flattenedFields","accessResult","slug","access","read","isValidID","length","Number","isFinite","where","equals","fullWhere","enableTrash","sanitizedJoins","customIDType","shouldQueryDrafts","data","docWithLocales","query","dbSelect","versions","drafts","createdAt","updatedAt","findOneArgs","draftsEnabled","payloadAPI","transactionID","versionFields","docs","db","queryDrafts","limit","pagination","existingVersions","parent","findOne","result","auth","lockStatus","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocument","find","and","greater_than","Date","getTime","_isLocked","_userEditing","user","value","doc","entity","entityType","hooks","beforeRead","hook","context","global"],"mappings":"AAiBA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAA4B,wCAAuC;AACrF,SAASC,kBAAkB,QAAQ,iBAAgB;AACnD,SAASC,6BAA6B,QAAQ,mCAAkC;AAChF,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,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sources":["../../../src/collections/operations/findVersionByID.ts"],"sourcesContent":["import type { FindOptions } from '../../index.js'\nimport type { PayloadRequest, PopulateType, SelectType } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection, TypeWithID } from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { APIError, Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport {\n isInheritedReadVersionsAccess,\n withInheritedReadVersionsParentID,\n} from '../../versions/isInheritedReadVersionsAccess.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { prefetchVersionForInheritedReadAccess } from './utilities/prefetchVersionForInheritedReadAccess.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n id: number | string\n overrideAccess?: boolean\n populate?: PopulateType\n req: PayloadRequest\n showHiddenFields?: boolean\n trash?: boolean\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionByIDOperation = async <TData extends TypeWithID = any>(\n args: Arguments,\n): Promise<TypeWithVersion<TData>> => {\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n overrideAccess,\n populate,\n req: { fallbackLocale, locale, payload },\n req,\n select: incomingSelect,\n showHiddenFields,\n trash = false,\n } = args\n\n if (!id) {\n throw new APIError('Missing ID of version.', httpStatus.BAD_REQUEST)\n }\n\n if (!hasVersionsEnabled(collectionConfig)) {\n if (disableErrors) {\n return null!\n }\n\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersionByID',\n overrideAccess,\n })\n\n const where = { id: { equals: id } }\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n const inheritsReadAccess = isInheritedReadVersionsAccess(collectionConfig.access.readVersions)\n const shouldPrefetchVersion = !overrideAccess && inheritsReadAccess\n const prefetched = shouldPrefetchVersion\n ? await prefetchVersionForInheritedReadAccess<TData>({\n id,\n collectionConfig,\n locale: locale!,\n req,\n select,\n trash,\n })\n : undefined\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResults = !overrideAccess\n ? await executeAccess(\n {\n id,\n slug: collectionConfig.slug,\n disableErrors,\n req,\n },\n inheritsReadAccess\n ? (accessArgs) =>\n collectionConfig.access.readVersions(\n withInheritedReadVersionsParentID(accessArgs, prefetched?.parentID),\n )\n : collectionConfig.access.readVersions,\n )\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResults === false) {\n return null!\n }\n\n const hasWhereAccess = typeof accessResults === 'object'\n\n let fullWhere = combineQueries(where, accessResults)\n\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n let result = prefetched?.version as TypeWithVersion<TData>\n\n if (!shouldPrefetchVersion || hasWhereAccess) {\n const versionsQuery = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select,\n where: fullWhere,\n })\n\n result = versionsQuery.docs[0]!\n }\n\n if (!result) {\n if (!disableErrors) {\n if (!hasWhereAccess) {\n throw new NotFound(req.t)\n }\n if (hasWhereAccess) {\n throw new Forbidden(req.t)\n }\n }\n\n return null!\n }\n\n if (collectionConfig.upload && !overrideAccess) {\n const filename = (result.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: result.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n\n if (!result.version) {\n // Fallback if not selected\n ;(result as any).version = {}\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n result.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || result.version\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth: depth!,\n doc: result.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: 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.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || result.version\n }\n }\n\n if (collectionConfig.upload) {\n result.version = markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: result.version as Record<string, unknown>,\n req,\n versionID: result.id,\n }) as TData\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersionByID',\n overrideAccess,\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n}\n"],"names":["executeAccess","combineQueries","sanitizeWhereQuery","APIError","Forbidden","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","httpStatus","resolveSelect","sanitizeSelect","buildVersionCollectionFields","isInheritedReadVersionsAccess","withInheritedReadVersionsParentID","buildAfterOperation","buildBeforeOperation","prefetchVersionForInheritedReadAccess","findVersionByIDOperation","args","id","collection","config","collectionConfig","currentDepth","depth","disableErrors","overrideAccess","populate","req","fallbackLocale","locale","payload","select","incomingSelect","showHiddenFields","trash","BAD_REQUEST","t","operation","where","equals","versionFields","fields","versions","inheritsReadAccess","access","readVersions","shouldPrefetchVersion","prefetched","undefined","accessResults","slug","accessArgs","parentID","hasWhereAccess","fullWhere","deletedAtPath","enableTrash","result","version","versionsQuery","db","findVersions","limit","pagination","docs","upload","filename","documentID","parent","hooks","beforeRead","length","hook","context","doc","query","draft","global","collectionSlug","versionID"],"mappings":"AAKA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AACrE,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,sBAAsB,QAAQ,yDAAwD;AAC/F,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,UAAU,QAAQ,gCAA+B;AAC1D,SAASC,aAAa,QAAQ,m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E,SAAS,CAAE;YACnDuD,OAAOC,OAAO,GACZ,AAAC,MAAMc,KAAK;gBACVrD,YAAYE;gBACZoD,SAAS9C,IAAI8C,OAAO;gBACpBC,KAAKjB,OAAOC,OAAO;gBACnBjC;gBACAkD,OAAOrB;gBACP3B;YACF,MAAO8B,OAAOC,OAAO;QACzB;IACF;IAEA,IAAIrC,iBAAiB4C,MAAM,EAAE;QAC3BR,OAAOC,OAAO,GAAGtD,uBAAuB;YACtC0E,gBAAgBzD,iBAAiB6B,IAAI;YACrCwB,KAAKjB,OAAOC,OAAO;YACnB/B;YACAoD,WAAWtB,OAAOvC,EAAE;QACtB;IACF;IAEA,wCAAwC;IACxC,8BAA8B;IAC9B,wCAAwC;IAExCuC,SAAS,MAAM5C,oBAAoB;QACjCI;QACAE,YAAYE;QACZgB,WAAW;QACXZ;QACAgC;IACF;IAEA,wCAAwC;IACxC,iBAAiB;IACjB,wCAAwC;IAExC,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/findVersionByID.ts"],"sourcesContent":["import type { FindOptions } from '../../index.js'\nimport type { PayloadRequest, PopulateType, SelectType } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection, TypeWithID } from '../config/types.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { APIError, Forbidden, NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { httpStatus } from '../../utilities/httpStatus.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport {\n isInheritedReadVersionsAccess,\n withInheritedReadVersionsParentID,\n} from '../../versions/isInheritedReadVersionsAccess.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\nimport { prefetchVersionForInheritedReadAccess } from './utilities/prefetchVersionForInheritedReadAccess.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n id: number | string\n overrideAccess?: boolean\n populate?: PopulateType\n req: PayloadRequest\n showHiddenFields?: boolean\n trash?: boolean\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionByIDOperation = async <TData extends TypeWithID = any>(\n args: Arguments,\n): Promise<TypeWithVersion<TData>> => {\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n overrideAccess,\n populate,\n req: { fallbackLocale, locale, payload },\n req,\n select: incomingSelect,\n showHiddenFields,\n trash = false,\n } = args\n\n if (!id) {\n throw new APIError('Missing ID of version.', httpStatus.BAD_REQUEST)\n }\n\n if (!hasVersionsEnabled(collectionConfig)) {\n if (disableErrors) {\n return null!\n }\n\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersionByID',\n overrideAccess,\n })\n\n const where = { id: { equals: id } }\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n const inheritsReadAccess = isInheritedReadVersionsAccess(collectionConfig.access.readVersions)\n const shouldPrefetchVersion = !overrideAccess && inheritsReadAccess\n const prefetched = shouldPrefetchVersion\n ? await prefetchVersionForInheritedReadAccess<TData>({\n id,\n collectionConfig,\n locale: locale!,\n req,\n select,\n trash,\n })\n : undefined\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResults = !overrideAccess\n ? await executeAccess(\n {\n id,\n slug: collectionConfig.slug,\n disableErrors,\n req,\n },\n inheritsReadAccess\n ? (accessArgs) =>\n collectionConfig.access.readVersions(\n withInheritedReadVersionsParentID(accessArgs, prefetched?.parentID),\n )\n : collectionConfig.access.readVersions,\n )\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResults === false) {\n return null!\n }\n\n const hasWhereAccess = typeof accessResults === 'object'\n\n let fullWhere = combineQueries(where, accessResults)\n\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n let result = prefetched?.version as TypeWithVersion<TData>\n\n if (!shouldPrefetchVersion || hasWhereAccess) {\n const versionsQuery = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: 1,\n locale: locale!,\n pagination: false,\n req,\n select,\n where: fullWhere,\n })\n\n result = versionsQuery.docs[0]!\n }\n\n if (!result) {\n if (!disableErrors) {\n if (!hasWhereAccess) {\n throw new NotFound(req.t)\n }\n if (hasWhereAccess) {\n throw new Forbidden(req.t)\n }\n }\n\n return null!\n }\n\n if (collectionConfig.upload && !overrideAccess) {\n const filename = (result.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: result.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n\n if (!result.version) {\n // Fallback if not selected\n ;(result as any).version = {}\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n result.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || result.version\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth: depth!,\n doc: result.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: 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.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || result.version\n }\n }\n\n if (collectionConfig.upload) {\n result.version = markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: result.version,\n req,\n versionID: result.id,\n })\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersionByID',\n overrideAccess,\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n}\n"],"names":["executeAccess","combineQueries","sanitizeWhereQuery","APIError","Forbidden","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","httpStatus","resolveSelect","sanitizeSelect","buildVersionCollectionFields","isInheritedReadVersionsAccess","withInheritedReadVersionsParentID","buildAfterOperation","buildBeforeOperation","prefetchVersionForInheritedReadAccess","findVersionByIDOperation","args","id","collection","config","collectionConfig","currentDepth","depth","disableErrors","overrideAccess","populate","req","fallbackLocale","locale","payload","select","incomingSelect","showHiddenFields","trash","BAD_REQUEST","t","operation","where","equals","versionFields","fields","versions","inheritsReadAccess","access","readVersions","shouldPrefetchVersion","prefetched","undefined","accessResults","slug","accessArgs","parentID","hasWhereAccess","fullWhere","deletedAtPath","enableTrash","result","version","versionsQuery","db","findVersions","limit","pagination","docs","upload","filename","documentID","parent","hooks","beforeRead","length","hook","context","doc","query","draft","global","collectionSlug","versionID"],"mappings":"AAKA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,wBAAuB;AACrE,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,sBAAsB,QAAQ,yDAAwD;AAC/F,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,UAAU,QAAQ,gCAA+B;AAC1D,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SACEC,6BAA6B,EAC7BC,iCAAiC,QAC5B,kDAAiD;AACxD,SAASC,mBAAmB,QAAQ,qCAAoC;AACxE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,qCAAqC,QAAQ,uDAAsD;AAe5G,OAAO,MAAMC,2BAA2B,OACtCC;IAEA,MAAM,EACJC,EAAE,EACFC,YAAY,EAAEC,QAAQC,gBAAgB,EAAE,EACxCC,YAAY,EACZC,KAAK,EACLC,aAAa,EACbC,cAAc,EACdC,QAAQ,EACRC,KAAK,EAAEC,cAAc,EAAEC,MAAM,EAAEC,OAAO,EAAE,EACxCH,GAAG,EACHI,QAAQC,cAAc,EACtBC,gBAAgB,EAChBC,QAAQ,KAAK,EACd,GAAGjB;IAEJ,IAAI,CAACC,IAAI;QACP,MAAM,IAAInB,SAAS,0BAA0BQ,WAAW4B,WAAW;IACrE;IAEA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
|
-
{"version":3,"sources":["../../../src/collections/operations/findVersions.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection } from '../config/types.js'\nimport type { FindOptions } from './local/find.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type Arguments = {\n collection: Collection\n depth?: number\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n populate?: PopulateType\n req?: PayloadRequest\n showHiddenFields?: boolean\n sort?: Sort\n trash?: boolean\n where?: Where\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionsOperation = async <TData extends TypeWithVersion<TData>>(\n args: Arguments,\n): Promise<PaginatedDocs<TData>> => {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'findVersions',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n depth,\n limit,\n overrideAccess,\n page,\n pagination = true,\n populate,\n select: incomingSelect,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = args\n\n const req = args.req!\n const { fallbackLocale, locale, payload } = req\n\n if (!hasVersionsEnabled(collectionConfig)) {\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResults!: AccessResult\n\n if (!overrideAccess) {\n accessResults = await executeAccess(\n { slug: collectionConfig.slug, req },\n collectionConfig.access.readVersions,\n )\n }\n\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n versionFields,\n where: where!,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n versionFields,\n })\n\n let fullWhere = combineQueries(where!, accessResults)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n const paginatedDocs = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: sanitizedLimit,\n locale: locale!,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n\n if (collectionConfig.upload && !overrideAccess) {\n for (const row of paginatedDocs.docs) {\n const filename = (row.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: row.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n let result: PaginatedDocs<TData> = paginatedDocs as unknown as PaginatedDocs<TData>\n result.docs = (await Promise.all(\n paginatedDocs.docs.map(async (doc) => {\n const docRef = doc\n // Fallback if not selected\n if (!docRef.version) {\n ;(docRef as any).version = {}\n }\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || docRef.version\n }\n }\n\n return docRef\n }),\n )) as TData[]\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.docs = await Promise.all(\n result.docs.map(async (data) => {\n data.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: data.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n findMany: true,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: showHiddenFields!,\n })\n return data\n }),\n )\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks.afterRead?.length) {\n result.docs = await Promise.all(\n result.docs.map(async (doc) => {\n const docRef = doc\n\n for (const hook of collectionConfig.hooks.afterRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: doc.version,\n findMany: true,\n overrideAccess,\n query: fullWhere,\n req,\n })) || doc.version\n }\n\n return docRef\n }),\n )\n }\n\n if (collectionConfig.upload) {\n result.docs = result.docs.map((row) => ({\n ...row,\n version: markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: row.version as Record<string, unknown>,\n req,\n versionID: row.id,\n }) as TData,\n }))\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n result.docs = result.docs.map((doc) => sanitizeInternalFields<TData>(doc))\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersions',\n overrideAccess,\n result,\n })\n\n return result\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","resolveSelect","sanitizeInternalFields","sanitizeSelect","buildVersionCollectionFields","buildAfterOperation","buildBeforeOperation","findVersionsOperation","args","collection","config","operation","overrideAccess","collectionConfig","depth","limit","page","pagination","populate","select","incomingSelect","showHiddenFields","sort","trash","where","req","fallbackLocale","locale","payload","t","accessResults","slug","access","readVersions","versionFields","fullWhere","deletedAtPath","enableTrash","fields","versions","usePagination","sanitizedLimit","sanitizedPage","paginatedDocs","db","findVersions","upload","row","docs","filename","version","documentID","parent","result","Promise","all","map","doc","docRef","hooks","beforeRead","length","hook","context","query","data","draft","undefined","findMany","global","collectionSlug","versionID","id"],"mappings":"AAOA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,QAAQ,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,sBAAsB,QAAQ,yDAAwD;AAC/F,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC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O;oBAChBkB,UAAU;oBACVxD;oBACAoD,OAAO7B;oBACPV;gBACF,MAAOgC,IAAIP,OAAO;YACtB;YAEA,OAAOQ;QACT;IAEJ;IAEA,IAAI7C,iBAAiBiC,MAAM,EAAE;QAC3BO,OAAOL,IAAI,GAAGK,OAAOL,IAAI,CAACQ,GAAG,CAAC,CAACT,MAAS,CAAA;gBACtC,GAAGA,GAAG;gBACNG,SAASpD,uBAAuB;oBAC9BwE,gBAAgBzD,iBAAiBkB,IAAI;oBACrC0B,KAAKV,IAAIG,OAAO;oBAChBzB;oBACA8C,WAAWxB,IAAIyB,EAAE;gBACnB;YACF,CAAA;IACF;IAEA,wCAAwC;IACxC,iBAAiB;IACjB,wCAAwC;IACxCnB,OAAOL,IAAI,GAAGK,OAAOL,IAAI,CAACQ,GAAG,CAAC,CAACC,MAAQvD,uBAA8BuD;IAErE,wCAAwC;IACxC,8BAA8B;IAC9B,wCAAwC;IAExCJ,SAAS,MAAMhD,oBAAoB;QACjCG;QACAC,YAAYI;QACZF,WAAW;QACXC;QACAyC;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/findVersions.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { PayloadRequest, PopulateType, SelectType, Sort, Where } from '../../types/index.js'\nimport type { TypeWithVersion } from '../../versions/types.js'\nimport type { Collection } from '../config/types.js'\nimport type { FindOptions } from './local/find.js'\n\nimport { executeAccess } from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { validateSortQuery } from '../../database/queryValidation/validateSortQuery.js'\nimport { sanitizeWhereQuery } from '../../database/sanitizeWhereQuery.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { checkFileAccess } from '../../uploads/checkFileAccess.js'\nimport { markHistoricalFileURLs } from '../../uploads/fileVersioning/markHistoricalFileURLs.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { hasVersionsEnabled } from '../../utilities/getVersionsConfig.js'\nimport { resolveSelect } from '../../utilities/resolveSelect.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { sanitizeSelect } from '../../utilities/sanitizeSelect.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { buildAfterOperation } from './utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from './utilities/buildBeforeOperation.js'\n\nexport type Arguments = {\n collection: Collection\n depth?: number\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n populate?: PopulateType\n req?: PayloadRequest\n showHiddenFields?: boolean\n sort?: Sort\n trash?: boolean\n where?: Where\n} & Pick<FindOptions<string, SelectType>, 'select'>\n\nexport const findVersionsOperation = async <TData extends TypeWithVersion<TData>>(\n args: Arguments,\n): Promise<PaginatedDocs<TData>> => {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'findVersions',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n depth,\n limit,\n overrideAccess,\n page,\n pagination = true,\n populate,\n select: incomingSelect,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = args\n\n const req = args.req!\n const { fallbackLocale, locale, payload } = req\n\n if (!hasVersionsEnabled(collectionConfig)) {\n throw new NotFound(req.t)\n }\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResults!: AccessResult\n\n if (!overrideAccess) {\n accessResults = await executeAccess(\n { slug: collectionConfig.slug, req },\n collectionConfig.access.readVersions,\n )\n }\n\n const versionFields = buildVersionCollectionFields(payload.config, collectionConfig, true)\n\n await validateQueryPaths({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n versionFields,\n where: where!,\n })\n\n await validateSortQuery({\n collectionConfig,\n overrideAccess: overrideAccess!,\n req,\n sort,\n versionFields,\n })\n\n let fullWhere = combineQueries(where!, accessResults)\n\n // Exclude trashed documents when trash: false\n fullWhere = appendNonTrashedFilter({\n deletedAtPath: 'version.deletedAt',\n enableTrash: collectionConfig.trash,\n trash,\n where: fullWhere,\n })\n\n sanitizeWhereQuery({ fields: versionFields, payload, where: fullWhere })\n\n const select = sanitizeSelect({\n fields: versionFields,\n select: resolveSelect({\n config: collectionConfig.select,\n operation: 'read',\n req,\n select: incomingSelect,\n }),\n versions: true,\n })\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n const paginatedDocs = await payload.db.findVersions<TData>({\n collection: collectionConfig.slug,\n limit: sanitizedLimit,\n locale: locale!,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n\n if (collectionConfig.upload && !overrideAccess) {\n for (const row of paginatedDocs.docs) {\n const filename = (row.version as Record<string, unknown>)?.filename\n\n await checkFileAccess({\n collection: args.collection,\n documentID: row.parent,\n filename: typeof filename === 'string' ? filename : '',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n let result: PaginatedDocs<TData> = paginatedDocs as unknown as PaginatedDocs<TData>\n result.docs = (await Promise.all(\n paginatedDocs.docs.map(async (doc) => {\n const docRef = doc\n // Fallback if not selected\n if (!docRef.version) {\n ;(docRef as any).version = {}\n }\n\n if (collectionConfig.hooks?.beforeRead?.length) {\n for (const hook of collectionConfig.hooks.beforeRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef.version,\n overrideAccess,\n query: fullWhere,\n req,\n })) || docRef.version\n }\n }\n\n return docRef\n }),\n )) as TData[]\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result.docs = await Promise.all(\n result.docs.map(async (data) => {\n data.version = await afterRead({\n collection: collectionConfig,\n context: req.context,\n depth: depth!,\n doc: data.version,\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n draft: undefined,\n fallbackLocale: fallbackLocale!,\n findMany: true,\n global: null,\n locale: locale!,\n overrideAccess: overrideAccess!,\n populate,\n req,\n select: typeof select?.version === 'object' ? select.version : undefined,\n showHiddenFields: showHiddenFields!,\n })\n return data\n }),\n )\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks.afterRead?.length) {\n result.docs = await Promise.all(\n result.docs.map(async (doc) => {\n const docRef = doc\n\n for (const hook of collectionConfig.hooks.afterRead) {\n docRef.version =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: doc.version,\n findMany: true,\n overrideAccess,\n query: fullWhere,\n req,\n })) || doc.version\n }\n\n return docRef\n }),\n )\n }\n\n if (collectionConfig.upload) {\n result.docs = result.docs.map((row) => ({\n ...row,\n version: markHistoricalFileURLs({\n collectionSlug: collectionConfig.slug,\n doc: row.version,\n req,\n versionID: row.id,\n }),\n }))\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n result.docs = result.docs.map((doc) => sanitizeInternalFields<TData>(doc))\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findVersions',\n overrideAccess,\n result,\n })\n\n return result\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","validateSortQuery","sanitizeWhereQuery","NotFound","afterRead","checkFileAccess","markHistoricalFileURLs","appendNonTrashedFilter","hasVersionsEnabled","resolveSelect","sanitizeInternalFields","sanitizeSelect","buildVersionCollectionFields","buildAfterOperation","buildBeforeOperation","findVersionsOperation","args","collection","config","operation","overrideAccess","collectionConfig","depth","limit","page","pagination","populate","select","incomingSelect","showHiddenFields","sort","trash","where","req","fallbackLocale","locale","payload","t","accessResults","slug","access","readVersions","versionFields","fullWhere","deletedAtPath","enableTrash","fields","versions","usePagination","sanitizedLimit","sanitizedPage","paginatedDocs","db","findVersions","upload","row","docs","filename","version","documentID","parent","result","Promise","all","map","doc","docRef","hooks","beforeRead","length","hook","context","query","data","draft","undefined","findMany","global","collectionSlug","versionID","id"],"mappings":"AAOA,SAASA,aAAa,QAAQ,8BAA6B;AAC3D,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,iBAAiB,QAAQ,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,sBAAsB,QAAQ,yDAAwD;AAC/F,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,kBAAkB,QAAQ,uCAAsC;AACzE,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,cAAc,QAAQ,oCAAmC;AAClE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,mBAAmB,QAAQ,qCAAoC;AACxE,SAASC,oBAAoB,QAAQ,sCAAqC;AAiB1E,OAAO,MAAMC,wBAAwB,OACnCC;IAEA,wCAAwC;IACxC,+BAA+B;IAC/B,wCAAwC;IAExCA,OAAO,MAAMF,qBAAqB;QAChCE;QACAC,YAAYD,KAAKC,UAAU,CAACC,MAAM;QAClCC,WAAW;QACXC,gBAAgBJ,KAAKI,cAAc;IACrC;IAEA,MAAM,EACJH,YAAY,EAAEC,QAAQG,gBAAgB,EAAE,EACxCC,KAAK,EACLC,KAAK,EACLH,cAAc,EACdI,IAAI,EACJC,aAAa,IAAI,EACjBC,QAAQ,EACRC,QAAQC,cAAc,EACtBC,gBAAgB,EAChBC,IAAI,EACJC,QAAQ,KAAK,EACbC,KAAK,EACN,G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A8B;IAC9B,wCAAwC;IAExCJ,SAAS,MAAMhD,oBAAoB;QACjCG;QACAC,YAAYI;QACZF,WAAW;QACXC;QACAyC;IACF;IAEA,OAAOA;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/collections/operations/local/findDistinct.ts"],"sourcesContent":["import type {\n CollectionSlug,\n DataFromCollectionSlug,\n PaginatedDistinctDocs,\n Payload,\n PayloadRequest,\n PopulateType,\n RequestContext,\n Sort,\n TypedLocale,\n User,\n Where,\n} from '../../../index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type { CreatePayloadRequestArgs } from '../../../utilities/createPayloadRequest.js'\n\nimport { APIError, createPayloadRequest } from '../../../index.js'\nimport { findDistinctOperation } from '../findDistinct.js'\n\nexport type Options<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug>,\n> = {\n /**\n * the Collection slug to operate against.\n */\n collection: TSlug\n /**\n * [Context](https://payloadcms.com/docs/hooks/context), which will then be passed to `context` and `req.context`,\n * which can be read by hooks. Useful if you want to pass additional information to the hooks which\n * shouldn't be necessarily part of the document, for example a `triggerBeforeChange` option which can be read by the BeforeChange hook\n * to determine if it should run or not.\n */\n context?: RequestContext\n /**\n * [Control auto-population](https://payloadcms.com/docs/queries/depth) of nested relationship and upload fields.\n */\n depth?: number\n /**\n * When set to `true`, errors will not be thrown.\n */\n disableErrors?: boolean\n /**\n * The field to get distinct values for\n */\n field: ({} & string) | TField\n /**\n * The maximum distinct field values to be returned.\n * By default the operation returns all the values.\n */\n limit?: number\n /**\n * Specify [locale](https://payloadcms.com/docs/configuration/localization) for any returned documents.\n */\n locale?: 'all' | TypedLocale\n /**\n * Get a specific page number (if limit is specified)\n * @default 1\n */\n page?: number\n /**\n * Specify [populate](https://payloadcms.com/docs/queries/select#populate) to control which fields to include to the result from populated documents.\n */\n populate?: PopulateType\n /**\n * The `PayloadRequest` object. You can pass it to thread the current [transaction](https://payloadcms.com/docs/database/transactions), user and locale to the operation.\n * Recommended to pass when using the Local API from hooks, as usually you want to execute the operation within the current transaction.\n */\n req?: Partial<PayloadRequest>\n /**\n * Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config.\n * @default false\n */\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n /**\n * When set to `true`, the query will include both normal and trashed documents.\n * To query only trashed documents, pass `trash: true` and combine with a `where` clause filtering by `deletedAt`.\n * By default (`false`), the query will only include normal documents and exclude those with a `deletedAt` field.\n *\n * This argument has no effect unless `trash` is enabled on the collection.\n * @default false\n */\n trash?: boolean\n /**\n * If you set `overrideAccess` to `false`, you can pass a user to use against the access control checks.\n */\n user?: null | User\n /**\n * A filter [query](https://payloadcms.com/docs/queries/overview)\n */\n where?: Where\n} & Pick<SharedLocalAPIOptions, 'overrideAccess'>\n\nexport async function findDistinct<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug> & string,\n>(\n payload: Payload,\n options: Options<TSlug, TField>,\n): Promise<PaginatedDistinctDocs<Record<TField, DataFromCollectionSlug<TSlug>[TField]>>> {\n const {\n collection: collectionSlug,\n depth = 0,\n disableErrors,\n field,\n limit,\n overrideAccess = false,\n page,\n populate,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = options\n const collection = payload.collections[collectionSlug]\n\n if (!collection) {\n throw new APIError(\n `The collection with slug ${String(collectionSlug)} can't be found. Find Operation.`,\n )\n }\n\n return findDistinctOperation({\n collection,\n depth,\n disableErrors,\n field,\n limit,\n overrideAccess,\n page,\n populate,\n req: await createPayloadRequest({\n ...(options as Omit<CreatePayloadRequestArgs, 'payload'>),\n payload,\n }),\n showHiddenFields,\n sort,\n trash,\n where,\n })
|
|
1
|
+
{"version":3,"sources":["../../../../src/collections/operations/local/findDistinct.ts"],"sourcesContent":["import type {\n CollectionSlug,\n DataFromCollectionSlug,\n PaginatedDistinctDocs,\n Payload,\n PayloadRequest,\n PopulateType,\n RequestContext,\n Sort,\n TypedLocale,\n User,\n Where,\n} from '../../../index.js'\nimport type { SharedLocalAPIOptions } from '../../../types/operations.js'\nimport type { CreatePayloadRequestArgs } from '../../../utilities/createPayloadRequest.js'\n\nimport { APIError, createPayloadRequest } from '../../../index.js'\nimport { findDistinctOperation } from '../findDistinct.js'\n\nexport type Options<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug>,\n> = {\n /**\n * the Collection slug to operate against.\n */\n collection: TSlug\n /**\n * [Context](https://payloadcms.com/docs/hooks/context), which will then be passed to `context` and `req.context`,\n * which can be read by hooks. Useful if you want to pass additional information to the hooks which\n * shouldn't be necessarily part of the document, for example a `triggerBeforeChange` option which can be read by the BeforeChange hook\n * to determine if it should run or not.\n */\n context?: RequestContext\n /**\n * [Control auto-population](https://payloadcms.com/docs/queries/depth) of nested relationship and upload fields.\n */\n depth?: number\n /**\n * When set to `true`, errors will not be thrown.\n */\n disableErrors?: boolean\n /**\n * The field to get distinct values for\n */\n field: ({} & string) | TField\n /**\n * The maximum distinct field values to be returned.\n * By default the operation returns all the values.\n */\n limit?: number\n /**\n * Specify [locale](https://payloadcms.com/docs/configuration/localization) for any returned documents.\n */\n locale?: 'all' | TypedLocale\n /**\n * Get a specific page number (if limit is specified)\n * @default 1\n */\n page?: number\n /**\n * Specify [populate](https://payloadcms.com/docs/queries/select#populate) to control which fields to include to the result from populated documents.\n */\n populate?: PopulateType\n /**\n * The `PayloadRequest` object. You can pass it to thread the current [transaction](https://payloadcms.com/docs/database/transactions), user and locale to the operation.\n * Recommended to pass when using the Local API from hooks, as usually you want to execute the operation within the current transaction.\n */\n req?: Partial<PayloadRequest>\n /**\n * Opt-in to receiving hidden fields. By default, they are hidden from returned documents in accordance to your config.\n * @default false\n */\n showHiddenFields?: boolean\n /**\n * Sort the documents, can be a string or an array of strings\n * @example '-createdAt' // Sort DESC by createdAt\n * @example ['group', '-createdAt'] // sort by 2 fields, ASC group and DESC createdAt\n */\n sort?: Sort\n /**\n * When set to `true`, the query will include both normal and trashed documents.\n * To query only trashed documents, pass `trash: true` and combine with a `where` clause filtering by `deletedAt`.\n * By default (`false`), the query will only include normal documents and exclude those with a `deletedAt` field.\n *\n * This argument has no effect unless `trash` is enabled on the collection.\n * @default false\n */\n trash?: boolean\n /**\n * If you set `overrideAccess` to `false`, you can pass a user to use against the access control checks.\n */\n user?: null | User\n /**\n * A filter [query](https://payloadcms.com/docs/queries/overview)\n */\n where?: Where\n} & Pick<SharedLocalAPIOptions, 'overrideAccess'>\n\nexport async function findDistinct<\n TSlug extends CollectionSlug,\n TField extends keyof DataFromCollectionSlug<TSlug> & string,\n>(\n payload: Payload,\n options: Options<TSlug, TField>,\n): Promise<PaginatedDistinctDocs<Record<TField, DataFromCollectionSlug<TSlug>[TField]>>> {\n const {\n collection: collectionSlug,\n depth = 0,\n disableErrors,\n field,\n limit,\n overrideAccess = false,\n page,\n populate,\n showHiddenFields,\n sort,\n trash = false,\n where,\n } = options\n const collection = payload.collections[collectionSlug]\n\n if (!collection) {\n throw new APIError(\n `The collection with slug ${String(collectionSlug)} can't be found. Find Operation.`,\n )\n }\n\n return findDistinctOperation({\n collection,\n depth,\n disableErrors,\n field,\n limit,\n overrideAccess,\n page,\n populate,\n req: await createPayloadRequest({\n ...(options as Omit<CreatePayloadRequestArgs, 'payload'>),\n payload,\n }),\n showHiddenFields,\n sort,\n trash,\n where,\n })\n}\n"],"names":["APIError","createPayloadRequest","findDistinctOperation","findDistinct","payload","options","collection","collectionSlug","depth","disableErrors","field","limit","overrideAccess","page","populate","showHiddenFields","sort","trash","where","collections","String","req"],"mappings":"AAgBA,SAASA,QAAQ,EAAEC,oBAAoB,QAAQ,oBAAmB;AAClE,SAASC,qBAAqB,QAAQ,qBAAoB;AAkF1D,OAAO,eAAeC,aAIpBC,OAAgB,EAChBC,OAA+B;IAE/B,MAAM,EACJC,YAAYC,cAAc,EAC1BC,QAAQ,CAAC,EACTC,aAAa,EACbC,KAAK,EACLC,KAAK,EACLC,iBAAiB,KAAK,EACtBC,IAAI,EACJC,QAAQ,EACRC,gBAAgB,EAChBC,IAAI,EACJC,QAAQ,KAAK,EACbC,KAAK,EACN,GAAGb;IACJ,MAAMC,aAAaF,QAAQe,WAAW,CAACZ,eAAe;IAEtD,IAAI,CAACD,YAAY;QACf,MAAM,IAAIN,SACR,CAAC,yBAAyB,EAAEoB,OAAOb,gBAAgB,gCAAgC,CAAC;IAExF;IAEA,OAAOL,sBAAsB;QAC3BI;QACAE;QACAC;QACAC;QACAC;QACAC;QACAC;QACAC;QACAO,KAAK,MAAMpB,qBAAqB;YAC9B,GAAII,OAAO;YACXD;QACF;QACAW;QACAC;QACAC;QACAC;IACF;AACF"}
|
|
@@ -229,7 +229,7 @@ import { updateDocument } from './utilities/update.js';
|
|
|
229
229
|
autosave: false,
|
|
230
230
|
collectionConfig: collection.config,
|
|
231
231
|
config: req.payload.config,
|
|
232
|
-
data
|
|
232
|
+
data,
|
|
233
233
|
depth: args.depth ?? 0,
|
|
234
234
|
docWithLocales: stored,
|
|
235
235
|
draftArg: draft,
|