Compare commits

..

1 Commits

Author SHA1 Message Date
Elliot DeNolf
9301167ffb chore(release): v3.0.0-alpha.60 [skip ci] 2024-04-09 09:26:41 -04:00
410 changed files with 28418 additions and 18455 deletions

View File

@@ -4,7 +4,7 @@ on:
pull_request:
types: [opened, reopened, synchronize]
push:
branches: ['main', 'beta']
branches: ['main', 'alpha']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -88,6 +88,7 @@ jobs:
tests-unit:
runs-on: ubuntu-latest
needs: build
if: false # Disable until tests are updated for 3.0
steps:
- name: Use Node.js 18
@@ -220,11 +221,8 @@ jobs:
- email
- field-error-states
- fields-relationship
- fields
- fields__collections__Blocks
- fields__collections__Array
- fields__collections__Relationship
- fields__collections__Lexical
# - fields
- fields/lexical
- live-preview
- localization
- plugin-form-builder

View File

@@ -3,7 +3,7 @@ import type { Metadata } from 'next'
import config from '@payload-config'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import { NotFoundPage, generatePageMetadata } from '@payloadcms/next/views'
import { NotFoundPage, generatePageMetadata } from '@payloadcms/next/views/NotFound/index.js'
type Args = {
params: {
@@ -14,8 +14,8 @@ type Args = {
}
}
export const generateMetadata = ({ params, searchParams }: Args): Promise<Metadata> =>
generatePageMetadata({ config, params, searchParams })
export const generateMetadata = ({ params }: Args): Promise<Metadata> =>
generatePageMetadata({ config, params })
const NotFound = ({ params, searchParams }: Args) => NotFoundPage({ config, params, searchParams })

View File

@@ -3,7 +3,7 @@ import type { Metadata } from 'next'
import config from '@payload-config'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import { RootPage, generatePageMetadata } from '@payloadcms/next/views'
import { RootPage, generatePageMetadata } from '@payloadcms/next/views/Root/index.js'
type Args = {
params: {

View File

@@ -1,7 +1,7 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes/index.js'
export const GET = REST_GET(config)
export const POST = REST_POST(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes'
import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes/index.js'
export const GET = GRAPHQL_PLAYGROUND_GET(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { GRAPHQL_POST } from '@payloadcms/next/routes'
import { GRAPHQL_POST } from '@payloadcms/next/routes/index.js'
export const POST = GRAPHQL_POST(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import configPromise from '@payload-config'
import { RootLayout } from '@payloadcms/next/layouts'
import { RootLayout } from '@payloadcms/next/layouts/Root/index.js'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import React from 'react'

1
emptyModule.js Normal file
View File

@@ -0,0 +1 @@
export default {}

View File

@@ -1,6 +1,6 @@
{
"name": "payload-monorepo",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"private": true,
"type": "module",
"workspaces:": [

View File

@@ -1,6 +1,6 @@
{
"name": "create-payload-app",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"license": "MIT",
"type": "module",
"homepage": "https://payloadcms.com",
@@ -35,7 +35,7 @@
"comment-json": "^4.2.3",
"degit": "^2.8.4",
"detect-package-manager": "^3.0.1",
"esprima-next": "^6.0.3",
"esprima": "^4.0.1",
"execa": "^5.0.0",
"figures": "^6.1.0",
"fs-extra": "^9.0.1",

View File

@@ -4,7 +4,6 @@ import * as p from '@clack/prompts'
import { parse, stringify } from 'comment-json'
import execa from 'execa'
import fs from 'fs'
import fse from 'fs-extra'
import globby from 'globby'
import path from 'path'
import { promisify } from 'util'
@@ -32,8 +31,6 @@ type InitNextArgs = Pick<CliArgs, '--debug'> & {
useDistFiles?: boolean
}
type NextConfigType = 'cjs' | 'esm'
type InitNextResult =
| {
isSrcDir: boolean
@@ -48,22 +45,11 @@ export async function initNext(args: InitNextArgs): Promise<InitNextResult> {
const nextAppDetails = args.nextAppDetails || (await getNextAppDetails(projectDir))
if (!nextAppDetails.nextAppDir) {
warning(`Could not find app directory in ${projectDir}, creating...`)
const createdAppDir = path.resolve(projectDir, nextAppDetails.isSrcDir ? 'src/app' : 'app')
fse.mkdirSync(createdAppDir, { recursive: true })
nextAppDetails.nextAppDir = createdAppDir
}
const { hasTopLevelLayout, isSrcDir, nextAppDir } =
nextAppDetails || (await getNextAppDetails(projectDir))
const { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigType } = nextAppDetails
if (!nextConfigType) {
return {
isSrcDir,
nextAppDir,
reason: `Could not determine Next Config type in ${projectDir}. Possibly try renaming next.config.js to next.config.cjs or next.config.mjs.`,
success: false,
}
if (!nextAppDir) {
return { isSrcDir, reason: `Could not find app directory in ${projectDir}`, success: false }
}
if (hasTopLevelLayout) {
@@ -83,7 +69,6 @@ export async function initNext(args: InitNextArgs): Promise<InitNextResult> {
const configurationResult = installAndConfigurePayload({
...args,
nextAppDetails,
nextConfigType,
useDistFiles: true, // Requires running 'pnpm pack-template-files' in cpa
})
@@ -111,13 +96,6 @@ export async function initNext(args: InitNextArgs): Promise<InitNextResult> {
async function addPayloadConfigToTsConfig(projectDir: string, isSrcDir: boolean) {
const tsConfigPath = path.resolve(projectDir, 'tsconfig.json')
// Check if tsconfig.json exists
if (!fs.existsSync(tsConfigPath)) {
warning(`Could not find tsconfig.json to add @payload-config path.`)
return
}
const userTsConfigContent = await readFile(tsConfigPath, {
encoding: 'utf8',
})
@@ -141,18 +119,13 @@ async function addPayloadConfigToTsConfig(projectDir: string, isSrcDir: boolean)
}
function installAndConfigurePayload(
args: InitNextArgs & {
nextAppDetails: NextAppDetails
nextConfigType: NextConfigType
useDistFiles?: boolean
},
args: InitNextArgs & { nextAppDetails: NextAppDetails; useDistFiles?: boolean },
):
| { payloadConfigPath: string; success: true }
| { payloadConfigPath?: string; reason: string; success: false } {
const {
'--debug': debug,
nextAppDetails: { isSrcDir, nextAppDir, nextConfigPath } = {},
nextConfigType,
projectDir,
useDistFiles,
} = args
@@ -199,7 +172,6 @@ function installAndConfigurePayload(
logDebug(`nextAppDir: ${nextAppDir}`)
logDebug(`projectDir: ${projectDir}`)
logDebug(`nextConfigPath: ${nextConfigPath}`)
logDebug(`payloadConfigPath: ${path.resolve(projectDir, 'payload.config.ts')}`)
logDebug(
`isSrcDir: ${isSrcDir}. source: ${templateSrcDir}. dest: ${path.dirname(nextConfigPath)}`,
@@ -209,7 +181,7 @@ function installAndConfigurePayload(
copyRecursiveSync(templateSrcDir, path.dirname(nextConfigPath), debug)
// Wrap next.config.js with withPayload
wrapNextConfig({ nextConfigPath, nextConfigType })
wrapNextConfig({ nextConfigPath })
return {
payloadConfigPath: path.resolve(nextAppDir, '../payload.config.ts'),
@@ -219,10 +191,10 @@ function installAndConfigurePayload(
async function installDeps(projectDir: string, packageManager: PackageManager, dbType: DbType) {
const packagesToInstall = ['payload', '@payloadcms/next', '@payloadcms/richtext-lexical'].map(
(pkg) => `${pkg}@beta`,
(pkg) => `${pkg}@alpha`,
)
packagesToInstall.push(`@payloadcms/db-${dbType}@beta`)
packagesToInstall.push(`@payloadcms/db-${dbType}@alpha`)
let exitCode = 0
switch (packageManager) {
@@ -254,7 +226,6 @@ type NextAppDetails = {
isSrcDir: boolean
nextAppDir?: string
nextConfigPath?: string
nextConfigType?: NextConfigType
}
export async function getNextAppDetails(projectDir: string): Promise<NextAppDetails> {
@@ -275,7 +246,6 @@ export async function getNextAppDetails(projectDir: string): Promise<NextAppDeta
await globby(['**/app'], {
absolute: true,
cwd: projectDir,
ignore: ['**/node_modules/**'],
onlyDirectories: true,
})
)?.[0]
@@ -284,31 +254,9 @@ export async function getNextAppDetails(projectDir: string): Promise<NextAppDeta
nextAppDir = undefined
}
const configType = await getProjectType(projectDir, nextConfigPath)
const hasTopLevelLayout = nextAppDir
? fs.existsSync(path.resolve(nextAppDir, 'layout.tsx'))
: false
return { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigPath, nextConfigType: configType }
}
async function getProjectType(projectDir: string, nextConfigPath: string): Promise<'cjs' | 'esm'> {
if (nextConfigPath.endsWith('.mjs')) {
return 'esm'
}
if (nextConfigPath.endsWith('.cjs')) {
return 'cjs'
}
const packageObj = await fse.readJson(path.resolve(projectDir, 'package.json'))
const packageJsonType = packageObj.type
if (packageJsonType === 'module') {
return 'esm'
}
if (packageJsonType === 'commonjs') {
return 'cjs'
}
return 'cjs'
return { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigPath }
}

View File

@@ -10,18 +10,14 @@ const mongodbReplacement: DbAdapterReplacement = {
importReplacement: "import { mongooseAdapter } from '@payloadcms/db-mongodb'",
packageName: '@payloadcms/db-mongodb',
// Replacement between `// database-adapter-config-start` and `// database-adapter-config-end`
configReplacement: [
' db: mongooseAdapter({',
" url: process.env.DATABASE_URI || '',",
' }),',
],
configReplacement: [' db: mongooseAdapter({', ' url: process.env.DATABASE_URI,', ' }),'],
}
const postgresReplacement: DbAdapterReplacement = {
configReplacement: [
' db: postgresAdapter({',
' pool: {',
" connectionString: process.env.DATABASE_URI || '',",
' connectionString: process.env.DATABASE_URI,',
' },',
' }),',
],

View File

@@ -18,46 +18,43 @@ export function getValidTemplates(): ProjectTemplate[] {
name: 'blank-3.0',
type: 'starter',
description: 'Blank 3.0 Template',
url: 'https://github.com/payloadcms/payload/templates/blank-3.0#beta',
url: 'https://github.com/payloadcms/payload/templates/blank-3.0',
},
{
name: 'blank',
type: 'starter',
description: 'Blank Template',
url: 'https://github.com/payloadcms/payload/templates/blank',
},
{
name: 'website',
type: 'starter',
description: 'Website Template',
url: 'https://github.com/payloadcms/payload/templates/website',
},
{
name: 'ecommerce',
type: 'starter',
description: 'E-commerce Template',
url: 'https://github.com/payloadcms/payload/templates/ecommerce',
},
{
name: 'plugin',
type: 'plugin',
description: 'Template for creating a Payload plugin',
url: 'https://github.com/payloadcms/payload-plugin-template',
},
{
name: 'payload-demo',
type: 'starter',
description: 'Payload demo site at https://demo.payloadcms.com',
url: 'https://github.com/payloadcms/public-demo',
},
{
name: 'payload-website',
type: 'starter',
description: 'Payload website CMS at https://payloadcms.com',
url: 'https://github.com/payloadcms/website-cms',
},
// Remove these until they have been updated for 3.0
// {
// name: 'blank',
// type: 'starter',
// description: 'Blank Template',
// url: 'https://github.com/payloadcms/payload/templates/blank',
// },
// {
// name: 'website',
// type: 'starter',
// description: 'Website Template',
// url: 'https://github.com/payloadcms/payload/templates/website',
// },
// {
// name: 'ecommerce',
// type: 'starter',
// description: 'E-commerce Template',
// url: 'https://github.com/payloadcms/payload/templates/ecommerce',
// },
// {
// name: 'plugin',
// type: 'plugin',
// description: 'Template for creating a Payload plugin',
// url: 'https://github.com/payloadcms/payload-plugin-template',
// },
// {
// name: 'payload-demo',
// type: 'starter',
// description: 'Payload demo site at https://demo.payloadcms.com',
// url: 'https://github.com/payloadcms/public-demo',
// },
// {
// name: 'payload-website',
// type: 'starter',
// description: 'Payload website CMS at https://payloadcms.com',
// url: 'https://github.com/payloadcms/website-cms',
// },
]
}

View File

@@ -1,159 +1,61 @@
import { parseAndModifyConfigContent, withPayloadStatement } from './wrap-next-config.js'
import { parseAndModifyConfigContent, withPayloadImportStatement } from './wrap-next-config.js'
import * as p from '@clack/prompts'
const esmConfigs = {
defaultNextConfig: `/** @type {import('next').NextConfig} */
const defaultNextConfig = `/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
`,
nextConfigWithFunc: `const nextConfig = {};
export default someFunc(nextConfig);
`,
nextConfigWithFuncMultiline: `const nextConfig = {};;
`
const nextConfigWithFunc = `const nextConfig = {
// Your Next.js config here
}
export default someFunc(nextConfig)
`
const nextConfigWithFuncMultiline = `const nextConfig = {
// Your Next.js config here
}
export default someFunc(
nextConfig
);
`,
nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
export { wrapped as default };
`,
nextConfigWithSpread: `const nextConfig = {
...someConfig,
};
export default nextConfig;
`,
}
)
`
const cjsConfigs = {
defaultNextConfig: `
/** @type {import('next').NextConfig} */
const nextConfig = {};
module.exports = nextConfig;
`,
anonConfig: `module.exports = {};`,
nextConfigWithFunc: `const nextConfig = {};
module.exports = someFunc(nextConfig);
`,
nextConfigWithFuncMultiline: `const nextConfig = {};
module.exports = someFunc(
nextConfig
);
`,
nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
module.exports = wrapped;
`,
nextConfigWithSpread: `const nextConfig = { ...someConfig };
module.exports = nextConfig;
`,
const nextConfigExportNamedDefault = `const nextConfig = {
// Your Next.js config here
}
const wrapped = someFunc(asdf)
export { wrapped as default }
`
describe('parseAndInsertWithPayload', () => {
describe('esm', () => {
const configType = 'esm'
const importStatement = withPayloadStatement[configType]
it('should parse the default next config', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
esmConfigs.defaultNextConfig,
configType,
)
expect(modifiedConfigContent).toContain(importStatement)
expect(modifiedConfigContent).toContain('withPayload(nextConfig)')
})
it('should parse the config with a function', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
esmConfigs.nextConfigWithFunc,
configType,
)
expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')
})
it('should parse the config with a function on a new line', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
esmConfigs.nextConfigWithFuncMultiline,
configType,
)
expect(modifiedConfigContent).toContain(importStatement)
expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/)
})
it('should parse the config with a spread', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
esmConfigs.nextConfigWithSpread,
configType,
)
expect(modifiedConfigContent).toContain(importStatement)
expect(modifiedConfigContent).toContain('withPayload(nextConfig)')
})
// Unsupported: export { wrapped as default }
it('should give warning with a named export as default', () => {
const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(() => {})
const { modifiedConfigContent, success } = parseAndModifyConfigContent(
esmConfigs.nextConfigExportNamedDefault,
configType,
)
expect(modifiedConfigContent).toContain(importStatement)
expect(success).toBe(false)
expect(warnLogSpy).toHaveBeenCalledWith(
expect.stringContaining('Could not automatically wrap'),
)
})
it('should parse the default next config', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(defaultNextConfig)
expect(modifiedConfigContent).toContain(withPayloadImportStatement)
expect(modifiedConfigContent).toContain('withPayload(nextConfig)')
})
it('should parse the config with a function', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFunc)
expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')
})
describe('cjs', () => {
const configType = 'cjs'
const requireStatement = withPayloadStatement[configType]
it('should parse the default next config', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.defaultNextConfig,
configType,
)
expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toContain('withPayload(nextConfig)')
})
it('should parse anonymous default config', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.anonConfig,
configType,
)
expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toContain('withPayload({})')
})
it('should parse the config with a function', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.nextConfigWithFunc,
configType,
)
expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')
})
it('should parse the config with a function on a new line', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.nextConfigWithFuncMultiline,
configType,
)
expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/)
})
it('should parse the config with a named export as default', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.nextConfigExportNamedDefault,
configType,
)
expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toContain('withPayload(wrapped)')
})
it('should parse the config with a function on a new line', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFuncMultiline)
expect(modifiedConfigContent).toContain(withPayloadImportStatement)
expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/)
})
it('should parse the config with a spread', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent(
cjsConfigs.nextConfigWithSpread,
configType,
)
expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toContain('withPayload(nextConfig)')
})
// Unsupported: export { wrapped as default }
it('should give warning with a named export as default', () => {
const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(() => {})
const { modifiedConfigContent, success } = parseAndModifyConfigContent(
nextConfigExportNamedDefault,
)
expect(modifiedConfigContent).toContain(withPayloadImportStatement)
expect(success).toBe(false)
expect(warnLogSpy).toHaveBeenCalledWith(expect.stringContaining('Could not automatically wrap'))
})
})

