payload 4.0.0-beta.1 → 4.0.0-beta.3

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.
Files changed (61) hide show
  1. package/dist/auth/types.d.ts.map +1 -1
  2. package/dist/auth/types.js.map +1 -1
  3. package/dist/cli/commands/data/utilities.d.ts +1 -1
  4. package/dist/cli/commands/data/utilities.d.ts.map +1 -1
  5. package/dist/cli/commands/data/utilities.js.map +1 -1
  6. package/dist/collections/config/types.d.ts +4 -1
  7. package/dist/collections/config/types.d.ts.map +1 -1
  8. package/dist/collections/config/types.js.map +1 -1
  9. package/dist/collections/operations/utilities/update.js.map +1 -1
  10. package/dist/config/sanitize.js.map +1 -1
  11. package/dist/config/types.d.ts.map +1 -1
  12. package/dist/config/types.js.map +1 -1
  13. package/dist/database/types.d.ts +4 -0
  14. package/dist/database/types.d.ts.map +1 -1
  15. package/dist/database/types.js.map +1 -1
  16. package/dist/fields/config/reservedFieldNames.d.ts.map +1 -1
  17. package/dist/fields/config/reservedFieldNames.js.map +1 -1
  18. package/dist/fields/config/types.d.ts.map +1 -1
  19. package/dist/fields/config/types.js.map +1 -1
  20. package/dist/fields/hooks/afterRead/promise.js.map +1 -1
  21. package/dist/fields/hooks/beforeChange/flattenValidationData.d.ts +14 -0
  22. package/dist/fields/hooks/beforeChange/flattenValidationData.d.ts.map +1 -0
  23. package/dist/fields/hooks/beforeChange/flattenValidationData.js +36 -0
  24. package/dist/fields/hooks/beforeChange/flattenValidationData.js.map +1 -0
  25. package/dist/fields/hooks/beforeChange/promise.d.ts +2 -1
  26. package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
  27. package/dist/fields/hooks/beforeChange/promise.js +96 -22
  28. package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
  29. package/dist/fields/hooks/beforeChange/traverseFields.d.ts +2 -1
  30. package/dist/fields/hooks/beforeChange/traverseFields.d.ts.map +1 -1
  31. package/dist/fields/hooks/beforeChange/traverseFields.js +2 -1
  32. package/dist/fields/hooks/beforeChange/traverseFields.js.map +1 -1
  33. package/dist/globals/config/types.d.ts +2 -1
  34. package/dist/globals/config/types.d.ts.map +1 -1
  35. package/dist/globals/config/types.js.map +1 -1
  36. package/dist/hierarchy/addHierarchyToCollection.d.ts.map +1 -1
  37. package/dist/hierarchy/addHierarchyToCollection.js +32 -21
  38. package/dist/hierarchy/addHierarchyToCollection.js.map +1 -1
  39. package/dist/hierarchy/resolveHierarchyCollections.js +7 -1
  40. package/dist/hierarchy/resolveHierarchyCollections.js.map +1 -1
  41. package/dist/index.bundled.d.ts +12 -3
  42. package/dist/llm-instructions/getInstructionsCollection.d.ts.map +1 -1
  43. package/dist/llm-instructions/getInstructionsCollection.js +2 -0
  44. package/dist/llm-instructions/getInstructionsCollection.js.map +1 -1
  45. package/dist/types/index.d.ts.map +1 -1
  46. package/dist/types/index.js.map +1 -1
  47. package/dist/uploads/fileVersioning/cloudStorage.js.map +1 -1
  48. package/dist/uploads/formatFilesize.js +1 -1
  49. package/dist/uploads/formatFilesize.js.map +1 -1
  50. package/dist/uploads/generateFileData.js.map +1 -1
  51. package/dist/uploads/getFileContentRequirement.js.map +1 -1
  52. package/dist/utilities/entityInputSchema/validateEntityData.d.ts.map +1 -1
  53. package/dist/utilities/entityInputSchema/validateEntityData.js.map +1 -1
  54. package/dist/utilities/getVersionsConfig.js.map +1 -1
  55. package/dist/utilities/telemetry/conf/index.d.ts +4 -1
  56. package/dist/utilities/telemetry/conf/index.d.ts.map +1 -1
  57. package/dist/utilities/telemetry/conf/index.js.map +1 -1
  58. package/dist/versions/isInheritedReadVersionsAccess.js.map +1 -1
  59. package/package.json +21 -21
  60. package/skills/payload/reference/ENDPOINTS.md +3 -9
  61. package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hierarchy/resolveHierarchyCollections.ts"],"sourcesContent":["import type { CollectionConfig, SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { Config } from '../config/types.js'\nimport type {\n JoinField,\n Option,\n RelationshipField,\n SelectField,\n Validate,\n} from '../fields/config/types.js'\nimport type { Document } from '../types/index.js'\nimport type {\n HierarchyJoinFieldConfig,\n SanitizedHierarchyConfig,\n SanitizedHierarchyRelatedCollection,\n} from './types.js'\n\nimport { sanitizeJoinField } from '../fields/config/sanitizeJoinField.js'\nimport { fieldAffectsData } from '../fields/config/types.js'\nimport { extractID } from '../utilities/extractID.js'\nimport { flattenAllFields } from '../utilities/flattenAllFields.js'\nimport { getHierarchyFieldName } from './constants.js'\nimport { hierarchyCollectionAfterDelete } from './hooks/collectionAfterDelete.js'\nimport { injectHierarchyButton } from './injectHierarchyButton.js'\n\n/**\n * Resolves hierarchy relationships across collections.\n *\n * This function runs after individual collection sanitization to establish\n * cross-collection hierarchy relationships. It discovers which collections\n * reference each hierarchy and configures the necessary fields, components,\n * and hooks.\n *\n * @remarks\n * Must be called after all collections are sanitized.\n *\n * **What it does:**\n * - Discovers related collections by scanning for hierarchy relationship fields\n * - Injects `HierarchyButton` component when `custom.hierarchy.injectHeaderButton` is set\n * - Adds `collectionSpecific` validation to ensure hierarchy items accept the document type\n * - Injects the `hierarchyType` select field when `collectionSpecific` is enabled\n * - Injects join field when `joinField` is configured\n * - Adds `afterDelete` hook to clear hierarchy references when items are deleted\n * - Populates `relatedCollections` in the sanitized hierarchy config\n */\nexport const resolveHierarchyCollections = (config: Config): void => {\n const hierarchyCollections =\n config.collections?.filter((col) => col.hierarchy && typeof col.hierarchy === 'object') || []\n\n for (const hierarchyCollection of hierarchyCollections) {\n const hierarchy = hierarchyCollection.hierarchy\n\n // TypeScript guard - hierarchy is guaranteed to be an object by the filter above\n if (!hierarchy || typeof hierarchy !== 'object') {\n continue\n }\n\n const hierarchyConfig = hierarchy as SanitizedHierarchyConfig\n const defaultFieldName = getHierarchyFieldName(hierarchyCollection.slug)\n const parentFieldName = hierarchyConfig.parentFieldName ?? defaultFieldName\n const isParentFieldNameOverridden = parentFieldName !== defaultFieldName\n const collectionSpecific = hierarchyConfig.collectionSpecific\n const typeFieldName = collectionSpecific ? collectionSpecific.fieldName : undefined\n const allowHasMany = hierarchyConfig.allowHasMany ?? true\n\n // Build relatedCollections by scanning all collections for hierarchy fields\n const sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection> = {}\n\n const selfParentField = hierarchyCollection.fields.find(\n (field) =>\n fieldAffectsData(field) &&\n field.name === parentFieldName &&\n field.type === 'relationship' &&\n (field as RelationshipField).relationTo === hierarchyCollection.slug,\n ) as RelationshipField | undefined\n\n // Check if the hierarchy collection's own parent field should be replaced with a header button\n if (selfParentField?.custom?.hierarchy?.injectHeaderButton === true) {\n injectHierarchyButton({\n collection: hierarchyCollection,\n fieldName: parentFieldName,\n hierarchyCollectionSlug: hierarchyCollection.slug,\n parentFieldName: hierarchyConfig.parentFieldName,\n })\n }\n\n for (const collection of config.collections || []) {\n // Skip the hierarchy collection itself (handled above)\n if (collection.slug === hierarchyCollection.slug) {\n continue\n }\n\n // Find hierarchy field by the default name (what createFolderField uses)\n const hierarchyField = collection.fields.find(\n (field) =>\n fieldAffectsData(field) &&\n field.name === defaultFieldName &&\n field.type === 'relationship' &&\n (field as RelationshipField).relationTo === hierarchyCollection.slug,\n ) as RelationshipField | undefined\n\n // If parentFieldName is overridden, rename the field to match\n if (hierarchyField && isParentFieldNameOverridden) {\n hierarchyField.name = parentFieldName\n }\n\n if (!hierarchyField) {\n continue\n }\n\n const fieldHasMany = hierarchyField.hasMany ?? allowHasMany\n\n // If collectionSpecific, inject validation to check hierarchy allows this collection type\n if (collectionSpecific) {\n injectCollectionSpecificValidation({\n hierarchyField,\n hierarchySlug: hierarchyCollection.slug,\n typeFieldName: typeFieldName!,\n })\n }\n\n // Store discovered collection with hasMany info\n sanitizedRelatedCollections[collection.slug] = {\n fieldName: parentFieldName,\n hasMany: fieldHasMany,\n }\n\n // Inject HierarchyButton if field requests it\n if (hierarchyField.custom?.hierarchy?.injectHeaderButton === true) {\n injectHierarchyButton({\n collection,\n fieldName: parentFieldName,\n hierarchyCollectionSlug: hierarchyCollection.slug,\n parentFieldName: hierarchyConfig.parentFieldName,\n })\n }\n }\n\n // If collectionSpecific, add type field to hierarchy collection\n if (hierarchyConfig.collectionSpecific) {\n injectTypeField({\n config,\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n parentFieldName: hierarchyConfig.parentFieldName,\n sanitizedRelatedCollections,\n typeFieldName: hierarchyConfig.collectionSpecific.fieldName,\n })\n }\n\n // If joinField is configured, add the join field to query children\n if (hierarchyConfig.joinField) {\n injectJoinField({\n config,\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n joinFieldConfig: hierarchyConfig.joinField,\n parentFieldName,\n relatedSlugs: Object.keys(sanitizedRelatedCollections),\n })\n }\n\n // Update hierarchy config with sanitized relatedCollections\n if (hierarchyConfig) {\n hierarchyConfig.relatedCollections = sanitizedRelatedCollections\n }\n\n // Add afterDelete hook to clear folder references from related documents\n if (Object.keys(sanitizedRelatedCollections).length > 0) {\n injectAfterDeleteHook({\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n sanitizedRelatedCollections,\n })\n }\n\n // Add sidebar tab for this hierarchy collection (unless explicitly disabled)\n if (hierarchyConfig.admin.injectSidebarTab !== false) {\n injectSidebarTab({\n config,\n hierarchyCollection,\n hierarchyConfig,\n })\n\n // Hide from nav when sidebar tab is injected (unless user explicitly set group)\n if (hierarchyCollection.admin?.group === undefined) {\n hierarchyCollection.admin = {\n ...hierarchyCollection.admin,\n group: false,\n }\n }\n }\n }\n}\n\n/**\n * Injects validation for collectionSpecific hierarchy fields.\n * Ensures the selected hierarchy item allows documents of this collection type.\n */\nfunction injectCollectionSpecificValidation({\n hierarchyField,\n hierarchySlug,\n typeFieldName,\n}: {\n hierarchyField: RelationshipField\n hierarchySlug: string\n typeFieldName: string\n}): void {\n const existingValidate = hierarchyField.validate\n\n const validate: Validate<unknown> = async (value, options) => {\n // Run existing validation first if present\n if (existingValidate) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const existingResult = await existingValidate(value as any, options as any)\n if (existingResult !== true) {\n return existingResult\n }\n }\n\n return validateCollectionSpecificHierarchy({\n hierarchySlug,\n options,\n typeFieldName,\n value,\n })\n }\n\n hierarchyField.validate = validate\n}\n\ntype HierarchyValidationOptions = Parameters<Validate<unknown>>[1]\n\nconst validateCollectionSpecificHierarchy = async ({\n hierarchySlug,\n options,\n typeFieldName,\n value,\n}: {\n hierarchySlug: string\n options: HierarchyValidationOptions\n typeFieldName: string\n value: unknown\n}): Promise<string | true> => {\n if (!value || (Array.isArray(value) && value.length === 0)) {\n return true\n }\n\n const { collectionSlug, overrideAccess, previousValue, req } = options\n const newIDs = (Array.isArray(value) ? value : [value]).map((item) => extractID<Document>(item))\n\n const previousIDs = new Set(\n (Array.isArray(previousValue) ? previousValue : previousValue ? [previousValue] : []).map(\n (item) => extractID<Document>(item),\n ),\n )\n\n for (const newID of newIDs) {\n if (previousIDs.has(newID)) {\n continue\n }\n\n let parentItem: Document | null = null\n if (typeof newID === 'string' || typeof newID === 'number') {\n try {\n parentItem = await req.payload.findByID({\n id: newID,\n collection: hierarchySlug,\n depth: 0,\n overrideAccess: overrideAccess ?? false,\n req,\n select: { [typeFieldName]: true },\n })\n } catch {\n return `Hierarchy item with ID ${newID} not found`\n }\n }\n\n if (!parentItem) {\n return `Hierarchy item with ID ${newID} not found`\n }\n\n const allowedTypes: string[] = (parentItem[typeFieldName] as string[]) || []\n\n if (allowedTypes.length === 0 || (collectionSlug && allowedTypes.includes(collectionSlug))) {\n continue\n }\n\n return `Hierarchy item \"${newID}\" does not allow documents of type \"${collectionSlug}\"`\n }\n\n return true\n}\n\n/**\n * Injects the hierarchyType select field into a hierarchy collection.\n */\nfunction injectTypeField({\n config,\n hierarchyCollection,\n parentFieldName,\n sanitizedRelatedCollections,\n typeFieldName,\n}: {\n config: Config\n hierarchyCollection: CollectionConfig | SanitizedCollectionConfig\n parentFieldName: string\n sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection>\n typeFieldName: string\n}): void {\n const collectionOptions: Option[] = Object.keys(sanitizedRelatedCollections).map((slug) => {\n const relatedCollection = config.collections?.find((c) => c.slug === slug)\n\n return {\n label: relatedCollection?.labels?.plural || slug,\n value: slug,\n }\n })\n\n const typeField: SelectField = {\n name: typeFieldName,\n type: 'select',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/ui/rsc#HierarchyTypeFieldServer',\n serverProps: {\n collectionOptions,\n parentFieldName,\n },\n },\n },\n position: 'sidebar',\n },\n hasMany: true,\n label: ({ t }) => t('general:allowedTypes'),\n options: collectionOptions,\n }\n\n hierarchyCollection.fields = hierarchyCollection.fields || []\n hierarchyCollection.fields.push(typeField)\n\n // Recompute flattenedFields since we added a field after initial sanitization\n // This is required for the field to be queryable\n if ('flattenedFields' in hierarchyCollection) {\n hierarchyCollection.flattenedFields = flattenAllFields({\n fields: hierarchyCollection.fields,\n })\n }\n}\n\n/**\n * Injects a join field to query all children of a hierarchy item.\n */\nfunction injectJoinField({\n config,\n hierarchyCollection,\n joinFieldConfig,\n parentFieldName,\n relatedSlugs,\n}: {\n config: Config\n hierarchyCollection: SanitizedCollectionConfig\n joinFieldConfig: HierarchyJoinFieldConfig\n parentFieldName: string\n relatedSlugs: string[]\n}): void {\n const { name, admin: userAdmin, ...userConfig } = joinFieldConfig\n\n const hasJoinField = hierarchyCollection.fields?.some(\n (field) => 'name' in field && field.name === name,\n )\n\n if (hasJoinField) {\n return\n }\n\n const joinField: JoinField = {\n // User config (spread first so auto-generated values take precedence for required fields)\n ...userConfig,\n // Auto-generated values (these cannot be overridden)\n name,\n type: 'join',\n collection: [hierarchyCollection.slug, ...relatedSlugs],\n hasMany: true,\n on: parentFieldName,\n // Merge admin config\n admin: {\n ...userAdmin,\n },\n }\n\n hierarchyCollection.fields = hierarchyCollection.fields || []\n hierarchyCollection.fields.push(joinField)\n\n // Sanitize the join field to register it properly\n sanitizeJoinField({\n config,\n field: joinField,\n joins: hierarchyCollection.joins,\n parentIsLocalized: false,\n polymorphicJoins: hierarchyCollection.polymorphicJoins,\n })\n\n // Recompute flattenedFields since we added a field after initial sanitization\n hierarchyCollection.flattenedFields = flattenAllFields({\n fields: hierarchyCollection.fields,\n })\n}\n\n/**\n * Injects afterDelete hook to clear hierarchy references from related documents.\n */\nfunction injectAfterDeleteHook({\n hierarchyCollection,\n sanitizedRelatedCollections,\n}: {\n hierarchyCollection: CollectionConfig | SanitizedCollectionConfig\n sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection>\n}): void {\n // Build map of collection slugs to their field names\n const relatedCollectionFieldMap: Record<string, string> = {}\n for (const [slug, relatedConfig] of Object.entries(sanitizedRelatedCollections)) {\n relatedCollectionFieldMap[slug] = relatedConfig.fieldName\n }\n\n hierarchyCollection.hooks = hierarchyCollection.hooks || {}\n hierarchyCollection.hooks.afterDelete = [\n ...(hierarchyCollection.hooks.afterDelete || []),\n hierarchyCollectionAfterDelete({ relatedCollections: relatedCollectionFieldMap }),\n ]\n}\n\n/**\n * Injects a sidebar tab for a hierarchy collection.\n */\nfunction injectSidebarTab({\n config,\n hierarchyCollection,\n hierarchyConfig,\n}: {\n config: Config\n hierarchyCollection: CollectionConfig\n hierarchyConfig: SanitizedHierarchyConfig\n}): void {\n const tabSlug = `hierarchy-${hierarchyCollection.slug}`\n const Icon = hierarchyConfig.admin.components.Icon\n\n // Initialize admin config structure\n config.admin = config.admin || {}\n config.admin.components = config.admin.components || {}\n config.admin.components.sidebar = config.admin.components.sidebar || {}\n config.admin.components.sidebar.tabs = config.admin.components.sidebar.tabs || []\n\n // Check if tab already exists\n const hasTab = config.admin.components.sidebar.tabs.some((tab) => tab.slug === tabSlug)\n\n if (!hasTab) {\n config.admin.components.sidebar.tabs.push({\n slug: tabSlug,\n components: {\n Content: {\n clientProps: {\n hierarchyCollectionSlug: hierarchyCollection.slug,\n },\n path: '@payloadcms/ui/rsc#HierarchySidebarTabServer',\n },\n Icon,\n },\n label: hierarchyCollection.labels?.plural || hierarchyCollection.slug,\n })\n }\n}\n"],"names":["sanitizeJoinField","fieldAffectsData","extractID","flattenAllFields","getHierarchyFieldName","hierarchyCollectionAfterDelete","injectHierarchyButton","resolveHierarchyCollections","config","hierarchyCollections","collections","filter","col","hierarchy","hierarchyCollection","hierarchyConfig","defaultFieldName","slug","parentFieldName","isParentFieldNameOverridden","collectionSpecific","typeFieldName","fieldName","undefined","allowHasMany","sanitizedRelatedCollections","selfParentField","fields","find","field","name","type","relationTo","custom","injectHeaderButton","collection","hierarchyCollectionSlug","hierarchyField","fieldHasMany","hasMany","injectCollectionSpecificValidation","hierarchySlug","injectTypeField","joinField","injectJoinField","joinFieldConfig","relatedSlugs","Object","keys","relatedCollections","length","injectAfterDeleteHook","admin","injectSidebarTab","group","existingValidate","validate","value","options","existingResult","validateCollectionSpecificHierarchy","Array","isArray","collectionSlug","overrideAccess","previousValue","req","newIDs","map","item","previousIDs","Set","newID","has","parentItem","payload","findByID","id","depth","select","allowedTypes","includes","collectionOptions","relatedCollection","c","label","labels","plural","typeField","components","Field","path","serverProps","position","t","push","flattenedFields","userAdmin","userConfig","hasJoinField","some","on","joins","parentIsLocalized","polymorphicJoins","relatedCollectionFieldMap","relatedConfig","entries","hooks","afterDelete","tabSlug","Icon","sidebar","tabs","hasTab","tab","Content","clientProps"],"mappings":"AAgBA,SAASA,iBAAiB,QAAQ,wCAAuC;AACzE,SAASC,gBAAgB,QAAQ,4BAA2B;AAC5D,SAASC,SAAS,QAAQ,4BAA2B;AACrD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,qBAAqB,QAAQ,iBAAgB;AACtD,SAASC,8BAA8B,QAAQ,mCAAkC;AACjF,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,MAAMC,8BAA8B,CAACC;IAC1C,MAAMC,uBACJD,OAAOE,WAAW,EAAEC,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AU,CAACuB,OAAO,CAACC,IAAI,CAACb,IAAI,CAAC,CAACe,MAAQA,IAAIlG,IAAI,KAAK6F;IAE/E,IAAI,CAACI,QAAQ;QACX1G,OAAO4C,KAAK,CAACqC,UAAU,CAACuB,OAAO,CAACC,IAAI,CAAClB,IAAI,CAAC;YACxC9E,MAAM6F;YACNrB,YAAY;gBACV2B,SAAS;oBACPC,aAAa;wBACXjF,yBAAyBtB,oBAAoBG,IAAI;oBACnD;oBACA0E,MAAM;gBACR;gBACAoB;YACF;YACA1B,OAAOvE,oBAAoBwE,MAAM,EAAEC,UAAUzE,oBAAoBG,IAAI;QACvE;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/hierarchy/resolveHierarchyCollections.ts"],"sourcesContent":["import type { CollectionConfig, SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { Config } from '../config/types.js'\nimport type {\n JoinField,\n Option,\n RelationshipField,\n SelectField,\n Validate,\n} from '../fields/config/types.js'\nimport type { Document } from '../types/index.js'\nimport type {\n HierarchyJoinFieldConfig,\n SanitizedHierarchyConfig,\n SanitizedHierarchyRelatedCollection,\n} from './types.js'\n\nimport { sanitizeJoinField } from '../fields/config/sanitizeJoinField.js'\nimport { fieldAffectsData } from '../fields/config/types.js'\nimport { extractID } from '../utilities/extractID.js'\nimport { flattenAllFields } from '../utilities/flattenAllFields.js'\nimport { getHierarchyFieldName } from './constants.js'\nimport { hierarchyCollectionAfterDelete } from './hooks/collectionAfterDelete.js'\nimport { injectHierarchyButton } from './injectHierarchyButton.js'\n\n/**\n * Resolves hierarchy relationships across collections.\n *\n * This function runs after individual collection sanitization to establish\n * cross-collection hierarchy relationships. It discovers which collections\n * reference each hierarchy and configures the necessary fields, components,\n * and hooks.\n *\n * @remarks\n * Must be called after all collections are sanitized.\n *\n * **What it does:**\n * - Discovers related collections by scanning for hierarchy relationship fields\n * - Injects `HierarchyButton` component when `custom.hierarchy.injectHeaderButton` is set\n * - Adds `collectionSpecific` validation to ensure hierarchy items accept the document type\n * - Injects the `hierarchyType` select field when `collectionSpecific` is enabled\n * - Injects join field when `joinField` is configured\n * - Adds `afterDelete` hook to clear hierarchy references when items are deleted\n * - Populates `relatedCollections` in the sanitized hierarchy config\n */\nexport const resolveHierarchyCollections = (config: Config): void => {\n const hierarchyCollections =\n config.collections?.filter((col) => col.hierarchy && typeof col.hierarchy === 'object') || []\n\n for (const hierarchyCollection of hierarchyCollections) {\n const hierarchy = hierarchyCollection.hierarchy\n\n // TypeScript guard - hierarchy is guaranteed to be an object by the filter above\n if (!hierarchy || typeof hierarchy !== 'object') {\n continue\n }\n\n const hierarchyConfig = hierarchy as SanitizedHierarchyConfig\n const defaultFieldName = getHierarchyFieldName(hierarchyCollection.slug)\n const parentFieldName = hierarchyConfig.parentFieldName ?? defaultFieldName\n const isParentFieldNameOverridden = parentFieldName !== defaultFieldName\n const collectionSpecific = hierarchyConfig.collectionSpecific\n const typeFieldName = collectionSpecific ? collectionSpecific.fieldName : undefined\n const allowHasMany = hierarchyConfig.allowHasMany ?? true\n\n // Build relatedCollections by scanning all collections for hierarchy fields\n const sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection> = {}\n\n const selfParentField = hierarchyCollection.fields.find(\n (field) =>\n fieldAffectsData(field) &&\n field.name === parentFieldName &&\n field.type === 'relationship' &&\n (field as RelationshipField).relationTo === hierarchyCollection.slug,\n ) as RelationshipField | undefined\n\n // Check if the hierarchy collection's own parent field should be replaced with a header button\n if (selfParentField?.custom?.hierarchy?.injectHeaderButton === true) {\n injectHierarchyButton({\n collection: hierarchyCollection,\n fieldName: parentFieldName,\n hierarchyCollectionSlug: hierarchyCollection.slug,\n parentFieldName: hierarchyConfig.parentFieldName,\n })\n }\n\n for (const collection of config.collections || []) {\n // Skip the hierarchy collection itself (handled above)\n if (collection.slug === hierarchyCollection.slug) {\n continue\n }\n\n // Find hierarchy field by the default name (what createFolderField uses)\n const hierarchyField = collection.fields.find(\n (field) =>\n fieldAffectsData(field) &&\n field.name === defaultFieldName &&\n field.type === 'relationship' &&\n (field as RelationshipField).relationTo === hierarchyCollection.slug,\n ) as RelationshipField | undefined\n\n // If parentFieldName is overridden, rename the field to match\n if (hierarchyField && isParentFieldNameOverridden) {\n hierarchyField.name = parentFieldName\n }\n\n if (!hierarchyField) {\n continue\n }\n\n const fieldHasMany = hierarchyField.hasMany ?? allowHasMany\n\n // If collectionSpecific, inject validation to check hierarchy allows this collection type\n if (collectionSpecific) {\n injectCollectionSpecificValidation({\n hierarchyField,\n hierarchySlug: hierarchyCollection.slug,\n typeFieldName: typeFieldName!,\n })\n }\n\n // Store discovered collection with hasMany info\n sanitizedRelatedCollections[collection.slug] = {\n fieldName: parentFieldName,\n hasMany: fieldHasMany,\n }\n\n // Inject HierarchyButton if field requests it\n if (hierarchyField.custom?.hierarchy?.injectHeaderButton === true) {\n injectHierarchyButton({\n collection,\n fieldName: parentFieldName,\n hierarchyCollectionSlug: hierarchyCollection.slug,\n parentFieldName: hierarchyConfig.parentFieldName,\n })\n }\n }\n\n // If collectionSpecific, add type field to hierarchy collection\n if (hierarchyConfig.collectionSpecific) {\n injectTypeField({\n config,\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n parentFieldName: hierarchyConfig.parentFieldName,\n sanitizedRelatedCollections,\n typeFieldName: hierarchyConfig.collectionSpecific.fieldName,\n })\n }\n\n // If joinField is configured, add the join field to query children\n if (hierarchyConfig.joinField) {\n injectJoinField({\n config,\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n joinFieldConfig: hierarchyConfig.joinField,\n parentFieldName,\n relatedSlugs: Object.keys(sanitizedRelatedCollections),\n })\n }\n\n // Update hierarchy config with sanitized relatedCollections\n if (hierarchyConfig) {\n hierarchyConfig.relatedCollections = sanitizedRelatedCollections\n }\n\n // Add afterDelete hook to clear folder references from related documents\n if (Object.keys(sanitizedRelatedCollections).length > 0) {\n injectAfterDeleteHook({\n hierarchyCollection: hierarchyCollection as SanitizedCollectionConfig,\n sanitizedRelatedCollections,\n })\n }\n\n // Add sidebar tab for this hierarchy collection (unless explicitly disabled)\n if (hierarchyConfig.admin.injectSidebarTab !== false) {\n injectSidebarTab({\n config,\n hierarchyCollection,\n hierarchyConfig,\n })\n\n // Hide from nav when sidebar tab is injected (unless user explicitly set group)\n if (hierarchyCollection.admin?.group === undefined) {\n hierarchyCollection.admin = {\n ...hierarchyCollection.admin,\n group: false,\n }\n }\n }\n }\n}\n\n/**\n * Injects validation for collectionSpecific hierarchy fields.\n * Ensures the selected hierarchy item allows documents of this collection type.\n */\nfunction injectCollectionSpecificValidation({\n hierarchyField,\n hierarchySlug,\n typeFieldName,\n}: {\n hierarchyField: RelationshipField\n hierarchySlug: string\n typeFieldName: string\n}): void {\n const existingValidate = hierarchyField.validate\n\n const validate: Validate<unknown> = async (value, options) => {\n // Run existing validation first if present\n if (existingValidate) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const existingResult = await existingValidate(value as any, options as any)\n if (existingResult !== true) {\n return existingResult\n }\n }\n\n return validateCollectionSpecificHierarchy({\n hierarchySlug,\n options,\n typeFieldName,\n value,\n })\n }\n\n hierarchyField.validate = validate\n}\n\ntype HierarchyValidationOptions = Parameters<Validate<unknown>>[1]\n\nconst validateCollectionSpecificHierarchy = async ({\n hierarchySlug,\n options,\n typeFieldName,\n value,\n}: {\n hierarchySlug: string\n options: HierarchyValidationOptions\n typeFieldName: string\n value: unknown\n}): Promise<string | true> => {\n if (!value || (Array.isArray(value) && value.length === 0)) {\n return true\n }\n\n const { collectionSlug, overrideAccess, previousValue, req } = options\n const newIDs = (Array.isArray(value) ? value : [value]).map((item) => extractID<Document>(item))\n\n const previousIDs = new Set(\n (Array.isArray(previousValue) ? previousValue : previousValue ? [previousValue] : []).map(\n (item) => extractID<Document>(item),\n ),\n )\n\n for (const newID of newIDs) {\n if (previousIDs.has(newID)) {\n continue\n }\n\n let parentItem: Document | null = null\n if (typeof newID === 'string' || typeof newID === 'number') {\n try {\n parentItem = await req.payload.findByID({\n id: newID,\n collection: hierarchySlug,\n depth: 0,\n overrideAccess: overrideAccess ?? false,\n req,\n select: { [typeFieldName]: true },\n })\n } catch {\n return `Hierarchy item with ID ${newID} not found`\n }\n }\n\n if (!parentItem) {\n return `Hierarchy item with ID ${newID} not found`\n }\n\n const allowedTypes: string[] = (parentItem[typeFieldName] as string[]) || []\n\n if (allowedTypes.length === 0 || (collectionSlug && allowedTypes.includes(collectionSlug))) {\n continue\n }\n\n return `Hierarchy item \"${newID}\" does not allow documents of type \"${collectionSlug}\"`\n }\n\n return true\n}\n\n/**\n * Injects the hierarchyType select field into a hierarchy collection.\n */\nfunction injectTypeField({\n config,\n hierarchyCollection,\n parentFieldName,\n sanitizedRelatedCollections,\n typeFieldName,\n}: {\n config: Config\n hierarchyCollection: CollectionConfig | SanitizedCollectionConfig\n parentFieldName: string\n sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection>\n typeFieldName: string\n}): void {\n const collectionOptions: Option[] = Object.keys(sanitizedRelatedCollections).map((slug) => {\n const relatedCollection = config.collections?.find((c) => c.slug === slug)\n\n return {\n label: relatedCollection?.labels?.plural || slug,\n value: slug,\n }\n })\n\n const typeField: SelectField = {\n name: typeFieldName,\n type: 'select',\n admin: {\n components: {\n Field: {\n path: '@payloadcms/ui/rsc#HierarchyTypeFieldServer',\n serverProps: {\n collectionOptions,\n parentFieldName,\n },\n },\n },\n position: 'sidebar',\n },\n hasMany: true,\n label: ({ t }) => t('general:allowedTypes'),\n options: collectionOptions,\n }\n\n hierarchyCollection.fields = hierarchyCollection.fields || []\n\n // This can run again on the same `fields` array, so replace the field if it already exists\n const existingTypeFieldIndex = hierarchyCollection.fields.findIndex(\n (field) => fieldAffectsData(field) && field.name === typeFieldName,\n )\n\n if (existingTypeFieldIndex === -1) {\n hierarchyCollection.fields.push(typeField)\n } else {\n hierarchyCollection.fields[existingTypeFieldIndex] = typeField\n }\n\n // Recompute flattenedFields since we added a field after initial sanitization\n // This is required for the field to be queryable\n if ('flattenedFields' in hierarchyCollection) {\n hierarchyCollection.flattenedFields = flattenAllFields({\n fields: hierarchyCollection.fields,\n })\n }\n}\n\n/**\n * Injects a join field to query all children of a hierarchy item.\n */\nfunction injectJoinField({\n config,\n hierarchyCollection,\n joinFieldConfig,\n parentFieldName,\n relatedSlugs,\n}: {\n config: Config\n hierarchyCollection: SanitizedCollectionConfig\n joinFieldConfig: HierarchyJoinFieldConfig\n parentFieldName: string\n relatedSlugs: string[]\n}): void {\n const { name, admin: userAdmin, ...userConfig } = joinFieldConfig\n\n const hasJoinField = hierarchyCollection.fields?.some(\n (field) => 'name' in field && field.name === name,\n )\n\n if (hasJoinField) {\n return\n }\n\n const joinField: JoinField = {\n // User config (spread first so auto-generated values take precedence for required fields)\n ...userConfig,\n // Auto-generated values (these cannot be overridden)\n name,\n type: 'join',\n collection: [hierarchyCollection.slug, ...relatedSlugs],\n hasMany: true,\n on: parentFieldName,\n // Merge admin config\n admin: {\n ...userAdmin,\n },\n }\n\n hierarchyCollection.fields = hierarchyCollection.fields || []\n hierarchyCollection.fields.push(joinField)\n\n // Sanitize the join field to register it properly\n sanitizeJoinField({\n config,\n field: joinField,\n joins: hierarchyCollection.joins,\n parentIsLocalized: false,\n polymorphicJoins: hierarchyCollection.polymorphicJoins,\n })\n\n // Recompute flattenedFields since we added a field after initial sanitization\n hierarchyCollection.flattenedFields = flattenAllFields({\n fields: hierarchyCollection.fields,\n })\n}\n\n/**\n * Injects afterDelete hook to clear hierarchy references from related documents.\n */\nfunction injectAfterDeleteHook({\n hierarchyCollection,\n sanitizedRelatedCollections,\n}: {\n hierarchyCollection: CollectionConfig | SanitizedCollectionConfig\n sanitizedRelatedCollections: Record<string, SanitizedHierarchyRelatedCollection>\n}): void {\n // Build map of collection slugs to their field names\n const relatedCollectionFieldMap: Record<string, string> = {}\n for (const [slug, relatedConfig] of Object.entries(sanitizedRelatedCollections)) {\n relatedCollectionFieldMap[slug] = relatedConfig.fieldName\n }\n\n hierarchyCollection.hooks = hierarchyCollection.hooks || {}\n hierarchyCollection.hooks.afterDelete = [\n ...(hierarchyCollection.hooks.afterDelete || []),\n hierarchyCollectionAfterDelete({ relatedCollections: relatedCollectionFieldMap }),\n ]\n}\n\n/**\n * Injects a sidebar tab for a hierarchy collection.\n */\nfunction injectSidebarTab({\n config,\n hierarchyCollection,\n hierarchyConfig,\n}: {\n config: Config\n hierarchyCollection: CollectionConfig\n hierarchyConfig: SanitizedHierarchyConfig\n}): void {\n const tabSlug = `hierarchy-${hierarchyCollection.slug}`\n const Icon = hierarchyConfig.admin.components.Icon\n\n // Initialize admin config structure\n config.admin = config.admin || {}\n config.admin.components = config.admin.components || {}\n config.admin.components.sidebar = config.admin.components.sidebar || {}\n config.admin.components.sidebar.tabs = config.admin.components.sidebar.tabs || []\n\n // Check if tab already exists\n const hasTab = config.admin.components.sidebar.tabs.some((tab) => tab.slug === tabSlug)\n\n if (!hasTab) {\n config.admin.components.sidebar.tabs.push({\n slug: tabSlug,\n components: {\n Content: {\n clientProps: {\n hierarchyCollectionSlug: hierarchyCollection.slug,\n },\n path: '@payloadcms/ui/rsc#HierarchySidebarTabServer',\n },\n Icon,\n },\n label: hierarchyCollection.labels?.plural || hierarchyCollection.slug,\n })\n }\n}\n"],"names":["sanitizeJoinField","fieldAffectsData","extractID","flattenAllFields","getHierarchyFieldName","hierarchyCollectionAfterDelete","injectHierarchyButton","resolveHierarchyCollections","config","hierarchyCollections","collections","filter","col","hierarchy","hierarchyCollection","hierarchyConfig","defaultFieldName","slug","parentFieldName","isParentFieldNameOverridden","collectionSpecific","typeFieldName","fieldName","undefined","allowHasMany","sanitizedRelatedCollections","selfParentField","fields","find","field","name","type","relationTo","custom","injectHeaderButton","collection","hierarchyCollectionSlug","hierarchyField","fieldHasMany","hasMany","injectCollectionSpecificValidation","hierarchySlug","injectTypeField","joinField","injectJoinField","joinFieldConfig","relatedSlugs","Object","keys","relatedCollections","length","injectAfterDeleteHook","admin","injectSidebarTab","group","existingValidate","validate","value","options","existingResult","validateCollectionSpecificHierarchy","Array","isArray","collectionSlug","overrideAccess","previousValue","req","newIDs","map","item","previousIDs","Set","newID","has","parentItem","payload","findByID","id","depth","select","allowedTypes","includes","collectionOptions","relatedCollection","c","label","labels","plural","typeField","components","Field","path","serverProps","position","t","existingTypeFieldIndex","findIndex","push","flattenedFields","userAdmin","userConfig","hasJoinField","some","on","joins","parentIsLocalized","polymorphicJoins","relatedCollectionFieldMap","relatedConfig","entries","hooks","afterDelete","tabSlug","Icon","sidebar","tabs","hasTab","tab","Content","clientProps"],"mappings":"AAgBA,SAASA,iBAAiB,QAAQ,wCAAuC;AACzE,SAASC,gBAAgB,QAAQ,4BAA2B;AAC5D,SAASC,SAAS,QAAQ,4BAA2B;AACrD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,qBAAqB,QAAQ,iBAAgB;AACtD,SAASC,8BAA8B,QAAQ,mCAAkC;AACjF,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,MAAMC,8BAA8B,CAACC;IAC1C,MAAMC,uBACJD,OAAOE,WAAW,EAAEC,OAAO,CAACC,MAAQA,IAAIC,SAAS,IAAI,OAAOD,IAAIC,SAAS,KAAK,aAAa,EAAE;IAE/F,KAAK,MAAMC,uBAAuBL,qBAAsB;QACtD,MAAMI,YAAYC,oBAAoBD,SAAS;QAE/C,iFAAiF;QACjF,IAAI,CAACA,aAAa,OAAOA,cAAc,UAAU;YAC/C;QACF;QAEA,MAAME,kBAAkBF;QACxB,MAAMG,mBAAmBZ,sBAAsBU,oBAAoBG,IAAI;QACvE,MAAMC,kBAAkBH,gBAAgBG,eAAe,IAAIF;QAC3D,MAAMG,8BAA8BD,oBAAoBF;QACxD,MAAMI,qBAAqBL,gBAAgBK,kBAAkB;QAC7D,MAAMC,gBAAgBD,qBAAqBA,mBAAmBE,SAAS,GAAGC;QAC1E,MAAMC,eAAeT,gBAAgBS,YAAY,IAAI;QAErD,4EA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E,MAAM;gBACR;gBACAsB;YACF;YACA5B,OAAOvE,oBAAoBwE,MAAM,EAAEC,UAAUzE,oBAAoBG,IAAI;QACvE;IACF;AACF"}
@@ -2285,6 +2285,10 @@ type MigrationTemplateArgs = {
2285
2285
  type GenerateSchemaArgs = {
2286
2286
  log?: boolean;
2287
2287
  outputFile?: string;
2288
+ /**
2289
+ * Format the generated schema with the project's oxfmt, falling back to Prettier.
2290
+ * @default true
2291
+ */
2288
2292
  prettify?: boolean;
2289
2293
  };
2290
2294
  type GenerateSchema = (args?: GenerateSchemaArgs) => Promise<{
@@ -2465,7 +2469,8 @@ type GlobalAdminOptions = {
2465
2469
  * Specify a navigational group for globals in the admin sidebar.
2466
2470
  * - Provide a string to place the entity in a custom group.
2467
2471
  * - Provide a record to define localized group names.
2468
- * - Set to `false` to exclude the entity from the sidebar / dashboard without disabling its routes.
2472
+ * - Set to `false` to exclude the global from the sidebar, command palette, and dashboard collection cards.
2473
+ * This does not disable routes or change access control.
2469
2474
  */
2470
2475
  group?: false | Record<string, string> | string;
2471
2476
  /**
@@ -10108,7 +10113,10 @@ type CollectionAdminOptions = {
10108
10113
  * Specify a navigational group for collections in the admin sidebar.
10109
10114
  * - Provide a string to place the entity in a custom group.
10110
10115
  * - Provide a record to define localized group names.
10111
- * - Set to `false` to exclude the entity from the sidebar / dashboard without disabling its routes.
10116
+ * - Set to `false` to exclude the collection from the sidebar, command palette, dashboard collection cards,
10117
+ * and pin picker, and its documents from both the Pinned and Recently viewed dashboard tabs, including existing pins.
10118
+ * This does not disable routes or change access control or rich text link and relationship eligibility.
10119
+ * Use `enableRichTextLink` and `enableRichTextRelationship` to configure rich text eligibility separately.
10112
10120
  */
10113
10121
  group?: false | Record<string, string> | string;
10114
10122
  /**
@@ -14742,6 +14750,7 @@ type Args$a = {
14742
14750
  * Data of the nearest parent block. If no parent block exists, this will be the `undefined`
14743
14751
  */
14744
14752
  blockData?: JsonObject;
14753
+ blockFields?: Field[];
14745
14754
  collection: null | SanitizedCollectionConfig;
14746
14755
  context: RequestContext;
14747
14756
  data: JsonObject;
@@ -14796,7 +14805,7 @@ type Args$a = {
14796
14805
  * - Transform data for storage
14797
14806
  * - Unflatten locales. The input `data` is the normal document for one locale. The output result will become the document with locales.
14798
14807
  */
14799
- declare const traverseFields$2: ({ id, blockData, collection, context, data, doc, docWithLocales, errors, fieldLabelPath, fields, global, isValidationOperation, mergeLocaleActions, operation, overrideAccess, parentIndexPath, parentIsLocalized, parentPath, parentSchemaPath, req, siblingData, siblingDoc, siblingDocWithLocales, skipHooks, skipValidation, submittedTopLevelFieldNames, }: Args$a) => Promise<void>;
14808
+ declare const traverseFields$2: ({ id, blockData, blockFields, collection, context, data, doc, docWithLocales, errors, fieldLabelPath, fields, global, isValidationOperation, mergeLocaleActions, operation, overrideAccess, parentIndexPath, parentIsLocalized, parentPath, parentSchemaPath, req, siblingData, siblingDoc, siblingDocWithLocales, skipHooks, skipValidation, submittedTopLevelFieldNames, }: Args$a) => Promise<void>;
14800
14809
 
14801
14810
  type Args$9<T> = {
14802
14811
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"getInstructionsCollection.d.ts","sourceRoot":"","sources":["../../src/llm-instructions/getInstructionsCollection.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AACtE,OAAO,KAAK,EAAU,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAajE,eAAO,MAAM,yBAAyB,gBAEnC;IACD,MAAM,EAAE,eAAe,CAAA;CACxB,KAAG,gBA6TH,CAAA"}
1
+ {"version":3,"file":"getInstructionsCollection.d.ts","sourceRoot":"","sources":["../../src/llm-instructions/getInstructionsCollection.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AACtE,OAAO,KAAK,EAAU,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAajE,eAAO,MAAM,yBAAyB,gBAEnC;IACD,MAAM,EAAE,eAAe,CAAA;CACxB,KAAG,gBA+TH,CAAA"}
@@ -75,6 +75,8 @@ export const getInstructionsCollection = ({ config })=>{
75
75
  'entityType',
76
76
  'additionalInstructions'
77
77
  ],
78
+ enableRichTextLink: false,
79
+ enableRichTextRelationship: false,
78
80
  group: false,
79
81
  listSearchableFields: [
80
82
  'entitySlug'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/llm-instructions/getInstructionsCollection.ts"],"sourcesContent":["import { getTranslation } from '@payloadcms/translations'\n\nimport type { CollectionConfig } from '../collections/config/types.js'\nimport type { Access, SanitizedConfig } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { InstructionTargetFields } from './shared.js'\n\nimport { getDataLoader } from '../collections/dataloader.js'\nimport { ValidationError } from '../errors/ValidationError.js'\nimport { getSelectMode } from '../utilities/getSelectMode.js'\nimport { isolateObjectProperty } from '../utilities/isolateObjectProperty.js'\nimport { getInstructionTargetAccess } from './getInstructionTargetAccess.js'\nimport { instructionsCollectionSlug } from './shared.js'\n\nconst syncContextKey = 'syncLLMInstructions'\n\nexport const getInstructionsCollection = ({\n config,\n}: {\n config: SanitizedConfig\n}): CollectionConfig => {\n const targets = [\n ...config.collections\n .filter(({ slug, admin }) => admin.hidden !== true && slug !== instructionsCollectionSlug)\n .map(({ slug, llmInstructions }) => ({\n slug,\n type: 'collection' as const,\n systemInstructions: llmInstructions,\n })),\n ...config.globals\n .filter(({ admin }) => admin.hidden !== true)\n .map(({ slug, llmInstructions }) => ({\n slug,\n type: 'global' as const,\n systemInstructions: llmInstructions,\n })),\n ]\n const options = config.llmInstructions === false ? undefined : config.llmInstructions\n const editorProvider = options?.editor ?? config.editor?.presets?.llmInstructions\n const configuredEditor = editorProvider?.({ config, isRoot: false, parentIsLocalized: false })\n const editor =\n configuredEditor?.converters?.fromMarkdown && configuredEditor.converters.toMarkdown\n ? configuredEditor\n : undefined\n const getTarget = ({ entitySlug, entityType }: InstructionTargetFields = {}) =>\n targets.find((target) => target.slug === entitySlug && target.type === entityType)\n const getTitle = ({ data, req }: { data?: InstructionTargetFields; req: PayloadRequest }) => {\n const target = getTarget(data)\n\n if (!target) {\n return ''\n }\n\n const label =\n target.type === 'collection'\n ? req.payload.collections[target.slug]?.config.labels.plural\n : req.payload.config.globals.find((global) => global.slug === target.slug)?.label\n\n return getTranslation(label || target.slug, req.i18n)\n }\n const canManage: Access =\n options?.access ||\n (({ req }: { req: PayloadRequest }) =>\n Boolean(req.user && req.user.collection === req.payload.config.admin.user))\n\n return {\n slug: instructionsCollectionSlug,\n access: {\n create: ({ req }) => req.context[syncContextKey] === true,\n delete: () => false,\n read: ({ req }) =>\n req.context[syncContextKey] === true ||\n getInstructionTargetAccess({ operation: 'read', req, targets }),\n update: async (args) => {\n const manageAccess = await canManage(args)\n\n if (!manageAccess) {\n return false\n }\n\n const targetAccess = await getInstructionTargetAccess({\n operation: 'update',\n req: args.req,\n targets,\n })\n\n if (!targetAccess) {\n return false\n }\n\n return manageAccess === true ? targetAccess : { and: [manageAccess, targetAccess] }\n },\n },\n admin: {\n defaultColumns: ['title', 'updatedAt', 'entityType', 'additionalInstructions'],\n group: false,\n listSearchableFields: ['entitySlug'],\n useAsTitle: 'entitySlug',\n },\n disableBulkEdit: true,\n disableDuplicate: true,\n fields: [\n {\n name: 'id',\n type: 'text',\n admin: { hidden: true },\n },\n {\n name: 'entitySlug',\n type: 'text',\n admin: { hidden: true },\n index: true,\n required: true,\n },\n {\n name: 'title',\n type: 'text',\n admin: { hidden: true },\n hooks: {\n afterRead: [({ data, req }) => getTitle({ data, req })],\n },\n label: ({ t }) => t('llmInstructions:title'),\n virtual: true,\n },\n {\n name: 'entityType',\n type: 'select',\n admin: { hidden: true },\n label: ({ t }) => t('version:type'),\n options: [\n { label: ({ t }) => t('general:collection'), value: 'collection' },\n { label: ({ t }) => t('llmInstructions:global'), value: 'global' },\n ],\n required: true,\n },\n {\n type: 'tabs',\n admin: { className: 'llm-instructions' },\n tabs: [\n {\n fields: [\n {\n name: 'additionalInstructionsDescription',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/ui#LLMInstructionsDescription',\n },\n },\n },\n {\n name: 'additionalInstructions',\n ...(editor ? { type: 'richText' as const, editor } : { type: 'textarea' as const }),\n admin: {\n className: 'llm-instructions__editor',\n components: { Cell: '@payloadcms/ui/rsc#LLMInstructionsCell' },\n },\n label: ({ t }) => t('llmInstructions:additionalInstructions'),\n },\n ],\n label: ({ t }) => t('llmInstructions:additionalInstructions'),\n },\n {\n fields: [\n {\n name: 'systemInstructionsDescription',\n type: 'ui',\n admin: {\n components: {\n Field: {\n clientProps: { isSystem: true },\n path: '@payloadcms/ui#LLMInstructionsDescription',\n },\n },\n },\n },\n {\n name: 'systemInstructions',\n ...(editor ? { type: 'richText' as const, editor } : { type: 'textarea' as const }),\n access: { create: () => false, update: () => false },\n admin: {\n className: 'llm-instructions__editor llm-instructions__editor--system',\n readOnly: true,\n },\n hooks: {\n afterRead: [\n ({ data }) => {\n const markdown = getTarget(data)?.systemInstructions\n\n return markdown\n ? (editor?.converters?.fromMarkdown?.({ markdown }) ?? markdown)\n : null\n },\n ],\n },\n label: ({ t }) => t('llmInstructions:systemInstructions'),\n virtual: true,\n },\n ],\n label: ({ t }) => t('llmInstructions:systemInstructions'),\n },\n ],\n },\n ],\n hooks: {\n beforeOperation: [\n async ({ args, operation, req }) => {\n if (operation !== 'read' || req.context[syncContextKey] || !req.user) {\n return args\n }\n\n // Only configuration-owned identities are created here. Client requests cannot set context.\n const syncReq = isolateObjectProperty(req, [\n 'context',\n 'payloadDataLoader',\n 'transactionID',\n ])\n\n syncReq.context = { ...req.context, [syncContextKey]: true }\n // Initialization must persist even if the caller rolls back its transaction.\n delete syncReq.transactionID\n syncReq.payloadDataLoader = getDataLoader(syncReq)\n\n const { docs } = await req.payload.find({\n collection: instructionsCollectionSlug,\n depth: 0,\n limit: 0,\n overrideAccess: false,\n pagination: false,\n req: syncReq,\n select: { id: true },\n })\n const existingIDs = new Set(docs.map(({ id }) => id))\n\n for (const target of targets) {\n const id = `${target.type}-${target.slug}`\n\n if (existingIDs.has(id)) {\n continue\n }\n\n try {\n await req.payload.create({\n collection: instructionsCollectionSlug,\n data: { id, entitySlug: target.slug, entityType: target.type },\n disableTransaction: true,\n overrideAccess: false,\n req: syncReq,\n user: req.user,\n })\n } catch (error) {\n // The unique ID allows only one concurrent request to create this entry.\n const existingDoc = await req.payload.findByID({\n id,\n collection: instructionsCollectionSlug,\n depth: 0,\n disableErrors: true,\n overrideAccess: false,\n req: syncReq,\n select: { id: true },\n })\n\n if (!existingDoc) {\n throw error\n }\n }\n }\n\n return args\n },\n ],\n beforeValidate: [\n ({ data, operation, originalDoc, req }) => {\n const { entitySlug, entityType } = { ...originalDoc, ...data }\n\n if (!entitySlug || !entityType) {\n return data\n }\n\n if (!getTarget({ entitySlug, entityType })) {\n throw new ValidationError({\n collection: instructionsCollectionSlug,\n errors: [\n {\n message: req.t('validation:invalidInput'),\n path:\n entityType === 'collection' || entityType === 'global'\n ? 'entitySlug'\n : 'entityType',\n },\n ],\n req,\n })\n }\n\n const id = `${entityType}-${entitySlug}`\n\n if (operation === 'update' && originalDoc?.id !== id) {\n throw new ValidationError({\n collection: instructionsCollectionSlug,\n errors: [\n {\n message: req.t('llmInstructions:targetCannotBeChanged'),\n path: originalDoc?.entityType !== entityType ? 'entityType' : 'entitySlug',\n },\n ],\n req,\n })\n }\n\n return { ...data, id }\n },\n ],\n },\n labels: {\n plural: ({ t }) => t('llmInstructions:instructions'),\n singular: ({ t }) => t('llmInstructions:instructions'),\n },\n lockDocuments: false,\n select: ({ select }) => {\n if (!select) {\n return\n }\n\n if (getSelectMode(select) === 'include') {\n return { ...select, entitySlug: true, entityType: true }\n }\n\n const targetSelect = { ...select }\n\n delete targetSelect.entitySlug\n delete targetSelect.entityType\n\n return targetSelect\n },\n versions: false,\n }\n}\n"],"names":["getTranslation","getDataLoader","ValidationError","getSelectMode","isolateObjectProperty","getInstructionTargetAccess","instructionsCollectionSlug","syncContextKey","getInstructionsCollection","config","targets","collections","filter","slug","admin","hidden","map","llmInstructions","type","systemInstructions","globals","options","undefined","editorProvider","editor","presets","configuredEditor","isRoot","parentIsLocalized","converters","fromMarkdown","toMarkdown","getTarget","entitySlug","entityType","find","target","getTitle","data","req","label","payload","labels","plural","global","i18n","canManage","access","Boolean","user","collection","create","context","delete","read","operation","update","args","manageAccess","targetAccess","and","defaultColumns","group","listSearchableFields","useAsTitle","disableBulkEdit","disableDuplicate","fields","name","index","required","hooks","afterRead","t","virtual","value","className","tabs","components","Field","Cell","clientProps","isSystem","path","readOnly","markdown","beforeOperation","syncReq","transactionID","payloadDataLoader","docs","depth","limit","overrideAccess","pagination","select","id","existingIDs","Set","has","disableTransaction","error","existingDoc","findByID","disableErrors","beforeValidate","originalDoc","errors","message","singular","lockDocuments","targetSelect","versions"],"mappings":"AAAA,SAASA,cAAc,QAAQ,2BAA0B;AAOzD,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAe,QAAQ,+BAA8B;AAC9D,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,0BAA0B,QAAQ,kCAAiC;AAC5E,SAASC,0BAA0B,QAAQ,cAAa;AAExD,MAAMC,iBAAiB;AAEvB,OAAO,MAAMC,4BAA4B,CAAC,EACxCC,MAAM,EAGP;IACC,MAAMC,UAAU;WACXD,OAAOE,WAAW,CAClBC,MAAM,CAAC,CAAC,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAKA,MAAMC,MAAM,KAAK,QAAQF,SAASP,4BAC9DU,GAAG,CAAC,CAAC,EAAEH,IAAI,EAAEI,eAAe,EAAE,GAAM,CAAA;gBACnCJ;gBACAK,MAAM;gBACNC,oBAAoBF;YACtB,CAAA;WACCR,OAAOW,OAAO,CACdR,MAAM,CAAC,CAAC,EAAEE,KAAK,EAAE,GAAKA,MAAMC,MAAM,KAAK,MACvCC,GAAG,C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AI;wBACpD,MAAM,IAAI9F,gBAAgB;4BACxBgD,YAAY5C;4BACZqG,QAAQ;gCACN;oCACEC,SAASrE,IAAIkC,CAAC,CAAC;oCACfU,MAAMuB,aAAaxE,eAAeA,aAAa,eAAe;gCAChE;6BACD;4BACDK;wBACF;oBACF;oBAEA,OAAO;wBAAE,GAAGD,IAAI;wBAAE0D;oBAAG;gBACvB;aACD;QACH;QACAtD,QAAQ;YACNC,QAAQ,CAAC,EAAE8B,CAAC,EAAE,GAAKA,EAAE;YACrBoC,UAAU,CAAC,EAAEpC,CAAC,EAAE,GAAKA,EAAE;QACzB;QACAqC,eAAe;QACff,QAAQ,CAAC,EAAEA,MAAM,EAAE;YACjB,IAAI,CAACA,QAAQ;gBACX;YACF;YAEA,IAAI5F,cAAc4F,YAAY,WAAW;gBACvC,OAAO;oBAAE,GAAGA,MAAM;oBAAE9D,YAAY;oBAAMC,YAAY;gBAAK;YACzD;YAEA,MAAM6E,eAAe;gBAAE,GAAGhB,MAAM;YAAC;YAEjC,OAAOgB,aAAa9E,UAAU;YAC9B,OAAO8E,aAAa7E,UAAU;YAE9B,OAAO6E;QACT;QACAC,UAAU;IACZ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/llm-instructions/getInstructionsCollection.ts"],"sourcesContent":["import { getTranslation } from '@payloadcms/translations'\n\nimport type { CollectionConfig } from '../collections/config/types.js'\nimport type { Access, SanitizedConfig } from '../config/types.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { InstructionTargetFields } from './shared.js'\n\nimport { getDataLoader } from '../collections/dataloader.js'\nimport { ValidationError } from '../errors/ValidationError.js'\nimport { getSelectMode } from '../utilities/getSelectMode.js'\nimport { isolateObjectProperty } from '../utilities/isolateObjectProperty.js'\nimport { getInstructionTargetAccess } from './getInstructionTargetAccess.js'\nimport { instructionsCollectionSlug } from './shared.js'\n\nconst syncContextKey = 'syncLLMInstructions'\n\nexport const getInstructionsCollection = ({\n config,\n}: {\n config: SanitizedConfig\n}): CollectionConfig => {\n const targets = [\n ...config.collections\n .filter(({ slug, admin }) => admin.hidden !== true && slug !== instructionsCollectionSlug)\n .map(({ slug, llmInstructions }) => ({\n slug,\n type: 'collection' as const,\n systemInstructions: llmInstructions,\n })),\n ...config.globals\n .filter(({ admin }) => admin.hidden !== true)\n .map(({ slug, llmInstructions }) => ({\n slug,\n type: 'global' as const,\n systemInstructions: llmInstructions,\n })),\n ]\n const options = config.llmInstructions === false ? undefined : config.llmInstructions\n const editorProvider = options?.editor ?? config.editor?.presets?.llmInstructions\n const configuredEditor = editorProvider?.({ config, isRoot: false, parentIsLocalized: false })\n const editor =\n configuredEditor?.converters?.fromMarkdown && configuredEditor.converters.toMarkdown\n ? configuredEditor\n : undefined\n const getTarget = ({ entitySlug, entityType }: InstructionTargetFields = {}) =>\n targets.find((target) => target.slug === entitySlug && target.type === entityType)\n const getTitle = ({ data, req }: { data?: InstructionTargetFields; req: PayloadRequest }) => {\n const target = getTarget(data)\n\n if (!target) {\n return ''\n }\n\n const label =\n target.type === 'collection'\n ? req.payload.collections[target.slug]?.config.labels.plural\n : req.payload.config.globals.find((global) => global.slug === target.slug)?.label\n\n return getTranslation(label || target.slug, req.i18n)\n }\n const canManage: Access =\n options?.access ||\n (({ req }: { req: PayloadRequest }) =>\n Boolean(req.user && req.user.collection === req.payload.config.admin.user))\n\n return {\n slug: instructionsCollectionSlug,\n access: {\n create: ({ req }) => req.context[syncContextKey] === true,\n delete: () => false,\n read: ({ req }) =>\n req.context[syncContextKey] === true ||\n getInstructionTargetAccess({ operation: 'read', req, targets }),\n update: async (args) => {\n const manageAccess = await canManage(args)\n\n if (!manageAccess) {\n return false\n }\n\n const targetAccess = await getInstructionTargetAccess({\n operation: 'update',\n req: args.req,\n targets,\n })\n\n if (!targetAccess) {\n return false\n }\n\n return manageAccess === true ? targetAccess : { and: [manageAccess, targetAccess] }\n },\n },\n admin: {\n defaultColumns: ['title', 'updatedAt', 'entityType', 'additionalInstructions'],\n enableRichTextLink: false,\n enableRichTextRelationship: false,\n group: false,\n listSearchableFields: ['entitySlug'],\n useAsTitle: 'entitySlug',\n },\n disableBulkEdit: true,\n disableDuplicate: true,\n fields: [\n {\n name: 'id',\n type: 'text',\n admin: { hidden: true },\n },\n {\n name: 'entitySlug',\n type: 'text',\n admin: { hidden: true },\n index: true,\n required: true,\n },\n {\n name: 'title',\n type: 'text',\n admin: { hidden: true },\n hooks: {\n afterRead: [({ data, req }) => getTitle({ data, req })],\n },\n label: ({ t }) => t('llmInstructions:title'),\n virtual: true,\n },\n {\n name: 'entityType',\n type: 'select',\n admin: { hidden: true },\n label: ({ t }) => t('version:type'),\n options: [\n { label: ({ t }) => t('general:collection'), value: 'collection' },\n { label: ({ t }) => t('llmInstructions:global'), value: 'global' },\n ],\n required: true,\n },\n {\n type: 'tabs',\n admin: { className: 'llm-instructions' },\n tabs: [\n {\n fields: [\n {\n name: 'additionalInstructionsDescription',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/ui#LLMInstructionsDescription',\n },\n },\n },\n {\n name: 'additionalInstructions',\n ...(editor ? { type: 'richText' as const, editor } : { type: 'textarea' as const }),\n admin: {\n className: 'llm-instructions__editor',\n components: { Cell: '@payloadcms/ui/rsc#LLMInstructionsCell' },\n },\n label: ({ t }) => t('llmInstructions:additionalInstructions'),\n },\n ],\n label: ({ t }) => t('llmInstructions:additionalInstructions'),\n },\n {\n fields: [\n {\n name: 'systemInstructionsDescription',\n type: 'ui',\n admin: {\n components: {\n Field: {\n clientProps: { isSystem: true },\n path: '@payloadcms/ui#LLMInstructionsDescription',\n },\n },\n },\n },\n {\n name: 'systemInstructions',\n ...(editor ? { type: 'richText' as const, editor } : { type: 'textarea' as const }),\n access: { create: () => false, update: () => false },\n admin: {\n className: 'llm-instructions__editor llm-instructions__editor--system',\n readOnly: true,\n },\n hooks: {\n afterRead: [\n ({ data }) => {\n const markdown = getTarget(data)?.systemInstructions\n\n return markdown\n ? (editor?.converters?.fromMarkdown?.({ markdown }) ?? markdown)\n : null\n },\n ],\n },\n label: ({ t }) => t('llmInstructions:systemInstructions'),\n virtual: true,\n },\n ],\n label: ({ t }) => t('llmInstructions:systemInstructions'),\n },\n ],\n },\n ],\n hooks: {\n beforeOperation: [\n async ({ args, operation, req }) => {\n if (operation !== 'read' || req.context[syncContextKey] || !req.user) {\n return args\n }\n\n // Only configuration-owned identities are created here. Client requests cannot set context.\n const syncReq = isolateObjectProperty(req, [\n 'context',\n 'payloadDataLoader',\n 'transactionID',\n ])\n\n syncReq.context = { ...req.context, [syncContextKey]: true }\n // Initialization must persist even if the caller rolls back its transaction.\n delete syncReq.transactionID\n syncReq.payloadDataLoader = getDataLoader(syncReq)\n\n const { docs } = await req.payload.find({\n collection: instructionsCollectionSlug,\n depth: 0,\n limit: 0,\n overrideAccess: false,\n pagination: false,\n req: syncReq,\n select: { id: true },\n })\n const existingIDs = new Set(docs.map(({ id }) => id))\n\n for (const target of targets) {\n const id = `${target.type}-${target.slug}`\n\n if (existingIDs.has(id)) {\n continue\n }\n\n try {\n await req.payload.create({\n collection: instructionsCollectionSlug,\n data: { id, entitySlug: target.slug, entityType: target.type },\n disableTransaction: true,\n overrideAccess: false,\n req: syncReq,\n user: req.user,\n })\n } catch (error) {\n // The unique ID allows only one concurrent request to create this entry.\n const existingDoc = await req.payload.findByID({\n id,\n collection: instructionsCollectionSlug,\n depth: 0,\n disableErrors: true,\n overrideAccess: false,\n req: syncReq,\n select: { id: true },\n })\n\n if (!existingDoc) {\n throw error\n }\n }\n }\n\n return args\n },\n ],\n beforeValidate: [\n ({ data, operation, originalDoc, req }) => {\n const { entitySlug, entityType } = { ...originalDoc, ...data }\n\n if (!entitySlug || !entityType) {\n return data\n }\n\n if (!getTarget({ entitySlug, entityType })) {\n throw new ValidationError({\n collection: instructionsCollectionSlug,\n errors: [\n {\n message: req.t('validation:invalidInput'),\n path:\n entityType === 'collection' || entityType === 'global'\n ? 'entitySlug'\n : 'entityType',\n },\n ],\n req,\n })\n }\n\n const id = `${entityType}-${entitySlug}`\n\n if (operation === 'update' && originalDoc?.id !== id) {\n throw new ValidationError({\n collection: instructionsCollectionSlug,\n errors: [\n {\n message: req.t('llmInstructions:targetCannotBeChanged'),\n path: originalDoc?.entityType !== entityType ? 'entityType' : 'entitySlug',\n },\n ],\n req,\n })\n }\n\n return { ...data, id }\n },\n ],\n },\n labels: {\n plural: ({ t }) => t('llmInstructions:instructions'),\n singular: ({ t }) => t('llmInstructions:instructions'),\n },\n lockDocuments: false,\n select: ({ select }) => {\n if (!select) {\n return\n }\n\n if (getSelectMode(select) === 'include') {\n return { ...select, entitySlug: true, entityType: true }\n }\n\n const targetSelect = { ...select }\n\n delete targetSelect.entitySlug\n delete targetSelect.entityType\n\n return targetSelect\n },\n versions: false,\n }\n}\n"],"names":["getTranslation","getDataLoader","ValidationError","getSelectMode","isolateObjectProperty","getInstructionTargetAccess","instructionsCollectionSlug","syncContextKey","getInstructionsCollection","config","targets","collections","filter","slug","admin","hidden","map","llmInstructions","type","systemInstructions","globals","options","undefined","editorProvider","editor","presets","configuredEditor","isRoot","parentIsLocalized","converters","fromMarkdown","toMarkdown","getTarget","entitySlug","entityType","find","target","getTitle","data","req","label","payload","labels","plural","global","i18n","canManage","access","Boolean","user","collection","create","context","delete","read","operation","update","args","manageAccess","targetAccess","and","defaultColumns","enableRichTextLink","enableRichTextRelationship","group","listSearchableFields","useAsTitle","disableBulkEdit","disableDuplicate","fields","name","index","required","hooks","afterRead","t","virtual","value","className","tabs","components","Field","Cell","clientProps","isSystem","path","readOnly","markdown","beforeOperation","syncReq","transactionID","payloadDataLoader","docs","depth","limit","overrideAccess","pagination","select","id","existingIDs","Set","has","disableTransaction","error","existingDoc","findByID","disableErrors","beforeValidate","originalDoc","errors","message","singular","lockDocuments","targetSelect","versions"],"mappings":"AAAA,SAASA,cAAc,QAAQ,2BAA0B;AAOzD,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAe,QAAQ,+BAA8B;AAC9D,SAASC,aAAa,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;AAEnE,MAAM,MAAM,oBAAoB,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,IAAI,OAAO,CAC9D,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CACrC,GACC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtC,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { OptionalKeys, RequiredKeys } from 'ts-essentials'\nimport type { URL } from 'url'\n\nimport type { ServerAdapter } from '../admin/adapters/server.js'\nimport type {\n DataFromCollectionSlug,\n QueryDraftDataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n AuthenticatedUser,\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n Payload,\n RequestContext,\n TypedCollectionJoins,\n TypedCollectionSelect,\n TypedFallbackLocale,\n TypedLocale,\n} from '../index.js'\nimport type { File } from '../uploads/types.js'\nimport type { HasManyRelationshipOperator, Operator } from './constants.js'\nexport type { TypeWithID } from '../collections/config/types.js'\nexport type { Payload } from '../index.js'\n\nexport interface PayloadRequestAPI {\n GraphQL: true\n local: true\n REST: true\n}\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: TypedFallbackLocale\n /**\n * Set by Payload only while running a collection's `read` access function for a\n * dynamic file transformation request. Restored to its prior value immediately\n * after that access check completes; never set for ordinary reads.\n */\n fileTransform?: true\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n *\n * Suppressing warning below as it is a valid use case - won't be an issue if generated types exist\n */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n locale?: 'all' | TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: keyof PayloadRequestAPI\n /** Optimized document loader */\n payloadDataLoader: {\n /**\n * Wraps `payload.find` with a cache to deduplicate requests\n * @experimental This is may be replaced by a more robust cache strategy in future versions\n * By calling this method with the same arguments many times in one request, it will only be handled one time\n * const result = await req.payloadDataLoader.find({\n * collection,\n * req,\n * where: findWhere,\n * })\n */\n find: Payload['find']\n } & DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /**\n * Framework abstraction for server-only navigation, cookies, and headers APIs.\n * Populated by the framework adapter (e.g. `@payloadcms/next`). Plugins that\n * have access to `req` should call methods here (`req.server.unauthorized()`,\n * `req.server.redirect(...)`) instead of importing from `next/navigation` or\n * `next/headers` directly. Optional because non-framework contexts (jobs,\n * scripts, tests) construct requests without a server adapter.\n */\n server?: ServerAdapter\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /** The signed-in user */\n user: AuthenticatedUser | null\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from 'payload'\n * `await addDataAndFileToRequest(req)`\n *\n * You should not expect this object to be the document data. It is the request data.\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n uploadReference?: unknown\n } & File\n /** All files from multipart form data, keyed by field name */\n files?: Record<string, File | File[]>\n}\nexport interface PayloadRequest\n extends CustomPayloadRequestProperties,\n Partial<Request>,\n PayloadRequestData {\n headers: Request['headers']\n /** The active Payload operation. */\n operation?: Operation\n}\n\nexport type { HasManyRelationshipOperator, Operator }\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value, including a nested query for supported relationship operators\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n and?: Where[]\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\ntype SerializableValue = boolean | number | object | string\nexport type DefaultValue =\n | ((args: {\n locale?: TypedLocale\n req: PayloadRequest\n user: PayloadRequest['user']\n }) => Promise<SerializableValue> | SerializableValue)\n | SerializableValue\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery<TSlug extends CollectionSlug = string> =\n TypedCollectionJoins[TSlug] extends Record<string, string>\n ?\n | false\n | Partial<{\n [K in keyof TypedCollectionJoins[TSlug]]:\n | {\n count?: boolean\n limit?: number\n page?: number\n sort?: string\n where?: Where\n }\n | false\n }>\n : never\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\n/**\n * Operations exposed to access control and request lifecycle functions.\n *\n * On-demand validation uses the first-class `validate` value rather than substituting `create`\n * or `update`.\n */\nexport type Operation = 'create' | 'delete' | 'read' | 'update' | 'validate'\nexport type FieldOperation = Exclude<Operation, 'delete'>\nexport type BeforeValidateOperation = Extract<FieldOperation, 'create' | 'update' | 'validate'>\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\n/**\n * Operations that invoke an entity-level `select` function.\n *\n * Narrower than `HookOperationType`: `select` runs only for read- and\n * write-path operations that materialize a document (`create`, `delete`,\n * `read`, `restoreVersion`, `update`). Operations like `autosave`, `count`,\n * `countVersions`, `forgotPassword`, `login`, `readDistinct`, `refresh`, and\n * `resetPassword` do not invoke `select` and are intentionally excluded.\n */\nexport type SelectFnOperation = 'create' | 'delete' | 'read' | 'restoreVersion' | 'update'\n\nexport type SelectFnArgs = {\n operation: SelectFnOperation\n req: PayloadRequest\n /** The caller's `select` arg, or `undefined` if not provided. */\n select?: SelectType\n}\n\nexport type SelectFn<TSelect extends SelectType = SelectType> = (\n args: SelectFnArgs,\n) => TSelect | undefined\n\n/**\n * Shared shape for the entity-level `select` config used by Collections and Globals.\n * The JSDoc on the `select` property is the single source of truth — pick from this\n * type when defining the config:\n *\n * & Pick<WithSelectFn<...>, 'select'>\n */\nexport type WithSelectFn<TSelect extends SelectType = SelectType> = {\n /**\n * Entity-level Select API configuration.\n *\n * A function that receives the current request context (`operation`, `req`,\n * the caller's `select`) and returns the final `select` to apply, replacing\n * the caller's. Return `undefined` to leave the caller's `select` unchanged.\n *\n * Useful to dynamically modify the caller's selection based on the request context:\n * - Forcing a field to be populated for reference within hooks / access control.\n * - Differentiating between API requests and admin panel requests, to optimize\n * the amount of data being queried in each case.\n *\n * Note: per-document data is not available — this runs before the read.\n *\n * @see https://payloadcms.com/docs/queries/select\n */\n select?: SelectFn<TSelect>\n}\n\nexport type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors\n ? T\n : null | T\n\nexport type TransformDataWithSelect<\n Data extends Record<string, any>,\n Select extends SelectType,\n> = Select extends never\n ? Data\n : string extends keyof Select\n ? Data\n : // START Handle types when they aren't generated\n // For example in any package in this repository outside of tests / plugins\n // This stil gives us autocomplete when using include select mode, i.e select: {title :true} returns type {title: any, id: string | number}\n string extends keyof Omit<Data, 'id'>\n ? Select extends SelectIncludeType\n ? {\n [K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id'\n ? number | string\n : unknown\n }\n : Data\n : // END Handle types when they aren't generated\n // Handle include mode\n Select extends SelectIncludeType\n ? {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | true\n ? K\n : never\n : // select 'id' always\n K extends 'id'\n ? K\n : never]: Data[K]\n }\n : // Handle exclude mode\n {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | undefined\n ? K\n : never\n : K]: Data[K]\n }\n\nexport type TransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromCollectionSlug<TSlug>, TSelect>\n : DataFromCollectionSlug<TSlug>\n\nexport type DraftTransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<QueryDraftDataFromCollectionSlug<TSlug>, TSelect>\n : QueryDraftDataFromCollectionSlug<TSlug>\n\nexport type TransformGlobalWithSelect<\n TSlug extends GlobalSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromGlobalSlug<TSlug>, TSelect>\n : DataFromGlobalSlug<TSlug>\n\nexport type PopulateType = Partial<TypedCollectionSelect>\n\nexport type { SharedLocalAPIOptions } from './operations.js'\n\nexport type ResolvedFilterOptions = { [collection: string]: Where }\n\nexport type PickPreserveOptional<T, K extends keyof T> = Partial<\n Pick<T, Extract<K, OptionalKeys<T>>>\n> &\n Pick<T, Extract<K, RequiredKeys<T>>>\n\nexport type MaybePromise<T> = Promise<T> | T\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"mappings":"AAqNA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
1
+ {"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { OptionalKeys, RequiredKeys } from 'ts-essentials'\nimport type { URL } from 'url'\n\nimport type { ServerAdapter } from '../admin/adapters/server.js'\nimport type {\n DataFromCollectionSlug,\n QueryDraftDataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n AuthenticatedUser,\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n Payload,\n RequestContext,\n TypedCollectionJoins,\n TypedCollectionSelect,\n TypedFallbackLocale,\n TypedLocale,\n} from '../index.js'\nimport type { File } from '../uploads/types.js'\nimport type { HasManyRelationshipOperator, Operator } from './constants.js'\nexport type { TypeWithID } from '../collections/config/types.js'\nexport type { Payload } from '../index.js'\n\nexport interface PayloadRequestAPI {\n GraphQL: true\n local: true\n REST: true\n}\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: TypedFallbackLocale\n /**\n * Set by Payload only while running a collection's `read` access function for a\n * dynamic file transformation request. Restored to its prior value immediately\n * after that access check completes; never set for ordinary reads.\n */\n fileTransform?: true\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n *\n * Suppressing warning below as it is a valid use case - won't be an issue if generated types exist\n */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n locale?: 'all' | TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: keyof PayloadRequestAPI\n /** Optimized document loader */\n payloadDataLoader: {\n /**\n * Wraps `payload.find` with a cache to deduplicate requests\n * @experimental This is may be replaced by a more robust cache strategy in future versions\n * By calling this method with the same arguments many times in one request, it will only be handled one time\n * const result = await req.payloadDataLoader.find({\n * collection,\n * req,\n * where: findWhere,\n * })\n */\n find: Payload['find']\n } & DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /**\n * Framework abstraction for server-only navigation, cookies, and headers APIs.\n * Populated by the framework adapter (e.g. `@payloadcms/next`). Plugins that\n * have access to `req` should call methods here (`req.server.unauthorized()`,\n * `req.server.redirect(...)`) instead of importing from `next/navigation` or\n * `next/headers` directly. Optional because non-framework contexts (jobs,\n * scripts, tests) construct requests without a server adapter.\n */\n server?: ServerAdapter\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /** The signed-in user */\n user: AuthenticatedUser | null\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from 'payload'\n * `await addDataAndFileToRequest(req)`\n *\n * You should not expect this object to be the document data. It is the request data.\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n uploadReference?: unknown\n } & File\n /** All files from multipart form data, keyed by field name */\n files?: Record<string, File | File[]>\n}\nexport interface PayloadRequest\n extends CustomPayloadRequestProperties, Partial<Request>, PayloadRequestData {\n headers: Request['headers']\n /** The active Payload operation. */\n operation?: Operation\n}\n\nexport type { HasManyRelationshipOperator, Operator }\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value, including a nested query for supported relationship operators\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n and?: Where[]\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\ntype SerializableValue = boolean | number | object | string\nexport type DefaultValue =\n | ((args: {\n locale?: TypedLocale\n req: PayloadRequest\n user: PayloadRequest['user']\n }) => Promise<SerializableValue> | SerializableValue)\n | SerializableValue\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery<TSlug extends CollectionSlug = string> =\n TypedCollectionJoins[TSlug] extends Record<string, string>\n ?\n | false\n | Partial<{\n [K in keyof TypedCollectionJoins[TSlug]]:\n | {\n count?: boolean\n limit?: number\n page?: number\n sort?: string\n where?: Where\n }\n | false\n }>\n : never\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\n/**\n * Operations exposed to access control and request lifecycle functions.\n *\n * On-demand validation uses the first-class `validate` value rather than substituting `create`\n * or `update`.\n */\nexport type Operation = 'create' | 'delete' | 'read' | 'update' | 'validate'\nexport type FieldOperation = Exclude<Operation, 'delete'>\nexport type BeforeValidateOperation = Extract<FieldOperation, 'create' | 'update' | 'validate'>\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\n/**\n * Operations that invoke an entity-level `select` function.\n *\n * Narrower than `HookOperationType`: `select` runs only for read- and\n * write-path operations that materialize a document (`create`, `delete`,\n * `read`, `restoreVersion`, `update`). Operations like `autosave`, `count`,\n * `countVersions`, `forgotPassword`, `login`, `readDistinct`, `refresh`, and\n * `resetPassword` do not invoke `select` and are intentionally excluded.\n */\nexport type SelectFnOperation = 'create' | 'delete' | 'read' | 'restoreVersion' | 'update'\n\nexport type SelectFnArgs = {\n operation: SelectFnOperation\n req: PayloadRequest\n /** The caller's `select` arg, or `undefined` if not provided. */\n select?: SelectType\n}\n\nexport type SelectFn<TSelect extends SelectType = SelectType> = (\n args: SelectFnArgs,\n) => TSelect | undefined\n\n/**\n * Shared shape for the entity-level `select` config used by Collections and Globals.\n * The JSDoc on the `select` property is the single source of truth — pick from this\n * type when defining the config:\n *\n * & Pick<WithSelectFn<...>, 'select'>\n */\nexport type WithSelectFn<TSelect extends SelectType = SelectType> = {\n /**\n * Entity-level Select API configuration.\n *\n * A function that receives the current request context (`operation`, `req`,\n * the caller's `select`) and returns the final `select` to apply, replacing\n * the caller's. Return `undefined` to leave the caller's `select` unchanged.\n *\n * Useful to dynamically modify the caller's selection based on the request context:\n * - Forcing a field to be populated for reference within hooks / access control.\n * - Differentiating between API requests and admin panel requests, to optimize\n * the amount of data being queried in each case.\n *\n * Note: per-document data is not available — this runs before the read.\n *\n * @see https://payloadcms.com/docs/queries/select\n */\n select?: SelectFn<TSelect>\n}\n\nexport type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors\n ? T\n : null | T\n\nexport type TransformDataWithSelect<\n Data extends Record<string, any>,\n Select extends SelectType,\n> = Select extends never\n ? Data\n : string extends keyof Select\n ? Data\n : // START Handle types when they aren't generated\n // For example in any package in this repository outside of tests / plugins\n // This stil gives us autocomplete when using include select mode, i.e select: {title :true} returns type {title: any, id: string | number}\n string extends keyof Omit<Data, 'id'>\n ? Select extends SelectIncludeType\n ? {\n [K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id'\n ? number | string\n : unknown\n }\n : Data\n : // END Handle types when they aren't generated\n // Handle include mode\n Select extends SelectIncludeType\n ? {\n [\n K in keyof Data as K extends keyof Select\n ? Select[K] extends object | true\n ? K\n : never\n : // select 'id' always\n K extends 'id'\n ? K\n : never\n ]: Data[K]\n }\n : // Handle exclude mode\n {\n [\n K in keyof Data as K extends keyof Select\n ? Select[K] extends object | undefined\n ? K\n : never\n : K\n ]: Data[K]\n }\n\nexport type TransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromCollectionSlug<TSlug>, TSelect>\n : DataFromCollectionSlug<TSlug>\n\nexport type DraftTransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<QueryDraftDataFromCollectionSlug<TSlug>, TSelect>\n : QueryDraftDataFromCollectionSlug<TSlug>\n\nexport type TransformGlobalWithSelect<\n TSlug extends GlobalSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromGlobalSlug<TSlug>, TSelect>\n : DataFromGlobalSlug<TSlug>\n\nexport type PopulateType = Partial<TypedCollectionSelect>\n\nexport type { SharedLocalAPIOptions } from './operations.js'\n\nexport type ResolvedFilterOptions = { [collection: string]: Where }\n\nexport type PickPreserveOptional<T, K extends keyof T> = Partial<\n Pick<T, Extract<K, OptionalKeys<T>>>\n> &\n Pick<T, Extract<K, RequiredKeys<T>>>\n\nexport type MaybePromise<T> = Promise<T> | T\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"mappings":"AAmNA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/uploads/fileVersioning/cloudStorage.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport {\n collectStoredFiles as collectSavedFiles,\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from './cleanup.js'\nimport { runFileCreationPlan, runFileOperationPlan } from './fileOperationManager.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyCloudUploadFileData,\n} from './storedFiles.js'\n\n/** Preserve the caller's cloud flags; nested Local API calls can replace req.context. */\nexport const captureCloudHookState = ({ req }: { req: PayloadRequest }): (() => void) => {\n const previousState = ['_payloadManagedCloudStorage', '_payloadManagedCloudMetadata'].map(\n (key) => ({\n hasProperty: Object.hasOwn(req.context ?? {}, key),\n key,\n value: req.context?.[key],\n }),\n )\n\n return () => {\n req.context ??= {}\n for (const { hasProperty, key, value } of previousState) {\n if (hasProperty) {\n req.context[key] = value\n } else {\n delete req.context[key]\n }\n }\n }\n}\n\nexport const runCloudFileCreation = async <T>({\n collection,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n files: FileToSave[]\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileCreationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n // Create's version and afterChange hooks run after the database insert. The\n // outer create operation restores the previous guard after those hooks finish.\n write: () => {\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n return write()\n },\n })\n}\n\nexport const runCloudFileUpdate = async <T>({\n id,\n collection,\n current,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n data: JsonObject\n files: FileToSave[]\n id: number | string\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n const storedCurrent = operations\n ? await withLegacyCloudUploadFileData({ collection, doc: current, req })\n : current\n const nextFiles = collectStoredFiles({\n collection,\n doc: { ...storedCurrent, ...data },\n req,\n trustGenerated: true,\n })\n const currentFiles = collectStoredFiles({ collection, doc: storedCurrent, req })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n const hasStoredFileChange =\n nextIdentities.size !== currentFiles.length ||\n currentFiles.some((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal && !hasStoredFileChange)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n if (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal) {\n return\n }\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n write: async () => {\n if (\n collection.versions &&\n !hasStoredOriginal({ doc: current }) &&\n hasStoredOriginal({ doc: storedCurrent })\n ) {\n await persistLegacyCloudVersions({ id, collection, current: storedCurrent, req })\n }\n\n const result = await withCloudHookGuard({\n metadata,\n req,\n write,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: await collectSavedFiles({ collection, doc: storedCurrent, req }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Track a verified client-uploaded source, retaining it if another document still references it. */\nconst trackClientUploadOriginal = ({\n collection,\n data,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): void => {\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { key: string }\n | undefined\n\n if (!verifiedOriginal) {\n return\n }\n\n const original = collectStoredFiles({ collection, doc: data, req, trustGenerated: true }).find(\n ({ key, roles }) =>\n key === verifiedOriginal.key && roles.some((role) => role.type === 'original'),\n )\n\n if (!original) {\n return\n }\n\n const object: StagedObject = {\n key: original.key,\n remove: () => collection.upload.fileOperations!.delete({ key: original.key, req }),\n }\n\n trackStagedObject({\n key: object.key,\n remove: () => removeUnreferencedStagedObjects({ collection, objects: [object], req }),\n })\n}\n\nconst persistLegacyCloudVersions = async ({\n id,\n collection,\n current,\n req,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n req: PayloadRequest\n}): Promise<void> => {\n let page = 1\n let hasVersions = false\n\n while (true) {\n const versions = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 100,\n page,\n req,\n where: { parent: { equals: id } },\n })\n\n for (const row of versions.docs) {\n hasVersions = true\n if (hasStoredOriginal({ doc: row.version })) {\n continue\n }\n\n const version = await withLegacyCloudUploadFileData({\n collection,\n doc: row.version,\n req,\n })\n if (!hasStoredOriginal({ doc: version })) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n\n if (versions.docs.length < 100) {\n break\n }\n page += 1\n }\n\n if (!hasVersions && hasStoredOriginal({ doc: current })) {\n await saveVersion({\n id,\n collection,\n docWithLocales: current,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n}\n\nconst hasStoredOriginal = ({ doc }: { doc: JsonObject }): boolean =>\n Boolean(\n doc.original &&\n typeof doc.original === 'object' &&\n typeof (doc.original as Record<string, unknown>).filename === 'string',\n )\n\nconst withCloudHookGuard = async <T>({\n metadata,\n req,\n write,\n}: {\n metadata: Record<string, unknown>\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const restoreCloudHookState = captureCloudHookState({ req })\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n\n try {\n return await write()\n } finally {\n restoreCloudHookState()\n }\n}\n"],"names":["saveVersion","collectStoredFiles","collectSavedFiles","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileCreationPlan","runFileOperationPlan","getStoredFileIdentity","withLegacyCloudUploadFileData","captureCloudHookState","req","previousState","map","key","hasProperty","Object","hasOwn","context","value","runCloudFileCreation","collection","data","files","write","operations","upload","fileOperations","skipCloudStorage","length","_payloadVerifiedProviderOriginal","metadata","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","trackClientUploadOriginal","staged","assign","_payloadManagedCloudStorage","_payloadManagedCloudMetadata","runCloudFileUpdate","id","current","storedCurrent","doc","nextFiles","trustGenerated","currentFiles","nextIdentities","Set","hasStoredFileChange","size","some","file","has","versions","hasStoredOriginal","persistLegacyCloudVersions","result","withCloudHookGuard","candidates","verifiedOriginal","original","find","roles","role","type","object","remove","delete","page","hasVersions","payload","db","findVersions","slug","limit","where","parent","equals","row","docs","version","updateVersion","versionData","createdAt","latest","publishedLocale","updatedAt","docWithLocales","draft","operation","Boolean","filename","restoreCloudHookState"],"mappings":"AAKA,SAASA,WAAW,QAAQ,gCAA+B;AAC3D,SACEC,sBAAsBC,iBAAiB,EACvCC,+BAA+B,EAC/BC,+BAA+B,QAC1B,eAAc;AACrB,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,4BAA2B;AACrF,SACEL,kBAAkB,EAClBM,qBAAqB,EACrBC,6BAA6B,QACxB,mBAAkB;AAEzB,uFAAuF,GACvF,OAAO,MAAMC,wBAAwB,CAAC,EAAEC,GAAG,EAA2B;IACpE,MAAMC,gBAAgB;QAAC;QAA+B;KAA+B,CAACC,GAAG,CACvF,CAACC,MAAS,CAAA;YACRC,aAAaC,OAAOC,MAAM,CAACN,IAAIO,OAAO,IAAI,CAAC,GAAGJ;YAC9CA;YACAK,OAAOR,IAAIO,OAAO,EAAE,CAACJ,IAAI;QAC3B,CAAA;IAGF,OAAO;QACLH,IAAIO,OAAO,KAAK,CAAC;QACjB,KAAK,MAAM,EAAEH,WAAW,EAAED,GAAG,EAAEK,KAAK,EAAE,IAAIP,cAAe;YACvD,IAAIG,aAAa;gBACfJ,IAAIO,OAAO,CAACJ,IAAI,GAAGK;YACrB,OAAO;gBACL,OAAOR,IAAIO,OAAO,CAACJ,IAAI;YACzB;QACF;IACF;AACF,EAAC;AAED,OAAO,MAAMM,uBAAuB,OAAU,EAC5CC,UAAU,EACVC,IAAI,EACJC,KAAK,EACLZ,GAAG,EACHa,KAAK,EA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P;IACf,SAAU;QACRuE;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/uploads/fileVersioning/cloudStorage.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport {\n collectStoredFiles as collectSavedFiles,\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from './cleanup.js'\nimport { runFileCreationPlan, runFileOperationPlan } from './fileOperationManager.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyCloudUploadFileData,\n} from './storedFiles.js'\n\n/** Preserve the caller's cloud flags; nested Local API calls can replace req.context. */\nexport const captureCloudHookState = ({ req }: { req: PayloadRequest }): (() => void) => {\n const previousState = ['_payloadManagedCloudStorage', '_payloadManagedCloudMetadata'].map(\n (key) => ({\n hasProperty: Object.hasOwn(req.context ?? {}, key),\n key,\n value: req.context?.[key],\n }),\n )\n\n return () => {\n req.context ??= {}\n for (const { hasProperty, key, value } of previousState) {\n if (hasProperty) {\n req.context[key] = value\n } else {\n delete req.context[key]\n }\n }\n }\n}\n\nexport const runCloudFileCreation = async <T>({\n collection,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n files: FileToSave[]\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileCreationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n // Create's version and afterChange hooks run after the database insert. The\n // outer create operation restores the previous guard after those hooks finish.\n write: () => {\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n return write()\n },\n })\n}\n\nexport const runCloudFileUpdate = async <T>({\n id,\n collection,\n current,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n data: JsonObject\n files: FileToSave[]\n id: number | string\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n const storedCurrent = operations\n ? await withLegacyCloudUploadFileData({ collection, doc: current, req })\n : current\n const nextFiles = collectStoredFiles({\n collection,\n doc: { ...storedCurrent, ...data },\n req,\n trustGenerated: true,\n })\n const currentFiles = collectStoredFiles({ collection, doc: storedCurrent, req })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n const hasStoredFileChange =\n nextIdentities.size !== currentFiles.length ||\n currentFiles.some((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal && !hasStoredFileChange)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n if (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal) {\n return\n }\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n write: async () => {\n if (\n collection.versions &&\n !hasStoredOriginal({ doc: current }) &&\n hasStoredOriginal({ doc: storedCurrent })\n ) {\n await persistLegacyCloudVersions({ id, collection, current: storedCurrent, req })\n }\n\n const result = await withCloudHookGuard({\n metadata,\n req,\n write,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: await collectSavedFiles({ collection, doc: storedCurrent, req }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Track a verified client-uploaded source, retaining it if another document still references it. */\nconst trackClientUploadOriginal = ({\n collection,\n data,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): void => {\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { key: string }\n | undefined\n\n if (!verifiedOriginal) {\n return\n }\n\n const original = collectStoredFiles({ collection, doc: data, req, trustGenerated: true }).find(\n ({ key, roles }) =>\n key === verifiedOriginal.key && roles.some((role) => role.type === 'original'),\n )\n\n if (!original) {\n return\n }\n\n const object: StagedObject = {\n key: original.key,\n remove: () => collection.upload.fileOperations!.delete({ key: original.key, req }),\n }\n\n trackStagedObject({\n key: object.key,\n remove: () => removeUnreferencedStagedObjects({ collection, objects: [object], req }),\n })\n}\n\nconst persistLegacyCloudVersions = async ({\n id,\n collection,\n current,\n req,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n req: PayloadRequest\n}): Promise<void> => {\n let page = 1\n let hasVersions = false\n\n while (true) {\n const versions = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 100,\n page,\n req,\n where: { parent: { equals: id } },\n })\n\n for (const row of versions.docs) {\n hasVersions = true\n if (hasStoredOriginal({ doc: row.version })) {\n continue\n }\n\n const version = await withLegacyCloudUploadFileData({\n collection,\n doc: row.version,\n req,\n })\n if (!hasStoredOriginal({ doc: version })) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n\n if (versions.docs.length < 100) {\n break\n }\n page += 1\n }\n\n if (!hasVersions && hasStoredOriginal({ doc: current })) {\n await saveVersion({\n id,\n collection,\n docWithLocales: current,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n}\n\nconst hasStoredOriginal = ({ doc }: { doc: JsonObject }): boolean =>\n Boolean(\n doc.original &&\n typeof doc.original === 'object' &&\n typeof (doc.original as Record<string, unknown>).filename === 'string',\n )\n\nconst withCloudHookGuard = async <T>({\n metadata,\n req,\n write,\n}: {\n metadata: Record<string, unknown>\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const restoreCloudHookState = captureCloudHookState({ req })\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n\n try {\n return await write()\n } finally {\n restoreCloudHookState()\n }\n}\n"],"names":["saveVersion","collectStoredFiles","collectSavedFiles","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileCreationPlan","runFileOperationPlan","getStoredFileIdentity","withLegacyCloudUploadFileData","captureCloudHookState","req","previousState","map","key","hasProperty","Object","hasOwn","context","value","runCloudFileCreation","collection","data","files","write","operations","upload","fileOperations","skipCloudStorage","length","_payloadVerifiedProviderOriginal","metadata","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","trackClientUploadOriginal","staged","assign","_payloadManagedCloudStorage","_payloadManagedCloudMetadata","runCloudFileUpdate","id","current","storedCurrent","doc","nextFiles","trustGenerated","currentFiles","nextIdentities","Set","hasStoredFileChange","size","some","file","has","versions","hasStoredOriginal","persistLegacyCloudVersions","result","withCloudHookGuard","candidates","verifiedOriginal","original","find","roles","role","type","object","remove","delete","page","hasVersions","payload","db","findVersions","slug","limit","where","parent","equals","row","docs","version","updateVersion","versionData","createdAt","latest","publishedLocale","updatedAt","docWithLocales","draft","operation","Boolean","filename","restoreCloudHookState"],"mappings":"AAKA,SAASA,WAAW,QAAQ,gCAA+B;AAC3D,SACEC,sBAAsBC,iBAAiB,EACvCC,+BAA+B,EAC/BC,+BAA+B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WAAWR,IAAIQ,SAAS;oBACxBN;gBACF;YACF;QACF;QAEA,IAAI3B,SAAS0B,IAAI,CAACrD,MAAM,GAAG,KAAK;YAC9B;QACF;QACA0C,QAAQ;IACV;IAEA,IAAI,CAACC,eAAef,kBAAkB;QAAEZ,KAAKF;IAAQ,IAAI;QACvD,MAAM1C,YAAY;YAChByC;YACArB;YACAqE,gBAAgB/C;YAChBgD,OAAO;YACPC,WAAW;YACXnB,SAAS9D,IAAI8D,OAAO;YACpB9D;QACF;IACF;AACF;AAEA,MAAM8C,oBAAoB,CAAC,EAAEZ,GAAG,EAAuB,GACrDgD,QACEhD,IAAIkB,QAAQ,IACZ,OAAOlB,IAAIkB,QAAQ,KAAK,YACxB,OAAO,AAAClB,IAAIkB,QAAQ,CAA6B+B,QAAQ,KAAK;AAGlE,MAAMlC,qBAAqB,OAAU,EACnC7B,QAAQ,EACRpB,GAAG,EACHa,KAAK,EAKN;IACC,MAAMuE,wBAAwBrF,sBAAsB;QAAEC;IAAI;IAC1DA,IAAIO,OAAO,KAAK,CAAC;IACjBP,IAAIO,OAAO,CAACqB,2BAA2B,GAAG;IAC1C5B,IAAIO,OAAO,CAACsB,4BAA4B,GAAGT;IAE3C,IAAI;QACF,OAAO,MAAMP;IACf,SAAU;QACRuE;IACF;AACF"}
@@ -1,4 +1,4 @@
1
- export function formatFilesize(bytes, decimals = 0) {
1
+ export function formatFilesize(bytes, decimals = 1) {
2
2
  if (bytes === 0) {
3
3
  return '0 bytes';
4
4
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/formatFilesize.ts"],"sourcesContent":["export function formatFilesize(bytes: number, decimals = 0): string {\n if (bytes === 0) {\n return '0 bytes'\n }\n\n const k = 1024\n const dm = decimals < 0 ? 0 : decimals\n const sizes = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n\n return `${parseFloat((bytes / k ** i).toFixed(dm))}${sizes[i]}`\n}\n"],"names":["formatFilesize","bytes","decimals","k","dm","sizes","i","Math","floor","log","parseFloat","toFixed"],"mappings":"AAAA,OAAO,SAASA,eAAeC,KAAa,EAAEC,WAAW,CAAC;IACxD,IAAID,UAAU,GAAG;QACf,OAAO;IACT;IAEA,MAAME,IAAI;IACV,MAAMC,KAAKF,WAAW,IAAI,IAAIA;IAC9B,MAAMG,QAAQ;QAAC;QAAU;QAAM;QAAM;QAAM;QAAM;QAAM;QAAM;QAAM;KAAK;IAExE,MAAMC,IAAIC,KAAKC,KAAK,CAACD,KAAKE,GAAG,CAACR,SAASM,KAAKE,GAAG,CAACN;IAEhD,OAAO,GAAGO,WAAW,AAACT,CAAAA,QAAQE,KAAKG,CAAAA,EAAGK,OAAO,CAACP,OAAOC,KAAK,CAACC,EAAE,EAAE;AACjE"}
1
+ {"version":3,"sources":["../../src/uploads/formatFilesize.ts"],"sourcesContent":["export function formatFilesize(bytes: number, decimals = 1): string {\n if (bytes === 0) {\n return '0 bytes'\n }\n\n const k = 1024\n const dm = decimals < 0 ? 0 : decimals\n const sizes = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n\n return `${parseFloat((bytes / k ** i).toFixed(dm))}${sizes[i]}`\n}\n"],"names":["formatFilesize","bytes","decimals","k","dm","sizes","i","Math","floor","log","parseFloat","toFixed"],"mappings":"AAAA,OAAO,SAASA,eAAeC,KAAa,EAAEC,WAAW,CAAC;IACxD,IAAID,UAAU,GAAG;QACf,OAAO;IACT;IAEA,MAAME,IAAI;IACV,MAAMC,KAAKF,WAAW,IAAI,IAAIA;IAC9B,MAAMG,QAAQ;QAAC;QAAU;QAAM;QAAM;QAAM;QAAM;QAAM;QAAM;QAAM;KAAK;IAExE,MAAMC,IAAIC,KAAKC,KAAK,CAACD,KAAKE,GAAG,CAACR,SAASM,KAAKE,GAAG,CAACN;IAEhD,OAAO,GAAGO,WAAW,AAACT,CAAAA,QAAQE,KAAKG,CAAAA,EAAGK,OAAO,CAACP,OAAOC,KAAK,CAACC,EAAE,EAAE;AACjE"}