payload 4.0.0-beta.8 → 4.0.0-beta.9
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/auth/baseFields/sessions.d.ts.map +1 -1
- package/dist/auth/baseFields/sessions.js +12 -0
- package/dist/auth/baseFields/sessions.js.map +1 -1
- package/dist/auth/createAuthToken.d.ts +3 -3
- package/dist/auth/createAuthToken.d.ts.map +1 -1
- package/dist/auth/createAuthToken.js +4 -1
- package/dist/auth/createAuthToken.js.map +1 -1
- package/dist/auth/getUserAgentLabel.d.ts +8 -0
- package/dist/auth/getUserAgentLabel.d.ts.map +1 -0
- package/dist/auth/getUserAgentLabel.js +70 -0
- package/dist/auth/getUserAgentLabel.js.map +1 -0
- package/dist/auth/operations/login.d.ts.map +1 -1
- package/dist/auth/operations/login.js +5 -0
- package/dist/auth/operations/login.js.map +1 -1
- package/dist/auth/operations/resetPassword.d.ts.map +1 -1
- package/dist/auth/operations/resetPassword.js +5 -0
- package/dist/auth/operations/resetPassword.js.map +1 -1
- package/dist/auth/sessions.d.ts +2 -2
- package/dist/auth/sessions.d.ts.map +1 -1
- package/dist/auth/sessions.js +5 -2
- package/dist/auth/sessions.js.map +1 -1
- package/dist/auth/types.d.ts +9 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.d.ts.map +1 -1
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.js +7 -3
- package/dist/cli/commands/generateImportMap/utilities/resolveImportMapFilePath.js.map +1 -1
- package/dist/collections/operations/create.js +1 -1
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/findByID.d.ts.map +1 -1
- package/dist/collections/operations/findByID.js +1 -3
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/collections/operations/local/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/local/restoreVersion.js +2 -1
- package/dist/collections/operations/local/restoreVersion.js.map +1 -1
- package/dist/collections/operations/restoreVersion.d.ts.map +1 -1
- package/dist/collections/operations/restoreVersion.js +22 -6
- package/dist/collections/operations/restoreVersion.js.map +1 -1
- package/dist/collections/operations/update.js +1 -1
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -1
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/exports/internal.d.ts +1 -1
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js.map +1 -1
- package/dist/index.bundled.d.ts +48 -63
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -2
- package/dist/index.js.map +1 -1
- package/dist/uploads/checkFileAccess.d.ts.map +1 -1
- package/dist/uploads/checkFileAccess.js +1 -0
- package/dist/uploads/checkFileAccess.js.map +1 -1
- package/dist/uploads/endpoints/getFile.d.ts.map +1 -1
- package/dist/uploads/endpoints/getFile.js +17 -5
- package/dist/uploads/endpoints/getFile.js.map +1 -1
- package/dist/uploads/fileSelectionParams.d.ts +10 -0
- package/dist/uploads/fileSelectionParams.d.ts.map +1 -0
- package/dist/uploads/fileSelectionParams.js +10 -0
- package/dist/uploads/fileSelectionParams.js.map +1 -0
- package/dist/uploads/fileVersioning/cloudStorage.d.ts +7 -0
- package/dist/uploads/fileVersioning/cloudStorage.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.js +43 -19
- package/dist/uploads/fileVersioning/cloudStorage.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts +18 -4
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js +73 -30
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/fileVersioning/restore.d.ts +17 -3
- package/dist/uploads/fileVersioning/restore.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restore.js +42 -1
- package/dist/uploads/fileVersioning/restore.js.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts +15 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts.map +1 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.js +176 -0
- package/dist/uploads/fileVersioning/restoreRequestTime.js.map +1 -0
- package/dist/uploads/fileVersioning/storedFiles.d.ts +4 -0
- package/dist/uploads/fileVersioning/storedFiles.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.js +10 -1
- package/dist/uploads/fileVersioning/storedFiles.js.map +1 -1
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.d.ts +122 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.d.ts.map +1 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.js +261 -0
- package/dist/uploads/generateFileData/edits/legacyUploadEdits.js.map +1 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.d.ts +30 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.d.ts.map +1 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.js +131 -0
- package/dist/uploads/generateFileData/edits/resolveUploadEdits.js.map +1 -0
- package/dist/uploads/generateFileData/index.d.ts +47 -0
- package/dist/uploads/generateFileData/index.d.ts.map +1 -0
- package/dist/uploads/generateFileData/index.js +365 -0
- package/dist/uploads/generateFileData/index.js.map +1 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.d.ts +52 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.js +394 -0
- package/dist/uploads/generateFileData/output/buildUploadOutput.js.map +1 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.d.ts +33 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.js +100 -0
- package/dist/uploads/generateFileData/output/buildVariantOutputs.js.map +1 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.d.ts +20 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.d.ts.map +1 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.js +20 -0
- package/dist/uploads/generateFileData/output/resolveTempFileHandling.js.map +1 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.d.ts +35 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.d.ts.map +1 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.js +54 -0
- package/dist/uploads/generateFileData/plan/planSourceRebuild.js.map +1 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.d.ts +44 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.d.ts.map +1 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.js +63 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.js.map +1 -0
- package/dist/uploads/generateFileData/runUploadTransformers.d.ts +46 -0
- package/dist/uploads/generateFileData/runUploadTransformers.d.ts.map +1 -0
- package/dist/uploads/generateFileData/runUploadTransformers.js +93 -0
- package/dist/uploads/generateFileData/runUploadTransformers.js.map +1 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.d.ts +32 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.js +43 -0
- package/dist/uploads/generateFileData/source/downloadClientUpload.js.map +1 -0
- package/dist/uploads/generateFileData/source/readUploadSource.d.ts +27 -0
- package/dist/uploads/generateFileData/source/readUploadSource.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/readUploadSource.js +97 -0
- package/dist/uploads/generateFileData/source/readUploadSource.js.map +1 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.d.ts +50 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.d.ts.map +1 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.js +42 -0
- package/dist/uploads/generateFileData/source/selectUploadSource.js.map +1 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.d.ts +9 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.js +19 -0
- package/dist/uploads/generateFileData/utils/checkFileAndUseDetectedType.js.map +1 -0
- package/dist/uploads/generateFileData/utils/generateImageSizeFilename.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/generateImageSizeFilename.js.map +1 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.d.ts +27 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.js +22 -0
- package/dist/uploads/generateFileData/utils/getUploadStorage.js.map +1 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.d.ts +11 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.d.ts.map +1 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.js +15 -0
- package/dist/uploads/generateFileData/utils/toFileUploadError.js.map +1 -0
- package/dist/uploads/getFileFromUploadInstructions.js +2 -2
- package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
- package/dist/uploads/requestTimeFileData.d.ts +36 -0
- package/dist/uploads/requestTimeFileData.d.ts.map +1 -0
- package/dist/uploads/requestTimeFileData.js +56 -0
- package/dist/uploads/requestTimeFileData.js.map +1 -0
- package/dist/uploads/transformState/planUpload.d.ts +27 -2
- package/dist/uploads/transformState/planUpload.d.ts.map +1 -1
- package/dist/uploads/transformState/planUpload.js +27 -4
- package/dist/uploads/transformState/planUpload.js.map +1 -1
- package/dist/uploads/transformState/transformStateInput.d.ts +52 -0
- package/dist/uploads/transformState/transformStateInput.d.ts.map +1 -0
- package/dist/uploads/transformState/transformStateInput.js +113 -0
- package/dist/uploads/transformState/transformStateInput.js.map +1 -0
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts +7 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts.map +1 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.js +40 -10
- package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
- package/dist/uploads/transformers/transformUploadFile.js +1 -1
- package/dist/uploads/transformers/transformUploadFile.js.map +1 -1
- package/dist/uploads/transformers/uploadTransformerBridge.d.ts +16 -6
- package/dist/uploads/transformers/uploadTransformerBridge.d.ts.map +1 -1
- package/dist/uploads/transformers/uploadTransformerBridge.js +3 -1
- package/dist/uploads/transformers/uploadTransformerBridge.js.map +1 -1
- package/dist/utilities/initTransaction.d.ts.map +1 -1
- package/dist/utilities/initTransaction.js +35 -7
- package/dist/utilities/initTransaction.js.map +1 -1
- package/dist/versions/getLatestCollectionVersion.d.ts +1 -2
- package/dist/versions/getLatestCollectionVersion.d.ts.map +1 -1
- package/dist/versions/getLatestCollectionVersion.js +7 -23
- package/dist/versions/getLatestCollectionVersion.js.map +1 -1
- package/dist/versions/getLatestGlobalVersion.d.ts +1 -2
- package/dist/versions/getLatestGlobalVersion.d.ts.map +1 -1
- package/dist/versions/getLatestGlobalVersion.js +2 -6
- package/dist/versions/getLatestGlobalVersion.js.map +1 -1
- package/package.json +3 -3
- package/skills/payload/SKILL.md +12 -9
- package/skills/payload/reference/ADAPTERS.md +21 -27
- package/skills/payload/reference/FIELDS.md +1 -1
- package/skills/payload/reference/HOOKS.md +1 -1
- package/skills/payload/reference/PLUGIN-DEVELOPMENT.md +1 -1
- package/skills/payload/reference/QUERIES.md +6 -6
- package/dist/uploads/generateFileData.d.ts +0 -60
- package/dist/uploads/generateFileData.d.ts.map +0 -1
- package/dist/uploads/generateFileData.js +0 -1022
- package/dist/uploads/generateFileData.js.map +0 -1
- package/dist/uploads/generateImageSizeFilename.d.ts.map +0 -1
- package/dist/uploads/generateImageSizeFilename.js.map +0 -1
- package/dist/uploads/transformState/resolveUploadEdits.d.ts +0 -91
- package/dist/uploads/transformState/resolveUploadEdits.d.ts.map +0 -1
- package/dist/uploads/transformState/resolveUploadEdits.js +0 -397
- package/dist/uploads/transformState/resolveUploadEdits.js.map +0 -1
- /package/dist/uploads/{generateImageSizeFilename.d.ts → generateFileData/utils/generateImageSizeFilename.d.ts} +0 -0
- /package/dist/uploads/{generateImageSizeFilename.js → generateFileData/utils/generateImageSizeFilename.js} +0 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { FileRetrievalError, Forbidden } from '../../../errors/index.js';
|
|
2
|
+
import { downloadFileToBuffer, resolveExternalFileURL } from '../../downloadFileToBuffer.js';
|
|
3
|
+
import { getFileByPath } from '../../getFileByPath.js';
|
|
4
|
+
import { validateUploadURL } from '../../validateUploadURL.js';
|
|
5
|
+
import { getStoredOriginal } from './selectUploadSource.js';
|
|
6
|
+
/**
|
|
7
|
+
* Reads the bytes of a source that did not arrive with the operation: a stored local file, a
|
|
8
|
+
* stored original in managed cloud storage, or a remote URL. Checks the path and the URL policy
|
|
9
|
+
* before anything is read.
|
|
10
|
+
*/ export async function readUploadSource({ collection, currentFilename, originalDoc, req, source, storedMimeType }) {
|
|
11
|
+
const { serverURL } = req.payload.config;
|
|
12
|
+
const { disableLocalStorage, staticDir } = collection.upload;
|
|
13
|
+
const storedOriginal = getStoredOriginal({
|
|
14
|
+
source
|
|
15
|
+
});
|
|
16
|
+
const externalUploadSource = source.type === 'externalURL' ? source.fileData : undefined;
|
|
17
|
+
const fileData = source.type === 'documentFile' || source.type === 'externalURL' ? source.fileData : source.original;
|
|
18
|
+
const { filename, url } = fileData;
|
|
19
|
+
if (filename && (filename.includes('../') || filename.includes('..\\'))) {
|
|
20
|
+
throw new Forbidden(req.t);
|
|
21
|
+
}
|
|
22
|
+
const isLocalFile = Boolean(serverURL && url?.startsWith(serverURL) || url?.startsWith('/'));
|
|
23
|
+
// A caller-supplied URL must pass the same `pasteURL` policy as the paste-url endpoint.
|
|
24
|
+
// Checked outside the try below so policy errors reach the caller as 400s.
|
|
25
|
+
if (externalUploadSource) {
|
|
26
|
+
validateUploadURL({
|
|
27
|
+
requireAllowList: false,
|
|
28
|
+
uploadConfig: collection.upload,
|
|
29
|
+
url: resolveExternalFileURL({
|
|
30
|
+
req,
|
|
31
|
+
url: externalUploadSource.url
|
|
32
|
+
}).url.href
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
let file;
|
|
36
|
+
let shouldOverwriteExistingFiles;
|
|
37
|
+
try {
|
|
38
|
+
if (!externalUploadSource && !disableLocalStorage && isLocalFile) {
|
|
39
|
+
// File is stored locally
|
|
40
|
+
file = await getFileByPath(`${staticDir}/${filename}`);
|
|
41
|
+
shouldOverwriteExistingFiles = true;
|
|
42
|
+
} else if (filename && storedOriginal && collection.upload.fileOperations) {
|
|
43
|
+
const { retrieveFileResponse } = await import('../../endpoints/getFile.js');
|
|
44
|
+
const response = await retrieveFileResponse({
|
|
45
|
+
collection: {
|
|
46
|
+
config: collection
|
|
47
|
+
},
|
|
48
|
+
doc: originalDoc,
|
|
49
|
+
filename,
|
|
50
|
+
isOriginal: true,
|
|
51
|
+
operation: 'transform',
|
|
52
|
+
req
|
|
53
|
+
});
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
throw new Error(`Unable to read retained original ${filename}`);
|
|
56
|
+
}
|
|
57
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
58
|
+
file = {
|
|
59
|
+
name: filename,
|
|
60
|
+
data: buffer,
|
|
61
|
+
mimetype: storedOriginal.mimeType,
|
|
62
|
+
size: buffer.length
|
|
63
|
+
};
|
|
64
|
+
shouldOverwriteExistingFiles = true;
|
|
65
|
+
} else if (filename && url) {
|
|
66
|
+
// File is remote
|
|
67
|
+
file = await downloadFileToBuffer({
|
|
68
|
+
data: fileData,
|
|
69
|
+
req,
|
|
70
|
+
uploadConfig: collection.upload
|
|
71
|
+
});
|
|
72
|
+
shouldOverwriteExistingFiles = !externalUploadSource;
|
|
73
|
+
}
|
|
74
|
+
} catch (err) {
|
|
75
|
+
throw new FileRetrievalError(req.t, err instanceof Error ? err.message : undefined);
|
|
76
|
+
}
|
|
77
|
+
// A stored file whose type cannot be detected from its bytes or extension keeps the type
|
|
78
|
+
// saved on the document.
|
|
79
|
+
if (file && !file.mimetype && storedMimeType) {
|
|
80
|
+
file = {
|
|
81
|
+
...file,
|
|
82
|
+
mimetype: storedMimeType
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
if (file && source.type === 'retainedOriginal' && currentFilename) {
|
|
86
|
+
file = {
|
|
87
|
+
...file,
|
|
88
|
+
name: currentFilename
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
file,
|
|
93
|
+
shouldOverwriteExistingFiles
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=readUploadSource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/source/readUploadSource.ts"],"sourcesContent":["import type { SanitizedCollectionConfig, TypeWithID } from '../../../collections/config/types.js'\nimport type { PayloadRequest } from '../../../types/index.js'\nimport type { UploadSource } from './selectUploadSource.js'\n\nimport { FileRetrievalError, Forbidden } from '../../../errors/index.js'\nimport { downloadFileToBuffer, resolveExternalFileURL } from '../../downloadFileToBuffer.js'\nimport { getFileByPath } from '../../getFileByPath.js'\nimport { validateUploadURL } from '../../validateUploadURL.js'\nimport { getStoredOriginal } from './selectUploadSource.js'\n\n/**\n * Reads the bytes of a source that did not arrive with the operation: a stored local file, a\n * stored original in managed cloud storage, or a remote URL. Checks the path and the URL policy\n * before anything is read.\n */\nexport async function readUploadSource({\n collection,\n currentFilename,\n originalDoc,\n req,\n source,\n storedMimeType,\n}: {\n collection: SanitizedCollectionConfig\n /** The main file's name. A file read from the retained original keeps it. */\n currentFilename?: string\n originalDoc: unknown\n req: PayloadRequest\n source: Exclude<UploadSource, { type: 'newUpload' } | { type: 'none' }>\n /** The saved MIME type, used when the read file's type cannot be detected. */\n storedMimeType?: string\n}): Promise<{\n file?: NonNullable<PayloadRequest['file']>\n /** Set when a file was read. True when the read file replaces the stored one. */\n shouldOverwriteExistingFiles?: boolean\n}> {\n const { serverURL } = req.payload.config\n const { disableLocalStorage, staticDir } = collection.upload\n const storedOriginal = getStoredOriginal({ source })\n const externalUploadSource = source.type === 'externalURL' ? source.fileData : undefined\n const fileData =\n source.type === 'documentFile' || source.type === 'externalURL'\n ? source.fileData\n : source.original\n const { filename, url } = fileData\n\n if (filename && (filename.includes('../') || filename.includes('..\\\\'))) {\n throw new Forbidden(req.t)\n }\n\n const isLocalFile = Boolean((serverURL && url?.startsWith(serverURL)) || url?.startsWith('/'))\n\n // A caller-supplied URL must pass the same `pasteURL` policy as the paste-url endpoint.\n // Checked outside the try below so policy errors reach the caller as 400s.\n if (externalUploadSource) {\n validateUploadURL({\n requireAllowList: false,\n uploadConfig: collection.upload,\n url: resolveExternalFileURL({ req, url: externalUploadSource.url }).url.href,\n })\n }\n\n let file: NonNullable<PayloadRequest['file']> | undefined\n let shouldOverwriteExistingFiles: boolean | undefined\n\n try {\n if (!externalUploadSource && !disableLocalStorage && isLocalFile) {\n // File is stored locally\n file = await getFileByPath(`${staticDir}/${filename}`)\n shouldOverwriteExistingFiles = true\n } else if (filename && storedOriginal && collection.upload.fileOperations) {\n const { retrieveFileResponse } = await import('../../endpoints/getFile.js')\n const response = await retrieveFileResponse({\n collection: { config: collection },\n doc: originalDoc as TypeWithID,\n filename,\n isOriginal: true,\n operation: 'transform',\n req,\n })\n\n if (!response.ok) {\n throw new Error(`Unable to read retained original ${filename}`)\n }\n\n const buffer = Buffer.from(await response.arrayBuffer())\n file = {\n name: filename,\n data: buffer,\n mimetype: storedOriginal.mimeType,\n size: buffer.length,\n }\n shouldOverwriteExistingFiles = true\n } else if (filename && url) {\n // File is remote\n file = await downloadFileToBuffer({ data: fileData, req, uploadConfig: collection.upload })\n shouldOverwriteExistingFiles = !externalUploadSource\n }\n } catch (err: unknown) {\n throw new FileRetrievalError(req.t, err instanceof Error ? err.message : undefined)\n }\n\n // A stored file whose type cannot be detected from its bytes or extension keeps the type\n // saved on the document.\n if (file && !file.mimetype && storedMimeType) {\n file = { ...file, mimetype: storedMimeType }\n }\n\n if (file && source.type === 'retainedOriginal' && currentFilename) {\n file = { ...file, name: currentFilename }\n }\n\n return { file, shouldOverwriteExistingFiles }\n}\n"],"names":["FileRetrievalError","Forbidden","downloadFileToBuffer","resolveExternalFileURL","getFileByPath","validateUploadURL","getStoredOriginal","readUploadSource","collection","currentFilename","originalDoc","req","source","storedMimeType","serverURL","payload","config","disableLocalStorage","staticDir","upload","storedOriginal","externalUploadSource","type","fileData","undefined","original","filename","url","includes","t","isLocalFile","Boolean","startsWith","requireAllowList","uploadConfig","href","file","shouldOverwriteExistingFiles","fileOperations","retrieveFileResponse","response","doc","isOriginal","operation","ok","Error","buffer","Buffer","from","arrayBuffer","name","data","mimetype","mimeType","size","length","err","message"],"mappings":"AAIA,SAASA,kBAAkB,EAAEC,SAAS,QAAQ,2BAA0B;AACxE,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,gCAA+B;AAC5F,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,iBAAiB,QAAQ,0BAAyB;AAE3D;;;;CAIC,GACD,OAAO,eAAeC,iBAAiB,EACrCC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,GAAG,EACHC,MAAM,EACNC,cAAc,EAUf;IAKC,MAAM,EAAEC,SAAS,EAAE,GAAGH,IAAII,OAAO,CAACC,MAAM;IACxC,MAAM,EAAEC,mBAAmB,EAAEC,SAAS,EAAE,GAAGV,WAAWW,MAAM;IAC5D,MAAMC,iBAAiBd,kBAAkB;QAAEM;IAAO;IAClD,MAAMS,uBAAuBT,OAAOU,IAAI,KAAK,gBAAgBV,OAAOW,QAAQ,GAAGC;IAC/E,MAAMD,WACJX,OAAOU,IAAI,KAAK,kBAAkBV,OAAOU,IAAI,KAAK,gBAC9CV,OAAOW,QAAQ,GACfX,OAAOa,QAAQ;IACrB,MAAM,EAAEC,QAAQ,EAAEC,GA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1B,iBAAiB;YACjBS,OAAO,MAAMlC,qBAAqB;gBAAEiD,MAAM5B;gBAAUZ;gBAAKuB,cAAc1B,WAAWW,MAAM;YAAC;YACzFkB,+BAA+B,CAAChB;QAClC;IACF,EAAE,OAAOmC,KAAc;QACrB,MAAM,IAAIxD,mBAAmBW,IAAIkB,CAAC,EAAE2B,eAAeX,QAAQW,IAAIC,OAAO,GAAGjC;IAC3E;IAEA,yFAAyF;IACzF,yBAAyB;IACzB,IAAIY,QAAQ,CAACA,KAAKgB,QAAQ,IAAIvC,gBAAgB;QAC5CuB,OAAO;YAAE,GAAGA,IAAI;YAAEgB,UAAUvC;QAAe;IAC7C;IAEA,IAAIuB,QAAQxB,OAAOU,IAAI,KAAK,sBAAsBb,iBAAiB;QACjE2B,OAAO;YAAE,GAAGA,IAAI;YAAEc,MAAMzC;QAAgB;IAC1C;IAEA,OAAO;QAAE2B;QAAMC;IAA6B;AAC9C"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { PayloadRequest } from '../../../types/index.js';
|
|
2
|
+
import type { ExternalUploadSource } from '../../sanitizeUploadData.js';
|
|
3
|
+
import type { FileData, OriginalFileData } from '../../types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Where the file of this operation comes from. Only a new upload arrives with its bytes. The
|
|
6
|
+
* other sources are read later, and only when the operation needs their bytes.
|
|
7
|
+
*/
|
|
8
|
+
export type UploadSource =
|
|
9
|
+
/** A file sent with this operation. */
|
|
10
|
+
{
|
|
11
|
+
file: NonNullable<PayloadRequest['file']>;
|
|
12
|
+
type: 'newUpload';
|
|
13
|
+
}
|
|
14
|
+
/** A file at a URL the caller gave. */
|
|
15
|
+
| {
|
|
16
|
+
fileData: ExternalUploadSource;
|
|
17
|
+
type: 'externalURL';
|
|
18
|
+
}
|
|
19
|
+
/** The file that a URL in the create data points at, or the stored main file. */
|
|
20
|
+
| {
|
|
21
|
+
fileData: FileData;
|
|
22
|
+
type: 'documentFile';
|
|
23
|
+
}
|
|
24
|
+
/** The stored original of a request-time document that is duplicated. */
|
|
25
|
+
| {
|
|
26
|
+
original: OriginalFileData;
|
|
27
|
+
type: 'duplicatedOriginal';
|
|
28
|
+
}
|
|
29
|
+
/** The stored original of the document that an update changes. */
|
|
30
|
+
| {
|
|
31
|
+
original: OriginalFileData;
|
|
32
|
+
type: 'retainedOriginal';
|
|
33
|
+
}
|
|
34
|
+
/** No file. */
|
|
35
|
+
| {
|
|
36
|
+
type: 'none';
|
|
37
|
+
};
|
|
38
|
+
export declare function selectUploadSource({ currentFileData, externalUploadSource, isDuplicating, newFile, operation, }: {
|
|
39
|
+
/** The file data the document has before this operation. On a create, the incoming data. */
|
|
40
|
+
currentFileData?: FileData;
|
|
41
|
+
externalUploadSource?: ExternalUploadSource;
|
|
42
|
+
isDuplicating?: boolean;
|
|
43
|
+
newFile: PayloadRequest['file'];
|
|
44
|
+
operation: 'create' | 'update';
|
|
45
|
+
}): UploadSource;
|
|
46
|
+
/** The stored original that the source reads, if it reads one. */
|
|
47
|
+
export declare function getStoredOriginal({ source, }: {
|
|
48
|
+
source: UploadSource;
|
|
49
|
+
}): OriginalFileData | undefined;
|
|
50
|
+
//# sourceMappingURL=selectUploadSource.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selectUploadSource.d.ts","sourceRoot":"","sources":["../../../../src/uploads/generateFileData/source/selectUploadSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAC7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAA;AACvE,OAAO,KAAK,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AAIhE;;;GAGG;AACH,MAAM,MAAM,YAAY;AACtB,uCAAuC;AACrC;IAAE,IAAI,EAAE,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE;AAClE,uCAAuC;GACrC;IAAE,QAAQ,EAAE,oBAAoB,CAAC;IAAC,IAAI,EAAE,aAAa,CAAA;CAAE;AACzD,iFAAiF;GAC/E;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,cAAc,CAAA;CAAE;AAC9C,yEAAyE;GACvE;IAAE,QAAQ,EAAE,gBAAgB,CAAC;IAAC,IAAI,EAAE,oBAAoB,CAAA;CAAE;AAC5D,kEAAkE;GAChE;IAAE,QAAQ,EAAE,gBAAgB,CAAC;IAAC,IAAI,EAAE,kBAAkB,CAAA;CAAE;AAC1D,eAAe;GACb;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAA;AAEpB,wBAAgB,kBAAkB,CAAC,EACjC,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,OAAO,EACP,SAAS,GACV,EAAE;IACD,4FAA4F;IAC5F,eAAe,CAAC,EAAE,QAAQ,CAAA;IAC1B,oBAAoB,CAAC,EAAE,oBAAoB,CAAA;IAC3C,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,OAAO,EAAE,cAAc,CAAC,MAAM,CAAC,CAAA;IAC/B,SAAS,EAAE,QAAQ,GAAG,QAAQ,CAAA;CAC/B,GAAG,YAAY,CAwBf;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,EAChC,MAAM,GACP,EAAE;IACD,MAAM,EAAE,YAAY,CAAA;CACrB,GAAG,gBAAgB,GAAG,SAAS,CAI/B"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isRequestTimeFile } from '../../isRequestTimeFile.js';
|
|
2
|
+
export function selectUploadSource({ currentFileData, externalUploadSource, isDuplicating, newFile, operation }) {
|
|
3
|
+
if (newFile) {
|
|
4
|
+
return {
|
|
5
|
+
type: 'newUpload',
|
|
6
|
+
file: newFile
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
if (externalUploadSource) {
|
|
10
|
+
return {
|
|
11
|
+
type: 'externalURL',
|
|
12
|
+
fileData: externalUploadSource
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
if (operation === 'update' && typeof currentFileData?.original?.filename === 'string' && typeof currentFileData.original.url === 'string') {
|
|
16
|
+
return {
|
|
17
|
+
type: 'retainedOriginal',
|
|
18
|
+
original: currentFileData.original
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
// A copy of a dynamic upload starts from the source's original, because its default file has no
|
|
22
|
+
// object.
|
|
23
|
+
if (isDuplicating && isRequestTimeFile({
|
|
24
|
+
entry: currentFileData
|
|
25
|
+
}) && currentFileData?.original) {
|
|
26
|
+
return {
|
|
27
|
+
type: 'duplicatedOriginal',
|
|
28
|
+
original: currentFileData.original
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
return currentFileData ? {
|
|
32
|
+
type: 'documentFile',
|
|
33
|
+
fileData: currentFileData
|
|
34
|
+
} : {
|
|
35
|
+
type: 'none'
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** The stored original that the source reads, if it reads one. */ export function getStoredOriginal({ source }) {
|
|
39
|
+
return source.type === 'retainedOriginal' || source.type === 'duplicatedOriginal' ? source.original : undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=selectUploadSource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/source/selectUploadSource.ts"],"sourcesContent":["import type { PayloadRequest } from '../../../types/index.js'\nimport type { ExternalUploadSource } from '../../sanitizeUploadData.js'\nimport type { FileData, OriginalFileData } from '../../types.js'\n\nimport { isRequestTimeFile } from '../../isRequestTimeFile.js'\n\n/**\n * Where the file of this operation comes from. Only a new upload arrives with its bytes. The\n * other sources are read later, and only when the operation needs their bytes.\n */\nexport type UploadSource =\n /** A file sent with this operation. */\n | { file: NonNullable<PayloadRequest['file']>; type: 'newUpload' }\n /** A file at a URL the caller gave. */\n | { fileData: ExternalUploadSource; type: 'externalURL' }\n /** The file that a URL in the create data points at, or the stored main file. */\n | { fileData: FileData; type: 'documentFile' }\n /** The stored original of a request-time document that is duplicated. */\n | { original: OriginalFileData; type: 'duplicatedOriginal' }\n /** The stored original of the document that an update changes. */\n | { original: OriginalFileData; type: 'retainedOriginal' }\n /** No file. */\n | { type: 'none' }\n\nexport function selectUploadSource({\n currentFileData,\n externalUploadSource,\n isDuplicating,\n newFile,\n operation,\n}: {\n /** The file data the document has before this operation. On a create, the incoming data. */\n currentFileData?: FileData\n externalUploadSource?: ExternalUploadSource\n isDuplicating?: boolean\n newFile: PayloadRequest['file']\n operation: 'create' | 'update'\n}): UploadSource {\n if (newFile) {\n return { type: 'newUpload', file: newFile }\n }\n\n if (externalUploadSource) {\n return { type: 'externalURL', fileData: externalUploadSource }\n }\n\n if (\n operation === 'update' &&\n typeof currentFileData?.original?.filename === 'string' &&\n typeof currentFileData.original.url === 'string'\n ) {\n return { type: 'retainedOriginal', original: currentFileData.original }\n }\n\n // A copy of a dynamic upload starts from the source's original, because its default file has no\n // object.\n if (isDuplicating && isRequestTimeFile({ entry: currentFileData }) && currentFileData?.original) {\n return { type: 'duplicatedOriginal', original: currentFileData.original }\n }\n\n return currentFileData ? { type: 'documentFile', fileData: currentFileData } : { type: 'none' }\n}\n\n/** The stored original that the source reads, if it reads one. */\nexport function getStoredOriginal({\n source,\n}: {\n source: UploadSource\n}): OriginalFileData | undefined {\n return source.type === 'retainedOriginal' || source.type === 'duplicatedOriginal'\n ? source.original\n : undefined\n}\n"],"names":["isRequestTimeFile","selectUploadSource","currentFileData","externalUploadSource","isDuplicating","newFile","operation","type","file","fileData","original","filename","url","entry","getStoredOriginal","source","undefined"],"mappings":"AAIA,SAASA,iBAAiB,QAAQ,6BAA4B;AAoB9D,OAAO,SAASC,mBAAmB,EACjCC,eAAe,EACfC,oBAAoB,EACpBC,aAAa,EACbC,OAAO,EACPC,SAAS,EAQV;IACC,IAAID,SAAS;QACX,OAAO;YAAEE,MAAM;YAAaC,MAAMH;QAAQ;IAC5C;IAEA,IAAIF,sBAAsB;QACxB,OAAO;YAAEI,MAAM;YAAeE,UAAUN;QAAqB;IAC/D;IAEA,IACEG,cAAc,YACd,OAAOJ,iBAAiBQ,UAAUC,aAAa,YAC/C,OAAOT,gBAAgBQ,QAAQ,CAACE,GAAG,KAAK,UACxC;QACA,OAAO;YAAEL,MAAM;YAAoBG,UAAUR,gBAAgBQ,QAAQ;QAAC;IACxE;IAEA,gGAAgG;IAChG,UAAU;IACV,IAAIN,iBAAiBJ,kBAAkB;QAAEa,OAAOX;IAAgB,MAAMA,iBAAiBQ,UAAU;QAC/F,OAAO;YAAEH,MAAM;YAAsBG,UAAUR,gBAAgBQ,QAAQ;QAAC;IAC1E;IAEA,OAAOR,kBAAkB;QAAEK,MAAM;QAAgBE,UAAUP;IAAgB,IAAI;QAAEK,MAAM;IAAO;AAChG;AAEA,gEAAgE,GAChE,OAAO,SAASO,kBAAkB,EAChCC,MAAM,EAGP;IACC,OAAOA,OAAOR,IAAI,KAAK,sBAAsBQ,OAAOR,IAAI,KAAK,uBACzDQ,OAAOL,QAAQ,GACfM;AACN"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SanitizedCollectionConfig } from '../../../collections/config/types.js';
|
|
2
|
+
import type { PayloadRequest } from '../../../types/index.js';
|
|
3
|
+
/** Checks the file, and uses the detected MIME type when the file is a processable image. */
|
|
4
|
+
export declare function checkFileAndUseDetectedType({ collection, file, req, }: {
|
|
5
|
+
collection: SanitizedCollectionConfig;
|
|
6
|
+
file: NonNullable<PayloadRequest['file']>;
|
|
7
|
+
req: PayloadRequest;
|
|
8
|
+
}): Promise<NonNullable<PayloadRequest['file']>>;
|
|
9
|
+
//# sourceMappingURL=checkFileAndUseDetectedType.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkFileAndUseDetectedType.d.ts","sourceRoot":"","sources":["../../../../src/uploads/generateFileData/utils/checkFileAndUseDetectedType.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAA;AACrF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAK7D,6FAA6F;AAC7F,wBAAsB,2BAA2B,CAAC,EAChD,UAAU,EACV,IAAI,EACJ,GAAG,GACJ,EAAE;IACD,UAAU,EAAE,yBAAyB,CAAA;IACrC,IAAI,EAAE,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;IACzC,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAY/C"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { checkFileRestrictions } from '../../checkFileRestrictions.js';
|
|
2
|
+
import { isProcessableImage } from '../../isProcessableImage.js';
|
|
3
|
+
/** Checks the file, and uses the detected MIME type when the file is a processable image. */ export async function checkFileAndUseDetectedType({ collection, file, req }) {
|
|
4
|
+
const detectedFileType = await checkFileRestrictions({
|
|
5
|
+
collection,
|
|
6
|
+
file,
|
|
7
|
+
req
|
|
8
|
+
});
|
|
9
|
+
const shouldUseDetectedFileType = detectedFileType && (isProcessableImage(file.mimetype) || isProcessableImage(detectedFileType.mime));
|
|
10
|
+
if (shouldUseDetectedFileType && detectedFileType.mime !== file.mimetype) {
|
|
11
|
+
return {
|
|
12
|
+
...file,
|
|
13
|
+
mimetype: detectedFileType.mime
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
return file;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=checkFileAndUseDetectedType.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/utils/checkFileAndUseDetectedType.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../../collections/config/types.js'\nimport type { PayloadRequest } from '../../../types/index.js'\n\nimport { checkFileRestrictions } from '../../checkFileRestrictions.js'\nimport { isProcessableImage } from '../../isProcessableImage.js'\n\n/** Checks the file, and uses the detected MIME type when the file is a processable image. */\nexport async function checkFileAndUseDetectedType({\n collection,\n file,\n req,\n}: {\n collection: SanitizedCollectionConfig\n file: NonNullable<PayloadRequest['file']>\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> {\n const detectedFileType = await checkFileRestrictions({ collection, file, req })\n\n const shouldUseDetectedFileType =\n detectedFileType &&\n (isProcessableImage(file.mimetype) || isProcessableImage(detectedFileType.mime))\n\n if (shouldUseDetectedFileType && detectedFileType.mime !== file.mimetype) {\n return { ...file, mimetype: detectedFileType.mime }\n }\n\n return file\n}\n"],"names":["checkFileRestrictions","isProcessableImage","checkFileAndUseDetectedType","collection","file","req","detectedFileType","shouldUseDetectedFileType","mimetype","mime"],"mappings":"AAGA,SAASA,qBAAqB,QAAQ,iCAAgC;AACtE,SAASC,kBAAkB,QAAQ,8BAA6B;AAEhE,2FAA2F,GAC3F,OAAO,eAAeC,4BAA4B,EAChDC,UAAU,EACVC,IAAI,EACJC,GAAG,EAKJ;IACC,MAAMC,mBAAmB,MAAMN,sBAAsB;QAAEG;QAAYC;QAAMC;IAAI;IAE7E,MAAME,4BACJD,oBACCL,CAAAA,mBAAmBG,KAAKI,QAAQ,KAAKP,mBAAmBK,iBAAiBG,IAAI,CAAA;IAEhF,IAAIF,6BAA6BD,iBAAiBG,IAAI,KAAKL,KAAKI,QAAQ,EAAE;QACxE,OAAO;YAAE,GAAGJ,IAAI;YAAEI,UAAUF,iBAAiBG,IAAI;QAAC;IACpD;IAEA,OAAOL;AACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateImageSizeFilename.d.ts","sourceRoot":"","sources":["../../../../src/uploads/generateFileData/utils/generateImageSizeFilename.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,KAAK,mBAAmB,GAAG;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA;AACD,eAAO,MAAM,yBAAyB,mDAKnC,mBAAmB,KAAG,MAExB,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/utils/generateImageSizeFilename.ts"],"sourcesContent":["/**\n * Create a new image name based on the output image name, the dimensions and\n * the extension.\n *\n * Ignore the fact that duplicate names could happen if the there is one\n * size with `width AND height` and one with only `height OR width`. Because\n * space is expensive, we will reuse the same image for both sizes.\n *\n * @param outputImageName - the sanitized image name\n * @param bufferInfo - the buffer info\n * @param extension - the extension to use\n * @returns the new image name that is not taken\n */\ntype CreateImageNameArgs = {\n extension: string\n height: number\n outputImageName: string\n width: number\n}\nexport const generateImageSizeFilename = ({\n extension,\n height,\n outputImageName,\n width,\n}: CreateImageNameArgs): string => {\n return `${outputImageName}-${width}x${height}.${extension}`\n}\n"],"names":["generateImageSizeFilename","extension","height","outputImageName","width"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAOD,OAAO,MAAMA,4BAA4B,CAAC,EACxCC,SAAS,EACTC,MAAM,EACNC,eAAe,EACfC,KAAK,EACe;IACpB,OAAO,GAAGD,gBAAgB,CAAC,EAAEC,MAAM,CAAC,EAAEF,OAAO,CAAC,EAAED,WAAW;AAC7D,EAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SanitizedCollectionConfig } from '../../../collections/config/types.js';
|
|
2
|
+
import type { PayloadRequest } from '../../../types/index.js';
|
|
3
|
+
/** An original that the client uploaded to the storage provider itself. */
|
|
4
|
+
export type ProviderOriginal = {
|
|
5
|
+
_objectKey?: string;
|
|
6
|
+
filename: string;
|
|
7
|
+
key: string;
|
|
8
|
+
prefix?: string;
|
|
9
|
+
};
|
|
10
|
+
/** Where the files of this upload are stored. */
|
|
11
|
+
export type UploadStorage = {
|
|
12
|
+
/** The new file is kept as `original` only where it can be stored. */
|
|
13
|
+
canStoreOriginal: boolean;
|
|
14
|
+
/** The collection's storage plugin manages its files (`upload.fileOperations`). */
|
|
15
|
+
hasManagedCloudStorage: boolean;
|
|
16
|
+
/** Set when the client uploaded the file to the provider and its receipt was verified. */
|
|
17
|
+
providerOriginal?: ProviderOriginal;
|
|
18
|
+
/** New files are staged for the managed storage, because the client did not upload them. */
|
|
19
|
+
shouldStageCloudFiles: boolean;
|
|
20
|
+
};
|
|
21
|
+
export declare function getUploadStorage({ collection, file, req, }: {
|
|
22
|
+
collection: SanitizedCollectionConfig;
|
|
23
|
+
/** The new file of this operation, if any. */
|
|
24
|
+
file: PayloadRequest['file'];
|
|
25
|
+
req: PayloadRequest;
|
|
26
|
+
}): UploadStorage;
|
|
27
|
+
//# sourceMappingURL=getUploadStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getUploadStorage.d.ts","sourceRoot":"","sources":["../../../../src/uploads/generateFileData/utils/getUploadStorage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAA;AACrF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAE7D,2EAA2E;AAC3E,MAAM,MAAM,gBAAgB,GAAG;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,iDAAiD;AACjD,MAAM,MAAM,aAAa,GAAG;IAC1B,sEAAsE;IACtE,gBAAgB,EAAE,OAAO,CAAA;IACzB,mFAAmF;IACnF,sBAAsB,EAAE,OAAO,CAAA;IAC/B,0FAA0F;IAC1F,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IACnC,4FAA4F;IAC5F,qBAAqB,EAAE,OAAO,CAAA;CAC/B,CAAA;AAED,wBAAgB,gBAAgB,CAAC,EAC/B,UAAU,EACV,IAAI,EACJ,GAAG,GACJ,EAAE;IACD,UAAU,EAAE,yBAAyB,CAAA;IACrC,8CAA8C;IAC9C,IAAI,EAAE,cAAc,CAAC,MAAM,CAAC,CAAA;IAC5B,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,aAAa,CAgChB"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function getUploadStorage({ collection, file, req }) {
|
|
2
|
+
const upload = collection.upload;
|
|
3
|
+
const hasManagedCloudStorage = Boolean(upload.fileOperations);
|
|
4
|
+
const uploadReference = file?.uploadReference;
|
|
5
|
+
const hasProviderDirectReference = uploadReference && typeof uploadReference === 'object' && !('uploadId' in uploadReference);
|
|
6
|
+
const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal;
|
|
7
|
+
const providerOriginal = hasProviderDirectReference && 'signedReceipt' in uploadReference && uploadReference.signedReceipt === verifiedOriginal?.signedReceipt && verifiedOriginal && typeof upload.adapter === 'string' ? {
|
|
8
|
+
_objectKey: verifiedOriginal._objectKey,
|
|
9
|
+
filename: verifiedOriginal.filename,
|
|
10
|
+
key: verifiedOriginal.key,
|
|
11
|
+
prefix: verifiedOriginal.prefix
|
|
12
|
+
} : undefined;
|
|
13
|
+
const shouldStageCloudFiles = hasManagedCloudStorage && !hasProviderDirectReference;
|
|
14
|
+
return {
|
|
15
|
+
canStoreOriginal: Boolean(!upload.disableLocalStorage || shouldStageCloudFiles || providerOriginal),
|
|
16
|
+
hasManagedCloudStorage,
|
|
17
|
+
providerOriginal,
|
|
18
|
+
shouldStageCloudFiles
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=getUploadStorage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/utils/getUploadStorage.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../../collections/config/types.js'\nimport type { PayloadRequest } from '../../../types/index.js'\n\n/** An original that the client uploaded to the storage provider itself. */\nexport type ProviderOriginal = {\n _objectKey?: string\n filename: string\n key: string\n prefix?: string\n}\n\n/** Where the files of this upload are stored. */\nexport type UploadStorage = {\n /** The new file is kept as `original` only where it can be stored. */\n canStoreOriginal: boolean\n /** The collection's storage plugin manages its files (`upload.fileOperations`). */\n hasManagedCloudStorage: boolean\n /** Set when the client uploaded the file to the provider and its receipt was verified. */\n providerOriginal?: ProviderOriginal\n /** New files are staged for the managed storage, because the client did not upload them. */\n shouldStageCloudFiles: boolean\n}\n\nexport function getUploadStorage({\n collection,\n file,\n req,\n}: {\n collection: SanitizedCollectionConfig\n /** The new file of this operation, if any. */\n file: PayloadRequest['file']\n req: PayloadRequest\n}): UploadStorage {\n const upload = collection.upload\n const hasManagedCloudStorage = Boolean(upload.fileOperations)\n const uploadReference = file?.uploadReference\n const hasProviderDirectReference =\n uploadReference && typeof uploadReference === 'object' && !('uploadId' in uploadReference)\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | ({ signedReceipt: string } & ProviderOriginal)\n | undefined\n const providerOriginal =\n hasProviderDirectReference &&\n 'signedReceipt' in uploadReference &&\n uploadReference.signedReceipt === verifiedOriginal?.signedReceipt &&\n verifiedOriginal &&\n typeof upload.adapter === 'string'\n ? {\n _objectKey: verifiedOriginal._objectKey,\n filename: verifiedOriginal.filename,\n key: verifiedOriginal.key,\n prefix: verifiedOriginal.prefix,\n }\n : undefined\n const shouldStageCloudFiles = hasManagedCloudStorage && !hasProviderDirectReference\n\n return {\n canStoreOriginal: Boolean(\n !upload.disableLocalStorage || shouldStageCloudFiles || providerOriginal,\n ),\n hasManagedCloudStorage,\n providerOriginal,\n shouldStageCloudFiles,\n }\n}\n"],"names":["getUploadStorage","collection","file","req","upload","hasManagedCloudStorage","Boolean","fileOperations","uploadReference","hasProviderDirectReference","verifiedOriginal","context","_payloadVerifiedProviderOriginal","providerOriginal","signedReceipt","adapter","_objectKey","filename","key","prefix","undefined","shouldStageCloudFiles","canStoreOriginal","disableLocalStorage"],"mappings":"AAuBA,OAAO,SAASA,iBAAiB,EAC/BC,UAAU,EACVC,IAAI,EACJC,GAAG,EAMJ;IACC,MAAMC,SAASH,WAAWG,MAAM;IAChC,MAAMC,yBAAyBC,QAAQF,OAAOG,cAAc;IAC5D,MAAMC,kBAAkBN,MAAMM;IAC9B,MAAMC,6BACJD,mBAAmB,OAAOA,oBAAoB,YAAY,CAAE,CAAA,cAAcA,eAAc;IAC1F,MAAME,mBAAmBP,IAAIQ,OAAO,EAAEC;IAGtC,MAAMC,mBACJJ,8BACA,mBAAmBD,mBACnBA,gBAAgBM,aAAa,KAAKJ,kBAAkBI,iBACpDJ,oBACA,OAAON,OAAOW,OAAO,KAAK,WACtB;QACEC,YAAYN,iBAAiBM,UAAU;QACvCC,UAAUP,iBAAiBO,QAAQ;QACnCC,KAAKR,iBAAiBQ,GAAG;QACzBC,QAAQT,iBAAiBS,MAAM;IACjC,IACAC;IACN,MAAMC,wBAAwBhB,0BAA0B,CAACI;IAEzD,OAAO;QACLa,kBAAkBhB,QAChB,CAACF,OAAOmB,mBAAmB,IAAIF,yBAAyBR;QAE1DR;QACAQ;QACAQ;IACF;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { PayloadRequest } from '../../../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Maps an error from transformer planning or the pipeline. A validation error and a broken
|
|
4
|
+
* transformer contract keep their own message; anything else is logged and becomes a
|
|
5
|
+
* `FileUploadError`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function toFileUploadError({ err, req }: {
|
|
8
|
+
err: unknown;
|
|
9
|
+
req: PayloadRequest;
|
|
10
|
+
}): Error;
|
|
11
|
+
//# sourceMappingURL=toFileUploadError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toFileUploadError.d.ts","sourceRoot":"","sources":["../../../../src/uploads/generateFileData/utils/toFileUploadError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAK7D;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;IAAE,GAAG,EAAE,OAAO,CAAC;IAAC,GAAG,EAAE,cAAc,CAAA;CAAE,GAAG,KAAK,CAQ5F"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { FileUploadError, ValidationError } from '../../../errors/index.js';
|
|
2
|
+
import { TransformerContractError } from '../../../errors/TransformerContractError.js';
|
|
3
|
+
/**
|
|
4
|
+
* Maps an error from transformer planning or the pipeline. A validation error and a broken
|
|
5
|
+
* transformer contract keep their own message; anything else is logged and becomes a
|
|
6
|
+
* `FileUploadError`.
|
|
7
|
+
*/ export function toFileUploadError({ err, req }) {
|
|
8
|
+
if (err instanceof ValidationError) {
|
|
9
|
+
return err;
|
|
10
|
+
}
|
|
11
|
+
req.payload.logger.error(err);
|
|
12
|
+
return err instanceof TransformerContractError ? err : new FileUploadError(req.t);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=toFileUploadError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/uploads/generateFileData/utils/toFileUploadError.ts"],"sourcesContent":["import type { PayloadRequest } from '../../../types/index.js'\n\nimport { FileUploadError, ValidationError } from '../../../errors/index.js'\nimport { TransformerContractError } from '../../../errors/TransformerContractError.js'\n\n/**\n * Maps an error from transformer planning or the pipeline. A validation error and a broken\n * transformer contract keep their own message; anything else is logged and becomes a\n * `FileUploadError`.\n */\nexport function toFileUploadError({ err, req }: { err: unknown; req: PayloadRequest }): Error {\n if (err instanceof ValidationError) {\n return err\n }\n\n req.payload.logger.error(err)\n\n return err instanceof TransformerContractError ? err : new FileUploadError(req.t)\n}\n"],"names":["FileUploadError","ValidationError","TransformerContractError","toFileUploadError","err","req","payload","logger","error","t"],"mappings":"AAEA,SAASA,eAAe,EAAEC,eAAe,QAAQ,2BAA0B;AAC3E,SAASC,wBAAwB,QAAQ,8CAA6C;AAEtF;;;;CAIC,GACD,OAAO,SAASC,kBAAkB,EAAEC,GAAG,EAAEC,GAAG,EAAyC;IACnF,IAAID,eAAeH,iBAAiB;QAClC,OAAOG;IACT;IAEAC,IAAIC,OAAO,CAACC,MAAM,CAACC,KAAK,CAACJ;IAEzB,OAAOA,eAAeF,2BAA2BE,MAAM,IAAIJ,gBAAgBK,IAAII,CAAC;AAClF"}
|
|
@@ -142,7 +142,7 @@ export const getFileFromUploadInstructions = async ({ collectionSlug, file, req
|
|
|
142
142
|
// Only Sharp's bridge stores sizes.
|
|
143
143
|
hasVariantsBuiltOnRequest: !(req.payload.config.upload?.transformers ?? []).some((transformer)=>{
|
|
144
144
|
const bridge = getUploadTransformerInternal(transformer);
|
|
145
|
-
return Boolean(bridge?.
|
|
145
|
+
return Boolean(bridge?.transformUpload) && bridge?.handlesCollection?.({
|
|
146
146
|
collectionSlug
|
|
147
147
|
}) !== false;
|
|
148
148
|
}),
|
|
@@ -289,7 +289,7 @@ const reservedUploadReferenceKeys = new Set([
|
|
|
289
289
|
/**
|
|
290
290
|
* Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw
|
|
291
291
|
* `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point
|
|
292
|
-
* fallback, done in generateFileData
|
|
292
|
+
* fallback, done in generateFileData/) isn't available yet at this point in the request
|
|
293
293
|
* lifecycle. Saved `_transforms` keys are not checked here: whether a stage applies them is known
|
|
294
294
|
* only after planning, so generateFileData decides that download.
|
|
295
295
|
*/ const requestHasSizeEdits = (req)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"sourcesContent":["import type { ReadableStream } from 'node:stream/web'\n\nimport { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport { mkdir, rm, stat } from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\nimport type { PayloadRequest } from '../types/index.js'\nimport type { SanitizedUploadConfig, UploadEdits, UploadInstructions } from './types.js'\n\nimport { APIError } from '../errors/APIError.js'\nimport { sanitizeFilename } from '../utilities/sanitizeFilename.js'\nimport { sanitizeUploadPrefix } from '../utilities/sanitizeUploadPrefix.js'\nimport { verifyClientUploadReceipt } from './clientUploadReceipt.js'\nimport { docWithFilenameExists } from './docWithFilenameExists.js'\nimport { normalizeStorageKey } from './fileVersioning/naming.js'\nimport { getFileContentRequirement, HEADER_PROBE_BYTE_LENGTH } from './getFileContentRequirement.js'\nimport { getImageSize } from './getImageSize.js'\nimport { hasCropOrResizeEdit } from './hasCropOrResizeEdit.js'\nimport { getStagedFile } from './stagedUpload.js'\nimport { getUploadTransformerInternal } from './transformers/uploadTransformerBridge.js'\n\nexport const getFileFromUploadInstructions = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (req.context) {\n delete req.context._payloadVerifiedProviderOriginal\n }\n\n if (\n !file ||\n typeof file !== 'object' ||\n typeof file.filename !== 'string' ||\n typeof file.mimeType !== 'string' ||\n !Number.isSafeInteger(file.size) ||\n file.size < 0 ||\n !file.uploadReference ||\n typeof file.uploadReference !== 'object' ||\n Array.isArray(file.uploadReference)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n /**\n * Handlers fetch files uploaded to a storage provider. An uploadId points to a temporary file\n * already stored by Payload, so no handler is needed.\n */\n if ('uploadId' in file.uploadReference) {\n return getStagedFile({ collectionSlug, req, uploadReference: file.uploadReference })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]!.config.upload\n const clientData = getClientData({ uploadReference: file.uploadReference })\n let allowOverwrite = false\n let providerFilename = file.filename\n let verifiedOriginal:\n | {\n _objectKey?: string\n filename: string\n key: string\n prefix?: string\n signedReceipt: string\n }\n | undefined\n\n if (uploadConfig?.uploadInstructions?.requiresUploadReceipt) {\n const signedReceipt =\n 'signedReceipt' in file.uploadReference ? file.uploadReference.signedReceipt : undefined\n const receipt = verifyClientUploadReceipt({\n collectionSlug,\n filename: file.filename,\n req,\n signedReceipt,\n })\n allowOverwrite = receipt.allowOverwrite === true\n let storageFilePath: string\n\n try {\n storageFilePath = normalizeStorageKey({ key: receipt.storageFilePath })\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n const isReceiptForUploadedFilename = path.posix.basename(storageFilePath) === file.filename\n const expectedKeySuffix = [receipt.filePrefix, receipt._objectKey, file.filename]\n .filter(Boolean)\n .join('/')\n\n if (\n (!allowOverwrite &&\n (!receipt._objectKey ||\n !isReceiptForUploadedFilename ||\n !`/${storageFilePath}`.endsWith(`/${expectedKeySuffix}`))) ||\n ('prefix' in file.uploadReference && file.uploadReference.prefix !== receipt.filePrefix) ||\n ('_objectKey' in file.uploadReference &&\n file.uploadReference._objectKey !== receipt._objectKey)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n providerFilename = file.filename\n if (!allowOverwrite) {\n verifiedOriginal = {\n _objectKey: receipt._objectKey,\n filename: file.filename,\n key: storageFilePath,\n prefix: receipt.filePrefix,\n signedReceipt: signedReceipt as string,\n }\n }\n file = {\n ...file,\n uploadReference: {\n _objectKey: receipt._objectKey,\n ...(receipt.adapterData && { adapterData: receipt.adapterData }),\n ...(clientData && { clientData }),\n prefix: receipt.filePrefix,\n signedReceipt,\n },\n }\n } else {\n const { _objectKey, prefix, signedReceipt } = file.uploadReference\n file = {\n ...file,\n uploadReference: {\n ...(_objectKey !== undefined && { _objectKey }),\n ...(clientData && { clientData }),\n ...(prefix !== undefined && { prefix }),\n ...(signedReceipt !== undefined && { signedReceipt }),\n },\n }\n }\n\n const prefix =\n 'prefix' in file.uploadReference && typeof file.uploadReference.prefix === 'string'\n ? file.uploadReference.prefix\n : undefined\n\n let sanitizedFilename: string\n\n try {\n sanitizedFilename = sanitizeFilename(file.filename)\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (\n sanitizedFilename !== file.filename ||\n (typeof prefix === 'string' && sanitizeUploadPrefix(prefix) !== prefix)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n // Provider-backed references are submitted with the document request. They may only claim a\n // new object identity; existing top-level and generated filenames already belong to another\n // document and must continue through that document's read access checks.\n if (\n !allowOverwrite &&\n (await docWithFilenameExists({\n collectionSlug,\n filename: file.filename,\n matchAnyPrefix: true,\n path: '',\n prefix,\n req,\n }))\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (!uploadConfig || !uploadConfig.handlers) {\n throw new APIError('uploadConfig.handlers is not present for ' + collectionSlug)\n }\n\n const contentRequirement = getFileContentRequirement({\n filename: providerFilename,\n hasSizeEdits: requestHasSizeEdits(req),\n // Only Sharp's bridge stores sizes.\n hasVariantsBuiltOnRequest: !(req.payload.config.upload?.transformers ?? []).some(\n (transformer) => {\n const bridge = getUploadTransformerInternal(transformer)\n\n return (\n Boolean(bridge?.prepareUpload) &&\n bridge?.handlesCollection?.({ collectionSlug }) !== false\n )\n },\n ),\n mimeType: file.mimeType,\n uploadConfig,\n })\n const providerFile = { ...file, filename: providerFilename }\n const rememberVerifiedOriginal = () => {\n if (verifiedOriginal) {\n req.context ??= {}\n req.context._payloadVerifiedProviderOriginal = verifiedOriginal\n }\n }\n\n // Nothing downstream reads this file's content - use the client-reported metadata directly\n // instead of re-downloading a file that, for a chunked upload, can be far larger than\n // the server's available memory or disk.\n if (contentRequirement === 'none') {\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n rangeHeader: file.size > 0 ? 'bytes=0-0' : undefined,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n const prefix = await readBoundedPrefix(response, 1)\n if (file.size > 0 && prefix.length === 0) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n }\n\n if (contentRequirement === 'header') {\n const headerFile = await fetchHeaderOnly({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n if (headerFile) {\n rememberVerifiedOriginal()\n return { ...headerFile, name: file.filename }\n }\n // The header wasn't enough to determine the image's dimensions - fall through to a full fetch.\n }\n\n const { contentType, tempFilePath } = await downloadToTempFile({\n collectionSlug,\n file: providerFile,\n req,\n })\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: contentType || file.mimeType,\n size: file.size,\n tempFilePath,\n uploadReference: file.uploadReference,\n }\n}\n\n/**\n * Downloads the whole file of a client upload that `getFileFromUploadInstructions` returned\n * without its full contents. `generateFileData` calls this when a transformer accepts the upload,\n * because only then is the document available to `canTransform`.\n */\nexport const fetchFullClientUpload = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: NonNullable<PayloadRequest['file']>\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (!file.uploadReference) {\n throw new APIError('Upload has no complete file or upload reference.', 400)\n }\n\n // Download by the name the object was stored under. Something earlier in the operation, such\n // as a hook, can rename the request file, so a verified receipt's filename comes first.\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { filename?: string }\n | undefined\n\n const { contentType, tempFilePath } = await downloadToTempFile({\n collectionSlug,\n file: {\n filename: verifiedOriginal?.filename ?? file.name,\n mimeType: file.mimetype,\n size: file.size,\n uploadReference: file.uploadReference as UploadInstructions['file']['uploadReference'],\n },\n req,\n })\n\n // The storage provider's content type wins over the type the client claimed, on purpose: it\n // describes the stored object. The check after the download can still change it from the bytes.\n return { ...file, data: Buffer.alloc(0), mimetype: contentType || file.mimetype, tempFilePath }\n}\n\nconst downloadToTempFile = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<{ contentType: null | string; tempFilePath: string }> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n req,\n uploadConfig: req.payload.collections[collectionSlug]!.config.upload,\n })\n\n const tempFilePath = await streamResponseToTempFile({ req, response })\n if ((await stat(tempFilePath)).size !== file.size) {\n await rm(tempFilePath, { force: true })\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n req.context ??= {}\n req.context._payloadClientUploadTempFile = true\n\n return { contentType: response.headers.get('Content-Type'), tempFilePath }\n}\n\nconst reservedUploadReferenceKeys = new Set([\n '_objectKey',\n 'adapterData',\n 'clientData',\n 'prefix',\n 'signedReceipt',\n])\n\n/**\n * Collects the fields the client added to `uploadReference`. Payload never reads them, so\n * adapters must verify them before use.\n */\nconst getClientData = ({\n uploadReference,\n}: {\n uploadReference: Record<string, unknown>\n}): Record<string, unknown> | undefined => {\n const entries = Object.entries(uploadReference).filter(\n ([key]) => !reservedUploadReferenceKeys.has(key),\n )\n\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw\n * `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point\n * fallback, done in generateFileData.ts) isn't available yet at this point in the request\n * lifecycle. Saved `_transforms` keys are not checked here: whether a stage applies them is known\n * only after planning, so generateFileData decides that download.\n */\nconst requestHasSizeEdits = (req: PayloadRequest): boolean => {\n const uploadEdits = req.query?.uploadEdits\n if (typeof uploadEdits !== 'object' || uploadEdits === null) {\n return false\n }\n\n return hasCropOrResizeEdit(uploadEdits)\n}\n\n/**\n * Fetches only the first `HEADER_PROBE_BYTE_LENGTH` bytes of the upload (via a best-effort byte\n * range request) and uses them to probe an image's dimensions, without downloading the rest of\n * the file. Returns null if that isn't enough to determine the dimensions, so the caller can\n * fall back to a full fetch.\n */\nconst fetchHeaderOnly = async ({\n collectionSlug,\n file,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<NonNullable<PayloadRequest['file']> | null> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n rangeHeader: `bytes=0-${HEADER_PROBE_BYTE_LENGTH - 1}`,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n\n const headerBuffer = await readBoundedPrefix(response, HEADER_PROBE_BYTE_LENGTH)\n\n try {\n await getImageSize({\n file: {\n name: file.filename,\n data: headerBuffer,\n mimetype: file.mimeType,\n size: file.size,\n },\n })\n } catch {\n return null\n }\n\n return {\n name: file.filename,\n data: headerBuffer,\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n}\n\nconst assertProviderFileSize = ({\n expectedSize,\n response,\n}: {\n expectedSize: number\n response: Response\n}): void => {\n const contentRange = response.headers.get('Content-Range')\n const reportedSize =\n response.status === 206\n ? contentRange?.match(/^bytes \\d+-\\d+\\/(\\d+)$/)?.[1]\n : response.headers.get('Content-Length')\n\n if (\n reportedSize === undefined ||\n reportedSize === null ||\n Number(reportedSize) !== expectedSize\n ) {\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n}\n\n/**\n * Runs the collection's upload handlers, following a single redirect if one is returned.\n * `rangeHeader`, when passed, is a best-effort hint - handlers that ignore it simply return the\n * full file, which callers must still bound their own reads against.\n */\nconst fetchUploadResponse = async ({\n collectionSlug,\n file,\n rangeHeader,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n rangeHeader?: string\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<Response> => {\n const scopedReq = rangeHeader ? withRangeHeader(req, rangeHeader) : req\n\n let response: null | Response = null\n let error: unknown\n\n for (const handler of uploadConfig.handlers!) {\n try {\n const result = await handler(scopedReq, {\n doc: null!,\n params: {\n collection: collectionSlug,\n filename: file.filename,\n uploadReference: file.uploadReference,\n },\n })\n if (result) {\n response = result\n /**\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n *\n * @see packages/payload/src/uploads/types.ts\n */\n break\n }\n } catch (err) {\n error = err\n }\n }\n\n if (!response) {\n if (error) {\n req.payload.logger.error(error)\n }\n\n throw new APIError('Expected response from the upload handler.')\n }\n\n if (response.status >= 300 && response.status < 400) {\n const redirectUrl = response.headers.get('Location')\n if (redirectUrl) {\n response = await fetch(redirectUrl, {\n ...(rangeHeader && { headers: { Range: rangeHeader } }),\n })\n }\n }\n\n if (!response.ok) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n\n return response\n}\n\n/**\n * Overrides `req.headers` with a `Range` header while leaving the real incoming request\n * untouched. Uses a Proxy, rather than cloning `req`, because `req` is a native `Request`\n * instance at runtime - accessors like `.signal` are brand-checked against `req`'s internal\n * slots, so a plain clone (e.g. `Object.create(req)`) throws once a handler reads one of them.\n * Forwarding reads through `Reflect.get(req, prop, req)` keeps `this` bound to the real `req`\n * so those accessors keep working.\n */\nconst withRangeHeader = (req: PayloadRequest, rangeHeader: string): PayloadRequest => {\n const headers = new Headers(req.headers)\n headers.set('range', rangeHeader)\n\n return new Proxy(req, {\n get(target, prop) {\n return prop === 'headers' ? headers : Reflect.get(target, prop, target)\n },\n })\n}\n\n/**\n * Reads at most `maxBytes` from the response body, then cancels the reader - so a handler that\n * ignores the range hint and starts streaming the whole file is still cut short on our end.\n */\nconst readBoundedPrefix = async (response: Response, maxBytes: number): Promise<Buffer> => {\n if (!response.body) {\n return Buffer.alloc(0)\n }\n\n const reader = response.body.getReader()\n const chunks: Buffer[] = []\n let total = 0\n\n try {\n while (total < maxBytes) {\n const { done, value } = await reader.read()\n if (done || !value) {\n break\n }\n\n const remaining = maxBytes - total\n const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value\n chunks.push(Buffer.from(chunk))\n total += chunk.byteLength\n }\n } finally {\n await reader.cancel().catch(() => {})\n }\n\n return Buffer.concat(chunks, total)\n}\n\n/**\n * Streams the fetched upload straight to disk instead of buffering it in memory. A client upload\n * (e.g. Azure's chunkLargeFiles) can be far larger than the server's available memory, so this\n * avoids re-downloading the whole file into a single in-memory buffer just to read it back out.\n */\nconst streamResponseToTempFile = async ({\n req,\n response,\n}: {\n req: PayloadRequest\n response: Response\n}): Promise<string> => {\n if (!response.body) {\n throw new APIError('Expected a response body from the upload handler.')\n }\n\n const tempFileDir = req.payload.config.upload?.tempFileDir || os.tmpdir()\n await mkdir(tempFileDir, { recursive: true })\n const tempFilePath = path.join(tempFileDir, `payload-client-upload-${randomUUID()}`)\n\n try {\n await pipeline(\n Readable.fromWeb(response.body as ReadableStream<Uint8Array>),\n fs.createWriteStream(tempFilePath),\n )\n } catch (error) {\n await rm(tempFilePath, { force: true })\n throw error\n }\n\n return tempFilePath\n}\n"],"names":["randomUUID","fs","mkdir","rm","stat","os","path","Readable","pipeline","APIError","sanitizeFilename","sanitizeUploadPrefix","verifyClientUploadReceipt","docWithFilenameExists","normalizeStorageKey","getFileContentRequirement","HEADER_PROBE_BYTE_LENGTH","getImageSize","hasCropOrResizeEdit","getStagedFile","getUploadTransformerInternal","getFileFromUploadInstructions","collectionSlug","file","req","context","_payloadVerifiedProviderOriginal","filename","mimeType","Number","isSafeInteger","size","uploadReference","Array","isArray","uploadConfig","payload","collections","config","upload","clientData","getClientData","allowOverwrite","providerFilename","verifiedOriginal","uploadInstructions","requiresUploadReceipt","signedReceipt","undefined","receipt","storageFilePath","key","isReceiptForUploadedFilename","posix","basename","expectedKeySuffix","filePrefix","_objectKey","filter","Boolean","join","endsWith","prefix","adapterData","sanitizedFilename","matchAnyPrefix","handlers","contentRequirement","hasSizeEdits","requestHasSizeEdits","hasVariantsBuiltOnRequest","transformers","some","transformer","bridge","prepareUpload","handlesCollection","providerFile","rememberVerifiedOriginal","response","fetchUploadResponse","rangeHeader","assertProviderFileSize","expectedSize","readBoundedPrefix","length","name","data","Buffer","alloc","mimetype","headerFile","fetchHeaderOnly","contentType","tempFilePath","downloadToTempFile","fetchFullClientUpload","streamResponseToTempFile","force","_payloadClientUploadTempFile","headers","get","reservedUploadReferenceKeys","Set","entries","Object","has","fromEntries","uploadEdits","query","headerBuffer","contentRange","reportedSize","status","match","scopedReq","withRangeHeader","error","handler","result","doc","params","collection","err","logger","redirectUrl","fetch","Range","ok","Headers","set","Proxy","target","prop","Reflect","maxBytes","body","reader","getReader","chunks","total","done","value","read","remaining","chunk","byteLength","subarray","push","from","cancel","catch","concat","tempFileDir","tmpdir","recursive","fromWeb","createWriteStream"],"mappings":"AAEA,SAASA,UAAU,QAAQ,cAAa;AACxC,OAAOC,QAAQ,UAAS;AACxB,SAASC,KAAK,EAAEC,EAAE,EAAEC,IAAI,QAAQ,mBAAkB;AAClD,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,cAAa;AACtC,SAASC,QAAQ,QAAQ,uBAAsB;AAK/C,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,yBAAyB,QAAQ,2BAA0B;AACpE,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,mBAAmB,QAAQ,6BAA4B;AAChE,SAASC,yBAAyB,EAAEC,wBAAwB,QAAQ,iCAAgC;AACpG,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,oBAAmB;AACjD,SAASC,4BAA4B,QAAQ,4CAA2C;AAExF,OAAO,MAAMC,gCAAgC,OAAO,EAClDC,cAAc,EACdC,IAAI,EACJC,GAAG,EAKJ;IACC,IAAIA,IAAIC,OAAO,EAAE;QACf,OAAOD,IAAIC,OAAO,CAACC,gCAAgC;IACrD;IAEA,IACE,CAACH,QACD,OAAOA,SAAS,YAChB,OAAOA,KAAKI,QAAQ,KAAK,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Y,OAAO,CAACE,MAAM,CAACC,MAAM,EAAEkH,eAAepJ,GAAGqJ,MAAM;IACvE,MAAMxJ,MAAMuJ,aAAa;QAAEE,WAAW;IAAK;IAC3C,MAAM7D,eAAexF,KAAKsD,IAAI,CAAC6F,aAAa,CAAC,sBAAsB,EAAEzJ,cAAc;IAEnF,IAAI;QACF,MAAMQ,SACJD,SAASqJ,OAAO,CAAC7E,SAASyD,IAAI,GAC9BvI,GAAG4J,iBAAiB,CAAC/D;IAEzB,EAAE,OAAOuB,OAAO;QACd,MAAMlH,GAAG2F,cAAc;YAAEI,OAAO;QAAK;QACrC,MAAMmB;IACR;IAEA,OAAOvB;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/getFileFromUploadInstructions.ts"],"sourcesContent":["import type { ReadableStream } from 'node:stream/web'\n\nimport { randomUUID } from 'node:crypto'\nimport fs from 'node:fs'\nimport { mkdir, rm, stat } from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\n\nimport type { PayloadRequest } from '../types/index.js'\nimport type { SanitizedUploadConfig, UploadEdits, UploadInstructions } from './types.js'\n\nimport { APIError } from '../errors/APIError.js'\nimport { sanitizeFilename } from '../utilities/sanitizeFilename.js'\nimport { sanitizeUploadPrefix } from '../utilities/sanitizeUploadPrefix.js'\nimport { verifyClientUploadReceipt } from './clientUploadReceipt.js'\nimport { docWithFilenameExists } from './docWithFilenameExists.js'\nimport { normalizeStorageKey } from './fileVersioning/naming.js'\nimport { getFileContentRequirement, HEADER_PROBE_BYTE_LENGTH } from './getFileContentRequirement.js'\nimport { getImageSize } from './getImageSize.js'\nimport { hasCropOrResizeEdit } from './hasCropOrResizeEdit.js'\nimport { getStagedFile } from './stagedUpload.js'\nimport { getUploadTransformerInternal } from './transformers/uploadTransformerBridge.js'\n\nexport const getFileFromUploadInstructions = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (req.context) {\n delete req.context._payloadVerifiedProviderOriginal\n }\n\n if (\n !file ||\n typeof file !== 'object' ||\n typeof file.filename !== 'string' ||\n typeof file.mimeType !== 'string' ||\n !Number.isSafeInteger(file.size) ||\n file.size < 0 ||\n !file.uploadReference ||\n typeof file.uploadReference !== 'object' ||\n Array.isArray(file.uploadReference)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n /**\n * Handlers fetch files uploaded to a storage provider. An uploadId points to a temporary file\n * already stored by Payload, so no handler is needed.\n */\n if ('uploadId' in file.uploadReference) {\n return getStagedFile({ collectionSlug, req, uploadReference: file.uploadReference })\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]!.config.upload\n const clientData = getClientData({ uploadReference: file.uploadReference })\n let allowOverwrite = false\n let providerFilename = file.filename\n let verifiedOriginal:\n | {\n _objectKey?: string\n filename: string\n key: string\n prefix?: string\n signedReceipt: string\n }\n | undefined\n\n if (uploadConfig?.uploadInstructions?.requiresUploadReceipt) {\n const signedReceipt =\n 'signedReceipt' in file.uploadReference ? file.uploadReference.signedReceipt : undefined\n const receipt = verifyClientUploadReceipt({\n collectionSlug,\n filename: file.filename,\n req,\n signedReceipt,\n })\n allowOverwrite = receipt.allowOverwrite === true\n let storageFilePath: string\n\n try {\n storageFilePath = normalizeStorageKey({ key: receipt.storageFilePath })\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n const isReceiptForUploadedFilename = path.posix.basename(storageFilePath) === file.filename\n const expectedKeySuffix = [receipt.filePrefix, receipt._objectKey, file.filename]\n .filter(Boolean)\n .join('/')\n\n if (\n (!allowOverwrite &&\n (!receipt._objectKey ||\n !isReceiptForUploadedFilename ||\n !`/${storageFilePath}`.endsWith(`/${expectedKeySuffix}`))) ||\n ('prefix' in file.uploadReference && file.uploadReference.prefix !== receipt.filePrefix) ||\n ('_objectKey' in file.uploadReference &&\n file.uploadReference._objectKey !== receipt._objectKey)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n providerFilename = file.filename\n if (!allowOverwrite) {\n verifiedOriginal = {\n _objectKey: receipt._objectKey,\n filename: file.filename,\n key: storageFilePath,\n prefix: receipt.filePrefix,\n signedReceipt: signedReceipt as string,\n }\n }\n file = {\n ...file,\n uploadReference: {\n _objectKey: receipt._objectKey,\n ...(receipt.adapterData && { adapterData: receipt.adapterData }),\n ...(clientData && { clientData }),\n prefix: receipt.filePrefix,\n signedReceipt,\n },\n }\n } else {\n const { _objectKey, prefix, signedReceipt } = file.uploadReference\n file = {\n ...file,\n uploadReference: {\n ...(_objectKey !== undefined && { _objectKey }),\n ...(clientData && { clientData }),\n ...(prefix !== undefined && { prefix }),\n ...(signedReceipt !== undefined && { signedReceipt }),\n },\n }\n }\n\n const prefix =\n 'prefix' in file.uploadReference && typeof file.uploadReference.prefix === 'string'\n ? file.uploadReference.prefix\n : undefined\n\n let sanitizedFilename: string\n\n try {\n sanitizedFilename = sanitizeFilename(file.filename)\n } catch {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (\n sanitizedFilename !== file.filename ||\n (typeof prefix === 'string' && sanitizeUploadPrefix(prefix) !== prefix)\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n // Provider-backed references are submitted with the document request. They may only claim a\n // new object identity; existing top-level and generated filenames already belong to another\n // document and must continue through that document's read access checks.\n if (\n !allowOverwrite &&\n (await docWithFilenameExists({\n collectionSlug,\n filename: file.filename,\n matchAnyPrefix: true,\n path: '',\n prefix,\n req,\n }))\n ) {\n throw new APIError('Invalid upload reference.', 400)\n }\n\n if (!uploadConfig || !uploadConfig.handlers) {\n throw new APIError('uploadConfig.handlers is not present for ' + collectionSlug)\n }\n\n const contentRequirement = getFileContentRequirement({\n filename: providerFilename,\n hasSizeEdits: requestHasSizeEdits(req),\n // Only Sharp's bridge stores sizes.\n hasVariantsBuiltOnRequest: !(req.payload.config.upload?.transformers ?? []).some(\n (transformer) => {\n const bridge = getUploadTransformerInternal(transformer)\n\n return (\n Boolean(bridge?.transformUpload) &&\n bridge?.handlesCollection?.({ collectionSlug }) !== false\n )\n },\n ),\n mimeType: file.mimeType,\n uploadConfig,\n })\n const providerFile = { ...file, filename: providerFilename }\n const rememberVerifiedOriginal = () => {\n if (verifiedOriginal) {\n req.context ??= {}\n req.context._payloadVerifiedProviderOriginal = verifiedOriginal\n }\n }\n\n // Nothing downstream reads this file's content - use the client-reported metadata directly\n // instead of re-downloading a file that, for a chunked upload, can be far larger than\n // the server's available memory or disk.\n if (contentRequirement === 'none') {\n const response = await fetchUploadResponse({\n collectionSlug,\n file: providerFile,\n rangeHeader: file.size > 0 ? 'bytes=0-0' : undefined,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n const prefix = await readBoundedPrefix(response, 1)\n if (file.size > 0 && prefix.length === 0) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n }\n\n if (contentRequirement === 'header') {\n const headerFile = await fetchHeaderOnly({\n collectionSlug,\n file: providerFile,\n req,\n uploadConfig,\n })\n if (headerFile) {\n rememberVerifiedOriginal()\n return { ...headerFile, name: file.filename }\n }\n // The header wasn't enough to determine the image's dimensions - fall through to a full fetch.\n }\n\n const { contentType, tempFilePath } = await downloadToTempFile({\n collectionSlug,\n file: providerFile,\n req,\n })\n rememberVerifiedOriginal()\n\n return {\n name: file.filename,\n data: Buffer.alloc(0),\n mimetype: contentType || file.mimeType,\n size: file.size,\n tempFilePath,\n uploadReference: file.uploadReference,\n }\n}\n\n/**\n * Downloads the whole file of a client upload that `getFileFromUploadInstructions` returned\n * without its full contents. `generateFileData` calls this when a transformer accepts the upload,\n * because only then is the document available to `canTransform`.\n */\nexport const fetchFullClientUpload = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: NonNullable<PayloadRequest['file']>\n req: PayloadRequest\n}): Promise<NonNullable<PayloadRequest['file']>> => {\n if (!file.uploadReference) {\n throw new APIError('Upload has no complete file or upload reference.', 400)\n }\n\n // Download by the name the object was stored under. Something earlier in the operation, such\n // as a hook, can rename the request file, so a verified receipt's filename comes first.\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { filename?: string }\n | undefined\n\n const { contentType, tempFilePath } = await downloadToTempFile({\n collectionSlug,\n file: {\n filename: verifiedOriginal?.filename ?? file.name,\n mimeType: file.mimetype,\n size: file.size,\n uploadReference: file.uploadReference as UploadInstructions['file']['uploadReference'],\n },\n req,\n })\n\n // The storage provider's content type wins over the type the client claimed, on purpose: it\n // describes the stored object. The check after the download can still change it from the bytes.\n return { ...file, data: Buffer.alloc(0), mimetype: contentType || file.mimetype, tempFilePath }\n}\n\nconst downloadToTempFile = async ({\n collectionSlug,\n file,\n req,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n}): Promise<{ contentType: null | string; tempFilePath: string }> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n req,\n uploadConfig: req.payload.collections[collectionSlug]!.config.upload,\n })\n\n const tempFilePath = await streamResponseToTempFile({ req, response })\n if ((await stat(tempFilePath)).size !== file.size) {\n await rm(tempFilePath, { force: true })\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n req.context ??= {}\n req.context._payloadClientUploadTempFile = true\n\n return { contentType: response.headers.get('Content-Type'), tempFilePath }\n}\n\nconst reservedUploadReferenceKeys = new Set([\n '_objectKey',\n 'adapterData',\n 'clientData',\n 'prefix',\n 'signedReceipt',\n])\n\n/**\n * Collects the fields the client added to `uploadReference`. Payload never reads them, so\n * adapters must verify them before use.\n */\nconst getClientData = ({\n uploadReference,\n}: {\n uploadReference: Record<string, unknown>\n}): Record<string, unknown> | undefined => {\n const entries = Object.entries(uploadReference).filter(\n ([key]) => !reservedUploadReferenceKeys.has(key),\n )\n\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Whether the request's `uploadEdits` query param carries a crop or resize edit - reads the raw\n * `req.query.uploadEdits`, since a full parse (with its `data`/`originalDoc` focal-point\n * fallback, done in generateFileData/) isn't available yet at this point in the request\n * lifecycle. Saved `_transforms` keys are not checked here: whether a stage applies them is known\n * only after planning, so generateFileData decides that download.\n */\nconst requestHasSizeEdits = (req: PayloadRequest): boolean => {\n const uploadEdits = req.query?.uploadEdits\n if (typeof uploadEdits !== 'object' || uploadEdits === null) {\n return false\n }\n\n return hasCropOrResizeEdit(uploadEdits)\n}\n\n/**\n * Fetches only the first `HEADER_PROBE_BYTE_LENGTH` bytes of the upload (via a best-effort byte\n * range request) and uses them to probe an image's dimensions, without downloading the rest of\n * the file. Returns null if that isn't enough to determine the dimensions, so the caller can\n * fall back to a full fetch.\n */\nconst fetchHeaderOnly = async ({\n collectionSlug,\n file,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<NonNullable<PayloadRequest['file']> | null> => {\n const response = await fetchUploadResponse({\n collectionSlug,\n file,\n rangeHeader: `bytes=0-${HEADER_PROBE_BYTE_LENGTH - 1}`,\n req,\n uploadConfig,\n })\n assertProviderFileSize({ expectedSize: file.size, response })\n\n const headerBuffer = await readBoundedPrefix(response, HEADER_PROBE_BYTE_LENGTH)\n\n try {\n await getImageSize({\n file: {\n name: file.filename,\n data: headerBuffer,\n mimetype: file.mimeType,\n size: file.size,\n },\n })\n } catch {\n return null\n }\n\n return {\n name: file.filename,\n data: headerBuffer,\n mimetype: response.headers.get('Content-Type') || file.mimeType,\n size: file.size,\n uploadReference: file.uploadReference,\n }\n}\n\nconst assertProviderFileSize = ({\n expectedSize,\n response,\n}: {\n expectedSize: number\n response: Response\n}): void => {\n const contentRange = response.headers.get('Content-Range')\n const reportedSize =\n response.status === 206\n ? contentRange?.match(/^bytes \\d+-\\d+\\/(\\d+)$/)?.[1]\n : response.headers.get('Content-Length')\n\n if (\n reportedSize === undefined ||\n reportedSize === null ||\n Number(reportedSize) !== expectedSize\n ) {\n throw new APIError('Uploaded source size does not match the declared size.', 400)\n }\n}\n\n/**\n * Runs the collection's upload handlers, following a single redirect if one is returned.\n * `rangeHeader`, when passed, is a best-effort hint - handlers that ignore it simply return the\n * full file, which callers must still bound their own reads against.\n */\nconst fetchUploadResponse = async ({\n collectionSlug,\n file,\n rangeHeader,\n req,\n uploadConfig,\n}: {\n collectionSlug: string\n file: UploadInstructions['file']\n rangeHeader?: string\n req: PayloadRequest\n uploadConfig: SanitizedUploadConfig\n}): Promise<Response> => {\n const scopedReq = rangeHeader ? withRangeHeader(req, rangeHeader) : req\n\n let response: null | Response = null\n let error: unknown\n\n for (const handler of uploadConfig.handlers!) {\n try {\n const result = await handler(scopedReq, {\n doc: null!,\n params: {\n collection: collectionSlug,\n filename: file.filename,\n uploadReference: file.uploadReference,\n },\n })\n if (result) {\n response = result\n /**\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n *\n * @see packages/payload/src/uploads/types.ts\n */\n break\n }\n } catch (err) {\n error = err\n }\n }\n\n if (!response) {\n if (error) {\n req.payload.logger.error(error)\n }\n\n throw new APIError('Expected response from the upload handler.')\n }\n\n if (response.status >= 300 && response.status < 400) {\n const redirectUrl = response.headers.get('Location')\n if (redirectUrl) {\n response = await fetch(redirectUrl, {\n ...(rangeHeader && { headers: { Range: rangeHeader } }),\n })\n }\n }\n\n if (!response.ok) {\n throw new APIError('Uploaded source is not readable.', 400)\n }\n\n return response\n}\n\n/**\n * Overrides `req.headers` with a `Range` header while leaving the real incoming request\n * untouched. Uses a Proxy, rather than cloning `req`, because `req` is a native `Request`\n * instance at runtime - accessors like `.signal` are brand-checked against `req`'s internal\n * slots, so a plain clone (e.g. `Object.create(req)`) throws once a handler reads one of them.\n * Forwarding reads through `Reflect.get(req, prop, req)` keeps `this` bound to the real `req`\n * so those accessors keep working.\n */\nconst withRangeHeader = (req: PayloadRequest, rangeHeader: string): PayloadRequest => {\n const headers = new Headers(req.headers)\n headers.set('range', rangeHeader)\n\n return new Proxy(req, {\n get(target, prop) {\n return prop === 'headers' ? headers : Reflect.get(target, prop, target)\n },\n })\n}\n\n/**\n * Reads at most `maxBytes` from the response body, then cancels the reader - so a handler that\n * ignores the range hint and starts streaming the whole file is still cut short on our end.\n */\nconst readBoundedPrefix = async (response: Response, maxBytes: number): Promise<Buffer> => {\n if (!response.body) {\n return Buffer.alloc(0)\n }\n\n const reader = response.body.getReader()\n const chunks: Buffer[] = []\n let total = 0\n\n try {\n while (total < maxBytes) {\n const { done, value } = await reader.read()\n if (done || !value) {\n break\n }\n\n const remaining = maxBytes - total\n const chunk = value.byteLength > remaining ? value.subarray(0, remaining) : value\n chunks.push(Buffer.from(chunk))\n total += chunk.byteLength\n }\n } finally {\n await reader.cancel().catch(() => {})\n }\n\n return Buffer.concat(chunks, total)\n}\n\n/**\n * Streams the fetched upload straight to disk instead of buffering it in memory. A client upload\n * (e.g. Azure's chunkLargeFiles) can be far larger than the server's available memory, so this\n * avoids re-downloading the whole file into a single in-memory buffer just to read it back out.\n */\nconst streamResponseToTempFile = async ({\n req,\n response,\n}: {\n req: PayloadRequest\n response: Response\n}): Promise<string> => {\n if (!response.body) {\n throw new APIError('Expected a response body from the upload handler.')\n }\n\n const tempFileDir = req.payload.config.upload?.tempFileDir || os.tmpdir()\n await mkdir(tempFileDir, { recursive: true })\n const tempFilePath = path.join(tempFileDir, `payload-client-upload-${randomUUID()}`)\n\n try {\n await pipeline(\n Readable.fromWeb(response.body as ReadableStream<Uint8Array>),\n fs.createWriteStream(tempFilePath),\n )\n } catch (error) {\n await rm(tempFilePath, { force: true })\n throw error\n }\n\n return tempFilePath\n}\n"],"names":["randomUUID","fs","mkdir","rm","stat","os","path","Readable","pipeline","APIError","sanitizeFilename","sanitizeUploadPrefix","verifyClientUploadReceipt","docWithFilenameExists","normalizeStorageKey","getFileContentRequirement","HEADER_PROBE_BYTE_LENGTH","getImageSize","hasCropOrResizeEdit","getStagedFile","getUploadTransformerInternal","getFileFromUploadInstructions","collectionSlug","file","req","context","_payloadVerifiedProviderOriginal","filename","mimeType","Number","isSafeInteger","size","uploadReference","Array","isArray","uploadConfig","payload","collections","config","upload","clientData","getClientData","allowOverwrite","providerFilename","verifiedOriginal","uploadInstructions","requiresUploadReceipt","signedReceipt","undefined","receipt","storageFilePath","key","isReceiptForUploadedFilename","posix","basename","expectedKeySuffix","filePrefix","_objectKey","filter","Boolean","join","endsWith","prefix","adapterData","sanitizedFilename","matchAnyPrefix","handlers","contentRequirement","hasSizeEdits","requestHasSizeEdits","hasVariantsBuiltOnRequest","transformers","some","transformer","bridge","transformUpload","handlesCollection","providerFile","rememberVerifiedOriginal","response","fetchUploadResponse","rangeHeader","assertProviderFileSize","expectedSize","readBoundedPrefix","length","name","data","Buffer","alloc","mimetype","headerFile","fetchHeaderOnly","contentType","tempFilePath","downloadToTempFile","fetchFullClientUpload","streamResponseToTempFile","force","_payloadClientUploadTempFile","headers","get","reservedUploadReferenceKeys","Set","entries","Object","has","fromEntries","uploadEdits","query","headerBuffer","contentRange","reportedSize","status","match","scopedReq","withRangeHeader","error","handler","result","doc","params","collection","err","logger","redirectUrl","fetch","Range","ok","Headers","set","Proxy","target","prop","Reflect","maxBytes","body","reader","getReader","chunks","total","done","value","read","remaining","chunk","byteLength","subarray","push","from","cancel","catch","concat","tempFileDir","tmpdir","recursive","fromWeb","createWriteStream"],"mappings":"AAEA,SAASA,UAAU,QAAQ,cAAa;AACxC,OAAOC,QAAQ,UAAS;AACxB,SAASC,KAAK,EAAEC,EAAE,EAAEC,IAAI,QAAQ,mBAAkB;AAClD,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,cAAa;AACtC,SAASC,QAAQ,QAAQ,uBAAsB;AAK/C,SAASC,QAAQ,QAAQ,wBAAuB;AAChD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M,EAAEM,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAML,OAAOM,IAAI;YACzC,IAAIF,QAAQ,CAACC,OAAO;gBAClB;YACF;YAEA,MAAME,YAAYT,WAAWK;YAC7B,MAAMK,QAAQH,MAAMI,UAAU,GAAGF,YAAYF,MAAMK,QAAQ,CAAC,GAAGH,aAAaF;YAC5EH,OAAOS,IAAI,CAAC5D,OAAO6D,IAAI,CAACJ;YACxBL,SAASK,MAAMC,UAAU;QAC3B;IACF,SAAU;QACR,MAAMT,OAAOa,MAAM,GAAGC,KAAK,CAAC,KAAO;IACrC;IAEA,OAAO/D,OAAOgE,MAAM,CAACb,QAAQC;AAC/B;AAEA;;;;CAIC,GACD,MAAM3C,2BAA2B,OAAO,EACtCzE,GAAG,EACHuD,QAAQ,EAIT;IACC,IAAI,CAACA,SAASyD,IAAI,EAAE;QAClB,MAAM,IAAI/H,SAAS;IACrB;IAEA,MAAMgJ,cAAcjI,IAAIY,OAAO,CAACE,MAAM,CAACC,MAAM,EAAEkH,eAAepJ,GAAGqJ,MAAM;IACvE,MAAMxJ,MAAMuJ,aAAa;QAAEE,WAAW;IAAK;IAC3C,MAAM7D,eAAexF,KAAKsD,IAAI,CAAC6F,aAAa,CAAC,sBAAsB,EAAEzJ,cAAc;IAEnF,IAAI;QACF,MAAMQ,SACJD,SAASqJ,OAAO,CAAC7E,SAASyD,IAAI,GAC9BvI,GAAG4J,iBAAiB,CAAC/D;IAEzB,EAAE,OAAOuB,OAAO;QACd,MAAMlH,GAAG2F,cAAc;YAAEI,OAAO;QAAK;QACrC,MAAMmB;IACR;IAEA,OAAOvB;AACT"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { SanitizedCollectionConfig } from '../collections/config/types.js';
|
|
2
|
+
import type { Document, PayloadRequest } from '../types/index.js';
|
|
3
|
+
import type { FileSizes, OriginalFileData } from './types.js';
|
|
4
|
+
/** The default entry describes the saved crop; its bytes are built from the original on request. */
|
|
5
|
+
export declare function getRequestTimeDefaultFileData({ original, transforms, }: {
|
|
6
|
+
original: OriginalFileData;
|
|
7
|
+
transforms: Document['_transforms'];
|
|
8
|
+
}): {
|
|
9
|
+
_objectKey: null;
|
|
10
|
+
_stored: boolean;
|
|
11
|
+
filename: string;
|
|
12
|
+
filesize: null;
|
|
13
|
+
height: number | null;
|
|
14
|
+
mimeType: string;
|
|
15
|
+
prefix: string | undefined;
|
|
16
|
+
url: null;
|
|
17
|
+
width: number | null;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Generate names from the current size declarations, without retaining old virtual metadata.
|
|
21
|
+
* Names are based on the main file's `filename`, and never reuse the main file's, the original's
|
|
22
|
+
* or a `reservedFilenames` name.
|
|
23
|
+
*/
|
|
24
|
+
export declare function getRequestTimeVariants({ collection, documentID, filename, original, prefix, req, reservedFilenames, staticPath, }: {
|
|
25
|
+
collection: SanitizedCollectionConfig;
|
|
26
|
+
documentID?: number | string;
|
|
27
|
+
/** The main file's name. */
|
|
28
|
+
filename: string;
|
|
29
|
+
original: OriginalFileData;
|
|
30
|
+
prefix?: string;
|
|
31
|
+
req: PayloadRequest;
|
|
32
|
+
/** Other names this document keeps, such as its stored variants. */
|
|
33
|
+
reservedFilenames?: string[];
|
|
34
|
+
staticPath?: string;
|
|
35
|
+
}): Promise<FileSizes>;
|
|
36
|
+
//# sourceMappingURL=requestTimeFileData.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestTimeFileData.d.ts","sourceRoot":"","sources":["../../src/uploads/requestTimeFileData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAEjE,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAM7D,oGAAoG;AACpG,wBAAgB,6BAA6B,CAAC,EAC5C,QAAQ,EACR,UAAU,GACX,EAAE;IACD,QAAQ,EAAE,gBAAgB,CAAA;IAC1B,UAAU,EAAE,QAAQ,CAAC,aAAa,CAAC,CAAA;CACpC;IAIG,UAAU;IACV,OAAO;IACP,QAAQ;IACR,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,MAAM;IACN,GAAG;IACH,KAAK;EAER;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,UAAU,EACV,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,GAAG,EACH,iBAAsB,EACtB,UAAU,GACX,EAAE;IACD,UAAU,EAAE,yBAAyB,CAAA;IACrC,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IAC5B,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,gBAAgB,CAAA;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,cAAc,CAAA;IACnB,oEAAoE;IACpE,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,GAAG,OAAO,CAAC,SAAS,CAAC,CA8BrB"}
|