View File

@@ -1,29 +1,16 @@
import type { Program } from 'esprima-next'
import chalk from 'chalk'
import { Syntax, parseModule } from 'esprima-next'
import { parseModule } from 'esprima'
import fs from 'fs'
import { warning } from '../utils/log.js'
import { log } from '../utils/log.js'
export const withPayloadStatement = {
cjs: `const { withPayload } = require('@payloadcms/next/withPayload')\n`,
esm: `import { withPayload } from '@payloadcms/next/withPayload'\n`,
}
export const withPayloadImportStatement = `import { withPayload } from '@payloadcms/next'\n`
type NextConfigType = 'cjs' | 'esm'
export const wrapNextConfig = (args: {
nextConfigPath: string
nextConfigType: NextConfigType
}) => {
const { nextConfigPath, nextConfigType: configType } = args
export const wrapNextConfig = (args: { nextConfigPath: string }) => {
const { nextConfigPath } = args
const configContent = fs.readFileSync(nextConfigPath, 'utf8')
const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(
configContent,
configType,
)
const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(configContent)
if (!success) {
return
@@ -35,121 +22,72 @@ export const wrapNextConfig = (args: {
/**
* Parses config content with AST and wraps it with withPayload function
*/
export function parseAndModifyConfigContent(
content: string,
configType: NextConfigType,
): { modifiedConfigContent: string; success: boolean } {
content = withPayloadStatement[configType] + content
export function parseAndModifyConfigContent(content: string): {
modifiedConfigContent: string
success: boolean
} {
content = withPayloadImportStatement + content
const ast = parseModule(content, { loc: true })
const exportDefaultDeclaration = ast.body.find((p) => p.type === 'ExportDefaultDeclaration') as
| Directive
| undefined
let ast: Program | undefined
try {
ast = parseModule(content, { loc: true })
} catch (error: unknown) {
if (error instanceof Error) {
warning(`Unable to parse Next config. Error: ${error.message} `)
warnUserWrapNotSuccessful(configType)
}
return {
modifiedConfigContent: content,
success: false,
}
const exportNamedDeclaration = ast.body.find((p) => p.type === 'ExportNamedDeclaration') as
| ExportNamedDeclaration
| undefined
if (!exportDefaultDeclaration && !exportNamedDeclaration) {
throw new Error('Could not find ExportDefaultDeclaration in next.config.js')
}
if (configType === 'esm') {
const exportDefaultDeclaration = ast.body.find(
(p) => p.type === Syntax.ExportDefaultDeclaration,
) as Directive | undefined
if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {
const modifiedConfigContent = insertBeforeAndAfter(
content,
exportDefaultDeclaration.declaration.loc,
)
return { modifiedConfigContent, success: true }
} else if (exportNamedDeclaration) {
const exportSpecifier = exportNamedDeclaration.specifiers.find(
(s) =>
s.type === 'ExportSpecifier' &&
s.exported?.name === 'default' &&
s.local?.type === 'Identifier' &&
s.local?.name,
)
const exportNamedDeclaration = ast.body.find(
(p) => p.type === Syntax.ExportNamedDeclaration,
) as ExportNamedDeclaration | undefined
if (exportSpecifier) {
warning('Could not automatically wrap next.config.js with withPayload.')
warning('Automatic wrapping of named exports as default not supported yet.')
if (!exportDefaultDeclaration && !exportNamedDeclaration) {
throw new Error('Could not find ExportDefaultDeclaration in next.config.js')
}
if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {
const modifiedConfigContent = insertBeforeAndAfter(
content,
exportDefaultDeclaration.declaration.loc,
)
return { modifiedConfigContent, success: true }
} else if (exportNamedDeclaration) {
const exportSpecifier = exportNamedDeclaration.specifiers.find(
(s) =>
s.type === 'ExportSpecifier' &&
s.exported?.name === 'default' &&
s.local?.type === 'Identifier' &&
s.local?.name,
)
if (exportSpecifier) {
warning('Could not automatically wrap next.config.js with withPayload.')
warning('Automatic wrapping of named exports as default not supported yet.')
warnUserWrapNotSuccessful(configType)
return {
modifiedConfigContent: content,
success: false,
}
warnUserWrapNotSuccessful()
return {
modifiedConfigContent: content,
success: false,
}
}
warning('Could not automatically wrap Next config with withPayload.')
warnUserWrapNotSuccessful(configType)
return {
modifiedConfigContent: content,
success: false,
}
} else if (configType === 'cjs') {
// Find `module.exports = X`
const moduleExports = ast.body.find(
(p) =>
p.type === Syntax.ExpressionStatement &&
p.expression?.type === Syntax.AssignmentExpression &&
p.expression.left?.type === Syntax.MemberExpression &&
p.expression.left.object?.type === Syntax.Identifier &&
p.expression.left.object.name === 'module' &&
p.expression.left.property?.type === Syntax.Identifier &&
p.expression.left.property.name === 'exports',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) as any
if (moduleExports && moduleExports.expression.right?.loc) {
const modifiedConfigContent = insertBeforeAndAfter(
content,
moduleExports.expression.right.loc,
)
return { modifiedConfigContent, success: true }
}
return {
modifiedConfigContent: content,
success: false,
}
}
warning('Could not automatically wrap Next config with withPayload.')
warnUserWrapNotSuccessful(configType)
warning('Could not automatically wrap next.config.js with withPayload.')
warnUserWrapNotSuccessful()
return {
modifiedConfigContent: content,
success: false,
}
}
function warnUserWrapNotSuccessful(configType: NextConfigType) {
function warnUserWrapNotSuccessful() {
// Output directions for user to update next.config.js
const withPayloadMessage = `
${chalk.bold(`Please manually wrap your existing next.config.js with the withPayload function. Here is an example:`)}
${withPayloadStatement[configType]}
import withPayload from '@payloadcms/next/withPayload'
const nextConfig = {
// Your Next.js config here
}
${configType === 'esm' ? 'export default withPayload(nextConfig)' : 'module.exports = withPayload(nextConfig)'}
export default withPayload(nextConfig)
`

View File

@@ -20,41 +20,32 @@ export async function writeEnvFile(args: {
return
}
const envOutputPath = path.join(projectDir, '.env')
try {
if (fs.existsSync(envOutputPath)) {
if (template?.type === 'starter') {
// Parse .env file into key/value pairs
const envFile = await fs.readFile(path.join(projectDir, '.env.example'), 'utf8')
const envWithValues: string[] = envFile
.split('\n')
.filter((e) => e)
.map((line) => {
if (line.startsWith('#') || !line.includes('=')) return line
if (template?.type === 'starter' && fs.existsSync(path.join(projectDir, '.env.example'))) {
// Parse .env file into key/value pairs
const envFile = await fs.readFile(path.join(projectDir, '.env.example'), 'utf8')
const envWithValues: string[] = envFile
.split('\n')
.filter((e) => e)
.map((line) => {
if (line.startsWith('#') || !line.includes('=')) return line
const split = line.split('=')
const key = split[0]
let value = split[1]
const split = line.split('=')
const key = split[0]
let value = split[1]
if (key === 'MONGODB_URI' || key === 'MONGO_URL' || key === 'DATABASE_URI') {
value = databaseUri
}
if (key === 'PAYLOAD_SECRET' || key === 'PAYLOAD_SECRET_KEY') {
value = payloadSecret
}
if (key === 'MONGODB_URI' || key === 'MONGO_URL' || key === 'DATABASE_URI') {
value = databaseUri
}
if (key === 'PAYLOAD_SECRET' || key === 'PAYLOAD_SECRET_KEY') {
value = payloadSecret
}
return `${key}=${value}`
})
return `${key}=${value}`
})
// Write new .env file
await fs.writeFile(envOutputPath, envWithValues.join('\n'))
} else {
const existingEnv = await fs.readFile(envOutputPath, 'utf8')
const newEnv =
existingEnv + `\nDATABASE_URI=${databaseUri}\nPAYLOAD_SECRET=${payloadSecret}\n`
await fs.writeFile(envOutputPath, newEnv)
}
// Write new .env file
await fs.writeFile(path.join(projectDir, '.env'), envWithValues.join('\n'))
} else {
const content = `DATABASE_URI=${databaseUri}\nPAYLOAD_SECRET=${payloadSecret}`
await fs.outputFile(`${projectDir}/.env`, content)

View File

@@ -21,12 +21,6 @@ export function helpMessage(): void {
console.log(chalk`
{bold USAGE}
{dim Inside of an existing Next.js project}
{dim $} {bold npx create-payload-app}
{dim Create a new project from scratch}
{dim $} {bold npx create-payload-app}
{dim $} {bold npx create-payload-app} my-project
{dim $} {bold npx create-payload-app} -n my-project -t template-name
@@ -86,7 +80,7 @@ export function successfulNextInit(): string {
}
export function moveMessage(args: { nextAppDir: string; projectDir: string }): string {
const relativeAppDir = path.relative(process.cwd(), args.nextAppDir)
const relativePath = path.relative(process.cwd(), args.nextAppDir)
return `
${header('Next Steps:')}
@@ -94,10 +88,7 @@ Payload does not support a top-level layout.tsx file in the app directory.
${chalk.bold('To continue:')}
- Create a new directory in ./${relativeAppDir} such as ./${relativeAppDir}/${chalk.bold('(app)')}
- Move all files from ./${relativeAppDir} into that directory
It is recommended to do this from your IDE if your app has existing file references.
Move all files from ./${relativePath} to a named directory such as ./${relativePath}/${chalk.bold('(app)')}
Once moved, rerun the create-payload-app command again.
`

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-mongodb",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"description": "The officially supported MongoDB database adapter for Payload",
"repository": {
"type": "git",

View File

@@ -56,6 +56,12 @@ export const init: Init = function init(this: MongooseAdapter) {
this.autoPluralization === true ? undefined : collection.slug,
) as CollectionModel
this.collections[collection.slug] = model
// TS expect error only needed until we launch 2.0.0
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
this.payload.collections[collection.slug] = {
config: collection,
}
})
const model = buildGlobalModel(this.payload.config)

View File

@@ -59,12 +59,17 @@ export async function buildSearchParam({
let hasCustomID = false
if (sanitizedPath === '_id') {
const customIDFieldType = payload.collections[collectionSlug]?.customIDType
const customIDfield = payload.collections[collectionSlug]?.config.fields.find(
(field) => fieldAffectsData(field) && field.name === 'id',
)
let idFieldType: 'number' | 'text' = 'text'
if (customIDFieldType) {
idFieldType = customIDFieldType
if (customIDfield) {
if (customIDfield?.type === 'text' || customIDfield?.type === 'number') {
idFieldType = customIDfield.type
}
hasCustomID = true
}
@@ -208,11 +213,18 @@ export async function buildSearchParam({
} else {
;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach(
(relationTo) => {
const isRelatedToCustomNumberID =
payload.collections[relationTo]?.customIDType === 'number'
const isRelatedToCustomNumberID = payload.collections[
relationTo
]?.config?.fields.find((relatedField) => {
return (
fieldAffectsData(relatedField) &&
relatedField.name === 'id' &&
relatedField.type === 'number'
)
})
if (isRelatedToCustomNumberID) {
hasNumberIDRelation = true
if (isRelatedToCustomNumberID.type === 'number') hasNumberIDRelation = true
}
},
)

View File

@@ -1,20 +1,18 @@
import { SanitizedConfig, sanitizeConfig } from 'payload/config'
import { sanitizeConfig } from 'payload/config'
import { Config } from 'payload/config'
import { getLocalizedSortProperty } from './getLocalizedSortProperty.js'
const config = sanitizeConfig({
const config = {
localization: {
locales: ['en', 'es'],
defaultLocale: 'en',
fallback: true,
},
} as Config) as SanitizedConfig
} as Config
describe('get localized sort property', () => {
it('passes through a non-localized sort property', () => {
const result = getLocalizedSortProperty({
segments: ['title'],
config,
config: sanitizeConfig(config),
fields: [
{
name: 'title',
@@ -30,7 +28,7 @@ describe('get localized sort property', () => {
it('properly localizes an un-localized sort property', () => {
const result = getLocalizedSortProperty({
segments: ['title'],
config,
config: sanitizeConfig(config),
fields: [
{
name: 'title',
@@ -47,7 +45,7 @@ describe('get localized sort property', () => {
it('keeps specifically asked-for localized sort properties', () => {
const result = getLocalizedSortProperty({
segments: ['title', 'es'],
config,
config: sanitizeConfig(config),
fields: [
{
name: 'title',
@@ -64,7 +62,7 @@ describe('get localized sort property', () => {
it('properly localizes nested sort properties', () => {
const result = getLocalizedSortProperty({
segments: ['group', 'title'],
config,
config: sanitizeConfig(config),
fields: [
{
name: 'group',
@@ -87,7 +85,7 @@ describe('get localized sort property', () => {
it('keeps requested locale with nested sort properties', () => {
const result = getLocalizedSortProperty({
segments: ['group', 'title', 'es'],
config,
config: sanitizeConfig(config),
fields: [
{
name: 'group',
@@ -110,7 +108,7 @@ describe('get localized sort property', () => {
it('properly localizes field within row', () => {
const result = getLocalizedSortProperty({
segments: ['title'],
config,
config: sanitizeConfig(config),
fields: [
{
type: 'row',
@@ -132,7 +130,7 @@ describe('get localized sort property', () => {
it('properly localizes field within named tab', () => {
const result = getLocalizedSortProperty({
segments: ['tab', 'title'],
config,
config: sanitizeConfig(config),
fields: [
{
type: 'tabs',
@@ -159,7 +157,7 @@ describe('get localized sort property', () => {
it('properly localizes field within unnamed tab', () => {
const result = getLocalizedSortProperty({
segments: ['title'],
config,
config: sanitizeConfig(config),
fields: [
{
type: 'tabs',

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-postgres",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"description": "The officially supported Postgres database adapter for Payload",
"repository": {
"type": "git",

View File

@@ -298,12 +298,11 @@ export const buildTable = ({
throwValidationError: true,
})
let colType = adapter.idType === 'uuid' ? 'uuid' : 'integer'
const relatedCollectionCustomIDType =
adapter.payload.collections[relationshipConfig.slug]?.customIDType
if (relatedCollectionCustomIDType === 'number') colType = 'numeric'
if (relatedCollectionCustomIDType === 'text') colType = 'varchar'
const relatedCollectionCustomID = relationshipConfig.fields.find(
(field) => fieldAffectsData(field) && field.name === 'id',
)
if (relatedCollectionCustomID?.type === 'number') colType = 'numeric'
if (relatedCollectionCustomID?.type === 'text') colType = 'varchar'
relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](
`${formattedRelationTo}_id`,

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/graphql",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"main": "./src/index.ts",
"types": "./src/index.d.ts",
"type": "module",

View File

@@ -1,15 +0,0 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"jsc": {
"target": "esnext",
"parser": {
"syntax": "typescript",
"tsx": true,
"dts": true
}
},
"module": {
"type": "commonjs"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/next",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"main": "./src/index.js",
"types": "./src/index.js",
"type": "module",
@@ -11,8 +11,7 @@
"directory": "packages/next"
},
"scripts": {
"build:cjs": "swc ./src/withPayload.js -o ./dist/cjs/withPayload.cjs --config-file .swcrc-cjs",
"build": "pnpm copyfiles && pnpm build:swc && pnpm build:cjs && pnpm build:types && pnpm build:webpack && rm dist/prod/index.js",
"build": "pnpm copyfiles && pnpm build:swc && pnpm build:types && pnpm build:webpack && rm dist/prod/index.js",
"build:swc": "swc ./src -d ./dist --config-file .swcrc",
"build:types": "tsc --emitDeclarationOnly --outDir dist",
"build:webpack": "webpack --config webpack.config.js",
@@ -28,10 +27,6 @@
"require": "./src/index.js",
"types": "./src/index.js"
},
"./withPayload": {
"import": "./src/withPayload.js",
"require": "./src/withPayload.js"
},
"./*": {
"import": "./src/exports/*.ts",
"require": "./src/exports/*.ts",
@@ -89,9 +84,9 @@
"require": "./dist/prod/styles.css",
"default": "./dist/prod/styles.css"
},
"./withPayload": {
"import": "./dist/withPayload.js",
"require": "./dist/cjs/withPayload.cjs"
".": {
"import": "./dist/index.js",
"require": "./dist/index.js"
},
"./*": {
"import": "./dist/exports/*.js",

View File

@@ -1,2 +1,2 @@
export { getNextRequestI18n } from '../utilities/getNextRequestI18n.js'
export { getNextI18n } from '../utilities/getNextI18n.js'
export { getPayloadHMR } from '../utilities/getPayloadHMR.js'

View File

@@ -1,18 +1,16 @@
import type { AcceptedLanguages } from '@payloadcms/translations'
import type { SanitizedConfig } from 'payload/types'
import { rtlLanguages } from '@payloadcms/translations'
import { initI18n } from '@payloadcms/translations'
import { translations } from '@payloadcms/translations/client'
import { RootProvider } from '@payloadcms/ui/providers/Root'
import '@payloadcms/ui/scss/app.scss'
import { buildComponentMap } from '@payloadcms/ui/utilities/buildComponentMap'
import { headers as getHeaders, cookies as nextCookies } from 'next/headers.js'
import { parseCookies } from 'payload/auth'
import { createClientConfig } from 'payload/config'
import { deepMerge } from 'payload/utilities'
import React from 'react'
import 'react-toastify/dist/ReactToastify.css'
import { getPayloadHMR } from '../../utilities/getPayloadHMR.js'
import { getRequestLanguage } from '../../utilities/getRequestLanguage.js'
import { DefaultEditView } from '../../views/Edit/Default/index.js'
import { DefaultListView } from '../../views/List/Default/index.js'
@@ -22,6 +20,8 @@ export const metadata = {
title: 'Next.js',
}
const rtlLanguages = ['ar', 'fa', 'ha', 'ku', 'ur', 'ps', 'dv', 'ks', 'khw', 'he', 'yi']
export const RootLayout = async ({
children,
config: configPromise,
@@ -30,37 +30,26 @@ export const RootLayout = async ({
config: Promise<SanitizedConfig>
}) => {
const config = await configPromise
const clientConfig = await createClientConfig(config)
const headers = getHeaders()
const cookies = parseCookies(headers)
const languageCode = getRequestLanguage({
config,
cookies,
headers,
})
const lang =
getRequestLanguage({
config,
cookies,
headers,
}) ?? clientConfig.i18n.fallbackLanguage
const payload = await getPayloadHMR({ config })
const i18n = await initI18n({ config: config.i18n, context: 'client', language: languageCode })
const clientConfig = await createClientConfig({ config, t: i18n.t })
const dir = rtlLanguages.includes(lang) ? 'RTL' : 'LTR'
const dir = (rtlLanguages as unknown as AcceptedLanguages[]).includes(languageCode)
? 'RTL'
: 'LTR'
const mergedTranslations = deepMerge(translations, clientConfig.i18n.translations)
const languageOptions = Object.entries(config.i18n.supportedLanguages || {}).reduce(
(acc, [language, languageConfig]) => {
if (Object.keys(config.i18n.supportedLanguages).includes(language)) {
acc.push({
label: languageConfig.translations.general.thisLanguage,
value: language,
})
}
return acc
},
[],
)
const languageOptions = Object.entries(translations || {}).map(([language, translations]) => ({
label: translations.general.thisLanguage,
value: language,
}))
// eslint-disable-next-line @typescript-eslint/require-await
async function switchLanguageServerAction(lang: string): Promise<void> {
@@ -77,23 +66,20 @@ export const RootLayout = async ({
DefaultListView,
children,
config,
i18n,
payload,
})
return (
<html dir={dir} lang={languageCode}>
<html dir={dir} lang={lang}>
<body>
<RootProvider
componentMap={componentMap}
config={clientConfig}
dateFNSKey={i18n.dateFNSKey}
fallbackLang={clientConfig.i18n.fallbackLanguage}
languageCode={languageCode}
lang={lang}
languageOptions={languageOptions}
// eslint-disable-next-line react/jsx-no-bind
switchLanguageServerAction={switchLanguageServerAction}
translations={i18n.translations}
translations={mergedTranslations[lang]}
>
{wrappedChildren}
</RootProvider>

View File

@@ -1,5 +1,11 @@
import type { BuildFormStateArgs } from '@payloadcms/ui/forms/buildStateFromSchema'
import type { DocumentPreferences, Field, PayloadRequest, TypeWithID } from 'payload/types'
import type {
DocumentPreferences,
Field,
PayloadRequest,
SanitizedConfig,
TypeWithID,
} from 'payload/types'
import { buildStateFromSchema } from '@payloadcms/ui/forms/buildStateFromSchema'
import { reduceFieldsToValues } from '@payloadcms/ui/utilities/reduceFieldsToValues'
@@ -16,12 +22,12 @@ if (!cached) {
cached = global._payload_fieldSchemaMap = null
}
export const getFieldSchemaMap = (req: PayloadRequest): FieldSchemaMap => {
export const getFieldSchemaMap = (config: SanitizedConfig): FieldSchemaMap => {
if (cached && process.env.NODE_ENV !== 'development') {
return cached
}
cached = buildFieldSchemaMap(req)
cached = buildFieldSchemaMap(config)
return cached
}
@@ -59,7 +65,7 @@ export const buildFormState = async ({ req }: { req: PayloadRequest }) => {
})
}
const fieldSchemaMap = getFieldSchemaMap(req)
const fieldSchemaMap = getFieldSchemaMap(req.payload.config)
const id = collectionSlug ? reqData.id : undefined
const schemaPathSegments = schemaPath.split('.')
@@ -156,7 +162,7 @@ export const buildFormState = async ({ req }: { req: PayloadRequest }) => {
})
}
if (globalSlug && schemaPath === globalSlug) {
if (globalSlug) {
resolvedData = await req.payload.findGlobal({
slug: globalSlug,
depth: 0,

View File

@@ -4,22 +4,9 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const deleteByID: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const deleteByID: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const doc = await deleteByIDOperation({
id,
collection,

View File

@@ -5,24 +5,12 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const duplicate: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const duplicate: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
// draft defaults to true, unless explicitly set requested as false to prevent the newly duplicated document from being published
const draft = searchParams.get('draft') !== 'false'
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const doc = await duplicateOperation({
id,
collection,

View File

@@ -4,22 +4,10 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const findByID: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const findByID: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const result = await findByIDOperation({
id,
collection,

View File

@@ -4,22 +4,10 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const findVersionByID: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const findVersionByID: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const result = await findVersionByIDOperation({
id,
collection,

View File

@@ -1,5 +1,4 @@
import httpStatus from 'http-status'
import { extractJWT } from 'payload/auth'
import { findByIDOperation } from 'payload/operations'
import { isNumber } from 'payload/utilities'
@@ -25,14 +24,11 @@ export const preview: CollectionRouteHandlerWithID = async ({ id, collection, re
(config) => config.slug === collection.config.slug,
)?.admin?.preview
const token = extractJWT(req)
if (typeof generatePreviewURL === 'function') {
try {
previewURL = await generatePreviewURL(result, {
locale: req.locale,
req,
token,
token: req.user?.token,
})
} catch (err) {
routeError({

View File

@@ -4,22 +4,10 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const restoreVersion: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const restoreVersion: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const result = await restoreVersionOperation({
id,
collection,

View File

@@ -4,24 +4,12 @@ import { isNumber } from 'payload/utilities'
import type { CollectionRouteHandlerWithID } from '../types.js'
import { sanitizeCollectionID } from '../utilities/sanitizeCollectionID.js'
export const updateByID: CollectionRouteHandlerWithID = async ({
id: incomingID,
collection,
req,
}) => {
export const updateByID: CollectionRouteHandlerWithID = async ({ id, collection, req }) => {
const { searchParams } = req
const depth = searchParams.get('depth')
const autosave = searchParams.get('autosave') === 'true'
const draft = searchParams.get('draft') === 'true'
const id = sanitizeCollectionID({
id: incomingID,
collectionSlug: collection.config.slug,
payload: req.payload,
})
const doc = await updateByIDOperation({
id,
autosave,

View File

@@ -1,5 +1,4 @@
import httpStatus from 'http-status'
import { extractJWT } from 'payload/auth'
import { findOneOperation } from 'payload/operations'
import { isNumber } from 'payload/utilities'
@@ -25,14 +24,11 @@ export const preview: GlobalRouteHandler = async ({ globalConfig, req }) => {
(config) => config.slug === globalConfig.slug,
)?.admin?.preview
const token = extractJWT(req)
if (typeof generatePreviewURL === 'function') {
try {
previewURL = await generatePreviewURL(result, {
locale: req.locale,
req,
token,
token: req.user?.token,
})
} catch (err) {
routeError({

View File

@@ -1,23 +0,0 @@
import type { Payload } from 'payload/types'
type Args = {
collectionSlug: string
id: string
payload: Payload
}
export const sanitizeCollectionID = ({ id, collectionSlug, payload }: Args): number | string => {
let sanitizedID: number | string = id
const collection = payload.collections[collectionSlug]
// If default db ID type is a number, we should sanitize
let shouldSanitize = Boolean(payload.db.defaultIDType === 'number')
// UNLESS the customIDType for this collection is text.... then we leave it
if (shouldSanitize && collection.customIDType === 'text') shouldSanitize = false
// If we still should sanitize, parse float
if (shouldSanitize) sanitizedID = parseFloat(sanitizedID)
return sanitizedID
}

View File

@@ -1,13 +1,10 @@
import type { PayloadRequest } from 'payload/types'
import type { SanitizedConfig } from 'payload/types'
import type { FieldSchemaMap } from './types.js'
import { traverseFields } from './traverseFields.js'
export const buildFieldSchemaMap = ({
i18n,
payload: { config },
}: PayloadRequest): FieldSchemaMap => {
export const buildFieldSchemaMap = (config: SanitizedConfig): FieldSchemaMap => {
const result: FieldSchemaMap = new Map()
const validRelationships = config.collections.map((c) => c.slug) || []
@@ -16,7 +13,6 @@ export const buildFieldSchemaMap = ({
traverseFields({
config,
fields: collection.fields,
i18n,
schemaMap: result,
schemaPath: collection.slug,
validRelationships,
@@ -27,7 +23,6 @@ export const buildFieldSchemaMap = ({
traverseFields({
config,
fields: global.fields,
i18n,
schemaMap: result,
schemaPath: global.slug,
validRelationships,

View File

@@ -1,4 +1,3 @@
import type { I18n } from '@payloadcms/translations'
import type { Field, SanitizedConfig } from 'payload/types'
import { tabHasName } from 'payload/types'
@@ -8,7 +7,6 @@ import type { FieldSchemaMap } from './types.js'
type Args = {
config: SanitizedConfig
fields: Field[]
i18n: I18n
schemaMap: FieldSchemaMap
schemaPath: string
validRelationships: string[]
@@ -17,7 +15,6 @@ type Args = {
export const traverseFields = ({
config,
fields,
i18n,
schemaMap,
schemaPath,
validRelationships,
@@ -31,7 +28,6 @@ export const traverseFields = ({
traverseFields({
config,
fields: field.fields,
i18n,
schemaMap,
schemaPath: `${schemaPath}.${field.name}`,
validRelationships,
@@ -43,7 +39,6 @@ export const traverseFields = ({
traverseFields({
config,
fields: field.fields,
i18n,
schemaMap,
schemaPath,
validRelationships,
@@ -59,7 +54,6 @@ export const traverseFields = ({
traverseFields({
config,
fields: block.fields,
i18n,
schemaMap,
schemaPath: blockSchemaPath,
validRelationships,
@@ -71,7 +65,6 @@ export const traverseFields = ({
if (typeof field.editor.generateSchemaMap === 'function') {
field.editor.generateSchemaMap({
config,
i18n,
schemaMap,
schemaPath: `${schemaPath}.${field.name}`,
})
@@ -90,7 +83,6 @@ export const traverseFields = ({
traverseFields({
config,
fields: tab.fields,
i18n,
schemaMap,
schemaPath: tabSchemaPath,
validRelationships,

View File

@@ -6,6 +6,7 @@ import type {
} from 'payload/types'
import { initI18n } from '@payloadcms/translations'
import { translations } from '@payloadcms/translations/api'
import { executeAuthStrategies } from 'payload/auth'
import { parseCookies } from 'payload/auth'
import { getDataLoader } from 'payload/utilities'
@@ -71,10 +72,11 @@ export const createPayloadRequest = async ({
headers: request.headers,
})
const i18n = await initI18n({
const i18n = initI18n({
config: config.i18n,
context: 'api',
language,
translations,
})
const customRequest: CustomPayloadRequest = {

View File

@@ -0,0 +1,22 @@
import type { I18n } from '@payloadcms/translations'
import type { SanitizedConfig } from 'payload/types'
import { initI18n } from '@payloadcms/translations'
import { translations } from '@payloadcms/translations/client'
import { cookies, headers } from 'next/headers.js'
import { getRequestLanguage } from './getRequestLanguage.js'
export const getNextI18n = ({
config,
language,
}: {
config: SanitizedConfig
language?: string
}): I18n =>
initI18n({
config: config.i18n,
context: 'client',
language: language || getRequestLanguage({ config, cookies: cookies(), headers: headers() }),
translations,
})

View File

@@ -1,19 +0,0 @@
import type { I18n } from '@payloadcms/translations'
import type { SanitizedConfig } from 'payload/types'
import { initI18n } from '@payloadcms/translations'
import { cookies, headers } from 'next/headers.js'
import { getRequestLanguage } from './getRequestLanguage.js'
/**
* In the context of NextJS, this function initializes the i18n object for the current request.
*
* It must be called on the server side, and within the lifecycle of a request since it relies on the request headers and cookies.
*/
export const getNextRequestI18n = async ({ config }: { config: SanitizedConfig }): Promise<I18n> =>
initI18n({
config: config.i18n,
context: 'client',
language: getRequestLanguage({ config, cookies: cookies(), headers: headers() }),
})

View File

@@ -35,10 +35,7 @@ export const getPayloadHMR = async (options: InitOptions): Promise<Payload> => {
cached.payload.config = config
cached.payload.collections = config.collections.reduce((collections, collection) => {
collections[collection.slug] = {
config: collection,
customIDType: cached.payload.collections[collection.slug]?.customIDType,
}
collections[collection.slug] = { config: collection }
return collections
}, {})

View File

@@ -1,13 +1,12 @@
import type { AcceptedLanguages } from '@payloadcms/translations'
import type { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies.js'
import type { SanitizedConfig } from 'payload/config'
import { extractHeaderLanguage } from '@payloadcms/translations'
import { matchLanguage } from '@payloadcms/translations'
type GetRequestLanguageArgs = {
config: SanitizedConfig
cookies: Map<string, string> | ReadonlyRequestCookies
defaultLanguage?: AcceptedLanguages
defaultLanguage?: string
headers: Request['headers']
}
@@ -16,23 +15,14 @@ export const getRequestLanguage = ({
cookies,
defaultLanguage = 'en',
headers,
}: GetRequestLanguageArgs): AcceptedLanguages => {
const langCookie = cookies.get(`${config.cookiePrefix || 'payload'}-lng`)
const languageFromCookie = typeof langCookie === 'string' ? langCookie : langCookie?.value
const languageFromHeader = headers.get('Accept-Language')
? extractHeaderLanguage(headers.get('Accept-Language'))
: undefined
const fallbackLang = config?.i18n?.fallbackLanguage || defaultLanguage
}: GetRequestLanguageArgs): string => {
const acceptLanguage = headers.get('Accept-Language')
const cookieLanguage = cookies.get(`${config.cookiePrefix || 'payload'}-lng`)
const supportedLanguageKeys = Object.keys(config?.i18n?.supportedLanguages || {})
const reqLanguage =
(typeof cookieLanguage === 'string' ? cookieLanguage : cookieLanguage?.value) ||
acceptLanguage ||
defaultLanguage
if (languageFromCookie && supportedLanguageKeys.includes(languageFromCookie)) {
return languageFromCookie as AcceptedLanguages
}
if (languageFromHeader && supportedLanguageKeys.includes(languageFromHeader)) {
return languageFromHeader
}
return supportedLanguageKeys.includes(fallbackLang) ? (fallbackLang as AcceptedLanguages) : 'en'
return matchLanguage(reqLanguage)
}

View File

@@ -8,6 +8,7 @@ import type {
} from 'payload/types'
import { initI18n } from '@payloadcms/translations'
import { translations } from '@payloadcms/translations/client'
import { findLocaleFromCode } from '@payloadcms/ui/utilities/findLocaleFromCode'
import { headers as getHeaders } from 'next/headers.js'
import { notFound, redirect } from 'next/navigation.js'
@@ -44,13 +45,14 @@ export const initPage = async ({
const cookies = parseCookies(headers)
const language = getRequestLanguage({ config: payload.config, cookies, headers })
const i18n = await initI18n({
const i18n = initI18n({
config: payload.config.i18n,
context: 'client',
language,
translations,
})
const req = await createLocalReq(
const req = createLocalReq(
{
fallbackLocale: null,
locale: locale.code,

View File

@@ -1,10 +1,9 @@
import type { Field, WithServerSideProps as WithServerSidePropsType } from 'payload/types'
import type { Field } from 'payload/types'
import type { AdminViewProps } from 'payload/types'
import { Form } from '@payloadcms/ui/forms/Form'
import { FormSubmit } from '@payloadcms/ui/forms/Submit'
import { buildStateFromSchema } from '@payloadcms/ui/forms/buildStateFromSchema'
import { WithServerSideProps as WithServerSidePropsGeneric } from '@payloadcms/ui/providers/ComponentMap'
import { mapFields } from '@payloadcms/ui/utilities/buildComponentMap'
import React from 'react'
@@ -17,8 +16,6 @@ export const CreateFirstUserView: React.FC<AdminViewProps> = async ({ initPageRe
const {
req,
req: {
i18n,
payload,
payload: {
config,
config: {
@@ -51,15 +48,9 @@ export const CreateFirstUserView: React.FC<AdminViewProps> = async ({ initPageRe
},
]
const WithServerSideProps: WithServerSidePropsType = ({ Component, ...rest }) => {
return <WithServerSidePropsGeneric Component={Component} payload={payload} {...rest} />
}
const createFirstUserFieldMap = mapFields({
WithServerSideProps,
config,
fieldSchema: fields,
i18n,
parentPath: userSlug,
})

View File

@@ -3,7 +3,7 @@ import type { SanitizedCollectionConfig, SanitizedGlobalConfig } from 'payload/t
import type { GenerateViewMetadata } from '../Root/index.js'
import { getNextRequestI18n } from '../../utilities/getNextRequestI18n.js'
import { getNextI18n } from '../../utilities/getNextI18n.js'
import { generateMetadata as apiMeta } from '../API/meta.js'
import { generateMetadata as editMeta } from '../Edit/meta.js'
import { generateMetadata as livePreviewMeta } from '../LivePreview/meta.js'
@@ -89,7 +89,7 @@ export const getMetaBySegment: GenerateEditViewMetadata = async ({
}
}
const i18n = await getNextRequestI18n({
const i18n = await getNextI18n({
config,
})

View File

@@ -117,10 +117,7 @@ export const ListView: React.FC<AdminViewProps> = async ({ initPageResult, searc
<Fragment>
<HydrateClientUser permissions={permissions} user={user} />
<ListInfoProvider
collectionConfig={createClientCollectionConfig({
collection: collectionConfig,
t: initPageResult.req.i18n.t,
})}
collectionConfig={createClientCollectionConfig(collectionConfig)}
collectionSlug={collectionSlug}
hasCreatePermission={permissions?.collections?.[collectionSlug]?.create?.permission}
newDocumentURL={`${admin}/collections/${collectionSlug}/create`}

View File

@@ -2,11 +2,11 @@ import type { I18n } from '@payloadcms/translations'
import type { Metadata } from 'next'
import type { AdminViewComponent, SanitizedConfig } from 'payload/types'
import { getNextI18n } from '@payloadcms/next/utilities'
import { HydrateClientUser } from '@payloadcms/ui/elements/HydrateClientUser'
import { DefaultTemplate } from '@payloadcms/ui/templates/Default'
import React, { Fragment } from 'react'
import { getNextRequestI18n } from '../../utilities/getNextRequestI18n.js'
import { initPage } from '../../utilities/initPage.js'
import { NotFoundClient } from './index.client.js'
@@ -19,7 +19,7 @@ export const generatePageMetadata = async ({
}): Promise<Metadata> => {
const config = await configPromise
const i18n = await getNextRequestI18n({
const i18n = getNextI18n({
config,
})

View File

@@ -1,7 +1,7 @@
import type { Metadata } from 'next'
import type { SanitizedConfig } from 'payload/types'
import { getNextRequestI18n } from '../../utilities/getNextRequestI18n.js'
import { getNextI18n } from '../../utilities/getNextI18n.js'
import { generateAccountMetadata } from '../Account/index.js'
import { generateCreateFirstUserMetadata } from '../CreateFirstUser/index.js'
import { generateDashboardMetadata } from '../Dashboard/index.js'
@@ -49,7 +49,7 @@ export const generatePageMetadata = async ({ config: configPromise, params }: Ar
const isGlobal = segmentOne === 'globals'
const isCollection = segmentOne === 'collections'
const i18n = await getNextRequestI18n({
const i18n = getNextI18n({
config,
})

View File

@@ -85,9 +85,7 @@ export const SetStepNav: React.FC<{
url: `${adminRoute}/collections/${collectionSlug}/${id}/versions`,
},
{
label: doc?.createdAt
? formatDate({ date: doc.createdAt, i18n, pattern: dateFormat })
: '',
label: doc?.createdAt ? formatDate(doc.createdAt, dateFormat, i18n?.language) : '',
},
]
}
@@ -103,9 +101,7 @@ export const SetStepNav: React.FC<{
url: `${adminRoute}/globals/${globalConfig.slug}/versions`,
},
{
label: doc?.createdAt
? formatDate({ date: doc.createdAt, i18n, pattern: dateFormat })
: '',
label: doc?.createdAt ? formatDate(doc.createdAt, dateFormat, i18n?.language) : '',
},
]
}

View File

@@ -61,7 +61,7 @@ export const DefaultVersionView: React.FC<DefaultVersionsViewProps> = ({
} = config
const formattedCreatedAt = doc?.createdAt
? formatDate({ date: doc.createdAt, i18n, pattern: dateFormat })
? formatDate(doc.createdAt, dateFormat, i18n.language)
: ''
const originalDocFetchURL = `${serverURL}${apiRoute}/${globalSlug ? 'globals/' : ''}${

View File

@@ -88,7 +88,7 @@ export const SelectComparison: React.FC<Props> = (props) => {
setOptions((existingOptions) => [
...existingOptions,
...data.docs.map((doc) => ({
label: formatDate({ date: doc.updatedAt, i18n, pattern: dateFormat }),
label: formatDate(doc.updatedAt, dateFormat, i18n.language),
value: doc.id,
})),
])

View File

@@ -22,7 +22,7 @@ export const generateMetadata: GenerateEditViewMetadata = async ({
const doc: any = {} // TODO: figure this out
const formattedCreatedAt = doc?.createdAt
? formatDate({ date: doc.createdAt, i18n, pattern: config?.admin?.dateFormat })
? formatDate(doc.createdAt, config?.admin?.dateFormat, i18n?.language)
: ''
if (collectionConfig) {

View File

@@ -38,8 +38,7 @@ export const CreatedAtCell: React.FC<CreatedAtCellProps> = ({
return (
<Link href={to}>
{cellData &&
formatDate({ date: cellData as Date | number | string, i18n, pattern: dateFormat })}
{cellData && formatDate(cellData as Date | number | string, dateFormat, i18n.language)}
</Link>
)
}

View File

@@ -101,7 +101,7 @@ export const VersionsView: EditViewComponent = async (props) => {
return (
<React.Fragment>
<SetStepNav
collectionSlug={collectionConfig?.slug}
collectionSlug={collectionConfig?.slug || globalConfig?.slug}
globalSlug={globalConfig?.slug}
id={id}
pluralLabel={collectionConfig?.labels?.plural || globalConfig?.label}

View File

@@ -1,9 +1,5 @@
/**
* @param {import('next').NextConfig} nextConfig
*
* @returns {import('next').NextConfig}
* */
export const withPayload = (nextConfig = {}) => {
/** @type {import('next').NextConfig} */
const withPayload = (nextConfig = {}) => {
return {
...nextConfig,
experimental: {

View File

@@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"composite": true, // Required for references to work
"noEmit": false /* Do not emit outputs. */,
"emitDeclarationOnly": true,
"outDir": "./dist/cjs" /* Specify an output folder for all emitted files. */,
"rootDir": "./src" /* Specify the root folder within your source files. */,
"sourceMap": true
},
"include": ["src/withPayload.js" /* Include the withPayload.js file in the build */]
}

View File

@@ -24,4 +24,3 @@
/node.d.ts
/uploads.js
/uploads.d.ts
/i18n

View File

@@ -1,6 +1,6 @@
{
"name": "payload",
"version": "3.0.0-beta.4",
"version": "3.0.0-alpha.60",
"description": "Node, React and MongoDB Headless CMS and Application Framework",
"license": "MIT",
"main": "./src/index.ts",

View File

@@ -1,10 +1,8 @@
import type { I18n } from '@payloadcms/translations'
import type { JSONSchema4 } from 'json-schema'
import type { SanitizedConfig } from '../config/types.js'
import type { Field, RichTextField, Validate } from '../fields/config/types.js'
import type { PayloadRequest, RequestContext } from '../types/index.js'
import type { WithServerSideProps } from './elements/WithServerSideProps.js'
export type RichTextFieldProps<
Value extends object,
@@ -29,14 +27,11 @@ type RichTextAdapterBase<
siblingDoc: Record<string, unknown>
}) => Promise<void> | null
generateComponentMap: (args: {
WithServerSideProps: WithServerSideProps
config: SanitizedConfig
i18n: I18n
schemaPath: string
}) => Map<string, React.ReactNode>
generateSchemaMap?: (args: {
config: SanitizedConfig
i18n: I18n
schemaMap: Map<string, Field[]>
schemaPath: string
}) => Map<string, Field[]>

View File

@@ -1,3 +1 @@
import type { CustomComponent } from '../../config/types.js'
export type CustomPreviewButton = CustomComponent
export type CustomPreviewButton = React.ComponentType

View File

@@ -1,3 +1 @@
import type { CustomComponent } from '../../config/types.js'
export type CustomPublishButton = CustomComponent
export type CustomPublishButton = React.ComponentType

View File

@@ -1,3 +1 @@
import type { CustomComponent } from '../../config/types.js'
export type CustomSaveButton = CustomComponent
export type CustomSaveButton = React.ComponentType

View File

@@ -1,3 +1 @@
import type { CustomComponent } from '../../config/types.js'
export type CustomSaveDraftButton = CustomComponent
export type CustomSaveDraftButton = React.ComponentType

View File

@@ -1,4 +0,0 @@
export type WithServerSideProps = (args: {
[key: string]: any
Component: React.ComponentType<any>
}) => React.ReactNode

View File

@@ -1,11 +1,8 @@
import type React from 'react'
import type { CustomComponent, LabelFunction } from '../../config/types.js'
import type { Payload } from '../../index.js'
export type DescriptionFunction = () => string
export type DescriptionFunction = LabelFunction
export type DescriptionComponent = CustomComponent<FieldDescriptionProps>
export type DescriptionComponent = React.ComponentType<FieldDescriptionProps>
export type Description =
| DescriptionComponent
@@ -18,5 +15,4 @@ export type FieldDescriptionProps = {
className?: string
description?: Record<string, string> | string
marginPlacement?: 'bottom' | 'top'
payload?: Payload
}

View File

@@ -1,10 +1,8 @@
import type { LabelFunction } from '../../config/types.js'
export type LabelProps = {
CustomLabel?: React.ReactNode
as?: 'label' | 'span'
htmlFor?: string
label?: LabelFunction | Record<string, string> | false | string
label?: Record<string, string> | false | string
required?: boolean
unstyled?: boolean
}

View File

@@ -1,5 +1,3 @@
import type { CustomComponent } from '../../config/types.js'
export type RowLabelComponent = CustomComponent
export type RowLabelComponent = React.ComponentType
export type RowLabel = Record<string, string> | RowLabelComponent | string

View File

@@ -13,7 +13,6 @@ export type {
DocumentTabConfig,
DocumentTabProps,
} from './elements/Tab.js'
export type { WithServerSideProps } from './elements/WithServerSideProps.js'
export type { ErrorProps } from './forms/Error.js'
export type {
Description,

View File

@@ -1,4 +1,4 @@
import type { SupportedLanguages } from '@payloadcms/translations'
import type { Translations } from '@payloadcms/translations'
import type { Permissions } from '../../auth/index.js'
import type { SanitizedCollectionConfig } from '../../collections/config/types.js'
@@ -43,7 +43,7 @@ export type InitPageResult = {
locale: Locale
permissions: Permissions
req: PayloadRequest
translations: SupportedLanguages
translations: Translations
visibleEntities: VisibleEntities
}

View File

@@ -2,12 +2,15 @@ import crypto from 'crypto'
import type { Field, FieldHook } from '../../fields/config/types.js'
import { extractTranslations } from '../../translations/extractTranslations.js'
const labels = extractTranslations(['authentication:enableAPIKey', 'authentication:apiKey'])
const encryptKey: FieldHook = ({ req, value }) =>
value ? req.payload.encrypt(value as string) : null
const decryptKey: FieldHook = ({ req, value }) =>
value ? req.payload.decrypt(value as string) : undefined
// eslint-disable-next-line no-restricted-exports
export default [
{
name: 'enableAPIKey',
@@ -18,7 +21,7 @@ export default [
},
},
defaultValue: false,
label: ({ t }) => t('authentication:enableAPIKey'),
label: labels['authentication:enableAPIKey'],
},
{
name: 'apiKey',
@@ -32,7 +35,7 @@ export default [
afterRead: [decryptKey],
beforeChange: [encryptKey],
},
label: ({ t }) => t('authentication:apiKey'),
label: labels['authentication:apiKey'],
},
{
name: 'apiKeyIndex',

View File

@@ -1,6 +1,9 @@
import type { Field } from '../../fields/config/types.js'
import { email } from '../../fields/validations.js'
import { extractTranslations } from '../../translations/extractTranslations.js'
const labels = extractTranslations(['general:email'])
const baseAuthFields: Field[] = [
{
@@ -11,7 +14,7 @@ const baseAuthFields: Field[] = [
Field: () => null,
},
},
label: ({ t }) => t('general:email'),
label: labels['general:email'],
required: true,
unique: true,
validate: email,

View File

@@ -1,5 +1,9 @@
import type { Field, FieldHook } from '../../fields/config/types.js'
import { extractTranslations } from '../../translations/extractTranslations.js'
const labels = extractTranslations(['authentication:verified'])
const autoRemoveVerificationToken: FieldHook = ({ data, operation, originalDoc, value }) => {
// If a user manually sets `_verified` to true,
// and it was `false`, set _verificationToken to `null`.
@@ -29,7 +33,7 @@ export default [
Field: () => null,
},
},
label: ({ t }) => t('authentication:verified'),
label: labels['authentication:verified'],
},
{
name: '_verificationToken',

View File

@@ -1,5 +1,9 @@
import type { CollectionConfig } from '../collections/config/types.js'
import { extractTranslations } from '../translations/extractTranslations.js'
const labels = extractTranslations(['general:user', 'general:users'])
export const defaultUserCollection: CollectionConfig = {
slug: 'users',
admin: {
@@ -10,7 +14,7 @@ export const defaultUserCollection: CollectionConfig = {
},
fields: [],
labels: {
plural: ({ t }) => t('general:users'),
singular: ({ t }) => t('general:user'),
plural: labels['general:users'],
singular: labels['general:user'],
},
}

View File

@@ -1,9 +1,8 @@
import type { GeneratedTypes } from '../index.js'
import type { AuthStrategyFunctionArgs, User } from './index.js'
export const executeAuthStrategies = async (
args: AuthStrategyFunctionArgs,
): Promise<GeneratedTypes['user'] | null> => {
): Promise<User | null> => {
return args.payload.authStrategies.reduce(async (accumulatorPromise, strategy) => {
const authUser = await accumulatorPromise
if (!authUser) {

View File

@@ -1,7 +1,6 @@
/* eslint-disable no-param-reassign */
import type { CollectionConfig } from '../collections/config/types.js'
import type { Field, TabAsField } from '../fields/config/types.js'
import type { PayloadRequest } from '../types/index.js'
import type { User } from './index.js'
import { fieldAffectsData, tabHasName } from '../fields/config/types.js'
@@ -106,7 +105,7 @@ const traverseFields = ({
export const getFieldsToSign = (args: {
collectionConfig: CollectionConfig
email: string
user: PayloadRequest['user']
user: User
}): Record<string, unknown> => {
const { collectionConfig, email, user } = args

View File

@@ -1,4 +1,3 @@
import type { GeneratedTypes } from '../../index.js'
import type { PayloadRequest } from '../../types/index.js'
import type { Permissions, User } from '../types.js'
@@ -11,16 +10,16 @@ import { getAccessResults } from '../getAccessResults.js'
export type AuthArgs = {
headers: Request['headers']
req?: Omit<PayloadRequest, 'user'>
req: Omit<PayloadRequest, 'user'>
}
export type AuthResult = {
cookies: Map<string, string>
permissions: Permissions
user: GeneratedTypes['user'] | null
user: User | null
}
export const auth = async (args: Required<AuthArgs>): Promise<AuthResult> => {
export const auth = async (args: AuthArgs): Promise<AuthResult> => {
const { headers } = args
const req = args.req as PayloadRequest
const { payload } = req

View File

@@ -10,6 +10,6 @@ export const auth = async (payload: Payload, options: AuthArgs): Promise<AuthRes
return await authOperation({
headers,
req: await createLocalReq({ req: options.req as PayloadRequest }, payload),
req: createLocalReq({ req: options.req as PayloadRequest }, payload),
})
}

View File

@@ -26,11 +26,6 @@ type ResolveFn = (...args: Required<ResolveArgs>) => Promise<ResolveResult>
const locatedConfig = getTsconfig()
const tsconfig = locatedConfig.config.compilerOptions as unknown as ts.CompilerOptions
// Ensure baseUrl is set in order to support paths
if (!tsconfig.baseUrl) {
tsconfig.baseUrl = '.'
}
// Don't resolve d.ts files, because we aren't type-checking
tsconfig.noDtsResolution = true
tsconfig.module = ts.ModuleKind.ESNext
@@ -83,6 +78,7 @@ export const resolve: ResolveFn = async (specifier, context, nextResolve) => {
// and keep going
let nextResult: ResolveResult
// First, try to
if (!isTS) {
try {
nextResult = await nextResolve(specifier, context, nextResolve)

View File

@@ -23,22 +23,14 @@ export type ClientCollectionConfig = Omit<
fields: ClientFieldConfig[]
}
import type { TFunction } from '@payloadcms/translations'
import type { ClientFieldConfig } from '../../fields/config/client.js'
import type { SanitizedCollectionConfig } from './types.js'
import { createClientFieldConfigs } from '../../fields/config/client.js'
export const createClientCollectionConfig = ({
collection,
t,
}: {
collection: SanitizedCollectionConfig
t: TFunction
}) => {
export const createClientCollectionConfig = (collection: SanitizedCollectionConfig) => {
const sanitized = { ...collection }
sanitized.fields = createClientFieldConfigs({ fields: sanitized.fields, t })
sanitized.fields = createClientFieldConfigs(sanitized.fields)
const serverOnlyCollectionProperties: Partial<ServerOnlyCollectionProperties>[] = [
'hooks',
@@ -68,14 +60,6 @@ export const createClientCollectionConfig = ({
delete sanitized.auth.verify
}
if (sanitized.labels) {
Object.entries(sanitized.labels).forEach(([labelType, collectionLabel]) => {
if (typeof collectionLabel === 'function') {
sanitized.labels[labelType] = collectionLabel({ t })
}
})
}
if ('admin' in sanitized) {
sanitized.admin = { ...sanitized.admin }
@@ -101,11 +85,7 @@ export const createClientCollectionConfig = ({
return sanitized
}
export const createClientCollectionConfigs = ({
collections,
t,
}: {
collections: SanitizedCollectionConfig[]
t: TFunction
}): ClientCollectionConfig[] =>
collections.map((collection) => createClientCollectionConfig({ collection, t }))
export const createClientCollectionConfigs = (
collections: SanitizedCollectionConfig[],
): ClientCollectionConfig[] =>
collections.map((collection) => createClientCollectionConfig(collection))

View File

@@ -11,12 +11,15 @@ import TimestampsRequired from '../../errors/TimestampsRequired.js'
import { sanitizeFields } from '../../fields/config/sanitize.js'
import { fieldAffectsData } from '../../fields/config/types.js'
import mergeBaseFields from '../../fields/mergeBaseFields.js'
import { extractTranslations } from '../../translations/extractTranslations.js'
import { getBaseUploadFields } from '../../uploads/getBaseFields.js'
import { formatLabels } from '../../utilities/formatLabels.js'
import { isPlainObject } from '../../utilities/isPlainObject.js'
import baseVersionFields from '../../versions/baseFields.js'
import { authDefaults, defaults } from './defaults.js'
const translations = extractTranslations(['general:createdAt', 'general:updatedAt'])
const sanitizeCollection = (
config: Config,
collection: CollectionConfig,
@@ -48,7 +51,7 @@ const sanitizeCollection = (
disableBulkEdit: true,
hidden: true,
},
label: ({ t }) => t('general:updatedAt'),
label: translations['general:updatedAt'],
})
}
if (!hasCreatedAt) {
@@ -61,7 +64,7 @@ const sanitizeCollection = (
// The default sort for list view is createdAt. Thus, enabling indexing by default, is a major performance improvement, especially for large or a large amount of collections.
type: 'date',
index: true,
label: ({ t }) => t('general:createdAt'),
label: translations['general:createdAt'],
})
}
}

View File

@@ -140,10 +140,10 @@ const collectionSchema = joi.object().keys({
labels: joi.object({
plural: joi
.alternatives()
.try(joi.func(), joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
.try(joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
singular: joi
.alternatives()
.try(joi.func(), joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
.try(joi.string(), joi.object().pattern(joi.string(), [joi.string()])),
}),
timestamps: joi.boolean(),
typescript: joi.object().keys({

View File

@@ -10,12 +10,10 @@ import type {
import type { Auth, ClientUser, IncomingAuthType } from '../../auth/types.js'
import type {
Access,
CustomComponent,
EditConfig,
Endpoint,
EntityDescription,
GeneratePreviewURL,
LabelFunction,
LivePreviewConfig,
} from '../../config/types.js'
import type { Field } from '../../fields/config/types.js'
@@ -202,10 +200,10 @@ export type CollectionAdminOptions = {
* Custom admin components
*/
components?: {
AfterList?: CustomComponent[]
AfterListTable?: CustomComponent[]
BeforeList?: CustomComponent[]
BeforeListTable?: CustomComponent[]
AfterList?: React.ComponentType<any>[]
AfterListTable?: React.ComponentType<any>[]
BeforeList?: React.ComponentType<any>[]
BeforeListTable?: React.ComponentType<any>[]
/**
* Components within the edit view
*/
@@ -240,7 +238,7 @@ export type CollectionAdminOptions = {
List?:
| {
Component?: React.ComponentType<any>
actions?: CustomComponent[]
actions?: React.ComponentType<any>[]
}
| React.ComponentType<any>
}
@@ -362,8 +360,8 @@ export type CollectionConfig = {
* Label configuration
*/
labels?: {
plural?: LabelFunction | Record<string, string> | string
singular?: LabelFunction | Record<string, string> | string
plural?: Record<string, string> | string
singular?: Record<string, string> | string
}
slug: string
/**
@@ -409,7 +407,6 @@ export interface SanitizedCollectionConfig
export type Collection = {
config: SanitizedCollectionConfig
customIDType?: 'number' | 'text'
graphQL?: {
JWT: GraphQLObjectType
mutationInputType: GraphQLNonNull<any>

View File

@@ -5,6 +5,8 @@ import DataLoader from 'dataloader'
import type { PayloadRequest } from '../types/index.js'
import type { TypeWithID } from './config/types.js'
import { fieldAffectsData } from '../fields/config/types.js'
import { getIDType } from '../utilities/getIDType.js'
import { isValidID } from '../utilities/isValidID.js'
// Payload uses `dataloader` to solve the classic GraphQL N+1 problem.
@@ -69,13 +71,15 @@ const batchAndLoadDocs =
const batchKey = JSON.stringify(batchKeyArray)
const idType = payload.collections?.[collection].customIDType || payload.db.defaultIDType
const idField = payload.collections?.[collection].config.fields.find(
(field) => fieldAffectsData(field) && field.name === 'id',
)
let sanitizedID: number | string = id
if (idType === 'number') sanitizedID = parseFloat(id)
if (idField?.type === 'number') sanitizedID = parseFloat(id)
if (isValidID(sanitizedID, idType)) {
if (isValidID(sanitizedID, getIDType(idField, payload?.db?.defaultIDType))) {
return {
...batches,
[batchKey]: [...(batches[batchKey] || []), sanitizedID],

View File

@@ -22,6 +22,7 @@ import { generateFileData } from '../../uploads/generateFileData.js'
import { unlinkTempFiles } from '../../uploads/unlinkTempFiles.js'
import { uploadFiles } from '../../uploads/uploadFiles.js'
import { commitTransaction } from '../../utilities/commitTransaction.js'
import flattenFields from '../../utilities/flattenTopLevelFields.js'
import { initTransaction } from '../../utilities/initTransaction.js'
import { killTransaction } from '../../utilities/killTransaction.js'
import sanitizeInternalFields from '../../utilities/sanitizeInternalFields.js'
@@ -105,8 +106,11 @@ export const createOperation = async <TSlug extends keyof GeneratedTypes['collec
// /////////////////////////////////////
// Custom id
// /////////////////////////////////////
// @todo: Refactor code to store 'customId' on the collection configuration itself so we don't need to repeat flattenFields
const hasIdField =
flattenFields(collectionConfig.fields).findIndex((field) => field.name === 'id') > -1
if (payload.collections[collectionConfig.slug].customIDType) {
if (hasIdField) {
data = {
_id: data.id,
...data,

View File

@@ -34,7 +34,6 @@ export type Options<TSlug extends keyof GeneratedTypes['collections']> = {
user?: Document
}
// eslint-disable-next-line no-restricted-exports
export default async function createLocal<TSlug extends keyof GeneratedTypes['collections']>(
payload: Payload,
options: Options<TSlug>,
@@ -59,7 +58,7 @@ export default async function createLocal<TSlug extends keyof GeneratedTypes['co
)
}
const req = await createLocalReq(options, payload)
const req = createLocalReq(options, payload)
req.file = file ?? (await getFileByPath(filePath))
return createOperation<TSlug>({

View File

@@ -50,7 +50,7 @@ export async function duplicate<TSlug extends keyof GeneratedTypes['collections'
)
}
const req = await createLocalReq(options, payload)
const req = createLocalReq(options, payload)
return duplicateOperation<TSlug>({
id,

View File

@@ -1,5 +1,3 @@
import type { TFunction } from '@payloadcms/translations'
import type { ClientCollectionConfig } from '../collections/config/client.js'
import type { SanitizedCollectionConfig } from '../collections/config/types.js'
import type { ClientGlobalConfig } from '../globals/config/client.js'
@@ -43,13 +41,10 @@ export type ClientConfig = Omit<
globals: ClientGlobalConfig[]
}
export const createClientConfig = async ({
config,
t,
}: {
config: SanitizedConfig
t: TFunction
}): Promise<ClientConfig> => {
export const createClientConfig = async (
configPromise: Promise<SanitizedConfig> | SanitizedConfig,
): Promise<ClientConfig> => {
const config = await configPromise
const clientConfig: ClientConfig = { ...config }
const serverOnlyConfigProperties: Partial<ServerOnlyRootProperties>[] = [
@@ -100,15 +95,11 @@ export const createClientConfig = async ({
}
}
clientConfig.collections = createClientCollectionConfigs({
collections: clientConfig.collections as SanitizedCollectionConfig[],
t,
})
clientConfig.collections = createClientCollectionConfigs(
clientConfig.collections as SanitizedCollectionConfig[],
)
clientConfig.globals = createClientGlobalConfigs({
globals: clientConfig.globals as SanitizedGlobalConfig[],
t,
})
clientConfig.globals = createClientGlobalConfigs(clientConfig.globals as SanitizedGlobalConfig[])
return clientConfig
}

View File

@@ -1,4 +1,4 @@
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import merge from 'deepmerge'
import type {
@@ -87,10 +87,8 @@ export const sanitizeConfig = (incomingConfig: Config): SanitizedConfig => {
config.i18n = {
fallbackLanguage: 'en',
supportedLanguages: {
en,
},
translations: {},
supportedLanguages: Object.keys(translations),
translations,
...(incomingConfig?.i18n ?? {}),
}

View File

@@ -1,4 +1,4 @@
import type { I18nOptions, TFunction } from '@payloadcms/translations'
import type { I18nOptions } from '@payloadcms/translations'
import type { Options as ExpressFileUploadOptions } from 'express-fileupload'
import type GraphQL from 'graphql'
import type { Transporter } from 'nodemailer'
@@ -76,8 +76,7 @@ export type ServerOnlyLivePreviewProperties = keyof Pick<LivePreviewConfig, 'url
type GeneratePreviewURLOptions = {
locale: string
req: PayloadRequest
token: null | string
token: string
}
export type GeneratePreviewURL = (
@@ -280,7 +279,7 @@ export type EditViewConfig =
path: string
}
| {
actions?: CustomComponent[]
actions?: React.ComponentType<any>[]
}
/**
@@ -292,14 +291,6 @@ export type EditViewConfig =
*/
export type EditView = EditViewComponent | EditViewConfig
export type ServerProps = {
payload: Payload
}
export const serverProps: (keyof ServerProps)[] = ['payload']
export type CustomComponent<T extends any = any> = React.ComponentType<T & ServerProps>
export type Locale = {
/**
* value of supported locale
@@ -372,8 +363,6 @@ export type LocalizationConfig = Prettify<
LocalizationConfigWithLabels | LocalizationConfigWithNoLabels
>
export type LabelFunction = ({ t }: { t: TFunction }) => string
export type SharpDependency = (
input?:
| ArrayBuffer
@@ -429,46 +418,46 @@ export type Config = {
/**
* Replace the navigation with a custom component
*/
Nav?: CustomComponent
Nav?: React.ComponentType<any>
/**
* Add custom components to the top right of the Admin Panel
*/
actions?: CustomComponent[]
actions?: React.ComponentType<any>[]
/**
* Add custom components after the collection overview
*/
afterDashboard?: CustomComponent[]
afterDashboard?: React.ComponentType<any>[]
/**
* Add custom components after the email/password field
*/
afterLogin?: CustomComponent[]
afterLogin?: React.ComponentType<any>[]
/**
* Add custom components after the navigation links
*/
afterNavLinks?: CustomComponent[]
afterNavLinks?: React.ComponentType<any>[]
/**
* Add custom components before the collection overview
*/
beforeDashboard?: CustomComponent[]
beforeDashboard?: React.ComponentType<any>[]
/**
* Add custom components before the email/password field
*/
beforeLogin?: CustomComponent[]
beforeLogin?: React.ComponentType<any>[]
/**
* Add custom components before the navigation links
*/
beforeNavLinks?: CustomComponent[]
beforeNavLinks?: React.ComponentType<any>[]
/** Replace graphical components */
graphics?: {
/** Replace the icon in the navigation */
Icon?: CustomComponent
Icon?: React.ComponentType<any>
/** Replace the logo on the login page */
Logo?: CustomComponent
Logo?: React.ComponentType<any>
}
/** Replace logout related components */
logout?: {
/** Replace the logout button */
Button?: CustomComponent
Button?: React.ComponentType<any>
}
/**
* Wrap the admin dashboard in custom context providers
@@ -682,12 +671,11 @@ export type Config = {
export type SanitizedConfig = Omit<
DeepRequired<Config>,
'collections' | 'endpoint' | 'globals' | 'i18n' | 'localization'
'collections' | 'endpoint' | 'globals' | 'localization'
> & {
collections: SanitizedCollectionConfig[]
endpoints: Endpoint[]
globals: SanitizedGlobalConfig[]
i18n: Required<I18nOptions>
localization: SanitizedLocalizationConfig | false
paths: {
config: string
@@ -725,7 +713,7 @@ export type EditConfig =
)
| EditViewComponent
export type EntityDescriptionComponent = CustomComponent
export type EntityDescriptionComponent = React.ComponentType<any>
export type EntityDescriptionFunction = () => string

View File

@@ -1,6 +1,6 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
@@ -8,7 +8,7 @@ import APIError from './APIError.js'
class AuthenticationError extends APIError {
constructor(t?: TFunction) {
super(
t ? t('error:emailOrPasswordIncorrect') : en.translations.error.emailOrPasswordIncorrect,
t ? t('error:emailOrPasswordIncorrect') : translations.en.error.emailOrPasswordIncorrect,
httpStatus.UNAUTHORIZED,
)
}

View File

@@ -1,6 +1,6 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
@@ -8,7 +8,7 @@ import APIError from './APIError.js'
class ErrorDeletingFile extends APIError {
constructor(t?: TFunction) {
super(
t ? t('error:deletingFile') : en.translations.error.deletingFile,
t ? t('error:deletingFile') : translations.en.error.deletingFile,
httpStatus.INTERNAL_SERVER_ERROR,
)
}

View File

@@ -1,6 +1,6 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
@@ -8,7 +8,7 @@ import APIError from './APIError.js'
class FileUploadError extends APIError {
constructor(t?: TFunction) {
super(
t ? t('error:problemUploadingFile') : en.translations.error.problemUploadingFile,
t ? t('error:problemUploadingFile') : translations.en.error.problemUploadingFile,
httpStatus.BAD_REQUEST,
)
}

View File

@@ -1,6 +1,6 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
@@ -8,7 +8,7 @@ import APIError from './APIError.js'
class Forbidden extends APIError {
constructor(t?: TFunction) {
super(
t ? t('error:notAllowedToPerformAction') : en.translations.error.notAllowedToPerformAction,
t ? t('error:notAllowedToPerformAction') : translations.en.error.notAllowedToPerformAction,
httpStatus.FORBIDDEN,
)
}

View File

@@ -1,13 +1,13 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
class LockedAuth extends APIError {
constructor(t?: TFunction) {
super(t ? t('error:userLocked') : en.translations.error.userLocked, httpStatus.UNAUTHORIZED)
super(t ? t('error:userLocked') : translations.en.error.userLocked, httpStatus.UNAUTHORIZED)
}
}

View File

@@ -1,6 +1,6 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
@@ -8,7 +8,7 @@ import APIError from './APIError.js'
class MissingFile extends APIError {
constructor(t?: TFunction) {
super(
t ? t('error:noFilesUploaded') : en.translations.error.noFilesUploaded,
t ? t('error:noFilesUploaded') : translations.en.error.noFilesUploaded,
httpStatus.BAD_REQUEST,
)
}

View File

@@ -1,13 +1,13 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
class NotFound extends APIError {
constructor(t?: TFunction) {
super(t ? t('general:notFound') : en.translations.general.notFound, httpStatus.NOT_FOUND)
super(t ? t('general:notFound') : translations.en.general.notFound, httpStatus.NOT_FOUND)
}
}

View File

@@ -1,13 +1,13 @@
import type { TFunction } from '@payloadcms/translations'
import { en } from '@payloadcms/translations/languages/en'
import { translations } from '@payloadcms/translations/api'
import httpStatus from 'http-status'
import APIError from './APIError.js'
class UnauthorizedError extends APIError {
constructor(t?: TFunction) {
super(t ? t('error:unauthorized') : en.translations.error.unauthorized, httpStatus.UNAUTHORIZED)
super(t ? t('error:unauthorized') : translations.en.error.unauthorized, httpStatus.UNAUTHORIZED)
}
}

Some files were not shown because too many files have changed in this diff Show More