@payloadcms/plugin-cloud-storage 4.0.0-beta.5 → 4.0.0-beta.7
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/hooks/afterDelete.js +1 -1
- package/dist/hooks/afterDelete.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utilities/createFileOperations.d.ts.map +1 -1
- package/dist/utilities/createFileOperations.js +50 -15
- package/dist/utilities/createFileOperations.js.map +1 -1
- package/dist/utilities/getFilePrefix.d.ts +3 -1
- package/dist/utilities/getFilePrefix.d.ts.map +1 -1
- package/dist/utilities/getFilePrefix.js +12 -5
- package/dist/utilities/getFilePrefix.js.map +1 -1
- package/dist/utilities/getStorageLocationSelect.js +7 -1
- package/dist/utilities/getStorageLocationSelect.js.map +1 -1
- package/dist/utilities/resolveSignedURLKey.d.ts.map +1 -1
- package/dist/utilities/resolveSignedURLKey.js +5 -15
- package/dist/utilities/resolveSignedURLKey.js.map +1 -1
- package/package.json +4 -4
|
@@ -41,7 +41,7 @@ export const getAfterDeleteHook = ({ adapter, collection, collectionPrefix, useC
|
|
|
41
41
|
} catch (err) {
|
|
42
42
|
req.payload.logger.error({
|
|
43
43
|
err,
|
|
44
|
-
msg: `There was an error while deleting files corresponding to the ${collection.labels?.singular} with ID ${doc.id}.`
|
|
44
|
+
msg: `There was an error while deleting files corresponding to the ${typeof collection.labels?.singular === 'string' ? collection.labels.singular : collection.slug} with ID ${doc.id}.`
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
47
|
return doc;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/afterDelete.ts"],"sourcesContent":["import type { CollectionAfterDeleteHook, CollectionConfig, FileData, TypeWithID } from 'payload'\n\nimport type { GeneratedAdapter, TypeWithPrefix } from '../types.js'\n\nimport { buildPrefixWithObjectKey } from '../utilities/buildPrefixWithObjectKey.js'\nimport { buildStoragePathData } from '../utilities/buildStoragePathData.js'\n\ninterface Args {\n adapter: GeneratedAdapter\n collection: CollectionConfig\n collectionPrefix?: string\n useCompositePrefixes?: boolean\n}\n\nexport const getAfterDeleteHook = ({\n adapter,\n collection,\n collectionPrefix,\n useCompositePrefixes,\n}: Args): CollectionAfterDeleteHook<FileData & TypeWithID & TypeWithPrefix> => {\n return async ({ id, doc, req }) => {\n // Managed objects are deleted after the operation commits and all references are checked.\n const managedDeletedUploads = req.context?._payloadManagedDeletedUploads as\n | Set<string>\n | undefined\n if (\n collection.versions ||\n (Boolean(doc.original) && typeof doc.original?.filename === 'string') ||\n managedDeletedUploads?.has(JSON.stringify([collection.slug, String(id)]))\n ) {\n return doc\n }\n\n try {\n // Fold `_objectKey` so deletes target the real object folder.\n const docPrefix = buildPrefixWithObjectKey({\n objectKey: (doc as { _objectKey?: string })._objectKey,\n prefix: doc.prefix,\n })\n\n const filesToDelete: string[] = [\n doc.filename,\n ...Object.values(doc?.variants || []).map(\n (resizedFileData) => resizedFileData?.filename as string,\n ),\n ]\n\n const promises = filesToDelete.map(async (filename) => {\n if (filename) {\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n await adapter.handleDelete({ collection, doc, filename, req, storageFilePath })\n }\n })\n\n await Promise.all(promises)\n } catch (err: unknown) {\n req.payload.logger.error({\n err,\n msg: `There was an error while deleting files corresponding to the ${collection.labels?.singular} with ID ${doc.id}.`,\n })\n }\n return doc\n }\n}\n"],"names":["buildPrefixWithObjectKey","buildStoragePathData","getAfterDeleteHook","adapter","collection","collectionPrefix","useCompositePrefixes","id","doc","req","managedDeletedUploads","context","_payloadManagedDeletedUploads","versions","Boolean","original","filename","has","JSON","stringify","slug","String","docPrefix","objectKey","_objectKey","prefix","filesToDelete","Object","values","variants","map","resizedFileData","promises","storageFilePath","handleDelete","Promise","all","err","payload","logger","error","msg","labels","singular"],"mappings":"AAIA,SAASA,wB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AfterDeleteHook, CollectionConfig, FileData, TypeWithID } from 'payload'\n\nimport type { GeneratedAdapter, TypeWithPrefix } from '../types.js'\n\nimport { buildPrefixWithObjectKey } from '../utilities/buildPrefixWithObjectKey.js'\nimport { buildStoragePathData } from '../utilities/buildStoragePathData.js'\n\ninterface Args {\n adapter: GeneratedAdapter\n collection: CollectionConfig\n collectionPrefix?: string\n useCompositePrefixes?: boolean\n}\n\nexport const getAfterDeleteHook = ({\n adapter,\n collection,\n collectionPrefix,\n useCompositePrefixes,\n}: Args): CollectionAfterDeleteHook<FileData & TypeWithID & TypeWithPrefix> => {\n return async ({ id, doc, req }) => {\n // Managed objects are deleted after the operation commits and all references are checked.\n const managedDeletedUploads = req.context?._payloadManagedDeletedUploads as\n | Set<string>\n | undefined\n if (\n collection.versions ||\n (Boolean(doc.original) && typeof doc.original?.filename === 'string') ||\n managedDeletedUploads?.has(JSON.stringify([collection.slug, String(id)]))\n ) {\n return doc\n }\n\n try {\n // Fold `_objectKey` so deletes target the real object folder.\n const docPrefix = buildPrefixWithObjectKey({\n objectKey: (doc as { _objectKey?: string })._objectKey,\n prefix: doc.prefix,\n })\n\n const filesToDelete: string[] = [\n doc.filename,\n ...Object.values(doc?.variants || []).map(\n (resizedFileData) => resizedFileData?.filename as string,\n ),\n ]\n\n const promises = filesToDelete.map(async (filename) => {\n if (filename) {\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n })\n await adapter.handleDelete({ collection, doc, filename, req, storageFilePath })\n }\n })\n\n await Promise.all(promises)\n } catch (err: unknown) {\n req.payload.logger.error({\n err,\n msg: `There was an error while deleting files corresponding to the ${typeof collection.labels?.singular === 'string' ? collection.labels.singular : collection.slug} with ID ${doc.id}.`,\n })\n }\n return doc\n }\n}\n"],"names":["buildPrefixWithObjectKey","buildStoragePathData","getAfterDeleteHook","adapter","collection","collectionPrefix","useCompositePrefixes","id","doc","req","managedDeletedUploads","context","_payloadManagedDeletedUploads","versions","Boolean","original","filename","has","JSON","stringify","slug","String","docPrefix","objectKey","_objectKey","prefix","filesToDelete","Object","values","variants","map","resizedFileData","promises","storageFilePath","handleDelete","Promise","all","err","payload","logger","error","msg","labels","singular"],"mappings":"AAIA,SAASA,wBAAwB,QAAQ,2CAA0C;AACnF,SAASC,oBAAoB,QAAQ,uCAAsC;AAS3E,OAAO,MAAMC,qBAAqB,CAAC,EACjCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,oBAAoB,EACf;IACL,OAAO,OAAO,EAAEC,EAAE,EAAEC,GAAG,EAAEC,GAAG,EAAE;QAC5B,0FAA0F;QAC1F,MAAMC,wBAAwBD,IAAIE,OAAO,EAAEC;QAG3C,IACER,WAAWS,QAAQ,IAClBC,QAAQN,IAAIO,QAAQ,KAAK,OAAOP,IAAIO,QAAQ,EAAEC,aAAa,YAC5DN,uBAAuBO,IAAIC,KAAKC,SAAS,CAAC;YAACf,WAAWgB,IAAI;YAAEC,OAAOd;SAAI,IACvE;YACA,OAAOC;QACT;QAEA,IAAI;YACF,8DAA8D;YAC9D,MAAMc,YAAYtB,yBAAyB;gBACzCuB,WAAW,AAACf,IAAgCgB,UAAU;gBACtDC,QAAQjB,IAAIiB,MAAM;YACpB;YAEA,MAAMC,gBAA0B;gBAC9BlB,IAAIQ,QAAQ;mBACTW,OAAOC,MAAM,CAACpB,KAAKqB,YAAY,EAAE,EAAEC,GAAG,CACvC,CAACC,kBAAoBA,iBAAiBf;aAEzC;YAED,MAAMgB,WAAWN,cAAcI,GAAG,CAAC,OAAOd;gBACxC,IAAIA,UAAU;oBACZ,MAAM,EAAEiB,eAAe,EAAE,GAAGhC,qBAAqB;wBAC/CI;wBACAiB;wBACAN;wBACAV;oBACF;oBACA,MAAMH,QAAQ+B,YAAY,CAAC;wBAAE9B;wBAAYI;wBAAKQ;wBAAUP;wBAAKwB;oBAAgB;gBAC/E;YACF;YAEA,MAAME,QAAQC,GAAG,CAACJ;QACpB,EAAE,OAAOK,KAAc;YACrB5B,IAAI6B,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;gBACvBH;gBACAI,KAAK,CAAC,6DAA6D,EAAE,OAAOrC,WAAWsC,MAAM,EAAEC,aAAa,WAAWvC,WAAWsC,MAAM,CAACC,QAAQ,GAAGvC,WAAWgB,IAAI,CAAC,SAAS,EAAEZ,IAAID,EAAE,CAAC,CAAC,CAAC;YAC1L;QACF;QACA,OAAOC;IACT;AACF,EAAC"}
|
package/dist/types.d.ts
CHANGED
|
@@ -77,6 +77,8 @@ export type StaticHandler = (req: PayloadRequest, args: {
|
|
|
77
77
|
params: {
|
|
78
78
|
collection: string;
|
|
79
79
|
filename: string;
|
|
80
|
+
/** True when the request asks for the original with `?original=true`. */
|
|
81
|
+
isOriginal?: boolean;
|
|
80
82
|
operation?: FileHandlerOperation;
|
|
81
83
|
prefix?: string;
|
|
82
84
|
uploadReference?: unknown;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,KAAK,EACL,QAAQ,EACR,oBAAoB,EACpB,SAAS,EACT,cAAc,EACd,cAAc,EACd,yBAAyB,EACzB,UAAU,EACV,oBAAoB,EACpB,wBAAwB,EACxB,4BAA4B,EAC7B,MAAM,SAAS,CAAA;AAEhB,YAAY,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,MAAM,WAAW,IAAI;IACnB,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,MAAM,mBAAmB,GAAG;IAAE,MAAM,CAAC,EAAE,wBAAwB,CAAA;CAAE,GA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AC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAA;AAE9B,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,2BAA2B,CAAC,EAAE,IAAI,CAAA;IAClC,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,iBAAiB,CAAC,CAAC,CAAA;IACrE;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;;;OAQG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Field,\n FileData,\n FileHandlerOperation,\n ImageSize,\n PayloadHandler,\n PayloadRequest,\n SanitizedCollectionConfig,\n TypeWithID,\n UploadCollectionSlug,\n UploadInstructionsAccess,\n UploadInstructionsCapability,\n} from 'payload'\n\nexport type { FileHandlerOperation } from 'payload'\n\nexport interface File {\n buffer: Buffer\n filename: string\n filesize: number\n mimeType: string\n tempFilePath?: string\n uploadReference?: unknown\n}\n\nexport type ClientUploadsConfig = { access?: UploadInstructionsAccess } | boolean\n\n/**\n * Reference to a client-uploaded object, returned by an upload handler and\n * submitted with the document. Always carries the signed receipt; `prefix`\n * locates the stored object.\n */\nexport type UploadReference = {\n _objectKey?: string\n /** Data the adapter signed into the receipt with `resolveSignedURLKey`. Not stored on the document. */\n adapterData?: Record<string, unknown>\n /** Fields the client added to `uploadReference`. Not verified; check them before use. */\n clientData?: Record<string, unknown>\n prefix: string\n signedReceipt: `${string}.${string}`\n}\n\nexport type HandleUpload = (args: {\n collection: CollectionConfig\n data: any\n file: File\n req: PayloadRequest\n /**\n * Pre-resolved storage path (`_objectKey` folded in, contained beneath the collection prefix).\n */\n storageFilePath: string\n}) =>\n | Partial<FileData & TypeWithID>\n | Promise<Partial<FileData & TypeWithID>>\n | Promise<void>\n | void\n\nexport interface TypeWithPrefix {\n prefix?: string\n}\n\nexport type HandleDelete = (args: {\n collection: CollectionConfig\n doc: FileData & TypeWithID & TypeWithPrefix\n filename: string\n req: PayloadRequest\n /**\n * Pre-resolved storage path of the object to delete.\n */\n storageFilePath: string\n}) => Promise<void> | void\n\n/** Deletes a stored object without requiring a saved document. */\nexport type DeleteFile = (args: {\n collection: CollectionConfig\n req: PayloadRequest\n /** Complete storage path, with prefixes and `_objectKey` already resolved. */\n storageFilePath: string\n}) => Promise<void> | void\n\n/** Complete storage keys are resolved before invoking a provider operation. */\nexport type FileOperationArgs = {\n collection: SanitizedCollectionConfig\n from: string\n mimeType?: string\n req: PayloadRequest\n to: string\n}\n\nexport type CopyFile = (args: FileOperationArgs) => Promise<void>\nexport type MoveFile = (args: FileOperationArgs) => Promise<void>\n\nexport type GenerateURL = (args: {\n collection: CollectionConfig\n data: any\n filename: string\n prefix?: string\n}) => Promise<string> | string\n\nexport type StaticHandler = (\n req: PayloadRequest,\n args: {\n doc?: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n) => Promise<Response> | Response\n\nexport interface GeneratedAdapter {\n /** Preserve object metadata and fail if `to` already exists. Rename retains `from` for history. */\n copyFile: CopyFile\n deleteFile: DeleteFile\n /**\n * Additional fields to be injected into the base collection and image sizes\n */\n fields?: Field[]\n /**\n * Generates the public URL for a file\n */\n generateURL?: GenerateURL\n handleDelete: HandleDelete\n handleUpload: HandleUpload\n moveFile?: MoveFile\n name: string\n onInit?: () => Promise<void> | void\n staticHandler: StaticHandler\n /** Reads source files by path when staging server-mediated uploads. */\n supportsTempFiles?: boolean\n /** Generates upload instructions when supported. */\n uploadInstructions?: {\n adminHandler?: {\n path: string\n props?: Record<string, unknown>\n }\n enabled: boolean\n endpoint?: {\n handler: PayloadHandler\n path: `/${string}`\n }\n } & UploadInstructionsCapability\n}\n\nexport type Adapter = (args: { collection: CollectionConfig; prefix?: string }) => GeneratedAdapter\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type GenerateFileURL = (args: {\n collection: CollectionConfig\n filename: string\n prefix?: string\n size?: ImageSize\n}) => Promise<string> | string\n\nexport interface CollectionOptions {\n adapter: Adapter | null\n disableLocalStorage?: boolean\n disablePayloadAccessControl?: true\n generateFileURL?: GenerateFileURL\n prefix?: string\n}\n\nexport interface PluginOptions {\n collections: Partial<Record<UploadCollectionSlug, CollectionOptions>>\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * When true (compositional prefixes), the stored `prefix` field is only the\n * document-level segment; the collection prefix comes from plugin options and\n * must not be pre-filled as the field default.\n *\n * Set by storage adapters that support compositional prefixes (e.g. S3, Azure, R2, Vercel Blob, GCS).\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Field,\n FileData,\n FileHandlerOperation,\n ImageSize,\n PayloadHandler,\n PayloadRequest,\n SanitizedCollectionConfig,\n TypeWithID,\n UploadCollectionSlug,\n UploadInstructionsAccess,\n UploadInstructionsCapability,\n} from 'payload'\n\nexport type { FileHandlerOperation } from 'payload'\n\nexport interface File {\n buffer: Buffer\n filename: string\n filesize: number\n mimeType: string\n tempFilePath?: string\n uploadReference?: unknown\n}\n\nexport type ClientUploadsConfig = { access?: UploadInstructionsAccess } | boolean\n\n/**\n * Reference to a client-uploaded object, returned by an upload handler and\n * submitted with the document. Always carries the signed receipt; `prefix`\n * locates the stored object.\n */\nexport type UploadReference = {\n _objectKey?: string\n /** Data the adapter signed into the receipt with `resolveSignedURLKey`. Not stored on the document. */\n adapterData?: Record<string, unknown>\n /** Fields the client added to `uploadReference`. Not verified; check them before use. */\n clientData?: Record<string, unknown>\n prefix: string\n signedReceipt: `${string}.${string}`\n}\n\nexport type HandleUpload = (args: {\n collection: CollectionConfig\n data: any\n file: File\n req: PayloadRequest\n /**\n * Pre-resolved storage path (`_objectKey` folded in, contained beneath the collection prefix).\n */\n storageFilePath: string\n}) =>\n | Partial<FileData & TypeWithID>\n | Promise<Partial<FileData & TypeWithID>>\n | Promise<void>\n | void\n\nexport interface TypeWithPrefix {\n prefix?: string\n}\n\nexport type HandleDelete = (args: {\n collection: CollectionConfig\n doc: FileData & TypeWithID & TypeWithPrefix\n filename: string\n req: PayloadRequest\n /**\n * Pre-resolved storage path of the object to delete.\n */\n storageFilePath: string\n}) => Promise<void> | void\n\n/** Deletes a stored object without requiring a saved document. */\nexport type DeleteFile = (args: {\n collection: CollectionConfig\n req: PayloadRequest\n /** Complete storage path, with prefixes and `_objectKey` already resolved. */\n storageFilePath: string\n}) => Promise<void> | void\n\n/** Complete storage keys are resolved before invoking a provider operation. */\nexport type FileOperationArgs = {\n collection: SanitizedCollectionConfig\n from: string\n mimeType?: string\n req: PayloadRequest\n to: string\n}\n\nexport type CopyFile = (args: FileOperationArgs) => Promise<void>\nexport type MoveFile = (args: FileOperationArgs) => Promise<void>\n\nexport type GenerateURL = (args: {\n collection: CollectionConfig\n data: any\n filename: string\n prefix?: string\n}) => Promise<string> | string\n\nexport type StaticHandler = (\n req: PayloadRequest,\n args: {\n doc?: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n /** True when the request asks for the original with `?original=true`. */\n isOriginal?: boolean\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n) => Promise<Response> | Response\n\nexport interface GeneratedAdapter {\n /** Preserve object metadata and fail if `to` already exists. Rename retains `from` for history. */\n copyFile: CopyFile\n deleteFile: DeleteFile\n /**\n * Additional fields to be injected into the base collection and image sizes\n */\n fields?: Field[]\n /**\n * Generates the public URL for a file\n */\n generateURL?: GenerateURL\n handleDelete: HandleDelete\n handleUpload: HandleUpload\n moveFile?: MoveFile\n name: string\n onInit?: () => Promise<void> | void\n staticHandler: StaticHandler\n /** Reads source files by path when staging server-mediated uploads. */\n supportsTempFiles?: boolean\n /** Generates upload instructions when supported. */\n uploadInstructions?: {\n adminHandler?: {\n path: string\n props?: Record<string, unknown>\n }\n enabled: boolean\n endpoint?: {\n handler: PayloadHandler\n path: `/${string}`\n }\n } & UploadInstructionsCapability\n}\n\nexport type Adapter = (args: { collection: CollectionConfig; prefix?: string }) => GeneratedAdapter\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type GenerateFileURL = (args: {\n collection: CollectionConfig\n filename: string\n prefix?: string\n size?: ImageSize\n}) => Promise<string> | string\n\nexport interface CollectionOptions {\n adapter: Adapter | null\n disableLocalStorage?: boolean\n disablePayloadAccessControl?: true\n generateFileURL?: GenerateFileURL\n prefix?: string\n}\n\nexport interface PluginOptions {\n collections: Partial<Record<UploadCollectionSlug, CollectionOptions>>\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * When true (compositional prefixes), the stored `prefix` field is only the\n * document-level segment; the collection prefix comes from plugin options and\n * must not be pre-filled as the field default.\n *\n * Set by storage adapters that support compositional prefixes (e.g. S3, Azure, R2, Vercel Blob, GCS).\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n"],"names":[],"mappings":"AAgLA,WAkBC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createFileOperations.d.ts","sourceRoot":"","sources":["../../src/utilities/createFileOperations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"createFileOperations.d.ts","sourceRoot":"","sources":["../../src/utilities/createFileOperations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAqC,YAAY,EAAE,MAAM,SAAS,CAAA;AAOhG,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AASpE,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,gBAAgB,CAAA;IACzB,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,2BAA2B,CAAC,EAAE,OAAO,CAAA;IACrC,eAAe,CAAC,EAAE,eAAe,CAAA;IACjC,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AAED,eAAO,MAAM,oBAAoB,mHAO9B,IAAI,KAAG,WAAW,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAmOnD,CAAA"}
|
|
@@ -122,21 +122,16 @@ export const createFileOperations = ({ adapter, collection, collectionPrefix, di
|
|
|
122
122
|
}
|
|
123
123
|
},
|
|
124
124
|
stage: async ({ data, files, req, trackStagedObject })=>{
|
|
125
|
-
const
|
|
125
|
+
const uploadedKeys = new Set();
|
|
126
126
|
const metadata = {};
|
|
127
127
|
const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal;
|
|
128
128
|
for (const file of files){
|
|
129
129
|
const filename = path.basename(file.path);
|
|
130
|
-
const
|
|
131
|
-
data
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
if (data.variants && typeof data.variants === 'object') {
|
|
137
|
-
representations.push(...Object.values(data.variants).filter((value)=>Boolean(value) && typeof value === 'object'));
|
|
138
|
-
}
|
|
139
|
-
const destinations = representations.filter((value)=>value.filename === filename);
|
|
130
|
+
const destinations = getStageDestinations({
|
|
131
|
+
data,
|
|
132
|
+
file,
|
|
133
|
+
filename
|
|
134
|
+
});
|
|
140
135
|
// Provider-direct uploads already placed the source object at its verified location.
|
|
141
136
|
// A bounded content probe can still appear in files, but it is not a representation
|
|
142
137
|
// Payload should upload again.
|
|
@@ -174,10 +169,10 @@ export const createFileOperations = ({ adapter, collection, collectionPrefix, di
|
|
|
174
169
|
filename,
|
|
175
170
|
useCompositePrefixes
|
|
176
171
|
}).storageFilePath;
|
|
177
|
-
if (
|
|
178
|
-
throw new Error(`Duplicate managed cloud
|
|
172
|
+
if (uploadedKeys.has(storageFilePath)) {
|
|
173
|
+
throw new Error(`Duplicate managed cloud file: ${storageFilePath}`);
|
|
179
174
|
}
|
|
180
|
-
|
|
175
|
+
uploadedKeys.add(storageFilePath);
|
|
181
176
|
const buffer = 'buffer' in file ? file.buffer : adapter.supportsTempFiles ? Buffer.alloc(0) : await fs.readFile(file.sourcePath);
|
|
182
177
|
const uploadFile = {
|
|
183
178
|
buffer,
|
|
@@ -185,6 +180,7 @@ export const createFileOperations = ({ adapter, collection, collectionPrefix, di
|
|
|
185
180
|
filesize: 'buffer' in file ? file.buffer.length : (await fs.stat(file.sourcePath)).size,
|
|
186
181
|
mimeType: getMimeType({
|
|
187
182
|
data,
|
|
183
|
+
destination: destinations[0],
|
|
188
184
|
filename
|
|
189
185
|
}),
|
|
190
186
|
...'sourcePath' in file ? {
|
|
@@ -228,7 +224,46 @@ export const createFileOperations = ({ adapter, collection, collectionPrefix, di
|
|
|
228
224
|
}
|
|
229
225
|
};
|
|
230
226
|
};
|
|
231
|
-
|
|
227
|
+
/**
|
|
228
|
+
* The document fields a staged file is stored for. The file's role names its field, because the
|
|
229
|
+
* main file and the original can share a filename in different folders. Fields with the same
|
|
230
|
+
* filename and `_objectKey` describe the same object, so they share its location.
|
|
231
|
+
*/ const getStageDestinations = ({ data, file, filename })=>{
|
|
232
|
+
const representations = [
|
|
233
|
+
data
|
|
234
|
+
];
|
|
235
|
+
if (data.original && typeof data.original === 'object') {
|
|
236
|
+
representations.push(data.original);
|
|
237
|
+
}
|
|
238
|
+
if (data.variants && typeof data.variants === 'object') {
|
|
239
|
+
representations.push(...Object.values(data.variants).filter((value)=>Boolean(value) && typeof value === 'object'));
|
|
240
|
+
}
|
|
241
|
+
const namedDestinations = representations.filter((value)=>value.filename === filename);
|
|
242
|
+
const roleDestination = file.role ? getRoleRepresentation({
|
|
243
|
+
data,
|
|
244
|
+
role: file.role
|
|
245
|
+
}) : undefined;
|
|
246
|
+
if (roleDestination?.filename !== filename) {
|
|
247
|
+
return namedDestinations;
|
|
248
|
+
}
|
|
249
|
+
return [
|
|
250
|
+
roleDestination,
|
|
251
|
+
...namedDestinations.filter((value)=>value !== roleDestination && value._objectKey === roleDestination._objectKey)
|
|
252
|
+
];
|
|
253
|
+
};
|
|
254
|
+
const getRoleRepresentation = ({ data, role })=>{
|
|
255
|
+
let representation = data;
|
|
256
|
+
if (role.type === 'original') {
|
|
257
|
+
representation = data.original;
|
|
258
|
+
} else if (role.type === 'size') {
|
|
259
|
+
representation = data.variants?.[role.sizeKey];
|
|
260
|
+
}
|
|
261
|
+
return representation && typeof representation === 'object' ? representation : undefined;
|
|
262
|
+
};
|
|
263
|
+
const getMimeType = ({ data, destination, filename })=>{
|
|
264
|
+
if (typeof destination.mimeType === 'string') {
|
|
265
|
+
return destination.mimeType;
|
|
266
|
+
}
|
|
232
267
|
if (data.original && typeof data.original === 'object') {
|
|
233
268
|
const original = data.original;
|
|
234
269
|
if (original.filename === filename && original.mimeType) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/createFileOperations.ts"],"sourcesContent":["import type { CollectionConfig, ImageSize, JsonObject, UploadConfig } from 'payload'\n\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\nimport { deepCopyObjectSimple, generatePayloadFileURL } from 'payload'\n\nimport type { GeneratedAdapter, GenerateFileURL } from '../types.js'\n\nimport { buildPrefixWithObjectKey } from './buildPrefixWithObjectKey.js'\nimport {\n buildStoragePathData,\n buildUploadPrefix,\n buildUploadStoragePathData,\n} from './buildStoragePathData.js'\n\ntype Args = {\n adapter: GeneratedAdapter\n collection: CollectionConfig\n collectionPrefix?: string\n disablePayloadAccessControl?: boolean\n generateFileURL?: GenerateFileURL\n useCompositePrefixes?: boolean\n}\n\nexport const createFileOperations = ({\n adapter,\n collection,\n collectionPrefix,\n disablePayloadAccessControl,\n generateFileURL,\n useCompositePrefixes,\n}: Args): NonNullable<UploadConfig['fileOperations']> => {\n if (typeof adapter.deleteFile !== 'function') {\n throw new Error(\n `Storage adapter \"${adapter.name}\" must implement deleteFile for collection \"${collection.slug}\".`,\n )\n }\n\n return {\n copy: async ({ from, req, to, trackStagedObject }) => {\n await adapter.copyFile({\n collection: req.payload.collections[collection.slug]!.config,\n from,\n req,\n to,\n })\n trackStagedObject({\n key: to,\n remove: async () => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath: to,\n })\n },\n })\n },\n delete: async ({ key, req }) => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath: key,\n })\n },\n hasLegacyFile: async ({ doc, req }) => {\n if (typeof doc.filename !== 'string' || typeof doc.url !== 'string') {\n return false\n }\n\n const docPrefix = typeof doc.prefix === 'string' ? doc.prefix : undefined\n const objectFolder = buildPrefixWithObjectKey({\n objectKey: typeof doc._objectKey === 'string' ? doc._objectKey : undefined,\n prefix: docPrefix,\n })\n const expectedURL = async ({ filename, size }: { filename: string; size?: ImageSize }) => {\n if (generateFileURL) {\n return generateFileURL({ collection, filename, prefix: objectFolder, size })\n }\n if (disablePayloadAccessControl && adapter.generateURL) {\n return adapter.generateURL({ collection, data: doc, filename, prefix: objectFolder })\n }\n return generatePayloadFileURL({\n collectionSlug: collection.slug,\n config: req.payload.config as unknown as Parameters<\n typeof generatePayloadFileURL\n >[0]['config'],\n filename,\n relative: true,\n })\n }\n if (\n !isSameFileLocation({\n actual: doc.url,\n expected: await expectedURL({ filename: doc.filename }),\n })\n ) {\n return false\n }\n if (doc.variants && typeof doc.variants === 'object' && !Array.isArray(doc.variants)) {\n for (const [sizeKey, size] of Object.entries(doc.variants)) {\n if (\n size &&\n typeof size === 'object' &&\n 'filename' in size &&\n typeof size.filename === 'string'\n ) {\n const imageSize = req.payload.collections[\n collection.slug\n ]?.config.upload.variants?.find(({ name }) => name === sizeKey)\n if (\n !('url' in size) ||\n typeof size.url !== 'string' ||\n !isSameFileLocation({\n actual: size.url,\n expected: await expectedURL({ filename: size.filename, size: imageSize }),\n })\n ) {\n return false\n }\n }\n }\n }\n return true\n },\n resolveStorageKey: ({ _objectKey, filename, prefix }) =>\n buildStoragePathData({\n collectionPrefix,\n docPrefix: buildPrefixWithObjectKey({ objectKey: _objectKey, prefix }),\n filename,\n useCompositePrefixes,\n }).storageFilePath,\n ...(adapter.moveFile && {\n move: async ({ from, req, to, trackStagedObject }) => {\n await adapter.moveFile!({\n collection: req.payload.collections[collection.slug]!.config,\n from,\n req,\n to,\n })\n trackStagedObject({\n key: to,\n remove: () =>\n adapter.moveFile!({\n collection: req.payload.collections[collection.slug]!.config,\n from: to,\n req,\n to: from,\n }),\n })\n },\n }),\n stage: async ({ data, files, req, trackStagedObject }) => {\n const uploadedNames = new Set<string>()\n const metadata: Record<string, unknown> = {}\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { filename: string }\n | undefined\n for (const file of files) {\n const filename = path.basename(file.path)\n const representations: Record<string, unknown>[] = [data]\n if (data.original && typeof data.original === 'object') {\n representations.push(data.original as Record<string, unknown>)\n }\n if (data.variants && typeof data.variants === 'object') {\n representations.push(\n ...Object.values(data.variants).filter(\n (value): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object',\n ),\n )\n }\n const destinations = representations.filter((value) => value.filename === filename)\n // Provider-direct uploads already placed the source object at its verified location.\n // A bounded content probe can still appear in files, but it is not a representation\n // Payload should upload again.\n if (!destinations.length && verifiedOriginal) {\n continue\n }\n if (!destinations.length) {\n throw new Error(`No stored representation describes ${filename}`)\n }\n const prefixLocation = destinations.find(\n (destination) => typeof destination.prefix === 'string',\n )\n const objectKeyLocation = destinations.find(\n (destination) => typeof destination._objectKey === 'string',\n )\n const prefix =\n typeof prefixLocation?.prefix === 'string' ? prefixLocation.prefix : undefined\n const objectKey =\n typeof objectKeyLocation?._objectKey === 'string'\n ? objectKeyLocation._objectKey\n : undefined\n const prefixData = buildUploadPrefix({\n collectionPrefix,\n docPrefix: typeof prefix === 'string' ? prefix : undefined,\n useCompositePrefixes,\n })\n const uploadPrefix = useCompositePrefixes\n ? prefixData.sanitizedDocPrefix\n : prefixData.uploadPrefix\n for (const destination of destinations) {\n destination.prefix = uploadPrefix\n destination._objectKey = objectKey\n }\n const docPrefix = buildPrefixWithObjectKey({ objectKey, prefix: uploadPrefix })\n const dataForUpload = { ...data, prefix: docPrefix }\n const storageFilePath = buildUploadStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n }).storageFilePath\n\n if (uploadedNames.has(filename)) {\n throw new Error(`Duplicate managed cloud filename: ${filename}`)\n }\n\n uploadedNames.add(filename)\n const buffer =\n 'buffer' in file\n ? file.buffer\n : adapter.supportsTempFiles\n ? Buffer.alloc(0)\n : await fs.readFile(file.sourcePath)\n const uploadFile = {\n buffer,\n filename,\n filesize: 'buffer' in file ? file.buffer.length : (await fs.stat(file.sourcePath)).size,\n mimeType: getMimeType({ data, filename }),\n ...('sourcePath' in file ? { tempFilePath: file.sourcePath } : {}),\n }\n\n // A new object folder is allocated for every server upload, so an interrupted\n // provider write can be removed without touching an earlier revision.\n trackStagedObject({\n key: storageFilePath,\n remove: async () => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath,\n })\n },\n })\n\n const dataBeforeUpload = deepCopyObjectSimple(dataForUpload as JsonObject)\n const result = await adapter.handleUpload({\n collection,\n data: dataForUpload,\n file: uploadFile,\n req,\n storageFilePath,\n })\n\n if (result && typeof result === 'object') {\n // Adapters may return the entire input document, including fields made stale by this upload.\n for (const [key, value] of Object.entries(result)) {\n if (!isDeepStrictEqual(value, dataBeforeUpload[key])) {\n metadata[key] = value\n }\n }\n }\n }\n\n delete metadata.prefix\n delete metadata._objectKey\n return { metadata }\n },\n }\n}\n\nconst getMimeType = ({\n data,\n filename,\n}: {\n data: Record<string, unknown>\n filename: string\n}): string => {\n if (data.original && typeof data.original === 'object') {\n const original = data.original as { filename?: string; mimeType?: string }\n if (original.filename === filename && original.mimeType) {\n return original.mimeType\n }\n }\n if (data.variants && typeof data.variants === 'object') {\n for (const size of Object.values(data.variants)) {\n const candidate = size as { filename?: string; mimeType?: string } | null\n if (candidate?.filename === filename && candidate.mimeType) {\n return candidate.mimeType\n }\n }\n }\n return typeof data.mimeType === 'string' ? data.mimeType : 'application/octet-stream'\n}\n\n/** Signed and time-limited URLs change their query on every generation, so only the location is compared. */\nconst isSameFileLocation = ({\n actual,\n expected,\n}: {\n actual: string\n expected: null | string | undefined\n}): boolean =>\n typeof expected === 'string' &&\n getFileLocation({ url: actual }) === getFileLocation({ url: expected })\n\nconst getFileLocation = ({ url }: { url: string }): string => {\n const parsed = new URL(url, 'http://payload.local')\n\n return url.startsWith('/') ? parsed.pathname : `${parsed.origin}${parsed.pathname}`\n}\n"],"names":["fs","path","isDeepStrictEqual","deepCopyObjectSimple","generatePayloadFileURL","buildPrefixWithObjectKey","buildStoragePathData","buildUploadPrefix","buildUploadStoragePathData","createFileOperations","adapter","collection","collectionPrefix","disablePayloadAccessControl","generateFileURL","useCompositePrefixes","deleteFile","Error","name","slug","copy","from","req","to","trackStagedObject","copyFile","payload","collections","config","key","remove","storageFilePath","delete","hasLegacyFile","doc","filename","url","docPrefix","prefix","undefined","objectFolder","objectKey","_objectKey","expectedURL","size","generateURL","data","collectionSlug","relative","isSameFileLocation","actual","expected","variants","Array","isArray","sizeKey","Object","entries","imageSize","upload","find","resolveStorageKey","moveFile","move","stage","files","uploadedNames","Set","metadata","verifiedOriginal","context","_payloadVerifiedProviderOriginal","file","basename","representations","original","push","values","filter","value","Boolean","destinations","length","prefixLocation","destination","objectKeyLocation","prefixData","uploadPrefix","sanitizedDocPrefix","dataForUpload","has","add","buffer","supportsTempFiles","Buffer","alloc","readFile","sourcePath","uploadFile","filesize","stat","mimeType","getMimeType","tempFilePath","dataBeforeUpload","result","handleUpload","candidate","getFileLocation","parsed","URL","startsWith","pathname","origin"],"mappings":"AAEA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAC5B,SAASC,iBAAiB,QAAQ,YAAW;AAC7C,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,UAAS;AAItE,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,0BAA0B,QACrB,4BAA2B;AAWlC,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,2BAA2B,EAC3BC,eAAe,EACfC,oBAAoB,EACf;IACL,IAAI,OAAOL,QAAQM,UAAU,KAAK,YAAY;QAC5C,MAAM,IAAIC,MACR,CAAC,iBAAiB,EAAEP,QAAQQ,IAAI,CAAC,4CAA4C,EAAEP,WAAWQ,IAAI,CAAC,EAAE,CAAC;IAEtG;IAEA,OAAO;QACLC,MAAM,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAEC,EAAE,EAAEC,iBAAiB,EAAE;YAC/C,MAAMd,QAAQe,QAAQ,CAAC;gBACrBd,YAAYW,IAAII,OAAO,CAACC,WAAW,CAAChB,WAAWQ,IAAI,CAAC,CAAES,MAAM;gBAC5DP;gBACAC;gBACAC;YACF;YACAC,kBAAkB;gBAChBK,KAAKN;gBACLO,QAAQ;oBACN,MAAMpB,QAAQM,UAAU,CAAC;wBACvBL;wBACAW;wBACAS,iBAAiBR;oBACnB;gBACF;YACF;QACF;QACAS,QAAQ,OAAO,EAAEH,GAAG,EAAEP,GAAG,EAAE;YACzB,MAAMZ,QAAQM,UAAU,CAAC;gBACvBL;gBACAW;gBACAS,iBAAiBF;YACnB;QACF;QACAI,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AC,EAAExE,GAAG,EAAmB;IAC/C,MAAMyE,SAAS,IAAIC,IAAI1E,KAAK;IAE5B,OAAOA,IAAI2E,UAAU,CAAC,OAAOF,OAAOG,QAAQ,GAAG,GAAGH,OAAOI,MAAM,GAAGJ,OAAOG,QAAQ,EAAE;AACrF"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/createFileOperations.ts"],"sourcesContent":["import type { CollectionConfig, FileToSave, ImageSize, JsonObject, UploadConfig } from 'payload'\n\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\nimport { deepCopyObjectSimple, generatePayloadFileURL } from 'payload'\n\nimport type { GeneratedAdapter, GenerateFileURL } from '../types.js'\n\nimport { buildPrefixWithObjectKey } from './buildPrefixWithObjectKey.js'\nimport {\n buildStoragePathData,\n buildUploadPrefix,\n buildUploadStoragePathData,\n} from './buildStoragePathData.js'\n\ntype Args = {\n adapter: GeneratedAdapter\n collection: CollectionConfig\n collectionPrefix?: string\n disablePayloadAccessControl?: boolean\n generateFileURL?: GenerateFileURL\n useCompositePrefixes?: boolean\n}\n\nexport const createFileOperations = ({\n adapter,\n collection,\n collectionPrefix,\n disablePayloadAccessControl,\n generateFileURL,\n useCompositePrefixes,\n}: Args): NonNullable<UploadConfig['fileOperations']> => {\n if (typeof adapter.deleteFile !== 'function') {\n throw new Error(\n `Storage adapter \"${adapter.name}\" must implement deleteFile for collection \"${collection.slug}\".`,\n )\n }\n\n return {\n copy: async ({ from, req, to, trackStagedObject }) => {\n await adapter.copyFile({\n collection: req.payload.collections[collection.slug]!.config,\n from,\n req,\n to,\n })\n trackStagedObject({\n key: to,\n remove: async () => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath: to,\n })\n },\n })\n },\n delete: async ({ key, req }) => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath: key,\n })\n },\n hasLegacyFile: async ({ doc, req }) => {\n if (typeof doc.filename !== 'string' || typeof doc.url !== 'string') {\n return false\n }\n\n const docPrefix = typeof doc.prefix === 'string' ? doc.prefix : undefined\n const objectFolder = buildPrefixWithObjectKey({\n objectKey: typeof doc._objectKey === 'string' ? doc._objectKey : undefined,\n prefix: docPrefix,\n })\n const expectedURL = async ({ filename, size }: { filename: string; size?: ImageSize }) => {\n if (generateFileURL) {\n return generateFileURL({ collection, filename, prefix: objectFolder, size })\n }\n if (disablePayloadAccessControl && adapter.generateURL) {\n return adapter.generateURL({ collection, data: doc, filename, prefix: objectFolder })\n }\n return generatePayloadFileURL({\n collectionSlug: collection.slug,\n config: req.payload.config as unknown as Parameters<\n typeof generatePayloadFileURL\n >[0]['config'],\n filename,\n relative: true,\n })\n }\n if (\n !isSameFileLocation({\n actual: doc.url,\n expected: await expectedURL({ filename: doc.filename }),\n })\n ) {\n return false\n }\n if (doc.variants && typeof doc.variants === 'object' && !Array.isArray(doc.variants)) {\n for (const [sizeKey, size] of Object.entries(doc.variants)) {\n if (\n size &&\n typeof size === 'object' &&\n 'filename' in size &&\n typeof size.filename === 'string'\n ) {\n const imageSize = req.payload.collections[\n collection.slug\n ]?.config.upload.variants?.find(({ name }) => name === sizeKey)\n if (\n !('url' in size) ||\n typeof size.url !== 'string' ||\n !isSameFileLocation({\n actual: size.url,\n expected: await expectedURL({ filename: size.filename, size: imageSize }),\n })\n ) {\n return false\n }\n }\n }\n }\n return true\n },\n resolveStorageKey: ({ _objectKey, filename, prefix }) =>\n buildStoragePathData({\n collectionPrefix,\n docPrefix: buildPrefixWithObjectKey({ objectKey: _objectKey, prefix }),\n filename,\n useCompositePrefixes,\n }).storageFilePath,\n ...(adapter.moveFile && {\n move: async ({ from, req, to, trackStagedObject }) => {\n await adapter.moveFile!({\n collection: req.payload.collections[collection.slug]!.config,\n from,\n req,\n to,\n })\n trackStagedObject({\n key: to,\n remove: () =>\n adapter.moveFile!({\n collection: req.payload.collections[collection.slug]!.config,\n from: to,\n req,\n to: from,\n }),\n })\n },\n }),\n stage: async ({ data, files, req, trackStagedObject }) => {\n const uploadedKeys = new Set<string>()\n const metadata: Record<string, unknown> = {}\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { filename: string }\n | undefined\n for (const file of files) {\n const filename = path.basename(file.path)\n const destinations = getStageDestinations({ data, file, filename })\n // Provider-direct uploads already placed the source object at its verified location.\n // A bounded content probe can still appear in files, but it is not a representation\n // Payload should upload again.\n if (!destinations.length && verifiedOriginal) {\n continue\n }\n if (!destinations.length) {\n throw new Error(`No stored representation describes ${filename}`)\n }\n const prefixLocation = destinations.find(\n (destination) => typeof destination.prefix === 'string',\n )\n const objectKeyLocation = destinations.find(\n (destination) => typeof destination._objectKey === 'string',\n )\n const prefix =\n typeof prefixLocation?.prefix === 'string' ? prefixLocation.prefix : undefined\n const objectKey =\n typeof objectKeyLocation?._objectKey === 'string'\n ? objectKeyLocation._objectKey\n : undefined\n const prefixData = buildUploadPrefix({\n collectionPrefix,\n docPrefix: typeof prefix === 'string' ? prefix : undefined,\n useCompositePrefixes,\n })\n const uploadPrefix = useCompositePrefixes\n ? prefixData.sanitizedDocPrefix\n : prefixData.uploadPrefix\n for (const destination of destinations) {\n destination.prefix = uploadPrefix\n destination._objectKey = objectKey\n }\n const docPrefix = buildPrefixWithObjectKey({ objectKey, prefix: uploadPrefix })\n const dataForUpload = { ...data, prefix: docPrefix }\n const storageFilePath = buildUploadStoragePathData({\n collectionPrefix,\n docPrefix,\n filename,\n useCompositePrefixes,\n }).storageFilePath\n\n if (uploadedKeys.has(storageFilePath)) {\n throw new Error(`Duplicate managed cloud file: ${storageFilePath}`)\n }\n\n uploadedKeys.add(storageFilePath)\n const buffer =\n 'buffer' in file\n ? file.buffer\n : adapter.supportsTempFiles\n ? Buffer.alloc(0)\n : await fs.readFile(file.sourcePath)\n const uploadFile = {\n buffer,\n filename,\n filesize: 'buffer' in file ? file.buffer.length : (await fs.stat(file.sourcePath)).size,\n mimeType: getMimeType({ data, destination: destinations[0]!, filename }),\n ...('sourcePath' in file ? { tempFilePath: file.sourcePath } : {}),\n }\n\n // A new object folder is allocated for every server upload, so an interrupted\n // provider write can be removed without touching an earlier revision.\n trackStagedObject({\n key: storageFilePath,\n remove: async () => {\n await adapter.deleteFile({\n collection,\n req,\n storageFilePath,\n })\n },\n })\n\n const dataBeforeUpload = deepCopyObjectSimple(dataForUpload as JsonObject)\n const result = await adapter.handleUpload({\n collection,\n data: dataForUpload,\n file: uploadFile,\n req,\n storageFilePath,\n })\n\n if (result && typeof result === 'object') {\n // Adapters may return the entire input document, including fields made stale by this upload.\n for (const [key, value] of Object.entries(result)) {\n if (!isDeepStrictEqual(value, dataBeforeUpload[key])) {\n metadata[key] = value\n }\n }\n }\n }\n\n delete metadata.prefix\n delete metadata._objectKey\n return { metadata }\n },\n }\n}\n\n/**\n * The document fields a staged file is stored for. The file's role names its field, because the\n * main file and the original can share a filename in different folders. Fields with the same\n * filename and `_objectKey` describe the same object, so they share its location.\n */\nconst getStageDestinations = ({\n data,\n file,\n filename,\n}: {\n data: Record<string, unknown>\n file: FileToSave\n filename: string\n}): Record<string, unknown>[] => {\n const representations: Record<string, unknown>[] = [data]\n if (data.original && typeof data.original === 'object') {\n representations.push(data.original as Record<string, unknown>)\n }\n if (data.variants && typeof data.variants === 'object') {\n representations.push(\n ...Object.values(data.variants).filter(\n (value): value is Record<string, unknown> => Boolean(value) && typeof value === 'object',\n ),\n )\n }\n const namedDestinations = representations.filter((value) => value.filename === filename)\n const roleDestination = file.role ? getRoleRepresentation({ data, role: file.role }) : undefined\n\n if (roleDestination?.filename !== filename) {\n return namedDestinations\n }\n\n return [\n roleDestination,\n ...namedDestinations.filter(\n (value) => value !== roleDestination && value._objectKey === roleDestination._objectKey,\n ),\n ]\n}\n\nconst getRoleRepresentation = ({\n data,\n role,\n}: {\n data: Record<string, unknown>\n role: NonNullable<FileToSave['role']>\n}): Record<string, unknown> | undefined => {\n let representation: unknown = data\n\n if (role.type === 'original') {\n representation = data.original\n } else if (role.type === 'size') {\n representation = (data.variants as Record<string, unknown> | undefined)?.[role.sizeKey]\n }\n\n return representation && typeof representation === 'object'\n ? (representation as Record<string, unknown>)\n : undefined\n}\n\nconst getMimeType = ({\n data,\n destination,\n filename,\n}: {\n data: Record<string, unknown>\n destination: Record<string, unknown>\n filename: string\n}): string => {\n if (typeof destination.mimeType === 'string') {\n return destination.mimeType\n }\n if (data.original && typeof data.original === 'object') {\n const original = data.original as { filename?: string; mimeType?: string }\n if (original.filename === filename && original.mimeType) {\n return original.mimeType\n }\n }\n if (data.variants && typeof data.variants === 'object') {\n for (const size of Object.values(data.variants)) {\n const candidate = size as { filename?: string; mimeType?: string } | null\n if (candidate?.filename === filename && candidate.mimeType) {\n return candidate.mimeType\n }\n }\n }\n return typeof data.mimeType === 'string' ? data.mimeType : 'application/octet-stream'\n}\n\n/** Signed and time-limited URLs change their query on every generation, so only the location is compared. */\nconst isSameFileLocation = ({\n actual,\n expected,\n}: {\n actual: string\n expected: null | string | undefined\n}): boolean =>\n typeof expected === 'string' &&\n getFileLocation({ url: actual }) === getFileLocation({ url: expected })\n\nconst getFileLocation = ({ url }: { url: string }): string => {\n const parsed = new URL(url, 'http://payload.local')\n\n return url.startsWith('/') ? parsed.pathname : `${parsed.origin}${parsed.pathname}`\n}\n"],"names":["fs","path","isDeepStrictEqual","deepCopyObjectSimple","generatePayloadFileURL","buildPrefixWithObjectKey","buildStoragePathData","buildUploadPrefix","buildUploadStoragePathData","createFileOperations","adapter","collection","collectionPrefix","disablePayloadAccessControl","generateFileURL","useCompositePrefixes","deleteFile","Error","name","slug","copy","from","req","to","trackStagedObject","copyFile","payload","collections","config","key","remove","storageFilePath","delete","hasLegacyFile","doc","filename","url","docPrefix","prefix","undefined","objectFolder","objectKey","_objectKey","expectedURL","size","generateURL","data","collectionSlug","relative","isSameFileLocation","actual","expected","variants","Array","isArray","sizeKey","Object","entries","imageSize","upload","find","resolveStorageKey","moveFile","move","stage","files","uploadedKeys","Set","metadata","verifiedOriginal","context","_payloadVerifiedProviderOriginal","file","basename","destinations","getStageDestinations","length","prefixLocation","destination","objectKeyLocation","prefixData","uploadPrefix","sanitizedDocPrefix","dataForUpload","has","add","buffer","supportsTempFiles","Buffer","alloc","readFile","sourcePath","uploadFile","filesize","stat","mimeType","getMimeType","tempFilePath","dataBeforeUpload","result","handleUpload","value","representations","original","push","values","filter","Boolean","namedDestinations","roleDestination","role","getRoleRepresentation","representation","type","candidate","getFileLocation","parsed","URL","startsWith","pathname","origin"],"mappings":"AAEA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAC5B,SAASC,iBAAiB,QAAQ,YAAW;AAC7C,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,UAAS;AAItE,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,0BAA0B,QACrB,4BAA2B;AAWlC,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,2BAA2B,EAC3BC,eAAe,EACfC,oBAAoB,EACf;IACL,IAAI,OAAOL,QAAQM,UAAU,KAAK,YAAY;QAC5C,MAAM,IAAIC,MACR,CAAC,iBAAiB,EAAEP,QAAQQ,IAAI,CAAC,4CAA4C,EAAEP,WAAWQ,IAAI,CAAC,EAAE,CAAC;IAEtG;IAEA,OAAO;QACLC,MAAM,OAAO,EAAEC,IAAI,EAAEC,GAAG,EAAEC,EAAE,EAAEC,iBAAiB,EAAE;YAC/C,MAAMd,QAAQe,QAAQ,CAAC;gBACrBd,YAAYW,IAAII,OAAO,CAACC,WAAW,CAAChB,WAAWQ,IAAI,CAAC,CAAES,MAAM;gBAC5DP;gBACAC;gBACAC;YACF;YACAC,kBAAkB;gBAChBK,KAAKN;gBACLO,QAAQ;oBACN,MAAMpB,QAAQM,UAAU,CAAC;wBACvBL;wBACAW;wBACAS,iBAAiBR;oBACnB;gBACF;YACF;QACF;QACAS,QAAQ,OAAO,EAAEH,GAAG,EAAEP,GAAG,EAAE;YACzB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Request, TypeWithID } from 'pay
|
|
|
8
8
|
* `overrideAccess: false`, any query-param prefix only narrows that lookup, and `_objectKey`
|
|
9
9
|
* is read from the resolved document via `showHiddenFields`.
|
|
10
10
|
*/
|
|
11
|
-
export declare function getFilePrefix({ collection, collectionPrefix, doc, filename, prefixQueryParam, req, uploadReference, useCompositePrefixes, }: {
|
|
11
|
+
export declare function getFilePrefix({ collection, collectionPrefix, doc, filename, isOriginal, prefixQueryParam, req, uploadReference, useCompositePrefixes, }: {
|
|
12
12
|
collection: CollectionConfig;
|
|
13
13
|
collectionPrefix?: string;
|
|
14
14
|
doc?: Partial<FileData> & TypeWithID;
|
|
15
15
|
filename: string;
|
|
16
|
+
/** Serves the original when it shares the main file's name. */
|
|
17
|
+
isOriginal?: boolean;
|
|
16
18
|
/**
|
|
17
19
|
* Only narrows the access-controlled fallback lookup below; never trusted or
|
|
18
20
|
* returned directly. Prefer passing the access-checked document as `doc` instead.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFilePrefix.d.ts","sourceRoot":"","sources":["../../src/utilities/getFilePrefix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,QAAQ,EACR,cAAc,EAEd,UAAU,EACX,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"getFilePrefix.d.ts","sourceRoot":"","sources":["../../src/utilities/getFilePrefix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,QAAQ,EACR,cAAc,EAEd,UAAU,EACX,MAAM,SAAS,CAAA;AAQhB;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,EAClC,UAAU,EACV,gBAAgB,EAChB,GAAG,EACH,QAAQ,EACR,UAAU,EACV,gBAAgB,EAChB,GAAG,EACH,eAAe,EACf,oBAA4B,GAC7B,EAAE;IACD,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,GAAG,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,GAAG,UAAU,CAAA;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,+DAA+D;IAC/D,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,GAAG,EAAE,cAAc,CAAA;IACnB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,GAAG,OAAO,CAAC,MAAM,CAAC,CA2ElB"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isOriginalFileRequest } from 'payload/internal';
|
|
1
2
|
import { buildPrefixWithObjectKey } from './buildPrefixWithObjectKey.js';
|
|
2
3
|
import { buildUploadStoragePathData } from './buildStoragePathData.js';
|
|
3
4
|
import { sanitizePrefix } from './sanitizePrefix.js';
|
|
@@ -9,13 +10,14 @@ import { sanitizePrefix } from './sanitizePrefix.js';
|
|
|
9
10
|
* a signed receipt by every adapter). Otherwise the document is resolved with
|
|
10
11
|
* `overrideAccess: false`, any query-param prefix only narrows that lookup, and `_objectKey`
|
|
11
12
|
* is read from the resolved document via `showHiddenFields`.
|
|
12
|
-
*/ export async function getFilePrefix({ collection, collectionPrefix, doc, filename, prefixQueryParam, req, uploadReference, useCompositePrefixes = false }) {
|
|
13
|
+
*/ export async function getFilePrefix({ collection, collectionPrefix, doc, filename, isOriginal, prefixQueryParam, req, uploadReference, useCompositePrefixes = false }) {
|
|
13
14
|
// The serve path already loaded and authorized this document — trust it over any
|
|
14
15
|
// client-supplied upload reference or query prefix.
|
|
15
16
|
if (doc) {
|
|
16
17
|
return getRepresentationPrefix({
|
|
17
18
|
doc,
|
|
18
|
-
filename
|
|
19
|
+
filename,
|
|
20
|
+
isOriginal
|
|
19
21
|
});
|
|
20
22
|
}
|
|
21
23
|
// Upload instructions call handlers without a document yet. Re-contain the claimed
|
|
@@ -87,11 +89,16 @@ import { sanitizePrefix } from './sanitizePrefix.js';
|
|
|
87
89
|
const found = files?.docs?.[0];
|
|
88
90
|
return found ? getRepresentationPrefix({
|
|
89
91
|
doc: found,
|
|
90
|
-
filename
|
|
92
|
+
filename,
|
|
93
|
+
isOriginal
|
|
91
94
|
}) : '';
|
|
92
95
|
}
|
|
93
|
-
const getRepresentationPrefix = ({ doc, filename })=>{
|
|
94
|
-
const representation =
|
|
96
|
+
/** The main file wins a shared filename unless the original is asked for. */ const getRepresentationPrefix = ({ doc, filename, isOriginal })=>{
|
|
97
|
+
const representation = isOriginalFileRequest({
|
|
98
|
+
doc,
|
|
99
|
+
filename,
|
|
100
|
+
isOriginal
|
|
101
|
+
}) ? doc.original : Object.values(doc.variants ?? {}).find((variant)=>variant?.filename === filename) ?? doc;
|
|
95
102
|
return buildPrefixWithObjectKey({
|
|
96
103
|
objectKey: representation._objectKey ?? (!doc.original?.filename ? doc._objectKey : undefined),
|
|
97
104
|
prefix: representation.prefix ?? (!doc.original?.filename ? doc.prefix : undefined)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/getFilePrefix.ts"],"sourcesContent":["import type {\n CollectionConfig,\n FileData,\n PayloadRequest,\n SanitizedUploadConfig,\n TypeWithID,\n} from 'payload'\n\nimport { buildPrefixWithObjectKey } from './buildPrefixWithObjectKey.js'\nimport { buildUploadStoragePathData } from './buildStoragePathData.js'\nimport { sanitizePrefix } from './sanitizePrefix.js'\n\n/**\n * Resolves the folder a stored object lives under (semantic `prefix` plus `_objectKey`).\n *\n * An already-authorized `doc` wins outright. Otherwise an `uploadReference` is used (its\n * `prefix` re-contained with {@link buildUploadStoragePathData}, since it hasn't been verified against\n * a signed receipt by every adapter). Otherwise the document is resolved with\n * `overrideAccess: false`, any query-param prefix only narrows that lookup, and `_objectKey`\n * is read from the resolved document via `showHiddenFields`.\n */\nexport async function getFilePrefix({\n collection,\n collectionPrefix,\n doc,\n filename,\n prefixQueryParam,\n req,\n uploadReference,\n useCompositePrefixes = false,\n}: {\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: Partial<FileData> & TypeWithID\n filename: string\n /**\n * Only narrows the access-controlled fallback lookup below; never trusted or\n * returned directly. Prefer passing the access-checked document as `doc` instead.\n */\n prefixQueryParam?: string\n req: PayloadRequest\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}): Promise<string> {\n // The serve path already loaded and authorized this document — trust it over any\n // client-supplied upload reference or query prefix.\n if (doc) {\n return getRepresentationPrefix({ doc, filename })\n }\n\n // Upload instructions call handlers without a document yet. Re-contain the claimed\n // prefix — it hasn't been verified against a signed receipt by every adapter.\n if (\n uploadReference &&\n typeof uploadReference === 'object' &&\n 'prefix' in uploadReference &&\n typeof uploadReference.prefix === 'string'\n ) {\n const referenceObjectKey =\n '_objectKey' in uploadReference\n ? (uploadReference as { _objectKey?: string })._objectKey\n : undefined\n const containedPrefix = buildUploadStoragePathData({\n collectionPrefix,\n docPrefix: uploadReference.prefix,\n filename,\n useCompositePrefixes,\n }).sanitizedDocPrefix\n return buildPrefixWithObjectKey({ objectKey: referenceObjectKey, prefix: containedPrefix })\n }\n\n // Reads without a query prefix or read-access constraints skip the endpoint's document lookup.\n const variants = (collection?.upload as SanitizedUploadConfig)?.variants || []\n\n const filenameClause = {\n or: [\n {\n filename: { equals: filename },\n },\n { 'original.filename': { equals: filename } },\n ...variants.map((imageSize) => ({\n [`variants.${imageSize.name}.filename`]: { equals: filename },\n })),\n ],\n }\n\n // Only filter by prefix when the collection persists a `prefix` field (querying a missing field throws).\n const hasPrefixField = collection.fields?.some(\n (field) => 'name' in field && field.name === 'prefix',\n )\n const where =\n typeof prefixQueryParam === 'string' && hasPrefixField\n ? { and: [filenameClause, { prefix: { equals: sanitizePrefix(prefixQueryParam) } }] }\n : filenameClause\n\n const files = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n draft: true,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n select: {\n _objectKey: true,\n filename: true,\n original: true,\n prefix: true,\n variants: true,\n },\n showHiddenFields: true,\n where,\n })\n\n const found = files?.docs?.[0] as\n | ({ _objectKey?: string; prefix?: string } & Partial<FileData>)\n | undefined\n return found ? getRepresentationPrefix({ doc: found, filename }) : ''\n}\n\nconst getRepresentationPrefix = ({\n doc,\n filename,\n}: {\n doc: Partial<FileData>\n filename: string\n}): string => {\n const representation
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/getFilePrefix.ts"],"sourcesContent":["import type {\n CollectionConfig,\n FileData,\n PayloadRequest,\n SanitizedUploadConfig,\n TypeWithID,\n} from 'payload'\n\nimport { isOriginalFileRequest } from 'payload/internal'\n\nimport { buildPrefixWithObjectKey } from './buildPrefixWithObjectKey.js'\nimport { buildUploadStoragePathData } from './buildStoragePathData.js'\nimport { sanitizePrefix } from './sanitizePrefix.js'\n\n/**\n * Resolves the folder a stored object lives under (semantic `prefix` plus `_objectKey`).\n *\n * An already-authorized `doc` wins outright. Otherwise an `uploadReference` is used (its\n * `prefix` re-contained with {@link buildUploadStoragePathData}, since it hasn't been verified against\n * a signed receipt by every adapter). Otherwise the document is resolved with\n * `overrideAccess: false`, any query-param prefix only narrows that lookup, and `_objectKey`\n * is read from the resolved document via `showHiddenFields`.\n */\nexport async function getFilePrefix({\n collection,\n collectionPrefix,\n doc,\n filename,\n isOriginal,\n prefixQueryParam,\n req,\n uploadReference,\n useCompositePrefixes = false,\n}: {\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: Partial<FileData> & TypeWithID\n filename: string\n /** Serves the original when it shares the main file's name. */\n isOriginal?: boolean\n /**\n * Only narrows the access-controlled fallback lookup below; never trusted or\n * returned directly. Prefer passing the access-checked document as `doc` instead.\n */\n prefixQueryParam?: string\n req: PayloadRequest\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}): Promise<string> {\n // The serve path already loaded and authorized this document — trust it over any\n // client-supplied upload reference or query prefix.\n if (doc) {\n return getRepresentationPrefix({ doc, filename, isOriginal })\n }\n\n // Upload instructions call handlers without a document yet. Re-contain the claimed\n // prefix — it hasn't been verified against a signed receipt by every adapter.\n if (\n uploadReference &&\n typeof uploadReference === 'object' &&\n 'prefix' in uploadReference &&\n typeof uploadReference.prefix === 'string'\n ) {\n const referenceObjectKey =\n '_objectKey' in uploadReference\n ? (uploadReference as { _objectKey?: string })._objectKey\n : undefined\n const containedPrefix = buildUploadStoragePathData({\n collectionPrefix,\n docPrefix: uploadReference.prefix,\n filename,\n useCompositePrefixes,\n }).sanitizedDocPrefix\n return buildPrefixWithObjectKey({ objectKey: referenceObjectKey, prefix: containedPrefix })\n }\n\n // Reads without a query prefix or read-access constraints skip the endpoint's document lookup.\n const variants = (collection?.upload as SanitizedUploadConfig)?.variants || []\n\n const filenameClause = {\n or: [\n {\n filename: { equals: filename },\n },\n { 'original.filename': { equals: filename } },\n ...variants.map((imageSize) => ({\n [`variants.${imageSize.name}.filename`]: { equals: filename },\n })),\n ],\n }\n\n // Only filter by prefix when the collection persists a `prefix` field (querying a missing field throws).\n const hasPrefixField = collection.fields?.some(\n (field) => 'name' in field && field.name === 'prefix',\n )\n const where =\n typeof prefixQueryParam === 'string' && hasPrefixField\n ? { and: [filenameClause, { prefix: { equals: sanitizePrefix(prefixQueryParam) } }] }\n : filenameClause\n\n const files = await req.payload.find({\n collection: collection.slug,\n depth: 0,\n draft: true,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n select: {\n _objectKey: true,\n filename: true,\n original: true,\n prefix: true,\n variants: true,\n },\n showHiddenFields: true,\n where,\n })\n\n const found = files?.docs?.[0] as\n | ({ _objectKey?: string; prefix?: string } & Partial<FileData>)\n | undefined\n return found ? getRepresentationPrefix({ doc: found, filename, isOriginal }) : ''\n}\n\n/** The main file wins a shared filename unless the original is asked for. */\nconst getRepresentationPrefix = ({\n doc,\n filename,\n isOriginal,\n}: {\n doc: Partial<FileData>\n filename: string\n isOriginal?: boolean\n}): string => {\n const representation = isOriginalFileRequest({ doc, filename, isOriginal })\n ? doc.original!\n : (Object.values(doc.variants ?? {}).find((variant) => variant?.filename === filename) ?? doc)\n return buildPrefixWithObjectKey({\n objectKey: representation._objectKey ?? (!doc.original?.filename ? doc._objectKey : undefined),\n prefix: representation.prefix ?? (!doc.original?.filename ? doc.prefix : undefined),\n })\n}\n"],"names":["isOriginalFileRequest","buildPrefixWithObjectKey","buildUploadStoragePathData","sanitizePrefix","getFilePrefix","collection","collectionPrefix","doc","filename","isOriginal","prefixQueryParam","req","uploadReference","useCompositePrefixes","getRepresentationPrefix","prefix","referenceObjectKey","_objectKey","undefined","containedPrefix","docPrefix","sanitizedDocPrefix","objectKey","variants","upload","filenameClause","or","equals","map","imageSize","name","hasPrefixField","fields","some","field","where","and","files","payload","find","slug","depth","draft","limit","overrideAccess","pagination","select","original","showHiddenFields","found","docs","representation","Object","values","variant"],"mappings":"AAQA,SAASA,qBAAqB,QAAQ,mBAAkB;AAExD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,0BAA0B,QAAQ,4BAA2B;AACtE,SAASC,cAAc,QAAQ,sBAAqB;AAEpD;;;;;;;;CAQC,GACD,OAAO,eAAeC,cAAc,EAClCC,UAAU,EACVC,gBAAgB,EAChBC,GAAG,EACHC,QAAQ,EACRC,UAAU,EACVC,gBAAgB,EAChBC,GAAG,EACHC,eAAe,EACfC,uBAAuB,KAAK,EAgB7B;IACC,iFAAiF;IACjF,oDAAoD;IACpD,IAAIN,KAAK;QACP,OAAOO,wBAAwB;YAAEP;YAAKC;YAAUC;QAAW;IAC7D;IAEA,mFAAmF;IACnF,8EAA8E;IAC9E,IACEG,mBACA,OAAOA,oBAAoB,YAC3B,YAAYA,mBACZ,OAAOA,gBAAgBG,MAAM,KAAK,UAClC;QACA,MAAMC,qBACJ,gBAAgBJ,kBACZ,AAACA,gBAA4CK,UAAU,GACvDC;QACN,MAAMC,kBAAkBjB,2BAA2B;YACjDI;YACAc,WAAWR,gBAAgBG,MAAM;YACjCP;YACAK;QACF,GAAGQ,kBAAkB;QACrB,OAAOpB,yBAAyB;YAAEq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AAW,KACrEF,IAAIwC,QAAQ,GACXK,OAAOC,MAAM,CAAC9C,IAAIgB,QAAQ,IAAI,CAAC,GAAGgB,IAAI,CAAC,CAACe,UAAYA,SAAS9C,aAAaA,aAAaD;IAC5F,OAAON,yBAAyB;QAC9BqB,WAAW6B,eAAelC,UAAU,IAAK,CAAA,CAACV,IAAIwC,QAAQ,EAAEvC,WAAWD,IAAIU,UAAU,GAAGC,SAAQ;QAC5FH,QAAQoC,eAAepC,MAAM,IAAK,CAAA,CAACR,IAAIwC,QAAQ,EAAEvC,WAAWD,IAAIQ,MAAM,GAAGG,SAAQ;IACnF;AACF"}
|
|
@@ -23,11 +23,17 @@ const withLocationFields = ({ select })=>{
|
|
|
23
23
|
}
|
|
24
24
|
});
|
|
25
25
|
if (isSelectRecord(result.original)) {
|
|
26
|
-
|
|
26
|
+
const original = addLocationFields({
|
|
27
27
|
representation: {
|
|
28
28
|
...result.original
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
|
+
result.original = original;
|
|
32
|
+
// The original URL compares the original's location with the main file's location.
|
|
33
|
+
if (original.url === true) {
|
|
34
|
+
result.filename = true;
|
|
35
|
+
result._objectKey = true;
|
|
36
|
+
}
|
|
31
37
|
}
|
|
32
38
|
if (isSelectRecord(result.variants)) {
|
|
33
39
|
result.variants = Object.fromEntries(Object.entries(result.variants).map(([name, variant])=>[
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/getStorageLocationSelect.ts"],"sourcesContent":["import type { CollectionConfig, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\ntype SelectRecord = Record<string, unknown>\n\nconst locationFieldNames = ['filename', 'prefix', '_objectKey'] as const\n\n/**\n * URL hooks rebuild direct URLs from each representation's stored location, so a positive\n * selection of a URL must also read the fields that location is built from.\n */\nexport const getStorageLocationSelect =\n ({\n select: existingSelect,\n }: {\n select: CollectionConfig['select']\n }): NonNullable<CollectionConfig['select']> =>\n (args) => {\n const select = existingSelect?.(args) ?? args.select\n\n if (!select || getSelectMode(select) === 'exclude') {\n return select\n }\n\n return withLocationFields({ select })\n }\n\nconst withLocationFields = ({ select }: { select: SelectType }): SelectType => {\n const result = addLocationFields({ representation: { ...select } })\n\n if (isSelectRecord(result.original)) {\n
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/getStorageLocationSelect.ts"],"sourcesContent":["import type { CollectionConfig, SelectType } from 'payload'\n\nimport { getSelectMode } from 'payload/shared'\n\ntype SelectRecord = Record<string, unknown>\n\nconst locationFieldNames = ['filename', 'prefix', '_objectKey'] as const\n\n/**\n * URL hooks rebuild direct URLs from each representation's stored location, so a positive\n * selection of a URL must also read the fields that location is built from.\n */\nexport const getStorageLocationSelect =\n ({\n select: existingSelect,\n }: {\n select: CollectionConfig['select']\n }): NonNullable<CollectionConfig['select']> =>\n (args) => {\n const select = existingSelect?.(args) ?? args.select\n\n if (!select || getSelectMode(select) === 'exclude') {\n return select\n }\n\n return withLocationFields({ select })\n }\n\nconst withLocationFields = ({ select }: { select: SelectType }): SelectType => {\n const result = addLocationFields({ representation: { ...select } })\n\n if (isSelectRecord(result.original)) {\n const original = addLocationFields({ representation: { ...result.original } })\n result.original = original\n\n // The original URL compares the original's location with the main file's location.\n if (original.url === true) {\n result.filename = true\n result._objectKey = true\n }\n }\n\n if (isSelectRecord(result.variants)) {\n result.variants = Object.fromEntries(\n Object.entries(result.variants).map(([name, variant]) => [\n name,\n isSelectRecord(variant) ? addLocationFields({ representation: { ...variant } }) : variant,\n ]),\n )\n }\n\n return result as SelectType\n}\n\nconst addLocationFields = ({ representation }: { representation: SelectRecord }): SelectRecord => {\n if (representation.url === true) {\n for (const fieldName of locationFieldNames) {\n representation[fieldName] = true\n }\n }\n\n return representation\n}\n\nconst isSelectRecord = (value: unknown): value is SelectRecord =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n"],"names":["getSelectMode","locationFieldNames","getStorageLocationSelect","select","existingSelect","args","withLocationFields","result","addLocationFields","representation","isSelectRecord","original","url","filename","_objectKey","variants","Object","fromEntries","entries","map","name","variant","fieldName","value","Array","isArray"],"mappings":"AAEA,SAASA,aAAa,QAAQ,iBAAgB;AAI9C,MAAMC,qBAAqB;IAAC;IAAY;IAAU;CAAa;AAE/D;;;CAGC,GACD,OAAO,MAAMC,2BACX,CAAC,EACCC,QAAQC,cAAc,EAGvB,GACD,CAACC;QACC,MAAMF,SAASC,iBAAiBC,SAASA,KAAKF,MAAM;QAEpD,IAAI,CAACA,UAAUH,cAAcG,YAAY,WAAW;YAClD,OAAOA;QACT;QAEA,OAAOG,mBAAmB;YAAEH;QAAO;IACrC,EAAC;AAEH,MAAMG,qBAAqB,CAAC,EAAEH,MAAM,EAA0B;IAC5D,MAAMI,SAASC,kBAAkB;QAAEC,gBAAgB;YAAE,GAAGN,MAAM;QAAC;IAAE;IAEjE,IAAIO,eAAeH,OAAOI,QAAQ,GAAG;QACnC,MAAMA,WAAWH,kBAAkB;YAAEC,gBAAgB;gBAAE,GAAGF,OAAOI,QAAQ;YAAC;QAAE;QAC5EJ,OAAOI,QAAQ,GAAGA;QAElB,mFAAmF;QACnF,IAAIA,SAASC,GAAG,KAAK,MAAM;YACzBL,OAAOM,QAAQ,GAAG;YAClBN,OAAOO,UAAU,GAAG;QACtB;IACF;IAEA,IAAIJ,eAAeH,OAAOQ,QAAQ,GAAG;QACnCR,OAAOQ,QAAQ,GAAGC,OAAOC,WAAW,CAClCD,OAAOE,OAAO,CAACX,OAAOQ,QAAQ,EAAEI,GAAG,CAAC,CAAC,CAACC,MAAMC,QAAQ,GAAK;gBACvDD;gBACAV,eAAeW,WAAWb,kBAAkB;oBAAEC,gBAAgB;wBAAE,GAAGY,OAAO;oBAAC;gBAAE,KAAKA;aACnF;IAEL;IAEA,OAAOd;AACT;AAEA,MAAMC,oBAAoB,CAAC,EAAEC,cAAc,EAAoC;IAC7E,IAAIA,eAAeG,GAAG,KAAK,MAAM;QAC/B,KAAK,MAAMU,aAAarB,mBAAoB;YAC1CQ,cAAc,CAACa,UAAU,GAAG;QAC9B;IACF;IAEA,OAAOb;AACT;AAEA,MAAMC,iBAAiB,CAACa,QACtB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveSignedURLKey.d.ts","sourceRoot":"","sources":["../../src/utilities/resolveSignedURLKey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"resolveSignedURLKey.d.ts","sourceRoot":"","sources":["../../src/utilities/resolveSignedURLKey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAM7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAIlD,KAAK,IAAI,GAAG;IACV,mGAAmG;IACnG,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACrC,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,WAAW,EACX,gBAAqB,EACrB,cAAc,EACd,SAAS,EACT,QAAQ,EACR,GAAG,EACH,oBAA4B,GAC7B,EAAE,IAAI,GAAG,OAAO,CAAC;IAChB,kBAAkB,EAAE,MAAM,CAAA;IAC1B,iBAAiB,EAAE,MAAM,CAAA;IACzB,eAAe,EAAE,MAAM,CAAA;IACvB,eAAe,EAAE,eAAe,CAAA;CACjC,CAAC,CAwCD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { createClientUploadReceipt,
|
|
2
|
+
import { createClientUploadReceipt, getSafeFileName } from 'payload/internal';
|
|
3
3
|
import { getSanitizedUploadFilename } from 'payload/shared';
|
|
4
4
|
import { buildUploadPrefix, buildUploadStoragePathData } from './buildStoragePathData.js';
|
|
5
5
|
/**
|
|
@@ -19,21 +19,11 @@ import { buildUploadPrefix, buildUploadStoragePathData } from './buildStoragePat
|
|
|
19
19
|
* key with {@link buildUploadStoragePathData}, so the receipt only ever signs a key
|
|
20
20
|
* beneath the configured collection prefix.
|
|
21
21
|
*/ export async function resolveSignedURLKey({ adapterData, collectionPrefix = '', collectionSlug, docPrefix, filename, req, useCompositePrefixes = false }) {
|
|
22
|
-
|
|
23
|
-
let sanitizedFilename = getSanitizedUploadFilename(filename);
|
|
24
|
-
let originalFilename = getOriginalFilename({
|
|
25
|
-
filename: sanitizedFilename
|
|
26
|
-
});
|
|
27
|
-
while(await getSafeFileName({
|
|
22
|
+
const sanitizedFilename = await getSafeFileName({
|
|
28
23
|
collectionSlug,
|
|
29
|
-
desiredFilename:
|
|
24
|
+
desiredFilename: getSanitizedUploadFilename(filename),
|
|
30
25
|
req
|
|
31
|
-
})
|
|
32
|
-
sanitizedFilename = incrementName(sanitizedFilename);
|
|
33
|
-
originalFilename = getOriginalFilename({
|
|
34
|
-
filename: sanitizedFilename
|
|
35
|
-
});
|
|
36
|
-
}
|
|
26
|
+
});
|
|
37
27
|
const rawBaseDocPrefix = useCompositePrefixes ? docPrefix : docPrefix || collectionPrefix;
|
|
38
28
|
const { sanitizedDocPrefix } = buildUploadPrefix({
|
|
39
29
|
collectionPrefix,
|
|
@@ -46,7 +36,7 @@ import { buildUploadPrefix, buildUploadStoragePathData } from './buildStoragePat
|
|
|
46
36
|
const { storageFilePath } = buildUploadStoragePathData({
|
|
47
37
|
collectionPrefix,
|
|
48
38
|
docPrefix: keyedDocPrefix,
|
|
49
|
-
filename:
|
|
39
|
+
filename: sanitizedFilename,
|
|
50
40
|
useCompositePrefixes
|
|
51
41
|
});
|
|
52
42
|
const uploadReference = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/resolveSignedURLKey.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { randomUUID } from 'node:crypto'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/resolveSignedURLKey.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { randomUUID } from 'node:crypto'\nimport { createClientUploadReceipt, getSafeFileName } from 'payload/internal'\nimport { getSanitizedUploadFilename } from 'payload/shared'\n\nimport type { UploadReference } from '../types.js'\n\nimport { buildUploadPrefix, buildUploadStoragePathData } from './buildStoragePathData.js'\n\ntype Args = {\n /** Signed into the receipt and returned to the upload handler as `uploadReference.adapterData`. */\n adapterData?: Record<string, unknown>\n collectionPrefix?: string\n collectionSlug: string\n docPrefix?: string\n filename: string\n req: PayloadRequest\n useCompositePrefixes?: boolean\n}\n\n/**\n * Resolves the storage key for an upload-instructions request, deduping\n * the filename via {@link getSafeFileName} so a duplicate upload does not\n * overwrite an existing blob.\n *\n * A unique per-upload segment is included in the storage key so each issued\n * key is distinct. The stored `filename` stays clean and the semantic `prefix`\n * stays exactly what the collection configured — the per-upload entropy is\n * persisted separately in `_objectKey`.\n *\n * The resolved `sanitizedFilename` is returned so the browser-side handler\n * can update the form via `updateFilename`.\n *\n * The semantic prefix is resolved with {@link buildUploadPrefix} and the final\n * key with {@link buildUploadStoragePathData}, so the receipt only ever signs a key\n * beneath the configured collection prefix.\n */\nexport async function resolveSignedURLKey({\n adapterData,\n collectionPrefix = '',\n collectionSlug,\n docPrefix,\n filename,\n req,\n useCompositePrefixes = false,\n}: Args): Promise<{\n sanitizedDocPrefix: string\n sanitizedFilename: string\n storageFilePath: string\n uploadReference: UploadReference\n}> {\n const sanitizedFilename = await getSafeFileName({\n collectionSlug,\n desiredFilename: getSanitizedUploadFilename(filename),\n req,\n })\n\n const rawBaseDocPrefix = useCompositePrefixes ? docPrefix : docPrefix || collectionPrefix\n const { sanitizedDocPrefix } = buildUploadPrefix({\n collectionPrefix,\n docPrefix: rawBaseDocPrefix,\n useCompositePrefixes,\n })\n\n const _objectKey = randomUUID()\n // Per-upload segment lives in the key; it is persisted in `_objectKey`, keeping `prefix` semantic.\n const keyedDocPrefix = sanitizedDocPrefix ? `${sanitizedDocPrefix}/${_objectKey}` : _objectKey\n\n const { storageFilePath } = buildUploadStoragePathData({\n collectionPrefix,\n docPrefix: keyedDocPrefix,\n filename: sanitizedFilename,\n useCompositePrefixes,\n })\n\n const uploadReference = {\n _objectKey,\n prefix: sanitizedDocPrefix,\n signedReceipt: createClientUploadReceipt({\n _objectKey,\n ...(adapterData !== undefined && { adapterData }),\n collectionSlug,\n filename: sanitizedFilename,\n filePrefix: sanitizedDocPrefix,\n req,\n storageFilePath,\n }),\n }\n\n return { sanitizedDocPrefix, sanitizedFilename, storageFilePath, uploadReference }\n}\n"],"names":["randomUUID","createClientUploadReceipt","getSafeFileName","getSanitizedUploadFilename","buildUploadPrefix","buildUploadStoragePathData","resolveSignedURLKey","adapterData","collectionPrefix","collectionSlug","docPrefix","filename","req","useCompositePrefixes","sanitizedFilename","desiredFilename","rawBaseDocPrefix","sanitizedDocPrefix","_objectKey","keyedDocPrefix","storageFilePath","uploadReference","prefix","signedReceipt","undefined","filePrefix"],"mappings":"AAEA,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,yBAAyB,EAAEC,eAAe,QAAQ,mBAAkB;AAC7E,SAASC,0BAA0B,QAAQ,iBAAgB;AAI3D,SAASC,iBAAiB,EAAEC,0BAA0B,QAAQ,4BAA2B;AAazF;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,WAAW,EACXC,mBAAmB,EAAE,EACrBC,cAAc,EACdC,SAAS,EACTC,QAAQ,EACRC,GAAG,EACHC,uBAAuB,KAAK,EACvB;IAML,MAAMC,oBAAoB,MAAMZ,gBAAgB;QAC9CO;QACAM,iBAAiBZ,2BAA2BQ;QAC5CC;IACF;IAEA,MAAMI,mBAAmBH,uBAAuBH,YAAYA,aAAaF;IACzE,MAAM,EAAES,kBAAkB,EAAE,GAAGb,kBAAkB;QAC/CI;QACAE,WAAWM;QACXH;IACF;IAEA,MAAMK,aAAalB;IACnB,mGAAmG;IACnG,MAAMmB,iBAAiBF,qBAAqB,GAAGA,mBAAmB,CAAC,EAAEC,YAAY,GAAGA;IAEpF,MAAM,EAAEE,eAAe,EAAE,GAAGf,2BAA2B;QACrDG;QACAE,WAAWS;QACXR,UAAUG;QACVD;IACF;IAEA,MAAMQ,kBAAkB;QACtBH;QACAI,QAAQL;QACRM,eAAetB,0BAA0B;YACvCiB;YACA,GAAIX,gBAAgBiB,aAAa;gBAAEjB;YAAY,CAAC;YAChDE;YACAE,UAAUG;YACVW,YAAYR;YACZL;YACAQ;QACF;IACF;IAEA,OAAO;QAAEH;QAAoBH;QAAmBM;QAAiBC;IAAgB;AACnF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/plugin-cloud-storage",
|
|
3
|
-
"version": "4.0.0-beta.
|
|
3
|
+
"version": "4.0.0-beta.7",
|
|
4
4
|
"description": "The official cloud storage plugin for Payload CMS",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"license": "MIT",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"registry": "https://registry.npmjs.org/"
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@payloadcms/ui": "4.0.0-beta.
|
|
55
|
+
"@payloadcms/ui": "4.0.0-beta.7",
|
|
56
56
|
"find-node-modules": "^2.1.3",
|
|
57
57
|
"range-parser": "^1.2.1"
|
|
58
58
|
},
|
|
@@ -60,10 +60,10 @@
|
|
|
60
60
|
"@types/find-node-modules": "^2.1.2",
|
|
61
61
|
"@types/react": "19.3.0",
|
|
62
62
|
"@types/react-dom": "19.3.0",
|
|
63
|
-
"payload": "4.0.0-beta.
|
|
63
|
+
"payload": "4.0.0-beta.7"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
|
-
"payload": "4.0.0-beta.
|
|
66
|
+
"payload": "4.0.0-beta.7",
|
|
67
67
|
"react": "^19.0.1 || ^19.1.2 || ^19.2.1",
|
|
68
68
|
"react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1"
|
|
69
69
|
},
|