@payloadcms/plugin-import-export 4.0.0-internal.5b1e7cd → 4.0.0-internal.5e065b3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/CollectionField/index.d.ts +3 -2
- package/dist/components/CollectionField/index.d.ts.map +1 -1
- package/dist/components/CollectionField/index.js.map +1 -1
- package/dist/components/ExportListMenuItem/index.d.ts.map +1 -1
- package/dist/components/ExportListMenuItem/index.js +14 -12
- package/dist/components/ExportListMenuItem/index.js.map +1 -1
- package/dist/components/ExportPreview/index.css +52 -0
- package/dist/components/ExportPreview/index.d.ts +1 -1
- package/dist/components/ExportPreview/index.d.ts.map +1 -1
- package/dist/components/ExportPreview/index.js +12 -2
- package/dist/components/ExportPreview/index.js.map +1 -1
- package/dist/components/FieldsToExport/index.d.ts +3 -2
- package/dist/components/FieldsToExport/index.d.ts.map +1 -1
- package/dist/components/FieldsToExport/index.js +18 -15
- package/dist/components/FieldsToExport/index.js.map +1 -1
- package/dist/components/FieldsToExport/reduceFields.d.ts +6 -0
- package/dist/components/FieldsToExport/reduceFields.d.ts.map +1 -1
- package/dist/components/FieldsToExport/reduceFields.js +4 -0
- package/dist/components/FieldsToExport/reduceFields.js.map +1 -1
- package/dist/components/FormatField/index.d.ts +3 -2
- package/dist/components/FormatField/index.d.ts.map +1 -1
- package/dist/components/FormatField/index.js +6 -3
- package/dist/components/FormatField/index.js.map +1 -1
- package/dist/components/ImportListMenuItem/index.d.ts.map +1 -1
- package/dist/components/ImportListMenuItem/index.js +14 -12
- package/dist/components/ImportListMenuItem/index.js.map +1 -1
- package/dist/components/ImportPreview/index.css +45 -0
- package/dist/components/ImportPreview/index.d.ts +1 -1
- package/dist/components/ImportPreview/index.d.ts.map +1 -1
- package/dist/components/ImportPreview/index.js +44 -11
- package/dist/components/ImportPreview/index.js.map +1 -1
- package/dist/components/LimitField/index.d.ts +3 -2
- package/dist/components/LimitField/index.d.ts.map +1 -1
- package/dist/components/LimitField/index.js.map +1 -1
- package/dist/components/LocaleField/index.d.ts +3 -2
- package/dist/components/LocaleField/index.d.ts.map +1 -1
- package/dist/components/LocaleField/index.js.map +1 -1
- package/dist/components/Page/index.d.ts +4 -3
- package/dist/components/Page/index.d.ts.map +1 -1
- package/dist/components/Page/index.js +1 -1
- package/dist/components/Page/index.js.map +1 -1
- package/dist/components/RelationshipCell/getRelationshipGroupKey.d.ts +7 -0
- package/dist/components/RelationshipCell/getRelationshipGroupKey.d.ts.map +1 -0
- package/dist/components/RelationshipCell/getRelationshipGroupKey.js +3 -0
- package/dist/components/RelationshipCell/getRelationshipGroupKey.js.map +1 -0
- package/dist/components/RelationshipCell/getRelationshipGroups.d.ts +43 -0
- package/dist/components/RelationshipCell/getRelationshipGroups.d.ts.map +1 -0
- package/dist/components/RelationshipCell/getRelationshipGroups.js +109 -0
- package/dist/components/RelationshipCell/getRelationshipGroups.js.map +1 -0
- package/dist/components/RelationshipCell/index.css +30 -0
- package/dist/components/RelationshipCell/index.d.ts +15 -0
- package/dist/components/RelationshipCell/index.d.ts.map +1 -0
- package/dist/components/RelationshipCell/index.js +57 -0
- package/dist/components/RelationshipCell/index.js.map +1 -0
- package/dist/components/SortBy/index.css +9 -0
- package/dist/components/SortBy/index.d.ts +4 -3
- package/dist/components/SortBy/index.d.ts.map +1 -1
- package/dist/components/SortBy/index.js +1 -2
- package/dist/components/SortBy/index.js.map +1 -1
- package/dist/components/SortOrder/index.css +9 -0
- package/dist/components/SortOrder/index.d.ts +4 -3
- package/dist/components/SortOrder/index.d.ts.map +1 -1
- package/dist/components/SortOrder/index.js +1 -2
- package/dist/components/SortOrder/index.js.map +1 -1
- package/dist/export/batchProcessor.d.ts +12 -3
- package/dist/export/batchProcessor.d.ts.map +1 -1
- package/dist/export/batchProcessor.js +61 -15
- package/dist/export/batchProcessor.js.map +1 -1
- package/dist/export/createExport.d.ts +4 -2
- package/dist/export/createExport.d.ts.map +1 -1
- package/dist/export/createExport.js +105 -22
- package/dist/export/createExport.js.map +1 -1
- package/dist/export/getCreateExportCollectionTask.d.ts.map +1 -1
- package/dist/export/getCreateExportCollectionTask.js +11 -0
- package/dist/export/getCreateExportCollectionTask.js.map +1 -1
- package/dist/export/getExportCollection.d.ts.map +1 -1
- package/dist/export/getExportCollection.js +9 -4
- package/dist/export/getExportCollection.js.map +1 -1
- package/dist/export/handleDownload.d.ts.map +1 -1
- package/dist/export/handleDownload.js +7 -3
- package/dist/export/handleDownload.js.map +1 -1
- package/dist/export/handlePreview.d.ts.map +1 -1
- package/dist/export/handlePreview.js +60 -16
- package/dist/export/handlePreview.js.map +1 -1
- package/dist/exports/types.d.ts +1 -1
- package/dist/exports/types.d.ts.map +1 -1
- package/dist/exports/types.js.map +1 -1
- package/dist/import/batchProcessor.d.ts +17 -4
- package/dist/import/batchProcessor.d.ts.map +1 -1
- package/dist/import/batchProcessor.js +63 -34
- package/dist/import/batchProcessor.js.map +1 -1
- package/dist/import/createImport.d.ts +3 -11
- package/dist/import/createImport.d.ts.map +1 -1
- package/dist/import/createImport.js +42 -54
- package/dist/import/createImport.js.map +1 -1
- package/dist/import/getCreateImportCollectionTask.d.ts.map +1 -1
- package/dist/import/getCreateImportCollectionTask.js +5 -2
- package/dist/import/getCreateImportCollectionTask.js.map +1 -1
- package/dist/import/getImportCollection.d.ts.map +1 -1
- package/dist/import/getImportCollection.js +6 -4
- package/dist/import/getImportCollection.js.map +1 -1
- package/dist/import/handlePreview.d.ts.map +1 -1
- package/dist/import/handlePreview.js +37 -7
- package/dist/import/handlePreview.js.map +1 -1
- package/dist/index.d.ts +51 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -8
- package/dist/index.js.map +1 -1
- package/dist/translations/languages/en.d.ts.map +1 -1
- package/dist/types.d.ts +205 -42
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utilities/applyFieldHooks.d.ts +22 -0
- package/dist/utilities/applyFieldHooks.d.ts.map +1 -0
- package/dist/utilities/applyFieldHooks.js +117 -0
- package/dist/utilities/applyFieldHooks.js.map +1 -0
- package/dist/utilities/collectDisabledFieldPaths.d.ts.map +1 -1
- package/dist/utilities/collectDisabledFieldPaths.js +1 -1
- package/dist/utilities/collectDisabledFieldPaths.js.map +1 -1
- package/dist/utilities/flattenObject.d.ts +8 -6
- package/dist/utilities/flattenObject.d.ts.map +1 -1
- package/dist/utilities/flattenObject.js +85 -75
- package/dist/utilities/flattenObject.js.map +1 -1
- package/dist/utilities/flattenedFields.d.ts +21 -0
- package/dist/utilities/flattenedFields.d.ts.map +1 -0
- package/dist/utilities/flattenedFields.js +37 -0
- package/dist/utilities/flattenedFields.js.map +1 -0
- package/dist/utilities/getExportFieldFunctions.d.ts +5 -5
- package/dist/utilities/getExportFieldFunctions.d.ts.map +1 -1
- package/dist/utilities/getExportFieldFunctions.js +122 -99
- package/dist/utilities/getExportFieldFunctions.js.map +1 -1
- package/dist/utilities/getFileFromDoc.js +3 -3
- package/dist/utilities/getFileFromDoc.js.map +1 -1
- package/dist/utilities/getImportFieldFunctions.d.ts +5 -5
- package/dist/utilities/getImportFieldFunctions.d.ts.map +1 -1
- package/dist/utilities/getImportFieldFunctions.js +95 -103
- package/dist/utilities/getImportFieldFunctions.js.map +1 -1
- package/dist/utilities/getSchemaColumns.d.ts +1 -1
- package/dist/utilities/getSchemaColumns.js +2 -2
- package/dist/utilities/getSchemaColumns.js.map +1 -1
- package/dist/utilities/getSelect.d.ts.map +1 -1
- package/dist/utilities/getSelect.js +11 -3
- package/dist/utilities/getSelect.js.map +1 -1
- package/dist/utilities/getSubmittedFormValues.d.ts +12 -0
- package/dist/utilities/getSubmittedFormValues.d.ts.map +1 -0
- package/dist/utilities/getSubmittedFormValues.js +24 -0
- package/dist/utilities/getSubmittedFormValues.js.map +1 -0
- package/dist/utilities/isPlainObject.d.ts +2 -0
- package/dist/utilities/isPlainObject.d.ts.map +1 -0
- package/dist/utilities/isPlainObject.js +3 -0
- package/dist/utilities/isPlainObject.js.map +1 -0
- package/dist/utilities/polymorphicRel.d.ts +14 -0
- package/dist/utilities/polymorphicRel.d.ts.map +1 -0
- package/dist/utilities/polymorphicRel.js +17 -0
- package/dist/utilities/polymorphicRel.js.map +1 -0
- package/dist/utilities/processRichTextField.d.ts.map +1 -1
- package/dist/utilities/processRichTextField.js +7 -0
- package/dist/utilities/processRichTextField.js.map +1 -1
- package/dist/utilities/removeDisabledFields.js.map +1 -1
- package/dist/utilities/setNestedValue.d.ts +2 -1
- package/dist/utilities/setNestedValue.d.ts.map +1 -1
- package/dist/utilities/setNestedValue.js +65 -32
- package/dist/utilities/setNestedValue.js.map +1 -1
- package/dist/utilities/sortHelpers.d.ts +1 -1
- package/dist/utilities/unflattenObject.d.ts +4 -3
- package/dist/utilities/unflattenObject.d.ts.map +1 -1
- package/dist/utilities/unflattenObject.js +69 -170
- package/dist/utilities/unflattenObject.js.map +1 -1
- package/dist/utilities/unflattenPostProcess.d.ts +11 -0
- package/dist/utilities/unflattenPostProcess.d.ts.map +1 -0
- package/dist/utilities/unflattenPostProcess.js +174 -0
- package/dist/utilities/unflattenPostProcess.js.map +1 -0
- package/license.md +1 -1
- package/package.json +9 -9
- package/dist/components/ExportPreview/index.scss +0 -48
- package/dist/components/FieldsToExport/index.scss +0 -0
- package/dist/components/FieldsToExport/reduceFields.spec.js +0 -239
- package/dist/components/FieldsToExport/reduceFields.spec.js.map +0 -1
- package/dist/components/ImportPreview/index.scss +0 -41
- package/dist/components/SortBy/index.scss +0 -3
- package/dist/components/SortOrder/index.scss +0 -3
- package/dist/utilities/buildDisabledFieldRegex.spec.js +0 -64
- package/dist/utilities/buildDisabledFieldRegex.spec.js.map +0 -1
- package/dist/utilities/fieldToRegex.spec.js +0 -151
- package/dist/utilities/fieldToRegex.spec.js.map +0 -1
- package/dist/utilities/filterToSelectedFields.spec.js +0 -204
- package/dist/utilities/filterToSelectedFields.spec.js.map +0 -1
- package/dist/utilities/getSchemaColumns.spec.js +0 -157
- package/dist/utilities/getSchemaColumns.spec.js.map +0 -1
- package/dist/utilities/parseCSV.spec.js +0 -195
- package/dist/utilities/parseCSV.spec.js.map +0 -1
- package/dist/utilities/unflattenObject.spec.js +0 -680
- package/dist/utilities/unflattenObject.spec.js.map +0 -1
- /package/dist/components/Page/{index.scss → index.css} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/import/getImportCollection.ts"],"sourcesContent":["import type { CollectionAfterChangeHook, CollectionConfig } from 'payload'\n\nimport { FileRetrievalError } from 'payload'\n\nimport type { ImportConfig, ImportExportPluginConfig } from '../types.js'\nimport type { ImportTaskInput } from './getCreateImportCollectionTask.js'\n\nimport { getFileFromDoc } from '../utilities/getFileFromDoc.js'\nimport { resolveLimit } from '../utilities/resolveLimit.js'\nimport { createImport } from './createImport.js'\nimport { getFields } from './getFields.js'\nimport { handlePreview } from './handlePreview.js'\n\nconst FALLBACK_BATCH_SIZE = 100\nconst FALLBACK_VERSION_STATUS = 'published'\n\nexport const getImportCollection = ({\n collectionSlugs,\n importConfig,\n pluginConfig,\n}: {\n /**\n * Collection slugs that this import collection supports.\n */\n collectionSlugs: string[]\n importConfig?: ImportConfig\n pluginConfig: ImportExportPluginConfig\n}): CollectionConfig => {\n const afterChange: CollectionAfterChangeHook[] = []\n\n const collection: CollectionConfig = {\n slug: 'imports',\n access: {\n update: () => false,\n },\n admin: {\n components: {\n edit: {\n SaveButton: '@payloadcms/plugin-import-export/rsc#ImportSaveButton',\n },\n },\n custom: {\n 'plugin-import-export': {\n collectionSlugs,\n },\n },\n disableCopyToLocale: true,\n group: false,\n useAsTitle: 'filename',\n },\n disableDuplicate: true,\n endpoints: [\n {\n handler: handlePreview,\n method: 'post',\n path: '/preview-data',\n },\n ],\n fields: getFields({ collectionSlugs }),\n hooks: {\n afterChange,\n },\n lockDocuments: false,\n upload: {\n filesRequiredOnCreate: true,\n hideFileInputOnCreate: false,\n hideRemoveFile: true,\n mimeTypes: ['text/csv', 'application/json'],\n },\n }\n\n afterChange.push(async ({ collection: collectionConfig, doc, operation, req }) => {\n if (operation !== 'create' || doc.status !== 'pending') {\n return doc\n }\n\n const targetCollection = req.payload.collections[doc.collectionSlug]\n const targetPluginConfig = targetCollection?.config.custom?.['plugin-import-export']\n\n const disableJobsQueue =\n targetPluginConfig?.importDisableJobsQueue ?? importConfig?.disableJobsQueue ?? false\n\n const debug = pluginConfig.debug || false\n\n if (debug) {\n req.payload.logger.info({\n collectionSlug: doc.collectionSlug,\n disableJobsQueue,\n docId: doc.id,\n msg: '[Import Sync Hook] Starting',\n transactionID: req.transactionID,\n })\n }\n\n if (!disableJobsQueue) {\n return doc\n }\n\n try {\n // Get file data from the uploaded document\n // First try req.file which is available during the same request (especially important for cloud storage)\n // Fall back to getFileFromDoc for cases where req.file isn't available\n let fileData: Buffer\n let fileMimetype: string\n\n if (req.file?.data) {\n fileData = req.file.data\n fileMimetype = req.file.mimetype || doc.mimeType\n\n if (!fileMimetype) {\n throw new FileRetrievalError(\n req.t,\n `Unable to determine mimetype for file: ${doc.filename}`,\n )\n }\n } else {\n const fileFromDoc = await getFileFromDoc({\n collectionConfig,\n doc: {\n filename: doc.filename,\n mimeType: doc.mimeType,\n url: doc.url,\n },\n req,\n })\n fileData = fileFromDoc.data\n fileMimetype = fileFromDoc.mimetype\n }\n\n const maxLimit = await resolveLimit({\n limit: targetPluginConfig?.importLimit,\n req,\n })\n const defaultVersionStatus =\n targetPluginConfig?.defaultVersionStatus ??\n importConfig?.defaultVersionStatus ??\n pluginConfig.defaultVersionStatus ??\n FALLBACK_VERSION_STATUS\n const batchSize =\n targetPluginConfig?.importBatchSize ??\n importConfig?.batchSize ??\n pluginConfig.batchSize ??\n FALLBACK_BATCH_SIZE\n\n const result = await createImport({\n id: doc.id,\n name: doc.filename || 'import',\n batchSize,\n collectionSlug: doc.collectionSlug,\n debug,\n defaultVersionStatus,\n file: {\n name: doc.filename,\n data: fileData,\n mimetype: fileMimetype,\n },\n format: fileMimetype === 'text/csv' ? 'csv' : 'json',\n importMode: doc.importMode || 'create',\n matchField: doc.matchField,\n maxLimit,\n req,\n userCollection: req?.user?.collection || req?.user?.user?.collection,\n userID: req?.user?.id || req?.user?.user?.id,\n })\n\n // Determine status\n let status: 'completed' | 'failed' | 'partial'\n if (result.errors.length === 0) {\n status = 'completed'\n } else if (result.imported + result.updated === 0) {\n status = 'failed'\n } else {\n status = 'partial'\n }\n\n const summary = {\n imported: result.imported,\n issueDetails:\n result.errors.length > 0\n ? result.errors.map((e) => ({\n data: e.doc,\n error: e.error,\n row: e.index + 1,\n }))\n : undefined,\n issues: result.errors.length,\n total: result.total,\n updated: result.updated,\n }\n\n // Try to update the document with results\n try {\n await req.payload.update({\n id: doc.id,\n collection: collectionConfig.slug,\n data: {\n status,\n summary,\n },\n overrideAccess: true,\n req,\n })\n } catch (updateErr) {\n // Update may fail if document not yet committed\n if (debug) {\n req.payload.logger.error({\n err: updateErr,\n msg: `Failed to update import document ${doc.id} with results`,\n })\n }\n }\n\n // Return updated doc for immediate response\n return {\n ...doc,\n status,\n summary,\n }\n } catch (err) {\n const summary = {\n imported: 0,\n issueDetails: [\n {\n data: {},\n error: err instanceof Error ? err.message : String(err),\n row: 0,\n },\n ],\n issues: 1,\n total: 0,\n updated: 0,\n }\n\n if (debug) {\n req.payload.logger.error({\n docId: doc.id,\n err,\n msg: '[Import Sync Hook] Import processing failed, attempting to update status',\n transactionID: req.transactionID,\n })\n }\n\n // Try to update document with error status\n try {\n if (debug) {\n req.payload.logger.info({\n collectionSlug: collectionConfig.slug,\n docId: doc.id,\n msg: '[Import Sync Hook] About to update document with failed status',\n })\n }\n await req.payload.update({\n id: doc.id,\n collection: collectionConfig.slug,\n data: {\n status: 'failed',\n summary,\n },\n overrideAccess: true,\n req,\n })\n if (debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Sync Hook] Successfully updated document with failed status',\n })\n }\n } catch (updateErr) {\n // Update may fail if document not yet committed, log but continue\n // ALWAYS log this error to help debug Postgres issues\n req.payload.logger.error({\n err: updateErr,\n msg: `[Import Sync Hook] Failed to update import document ${doc.id} with error status`,\n transactionID: req.transactionID,\n })\n }\n\n if (debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Sync Hook] Returning failed doc',\n status: 'failed',\n })\n }\n\n // Return error status for immediate response\n return {\n ...doc,\n status: 'failed',\n summary,\n }\n }\n })\n\n afterChange.push(async ({ collection: collectionConfig, doc, operation, req }) => {\n if (operation !== 'create') {\n return\n }\n\n const targetCollection = req.payload.collections[doc.collectionSlug]\n const targetPluginConfig = targetCollection?.config.custom?.['plugin-import-export']\n\n const disableJobsQueue =\n targetPluginConfig?.importDisableJobsQueue ?? importConfig?.disableJobsQueue ?? false\n\n if (pluginConfig.debug) {\n req.payload.logger.info({\n collectionSlug: doc.collectionSlug,\n disableJobsQueue,\n docId: doc.id,\n docStatus: doc.status,\n msg: '[Import Job Hook] Checking if should queue job',\n transactionID: req.transactionID,\n })\n }\n\n if (disableJobsQueue) {\n if (pluginConfig.debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Job Hook] Skipping job queue (sync mode)',\n })\n }\n return\n }\n\n try {\n // Resolve maxLimit ahead of time since it may involve async config resolution\n const maxLimit = await resolveLimit({\n limit: targetPluginConfig?.importLimit,\n req,\n })\n const defaultVersionStatus =\n targetPluginConfig?.defaultVersionStatus ??\n importConfig?.defaultVersionStatus ??\n pluginConfig.defaultVersionStatus ??\n FALLBACK_VERSION_STATUS\n const batchSize =\n targetPluginConfig?.importBatchSize ??\n importConfig?.batchSize ??\n pluginConfig.batchSize ??\n FALLBACK_BATCH_SIZE\n\n const input: ImportTaskInput = {\n batchSize,\n debug: pluginConfig.debug,\n defaultVersionStatus,\n importCollection: collectionConfig.slug,\n importId: doc.id,\n maxLimit,\n userCollection: req.user?.collection || req?.user?.user?.collection,\n userID: req?.user?.id || req?.user?.user?.id,\n }\n\n await req.payload.jobs.queue({\n input,\n task: 'createCollectionImport',\n })\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: `Failed to queue import job for document ${doc.id}`,\n })\n }\n })\n\n return collection\n}\n"],"names":["FileRetrievalError","getFileFromDoc","resolveLimit","createImport","getFields","handlePreview","FALLBACK_BATCH_SIZE","FALLBACK_VERSION_STATUS","getImportCollection","collectionSlugs","importConfig","pluginConfig","afterChange","collection","slug","access","update","admin","components","edit","SaveButton","custom","disableCopyToLocale","group","useAsTitle","disableDuplicate","endpoints","handler","method","path","fields","hooks","lockDocuments","upload","filesRequiredOnCreate","hideFileInputOnCreate","hideRemoveFile","mimeTypes","push","collectionConfig","doc","operation","req","status","targetCollection","payload","collections","collectionSlug","targetPluginConfig","config","disableJobsQueue","importDisableJobsQueue","debug","logger","info","docId","id","msg","transactionID","fileData","fileMimetype","file","data","mimetype","mimeType","t","filename","fileFromDoc","url","maxLimit","limit","importLimit","defaultVersionStatus","batchSize","importBatchSize","result","name","format","importMode","matchField","userCollection","user","userID","errors","length","imported","updated","summary","issueDetails","map","e","error","row","index","undefined","issues","total","overrideAccess","updateErr","err","Error","message","String","docStatus","input","importCollection","importId","jobs","queue","task"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,UAAS;AAK5C,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB;AAElD,MAAMC,sBAAsB;AAC5B,MAAMC,0BAA0B;AAEhC,OAAO,MAAMC,sBAAsB,CAAC,EAClCC,eAAe,EACfC,YAAY,EACZC,YAAY,EAQb;IACC,MAAMC,cAA2C,EAAE;IAEnD,MAAMC,aAA+B;QACnCC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,YAAY;gBACVC,MAAM;oBACJC,YAAY;gBACd;YACF;YACAC,QAAQ;gBACN,wBAAwB;oBACtBZ;gBACF;YACF;YAC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;gBAC3BJ;gBACAK,MAAM;YACR;QACF,EAAE,OAAOV,KAAK;YACZzD,IAAIG,OAAO,CAACQ,MAAM,CAACsC,KAAK,CAAC;gBACvBQ;gBACA1C,KAAK,CAAC,wCAAwC,EAAEjB,IAAIgB,EAAE,EAAE;YAC1D;QACF;IACF;IAEA,OAAO3C;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/import/getImportCollection.ts"],"sourcesContent":["import type { CollectionAfterChangeHook, CollectionConfig } from 'payload'\n\nimport { FileRetrievalError } from 'payload'\n\nimport type { ImportConfig, ImportExportPluginConfig } from '../types.js'\nimport type { ImportTaskInput } from './getCreateImportCollectionTask.js'\n\nimport { getFileFromDoc } from '../utilities/getFileFromDoc.js'\nimport { resolveLimit } from '../utilities/resolveLimit.js'\nimport { createImport } from './createImport.js'\nimport { getFields } from './getFields.js'\nimport { handlePreview } from './handlePreview.js'\n\nconst FALLBACK_BATCH_SIZE = 100\nconst FALLBACK_VERSION_STATUS = 'published'\n\nexport const getImportCollection = ({\n collectionSlugs,\n importConfig,\n pluginConfig,\n}: {\n /**\n * Collection slugs that this import collection supports.\n */\n collectionSlugs: string[]\n importConfig?: ImportConfig\n pluginConfig: ImportExportPluginConfig\n}): CollectionConfig => {\n const afterChange: CollectionAfterChangeHook[] = []\n\n const collection: CollectionConfig = {\n slug: 'imports',\n access: {\n update: () => false,\n },\n admin: {\n components: {\n edit: {\n SaveButton: '@payloadcms/plugin-import-export/rsc#ImportSaveButton',\n },\n },\n custom: {\n 'plugin-import-export': {\n collectionSlugs,\n },\n },\n disableCopyToLocale: true,\n group: false,\n useAsTitle: 'filename',\n },\n disableDuplicate: true,\n endpoints: [\n {\n handler: handlePreview,\n method: 'post',\n path: '/preview-data',\n },\n ],\n fields: getFields({ collectionSlugs }),\n hooks: {\n afterChange,\n },\n lockDocuments: false,\n upload: {\n filesRequiredOnCreate: true,\n hideFileInputOnCreate: false,\n hideRemoveFile: true,\n mimeTypes: ['text/csv', 'application/json'],\n },\n }\n\n afterChange.push(async ({ collection: collectionConfig, doc, operation, req }) => {\n if (operation !== 'create' || doc.status !== 'pending') {\n return doc\n }\n\n const targetCollection = req.payload.collections[doc.collectionSlug]\n const targetPluginConfig = targetCollection?.config.custom?.['plugin-import-export']\n\n const disableJobsQueue =\n targetPluginConfig?.importDisableJobsQueue ?? importConfig?.disableJobsQueue ?? false\n\n const debug = pluginConfig.debug || false\n\n if (debug) {\n req.payload.logger.info({\n collectionSlug: doc.collectionSlug,\n disableJobsQueue,\n docId: doc.id,\n msg: '[Import Sync Hook] Starting',\n transactionID: req.transactionID,\n })\n }\n\n if (!disableJobsQueue) {\n return doc\n }\n\n try {\n // Get file data from the uploaded document\n // First try req.file which is available during the same request (especially important for cloud storage)\n // Fall back to getFileFromDoc for cases where req.file isn't available\n let fileData: Buffer\n let fileMimetype: string\n\n if (req.file?.data) {\n fileData = req.file.data\n fileMimetype = req.file.mimetype || doc.mimeType\n\n if (!fileMimetype) {\n throw new FileRetrievalError(\n req.t,\n `Unable to determine mimetype for file: ${doc.filename}`,\n )\n }\n } else {\n const fileFromDoc = await getFileFromDoc({\n collectionConfig,\n doc: {\n filename: doc.filename,\n mimeType: doc.mimeType,\n url: doc.url,\n },\n req,\n })\n fileData = fileFromDoc.data\n fileMimetype = fileFromDoc.mimetype\n }\n\n const maxLimit = await resolveLimit({\n limit: targetPluginConfig?.importLimit,\n req,\n })\n const defaultVersionStatus =\n targetPluginConfig?.defaultVersionStatus ??\n importConfig?.defaultVersionStatus ??\n pluginConfig.defaultVersionStatus ??\n FALLBACK_VERSION_STATUS\n const batchSize =\n targetPluginConfig?.importBatchSize ??\n importConfig?.batchSize ??\n pluginConfig.batchSize ??\n FALLBACK_BATCH_SIZE\n\n const result = await createImport({\n id: doc.id,\n name: doc.filename || 'import',\n batchSize,\n collectionSlug: doc.collectionSlug,\n debug,\n defaultVersionStatus,\n file: {\n name: doc.filename,\n data: fileData,\n mimetype: fileMimetype,\n },\n format: fileMimetype === 'text/csv' ? 'csv' : 'json',\n importDoc: doc,\n importMode: doc.importMode || 'create',\n matchField: doc.matchField,\n maxLimit,\n req,\n userCollection: req?.user?.collection,\n userID: req?.user?.id,\n })\n\n // Determine status\n let status: 'completed' | 'failed' | 'partial'\n if (result.errors.length === 0) {\n status = 'completed'\n } else if (result.imported + result.updated === 0) {\n status = 'failed'\n } else {\n status = 'partial'\n }\n\n const summary = {\n imported: result.imported,\n issueDetails:\n result.errors.length > 0\n ? result.errors.map((e) => ({\n data: e.doc,\n error: e.error,\n row: e.index + 1,\n }))\n : undefined,\n issues: result.errors.length,\n total: result.total,\n updated: result.updated,\n }\n\n // Try to update the document with results\n try {\n await req.payload.update({\n id: doc.id,\n collection: collectionConfig.slug,\n data: {\n status,\n summary,\n },\n overrideAccess: true,\n req,\n })\n } catch (updateErr) {\n // Update may fail if document not yet committed\n if (debug) {\n req.payload.logger.error({\n err: updateErr,\n msg: `Failed to update import document ${doc.id} with results`,\n })\n }\n }\n\n // Return updated doc for immediate response\n return {\n ...doc,\n status,\n summary,\n }\n } catch (err) {\n const summary = {\n imported: 0,\n issueDetails: [\n {\n data: {},\n error: err instanceof Error ? err.message : String(err),\n row: 0,\n },\n ],\n issues: 1,\n total: 0,\n updated: 0,\n }\n\n if (debug) {\n req.payload.logger.error({\n docId: doc.id,\n err,\n msg: '[Import Sync Hook] Import processing failed, attempting to update status',\n transactionID: req.transactionID,\n })\n }\n\n // Try to update document with error status\n try {\n if (debug) {\n req.payload.logger.info({\n collectionSlug: collectionConfig.slug,\n docId: doc.id,\n msg: '[Import Sync Hook] About to update document with failed status',\n })\n }\n await req.payload.update({\n id: doc.id,\n collection: collectionConfig.slug,\n data: {\n status: 'failed',\n summary,\n },\n overrideAccess: true,\n req,\n })\n if (debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Sync Hook] Successfully updated document with failed status',\n })\n }\n } catch (updateErr) {\n // Update may fail if document not yet committed, log but continue\n // ALWAYS log this error to help debug Postgres issues\n req.payload.logger.error({\n err: updateErr,\n msg: `[Import Sync Hook] Failed to update import document ${doc.id} with error status`,\n transactionID: req.transactionID,\n })\n }\n\n if (debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Sync Hook] Returning failed doc',\n status: 'failed',\n })\n }\n\n // Return error status for immediate response\n return {\n ...doc,\n status: 'failed',\n summary,\n }\n }\n })\n\n afterChange.push(async ({ collection: collectionConfig, doc, operation, req }) => {\n if (operation !== 'create') {\n return\n }\n\n const targetCollection = req.payload.collections[doc.collectionSlug]\n const targetPluginConfig = targetCollection?.config.custom?.['plugin-import-export']\n\n const disableJobsQueue =\n targetPluginConfig?.importDisableJobsQueue ?? importConfig?.disableJobsQueue ?? false\n\n if (pluginConfig.debug) {\n req.payload.logger.info({\n collectionSlug: doc.collectionSlug,\n disableJobsQueue,\n docId: doc.id,\n docStatus: doc.status,\n msg: '[Import Job Hook] Checking if should queue job',\n transactionID: req.transactionID,\n })\n }\n\n if (disableJobsQueue) {\n if (pluginConfig.debug) {\n req.payload.logger.info({\n docId: doc.id,\n msg: '[Import Job Hook] Skipping job queue (sync mode)',\n })\n }\n return\n }\n\n try {\n // Resolve maxLimit ahead of time since it may involve async config resolution\n const maxLimit = await resolveLimit({\n limit: targetPluginConfig?.importLimit,\n req,\n })\n const defaultVersionStatus =\n targetPluginConfig?.defaultVersionStatus ??\n importConfig?.defaultVersionStatus ??\n pluginConfig.defaultVersionStatus ??\n FALLBACK_VERSION_STATUS\n const batchSize =\n targetPluginConfig?.importBatchSize ??\n importConfig?.batchSize ??\n pluginConfig.batchSize ??\n FALLBACK_BATCH_SIZE\n\n const input: ImportTaskInput = {\n batchSize,\n debug: pluginConfig.debug,\n defaultVersionStatus,\n importCollection: collectionConfig.slug,\n importId: doc.id,\n maxLimit,\n userCollection: req.user?.collection,\n userID: req?.user?.id,\n }\n\n await req.payload.jobs.queue({\n input,\n overrideAccess: true,\n task: 'createCollectionImport',\n })\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: `Failed to queue import job for document ${doc.id}`,\n })\n }\n })\n\n return collection\n}\n"],"names":["FileRetrievalError","getFileFromDoc","resolveLimit","createImport","getFields","handlePreview","FALLBACK_BATCH_SIZE","FALLBACK_VERSION_STATUS","getImportCollection","collectionSlugs","importConfig","pluginConfig","afterChange","collection","slug","access","update","admin","components","edit","SaveButton","custom","disableCopyToLocale","group","useAsTitle","disableDuplicate","endpoints","handler","method","path","fields","hooks","lockDocuments","upload","filesRequiredOnCreate","hideFileInputOnCreate","hideRemoveFile","mimeTypes","push","collectionConfig","doc","operation","req","status","targetCollection","payload","collections","collectionSlug","targetPluginConfig","config","disableJobsQueue","importDisableJobsQueue","debug","logger","info","docId","id","msg","transactionID","fileData","fileMimetype","file","data","mimetype","mimeType","t","filename","fileFromDoc","url","maxLimit","limit","importLimit","defaultVersionStatus","batchSize","importBatchSize","result","name","format","importDoc","importMode","matchField","userCollection","user","userID","errors","length","imported","updated","summary","issueDetails","map","e","error","row","index","undefined","issues","total","overrideAccess","updateErr","err","Error","message","String","docStatus","input","importCollection","importId","jobs","queue","task"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,UAAS;AAK5C,SAASC,cAAc,QAAQ,iCAAgC;AAC/D,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB;AAElD,MAAMC,sBAAsB;AAC5B,MAAMC,0BAA0B;AAEhC,OAAO,MAAMC,sBAAsB,CAAC,EAClCC,eAAe,EACfC,YAAY,EACZC,YAAY,EAQb;IACC,MAAMC,cAA2C,EAAE;IAEnD,MAAMC,aAA+B;QACnCC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,YAAY;gBACVC,MAAM;oBACJC,YAAY;gBACd;YACF;YACAC,QAAQ;gBACN,wBAAwB;oBACtBZ;gBACF;YACF;YACAa,qBAAqB;YAC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Q;gBACA3C,KAAK,CAAC,wCAAwC,EAAEjB,IAAIgB,EAAE,EAAE;YAC1D;QACF;IACF;IAEA,OAAO3C;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlePreview.d.ts","sourceRoot":"","sources":["../../src/import/handlePreview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"handlePreview.d.ts","sourceRoot":"","sources":["../../src/import/handlePreview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAqB7C,eAAO,MAAM,aAAa,QAAe,cAAc,KAAG,OAAO,CAAC,QAAQ,CA4IzE,CAAA"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { addDataAndFileToRequest } from 'payload';
|
|
2
2
|
import { DEFAULT_PREVIEW_LIMIT, MAX_PREVIEW_LIMIT, MIN_PREVIEW_LIMIT, MIN_PREVIEW_PAGE } from '../constants.js';
|
|
3
|
+
import { applyFieldHooks } from '../utilities/applyFieldHooks.js';
|
|
3
4
|
import { getImportFieldFunctions } from '../utilities/getImportFieldFunctions.js';
|
|
5
|
+
import { getSubmittedFormValues } from '../utilities/getSubmittedFormValues.js';
|
|
4
6
|
import { parseCSV } from '../utilities/parseCSV.js';
|
|
5
7
|
import { parseJSON } from '../utilities/parseJSON.js';
|
|
6
8
|
import { removeDisabledFields } from '../utilities/removeDisabledFields.js';
|
|
@@ -8,7 +10,7 @@ import { resolveLimit } from '../utilities/resolveLimit.js';
|
|
|
8
10
|
import { unflattenObject } from '../utilities/unflattenObject.js';
|
|
9
11
|
export const handlePreview = async (req)=>{
|
|
10
12
|
await addDataAndFileToRequest(req);
|
|
11
|
-
const { collectionSlug, fileData, format, previewLimit: rawPreviewLimit = DEFAULT_PREVIEW_LIMIT, previewPage: rawPreviewPage = 1 } = req.data;
|
|
13
|
+
const { collectionSlug, fileData, format, formData, previewLimit: rawPreviewLimit = DEFAULT_PREVIEW_LIMIT, previewPage: rawPreviewPage = 1 } = req.data;
|
|
12
14
|
// Validate and clamp pagination values to safe bounds
|
|
13
15
|
const previewLimit = Math.max(MIN_PREVIEW_LIMIT, Math.min(rawPreviewLimit, MAX_PREVIEW_LIMIT));
|
|
14
16
|
const previewPage = Math.max(MIN_PREVIEW_PAGE, rawPreviewPage);
|
|
@@ -36,31 +38,59 @@ export const handlePreview = async (req)=>{
|
|
|
36
38
|
try {
|
|
37
39
|
// Parse the file data
|
|
38
40
|
let parsedData;
|
|
41
|
+
let originalDocs = [];
|
|
39
42
|
const buffer = Buffer.from(fileData, 'base64');
|
|
43
|
+
const importFieldHooks = getImportFieldFunctions({
|
|
44
|
+
fields: targetCollection.config.flattenedFields || []
|
|
45
|
+
});
|
|
40
46
|
if (format === 'csv') {
|
|
41
47
|
const rawData = await parseCSV({
|
|
42
48
|
data: buffer,
|
|
43
49
|
req
|
|
44
50
|
});
|
|
45
|
-
|
|
46
|
-
const fromCSVFunctions = getImportFieldFunctions({
|
|
47
|
-
fields: targetCollection.config.flattenedFields || []
|
|
48
|
-
});
|
|
51
|
+
originalDocs = rawData;
|
|
49
52
|
// Unflatten CSV data
|
|
50
53
|
parsedData = rawData.map((doc)=>{
|
|
51
54
|
const unflattened = unflattenObject({
|
|
52
55
|
data: doc,
|
|
53
56
|
fields: targetCollection.config.flattenedFields ?? [],
|
|
54
|
-
|
|
57
|
+
format: 'csv',
|
|
58
|
+
importFieldHooks,
|
|
55
59
|
req
|
|
56
60
|
});
|
|
57
61
|
return unflattened ?? {};
|
|
58
62
|
}).filter((doc)=>doc && Object.keys(doc).length > 0);
|
|
59
63
|
} else {
|
|
60
|
-
|
|
64
|
+
const parsedDocs = parseJSON({
|
|
61
65
|
data: buffer,
|
|
62
66
|
req
|
|
63
67
|
});
|
|
68
|
+
originalDocs = parsedDocs;
|
|
69
|
+
// Apply field-level import hooks for JSON format
|
|
70
|
+
parsedData = parsedDocs.map((doc)=>applyFieldHooks({
|
|
71
|
+
type: 'beforeImport',
|
|
72
|
+
data: doc,
|
|
73
|
+
fieldHooks: importFieldHooks,
|
|
74
|
+
fields: targetCollection.config.flattenedFields ?? [],
|
|
75
|
+
format: 'json',
|
|
76
|
+
operation: 'import',
|
|
77
|
+
req
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
const importHooks = targetCollection.config.custom?.['plugin-import-export']?.importHooks;
|
|
81
|
+
if (importHooks?.before && parsedData.length > 0) {
|
|
82
|
+
const result = await importHooks.before({
|
|
83
|
+
batchNumber: 1,
|
|
84
|
+
data: parsedData,
|
|
85
|
+
format: format ?? 'csv',
|
|
86
|
+
importDoc: getSubmittedFormValues({
|
|
87
|
+
formData: formData ?? {}
|
|
88
|
+
}),
|
|
89
|
+
originalData: originalDocs,
|
|
90
|
+
req,
|
|
91
|
+
totalBatches: 1
|
|
92
|
+
});
|
|
93
|
+
parsedData = result;
|
|
64
94
|
}
|
|
65
95
|
// Remove disabled fields from the documents
|
|
66
96
|
const disabledFields = targetCollection.config.admin?.custom?.['plugin-import-export']?.disabledFields ?? [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/import/handlePreview.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest } from 'payload'\n\nimport type { ImportPreviewResponse } from '../types.js'\n\nimport {\n DEFAULT_PREVIEW_LIMIT,\n MAX_PREVIEW_LIMIT,\n MIN_PREVIEW_LIMIT,\n MIN_PREVIEW_PAGE,\n} from '../constants.js'\nimport { getImportFieldFunctions } from '../utilities/getImportFieldFunctions.js'\nimport { parseCSV } from '../utilities/parseCSV.js'\nimport { parseJSON } from '../utilities/parseJSON.js'\nimport { removeDisabledFields } from '../utilities/removeDisabledFields.js'\nimport { resolveLimit } from '../utilities/resolveLimit.js'\nimport { unflattenObject } from '../utilities/unflattenObject.js'\n\nexport const handlePreview = async (req: PayloadRequest): Promise<Response> => {\n await addDataAndFileToRequest(req)\n\n const {\n collectionSlug,\n fileData,\n format,\n previewLimit: rawPreviewLimit = DEFAULT_PREVIEW_LIMIT,\n previewPage: rawPreviewPage = 1,\n } = req.data as {\n collectionSlug: string\n fileData?: string\n format?: 'csv' | 'json'\n previewLimit?: number\n previewPage?: number\n }\n\n // Validate and clamp pagination values to safe bounds\n const previewLimit = Math.max(MIN_PREVIEW_LIMIT, Math.min(rawPreviewLimit, MAX_PREVIEW_LIMIT))\n const previewPage = Math.max(MIN_PREVIEW_PAGE, rawPreviewPage)\n\n const targetCollection = req.payload.collections[collectionSlug]\n if (!targetCollection) {\n return Response.json(\n { error: `Collection with slug ${collectionSlug} not found` },\n { status: 400 },\n )\n }\n\n // Resolve max limit from the collection config\n const pluginConfig = targetCollection.config.custom?.['plugin-import-export']\n const maxLimit = await resolveLimit({\n limit: pluginConfig?.importLimit,\n req,\n })\n\n if (!fileData) {\n return Response.json({ error: 'No file data provided' }, { status: 400 })\n }\n\n try {\n // Parse the file data\n let parsedData: Record<string, unknown>[]\n const buffer = Buffer.from(fileData, 'base64')\n\n if (format === 'csv') {\n const rawData = await parseCSV({ data: buffer, req })\n
|
|
1
|
+
{"version":3,"sources":["../../src/import/handlePreview.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest } from 'payload'\n\nimport type { ImportDoc, ImportPreviewResponse } from '../types.js'\n\nimport {\n DEFAULT_PREVIEW_LIMIT,\n MAX_PREVIEW_LIMIT,\n MIN_PREVIEW_LIMIT,\n MIN_PREVIEW_PAGE,\n} from '../constants.js'\nimport { applyFieldHooks } from '../utilities/applyFieldHooks.js'\nimport { getImportFieldFunctions } from '../utilities/getImportFieldFunctions.js'\nimport { getSubmittedFormValues } from '../utilities/getSubmittedFormValues.js'\nimport { parseCSV } from '../utilities/parseCSV.js'\nimport { parseJSON } from '../utilities/parseJSON.js'\nimport { removeDisabledFields } from '../utilities/removeDisabledFields.js'\nimport { resolveLimit } from '../utilities/resolveLimit.js'\nimport { unflattenObject } from '../utilities/unflattenObject.js'\n\nexport const handlePreview = async (req: PayloadRequest): Promise<Response> => {\n await addDataAndFileToRequest(req)\n\n const {\n collectionSlug,\n fileData,\n format,\n formData,\n previewLimit: rawPreviewLimit = DEFAULT_PREVIEW_LIMIT,\n previewPage: rawPreviewPage = 1,\n } = req.data as {\n collectionSlug: string\n fileData?: string\n format?: 'csv' | 'json'\n formData?: Record<string, unknown>\n previewLimit?: number\n previewPage?: number\n }\n\n // Validate and clamp pagination values to safe bounds\n const previewLimit = Math.max(MIN_PREVIEW_LIMIT, Math.min(rawPreviewLimit, MAX_PREVIEW_LIMIT))\n const previewPage = Math.max(MIN_PREVIEW_PAGE, rawPreviewPage)\n\n const targetCollection = req.payload.collections[collectionSlug]\n if (!targetCollection) {\n return Response.json(\n { error: `Collection with slug ${collectionSlug} not found` },\n { status: 400 },\n )\n }\n\n // Resolve max limit from the collection config\n const pluginConfig = targetCollection.config.custom?.['plugin-import-export']\n const maxLimit = await resolveLimit({\n limit: pluginConfig?.importLimit,\n req,\n })\n\n if (!fileData) {\n return Response.json({ error: 'No file data provided' }, { status: 400 })\n }\n\n try {\n // Parse the file data\n let parsedData: Record<string, unknown>[]\n let originalDocs: Record<string, unknown>[] = []\n const buffer = Buffer.from(fileData, 'base64')\n\n const importFieldHooks = getImportFieldFunctions({\n fields: targetCollection.config.flattenedFields || [],\n })\n\n if (format === 'csv') {\n const rawData = await parseCSV({ data: buffer, req })\n originalDocs = rawData\n\n // Unflatten CSV data\n parsedData = rawData\n .map((doc) => {\n const unflattened = unflattenObject({\n data: doc,\n fields: targetCollection.config.flattenedFields ?? [],\n format: 'csv',\n importFieldHooks,\n req,\n })\n return unflattened ?? {}\n })\n .filter((doc) => doc && Object.keys(doc).length > 0)\n } else {\n const parsedDocs = parseJSON({ data: buffer, req })\n originalDocs = parsedDocs\n // Apply field-level import hooks for JSON format\n parsedData = parsedDocs.map((doc) =>\n applyFieldHooks({\n type: 'beforeImport',\n data: doc,\n fieldHooks: importFieldHooks,\n fields: targetCollection.config.flattenedFields ?? [],\n format: 'json',\n operation: 'import',\n req,\n }),\n )\n }\n\n const importHooks = targetCollection.config.custom?.['plugin-import-export']?.importHooks\n if (importHooks?.before && parsedData.length > 0) {\n const result = await importHooks.before({\n batchNumber: 1,\n data: parsedData as unknown as Parameters<typeof importHooks.before>[0]['data'],\n format: format ?? 'csv',\n importDoc: getSubmittedFormValues({\n formData: formData ?? {},\n }) as ImportDoc,\n originalData: originalDocs,\n req,\n totalBatches: 1,\n })\n parsedData = result as unknown as Record<string, unknown>[]\n }\n\n // Remove disabled fields from the documents\n const disabledFields =\n targetCollection.config.admin?.custom?.['plugin-import-export']?.disabledFields ?? []\n\n if (disabledFields.length > 0) {\n parsedData = parsedData.map((doc) => removeDisabledFields(doc, disabledFields))\n }\n\n // Calculate pagination\n const totalDocs = parsedData.length\n const totalPages = totalDocs === 0 ? 0 : Math.ceil(totalDocs / previewLimit)\n const startIndex = (previewPage - 1) * previewLimit\n const endIndex = startIndex + previewLimit\n const paginatedDocs = parsedData.slice(startIndex, endIndex)\n\n const hasNextPage = previewPage < totalPages\n const hasPrevPage = previewPage > 1\n\n // Check if the file exceeds the max limit\n const limitExceeded = typeof maxLimit === 'number' && maxLimit > 0 && totalDocs > maxLimit\n\n const response: ImportPreviewResponse = {\n docs: paginatedDocs,\n hasNextPage,\n hasPrevPage,\n limit: previewLimit,\n limitExceeded,\n maxLimit,\n page: previewPage,\n totalDocs,\n totalPages,\n }\n\n return Response.json(response)\n } catch (error) {\n req.payload.logger.error({ err: error, msg: 'Error parsing import preview data' })\n return Response.json({ error: 'Failed to parse file data' }, { status: 500 })\n }\n}\n"],"names":["addDataAndFileToRequest","DEFAULT_PREVIEW_LIMIT","MAX_PREVIEW_LIMIT","MIN_PREVIEW_LIMIT","MIN_PREVIEW_PAGE","applyFieldHooks","getImportFieldFunctions","getSubmittedFormValues","parseCSV","parseJSON","removeDisabledFields","resolveLimit","unflattenObject","handlePreview","req","collectionSlug","fileData","format","formData","previewLimit","rawPreviewLimit","previewPage","rawPreviewPage","data","Math","max","min","targetCollection","payload","collections","Response","json","error","status","pluginConfig","config","custom","maxLimit","limit","importLimit","parsedData","originalDocs","buffer","Buffer","from","importFieldHooks","fields","flattenedFields","rawData","map","doc","unflattened","filter","Object","keys","length","parsedDocs","type","fieldHooks","operation","importHooks","before","result","batchNumber","importDoc","originalData","totalBatches","disabledFields","admin","totalDocs","totalPages","ceil","startIndex","endIndex","paginatedDocs","slice","hasNextPage","hasPrevPage","limitExceeded","response","docs","page","logger","err","msg"],"mappings":"AAEA,SAASA,uBAAuB,QAAQ,UAAS;AAIjD,SACEC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,gBAAgB,QACX,kBAAiB;AACxB,SAASC,eAAe,QAAQ,kCAAiC;AACjE,SAASC,uBAAuB,QAAQ,0CAAyC;AACjF,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,QAAQ,QAAQ,2BAA0B;AACnD,SAASC,SAAS,QAAQ,4BAA2B;AACrD,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,eAAe,QAAQ,kCAAiC;AAEjE,OAAO,MAAMC,gBAAgB,OAAOC;IAClC,MAAMd,wBAAwBc;IAE9B,MAAM,EACJC,cAAc,EACdC,QAAQ,EACRC,MAAM,EACNC,QAAQ,EACRC,cAAcC,kBAAkBnB,qBAAqB,EACrDoB,aAAaC,iBAAiB,CAAC,EAChC,GAAGR,IAAIS,IAAI;IASZ,sDAAsD;IACtD,MAAMJ,eAAeK,KAAKC,GAAG,CAACtB,mBAAmBqB,KAAKE,GAAG,CAACN,iBAAiBlB;IAC3E,MAAMmB,cAAcG,KAAKC,GAAG,CAACrB,kBAAkBkB;IAE/C,MAAMK,mBAAmBb,IAAIc,OAAO,CAACC,WAAW,CAACd,eAAe;IAChE,IAAI,CAACY,kBA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SAASC,IAAI,CAACgD;IACvB,EAAE,OAAO/C,OAAO;QACdlB,IAAIc,OAAO,CAACsD,MAAM,CAAClD,KAAK,CAAC;YAAEmD,KAAKnD;YAAOoD,KAAK;QAAoC;QAChF,OAAOtD,SAASC,IAAI,CAAC;YAAEC,OAAO;QAA4B,GAAG;YAAEC,QAAQ;QAAI;IAC7E;AACF,EAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import type { ExportAfterHook, ExportBeforeHook, FieldBeforeExportHook, FieldBeforeImportHook, ImportAfterHook, ImportBeforeHook, ImportExportPluginConfig, Limit } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Adds CSV/JSON import and export functionality to selected collections.
|
|
4
|
+
*
|
|
5
|
+
* Registers two upload collections (`exports`, `imports`) that drive the admin
|
|
6
|
+
* UI flow, plus the `createCollectionExport` and `createCollectionImport` jobs
|
|
7
|
+
* that run the work asynchronously. Per-collection settings (batch size, limits,
|
|
8
|
+
* format, lifecycle hooks, override) live on each entry of `collections`.
|
|
9
|
+
*
|
|
10
|
+
* @see https://payloadcms.com/docs/plugins/import-export
|
|
11
|
+
*/
|
|
12
|
+
export declare const importExportPlugin: (options: ImportExportPluginConfig) => import("payload").Plugin;
|
|
4
13
|
declare module 'payload' {
|
|
5
14
|
interface FieldCustom {
|
|
6
15
|
'plugin-import-export'?: {
|
|
@@ -12,11 +21,22 @@ declare module 'payload' {
|
|
|
12
21
|
* @default false
|
|
13
22
|
*/
|
|
14
23
|
disabled?: boolean;
|
|
15
|
-
fromCSV?: FromCSVFunction;
|
|
16
24
|
/**
|
|
17
|
-
*
|
|
25
|
+
* Field-level lifecycle hooks for import/export transformations.
|
|
26
|
+
* Works for both CSV and JSON formats.
|
|
18
27
|
*/
|
|
19
|
-
|
|
28
|
+
hooks?: {
|
|
29
|
+
/**
|
|
30
|
+
* Runs before a field value is exported. Return a transformed value,
|
|
31
|
+
* `undefined` to use default behavior, or mutate `siblingData` to add
|
|
32
|
+
* extra columns at the same level.
|
|
33
|
+
*/
|
|
34
|
+
beforeExport?: FieldBeforeExportHook;
|
|
35
|
+
/**
|
|
36
|
+
* Runs before a field value is imported. Return the transformed value.
|
|
37
|
+
*/
|
|
38
|
+
beforeImport?: FieldBeforeImportHook;
|
|
39
|
+
};
|
|
20
40
|
};
|
|
21
41
|
}
|
|
22
42
|
interface CollectionAdminCustom {
|
|
@@ -47,9 +67,17 @@ declare module 'payload' {
|
|
|
47
67
|
};
|
|
48
68
|
}
|
|
49
69
|
interface CollectionCustom {
|
|
70
|
+
/**
|
|
71
|
+
* @internal
|
|
72
|
+
* Server-side storage for resolved plugin config. Users should configure
|
|
73
|
+
* import/export via `importExportPlugin({ collections: [{ slug, export: { ... }, import: { ... } }] })`.
|
|
74
|
+
* These fields are populated automatically and are not part of the public
|
|
75
|
+
* API — the names here intentionally diverge from the user-facing nested
|
|
76
|
+
* `export.hooks` / `import.hooks` config and may change without notice.
|
|
77
|
+
*/
|
|
50
78
|
'plugin-import-export'?: {
|
|
51
79
|
/**
|
|
52
|
-
* Default version status for imported documents when _status field is not provided.
|
|
80
|
+
* @internal Default version status for imported documents when _status field is not provided.
|
|
53
81
|
* Only applies to collections with versions enabled.
|
|
54
82
|
* @default 'published'
|
|
55
83
|
*/
|
|
@@ -64,6 +92,14 @@ declare module 'payload' {
|
|
|
64
92
|
* @default false
|
|
65
93
|
*/
|
|
66
94
|
exportDisableJobsQueue?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Lifecycle hooks for export operations. Stored server-side since functions
|
|
97
|
+
* cannot be serialized to the client.
|
|
98
|
+
*/
|
|
99
|
+
exportHooks?: {
|
|
100
|
+
after?: ExportAfterHook;
|
|
101
|
+
before?: ExportBeforeHook;
|
|
102
|
+
};
|
|
67
103
|
/**
|
|
68
104
|
* Maximum number of documents that can be exported from this collection.
|
|
69
105
|
* Set to 0 for unlimited (default). Can be a number or function.
|
|
@@ -80,6 +116,14 @@ declare module 'payload' {
|
|
|
80
116
|
* @default false
|
|
81
117
|
*/
|
|
82
118
|
importDisableJobsQueue?: boolean;
|
|
119
|
+
/**
|
|
120
|
+
* Lifecycle hooks for import operations. Stored server-side since functions
|
|
121
|
+
* cannot be serialized to the client.
|
|
122
|
+
*/
|
|
123
|
+
importHooks?: {
|
|
124
|
+
after?: ImportAfterHook;
|
|
125
|
+
before?: ImportBeforeHook;
|
|
126
|
+
};
|
|
83
127
|
/**
|
|
84
128
|
* Maximum number of documents that can be imported to this collection.
|
|
85
129
|
* Set to 0 for unlimited (default). Can be a number or function.
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,qBAAqB,EACrB,eAAe,EACf,gBAAgB,EAChB,wBAAwB,EACxB,KAAK,EAEN,MAAM,YAAY,CAAA;AAQnB;;;;;;;;;GASG;AACH,eAAO,MAAM,kBAAkB,iEAyM7B,CAAA;AAEF,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,WAAW;QAC1B,sBAAsB,CAAC,EAAE;YACvB;;;;;;eAMG;YACH,QAAQ,CAAC,EAAE,OAAO,CAAA;YAClB;;;eAGG;YACH,KAAK,CAAC,EAAE;gBACN;;;;mBAIG;gBACH,YAAY,CAAC,EAAE,qBAAqB,CAAA;gBACpC;;mBAEG;gBACH,YAAY,CAAC,EAAE,qBAAqB,CAAA;aACrC,CAAA;SACF,CAAA;KACF;IAED,UAAiB,qBAAqB;QACpC,sBAAsB,CAAC,EAAE;YACvB;;;eAGG;YACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAA;YAC1B;;;eAGG;YACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;YACzB;;eAEG;YACH,eAAe,CAAC,EAAE,OAAO,CAAA;YACzB;;eAEG;YACH,WAAW,CAAC,EAAE,OAAO,CAAA;YACrB;;;eAGG;YACH,YAAY,CAAC,EAAE,KAAK,GAAG,MAAM,CAAA;SAC9B,CAAA;KACF;IAED,UAAiB,gBAAgB;QAC/B;;;;;;;WAOG;QACH,sBAAsB,CAAC,EAAE;YACvB;;;;eAIG;YACH,oBAAoB,CAAC,EAAE,OAAO,GAAG,WAAW,CAAA;YAC5C;;;eAGG;YACH,eAAe,CAAC,EAAE,MAAM,CAAA;YACxB;;;eAGG;YACH,sBAAsB,CAAC,EAAE,OAAO,CAAA;YAChC;;;eAGG;YACH,WAAW,CAAC,EAAE;gBAAE,KAAK,CAAC,EAAE,eAAe,CAAC;gBAAC,MAAM,CAAC,EAAE,gBAAgB,CAAA;aAAE,CAAA;YACpE;;;;eAIG;YACH,WAAW,CAAC,EAAE,KAAK,CAAA;YACnB;;;eAGG;YACH,eAAe,CAAC,EAAE,MAAM,CAAA;YACxB;;;eAGG;YACH,sBAAsB,CAAC,EAAE,OAAO,CAAA;YAChC;;;eAGG;YACH,WAAW,CAAC,EAAE;gBAAE,KAAK,CAAC,EAAE,eAAe,CAAC;gBAAC,MAAM,CAAC,EAAE,gBAAgB,CAAA;aAAE,CAAA;YACpE;;;;eAIG;YACH,WAAW,CAAC,EAAE,KAAK,CAAA;SACpB,CAAA;KACF;CACF"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
|
-
import { deepMergeSimple } from 'payload';
|
|
1
|
+
import { deepMergeSimple, definePlugin } from 'payload';
|
|
2
2
|
import { getCreateCollectionExportTask } from './export/getCreateExportCollectionTask.js';
|
|
3
3
|
import { getCreateCollectionImportTask } from './import/getCreateImportCollectionTask.js';
|
|
4
4
|
import { translations } from './translations/index.js';
|
|
5
5
|
import { collectDisabledFieldPaths } from './utilities/collectDisabledFieldPaths.js';
|
|
6
6
|
import { getPluginCollections } from './utilities/getPluginCollections.js';
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Adds CSV/JSON import and export functionality to selected collections.
|
|
9
|
+
*
|
|
10
|
+
* Registers two upload collections (`exports`, `imports`) that drive the admin
|
|
11
|
+
* UI flow, plus the `createCollectionExport` and `createCollectionImport` jobs
|
|
12
|
+
* that run the work asynchronously. Per-collection settings (batch size, limits,
|
|
13
|
+
* format, lifecycle hooks, override) live on each entry of `collections`.
|
|
14
|
+
*
|
|
15
|
+
* @see https://payloadcms.com/docs/plugins/import-export
|
|
16
|
+
*/ export const importExportPlugin = definePlugin({
|
|
17
|
+
slug: '@payloadcms/plugin-import-export',
|
|
18
|
+
plugin: async ({ config, options: pluginConfig })=>{
|
|
8
19
|
// Get all export/import collections and the mappings from target collections to custom collections
|
|
9
20
|
const { customExportSlugMap, customImportSlugMap, exportCollections, importCollections } = await getPluginCollections({
|
|
10
21
|
config,
|
|
@@ -103,8 +114,10 @@ export const importExportPlugin = (pluginConfig)=>async (config)=>{
|
|
|
103
114
|
const importDisableJobsQueue = importConfig?.disableJobsQueue;
|
|
104
115
|
const importBatchSize = importConfig?.batchSize;
|
|
105
116
|
const exportLimit = exportConfig?.limit ?? pluginConfig.exportLimit;
|
|
117
|
+
const exportHooks = exportConfig?.hooks;
|
|
106
118
|
const importLimit = importConfig?.limit ?? pluginConfig.importLimit;
|
|
107
119
|
const importDefaultVersionStatus = importConfig?.defaultVersionStatus;
|
|
120
|
+
const importHooks = importConfig?.hooks;
|
|
108
121
|
collection.admin.custom = {
|
|
109
122
|
...collection.admin.custom || {},
|
|
110
123
|
'plugin-import-export': {
|
|
@@ -145,6 +158,12 @@ export const importExportPlugin = (pluginConfig)=>async (config)=>{
|
|
|
145
158
|
},
|
|
146
159
|
...importDefaultVersionStatus !== undefined && {
|
|
147
160
|
defaultVersionStatus: importDefaultVersionStatus
|
|
161
|
+
},
|
|
162
|
+
...exportHooks !== undefined && {
|
|
163
|
+
exportHooks
|
|
164
|
+
},
|
|
165
|
+
...importHooks !== undefined && {
|
|
166
|
+
importHooks
|
|
148
167
|
}
|
|
149
168
|
}
|
|
150
169
|
};
|
|
@@ -154,16 +173,25 @@ export const importExportPlugin = (pluginConfig)=>async (config)=>{
|
|
|
154
173
|
config.i18n = {};
|
|
155
174
|
}
|
|
156
175
|
/**
|
|
157
|
-
* Merge plugin translations
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
176
|
+
* Merge plugin translations — only for languages the user has enabled.
|
|
177
|
+
* Plugins run before sanitize, so `supportedLanguages` may be undefined; sanitize will
|
|
178
|
+
* default it to `{ en }`, so we mirror that here to avoid merging 30+ unused tables.
|
|
179
|
+
*/ const supportedLanguageKeys = config.i18n?.supportedLanguages ? Object.keys(config.i18n.supportedLanguages) : [
|
|
180
|
+
'en'
|
|
181
|
+
];
|
|
182
|
+
const simplifiedTranslations = {};
|
|
183
|
+
for (const lang of supportedLanguageKeys){
|
|
184
|
+
const entry = translations[lang];
|
|
185
|
+
if (entry) {
|
|
186
|
+
simplifiedTranslations[lang] = entry.translations;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
162
189
|
config.i18n = {
|
|
163
190
|
...config.i18n,
|
|
164
191
|
translations: deepMergeSimple(simplifiedTranslations, config.i18n?.translations ?? {})
|
|
165
192
|
};
|
|
166
193
|
return config;
|
|
167
|
-
}
|
|
194
|
+
}
|
|
195
|
+
});
|
|
168
196
|
|
|
169
197
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { deepMergeSimple } from 'payload'\n\nimport type { PluginDefaultTranslationsObject } from './translations/types.js'\nimport type {\n FromCSVFunction,\n ImportExportPluginConfig,\n Limit,\n PluginCollectionConfig,\n ToCSVFunction,\n} from './types.js'\n\nimport { getCreateCollectionExportTask } from './export/getCreateExportCollectionTask.js'\nimport { getCreateCollectionImportTask } from './import/getCreateImportCollectionTask.js'\nimport { translations } from './translations/index.js'\nimport { collectDisabledFieldPaths } from './utilities/collectDisabledFieldPaths.js'\nimport { getPluginCollections } from './utilities/getPluginCollections.js'\n\nexport const importExportPlugin =\n (pluginConfig: ImportExportPluginConfig) =>\n async (config: Config): Promise<Config> => {\n // Get all export/import collections and the mappings from target collections to custom collections\n const { customExportSlugMap, customImportSlugMap, exportCollections, importCollections } =\n await getPluginCollections({\n config,\n pluginConfig,\n })\n\n // Base collections are at index 0 (always present)\n const baseExportCollection = exportCollections[0]!\n const baseImportCollection = importCollections[0]!\n\n // Collect all export and import collection slugs for filtering\n const allExportSlugs = new Set(exportCollections.map((c) => c.slug))\n const allImportSlugs = new Set(importCollections.map((c) => c.slug))\n\n // Initialize collections array if needed\n if (!config.collections) {\n config.collections = []\n }\n\n // Push all export/import collections if their slugs don't already exist\n for (const collection of [...exportCollections, ...importCollections]) {\n const slugExists = config.collections.some((c) => c.slug === collection.slug)\n if (!slugExists) {\n config.collections.push(collection)\n }\n }\n\n // inject custom import export provider\n config.admin = config.admin || {}\n config.admin.components = config.admin.components || {}\n config.admin.components.providers = config.admin.components.providers || []\n config.admin.components.providers.push(\n '@payloadcms/plugin-import-export/rsc#ImportExportProvider',\n )\n\n // inject the createExport and createImport jobs into the config\n ;((config.jobs ??= {}).tasks ??= []).push(getCreateCollectionExportTask(config))\n config.jobs.tasks.push(getCreateCollectionImportTask(config))\n\n // Build a map of collection configs for quick lookup\n const collectionConfigMap = new Map<string, PluginCollectionConfig>()\n if (pluginConfig.collections) {\n for (const collectionConfig of pluginConfig.collections) {\n collectionConfigMap.set(collectionConfig.slug, collectionConfig)\n }\n }\n\n // Determine which collections to add import/export menu items to\n // Exclude all export and import collections\n const collectionsToUpdate = config.collections.filter(\n (c) => !allExportSlugs.has(c.slug) && !allImportSlugs.has(c.slug),\n )\n\n for (const collection of collectionsToUpdate) {\n // Get the plugin config for this collection (if specified)\n const collectionPluginConfig = collectionConfigMap.get(collection.slug)\n\n // If collections array is specified but this collection is not in it, skip\n if (\n pluginConfig.collections &&\n pluginConfig.collections.length > 0 &&\n !collectionPluginConfig\n ) {\n continue\n }\n\n // Determine which export/import collection to use for this collection\n const exportSlugForCollection =\n customExportSlugMap.get(collection.slug) || baseExportCollection.slug\n const importSlugForCollection =\n customImportSlugMap.get(collection.slug) || baseImportCollection.slug\n\n // Check if export/import are disabled for this collection\n const exportDisabled = collectionPluginConfig?.export === false\n const importDisabled = collectionPluginConfig?.import === false\n\n if (!collection.admin) {\n collection.admin = { components: { listMenuItems: [] } }\n }\n const components = collection.admin.components || {}\n if (!components.listMenuItems) {\n components.listMenuItems = []\n }\n\n // Add export menu item if not disabled\n if (!exportDisabled) {\n components.listMenuItems.push({\n clientProps: {\n collectionSlug: collection.slug,\n exportCollectionSlug: exportSlugForCollection,\n },\n path: '@payloadcms/plugin-import-export/rsc#ExportListMenuItem',\n })\n }\n\n // Add import menu item if not disabled\n if (!importDisabled) {\n components.listMenuItems.push({\n clientProps: {\n collectionSlug: collection.slug,\n importCollectionSlug: importSlugForCollection,\n },\n path: '@payloadcms/plugin-import-export/rsc#ImportListMenuItem',\n })\n }\n\n // Find fields explicitly marked as disabled for import/export\n const disabledFieldAccessors = collectDisabledFieldPaths(collection.fields)\n\n const exportConfig =\n typeof collectionPluginConfig?.export === 'object'\n ? collectionPluginConfig.export\n : undefined\n const exportFormat = exportConfig?.format\n const exportDisableJobsQueue = exportConfig?.disableJobsQueue\n const exportBatchSize = exportConfig?.batchSize\n const exportDisableSave = exportConfig?.disableSave\n const exportDisableDownload = exportConfig?.disableDownload\n\n const importConfig =\n typeof collectionPluginConfig?.import === 'object'\n ? collectionPluginConfig.import\n : undefined\n const importDisableJobsQueue = importConfig?.disableJobsQueue\n const importBatchSize = importConfig?.batchSize\n\n const exportLimit = exportConfig?.limit ?? pluginConfig.exportLimit\n\n const importLimit = importConfig?.limit ?? pluginConfig.importLimit\n const importDefaultVersionStatus = importConfig?.defaultVersionStatus\n\n collection.admin.custom = {\n ...(collection.admin.custom || {}),\n 'plugin-import-export': {\n ...(collection.admin.custom?.['plugin-import-export'] || {}),\n disabledFields: disabledFieldAccessors,\n ...(exportFormat !== undefined && { exportFormat }),\n ...(exportDisableSave !== undefined && { disableSave: exportDisableSave }),\n ...(exportDisableDownload !== undefined && { disableDownload: exportDisableDownload }),\n },\n }\n\n collection.custom = {\n ...(collection.custom || {}),\n 'plugin-import-export': {\n ...(collection.custom?.['plugin-import-export'] || {}),\n ...(exportLimit !== undefined && { exportLimit }),\n ...(exportDisableJobsQueue !== undefined && {\n exportDisableJobsQueue,\n }),\n ...(exportBatchSize !== undefined && { exportBatchSize }),\n ...(importLimit !== undefined && { importLimit }),\n ...(importDisableJobsQueue !== undefined && {\n importDisableJobsQueue,\n }),\n ...(importBatchSize !== undefined && { importBatchSize }),\n ...(importDefaultVersionStatus !== undefined && {\n defaultVersionStatus: importDefaultVersionStatus,\n }),\n },\n }\n\n collection.admin.components = components\n }\n\n if (!config.i18n) {\n config.i18n = {}\n }\n\n /**\n * Merge plugin translations\n */\n const simplifiedTranslations = Object.entries(translations).reduce(\n (acc, [key, value]) => {\n acc[key] = value.translations\n return acc\n },\n {} as Record<string, PluginDefaultTranslationsObject>,\n )\n\n config.i18n = {\n ...config.i18n,\n translations: deepMergeSimple(simplifiedTranslations, config.i18n?.translations ?? {}),\n }\n\n return config\n }\n\ndeclare module 'payload' {\n export interface FieldCustom {\n 'plugin-import-export'?: {\n /**\n * When `true` the field is **completely excluded** from the import-export plugin:\n * - It will not appear in the \"Fields to export\" selector.\n * - It is hidden from the preview list when no specific fields are chosen.\n * - Its data is omitted from the final CSV / JSON export.\n * @default false\n */\n disabled?: boolean\n fromCSV?: FromCSVFunction\n /**\n * Custom function used to modify the outgoing csv data by manipulating the data, siblingData or by returning the desired value\n */\n toCSV?: ToCSVFunction\n }\n }\n\n export interface CollectionAdminCustom {\n 'plugin-import-export'?: {\n /**\n * Array of collection slugs that this export/import collection can target.\n * Used by CollectionField to populate the dropdown options.\n */\n collectionSlugs?: string[]\n /**\n * Array of field paths that are disabled for import/export.\n * These paths are collected from fields marked with `custom['plugin-import-export'].disabled = true`.\n */\n disabledFields?: string[]\n /**\n * If true, disables the download button in the export preview UI.\n */\n disableDownload?: boolean\n /**\n * If true, disables the save button in the export preview UI.\n */\n disableSave?: boolean\n /**\n * When set, forces exports from this collection to use this format.\n * This value is read from the plugin config's `export.format` option.\n */\n exportFormat?: 'csv' | 'json'\n }\n }\n\n export interface CollectionCustom {\n 'plugin-import-export'?: {\n /**\n * Default version status for imported documents when _status field is not provided.\n * Only applies to collections with versions enabled.\n * @default 'published'\n */\n defaultVersionStatus?: 'draft' | 'published'\n /**\n * Number of documents to process in each batch during export.\n * @default 100\n */\n exportBatchSize?: number\n /**\n * If true, disables the jobs queue for exports and runs them synchronously.\n * @default false\n */\n exportDisableJobsQueue?: boolean\n /**\n * Maximum number of documents that can be exported from this collection.\n * Set to 0 for unlimited (default). Can be a number or function.\n * Stored in collection.custom (server-only) since functions cannot be serialized to client.\n */\n exportLimit?: Limit\n /**\n * Number of documents to process in each batch during import.\n * @default 100\n */\n importBatchSize?: number\n /**\n * If true, disables the jobs queue for imports and runs them synchronously.\n * @default false\n */\n importDisableJobsQueue?: boolean\n /**\n * Maximum number of documents that can be imported to this collection.\n * Set to 0 for unlimited (default). Can be a number or function.\n * Stored in collection.custom (server-only) since functions cannot be serialized to client.\n */\n importLimit?: Limit\n }\n }\n}\n"],"names":["deepMergeSimple","getCreateCollectionExportTask","getCreateCollectionImportTask","translations","collectDisabledFieldPaths","getPluginCollections","importExportPlugin","pluginConfig","config","customExportSlugMap","customImportSlugMap","exportCollections","importCollections","baseExportCollection","baseImportCollection","allExportSlugs","Set","map","c","slug","allImportSlugs","collections","collection","slugExists","some","push","admin","components","providers","jobs","tasks","collectionConfigMap","Map","collectionConfig","set","collectionsToUpdate","filter","has","collectionPluginConfig","get","length","exportSlugForCollection","importSlugForCollection","exportDisabled","export","importDisabled","import","listMenuItems","clientProps","collectionSlug","exportCollectionSlug","path","importCollectionSlug","disabledFieldAccessors","fields","exportConfig","undefined","exportFormat","format","exportDisableJobsQueue","disableJobsQueue","exportBatchSize","batchSize","exportDisableSave","disableSave","exportDisableDownload","disableDownload","importConfig","importDisableJobsQueue","importBatchSize","exportLimit","limit","importLimit","importDefaultVersionStatus","defaultVersionStatus","custom","disabledFields","i18n","simplifiedTranslations","Object","entries","reduce","acc","key","value"],"mappings":"AAEA,SAASA,eAAe,QAAQ,UAAS;AAWzC,SAASC,6BAA6B,QAAQ,4CAA2C;AACzF,SAASC,6BAA6B,QAAQ,4CAA2C;AACzF,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E,OAAO,MAAMC,qBACX,CAACC,eACD,OAAOC;QACL,mGAAmG;QACnG,MAAM,EAAEC,mBAAmB,EAAEC,mBAAmB,EAAEC,iBAAiB,EAAEC,iBAAiB,EAAE,GACtF,MAAMP,qBAAqB;YACzBG;YACAD;QACF;QAEF,mDAAmD;QACnD,MAAMM,uBAAuBF,iBAAiB,CAAC,EAAE;QACjD,MAAMG,uBAAuBF,iBAAiB,CAAC,EAAE;QAEjD,+DAA+D;QAC/D,MAAMG,iBAAiB,IAAIC,IAAIL,kBAAkBM,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI;QAClE,MAAMC,iBAAiB,IAAIJ,IAAIJ,kBAAkBK,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI;QAElE,yCAAyC;QACzC,IAAI,CAACX,OAAOa,WAAW,EAAE;YACvBb,OAAOa,WAAW,GAAG,EAAE;QACzB;QAEA,wEAAwE;QACxE,KAAK,MAAMC,cAAc;eAAIX;eAAsBC;SAAkB,CAAE;YACrE,MAAMW,aAAaf,OAAOa,WAAW,CAACG,IAAI,CAAC,CAACN,IAAMA,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I,CAACnB,OAAOqE,IAAI,EAAE;YAChBrE,OAAOqE,IAAI,GAAG,CAAC;QACjB;QAEA;;KAEC,GACD,MAAMC,yBAAyBC,OAAOC,OAAO,CAAC7E,cAAc8E,MAAM,CAChE,CAACC,KAAK,CAACC,KAAKC,MAAM;YAChBF,GAAG,CAACC,IAAI,GAAGC,MAAMjF,YAAY;YAC7B,OAAO+E;QACT,GACA,CAAC;QAGH1E,OAAOqE,IAAI,GAAG;YACZ,GAAGrE,OAAOqE,IAAI;YACd1E,cAAcH,gBAAgB8E,wBAAwBtE,OAAOqE,IAAI,EAAE1E,gBAAgB,CAAC;QACtF;QAEA,OAAOK;IACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { deepMergeSimple, definePlugin } from 'payload'\n\nimport type { PluginDefaultTranslationsObject } from './translations/types.js'\nimport type {\n ExportAfterHook,\n ExportBeforeHook,\n FieldBeforeExportHook,\n FieldBeforeImportHook,\n ImportAfterHook,\n ImportBeforeHook,\n ImportExportPluginConfig,\n Limit,\n PluginCollectionConfig,\n} from './types.js'\n\nimport { getCreateCollectionExportTask } from './export/getCreateExportCollectionTask.js'\nimport { getCreateCollectionImportTask } from './import/getCreateImportCollectionTask.js'\nimport { translations } from './translations/index.js'\nimport { collectDisabledFieldPaths } from './utilities/collectDisabledFieldPaths.js'\nimport { getPluginCollections } from './utilities/getPluginCollections.js'\n\n/**\n * Adds CSV/JSON import and export functionality to selected collections.\n *\n * Registers two upload collections (`exports`, `imports`) that drive the admin\n * UI flow, plus the `createCollectionExport` and `createCollectionImport` jobs\n * that run the work asynchronously. Per-collection settings (batch size, limits,\n * format, lifecycle hooks, override) live on each entry of `collections`.\n *\n * @see https://payloadcms.com/docs/plugins/import-export\n */\nexport const importExportPlugin = definePlugin<ImportExportPluginConfig>({\n slug: '@payloadcms/plugin-import-export',\n plugin: async ({ config, options: pluginConfig }) => {\n // Get all export/import collections and the mappings from target collections to custom collections\n const { customExportSlugMap, customImportSlugMap, exportCollections, importCollections } =\n await getPluginCollections({\n config,\n pluginConfig,\n })\n\n // Base collections are at index 0 (always present)\n const baseExportCollection = exportCollections[0]!\n const baseImportCollection = importCollections[0]!\n\n // Collect all export and import collection slugs for filtering\n const allExportSlugs = new Set(exportCollections.map((c) => c.slug))\n const allImportSlugs = new Set(importCollections.map((c) => c.slug))\n\n // Initialize collections array if needed\n if (!config.collections) {\n config.collections = []\n }\n\n // Push all export/import collections if their slugs don't already exist\n for (const collection of [...exportCollections, ...importCollections]) {\n const slugExists = config.collections.some((c) => c.slug === collection.slug)\n if (!slugExists) {\n config.collections.push(collection)\n }\n }\n\n // inject custom import export provider\n config.admin = config.admin || {}\n config.admin.components = config.admin.components || {}\n config.admin.components.providers = config.admin.components.providers || []\n config.admin.components.providers.push(\n '@payloadcms/plugin-import-export/rsc#ImportExportProvider',\n )\n\n // inject the createExport and createImport jobs into the config\n ;((config.jobs ??= {}).tasks ??= []).push(getCreateCollectionExportTask(config))\n config.jobs.tasks.push(getCreateCollectionImportTask(config))\n\n // Build a map of collection configs for quick lookup\n const collectionConfigMap = new Map<string, PluginCollectionConfig>()\n if (pluginConfig.collections) {\n for (const collectionConfig of pluginConfig.collections) {\n collectionConfigMap.set(collectionConfig.slug, collectionConfig)\n }\n }\n\n // Determine which collections to add import/export menu items to\n // Exclude all export and import collections\n const collectionsToUpdate = config.collections.filter(\n (c) => !allExportSlugs.has(c.slug) && !allImportSlugs.has(c.slug),\n )\n\n for (const collection of collectionsToUpdate) {\n // Get the plugin config for this collection (if specified)\n const collectionPluginConfig = collectionConfigMap.get(collection.slug)\n\n // If collections array is specified but this collection is not in it, skip\n if (\n pluginConfig.collections &&\n pluginConfig.collections.length > 0 &&\n !collectionPluginConfig\n ) {\n continue\n }\n\n // Determine which export/import collection to use for this collection\n const exportSlugForCollection =\n customExportSlugMap.get(collection.slug) || baseExportCollection.slug\n const importSlugForCollection =\n customImportSlugMap.get(collection.slug) || baseImportCollection.slug\n\n // Check if export/import are disabled for this collection\n const exportDisabled = collectionPluginConfig?.export === false\n const importDisabled = collectionPluginConfig?.import === false\n\n if (!collection.admin) {\n collection.admin = { components: { listMenuItems: [] } }\n }\n const components = collection.admin.components || {}\n if (!components.listMenuItems) {\n components.listMenuItems = []\n }\n\n // Add export menu item if not disabled\n if (!exportDisabled) {\n components.listMenuItems.push({\n clientProps: {\n collectionSlug: collection.slug,\n exportCollectionSlug: exportSlugForCollection,\n },\n path: '@payloadcms/plugin-import-export/rsc#ExportListMenuItem',\n })\n }\n\n // Add import menu item if not disabled\n if (!importDisabled) {\n components.listMenuItems.push({\n clientProps: {\n collectionSlug: collection.slug,\n importCollectionSlug: importSlugForCollection,\n },\n path: '@payloadcms/plugin-import-export/rsc#ImportListMenuItem',\n })\n }\n\n // Find fields explicitly marked as disabled for import/export\n const disabledFieldAccessors = collectDisabledFieldPaths(collection.fields)\n\n const exportConfig =\n typeof collectionPluginConfig?.export === 'object'\n ? collectionPluginConfig.export\n : undefined\n const exportFormat = exportConfig?.format\n const exportDisableJobsQueue = exportConfig?.disableJobsQueue\n const exportBatchSize = exportConfig?.batchSize\n const exportDisableSave = exportConfig?.disableSave\n const exportDisableDownload = exportConfig?.disableDownload\n\n const importConfig =\n typeof collectionPluginConfig?.import === 'object'\n ? collectionPluginConfig.import\n : undefined\n const importDisableJobsQueue = importConfig?.disableJobsQueue\n const importBatchSize = importConfig?.batchSize\n\n const exportLimit = exportConfig?.limit ?? pluginConfig.exportLimit\n const exportHooks = exportConfig?.hooks\n\n const importLimit = importConfig?.limit ?? pluginConfig.importLimit\n const importDefaultVersionStatus = importConfig?.defaultVersionStatus\n const importHooks = importConfig?.hooks\n\n collection.admin.custom = {\n ...(collection.admin.custom || {}),\n 'plugin-import-export': {\n ...(collection.admin.custom?.['plugin-import-export'] || {}),\n disabledFields: disabledFieldAccessors,\n ...(exportFormat !== undefined && { exportFormat }),\n ...(exportDisableSave !== undefined && { disableSave: exportDisableSave }),\n ...(exportDisableDownload !== undefined && { disableDownload: exportDisableDownload }),\n },\n }\n\n collection.custom = {\n ...(collection.custom || {}),\n 'plugin-import-export': {\n ...(collection.custom?.['plugin-import-export'] || {}),\n ...(exportLimit !== undefined && { exportLimit }),\n ...(exportDisableJobsQueue !== undefined && {\n exportDisableJobsQueue,\n }),\n ...(exportBatchSize !== undefined && { exportBatchSize }),\n ...(importLimit !== undefined && { importLimit }),\n ...(importDisableJobsQueue !== undefined && {\n importDisableJobsQueue,\n }),\n ...(importBatchSize !== undefined && { importBatchSize }),\n ...(importDefaultVersionStatus !== undefined && {\n defaultVersionStatus: importDefaultVersionStatus,\n }),\n ...(exportHooks !== undefined && { exportHooks }),\n ...(importHooks !== undefined && { importHooks }),\n },\n }\n\n collection.admin.components = components\n }\n\n if (!config.i18n) {\n config.i18n = {}\n }\n\n /**\n * Merge plugin translations — only for languages the user has enabled.\n * Plugins run before sanitize, so `supportedLanguages` may be undefined; sanitize will\n * default it to `{ en }`, so we mirror that here to avoid merging 30+ unused tables.\n */\n const supportedLanguageKeys = config.i18n?.supportedLanguages\n ? Object.keys(config.i18n.supportedLanguages)\n : ['en']\n\n const simplifiedTranslations: Record<string, PluginDefaultTranslationsObject> = {}\n for (const lang of supportedLanguageKeys) {\n const entry = translations[lang as keyof typeof translations]\n if (entry) {\n simplifiedTranslations[lang] = entry.translations\n }\n }\n\n config.i18n = {\n ...config.i18n,\n translations: deepMergeSimple(simplifiedTranslations, config.i18n?.translations ?? {}),\n }\n\n return config\n },\n})\n\ndeclare module 'payload' {\n export interface FieldCustom {\n 'plugin-import-export'?: {\n /**\n * When `true` the field is **completely excluded** from the import-export plugin:\n * - It will not appear in the \"Fields to export\" selector.\n * - It is hidden from the preview list when no specific fields are chosen.\n * - Its data is omitted from the final CSV / JSON export.\n * @default false\n */\n disabled?: boolean\n /**\n * Field-level lifecycle hooks for import/export transformations.\n * Works for both CSV and JSON formats.\n */\n hooks?: {\n /**\n * Runs before a field value is exported. Return a transformed value,\n * `undefined` to use default behavior, or mutate `siblingData` to add\n * extra columns at the same level.\n */\n beforeExport?: FieldBeforeExportHook\n /**\n * Runs before a field value is imported. Return the transformed value.\n */\n beforeImport?: FieldBeforeImportHook\n }\n }\n }\n\n export interface CollectionAdminCustom {\n 'plugin-import-export'?: {\n /**\n * Array of collection slugs that this export/import collection can target.\n * Used by CollectionField to populate the dropdown options.\n */\n collectionSlugs?: string[]\n /**\n * Array of field paths that are disabled for import/export.\n * These paths are collected from fields marked with `custom['plugin-import-export'].disabled = true`.\n */\n disabledFields?: string[]\n /**\n * If true, disables the download button in the export preview UI.\n */\n disableDownload?: boolean\n /**\n * If true, disables the save button in the export preview UI.\n */\n disableSave?: boolean\n /**\n * When set, forces exports from this collection to use this format.\n * This value is read from the plugin config's `export.format` option.\n */\n exportFormat?: 'csv' | 'json'\n }\n }\n\n export interface CollectionCustom {\n /**\n * @internal\n * Server-side storage for resolved plugin config. Users should configure\n * import/export via `importExportPlugin({ collections: [{ slug, export: { ... }, import: { ... } }] })`.\n * These fields are populated automatically and are not part of the public\n * API — the names here intentionally diverge from the user-facing nested\n * `export.hooks` / `import.hooks` config and may change without notice.\n */\n 'plugin-import-export'?: {\n /**\n * @internal Default version status for imported documents when _status field is not provided.\n * Only applies to collections with versions enabled.\n * @default 'published'\n */\n defaultVersionStatus?: 'draft' | 'published'\n /**\n * Number of documents to process in each batch during export.\n * @default 100\n */\n exportBatchSize?: number\n /**\n * If true, disables the jobs queue for exports and runs them synchronously.\n * @default false\n */\n exportDisableJobsQueue?: boolean\n /**\n * Lifecycle hooks for export operations. Stored server-side since functions\n * cannot be serialized to the client.\n */\n exportHooks?: { after?: ExportAfterHook; before?: ExportBeforeHook }\n /**\n * Maximum number of documents that can be exported from this collection.\n * Set to 0 for unlimited (default). Can be a number or function.\n * Stored in collection.custom (server-only) since functions cannot be serialized to client.\n */\n exportLimit?: Limit\n /**\n * Number of documents to process in each batch during import.\n * @default 100\n */\n importBatchSize?: number\n /**\n * If true, disables the jobs queue for imports and runs them synchronously.\n * @default false\n */\n importDisableJobsQueue?: boolean\n /**\n * Lifecycle hooks for import operations. Stored server-side since functions\n * cannot be serialized to the client.\n */\n importHooks?: { after?: ImportAfterHook; before?: ImportBeforeHook }\n /**\n * Maximum number of documents that can be imported to this collection.\n * Set to 0 for unlimited (default). Can be a number or function.\n * Stored in collection.custom (server-only) since functions cannot be serialized to client.\n */\n importLimit?: Limit\n }\n }\n}\n"],"names":["deepMergeSimple","definePlugin","getCreateCollectionExportTask","getCreateCollectionImportTask","translations","collectDisabledFieldPaths","getPluginCollections","importExportPlugin","slug","plugin","config","options","pluginConfig","customExportSlugMap","customImportSlugMap","exportCollections","importCollections","baseExportCollection","baseImportCollection","allExportSlugs","Set","map","c","allImportSlugs","collections","collection","slugExists","some","push","admin","components","providers","jobs","tasks","collectionConfigMap","Map","collectionConfig","set","collectionsToUpdate","filter","has","collectionPluginConfig","get","length","exportSlugForCollection","importSlugForCollection","exportDisabled","export","importDisabled","import","listMenuItems","clientProps","collectionSlug","exportCollectionSlug","path","importCollectionSlug","disabledFieldAccessors","fields","exportConfig","undefined","exportFormat","format","exportDisableJobsQueue","disableJobsQueue","exportBatchSize","batchSize","exportDisableSave","disableSave","exportDisableDownload","disableDownload","importConfig","importDisableJobsQueue","importBatchSize","exportLimit","limit","exportHooks","hooks","importLimit","importDefaultVersionStatus","defaultVersionStatus","importHooks","custom","disabledFields","i18n","supportedLanguageKeys","supportedLanguages","Object","keys","simplifiedTranslations","lang","entry"],"mappings":"AAAA,SAASA,eAAe,EAAEC,YAAY,QAAQ,UAAS;AAevD,SAASC,6BAA6B,QAAQ,4CAA2C;AACzF,SAASC,6BAA6B,QAAQ,4CAA2C;AACzF,SAASC,YAAY,QAAQ,0BAAyB;AACtD,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,oBAAoB,QAAQ,sCAAqC;AAE1E;;;;;;;;;CASC,GACD,OAAO,MAAMC,qBAAqBN,aAAuC;IACvEO,MAAM;IACNC,QAAQ,OAAO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ACC,KAAK,GAAGC,MAAMtF,YAAY;YACnD;QACF;QAEAM,OAAOyE,IAAI,GAAG;YACZ,GAAGzE,OAAOyE,IAAI;YACd/E,cAAcJ,gBAAgBwF,wBAAwB9E,OAAOyE,IAAI,EAAE/E,gBAAgB,CAAC;QACtF;QAEA,OAAOM;IACT;AACF,GAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../../src/translations/languages/en.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjD,eAAO,MAAM,cAAc
|
|
1
|
+
{"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../../src/translations/languages/en.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjD,eAAO,MAAM,cAAc;IACzB,sBAAsB;QACpB,UAAU;QACV,kBAAkB;QAClB,iBAAiB;QACjB,iBAAiB;QACjB,mBAAmB;QACnB,aAAa;QACb,4BAA4B;QAC5B,mBAAmB;QACnB,oBAAoB;QACpB,oBAAoB;QACpB,oBAAoB;QACpB,+BAA+B;QAC/B,wBAAwB;QACxB,+BAA+B;QAC/B,+BAA+B;QAC/B,mBAAmB;QACnB,oBAAoB;QACpB,8BAA8B;QAC9B,wBAAwB;QACxB,kBAAkB;QAClB,kBAAkB;QAClB,4BAA4B;QAC5B,kBAAkB;QAClB,wBAAwB;QACxB,oBAAoB;QACpB,qBAAqB;QACrB,mBAAmB;QACnB,aAAa;QACb,WAAW;QACX,mBAAmB;QACnB,mBAAmB;QACnB,OAAO;QACP,IAAI;QACJ,eAAe;QACf,eAAe;QACf,6BAA6B;QAC7B,+BAA+B;QAC/B,iCAAiC;QACjC,WAAW;QACX,mBAAmB;QACnB,sBAAsB;;CAEzB,CAAA;AAED,eAAO,MAAM,EAAE,EAAE,cAGhB,CAAA"}
|