@payloadcms/next 3.0.0-beta.11 → 3.0.0-beta.13
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/cjs/withPayload.cjs +2 -1
- package/dist/cjs/withPayload.cjs.map +1 -1
- package/dist/exports/routes.d.ts +1 -1
- package/dist/exports/routes.d.ts.map +1 -1
- package/dist/exports/routes.js +1 -1
- package/dist/exports/routes.js.map +1 -1
- package/dist/exports/utilities.d.ts +3 -1
- package/dist/exports/utilities.d.ts.map +1 -1
- package/dist/exports/utilities.js +3 -1
- package/dist/exports/utilities.js.map +1 -1
- package/dist/next-fileupload/handlers.js.map +1 -1
- package/dist/next-fileupload/isEligibleRequest.js +1 -1
- package/dist/next-fileupload/isEligibleRequest.js.map +1 -1
- package/dist/next-fileupload/processMultipart.d.ts.map +1 -1
- package/dist/next-fileupload/processMultipart.js +29 -6
- package/dist/next-fileupload/processMultipart.js.map +1 -1
- package/dist/next-fileupload/utilities.d.ts.map +1 -1
- package/dist/next-fileupload/utilities.js +4 -4
- package/dist/next-fileupload/utilities.js.map +1 -1
- package/dist/routes/graphql/handler.d.ts.map +1 -1
- package/dist/routes/graphql/handler.js +9 -4
- package/dist/routes/graphql/handler.js.map +1 -1
- package/dist/routes/rest/auth/access.d.ts.map +1 -1
- package/dist/routes/rest/auth/access.js +5 -0
- package/dist/routes/rest/auth/access.js.map +1 -1
- package/dist/routes/rest/auth/forgotPassword.d.ts.map +1 -1
- package/dist/routes/rest/auth/forgotPassword.js +7 -2
- package/dist/routes/rest/auth/forgotPassword.js.map +1 -1
- package/dist/routes/rest/auth/init.d.ts.map +1 -1
- package/dist/routes/rest/auth/init.js +6 -0
- package/dist/routes/rest/auth/init.js.map +1 -1
- package/dist/routes/rest/auth/login.d.ts.map +1 -1
- package/dist/routes/rest/auth/login.js +8 -5
- package/dist/routes/rest/auth/login.js.map +1 -1
- package/dist/routes/rest/auth/logout.d.ts.map +1 -1
- package/dist/routes/rest/auth/logout.js +11 -6
- package/dist/routes/rest/auth/logout.js.map +1 -1
- package/dist/routes/rest/auth/me.d.ts.map +1 -1
- package/dist/routes/rest/auth/me.js +5 -0
- package/dist/routes/rest/auth/me.js.map +1 -1
- package/dist/routes/rest/auth/refresh.d.ts.map +1 -1
- package/dist/routes/rest/auth/refresh.js +11 -7
- package/dist/routes/rest/auth/refresh.js.map +1 -1
- package/dist/routes/rest/auth/registerFirstUser.d.ts.map +1 -1
- package/dist/routes/rest/auth/registerFirstUser.js +17 -5
- package/dist/routes/rest/auth/registerFirstUser.js.map +1 -1
- package/dist/routes/rest/auth/resetPassword.d.ts.map +1 -1
- package/dist/routes/rest/auth/resetPassword.js +8 -5
- package/dist/routes/rest/auth/resetPassword.js.map +1 -1
- package/dist/routes/rest/auth/unlock.d.ts.map +1 -1
- package/dist/routes/rest/auth/unlock.js +7 -2
- package/dist/routes/rest/auth/unlock.js.map +1 -1
- package/dist/routes/rest/auth/verifyEmail.d.ts.map +1 -1
- package/dist/routes/rest/auth/verifyEmail.js +7 -2
- package/dist/routes/rest/auth/verifyEmail.js.map +1 -1
- package/dist/routes/rest/buildFormState.d.ts.map +1 -1
- package/dist/routes/rest/buildFormState.js +11 -0
- package/dist/routes/rest/buildFormState.js.map +1 -1
- package/dist/routes/rest/collections/count.d.ts +3 -0
- package/dist/routes/rest/collections/count.d.ts.map +1 -0
- package/dist/routes/rest/collections/count.js +15 -0
- package/dist/routes/rest/collections/count.js.map +1 -0
- package/dist/routes/rest/collections/create.d.ts.map +1 -1
- package/dist/routes/rest/collections/create.js +5 -0
- package/dist/routes/rest/collections/create.js.map +1 -1
- package/dist/routes/rest/collections/delete.d.ts.map +1 -1
- package/dist/routes/rest/collections/delete.js +7 -0
- package/dist/routes/rest/collections/delete.js.map +1 -1
- package/dist/routes/rest/collections/deleteByID.d.ts.map +1 -1
- package/dist/routes/rest/collections/deleteByID.js +7 -0
- package/dist/routes/rest/collections/deleteByID.js.map +1 -1
- package/dist/routes/rest/collections/docAccess.d.ts.map +1 -1
- package/dist/routes/rest/collections/docAccess.js +5 -0
- package/dist/routes/rest/collections/docAccess.js.map +1 -1
- package/dist/routes/rest/collections/duplicate.d.ts.map +1 -1
- package/dist/routes/rest/collections/duplicate.js +5 -0
- package/dist/routes/rest/collections/duplicate.js.map +1 -1
- package/dist/routes/rest/collections/find.d.ts.map +1 -1
- package/dist/routes/rest/collections/find.js +5 -0
- package/dist/routes/rest/collections/find.js.map +1 -1
- package/dist/routes/rest/collections/findByID.d.ts.map +1 -1
- package/dist/routes/rest/collections/findByID.js +5 -0
- package/dist/routes/rest/collections/findByID.js.map +1 -1
- package/dist/routes/rest/collections/findVersionByID.d.ts.map +1 -1
- package/dist/routes/rest/collections/findVersionByID.js +5 -0
- package/dist/routes/rest/collections/findVersionByID.js.map +1 -1
- package/dist/routes/rest/collections/findVersions.d.ts.map +1 -1
- package/dist/routes/rest/collections/findVersions.js +5 -0
- package/dist/routes/rest/collections/findVersions.js.map +1 -1
- package/dist/routes/rest/collections/preview.d.ts.map +1 -1
- package/dist/routes/rest/collections/preview.js +7 -1
- package/dist/routes/rest/collections/preview.js.map +1 -1
- package/dist/routes/rest/collections/restoreVersion.d.ts.map +1 -1
- package/dist/routes/rest/collections/restoreVersion.js +5 -0
- package/dist/routes/rest/collections/restoreVersion.js.map +1 -1
- package/dist/routes/rest/collections/update.d.ts.map +1 -1
- package/dist/routes/rest/collections/update.js +7 -0
- package/dist/routes/rest/collections/update.js.map +1 -1
- package/dist/routes/rest/collections/updateByID.d.ts.map +1 -1
- package/dist/routes/rest/collections/updateByID.js +5 -0
- package/dist/routes/rest/collections/updateByID.js.map +1 -1
- package/dist/routes/rest/files/getFile.d.ts.map +1 -1
- package/dist/routes/rest/files/getFile.js +15 -8
- package/dist/routes/rest/files/getFile.js.map +1 -1
- package/dist/routes/rest/files/getFileTypeFallback.d.ts +7 -0
- package/dist/routes/rest/files/getFileTypeFallback.d.ts.map +1 -0
- package/dist/routes/rest/files/getFileTypeFallback.js +21 -0
- package/dist/routes/rest/files/getFileTypeFallback.js.map +1 -0
- package/dist/routes/rest/globals/docAccess.d.ts.map +1 -1
- package/dist/routes/rest/globals/docAccess.js +5 -0
- package/dist/routes/rest/globals/docAccess.js.map +1 -1
- package/dist/routes/rest/globals/findOne.d.ts.map +1 -1
- package/dist/routes/rest/globals/findOne.js +5 -0
- package/dist/routes/rest/globals/findOne.js.map +1 -1
- package/dist/routes/rest/globals/findVersionByID.d.ts.map +1 -1
- package/dist/routes/rest/globals/findVersionByID.js +5 -0
- package/dist/routes/rest/globals/findVersionByID.js.map +1 -1
- package/dist/routes/rest/globals/findVersions.d.ts.map +1 -1
- package/dist/routes/rest/globals/findVersions.js +5 -0
- package/dist/routes/rest/globals/findVersions.js.map +1 -1
- package/dist/routes/rest/globals/preview.d.ts.map +1 -1
- package/dist/routes/rest/globals/preview.js +7 -1
- package/dist/routes/rest/globals/preview.js.map +1 -1
- package/dist/routes/rest/globals/restoreVersion.d.ts.map +1 -1
- package/dist/routes/rest/globals/restoreVersion.js +5 -0
- package/dist/routes/rest/globals/restoreVersion.js.map +1 -1
- package/dist/routes/rest/globals/update.d.ts.map +1 -1
- package/dist/routes/rest/globals/update.js +5 -0
- package/dist/routes/rest/globals/update.js.map +1 -1
- package/dist/routes/rest/index.d.ts +1 -0
- package/dist/routes/rest/index.d.ts.map +1 -1
- package/dist/routes/rest/index.js +55 -9
- package/dist/routes/rest/index.js.map +1 -1
- package/dist/routes/rest/routeError.d.ts +5 -4
- package/dist/routes/rest/routeError.d.ts.map +1 -1
- package/dist/routes/rest/routeError.js +25 -11
- package/dist/routes/rest/routeError.js.map +1 -1
- package/dist/utilities/getDataAndFile.d.ts.map +1 -1
- package/dist/utilities/getDataAndFile.js +26 -46
- package/dist/utilities/getDataAndFile.js.map +1 -1
- package/dist/utilities/getPayloadHMR.d.ts +2 -1
- package/dist/utilities/getPayloadHMR.d.ts.map +1 -1
- package/dist/utilities/getPayloadHMR.js +22 -19
- package/dist/utilities/getPayloadHMR.js.map +1 -1
- package/dist/utilities/headersWithCors.d.ts +8 -0
- package/dist/utilities/headersWithCors.d.ts.map +1 -0
- package/dist/utilities/headersWithCors.js +17 -0
- package/dist/utilities/headersWithCors.js.map +1 -0
- package/dist/utilities/initPage.d.ts.map +1 -1
- package/dist/utilities/initPage.js +15 -2
- package/dist/utilities/initPage.js.map +1 -1
- package/dist/views/CreateFirstUser/index.client.js +2 -2
- package/dist/views/CreateFirstUser/index.client.js.map +1 -1
- package/dist/views/CreateFirstUser/index.d.ts.map +1 -1
- package/dist/views/CreateFirstUser/index.js +17 -0
- package/dist/views/CreateFirstUser/index.js.map +1 -1
- package/dist/views/Edit/Default/index.d.ts.map +1 -1
- package/dist/views/Edit/Default/index.js +3 -2
- package/dist/views/Edit/Default/index.js.map +1 -1
- package/dist/views/ForgotPassword/ForgotPasswordForm/index.d.ts +3 -0
- package/dist/views/ForgotPassword/ForgotPasswordForm/index.d.ts.map +1 -0
- package/dist/views/ForgotPassword/ForgotPasswordForm/index.js +55 -0
- package/dist/views/ForgotPassword/ForgotPasswordForm/index.js.map +1 -0
- package/dist/views/ForgotPassword/index.d.ts.map +1 -1
- package/dist/views/ForgotPassword/index.js +3 -39
- package/dist/views/ForgotPassword/index.js.map +1 -1
- package/dist/views/LivePreview/Toolbar/Controls/index.d.ts.map +1 -1
- package/dist/views/LivePreview/Toolbar/Controls/index.js +6 -4
- package/dist/views/LivePreview/Toolbar/Controls/index.js.map +1 -1
- package/dist/views/Login/LoginForm/index.d.ts.map +1 -1
- package/dist/views/Login/LoginForm/index.js +26 -2
- package/dist/views/Login/LoginForm/index.js.map +1 -1
- package/dist/views/Logout/LogoutClient.d.ts.map +1 -1
- package/dist/views/Logout/LogoutClient.js +1 -2
- package/dist/views/Logout/LogoutClient.js.map +1 -1
- package/dist/withPayload.d.ts.map +1 -1
- package/dist/withPayload.js +2 -1
- package/dist/withPayload.js.map +1 -1
- package/package.json +11 -9
- package/src/index.js +0 -1
package/dist/cjs/withPayload.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/withPayload.js"],"names":[],"mappings":"AAAA;;;;GAIG;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/withPayload.js"],"names":[],"mappings":"AAAA;;;;GAIG;;;;;;;;;;;IAoEH,OAA0B;eAA1B;;IAnEa,WAAW;eAAX;;;AAAN,MAAM,cAAc,CAAC,aAAa,CAAC,CAAC;IACzC,OAAO;QACL,GAAG,UAAU;QACb,cAAc;YACZ,GAAI,YAAY,gBAAgB,CAAC,CAAC;YAClC,2BAA2B;gBACzB,QAAQ;uBACF,WAAW,YAAY,EAAE,2BAA2B,CAAC,OAAO,IAAI,EAAE;oBACtE;oBACA;oBACA;iBACD;YACH;YACA,kCAAkC;mBAC5B,YAAY,cAAc,oCAAoC,EAAE;gBACpE;gBACA;gBACA;gBACA;gBACA;gBACA;aACD;QACH;QACA,SAAS,CAAC,eAAe;YACvB,MAAM,wBACJ,OAAO,WAAW,OAAO,KAAK,aAC1B,WAAW,OAAO,CAAC,eAAe,kBAClC;YAEN,OAAO;gBACL,GAAG,qBAAqB;gBACxB,WAAW;uBACL,uBAAuB,aAAa,EAAE;oBAC1C;oBACA;oBACA;oBACA;iBACD;gBACD,gBAAgB;uBACV,uBAAuB,kBAAkB,EAAE;oBAC/C;wBAAE,QAAQ;oBAAwC;oBAClD;wBAAE,MAAM;oBAAwC;oBAChD;wBAAE,QAAQ;oBAAuC;oBACjD;wBAAE,MAAM;oBAAuC;iBAChD;gBACD,SAAS;oBACP,GAAI,uBAAuB,WAAW,CAAC,CAAC;oBACxC,OAAO;wBACL,GAAI,uBAAuB,SAAS,SAAS,CAAC,CAAC;oBACjD;oBACA,UAAU;wBACR,GAAI,uBAAuB,SAAS,YAAY,CAAC,CAAC;wBAClD,iCAAiC;wBACjC,oBAAoB;wBACpB,MAAM;wBACN,UAAU;wBACV,6BAA6B;wBAC7B,QAAQ;wBACR,kBAAkB;wBAClB,eAAe;oBACjB;gBACF;YACF;QACF;IACF;AACF;MAEA,WAAe","file":"withPayload.cjs","sourcesContent":["/**\n * @param {import('next').NextConfig} nextConfig\n *\n * @returns {import('next').NextConfig}\n * */\nexport const withPayload = (nextConfig = {}) => {\n return {\n ...nextConfig,\n experimental: {\n ...(nextConfig?.experimental || {}),\n outputFileTracingExcludes: {\n '**/*': [\n ...(nextConfig.experimental?.outputFileTracingExcludes?.['**/*'] || []),\n 'drizzle-kit',\n 'drizzle-kit/payload',\n 'libsql',\n ],\n },\n serverComponentsExternalPackages: [\n ...(nextConfig?.experimental?.serverComponentsExternalPackages || []),\n 'drizzle-kit',\n 'drizzle-kit/payload',\n 'libsql',\n 'pino',\n 'pino-pretty',\n 'graphql',\n ],\n },\n webpack: (webpackConfig, webpackOptions) => {\n const incomingWebpackConfig =\n typeof nextConfig.webpack === 'function'\n ? nextConfig.webpack(webpackConfig, webpackOptions)\n : webpackConfig\n\n return {\n ...incomingWebpackConfig,\n externals: [\n ...(incomingWebpackConfig?.externals || []),\n 'drizzle-kit',\n 'drizzle-kit/payload',\n 'sharp',\n 'libsql',\n ],\n ignoreWarnings: [\n ...(incomingWebpackConfig?.ignoreWarnings || []),\n { module: /node_modules\\/mongodb\\/lib\\/utils\\.js/ },\n { file: /node_modules\\/mongodb\\/lib\\/utils\\.js/ },\n { module: /node_modules\\/mongodb\\/lib\\/bson\\.js/ },\n { file: /node_modules\\/mongodb\\/lib\\/bson\\.js/ },\n ],\n resolve: {\n ...(incomingWebpackConfig?.resolve || {}),\n alias: {\n ...(incomingWebpackConfig?.resolve?.alias || {}),\n },\n fallback: {\n ...(incomingWebpackConfig?.resolve?.fallback || {}),\n '@aws-sdk/credential-providers': false,\n '@mongodb-js/zstd': false,\n aws4: false,\n kerberos: false,\n 'mongodb-client-encryption': false,\n snappy: false,\n 'supports-color': false,\n 'yocto-queue': false,\n },\n },\n }\n },\n }\n}\n\nexport default withPayload\n"]}
|
package/dist/exports/routes.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { GRAPHQL_PLAYGROUND_GET, GRAPHQL_POST } from '../routes/graphql/index.js';
|
|
2
|
-
export { DELETE as REST_DELETE, GET as REST_GET, PATCH as REST_PATCH, POST as REST_POST, } from '../routes/rest/index.js';
|
|
2
|
+
export { DELETE as REST_DELETE, GET as REST_GET, OPTIONS as REST_OPTIONS, PATCH as REST_PATCH, POST as REST_POST, } from '../routes/rest/index.js';
|
|
3
3
|
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/exports/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAA;AAEjF,OAAO,EACL,MAAM,IAAI,WAAW,EACrB,GAAG,IAAI,QAAQ,EACf,KAAK,IAAI,UAAU,EACnB,IAAI,IAAI,SAAS,GAClB,MAAM,yBAAyB,CAAA"}
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/exports/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAA;AAEjF,OAAO,EACL,MAAM,IAAI,WAAW,EACrB,GAAG,IAAI,QAAQ,EACf,OAAO,IAAI,YAAY,EACvB,KAAK,IAAI,UAAU,EACnB,IAAI,IAAI,SAAS,GAClB,MAAM,yBAAyB,CAAA"}
|
package/dist/exports/routes.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { GRAPHQL_PLAYGROUND_GET, GRAPHQL_POST } from '../routes/graphql/index.js';
|
|
2
|
-
export { DELETE as REST_DELETE, GET as REST_GET, PATCH as REST_PATCH, POST as REST_POST } from '../routes/rest/index.js';
|
|
2
|
+
export { DELETE as REST_DELETE, GET as REST_GET, OPTIONS as REST_OPTIONS, PATCH as REST_PATCH, POST as REST_POST } from '../routes/rest/index.js';
|
|
3
3
|
|
|
4
4
|
//# sourceMappingURL=routes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/routes.ts"],"sourcesContent":["export { GRAPHQL_PLAYGROUND_GET, GRAPHQL_POST } from '../routes/graphql/index.js'\n\nexport {\n DELETE as REST_DELETE,\n GET as REST_GET,\n PATCH as REST_PATCH,\n POST as REST_POST,\n} from '../routes/rest/index.js'\n"],"names":["GRAPHQL_PLAYGROUND_GET","GRAPHQL_POST","DELETE","REST_DELETE","GET","REST_GET","PATCH","REST_PATCH","POST","REST_POST"],"rangeMappings":";","mappings":"AAAA,SAASA,sBAAsB,EAAEC,YAAY,QAAQ,6BAA4B;AAEjF,SACEC,UAAUC,WAAW,EACrBC,OAAOC,QAAQ,EACfC,SAASC,UAAU,EACnBC,QAAQC,SAAS,QACZ,0BAAyB"}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/routes.ts"],"sourcesContent":["export { GRAPHQL_PLAYGROUND_GET, GRAPHQL_POST } from '../routes/graphql/index.js'\n\nexport {\n DELETE as REST_DELETE,\n GET as REST_GET,\n OPTIONS as REST_OPTIONS,\n PATCH as REST_PATCH,\n POST as REST_POST,\n} from '../routes/rest/index.js'\n"],"names":["GRAPHQL_PLAYGROUND_GET","GRAPHQL_POST","DELETE","REST_DELETE","GET","REST_GET","OPTIONS","REST_OPTIONS","PATCH","REST_PATCH","POST","REST_POST"],"rangeMappings":";","mappings":"AAAA,SAASA,sBAAsB,EAAEC,YAAY,QAAQ,6BAA4B;AAEjF,SACEC,UAAUC,WAAW,EACrBC,OAAOC,QAAQ,EACfC,WAAWC,YAAY,EACvBC,SAASC,UAAU,EACnBC,QAAQC,SAAS,QACZ,0BAAyB"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { traverseFields } from '../utilities/buildFieldSchemaMap/traverseFields.js';
|
|
2
|
+
export { createPayloadRequest } from '../utilities/createPayloadRequest.js';
|
|
2
3
|
export { getNextRequestI18n } from '../utilities/getNextRequestI18n.js';
|
|
3
|
-
export { getPayloadHMR } from '../utilities/getPayloadHMR.js';
|
|
4
|
+
export { getPayloadHMR, reload } from '../utilities/getPayloadHMR.js';
|
|
5
|
+
export { headersWithCors } from '../utilities/headersWithCors.js';
|
|
4
6
|
//# sourceMappingURL=utilities.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/exports/utilities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oDAAoD,CAAA;AACnF,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAA;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA"}
|
|
1
|
+
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/exports/utilities.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,oDAAoD,CAAA;AACnF,OAAO,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAA;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAA;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAA;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAA"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { traverseFields } from '../utilities/buildFieldSchemaMap/traverseFields.js';
|
|
2
|
+
export { createPayloadRequest } from '../utilities/createPayloadRequest.js';
|
|
2
3
|
export { getNextRequestI18n } from '../utilities/getNextRequestI18n.js';
|
|
3
|
-
export { getPayloadHMR } from '../utilities/getPayloadHMR.js';
|
|
4
|
+
export { getPayloadHMR, reload } from '../utilities/getPayloadHMR.js';
|
|
5
|
+
export { headersWithCors } from '../utilities/headersWithCors.js';
|
|
4
6
|
|
|
5
7
|
//# sourceMappingURL=utilities.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/utilities.ts"],"sourcesContent":["export { traverseFields } from '../utilities/buildFieldSchemaMap/traverseFields.js'\nexport { getNextRequestI18n } from '../utilities/getNextRequestI18n.js'\nexport { getPayloadHMR } from '../utilities/getPayloadHMR.js'\n"],"names":["traverseFields","getNextRequestI18n","getPayloadHMR"],"rangeMappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/exports/utilities.ts"],"sourcesContent":["export { traverseFields } from '../utilities/buildFieldSchemaMap/traverseFields.js'\nexport { createPayloadRequest } from '../utilities/createPayloadRequest.js'\nexport { getNextRequestI18n } from '../utilities/getNextRequestI18n.js'\nexport { getPayloadHMR, reload } from '../utilities/getPayloadHMR.js'\nexport { headersWithCors } from '../utilities/headersWithCors.js'\n"],"names":["traverseFields","createPayloadRequest","getNextRequestI18n","getPayloadHMR","reload","headersWithCors"],"rangeMappings":";;;;","mappings":"AAAA,SAASA,cAAc,QAAQ,qDAAoD;AACnF,SAASC,oBAAoB,QAAQ,uCAAsC;AAC3E,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SAASC,aAAa,EAAEC,MAAM,QAAQ,gCAA+B;AACrE,SAASC,eAAe,QAAQ,kCAAiC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next-fileupload/handlers.ts"],"sourcesContent":["import crypto from 'crypto'\nimport fs, { WriteStream } from 'fs'\nimport path from 'path'\n\nimport type { NextFileUploadOptions } from './index.js'\n\nimport { checkAndMakeDir, debugLog, deleteFile, getTempFilename } from './utilities.js'\n\ntype Handler = (\n options: NextFileUploadOptions,\n fieldname: string,\n filename: string,\n) => {\n cleanup: () => void\n complete: () => Buffer\n dataHandler: (data: Buffer) => void\n getFilePath: () => string\n getFileSize: () => number\n getHash: () => string\n getWritePromise: () => Promise<boolean>\n}\n\nexport const tempFileHandler: Handler = (options, fieldname, filename) => {\n const dir = path.normalize(options.tempFileDir)\n const tempFilePath = path.join(process.cwd(), dir, getTempFilename())\n checkAndMakeDir({ createParentPath: true }, tempFilePath)\n\n debugLog(options, `Temporary file path is ${tempFilePath}`)\n\n const hash = crypto.createHash('md5')\n let fileSize = 0\n let completed = false\n\n debugLog(options, `Opening write stream for ${fieldname}->${filename}...`)\n const writeStream = fs.createWriteStream(tempFilePath)\n const writePromise = new Promise<boolean>((resolve, reject) => {\n writeStream.on('finish', () => resolve(true))\n writeStream.on('error', (err) => {\n debugLog(options, `Error write temp file: ${err}`)\n reject(err)\n })\n })\n\n return {\n cleanup: () => {\n completed = true\n debugLog(options, `Cleaning up temporary file ${tempFilePath}...`)\n writeStream.end()\n deleteFile(tempFilePath, (err) =>\n err\n ? debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`)\n : debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`),\n )\n },\n complete: () => {\n completed = true\n debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`)\n if (writeStream instanceof WriteStream) writeStream.end()\n // Return empty buff since data was uploaded into a temp file.\n return Buffer.concat([])\n },\n dataHandler: (data) => {\n if (completed === true) {\n debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`)\n return\n }\n writeStream.write(data)\n hash.update(data)\n fileSize += data.length\n debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`)\n },\n getFilePath: () => tempFilePath,\n getFileSize: () => fileSize,\n getHash: () => hash.digest('hex'),\n getWritePromise: () => writePromise,\n }\n}\n\nexport const memHandler: Handler = (options, fieldname, filename) => {\n const buffers = []\n const hash = crypto.createHash('md5')\n let fileSize = 0\n let completed = false\n\n const getBuffer = () => Buffer.concat(buffers, fileSize)\n\n return {\n cleanup: () => {\n completed = true\n },\n complete: () => {\n debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`)\n completed = true\n return getBuffer()\n },\n dataHandler: (data) => {\n if (completed === true) {\n debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`)\n return\n }\n buffers.push(data)\n hash.update(data)\n fileSize += data.length\n debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`)\n },\n getFilePath: () => '',\n getFileSize: () => fileSize,\n getHash: () => hash.digest('hex'),\n getWritePromise: () => Promise.resolve(true),\n }\n}\n"],"names":["crypto","fs","WriteStream","path","checkAndMakeDir","debugLog","deleteFile","getTempFilename","tempFileHandler","options","fieldname","filename","dir","normalize","tempFileDir","tempFilePath","join","process","cwd","createParentPath","hash","createHash","fileSize","completed","writeStream","createWriteStream","writePromise","Promise","resolve","reject","on","err","cleanup","end","complete","Buffer","concat","dataHandler","data","write","update","length","getFilePath","getFileSize","getHash","digest","getWritePromise","memHandler","buffers","getBuffer","push"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,OAAOC,MAAMC,WAAW,QAAQ,KAAI;AACpC,OAAOC,UAAU,OAAM;AAIvB,SAASC,eAAe,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,eAAe,QAAQ,iBAAgB;AAgBvF,OAAO,MAAMC,kBAA2B,CAACC,SAASC,WAAWC;IAC3D,MAAMC,MAAMT,KAAKU,SAAS,CAACJ,QAAQK,WAAW;IAC9C,MAAMC,eAAeZ,KAAKa,IAAI,CAACC,QAAQC,GAAG,IAAIN,KAAKL;IACnDH,gBAAgB;QAAEe,kBAAkB;IAAK,GAAGJ;IAE5CV,SAASI,SAAS,CAAC,uBAAuB,EAAEM,aAAa,CAAC;IAE1D,MAAMK,OAAOpB,OAAOqB,UAAU,CAAC;IAC/B,IAAIC,WAAW;IACf,IAAIC,YAAY;IAEhBlB,SAASI,SAAS,CAAC,yBAAyB,EAAEC,UAAU,EAAE,EAAEC,SAAS,GAAG,CAAC;IACzE,MAAMa,cAAcvB,GAAGwB,iBAAiB,CAACV;IACzC,MAAMW,eAAe,IAAIC,QAAiB,CAAC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":["../../src/next-fileupload/handlers.ts"],"sourcesContent":["import crypto from 'crypto'\nimport fs, { WriteStream } from 'fs'\nimport path from 'path'\n\nimport type { NextFileUploadOptions } from './index.js'\n\nimport { checkAndMakeDir, debugLog, deleteFile, getTempFilename } from './utilities.js'\n\ntype Handler = (\n options: NextFileUploadOptions,\n fieldname: string,\n filename: string,\n) => {\n cleanup: () => void\n complete: () => Buffer\n dataHandler: (data: Buffer) => void\n getFilePath: () => string\n getFileSize: () => number\n getHash: () => string\n getWritePromise: () => Promise<boolean>\n}\n\nexport const tempFileHandler: Handler = (options, fieldname, filename) => {\n const dir = path.normalize(options.tempFileDir)\n const tempFilePath = path.join(process.cwd(), dir, getTempFilename())\n checkAndMakeDir({ createParentPath: true }, tempFilePath)\n\n debugLog(options, `Temporary file path is ${tempFilePath}`)\n\n const hash = crypto.createHash('md5')\n let fileSize = 0\n let completed = false\n\n debugLog(options, `Opening write stream for ${fieldname}->${filename}...`)\n const writeStream = fs.createWriteStream(tempFilePath)\n const writePromise = new Promise<boolean>((resolve, reject) => {\n writeStream.on('finish', () => resolve(true))\n writeStream.on('error', (err) => {\n debugLog(options, `Error write temp file: ${err}`)\n reject(err)\n })\n })\n\n return {\n cleanup: () => {\n completed = true\n debugLog(options, `Cleaning up temporary file ${tempFilePath}...`)\n writeStream.end()\n deleteFile(tempFilePath, (err) =>\n err\n ? debugLog(options, `Cleaning up temporary file ${tempFilePath} failed: ${err}`)\n : debugLog(options, `Cleaning up temporary file ${tempFilePath} done.`),\n )\n },\n complete: () => {\n completed = true\n debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`)\n if (writeStream instanceof WriteStream) writeStream.end()\n // Return empty buff since data was uploaded into a temp file.\n return Buffer.concat([])\n },\n dataHandler: (data) => {\n if (completed === true) {\n debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`)\n return\n }\n writeStream.write(data)\n hash.update(data)\n fileSize += data.length\n debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`)\n },\n getFilePath: () => tempFilePath,\n getFileSize: () => fileSize,\n getHash: () => hash.digest('hex'),\n getWritePromise: () => writePromise,\n }\n}\n\nexport const memHandler: Handler = (options, fieldname, filename) => {\n const buffers: Buffer[] = []\n const hash = crypto.createHash('md5')\n let fileSize = 0\n let completed = false\n\n const getBuffer = () => Buffer.concat(buffers, fileSize)\n\n return {\n cleanup: () => {\n completed = true\n },\n complete: () => {\n debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`)\n completed = true\n return getBuffer()\n },\n dataHandler: (data) => {\n if (completed === true) {\n debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`)\n return\n }\n buffers.push(data)\n hash.update(data)\n fileSize += data.length\n debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`)\n },\n getFilePath: () => '',\n getFileSize: () => fileSize,\n getHash: () => hash.digest('hex'),\n getWritePromise: () => Promise.resolve(true),\n }\n}\n"],"names":["crypto","fs","WriteStream","path","checkAndMakeDir","debugLog","deleteFile","getTempFilename","tempFileHandler","options","fieldname","filename","dir","normalize","tempFileDir","tempFilePath","join","process","cwd","createParentPath","hash","createHash","fileSize","completed","writeStream","createWriteStream","writePromise","Promise","resolve","reject","on","err","cleanup","end","complete","Buffer","concat","dataHandler","data","write","update","length","getFilePath","getFileSize","getHash","digest","getWritePromise","memHandler","buffers","getBuffer","push"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,OAAOC,MAAMC,WAAW,QAAQ,KAAI;AACpC,OAAOC,UAAU,OAAM;AAIvB,SAASC,eAAe,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,eAAe,QAAQ,iBAAgB;AAgBvF,OAAO,MAAMC,kBAA2B,CAACC,SAASC,WAAWC;IAC3D,MAAMC,MAAMT,KAAK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
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next-fileupload/isEligibleRequest.ts"],"sourcesContent":["const ACCEPTABLE_CONTENT_TYPE =
|
|
1
|
+
{"version":3,"sources":["../../src/next-fileupload/isEligibleRequest.ts"],"sourcesContent":["const ACCEPTABLE_CONTENT_TYPE = /multipart\\/['\"()+-_]+(?:; ?['\"()+-_]*)+$/i\nconst UNACCEPTABLE_METHODS = new Set(['GET', 'HEAD', 'DELETE', 'OPTIONS', 'CONNECT', 'TRACE'])\n\nconst hasBody = (req: Request): boolean => {\n return Boolean(\n req.headers.get('transfer-encoding') ||\n (req.headers.get('content-length') && req.headers.get('content-length') !== '0'),\n )\n}\n\nconst hasAcceptableMethod = (req: Request): boolean => !UNACCEPTABLE_METHODS.has(req.method)\n\nconst hasAcceptableContentType = (req: Request): boolean => {\n const contType = req.headers.get('content-type')\n return contType.includes('boundary=') && ACCEPTABLE_CONTENT_TYPE.test(contType)\n}\n\nexport const isEligibleRequest = (req: Request): boolean => {\n try {\n return hasBody(req) && hasAcceptableMethod(req) && hasAcceptableContentType(req)\n } catch (e) {\n return false\n }\n}\n"],"names":["ACCEPTABLE_CONTENT_TYPE","UNACCEPTABLE_METHODS","Set","hasBody","req","Boolean","headers","get","hasAcceptableMethod","has","method","hasAcceptableContentType","contType","includes","test","isEligibleRequest","e"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,MAAMA,0BAA0B;AAChC,MAAMC,uBAAuB,IAAIC,IAAI;IAAC;IAAO;IAAQ;IAAU;IAAW;IAAW;CAAQ;AAE7F,MAAMC,UAAU,CAACC;IACf,OAAOC,QACLD,IAAIE,OAAO,CAACC,GAAG,CAAC,wBACbH,IAAIE,OAAO,CAACC,GAAG,CAAC,qBAAqBH,IAAIE,OAAO,CAACC,GAAG,CAAC,sBAAsB;AAElF;AAEA,MAAMC,sBAAsB,CAACJ,MAA0B,CAACH,qBAAqBQ,GAAG,CAACL,IAAIM,MAAM;AAE3F,MAAMC,2BAA2B,CAACP;IAChC,MAAMQ,WAAWR,IAAIE,OAAO,CAACC,GAAG,CAAC;IACjC,OAAOK,SAASC,QAAQ,CAAC,gBAAgBb,wBAAwBc,IAAI,CAACF;AACxE;AAEA,OAAO,MAAMG,oBAAoB,CAACX;IAChC,IAAI;QACF,OAAOD,QAAQC,QAAQI,oBAAoBJ,QAAQO,yBAAyBP;IAC9E,EAAE,OAAOY,GAAG;QACV,OAAO;IACT;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processMultipart.d.ts","sourceRoot":"","sources":["../../src/next-fileupload/processMultipart.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"processMultipart.d.ts","sourceRoot":"","sources":["../../src/next-fileupload/processMultipart.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AAU/E,KAAK,gBAAgB,GAAG,CAAC,IAAI,EAAE;IAC7B,OAAO,EAAE,qBAAqB,CAAA;IAC9B,OAAO,EAAE,OAAO,CAAA;CACjB,KAAK,OAAO,CAAC,sBAAsB,CAAC,CAAA;AACrC,eAAO,MAAM,gBAAgB,EAAE,gBAoL9B,CAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import Busboy from 'busboy';
|
|
2
|
+
import httpStatus from 'http-status';
|
|
2
3
|
import { APIError } from 'payload/errors';
|
|
3
4
|
import { fileFactory } from './fileFactory.js';
|
|
4
5
|
import { memHandler, tempFileHandler } from './handlers.js';
|
|
@@ -8,6 +9,14 @@ import { buildFields, debugLog, isFunc, parseFileName } from './utilities.js';
|
|
|
8
9
|
const waitFlushProperty = Symbol('wait flush property symbol');
|
|
9
10
|
export const processMultipart = async ({ options, request })=>{
|
|
10
11
|
let parsingRequest = true;
|
|
12
|
+
let fileCount = 0;
|
|
13
|
+
let filesCompleted = 0;
|
|
14
|
+
let allFilesHaveResolved;
|
|
15
|
+
let failedResolvingFiles;
|
|
16
|
+
const allFilesComplete = new Promise((res, rej)=>{
|
|
17
|
+
allFilesHaveResolved = res;
|
|
18
|
+
failedResolvingFiles = rej;
|
|
19
|
+
});
|
|
11
20
|
const result = {
|
|
12
21
|
fields: undefined,
|
|
13
22
|
files: undefined
|
|
@@ -26,6 +35,7 @@ export const processMultipart = async ({ options, request })=>{
|
|
|
26
35
|
});
|
|
27
36
|
// Build req.files fields
|
|
28
37
|
busboy.on('file', (field, file, info)=>{
|
|
38
|
+
fileCount += 1;
|
|
29
39
|
// Parse file name(cutting huge names, decoding, etc..).
|
|
30
40
|
const { encoding, filename: name, mimeType: mime } = info;
|
|
31
41
|
const filename = parseFileName(options, name);
|
|
@@ -57,7 +67,7 @@ export const processMultipart = async ({ options, request })=>{
|
|
|
57
67
|
debugLog(options, `Aborting upload because of size limit ${field}->${filename}.`);
|
|
58
68
|
cleanup();
|
|
59
69
|
parsingRequest = false;
|
|
60
|
-
throw new APIError(options.responseOnLimit,
|
|
70
|
+
throw new APIError(options.responseOnLimit, httpStatus.REQUEST_ENTITY_TOO_LARGE, {
|
|
61
71
|
size: getFileSize()
|
|
62
72
|
});
|
|
63
73
|
}
|
|
@@ -77,6 +87,7 @@ export const processMultipart = async ({ options, request })=>{
|
|
|
77
87
|
}
|
|
78
88
|
return debugLog(options, `Don't add file instance if original name and size are empty`);
|
|
79
89
|
}
|
|
90
|
+
filesCompleted += 1;
|
|
80
91
|
result.files = buildFields(result.files, field, fileFactory({
|
|
81
92
|
name: filename,
|
|
82
93
|
buffer: complete(),
|
|
@@ -91,33 +102,44 @@ export const processMultipart = async ({ options, request })=>{
|
|
|
91
102
|
request[waitFlushProperty] = [];
|
|
92
103
|
}
|
|
93
104
|
request[waitFlushProperty].push(writePromise);
|
|
105
|
+
if (filesCompleted === fileCount) {
|
|
106
|
+
allFilesHaveResolved();
|
|
107
|
+
}
|
|
94
108
|
});
|
|
95
109
|
file.on('error', (err)=>{
|
|
96
110
|
uploadTimer.clear();
|
|
97
111
|
debugLog(options, `File Error: ${err.message}`);
|
|
98
112
|
cleanup();
|
|
113
|
+
failedResolvingFiles(err);
|
|
99
114
|
});
|
|
115
|
+
// Start upload process.
|
|
100
116
|
debugLog(options, `New upload started ${field}->${filename}, bytes:${getFileSize()}`);
|
|
101
117
|
uploadTimer.set();
|
|
102
118
|
});
|
|
103
|
-
busboy.on('finish', ()=>{
|
|
119
|
+
busboy.on('finish', async ()=>{
|
|
104
120
|
debugLog(options, `Busboy finished parsing request.`);
|
|
105
121
|
if (options.parseNested) {
|
|
106
122
|
result.fields = processNested(result.fields);
|
|
107
123
|
result.files = processNested(result.files);
|
|
108
124
|
}
|
|
109
125
|
if (request[waitFlushProperty]) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
126
|
+
try {
|
|
127
|
+
await Promise.all(request[waitFlushProperty]).then(()=>{
|
|
128
|
+
delete request[waitFlushProperty];
|
|
129
|
+
});
|
|
130
|
+
} catch (err) {
|
|
131
|
+
debugLog(options, `Error waiting for file write promises: ${err}`);
|
|
132
|
+
}
|
|
113
133
|
}
|
|
134
|
+
return result;
|
|
114
135
|
});
|
|
115
136
|
busboy.on('error', (err)=>{
|
|
116
137
|
debugLog(options, `Busboy error`);
|
|
117
138
|
parsingRequest = false;
|
|
118
|
-
throw new APIError('Busboy error parsing multipart request',
|
|
139
|
+
throw new APIError('Busboy error parsing multipart request', httpStatus.BAD_REQUEST);
|
|
119
140
|
});
|
|
120
141
|
const reader = request.body.getReader();
|
|
142
|
+
// Start parsing request
|
|
121
143
|
while(parsingRequest){
|
|
122
144
|
const { done, value } = await reader.read();
|
|
123
145
|
if (done) {
|
|
@@ -127,6 +149,7 @@ export const processMultipart = async ({ options, request })=>{
|
|
|
127
149
|
busboy.write(value);
|
|
128
150
|
}
|
|
129
151
|
}
|
|
152
|
+
if (fileCount !== 0) await allFilesComplete;
|
|
130
153
|
return result;
|
|
131
154
|
};
|
|
132
155
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next-fileupload/processMultipart.ts"],"sourcesContent":["import Busboy from 'busboy'\nimport { APIError } from 'payload/errors'\n\nimport type { NextFileUploadOptions, NextFileUploadResponse } from './index.js'\n\nimport { fileFactory } from './fileFactory.js'\nimport { memHandler, tempFileHandler } from './handlers.js'\nimport { processNested } from './processNested.js'\nimport { createUploadTimer } from './uploadTimer.js'\nimport { buildFields, debugLog, isFunc, parseFileName } from './utilities.js'\n\nconst waitFlushProperty = Symbol('wait flush property symbol')\n\ntype ProcessMultipart = (args: {\n options: NextFileUploadOptions\n request: Request\n}) => Promise<NextFileUploadResponse>\nexport const processMultipart: ProcessMultipart = async ({ options, request }) => {\n let parsingRequest = true\n const result: NextFileUploadResponse = {\n fields: undefined,\n files: undefined,\n }\n\n const headersObject = {}\n request.headers.forEach((value, name) => {\n headersObject[name] = value\n })\n\n const busboy = Busboy({ ...options, headers: headersObject })\n\n // Build multipart req.body fields\n busboy.on('field', (field, val) => {\n result.fields = buildFields(result.fields, field, val)\n })\n\n // Build req.files fields\n busboy.on('file', (field, file, info) => {\n // Parse file name(cutting huge names, decoding, etc..).\n const { encoding, filename: name, mimeType: mime } = info\n const filename = parseFileName(options, name)\n\n // Define methods and handlers for upload process.\n const { cleanup, complete, dataHandler, getFilePath, getFileSize, getHash, getWritePromise } =\n options.useTempFiles\n ? tempFileHandler(options, field, filename) // Upload into temporary file.\n : memHandler(options, field, filename) // Upload into RAM.\n\n const writePromise = options.useTempFiles\n ? getWritePromise().catch((err) => {\n busboy.end()\n cleanup()\n })\n : getWritePromise()\n\n const uploadTimer = createUploadTimer(options.uploadTimeout, () => {\n file.removeAllListeners('data')\n file.resume()\n const err = new Error(`Upload timeout for ${field}->${filename}, bytes:${getFileSize()}`)\n return file.destroy(err)\n })\n\n file.on('limit', () => {\n debugLog(options, `Size limit reached for ${field}->${filename}, bytes:${getFileSize()}`)\n uploadTimer.clear()\n\n if (isFunc(options.limitHandler)) {\n options.limitHandler({ request, size: getFileSize() })\n }\n\n // Return error and cleanup files if abortOnLimit set.\n if (options.abortOnLimit) {\n debugLog(options, `Aborting upload because of size limit ${field}->${filename}.`)\n cleanup()\n parsingRequest = false\n throw new APIError(options.responseOnLimit, 413, { size: getFileSize() })\n }\n })\n\n file.on('data', (data) => {\n uploadTimer.set()\n dataHandler(data)\n })\n\n file.on('end', () => {\n const size = getFileSize()\n debugLog(options, `Upload finished ${field}->${filename}, bytes:${size}`)\n uploadTimer.clear()\n\n if (!name && size === 0) {\n if (options.useTempFiles) {\n cleanup()\n debugLog(options, `Removing the empty file ${field}->${filename}`)\n }\n return debugLog(options, `Don't add file instance if original name and size are empty`)\n }\n\n result.files = buildFields(\n result.files,\n field,\n fileFactory(\n {\n name: filename,\n buffer: complete(),\n encoding,\n hash: getHash(),\n mimetype: mime,\n size,\n tempFilePath: getFilePath(),\n truncated: Boolean('truncated' in file && file.truncated),\n },\n options,\n ),\n )\n\n if (!request[waitFlushProperty]) {\n request[waitFlushProperty] = []\n }\n request[waitFlushProperty].push(writePromise)\n })\n\n file.on('error', (err) => {\n uploadTimer.clear()\n debugLog(options, `File Error: ${err.message}`)\n cleanup()\n })\n\n debugLog(options, `New upload started ${field}->${filename}, bytes:${getFileSize()}`)\n uploadTimer.set()\n })\n\n busboy.on('finish', () => {\n debugLog(options, `Busboy finished parsing request.`)\n if (options.parseNested) {\n result.fields = processNested(result.fields)\n result.files = processNested(result.files)\n }\n\n if (request[waitFlushProperty]) {\n Promise.all(request[waitFlushProperty]).then(() => {\n delete request[waitFlushProperty]\n })\n }\n })\n\n busboy.on('error', (err) => {\n debugLog(options, `Busboy error`)\n parsingRequest = false\n throw new APIError('Busboy error parsing multipart request', 500)\n })\n\n const reader = request.body.getReader()\n\n while (parsingRequest) {\n const { done, value } = await reader.read()\n\n if (done) {\n parsingRequest = false\n }\n\n if (value) {\n busboy.write(value)\n }\n }\n\n return result\n}\n"],"names":["Busboy","APIError","fileFactory","memHandler","tempFileHandler","processNested","createUploadTimer","buildFields","debugLog","isFunc","parseFileName","waitFlushProperty","Symbol","processMultipart","options","request","parsingRequest","result","fields","undefined","files","headersObject","headers","forEach","value","name","busboy","on","field","val","file","info","encoding","filename","mimeType","mime","cleanup","complete","dataHandler","getFilePath","getFileSize","getHash","getWritePromise","useTempFiles","writePromise","catch","err","end","uploadTimer","uploadTimeout","removeAllListeners","resume","Error","destroy","clear","limitHandler","size","abortOnLimit","responseOnLimit","data","set","buffer","hash","mimetype","tempFilePath","truncated","Boolean","push","message","parseNested","Promise","all","then","reader","body","getReader","done","read","write"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,SAASC,QAAQ,QAAQ,iBAAgB;AAIzC,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,UAAU,EAAEC,eAAe,QAAQ,gBAAe;AAC3D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,iBAAiB,QAAQ,mBAAkB;AACpD,SAASC,WAAW,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,aAAa,QAAQ,iBAAgB;AAE7E,MAAMC,oBAAoBC,OAAO;AAMjC,OAAO,MAAMC,mBAAqC,OAAO,EAAEC,OAAO,EAAEC,OAAO,EAAE;IAC3E,IAAIC,iBAAiB;IACrB,MAAMC,SAAiC;QACrCC,QAAQC;QACRC,OAAOD;IACT;IAEA,MAAME,gBAAgB,CAAC;IACvBN,QAAQO,OAAO,CAACC,OAAO,CAAC,CAACC,OAAOC;QAC9BJ,aAAa,CAACI,KAAK,GAAGD;IACxB;IAEA,MAAME,SAAS1B,OAAO;QAAE,GAAGc,OAAO;QAAEQ,SAASD;IAAc;IAE3D,kCAAkC;IAClCK,OAAOC,EAAE,CAAC,SAAS,CAAC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,cAAc,CAAC;QACpFQ,YAAYY,GAAG;IACjB;IAEAlC,OAAOC,EAAE,CAAC,UAAU;QAClBnB,SAASM,SAAS,CAAC,gCAAgC,CAAC;QACpD,IAAIA,QAAQuD,WAAW,EAAE;YACvBpD,OAAOC,MAAM,GAAGb,cAAcY,OAAOC,MAAM;YAC3CD,OAAOG,KAAK,GAAGf,cAAcY,OAAOG,KAAK;QAC3C;QAEA,IAAIL,OAAO,CAACJ,kBAAkB,EAAE;YAC9B2D,QAAQC,GAAG,CAACxD,OAAO,CAACJ,kBAAkB,EAAE6D,IAAI,CAAC;gBAC3C,OAAOzD,OAAO,CAACJ,kBAAkB;YACnC;QACF;IACF;IAEAe,OAAOC,EAAE,CAAC,SAAS,CAACmB;QAClBtC,SAASM,SAAS,CAAC,YAAY,CAAC;QAChCE,iBAAiB;QACjB,MAAM,IAAIf,SAAS,0CAA0C;IAC/D;IAEA,MAAMwE,SAAS1D,QAAQ2D,IAAI,CAACC,SAAS;IAErC,MAAO3D,eAAgB;QACrB,MAAM,EAAE4D,IAAI,EAAEpD,KAAK,EAAE,GAAG,MAAMiD,OAAOI,IAAI;QAEzC,IAAID,MAAM;YACR5D,iBAAiB;QACnB;QAEA,IAAIQ,OAAO;YACTE,OAAOoD,KAAK,CAACtD;QACf;IACF;IAEA,OAAOP;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/next-fileupload/processMultipart.ts"],"sourcesContent":["import Busboy from 'busboy'\nimport httpStatus from 'http-status'\nimport { APIError } from 'payload/errors'\n\nimport type { NextFileUploadOptions, NextFileUploadResponse } from './index.js'\n\nimport { fileFactory } from './fileFactory.js'\nimport { memHandler, tempFileHandler } from './handlers.js'\nimport { processNested } from './processNested.js'\nimport { createUploadTimer } from './uploadTimer.js'\nimport { buildFields, debugLog, isFunc, parseFileName } from './utilities.js'\n\nconst waitFlushProperty = Symbol('wait flush property symbol')\n\ntype ProcessMultipart = (args: {\n options: NextFileUploadOptions\n request: Request\n}) => Promise<NextFileUploadResponse>\nexport const processMultipart: ProcessMultipart = async ({ options, request }) => {\n let parsingRequest = true\n\n let fileCount = 0\n let filesCompleted = 0\n let allFilesHaveResolved: (value?: unknown) => void\n let failedResolvingFiles: (err: Error) => void\n\n const allFilesComplete = new Promise((res, rej) => {\n allFilesHaveResolved = res\n failedResolvingFiles = rej\n })\n\n const result: NextFileUploadResponse = {\n fields: undefined,\n files: undefined,\n }\n\n const headersObject = {}\n request.headers.forEach((value, name) => {\n headersObject[name] = value\n })\n\n const busboy = Busboy({ ...options, headers: headersObject })\n\n // Build multipart req.body fields\n busboy.on('field', (field, val) => {\n result.fields = buildFields(result.fields, field, val)\n })\n\n // Build req.files fields\n busboy.on('file', (field, file, info) => {\n fileCount += 1\n // Parse file name(cutting huge names, decoding, etc..).\n const { encoding, filename: name, mimeType: mime } = info\n const filename = parseFileName(options, name)\n\n // Define methods and handlers for upload process.\n const { cleanup, complete, dataHandler, getFilePath, getFileSize, getHash, getWritePromise } =\n options.useTempFiles\n ? tempFileHandler(options, field, filename) // Upload into temporary file.\n : memHandler(options, field, filename) // Upload into RAM.\n\n const writePromise = options.useTempFiles\n ? getWritePromise().catch((err) => {\n busboy.end()\n cleanup()\n })\n : getWritePromise()\n\n const uploadTimer = createUploadTimer(options.uploadTimeout, () => {\n file.removeAllListeners('data')\n file.resume()\n const err = new Error(`Upload timeout for ${field}->${filename}, bytes:${getFileSize()}`)\n return file.destroy(err)\n })\n\n file.on('limit', () => {\n debugLog(options, `Size limit reached for ${field}->${filename}, bytes:${getFileSize()}`)\n uploadTimer.clear()\n\n if (isFunc(options.limitHandler)) {\n options.limitHandler({ request, size: getFileSize() })\n }\n\n // Return error and cleanup files if abortOnLimit set.\n if (options.abortOnLimit) {\n debugLog(options, `Aborting upload because of size limit ${field}->${filename}.`)\n cleanup()\n parsingRequest = false\n throw new APIError(options.responseOnLimit, httpStatus.REQUEST_ENTITY_TOO_LARGE, {\n size: getFileSize(),\n })\n }\n })\n\n file.on('data', (data) => {\n uploadTimer.set()\n dataHandler(data)\n })\n\n file.on('end', () => {\n const size = getFileSize()\n debugLog(options, `Upload finished ${field}->${filename}, bytes:${size}`)\n uploadTimer.clear()\n\n if (!name && size === 0) {\n if (options.useTempFiles) {\n cleanup()\n debugLog(options, `Removing the empty file ${field}->${filename}`)\n }\n return debugLog(options, `Don't add file instance if original name and size are empty`)\n }\n\n filesCompleted += 1\n\n result.files = buildFields(\n result.files,\n field,\n fileFactory(\n {\n name: filename,\n buffer: complete(),\n encoding,\n hash: getHash(),\n mimetype: mime,\n size,\n tempFilePath: getFilePath(),\n truncated: Boolean('truncated' in file && file.truncated),\n },\n options,\n ),\n )\n\n if (!request[waitFlushProperty]) {\n request[waitFlushProperty] = []\n }\n request[waitFlushProperty].push(writePromise)\n\n if (filesCompleted === fileCount) {\n allFilesHaveResolved()\n }\n })\n\n file.on('error', (err) => {\n uploadTimer.clear()\n debugLog(options, `File Error: ${err.message}`)\n cleanup()\n failedResolvingFiles(err)\n })\n\n // Start upload process.\n debugLog(options, `New upload started ${field}->${filename}, bytes:${getFileSize()}`)\n uploadTimer.set()\n })\n\n busboy.on('finish', async () => {\n debugLog(options, `Busboy finished parsing request.`)\n if (options.parseNested) {\n result.fields = processNested(result.fields)\n result.files = processNested(result.files)\n }\n\n if (request[waitFlushProperty]) {\n try {\n await Promise.all(request[waitFlushProperty]).then(() => {\n delete request[waitFlushProperty]\n })\n } catch (err) {\n debugLog(options, `Error waiting for file write promises: ${err}`)\n }\n }\n\n return result\n })\n\n busboy.on('error', (err) => {\n debugLog(options, `Busboy error`)\n parsingRequest = false\n throw new APIError('Busboy error parsing multipart request', httpStatus.BAD_REQUEST)\n })\n\n const reader = request.body.getReader()\n\n // Start parsing request\n while (parsingRequest) {\n const { done, value } = await reader.read()\n\n if (done) {\n parsingRequest = false\n }\n\n if (value) {\n busboy.write(value)\n }\n }\n\n if (fileCount !== 0) await allFilesComplete\n\n return result\n}\n"],"names":["Busboy","httpStatus","APIError","fileFactory","memHandler","tempFileHandler","processNested","createUploadTimer","buildFields","debugLog","isFunc","parseFileName","waitFlushProperty","Symbol","processMultipart","options","request","parsingRequest","fileCount","filesCompleted","allFilesHaveResolved","failedResolvingFiles","allFilesComplete","Promise","res","rej","result","fields","undefined","files","headersObject","headers","forEach","value","name","busboy","on","field","val","file","info","encoding","filename","mimeType","mime","cleanup","complete","dataHandler","getFilePath","getFileSize","getHash","getWritePromise","useTempFiles","writePromise","catch","err","end","uploadTimer","uploadTimeout","removeAllListeners","resume","Error","destroy","clear","limitHandler","size","abortOnLimit","responseOnLimit","REQUEST_ENTITY_TOO_LARGE","data","set","buffer","hash","mimetype","tempFilePath","truncated","Boolean","push","message","parseNested","all","then","BAD_REQUEST","reader","body","getReader","done","read","write"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,YAAY,SAAQ;AAC3B,OAAOC,gBAAgB,cAAa;AACpC,SAASC,QAAQ,QAAQ,iBAAgB;AAIzC,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,UAAU,EAAEC,eAAe,QAAQ,gBAAe;AAC3D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,iBAAiB,QAAQ,mBAAkB;AACpD,SAASC,WAAW,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,aAAa,QAAQ,iBAAgB;AAE7E,MAAMC,oBAAoBC,OAAO;AAMjC,OAAO,MAAMC,mBAAqC,OAAO,EAAEC,OAAO,EAAEC,OAAO,EAAE;IAC3E,IAAIC,iBAAiB;IAErB,IAAIC,YAAY;IAChB,IAAIC,iBAAiB;IACrB,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,mBAAmB,IAAIC,QAAQ,CAACC,KAAKC;QACzCL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A;AAEJ;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,oDAwB5B,CAAA;AA+BD;;GAEG;AACH,KAAK,sBAAsB,GAAG,CAC5B,iBAAiB,EAAE,OAAO,GAAG,MAAM,EACnC,QAAQ,EAAE,MAAM,KACb;IACH,SAAS,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AACD,eAAO,MAAM,sBAAsB,EAAE,sBAwBpC,CAAA;AAED;;GAEG;AACH,KAAK,aAAa,GAAG,CAAC,IAAI,EAAE,qBAAqB,EAAE,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAA;AAC9E,eAAO,MAAM,aAAa,EAAE,aAoB3B,CAAA"}
|
|
@@ -13,7 +13,7 @@ let tempCounter = 0;
|
|
|
13
13
|
*/ export const debugLog = (options, msg)=>{
|
|
14
14
|
const opts = options || {};
|
|
15
15
|
if (!opts.debug) return false;
|
|
16
|
-
console.log(`
|
|
16
|
+
console.log(`Next-file-upload: ${msg}`) // eslint-disable-line
|
|
17
17
|
;
|
|
18
18
|
return true;
|
|
19
19
|
};
|
|
@@ -199,9 +199,9 @@ export const parseFileName = (opts, fileName)=>{
|
|
|
199
199
|
// Set regular expression for the file name.
|
|
200
200
|
const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp ? opts.safeFileNames : SAFE_FILE_NAME_REGEX;
|
|
201
201
|
// Parse file name extension.
|
|
202
|
-
|
|
203
|
-
if (extension.length) extension = '.' + extension.replace(nameRegex, '');
|
|
204
|
-
return name.replace(nameRegex, '').concat(extension);
|
|
202
|
+
const parsedFileName = parseFileNameExtension(opts.preserveExtension, parsedName);
|
|
203
|
+
if (parsedFileName.extension.length) parsedFileName.extension = '.' + parsedFileName.extension.replace(nameRegex, '');
|
|
204
|
+
return parsedFileName.name.replace(nameRegex, '').concat(parsedFileName.extension);
|
|
205
205
|
};
|
|
206
206
|
|
|
207
207
|
//# sourceMappingURL=utilities.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next-fileupload/utilities.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport { Readable } from 'stream'\n\nimport type { NextFileUploadOptions } from './index.js'\n\n// Parameters for safe file name parsing.\nconst SAFE_FILE_NAME_REGEX = /[^\\w-]/g\nconst MAX_EXTENSION_LENGTH = 3\n\n// Parameters to generate unique temporary file names:\nconst TEMP_COUNTER_MAX = 65536\nconst TEMP_PREFIX = 'tmp'\nlet tempCounter = 0\n\n/**\n * Logs message to console if options.debug option set to true.\n */\nexport const debugLog = (options: NextFileUploadOptions, msg: string) => {\n const opts = options || {}\n if (!opts.debug) return false\n console.log(`Express-file-upload: ${msg}`) // eslint-disable-line\n return true\n}\n\n/**\n * Generates unique temporary file name. e.g. tmp-5000-156788789789.\n */\nexport const getTempFilename = (prefix: string = TEMP_PREFIX) => {\n tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1\n return `${prefix}-${tempCounter}-${Date.now()}`\n}\n\ntype FuncType = (...args: any[]) => any\nexport const isFunc = (value: any): value is FuncType => {\n return typeof value === 'function'\n}\n\n/**\n * Set errorFunc to the same value as successFunc for callback mode.\n */\ntype ErrorFunc = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nconst errorFunc: ErrorFunc = (resolve, reject) => (isFunc(reject) ? reject : resolve)\n\n/**\n * Return a callback function for promise resole/reject args.\n * Ensures that callback is called only once.\n */\ntype PromiseCallback = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nexport const promiseCallback: PromiseCallback = (resolve, reject) => {\n let hasFired = false\n return (err: Error) => {\n if (hasFired) {\n return\n }\n\n hasFired = true\n return err ? errorFunc(resolve, reject)(err) : resolve()\n }\n}\n\n// The default prototypes for both objects and arrays.\n// Used by isSafeFromPollution\nconst OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype)\nconst ARRAY_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Array.prototype)\n\n/**\n * Determines whether a key insertion into an object could result in a prototype pollution\n */\ntype IsSafeFromPollution = (base: any, key: string) => boolean\nexport const isSafeFromPollution: IsSafeFromPollution = (base, key) => {\n // We perform an instanceof check instead of Array.isArray as the former is more\n // permissive for cases in which the object as an Array prototype but was not constructed\n // via an Array constructor or literal.\n const TOUCHES_ARRAY_PROTOTYPE = base instanceof Array && ARRAY_PROTOTYPE_KEYS.includes(key)\n const TOUCHES_OBJECT_PROTOTYPE = OBJECT_PROTOTYPE_KEYS.includes(key)\n\n return !TOUCHES_ARRAY_PROTOTYPE && !TOUCHES_OBJECT_PROTOTYPE\n}\n\n/**\n * Build request field/file objects to return\n */\ntype BuildFields = (instance: any, field: string, value: any) => any\nexport const buildFields: BuildFields = (instance, field, value) => {\n // Do nothing if value is not set.\n if (value === null || value === undefined) return instance\n instance = instance || Object.create(null)\n\n if (!isSafeFromPollution(instance, field)) {\n return instance\n }\n // Non-array fields\n if (!instance[field]) {\n instance[field] = value\n return instance\n }\n // Array fields\n if (instance[field] instanceof Array) {\n instance[field].push(value)\n } else {\n instance[field] = [instance[field], value]\n }\n return instance\n}\n\n/**\n * Creates a folder if it does not exist\n * for file specified in the path variable\n */\ntype CheckAndMakeDir = (fileUploadOptions: NextFileUploadOptions, filePath: string) => boolean\nexport const checkAndMakeDir: CheckAndMakeDir = (fileUploadOptions, filePath) => {\n if (!fileUploadOptions.createParentPath) return false\n // Check whether folder for the file exists.\n const parentPath = path.dirname(filePath)\n // Create folder if it doesn't exist.\n if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true })\n // Checks folder again and return a results.\n return fs.existsSync(parentPath)\n}\n\n/**\n * Delete a file.\n */\ntype DeleteFile = (filePath: string, callback: (args: any) => void) => void\nexport const deleteFile: DeleteFile = (filePath, callback: (args) => void) =>\n fs.unlink(filePath, callback)\n\n/**\n * Copy file via streams\n */\ntype CopyFile = (src: string, dst: string, callback: (err: Error) => void) => void\nconst copyFile: CopyFile = (src, dst, callback) => {\n // cbCalled flag and runCb helps to run cb only once.\n let cbCalled = false\n const runCb = (err?: Error) => {\n if (cbCalled) return\n cbCalled = true\n callback(err)\n }\n // Create read stream\n const readable = fs.createReadStream(src)\n readable.on('error', runCb)\n // Create write stream\n const writable = fs.createWriteStream(dst)\n writable.on('error', (err: Error) => {\n readable.destroy()\n runCb(err)\n })\n writable.on('close', () => runCb())\n // Copy file via piping streams.\n readable.pipe(writable)\n}\n\n/**\n * moveFile: moves the file from src to dst.\n * Firstly trying to rename the file if no luck copying it to dst and then deleting src.\n */\ntype MoveFile = (\n src: string,\n dst: string,\n callback: (err: Error, renamed?: boolean) => void,\n) => void\nexport const moveFile: MoveFile = (src, dst, callback) =>\n fs.rename(src, dst, (err) => {\n if (err) {\n // Try to copy file if rename didn't work.\n copyFile(src, dst, (cpErr) => (cpErr ? callback(cpErr) : deleteFile(src, callback)))\n return\n }\n // File was renamed successfully: Add true to the callback to indicate that.\n callback(null, true)\n })\n\n/**\n * Save buffer data to a file.\n * @param {Buffer} buffer - buffer to save to a file.\n * @param {string} filePath - path to a file.\n */\nexport const saveBufferToFile = (buffer, filePath, callback) => {\n if (!Buffer.isBuffer(buffer)) {\n return callback(new Error('buffer variable should be type of Buffer!'))\n }\n // Setup readable stream from buffer.\n let streamData = buffer\n const readStream = new Readable()\n readStream._read = () => {\n readStream.push(streamData)\n streamData = null\n }\n // Setup file system writable stream.\n const fstream = fs.createWriteStream(filePath)\n // console.log(\"Calling saveBuffer\");\n fstream.on('error', (err) => {\n // console.log(\"err cb\")\n callback(err)\n })\n fstream.on('close', () => {\n // console.log(\"close cb\");\n callback()\n })\n // Copy file via piping streams.\n readStream.pipe(fstream)\n}\n\n/**\n * Decodes uriEncoded file names.\n * @param {Object} opts - middleware options.\n * @param fileName {String} - file name to decode.\n * @returns {String}\n */\nconst uriDecodeFileName = (opts, fileName) => {\n if (!opts || !opts.uriDecodeFileNames) {\n return fileName\n }\n // Decode file name from URI with checking URI malformed errors.\n // See Issue https://github.com/richardgirges/express-fileupload/issues/342.\n try {\n return decodeURIComponent(fileName)\n } catch (err) {\n const matcher = /(%[a-f\\d]{2})/gi\n return fileName\n .split(matcher)\n .map((str) => {\n try {\n return decodeURIComponent(str)\n } catch (err) {\n return ''\n }\n })\n .join('')\n }\n}\n\n/**\n * Parses filename and extension and returns object {name, extension}.\n */\ntype ParseFileNameExtension = (\n preserveExtension: boolean | number,\n fileName: string,\n) => {\n extension: string\n name: string\n}\nexport const parseFileNameExtension: ParseFileNameExtension = (preserveExtension, fileName) => {\n const defaultResult = {\n name: fileName,\n extension: '',\n }\n if (!preserveExtension) return defaultResult\n\n // Define maximum extension length\n const maxExtLength =\n typeof preserveExtension === 'boolean' ? MAX_EXTENSION_LENGTH : preserveExtension\n\n const nameParts = fileName.split('.')\n if (nameParts.length < 2) return defaultResult\n\n let extension = nameParts.pop()\n if (extension.length > maxExtLength && maxExtLength > 0) {\n nameParts[nameParts.length - 1] += '.' + extension.substr(0, extension.length - maxExtLength)\n extension = extension.substr(-maxExtLength)\n }\n\n return {\n name: nameParts.join('.'),\n extension: maxExtLength ? extension : '',\n }\n}\n\n/**\n * Parse file name and extension.\n */\ntype ParseFileName = (opts: NextFileUploadOptions, fileName: string) => string\nexport const parseFileName: ParseFileName = (opts, fileName) => {\n // Check fileName argument\n if (!fileName || typeof fileName !== 'string') return getTempFilename()\n // Cut off file name if it's length more then 255.\n let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255)\n // Decode file name if uriDecodeFileNames option set true.\n parsedName = uriDecodeFileName(opts, parsedName)\n // Stop parsing file name if safeFileNames options hasn't been set.\n if (!opts.safeFileNames) return parsedName\n // Set regular expression for the file name.\n const nameRegex =\n typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp\n ? opts.safeFileNames\n : SAFE_FILE_NAME_REGEX\n // Parse file name extension.\n let { name, extension } = parseFileNameExtension(opts.preserveExtension, parsedName)\n if (extension.length) extension = '.' + extension.replace(nameRegex, '')\n\n return name.replace(nameRegex, '').concat(extension)\n}\n"],"names":["fs","path","Readable","SAFE_FILE_NAME_REGEX","MAX_EXTENSION_LENGTH","TEMP_COUNTER_MAX","TEMP_PREFIX","tempCounter","debugLog","options","msg","opts","debug","console","log","getTempFilename","prefix","Date","now","isFunc","value","errorFunc","resolve","reject","promiseCallback","hasFired","err","OBJECT_PROTOTYPE_KEYS","Object","getOwnPropertyNames","prototype","ARRAY_PROTOTYPE_KEYS","Array","isSafeFromPollution","base","key","TOUCHES_ARRAY_PROTOTYPE","includes","TOUCHES_OBJECT_PROTOTYPE","buildFields","instance","field","undefined","create","push","checkAndMakeDir","fileUploadOptions","filePath","createParentPath","parentPath","dirname","existsSync","mkdirSync","recursive","deleteFile","callback","unlink","copyFile","src","dst","cbCalled","runCb","readable","createReadStream","on","writable","createWriteStream","destroy","pipe","moveFile","rename","cpErr","saveBufferToFile","buffer","Buffer","isBuffer","Error","streamData","readStream","_read","fstream","uriDecodeFileName","fileName","uriDecodeFileNames","decodeURIComponent","matcher","split","map","str","join","parseFileNameExtension","preserveExtension","defaultResult","name","extension","maxExtLength","nameParts","length","pop","substr","parseFileName","parsedName","safeFileNames","nameRegex","RegExp","replace","concat"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,QAAQ,QAAQ,SAAQ;AAIjC,yCAAyC;AACzC,MAAMC,uBAAuB;AAC7B,MAAMC,uBAAuB;AAE7B,sDAAsD;AACtD,MAAMC,mBAAmB;AACzB,MAAMC,cAAc;AACpB,IAAIC,cAAc;AAElB;;C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ACzE,IAAIP,UAAUG,MAAM,EAAEH,YAAY,MAAMA,UAAUW,OAAO,CAACF,WAAW;IAErE,OAAOV,KAAKY,OAAO,CAACF,WAAW,IAAIG,MAAM,CAACZ;AAC5C,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/next-fileupload/utilities.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport { Readable } from 'stream'\n\nimport type { NextFileUploadOptions } from './index.js'\n\n// Parameters for safe file name parsing.\nconst SAFE_FILE_NAME_REGEX = /[^\\w-]/g\nconst MAX_EXTENSION_LENGTH = 3\n\n// Parameters to generate unique temporary file names:\nconst TEMP_COUNTER_MAX = 65536\nconst TEMP_PREFIX = 'tmp'\nlet tempCounter = 0\n\n/**\n * Logs message to console if options.debug option set to true.\n */\nexport const debugLog = (options: NextFileUploadOptions, msg: string) => {\n const opts = options || {}\n if (!opts.debug) return false\n console.log(`Next-file-upload: ${msg}`) // eslint-disable-line\n return true\n}\n\n/**\n * Generates unique temporary file name. e.g. tmp-5000-156788789789.\n */\nexport const getTempFilename = (prefix: string = TEMP_PREFIX) => {\n tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1\n return `${prefix}-${tempCounter}-${Date.now()}`\n}\n\ntype FuncType = (...args: any[]) => any\nexport const isFunc = (value: any): value is FuncType => {\n return typeof value === 'function'\n}\n\n/**\n * Set errorFunc to the same value as successFunc for callback mode.\n */\ntype ErrorFunc = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nconst errorFunc: ErrorFunc = (resolve, reject) => (isFunc(reject) ? reject : resolve)\n\n/**\n * Return a callback function for promise resole/reject args.\n * Ensures that callback is called only once.\n */\ntype PromiseCallback = (resolve: () => void, reject: (err: Error) => void) => (err: Error) => void\nexport const promiseCallback: PromiseCallback = (resolve, reject) => {\n let hasFired = false\n return (err: Error) => {\n if (hasFired) {\n return\n }\n\n hasFired = true\n return err ? errorFunc(resolve, reject)(err) : resolve()\n }\n}\n\n// The default prototypes for both objects and arrays.\n// Used by isSafeFromPollution\nconst OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype)\nconst ARRAY_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Array.prototype)\n\n/**\n * Determines whether a key insertion into an object could result in a prototype pollution\n */\ntype IsSafeFromPollution = (base: any, key: string) => boolean\nexport const isSafeFromPollution: IsSafeFromPollution = (base, key) => {\n // We perform an instanceof check instead of Array.isArray as the former is more\n // permissive for cases in which the object as an Array prototype but was not constructed\n // via an Array constructor or literal.\n const TOUCHES_ARRAY_PROTOTYPE = base instanceof Array && ARRAY_PROTOTYPE_KEYS.includes(key)\n const TOUCHES_OBJECT_PROTOTYPE = OBJECT_PROTOTYPE_KEYS.includes(key)\n\n return !TOUCHES_ARRAY_PROTOTYPE && !TOUCHES_OBJECT_PROTOTYPE\n}\n\n/**\n * Build request field/file objects to return\n */\ntype BuildFields = (instance: any, field: string, value: any) => any\nexport const buildFields: BuildFields = (instance, field, value) => {\n // Do nothing if value is not set.\n if (value === null || value === undefined) return instance\n instance = instance || Object.create(null)\n\n if (!isSafeFromPollution(instance, field)) {\n return instance\n }\n // Non-array fields\n if (!instance[field]) {\n instance[field] = value\n return instance\n }\n // Array fields\n if (instance[field] instanceof Array) {\n instance[field].push(value)\n } else {\n instance[field] = [instance[field], value]\n }\n return instance\n}\n\n/**\n * Creates a folder if it does not exist\n * for file specified in the path variable\n */\ntype CheckAndMakeDir = (fileUploadOptions: NextFileUploadOptions, filePath: string) => boolean\nexport const checkAndMakeDir: CheckAndMakeDir = (fileUploadOptions, filePath) => {\n if (!fileUploadOptions.createParentPath) return false\n // Check whether folder for the file exists.\n const parentPath = path.dirname(filePath)\n // Create folder if it doesn't exist.\n if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true })\n // Checks folder again and return a results.\n return fs.existsSync(parentPath)\n}\n\n/**\n * Delete a file.\n */\ntype DeleteFile = (filePath: string, callback: (args: any) => void) => void\nexport const deleteFile: DeleteFile = (filePath, callback: (args) => void) =>\n fs.unlink(filePath, callback)\n\n/**\n * Copy file via streams\n */\ntype CopyFile = (src: string, dst: string, callback: (err: Error) => void) => void\nconst copyFile: CopyFile = (src, dst, callback) => {\n // cbCalled flag and runCb helps to run cb only once.\n let cbCalled = false\n const runCb = (err?: Error) => {\n if (cbCalled) return\n cbCalled = true\n callback(err)\n }\n // Create read stream\n const readable = fs.createReadStream(src)\n readable.on('error', runCb)\n // Create write stream\n const writable = fs.createWriteStream(dst)\n writable.on('error', (err: Error) => {\n readable.destroy()\n runCb(err)\n })\n writable.on('close', () => runCb())\n // Copy file via piping streams.\n readable.pipe(writable)\n}\n\n/**\n * moveFile: moves the file from src to dst.\n * Firstly trying to rename the file if no luck copying it to dst and then deleting src.\n */\ntype MoveFile = (\n src: string,\n dst: string,\n callback: (err: Error, renamed?: boolean) => void,\n) => void\nexport const moveFile: MoveFile = (src, dst, callback) =>\n fs.rename(src, dst, (err) => {\n if (err) {\n // Try to copy file if rename didn't work.\n copyFile(src, dst, (cpErr) => (cpErr ? callback(cpErr) : deleteFile(src, callback)))\n return\n }\n // File was renamed successfully: Add true to the callback to indicate that.\n callback(null, true)\n })\n\n/**\n * Save buffer data to a file.\n * @param {Buffer} buffer - buffer to save to a file.\n * @param {string} filePath - path to a file.\n */\nexport const saveBufferToFile = (buffer, filePath, callback) => {\n if (!Buffer.isBuffer(buffer)) {\n return callback(new Error('buffer variable should be type of Buffer!'))\n }\n // Setup readable stream from buffer.\n let streamData = buffer\n const readStream = new Readable()\n readStream._read = () => {\n readStream.push(streamData)\n streamData = null\n }\n // Setup file system writable stream.\n const fstream = fs.createWriteStream(filePath)\n // console.log(\"Calling saveBuffer\");\n fstream.on('error', (err) => {\n // console.log(\"err cb\")\n callback(err)\n })\n fstream.on('close', () => {\n // console.log(\"close cb\");\n callback()\n })\n // Copy file via piping streams.\n readStream.pipe(fstream)\n}\n\n/**\n * Decodes uriEncoded file names.\n * @param {Object} opts - middleware options.\n * @param fileName {String} - file name to decode.\n * @returns {String}\n */\nconst uriDecodeFileName = (opts, fileName) => {\n if (!opts || !opts.uriDecodeFileNames) {\n return fileName\n }\n // Decode file name from URI with checking URI malformed errors.\n // See Issue https://github.com/richardgirges/express-fileupload/issues/342.\n try {\n return decodeURIComponent(fileName)\n } catch (err) {\n const matcher = /(%[a-f\\d]{2})/gi\n return fileName\n .split(matcher)\n .map((str) => {\n try {\n return decodeURIComponent(str)\n } catch (err) {\n return ''\n }\n })\n .join('')\n }\n}\n\n/**\n * Parses filename and extension and returns object {name, extension}.\n */\ntype ParseFileNameExtension = (\n preserveExtension: boolean | number,\n fileName: string,\n) => {\n extension: string\n name: string\n}\nexport const parseFileNameExtension: ParseFileNameExtension = (preserveExtension, fileName) => {\n const defaultResult = {\n name: fileName,\n extension: '',\n }\n if (!preserveExtension) return defaultResult\n\n // Define maximum extension length\n const maxExtLength =\n typeof preserveExtension === 'boolean' ? MAX_EXTENSION_LENGTH : preserveExtension\n\n const nameParts = fileName.split('.')\n if (nameParts.length < 2) return defaultResult\n\n let extension = nameParts.pop()\n if (extension.length > maxExtLength && maxExtLength > 0) {\n nameParts[nameParts.length - 1] += '.' + extension.substr(0, extension.length - maxExtLength)\n extension = extension.substr(-maxExtLength)\n }\n\n return {\n name: nameParts.join('.'),\n extension: maxExtLength ? extension : '',\n }\n}\n\n/**\n * Parse file name and extension.\n */\ntype ParseFileName = (opts: NextFileUploadOptions, fileName: string) => string\nexport const parseFileName: ParseFileName = (opts, fileName) => {\n // Check fileName argument\n if (!fileName || typeof fileName !== 'string') return getTempFilename()\n // Cut off file name if it's length more then 255.\n let parsedName = fileName.length <= 255 ? fileName : fileName.substr(0, 255)\n // Decode file name if uriDecodeFileNames option set true.\n parsedName = uriDecodeFileName(opts, parsedName)\n // Stop parsing file name if safeFileNames options hasn't been set.\n if (!opts.safeFileNames) return parsedName\n // Set regular expression for the file name.\n const nameRegex =\n typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp\n ? opts.safeFileNames\n : SAFE_FILE_NAME_REGEX\n // Parse file name extension.\n const parsedFileName = parseFileNameExtension(opts.preserveExtension, parsedName)\n if (parsedFileName.extension.length)\n parsedFileName.extension = '.' + parsedFileName.extension.replace(nameRegex, '')\n\n return parsedFileName.name.replace(nameRegex, '').concat(parsedFileName.extension)\n}\n"],"names":["fs","path","Readable","SAFE_FILE_NAME_REGEX","MAX_EXTENSION_LENGTH","TEMP_COUNTER_MAX","TEMP_PREFIX","tempCounter","debugLog","options","msg","opts","debug","console","log","getTempFilename","prefix","Date","now","isFunc","value","errorFunc","resolve","reject","promiseCallback","hasFired","err","OBJECT_PROTOTYPE_KEYS","Object","getOwnPropertyNames","prototype","ARRAY_PROTOTYPE_KEYS","Array","isSafeFromPollution","base","key","TOUCHES_ARRAY_PROTOTYPE","includes","TOUCHES_OBJECT_PROTOTYPE","buildFields","instance","field","undefined","create","push","checkAndMakeDir","fileUploadOptions","filePath","createParentPath","parentPath","dirname","existsSync","mkdirSync","recursive","deleteFile","callback","unlink","copyFile","src","dst","cbCalled","runCb","readable","createReadStream","on","writable","createWriteStream","destroy","pipe","moveFile","rename","cpErr","saveBufferToFile","buffer","Buffer","isBuffer","Error","streamData","readStream","_read","fstream","uriDecodeFileName","fileName","uriDecodeFileNames","decodeURIComponent","matcher","split","map","str","join","parseFileNameExtension","preserveExtension","defaultResult","name","extension","maxExtLength","nameParts","length","pop","substr","parseFileName","parsedName","safeFileNames","nameRegex","RegExp","parsedFileName","replace","concat"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC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AO5F,KAAK2F,aAAa,KAAK,YAAY3F,KAAK2F,aAAa,YAAYE,SACpE7F,KAAK2F,aAAa,GAClBnG;IACN,6BAA6B;IAC7B,MAAMsG,iBAAiBf,uBAAuB/E,KAAKgF,iBAAiB,EAAEU;IACtE,IAAII,eAAeX,SAAS,CAACG,MAAM,EACjCQ,eAAeX,SAAS,GAAG,MAAMW,eAAeX,SAAS,CAACY,OAAO,CAACH,WAAW;IAE/E,OAAOE,eAAeZ,IAAI,CAACa,OAAO,CAACH,WAAW,IAAII,MAAM,CAACF,eAAeX,SAAS;AACnF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/routes/graphql/handler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/routes/graphql/handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAqC,eAAe,EAAE,MAAM,eAAe,CAAA;AAoDvF,eAAO,MAAM,UAAU,WAAkB,QAAQ,eAAe,CAAC,GAAG,eAAe,iBA0BlF,CAAA;AAED,eAAO,MAAM,IAAI,WACN,QAAQ,eAAe,CAAC,GAAG,eAAe,eAAqB,OAAO,sBAqD9E,CAAA"}
|
|
@@ -2,6 +2,7 @@ import { configToSchema } from '@payloadcms/graphql';
|
|
|
2
2
|
import { createHandler } from 'graphql-http/lib/use/fetch';
|
|
3
3
|
import httpStatus from 'http-status';
|
|
4
4
|
import { createPayloadRequest } from '../../utilities/createPayloadRequest.js';
|
|
5
|
+
import { headersWithCors } from '../../utilities/headersWithCors.js';
|
|
5
6
|
const handleError = async (payload, err, debug, afterErrorHook)=>{
|
|
6
7
|
const status = err.originalError.status || httpStatus.INTERNAL_SERVER_ERROR;
|
|
7
8
|
let errorMessage = err.message;
|
|
@@ -23,7 +24,7 @@ const handleError = async (payload, err, debug, afterErrorHook)=>{
|
|
|
23
24
|
path: err.path
|
|
24
25
|
};
|
|
25
26
|
if (afterErrorHook) {
|
|
26
|
-
({ response } =
|
|
27
|
+
({ response } = afterErrorHook(err, response, null, null) || {
|
|
27
28
|
response
|
|
28
29
|
});
|
|
29
30
|
}
|
|
@@ -48,9 +49,10 @@ export const getGraphql = async (config)=>{
|
|
|
48
49
|
return cached.graphql;
|
|
49
50
|
}
|
|
50
51
|
if (!cached.promise) {
|
|
52
|
+
// eslint-disable-next-line no-async-promise-executor
|
|
51
53
|
cached.promise = new Promise(async (resolve)=>{
|
|
52
54
|
const resolvedConfig = await config;
|
|
53
|
-
const schema =
|
|
55
|
+
const schema = configToSchema(resolvedConfig);
|
|
54
56
|
resolve(schema);
|
|
55
57
|
});
|
|
56
58
|
}
|
|
@@ -98,12 +100,15 @@ export const POST = (config)=>async (request)=>{
|
|
|
98
100
|
schema,
|
|
99
101
|
validationRules: (request, args, defaultRules)=>defaultRules.concat(validationRules(args))
|
|
100
102
|
})(originalRequest);
|
|
101
|
-
const resHeaders =
|
|
103
|
+
const resHeaders = headersWithCors({
|
|
104
|
+
headers: new Headers(apiResponse.headers),
|
|
105
|
+
req
|
|
106
|
+
});
|
|
102
107
|
for(const key in headers){
|
|
103
108
|
resHeaders.append(key, headers[key]);
|
|
104
109
|
}
|
|
105
110
|
return new Response(apiResponse.body, {
|
|
106
|
-
headers:
|
|
111
|
+
headers: resHeaders,
|
|
107
112
|
status: apiResponse.status
|
|
108
113
|
});
|
|
109
114
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/routes/graphql/handler.ts"],"sourcesContent":["import type { GraphQLFormattedError } from 'graphql'\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/graphql/handler.ts"],"sourcesContent":["import type { GraphQLError, GraphQLFormattedError } from 'graphql'\nimport type { CollectionAfterErrorHook, Payload, SanitizedConfig } from 'payload/types'\n\nimport { configToSchema } from '@payloadcms/graphql'\nimport { createHandler } from 'graphql-http/lib/use/fetch'\nimport httpStatus from 'http-status'\n\nimport { createPayloadRequest } from '../../utilities/createPayloadRequest.js'\nimport { headersWithCors } from '../../utilities/headersWithCors.js'\n\nconst handleError = async (\n payload: Payload,\n err: any,\n debug: boolean,\n afterErrorHook: CollectionAfterErrorHook,\n // eslint-disable-next-line @typescript-eslint/require-await\n): Promise<GraphQLFormattedError> => {\n const status = err.originalError.status || httpStatus.INTERNAL_SERVER_ERROR\n let errorMessage = err.message\n payload.logger.error(err.stack)\n\n // Internal server errors can contain anything, including potentially sensitive data.\n // Therefore, error details will be hidden from the response unless `config.debug` is `true`\n if (!debug && status === httpStatus.INTERNAL_SERVER_ERROR) {\n errorMessage = 'Something went wrong.'\n }\n\n let response: GraphQLFormattedError = {\n extensions: {\n name: err?.originalError?.name || undefined,\n data: (err && err.originalError && err.originalError.data) || undefined,\n stack: debug ? err.stack : undefined,\n statusCode: status,\n },\n locations: err.locations,\n message: errorMessage,\n path: err.path,\n }\n\n if (afterErrorHook) {\n ;({ response } = afterErrorHook(err, response, null, null) || { response })\n }\n\n return response\n}\n\nlet cached = global._payload_graphql\n\nif (!cached) {\n // eslint-disable-next-line no-multi-assign\n cached = global._payload_graphql = { graphql: null, promise: null }\n}\n\nexport const getGraphql = async (config: Promise<SanitizedConfig> | SanitizedConfig) => {\n if (process.env.NODE_ENV === 'development') {\n cached = global._payload_graphql = { graphql: null, promise: null }\n }\n\n if (cached.graphql) {\n return cached.graphql\n }\n\n if (!cached.promise) {\n // eslint-disable-next-line no-async-promise-executor\n cached.promise = new Promise(async (resolve) => {\n const resolvedConfig = await config\n const schema = configToSchema(resolvedConfig)\n resolve(schema)\n })\n }\n\n try {\n cached.graphql = await cached.promise\n } catch (e) {\n cached.promise = null\n throw e\n }\n\n return cached.graphql\n}\n\nexport const POST =\n (config: Promise<SanitizedConfig> | SanitizedConfig) => async (request: Request) => {\n const originalRequest = request.clone()\n const req = await createPayloadRequest({\n config,\n request,\n })\n const { schema, validationRules } = await getGraphql(config)\n\n const { payload } = req\n\n const afterErrorHook =\n typeof payload.config.hooks.afterError === 'function' ? payload.config.hooks.afterError : null\n\n const headers = {}\n const apiResponse = await createHandler({\n context: { headers, req },\n onOperation: async (request, args, result) => {\n const response =\n typeof payload.extensions === 'function'\n ? await payload.extensions({\n args,\n req: request,\n result,\n })\n : result\n if (response.errors) {\n const errors = (await Promise.all(\n result.errors.map((error) => {\n return handleError(payload, error, payload.config.debug, afterErrorHook)\n }),\n )) as GraphQLError[]\n // errors type should be FormattedGraphQLError[] but onOperation has a return type of ExecutionResult instead of FormattedExecutionResult\n return { ...response, errors }\n }\n return response\n },\n schema,\n validationRules: (request, args, defaultRules) => defaultRules.concat(validationRules(args)),\n })(originalRequest)\n\n const resHeaders = headersWithCors({\n headers: new Headers(apiResponse.headers),\n req,\n })\n\n for (const key in headers) {\n resHeaders.append(key, headers[key])\n }\n\n return new Response(apiResponse.body, {\n headers: resHeaders,\n status: apiResponse.status,\n })\n }\n"],"names":["configToSchema","createHandler","httpStatus","createPayloadRequest","headersWithCors","handleError","payload","err","debug","afterErrorHook","status","originalError","INTERNAL_SERVER_ERROR","errorMessage","message","logger","error","stack","response","extensions","name","undefined","data","statusCode","locations","path","cached","global","_payload_graphql","graphql","promise","getGraphql","config","process","env","NODE_ENV","Promise","resolve","resolvedConfig","schema","e","POST","request","originalRequest","clone","req","validationRules","hooks","afterError","headers","apiResponse","context","onOperation","args","result","errors","all","map","defaultRules","concat","resHeaders","Headers","key","append","Response","body"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,cAAc,QAAQ,sBAAqB;AACpD,SAASC,aAAa,QAAQ,6BAA4B;AAC1D,OAAOC,gBAAgB,cAAa;AAEpC,SAASC,oBAAoB,QAAQ,0CAAyC;AAC9E,SAASC,eAAe,QAAQ,qCAAoC;AAEpE,MAAMC,cAAc,OACl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,aAAaxD,gBAAgB;YACjC6C,SAAS,IAAIY,QAAQX,YAAYD,OAAO;YACxCJ;QACF;QAEA,IAAK,MAAMiB,OAAOb,QAAS;YACzBW,WAAWG,MAAM,CAACD,KAAKb,OAAO,CAACa,IAAI;QACrC;QAEA,OAAO,IAAIE,SAASd,YAAYe,IAAI,EAAE;YACpChB,SAASW;YACTlD,QAAQwC,YAAYxC,MAAM;QAC5B;IACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../../../src/routes/rest/auth/access.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../../../src/routes/rest/auth/access.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAInD,eAAO,MAAM,MAAM,EAAE,gBAYpB,CAAA"}
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import httpStatus from 'http-status';
|
|
2
2
|
import { accessOperation } from 'payload/operations';
|
|
3
|
+
import { headersWithCors } from '../../../utilities/headersWithCors.js';
|
|
3
4
|
export const access = async ({ req })=>{
|
|
4
5
|
const results = await accessOperation({
|
|
5
6
|
req
|
|
6
7
|
});
|
|
7
8
|
return Response.json(results, {
|
|
9
|
+
headers: headersWithCors({
|
|
10
|
+
headers: new Headers(),
|
|
11
|
+
req
|
|
12
|
+
}),
|
|
8
13
|
status: httpStatus.OK
|
|
9
14
|
});
|
|
10
15
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/routes/rest/auth/access.ts"],"sourcesContent":["import httpStatus from 'http-status'\nimport { accessOperation } from 'payload/operations'\n\nimport type { BaseRouteHandler } from '../types.js'\n\nexport const access: BaseRouteHandler = async ({ req }) => {\n const results = await accessOperation({\n req,\n })\n\n return Response.json(results, {\n status: httpStatus.OK,\n })\n}\n"],"names":["httpStatus","accessOperation","access","req","results","Response","json","status","OK"],"rangeMappings":"
|
|
1
|
+
{"version":3,"sources":["../../../../src/routes/rest/auth/access.ts"],"sourcesContent":["import httpStatus from 'http-status'\nimport { accessOperation } from 'payload/operations'\n\nimport type { BaseRouteHandler } from '../types.js'\n\nimport { headersWithCors } from '../../../utilities/headersWithCors.js'\n\nexport const access: BaseRouteHandler = async ({ req }) => {\n const results = await accessOperation({\n req,\n })\n\n return Response.json(results, {\n headers: headersWithCors({\n headers: new Headers(),\n req,\n }),\n status: httpStatus.OK,\n })\n}\n"],"names":["httpStatus","accessOperation","headersWithCors","access","req","results","Response","json","headers","Headers","status","OK"],"rangeMappings":";;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,gBAAgB,cAAa;AACpC,SAASC,eAAe,QAAQ,qBAAoB;AAIpD,SAASC,eAAe,QAAQ,wCAAuC;AAEvE,OAAO,MAAMC,SAA2B,OAAO,EAAEC,GAAG,EAAE;IACpD,MAAMC,UAAU,MAAMJ,gBAAgB;QACpCG;IACF;IAEA,OAAOE,SAASC,IAAI,CAACF,SAAS;QAC5BG,SAASN,gBAAgB;YACvBM,SAAS,IAAIC;YACbL;QACF;QACAM,QAAQV,WAAWW,EAAE;IACvB;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forgotPassword.d.ts","sourceRoot":"","sources":["../../../../src/routes/rest/auth/forgotPassword.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"forgotPassword.d.ts","sourceRoot":"","sources":["../../../../src/routes/rest/auth/forgotPassword.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAA;AAIzD,eAAO,MAAM,cAAc,EAAE,sBAwB5B,CAAA"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import httpStatus from 'http-status';
|
|
2
2
|
import { forgotPasswordOperation } from 'payload/operations';
|
|
3
|
+
import { headersWithCors } from '../../../utilities/headersWithCors.js';
|
|
3
4
|
export const forgotPassword = async ({ collection, req })=>{
|
|
5
|
+
const { t } = req;
|
|
4
6
|
await forgotPasswordOperation({
|
|
5
7
|
collection,
|
|
6
8
|
data: {
|
|
@@ -11,9 +13,12 @@ export const forgotPassword = async ({ collection, req })=>{
|
|
|
11
13
|
req
|
|
12
14
|
});
|
|
13
15
|
return Response.json({
|
|
14
|
-
|
|
15
|
-
message: 'Success'
|
|
16
|
+
message: t('general:success')
|
|
16
17
|
}, {
|
|
18
|
+
headers: headersWithCors({
|
|
19
|
+
headers: new Headers(),
|
|
20
|
+
req
|
|
21
|
+
}),
|
|
17
22
|
status: httpStatus.OK
|
|
18
23
|
});
|
|
19
24
|
};
|