create-payload-app 4.0.0-internal.38b7f1d → 4.0.0-internal.4804abd

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.
Files changed (52) hide show
  1. package/dist/lib/ast/payload-config.js +1 -1
  2. package/dist/lib/ast/payload-config.js.map +1 -1
  3. package/dist/lib/ast/types.d.ts +1 -1
  4. package/dist/lib/ast/types.d.ts.map +1 -1
  5. package/dist/lib/ast/types.js.map +1 -1
  6. package/dist/lib/configure-plugin-project.d.ts.map +1 -1
  7. package/dist/lib/configure-pnpm-builds.d.ts +20 -0
  8. package/dist/lib/configure-pnpm-builds.d.ts.map +1 -0
  9. package/dist/lib/configure-pnpm-builds.js +100 -0
  10. package/dist/lib/configure-pnpm-builds.js.map +1 -0
  11. package/dist/lib/create-project.d.ts.map +1 -1
  12. package/dist/lib/create-project.js +13 -50
  13. package/dist/lib/create-project.js.map +1 -1
  14. package/dist/lib/init-next.d.ts +1 -1
  15. package/dist/lib/init-next.d.ts.map +1 -1
  16. package/dist/lib/init-next.js +20 -4
  17. package/dist/lib/init-next.js.map +1 -1
  18. package/dist/lib/update-payload-in-project.d.ts +1 -1
  19. package/dist/lib/update-payload-in-project.d.ts.map +1 -1
  20. package/dist/lib/update-payload-in-project.js +6 -5
  21. package/dist/lib/update-payload-in-project.js.map +1 -1
  22. package/dist/lib/wrap-next-config.d.ts.map +1 -1
  23. package/dist/main.d.ts.map +1 -1
  24. package/dist/main.js +6 -5
  25. package/dist/main.js.map +1 -1
  26. package/dist/template/src/app/(frontend)/page.tsx +5 -2
  27. package/dist/template/src/app/(payload)/admin/importMap.js +15 -2
  28. package/dist/template/src/collections/Folders.ts +16 -0
  29. package/dist/template/src/collections/Media.ts +4 -0
  30. package/dist/template/src/collections/Tags.ts +16 -0
  31. package/dist/template/src/collections/Users.ts +1 -0
  32. package/dist/template/src/payload-types.ts +63 -9
  33. package/dist/template/src/payload.config.ts +10 -2
  34. package/dist/types.d.ts +1 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/types.js.map +1 -1
  37. package/dist/utils/casing.d.ts.map +1 -1
  38. package/dist/utils/log.d.ts.map +1 -1
  39. package/dist/utils/messages.d.ts.map +1 -1
  40. package/dist/utils/messages.js +1 -0
  41. package/dist/utils/messages.js.map +1 -1
  42. package/dist/utils/resolvePackageVersion.d.ts +29 -0
  43. package/dist/utils/resolvePackageVersion.d.ts.map +1 -0
  44. package/dist/utils/resolvePackageVersion.js +41 -0
  45. package/dist/utils/resolvePackageVersion.js.map +1 -0
  46. package/dist/utils/resolvePackageVersion.spec.js +77 -0
  47. package/dist/utils/resolvePackageVersion.spec.js.map +1 -0
  48. package/package.json +2 -2
  49. package/dist/utils/getLatestPackageVersion.d.ts +0 -17
  50. package/dist/utils/getLatestPackageVersion.d.ts.map +0 -1
  51. package/dist/utils/getLatestPackageVersion.js +0 -20
  52. package/dist/utils/getLatestPackageVersion.js.map +0 -1
@@ -107,7 +107,7 @@ export function detectPayloadConfigStructure(sourceFile) {
107
107
  },
108
108
  importSources: {
109
109
  dbAdapter: dbAdapterImportInfo,
110
- storageAdapters: storageAdapterImports.length > 0 ? storageAdapterImports : undefined
110
+ storage: storageAdapterImports.length > 0 ? storageAdapterImports : undefined
111
111
  },
112
112
  sourceFile,
113
113
  structures: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/ast/payload-config.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport path from 'path'\nimport { Project, QuoteKind, type SourceFile, SyntaxKind } from 'ts-morph'\n\nimport type {\n ConfigureOptions,\n DatabaseAdapter,\n DetectionResult,\n Modification,\n StorageAdapter,\n TransformationResult,\n WriteOptions,\n WriteResult,\n} from './types.js'\n\nimport { debug } from '../../utils/log.js'\nimport { DB_ADAPTER_CONFIG, STORAGE_ADAPTER_CONFIG } from './adapter-config.js'\nimport {\n addImportDeclaration,\n cleanupOrphanedImports,\n formatError,\n removeImportDeclaration,\n} from './utils.js'\n\nexport function detectPayloadConfigStructure(sourceFile: SourceFile): DetectionResult {\n debug(`[AST] Detecting payload config structure in ${sourceFile.getFilePath()}`)\n\n // First find the actual name being used (might be aliased)\n const payloadImport = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n const buildConfigImportSpec = payloadImport\n ?.getNamedImports()\n .find((spec) => spec.getName() === 'buildConfig')\n\n const aliasNode = buildConfigImportSpec?.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n\n debug(`[AST] Looking for function call: ${buildConfigName}`)\n\n // Find buildConfig call expression (using actual name in code)\n const buildConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((call) => {\n const expression = call.getExpression()\n return expression.getText() === buildConfigName\n })\n\n if (!buildConfigCall) {\n debug(`[AST] ✗ ${buildConfigName} call not found`)\n return {\n error: formatError({\n actual: `No ${buildConfigName} call found in file`,\n context: 'buildConfig call',\n expected: `export default ${buildConfigName}({ ... })`,\n technicalDetails: `Could not find CallExpression with identifier \"${buildConfigName}\"`,\n }),\n success: false,\n }\n }\n\n debug(`[AST] ✓ ${buildConfigName} call found`)\n\n // Get import statements\n const importStatements = sourceFile.getImportDeclarations()\n debug(`[AST] Found ${importStatements.length} import statements`)\n\n // Find db property if it exists\n const configObject = buildConfigCall.getArguments()[0]\n let dbProperty\n if (configObject && configObject.getKind() === SyntaxKind.ObjectLiteralExpression) {\n dbProperty = configObject\n .asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n .getProperty('db')\n ?.asKind(SyntaxKind.PropertyAssignment)\n }\n\n debug(`[AST] db property: ${dbProperty ? '✓ found' : '✗ not found'}`)\n\n // Find plugins array if it exists\n let pluginsArray\n if (configObject && configObject.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n const pluginsProperty = objLiteral.getProperty('plugins')\n\n // Handle PropertyAssignment (e.g., plugins: [...])\n const propertyAssignment = pluginsProperty?.asKind(SyntaxKind.PropertyAssignment)\n if (propertyAssignment) {\n const initializer = propertyAssignment.getInitializer()\n if (initializer?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n pluginsArray = initializer.asKind(SyntaxKind.ArrayLiteralExpression)\n }\n }\n // For ShorthandPropertyAssignment (e.g., plugins), we can't get the array directly\n // but we'll detect it in addStorageAdapter\n }\n\n debug(`[AST] plugins array: ${pluginsArray ? '✓ found' : '✗ not found'}`)\n\n // Find all buildConfig calls for edge case detection (using actual name)\n const allBuildConfigCalls = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((call) => {\n const expression = call.getExpression()\n return expression.getText() === buildConfigName\n })\n\n const hasImportAlias = !!aliasNode\n\n // Check for other Payload imports\n const payloadImports = payloadImport?.getNamedImports() || []\n const hasOtherPayloadImports =\n payloadImports.length > 1 || payloadImports.some((imp) => imp.getName() !== 'buildConfig')\n\n // Track database adapter imports\n let dbAdapterImportInfo\n for (const [, config] of Object.entries(DB_ADAPTER_CONFIG)) {\n const importDecl = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === config.packageName)\n\n if (importDecl) {\n const namedImports = importDecl.getNamedImports()\n dbAdapterImportInfo = {\n hasOtherImports: namedImports.length > 1,\n importDeclaration: importDecl,\n packageName: config.packageName,\n }\n break\n }\n }\n\n // Track storage adapter imports\n const storageAdapterImports = []\n for (const [, config] of Object.entries(STORAGE_ADAPTER_CONFIG)) {\n if (!config.packageName || !config.adapterName) {\n continue\n }\n\n const importDecl = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === config.packageName)\n\n if (importDecl) {\n const namedImports = importDecl.getNamedImports()\n storageAdapterImports.push({\n hasOtherImports: namedImports.length > 1,\n importDeclaration: importDecl,\n packageName: config.packageName,\n })\n }\n }\n\n const needsManualIntervention = hasImportAlias || allBuildConfigCalls.length > 2\n\n debug(\n `[AST] Edge cases: alias=${hasImportAlias}, multiple=${allBuildConfigCalls.length > 1}, otherImports=${hasOtherPayloadImports}, manual=${needsManualIntervention}`,\n )\n\n return {\n edgeCases: {\n hasImportAlias,\n hasOtherPayloadImports,\n multipleBuildConfigCalls: allBuildConfigCalls.length > 1,\n needsManualIntervention,\n },\n importSources: {\n dbAdapter: dbAdapterImportInfo,\n storageAdapters: storageAdapterImports.length > 0 ? storageAdapterImports : undefined,\n },\n sourceFile,\n structures: {\n buildConfigCall,\n dbProperty,\n importStatements,\n pluginsArray,\n },\n success: true,\n }\n}\n\nexport function addDatabaseAdapter({\n adapter,\n envVarName = 'DATABASE_URL',\n sourceFile,\n}: {\n adapter: DatabaseAdapter\n envVarName?: string\n sourceFile: SourceFile\n}): TransformationResult {\n debug(`[AST] Adding database adapter: ${adapter} (envVar: ${envVarName})`)\n\n const modifications: Modification[] = []\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const { buildConfigCall, dbProperty } = detection.structures\n const config = DB_ADAPTER_CONFIG[adapter]\n\n // Remove old db adapter imports and track position for replacement\n const oldAdapters = Object.values(DB_ADAPTER_CONFIG)\n const removedAdapters: string[] = []\n let importInsertIndex: number | undefined\n oldAdapters.forEach((oldConfig) => {\n if (oldConfig.packageName !== config.packageName) {\n const { removedIndex } = removeImportDeclaration({\n moduleSpecifier: oldConfig.packageName,\n sourceFile,\n })\n if (removedIndex !== undefined) {\n // Use the first removed adapter's position\n if (importInsertIndex === undefined) {\n importInsertIndex = removedIndex\n }\n removedAdapters.push(oldConfig.packageName)\n modifications.push({\n type: 'import-removed',\n description: `Removed import from '${oldConfig.packageName}'`,\n })\n }\n }\n })\n\n if (removedAdapters.length > 0) {\n debug(`[AST] Removed old adapter imports: ${removedAdapters.join(', ')}`)\n }\n\n // Add new import at the position of the removed one (or default position)\n addImportDeclaration({\n insertIndex: importInsertIndex,\n moduleSpecifier: config.packageName,\n namedImports: [config.adapterName],\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: { ${config.adapterName} } from '${config.packageName}'`,\n })\n\n // Add special imports for specific adapters\n if (adapter === 'd1-sqlite') {\n debug('[AST] Adding special import: ./db/migrations')\n addImportDeclaration({\n defaultImport: 'migrations',\n moduleSpecifier: './db/migrations',\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: migrations from './db/migrations'`,\n })\n }\n\n // Get config object\n const configObject = buildConfigCall.getArguments()[0]\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n error: formatError({\n actual: 'buildConfig has no object literal argument',\n context: 'database adapter configuration',\n expected: 'buildConfig({ ... })',\n technicalDetails: 'buildConfig call must have an object literal as first argument',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n\n const newDbCode = `db: ${config.configTemplate(envVarName)}`\n\n if (dbProperty) {\n // Replace existing db property\n // NOTE: Using replaceWithText() instead of remove() + insertPropertyAssignment()\n // to avoid double comma issues. When remove() is called, ts-morph doesn't always\n // clean up trailing commas correctly, which can result in syntax like \"},,\" when\n // inserting a new property at that position. replaceWithText() preserves the\n // surrounding punctuation correctly.\n debug(`[AST] Replacing existing db property`)\n dbProperty.replaceWithText(newDbCode)\n modifications.push({\n type: 'property-added',\n description: `Replaced db property with ${adapter} adapter`,\n })\n } else {\n // No existing db property - insert at end\n const insertIndex = objLiteral.getProperties().length\n debug(`[AST] Adding db property at index ${insertIndex}`)\n objLiteral.insertPropertyAssignment(insertIndex, {\n name: 'db',\n initializer: config.configTemplate(envVarName),\n })\n modifications.push({\n type: 'property-added',\n description: `Added db property with ${adapter} adapter`,\n })\n }\n\n debug(`[AST] ✓ Database adapter ${adapter} added successfully`)\n\n return {\n modifications,\n modified: true,\n success: true,\n }\n}\n\nexport function addStorageAdapter({\n adapter,\n sourceFile,\n}: {\n adapter: StorageAdapter\n sourceFile: SourceFile\n}): TransformationResult {\n debug(`[AST] Adding storage adapter: ${adapter}`)\n\n const modifications: Modification[] = []\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const config = STORAGE_ADAPTER_CONFIG[adapter]\n\n // Local disk doesn't need any imports or plugins\n if (adapter === 'localDisk') {\n debug('[AST] localDisk storage adapter - no imports or plugins needed')\n return {\n modifications: [],\n modified: false,\n success: true,\n }\n }\n\n // Add import\n if (config.packageName && config.adapterName) {\n addImportDeclaration({\n moduleSpecifier: config.packageName,\n namedImports: [config.adapterName],\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: { ${config.adapterName} } from '${config.packageName}'`,\n })\n }\n\n const { buildConfigCall } = detection.structures\n const configObject = buildConfigCall.getArguments()[0]\n\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n error: formatError({\n actual: 'buildConfig has no object literal argument',\n context: 'storage adapter configuration',\n expected: 'buildConfig({ ... })',\n technicalDetails: 'buildConfig call must have an object literal as first argument',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n\n // Find or create plugins array\n const pluginsPropertyRaw = objLiteral.getProperty('plugins')\n let pluginsProperty = pluginsPropertyRaw?.asKind(SyntaxKind.PropertyAssignment)\n\n // Check if it's a shorthand property (e.g., `plugins` referencing an imported variable)\n const shorthandProperty = pluginsPropertyRaw?.asKind(SyntaxKind.ShorthandPropertyAssignment)\n\n if (shorthandProperty) {\n debug('[AST] Found shorthand plugins property, converting to long form with spread')\n // Get the identifier name (usually 'plugins')\n const identifierName = shorthandProperty.getName()\n\n // Find insert position before removing\n const allProperties = objLiteral.getProperties()\n const insertIndex = allProperties.indexOf(shorthandProperty)\n\n // Remove the shorthand property\n shorthandProperty.remove()\n\n // Create new property with spread operator: plugins: [...plugins, newAdapter]\n objLiteral.insertPropertyAssignment(insertIndex, {\n name: 'plugins',\n initializer: `[...${identifierName}]`,\n })\n\n pluginsProperty = objLiteral.getProperty('plugins')?.asKind(SyntaxKind.PropertyAssignment)\n modifications.push({\n type: 'property-added',\n description: `Converted shorthand plugins property to array with spread syntax`,\n })\n } else if (!pluginsProperty) {\n debug('[AST] Creating new plugins array')\n // Create plugins array\n objLiteral.addPropertyAssignment({\n name: 'plugins',\n initializer: '[]',\n })\n pluginsProperty = objLiteral.getProperty('plugins')?.asKind(SyntaxKind.PropertyAssignment)\n modifications.push({\n type: 'property-added',\n description: `Created plugins array`,\n })\n } else {\n debug('[AST] Reusing existing plugins array')\n }\n\n if (!pluginsProperty) {\n return {\n error: formatError({\n actual: 'Failed to create or find plugins property',\n context: 'storage adapter configuration',\n expected: 'plugins array property',\n technicalDetails: 'Could not create or access plugins property',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const initializer = pluginsProperty.getInitializer()\n if (!initializer || initializer.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return {\n error: formatError({\n actual: 'plugins property is not an array',\n context: 'storage adapter configuration',\n expected: 'plugins: [...]',\n technicalDetails: 'plugins property must be an array literal expression',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const pluginsArray = initializer.asKindOrThrow(SyntaxKind.ArrayLiteralExpression)\n\n // Add storage adapter call\n const configText = config.configTemplate()\n if (configText) {\n pluginsArray.addElement(configText)\n modifications.push({\n type: 'property-added',\n description: `Added ${adapter} to plugins array`,\n })\n }\n\n debug(`[AST] ✓ Storage adapter ${adapter} added successfully`)\n\n return {\n modifications,\n modified: true,\n success: true,\n }\n}\n\nexport function removeSharp(sourceFile: SourceFile): TransformationResult {\n debug('[AST] Removing sharp import and property')\n\n const modifications: Modification[] = []\n\n // Remove import\n const { removedIndex } = removeImportDeclaration({ moduleSpecifier: 'sharp', sourceFile })\n if (removedIndex !== undefined) {\n modifications.push({\n type: 'import-removed',\n description: `Removed import from 'sharp'`,\n })\n }\n\n // Find and remove sharp property from buildConfig\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n // If detection failed but we removed import, still count as partial success\n if (modifications.length > 0) {\n return {\n modifications,\n modified: true,\n success: true,\n warnings: ['Could not detect config structure to remove sharp property'],\n }\n }\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const { buildConfigCall } = detection.structures\n const configObject = buildConfigCall.getArguments()[0]\n\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n modifications,\n modified: modifications.length > 0,\n success: true,\n warnings: ['buildConfig has no object literal argument - could not remove sharp property'],\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n const sharpProperty = objLiteral.getProperty('sharp')\n\n if (sharpProperty) {\n sharpProperty.remove()\n modifications.push({\n type: 'property-removed',\n description: `Removed sharp property from config`,\n })\n debug('[AST] ✓ Sharp property removed from config')\n } else {\n debug('[AST] Sharp property not found (already absent)')\n }\n\n return {\n modifications,\n modified: modifications.length > 0,\n success: true,\n }\n}\n\n/** This shouldn't be necessary once the templates are updated. Can't hurt to keep in, though */\nexport function removeCommentMarkers(sourceFile: SourceFile): SourceFile {\n // Get the full text and replace comment markers\n let text = sourceFile.getFullText()\n\n // Remove inline comment markers from imports\n text = text.replace(/\\s*\\/\\/\\s*database-adapter-import\\s*$/gm, '')\n text = text.replace(/\\s*\\/\\/\\s*storage-adapter-import-placeholder\\s*$/gm, '')\n\n // Remove standalone comment lines\n text = text.replace(/^\\s*\\/\\/\\s*database-adapter-config-start\\s*\\n/gm, '')\n text = text.replace(/^\\s*\\/\\/\\s*database-adapter-config-end\\s*\\n/gm, '')\n text = text.replace(/^\\s*\\/\\/\\s*storage-adapter-placeholder\\s*\\n/gm, '')\n\n // Also remove the placeholder line from template (storage-adapter-import-placeholder at top)\n text = text.replace(/^\\/\\/\\s*storage-adapter-import-placeholder\\s*\\n/gm, '')\n\n // Replace the entire source file content\n sourceFile.replaceWithText(text)\n\n return sourceFile\n}\n\n/**\n * Validates payload config structure has required elements after transformation.\n * Checks that buildConfig() call exists and has a db property configured.\n */\nexport function validateStructure(sourceFile: SourceFile): WriteResult {\n debug('[AST] Validating payload config structure')\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success) {\n debug('[AST] ✗ Validation failed: detection unsuccessful')\n return {\n error: detection.error,\n success: false,\n }\n }\n\n const { structures } = detection\n\n // Validate db property exists\n if (!structures?.dbProperty) {\n debug('[AST] ✗ Validation failed: db property missing')\n return {\n error: formatError({\n actual: 'No db property found',\n context: 'database configuration',\n expected: 'buildConfig must have a db property',\n technicalDetails: 'PropertyAssignment with name \"db\" not found in buildConfig object',\n }),\n success: false,\n }\n }\n\n debug('[AST] ✓ Validation passed')\n return { success: true }\n}\n\nexport async function writeTransformedFile(\n sourceFile: SourceFile,\n options: WriteOptions = {},\n): Promise<WriteResult> {\n const { formatWithPrettier = true, validateStructure: shouldValidate = true } = options\n\n debug(`[AST] Writing transformed file: ${sourceFile.getFilePath()}`)\n\n // Validate if requested\n if (shouldValidate) {\n const validation = validateStructure(sourceFile)\n if (!validation.success) {\n return validation\n }\n }\n\n // Get file path and save to disk\n const filePath = sourceFile.getFilePath()\n\n // Format with ts-morph before saving (fixes trailing commas, indentation)\n debug('[AST] Formatting with ts-morph')\n sourceFile.formatText()\n\n // Write file\n debug('[AST] Writing file to disk')\n await sourceFile.save()\n\n // Format with prettier if requested\n if (formatWithPrettier) {\n debug('[AST] Running prettier formatting via CLI')\n try {\n // Detect project directory (go up from file until we find package.json or use dirname)\n const projectDir = path.dirname(filePath)\n\n // Run prettier via CLI (avoids Jest/ESM compatibility issues)\n const prettierCmd = `npx prettier --write \"${filePath}\"`\n\n debug(`[AST] Executing: ${prettierCmd}`)\n execSync(prettierCmd, {\n cwd: projectDir,\n stdio: 'pipe', // Suppress output\n })\n debug('[AST] ✓ Prettier formatting successful')\n } catch (error) {\n // Log but don't fail if prettier fails (might not be installed)\n debug(\n `[AST] ⚠ Prettier formatting failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n debug('[AST] Continuing with unformatted output')\n }\n } else {\n debug('[AST] Skipping prettier formatting (disabled)')\n }\n\n debug('[AST] ✓ File written successfully')\n\n return { success: true }\n}\n\nexport async function configurePayloadConfig(\n filePath: string,\n options: ConfigureOptions = {},\n): Promise<WriteResult> {\n debug(`[AST] Configuring payload config: ${filePath}`)\n debug(\n `[AST] Options: db=${options.db?.type}, storage=${options.storage}, removeSharp=${options.removeSharp}`,\n )\n\n const allModifications: Modification[] = []\n const allWarnings: string[] = []\n\n try {\n // Create Project and load source file with proper settings\n const project = new Project({\n manipulationSettings: {\n quoteKind: QuoteKind.Single,\n },\n })\n let sourceFile = project.addSourceFileAtPath(filePath)\n\n // Run detection\n const detection = detectPayloadConfigStructure(sourceFile)\n if (!detection.success) {\n return detection\n }\n\n // Apply transformations based on options\n if (options.db) {\n debug('[AST] Applying database adapter transformation')\n const result = addDatabaseAdapter({\n adapter: options.db.type,\n envVarName: options.db.envVarName,\n sourceFile,\n })\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n if (options.storage) {\n debug('[AST] Applying storage adapter transformation')\n const result = addStorageAdapter({ adapter: options.storage, sourceFile })\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n if (options.removeSharp) {\n debug('[AST] Applying sharp removal')\n const result = removeSharp(sourceFile)\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n // Remove comment markers from template\n sourceFile = removeCommentMarkers(sourceFile)\n\n // Cleanup orphaned imports after all transformations\n debug('[AST] Cleaning up orphaned imports')\n\n // Cleanup database adapter imports if db was removed\n for (const [, config] of Object.entries(DB_ADAPTER_CONFIG)) {\n if (options.db && config.packageName !== DB_ADAPTER_CONFIG[options.db.type].packageName) {\n const cleanup = cleanupOrphanedImports({\n importNames: [config.adapterName],\n moduleSpecifier: config.packageName,\n sourceFile,\n })\n if (cleanup.removed.length > 0) {\n cleanup.removed.forEach((importName) => {\n allModifications.push({\n type: 'import-removed',\n description: `Cleaned up unused import '${importName}' from '${config.packageName}'`,\n })\n })\n }\n }\n }\n\n // Log summary of modifications\n if (allModifications.length > 0) {\n debug(`[AST] Applied ${allModifications.length} modification(s):`)\n allModifications.forEach((mod) => {\n debug(`[AST] - ${mod.type}: ${mod.description}`)\n })\n }\n\n if (allWarnings.length > 0) {\n debug(`[AST] ${allWarnings.length} warning(s):`)\n allWarnings.forEach((warning) => {\n debug(`[AST] - ${warning}`)\n })\n }\n\n // Write transformed file with validation and formatting\n return await writeTransformedFile(sourceFile, {\n formatWithPrettier: options.formatWithPrettier,\n validateStructure: options.validateStructure ?? true,\n })\n } catch (error) {\n debug(`[AST] ✗ Configuration failed: ${error instanceof Error ? error.message : String(error)}`)\n return {\n error: formatError({\n actual: error instanceof Error ? error.message : String(error),\n context: 'configurePayloadConfig',\n expected: 'Successful file transformation',\n technicalDetails: error instanceof Error ? error.stack || error.message : String(error),\n }),\n success: false,\n }\n }\n}\n"],"names":["execSync","path","Project","QuoteKind","SyntaxKind","debug","DB_ADAPTER_CONFIG","STORAGE_ADAPTER_CONFIG","addImportDeclaration","cleanupOrphanedImports","formatError","removeImportDeclaration","detectPayloadConfigStructure","sourceFile","getFilePath","payloadImport","getImportDeclarations","find","imp","getModuleSpecifierValue","buildConfigImportSpec","getNamedImports","spec","getName","aliasNode","getAliasNode","buildConfigName","getText","buildConfigCall","getDescendantsOfKind","CallExpression","call","expression","getExpression","error","actual","context","expected","technicalDetails","success","importStatements","length","configObject","getArguments","dbProperty","getKind","ObjectLiteralExpression","asKindOrThrow","getProperty","asKind","PropertyAssignment","pluginsArray","objLiteral","pluginsProperty","propertyAssignment","initializer","getInitializer","ArrayLiteralExpression","allBuildConfigCalls","filter","hasImportAlias","payloadImports","hasOtherPayloadImports","some","dbAdapterImportInfo","config","Object","entries","importDecl","packageName","namedImports","hasOtherImports","importDeclaration","storageAdapterImports","adapterName","push","needsManualIntervention","edgeCases","multipleBuildConfigCalls","importSources","dbAdapter","storageAdapters","undefined","structures","addDatabaseAdapter","adapter","envVarName","modifications","detection","modified","oldAdapters","values","removedAdapters","importInsertIndex","forEach","oldConfig","removedIndex","moduleSpecifier","type","description","join","insertIndex","defaultImport","newDbCode","configTemplate","replaceWithText","getProperties","insertPropertyAssignment","name","addStorageAdapter","pluginsPropertyRaw","shorthandProperty","ShorthandPropertyAssignment","identifierName","allProperties","indexOf","remove","addPropertyAssignment","configText","addElement","removeSharp","warnings","sharpProperty","removeCommentMarkers","text","getFullText","replace","validateStructure","writeTransformedFile","options","formatWithPrettier","shouldValidate","validation","filePath","formatText","save","projectDir","dirname","prettierCmd","cwd","stdio","Error","message","configurePayloadConfig","db","storage","allModifications","allWarnings","project","manipulationSettings","quoteKind","Single","addSourceFileAtPath","result","cleanup","importNames","removed","importName","mod","warning","String","stack"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,OAAOC,UAAU,OAAM;AACvB,SAASC,OAAO,EAAEC,SAAS,EAAmBC,UAAU,QAAQ,WAAU;AAa1E,SAASC,KAAK,QAAQ,qBAAoB;AAC1C,SAASC,iBAAiB,EAAEC,sBAAsB,QAAQ,sBAAqB;AAC/E,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,WAAW,EACXC,uBAAuB,QAClB,aAAY;AAEnB,OAAO,SAASC,6BAA6BC,UAAsB;IACjER,MAAM,CAAC,4CAA4C,EAAEQ,WAAWC,WAAW,IAAI;IAE/E,2DAA2D;IAC3D,MAAMC,gBAAgBF,WACnBG,qBAAqB,GACr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../../../src/lib/ast/payload-config.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport path from 'path'\nimport { Project, QuoteKind, type SourceFile, SyntaxKind } from 'ts-morph'\n\nimport type {\n ConfigureOptions,\n DatabaseAdapter,\n DetectionResult,\n Modification,\n StorageAdapter,\n TransformationResult,\n WriteOptions,\n WriteResult,\n} from './types.js'\n\nimport { debug } from '../../utils/log.js'\nimport { DB_ADAPTER_CONFIG, STORAGE_ADAPTER_CONFIG } from './adapter-config.js'\nimport {\n addImportDeclaration,\n cleanupOrphanedImports,\n formatError,\n removeImportDeclaration,\n} from './utils.js'\n\nexport function detectPayloadConfigStructure(sourceFile: SourceFile): DetectionResult {\n debug(`[AST] Detecting payload config structure in ${sourceFile.getFilePath()}`)\n\n // First find the actual name being used (might be aliased)\n const payloadImport = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n const buildConfigImportSpec = payloadImport\n ?.getNamedImports()\n .find((spec) => spec.getName() === 'buildConfig')\n\n const aliasNode = buildConfigImportSpec?.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n\n debug(`[AST] Looking for function call: ${buildConfigName}`)\n\n // Find buildConfig call expression (using actual name in code)\n const buildConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((call) => {\n const expression = call.getExpression()\n return expression.getText() === buildConfigName\n })\n\n if (!buildConfigCall) {\n debug(`[AST] ✗ ${buildConfigName} call not found`)\n return {\n error: formatError({\n actual: `No ${buildConfigName} call found in file`,\n context: 'buildConfig call',\n expected: `export default ${buildConfigName}({ ... })`,\n technicalDetails: `Could not find CallExpression with identifier \"${buildConfigName}\"`,\n }),\n success: false,\n }\n }\n\n debug(`[AST] ✓ ${buildConfigName} call found`)\n\n // Get import statements\n const importStatements = sourceFile.getImportDeclarations()\n debug(`[AST] Found ${importStatements.length} import statements`)\n\n // Find db property if it exists\n const configObject = buildConfigCall.getArguments()[0]\n let dbProperty\n if (configObject && configObject.getKind() === SyntaxKind.ObjectLiteralExpression) {\n dbProperty = configObject\n .asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n .getProperty('db')\n ?.asKind(SyntaxKind.PropertyAssignment)\n }\n\n debug(`[AST] db property: ${dbProperty ? '✓ found' : '✗ not found'}`)\n\n // Find plugins array if it exists\n let pluginsArray\n if (configObject && configObject.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n const pluginsProperty = objLiteral.getProperty('plugins')\n\n // Handle PropertyAssignment (e.g., plugins: [...])\n const propertyAssignment = pluginsProperty?.asKind(SyntaxKind.PropertyAssignment)\n if (propertyAssignment) {\n const initializer = propertyAssignment.getInitializer()\n if (initializer?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n pluginsArray = initializer.asKind(SyntaxKind.ArrayLiteralExpression)\n }\n }\n // For ShorthandPropertyAssignment (e.g., plugins), we can't get the array directly\n // but we'll detect it in addStorageAdapter\n }\n\n debug(`[AST] plugins array: ${pluginsArray ? '✓ found' : '✗ not found'}`)\n\n // Find all buildConfig calls for edge case detection (using actual name)\n const allBuildConfigCalls = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((call) => {\n const expression = call.getExpression()\n return expression.getText() === buildConfigName\n })\n\n const hasImportAlias = !!aliasNode\n\n // Check for other Payload imports\n const payloadImports = payloadImport?.getNamedImports() || []\n const hasOtherPayloadImports =\n payloadImports.length > 1 || payloadImports.some((imp) => imp.getName() !== 'buildConfig')\n\n // Track database adapter imports\n let dbAdapterImportInfo\n for (const [, config] of Object.entries(DB_ADAPTER_CONFIG)) {\n const importDecl = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === config.packageName)\n\n if (importDecl) {\n const namedImports = importDecl.getNamedImports()\n dbAdapterImportInfo = {\n hasOtherImports: namedImports.length > 1,\n importDeclaration: importDecl,\n packageName: config.packageName,\n }\n break\n }\n }\n\n // Track storage adapter imports\n const storageAdapterImports = []\n for (const [, config] of Object.entries(STORAGE_ADAPTER_CONFIG)) {\n if (!config.packageName || !config.adapterName) {\n continue\n }\n\n const importDecl = sourceFile\n .getImportDeclarations()\n .find((imp) => imp.getModuleSpecifierValue() === config.packageName)\n\n if (importDecl) {\n const namedImports = importDecl.getNamedImports()\n storageAdapterImports.push({\n hasOtherImports: namedImports.length > 1,\n importDeclaration: importDecl,\n packageName: config.packageName,\n })\n }\n }\n\n const needsManualIntervention = hasImportAlias || allBuildConfigCalls.length > 2\n\n debug(\n `[AST] Edge cases: alias=${hasImportAlias}, multiple=${allBuildConfigCalls.length > 1}, otherImports=${hasOtherPayloadImports}, manual=${needsManualIntervention}`,\n )\n\n return {\n edgeCases: {\n hasImportAlias,\n hasOtherPayloadImports,\n multipleBuildConfigCalls: allBuildConfigCalls.length > 1,\n needsManualIntervention,\n },\n importSources: {\n dbAdapter: dbAdapterImportInfo,\n storage: storageAdapterImports.length > 0 ? storageAdapterImports : undefined,\n },\n sourceFile,\n structures: {\n buildConfigCall,\n dbProperty,\n importStatements,\n pluginsArray,\n },\n success: true,\n }\n}\n\nexport function addDatabaseAdapter({\n adapter,\n envVarName = 'DATABASE_URL',\n sourceFile,\n}: {\n adapter: DatabaseAdapter\n envVarName?: string\n sourceFile: SourceFile\n}): TransformationResult {\n debug(`[AST] Adding database adapter: ${adapter} (envVar: ${envVarName})`)\n\n const modifications: Modification[] = []\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const { buildConfigCall, dbProperty } = detection.structures\n const config = DB_ADAPTER_CONFIG[adapter]\n\n // Remove old db adapter imports and track position for replacement\n const oldAdapters = Object.values(DB_ADAPTER_CONFIG)\n const removedAdapters: string[] = []\n let importInsertIndex: number | undefined\n oldAdapters.forEach((oldConfig) => {\n if (oldConfig.packageName !== config.packageName) {\n const { removedIndex } = removeImportDeclaration({\n moduleSpecifier: oldConfig.packageName,\n sourceFile,\n })\n if (removedIndex !== undefined) {\n // Use the first removed adapter's position\n if (importInsertIndex === undefined) {\n importInsertIndex = removedIndex\n }\n removedAdapters.push(oldConfig.packageName)\n modifications.push({\n type: 'import-removed',\n description: `Removed import from '${oldConfig.packageName}'`,\n })\n }\n }\n })\n\n if (removedAdapters.length > 0) {\n debug(`[AST] Removed old adapter imports: ${removedAdapters.join(', ')}`)\n }\n\n // Add new import at the position of the removed one (or default position)\n addImportDeclaration({\n insertIndex: importInsertIndex,\n moduleSpecifier: config.packageName,\n namedImports: [config.adapterName],\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: { ${config.adapterName} } from '${config.packageName}'`,\n })\n\n // Add special imports for specific adapters\n if (adapter === 'd1-sqlite') {\n debug('[AST] Adding special import: ./db/migrations')\n addImportDeclaration({\n defaultImport: 'migrations',\n moduleSpecifier: './db/migrations',\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: migrations from './db/migrations'`,\n })\n }\n\n // Get config object\n const configObject = buildConfigCall.getArguments()[0]\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n error: formatError({\n actual: 'buildConfig has no object literal argument',\n context: 'database adapter configuration',\n expected: 'buildConfig({ ... })',\n technicalDetails: 'buildConfig call must have an object literal as first argument',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n\n const newDbCode = `db: ${config.configTemplate(envVarName)}`\n\n if (dbProperty) {\n // Replace existing db property\n // NOTE: Using replaceWithText() instead of remove() + insertPropertyAssignment()\n // to avoid double comma issues. When remove() is called, ts-morph doesn't always\n // clean up trailing commas correctly, which can result in syntax like \"},,\" when\n // inserting a new property at that position. replaceWithText() preserves the\n // surrounding punctuation correctly.\n debug(`[AST] Replacing existing db property`)\n dbProperty.replaceWithText(newDbCode)\n modifications.push({\n type: 'property-added',\n description: `Replaced db property with ${adapter} adapter`,\n })\n } else {\n // No existing db property - insert at end\n const insertIndex = objLiteral.getProperties().length\n debug(`[AST] Adding db property at index ${insertIndex}`)\n objLiteral.insertPropertyAssignment(insertIndex, {\n name: 'db',\n initializer: config.configTemplate(envVarName),\n })\n modifications.push({\n type: 'property-added',\n description: `Added db property with ${adapter} adapter`,\n })\n }\n\n debug(`[AST] ✓ Database adapter ${adapter} added successfully`)\n\n return {\n modifications,\n modified: true,\n success: true,\n }\n}\n\nexport function addStorageAdapter({\n adapter,\n sourceFile,\n}: {\n adapter: StorageAdapter\n sourceFile: SourceFile\n}): TransformationResult {\n debug(`[AST] Adding storage adapter: ${adapter}`)\n\n const modifications: Modification[] = []\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const config = STORAGE_ADAPTER_CONFIG[adapter]\n\n // Local disk doesn't need any imports or plugins\n if (adapter === 'localDisk') {\n debug('[AST] localDisk storage adapter - no imports or plugins needed')\n return {\n modifications: [],\n modified: false,\n success: true,\n }\n }\n\n // Add import\n if (config.packageName && config.adapterName) {\n addImportDeclaration({\n moduleSpecifier: config.packageName,\n namedImports: [config.adapterName],\n sourceFile,\n })\n modifications.push({\n type: 'import-added',\n description: `Added import: { ${config.adapterName} } from '${config.packageName}'`,\n })\n }\n\n const { buildConfigCall } = detection.structures\n const configObject = buildConfigCall.getArguments()[0]\n\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n error: formatError({\n actual: 'buildConfig has no object literal argument',\n context: 'storage adapter configuration',\n expected: 'buildConfig({ ... })',\n technicalDetails: 'buildConfig call must have an object literal as first argument',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n\n // Find or create plugins array\n const pluginsPropertyRaw = objLiteral.getProperty('plugins')\n let pluginsProperty = pluginsPropertyRaw?.asKind(SyntaxKind.PropertyAssignment)\n\n // Check if it's a shorthand property (e.g., `plugins` referencing an imported variable)\n const shorthandProperty = pluginsPropertyRaw?.asKind(SyntaxKind.ShorthandPropertyAssignment)\n\n if (shorthandProperty) {\n debug('[AST] Found shorthand plugins property, converting to long form with spread')\n // Get the identifier name (usually 'plugins')\n const identifierName = shorthandProperty.getName()\n\n // Find insert position before removing\n const allProperties = objLiteral.getProperties()\n const insertIndex = allProperties.indexOf(shorthandProperty)\n\n // Remove the shorthand property\n shorthandProperty.remove()\n\n // Create new property with spread operator: plugins: [...plugins, newAdapter]\n objLiteral.insertPropertyAssignment(insertIndex, {\n name: 'plugins',\n initializer: `[...${identifierName}]`,\n })\n\n pluginsProperty = objLiteral.getProperty('plugins')?.asKind(SyntaxKind.PropertyAssignment)\n modifications.push({\n type: 'property-added',\n description: `Converted shorthand plugins property to array with spread syntax`,\n })\n } else if (!pluginsProperty) {\n debug('[AST] Creating new plugins array')\n // Create plugins array\n objLiteral.addPropertyAssignment({\n name: 'plugins',\n initializer: '[]',\n })\n pluginsProperty = objLiteral.getProperty('plugins')?.asKind(SyntaxKind.PropertyAssignment)\n modifications.push({\n type: 'property-added',\n description: `Created plugins array`,\n })\n } else {\n debug('[AST] Reusing existing plugins array')\n }\n\n if (!pluginsProperty) {\n return {\n error: formatError({\n actual: 'Failed to create or find plugins property',\n context: 'storage adapter configuration',\n expected: 'plugins array property',\n technicalDetails: 'Could not create or access plugins property',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const initializer = pluginsProperty.getInitializer()\n if (!initializer || initializer.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return {\n error: formatError({\n actual: 'plugins property is not an array',\n context: 'storage adapter configuration',\n expected: 'plugins: [...]',\n technicalDetails: 'plugins property must be an array literal expression',\n }),\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const pluginsArray = initializer.asKindOrThrow(SyntaxKind.ArrayLiteralExpression)\n\n // Add storage adapter call\n const configText = config.configTemplate()\n if (configText) {\n pluginsArray.addElement(configText)\n modifications.push({\n type: 'property-added',\n description: `Added ${adapter} to plugins array`,\n })\n }\n\n debug(`[AST] ✓ Storage adapter ${adapter} added successfully`)\n\n return {\n modifications,\n modified: true,\n success: true,\n }\n}\n\nexport function removeSharp(sourceFile: SourceFile): TransformationResult {\n debug('[AST] Removing sharp import and property')\n\n const modifications: Modification[] = []\n\n // Remove import\n const { removedIndex } = removeImportDeclaration({ moduleSpecifier: 'sharp', sourceFile })\n if (removedIndex !== undefined) {\n modifications.push({\n type: 'import-removed',\n description: `Removed import from 'sharp'`,\n })\n }\n\n // Find and remove sharp property from buildConfig\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success || !detection.structures) {\n // If detection failed but we removed import, still count as partial success\n if (modifications.length > 0) {\n return {\n modifications,\n modified: true,\n success: true,\n warnings: ['Could not detect config structure to remove sharp property'],\n }\n }\n return {\n error: detection.error,\n modifications: [],\n modified: false,\n success: false,\n }\n }\n\n const { buildConfigCall } = detection.structures\n const configObject = buildConfigCall.getArguments()[0]\n\n if (!configObject || configObject.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return {\n modifications,\n modified: modifications.length > 0,\n success: true,\n warnings: ['buildConfig has no object literal argument - could not remove sharp property'],\n }\n }\n\n const objLiteral = configObject.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n const sharpProperty = objLiteral.getProperty('sharp')\n\n if (sharpProperty) {\n sharpProperty.remove()\n modifications.push({\n type: 'property-removed',\n description: `Removed sharp property from config`,\n })\n debug('[AST] ✓ Sharp property removed from config')\n } else {\n debug('[AST] Sharp property not found (already absent)')\n }\n\n return {\n modifications,\n modified: modifications.length > 0,\n success: true,\n }\n}\n\n/** This shouldn't be necessary once the templates are updated. Can't hurt to keep in, though */\nexport function removeCommentMarkers(sourceFile: SourceFile): SourceFile {\n // Get the full text and replace comment markers\n let text = sourceFile.getFullText()\n\n // Remove inline comment markers from imports\n text = text.replace(/\\s*\\/\\/\\s*database-adapter-import\\s*$/gm, '')\n text = text.replace(/\\s*\\/\\/\\s*storage-adapter-import-placeholder\\s*$/gm, '')\n\n // Remove standalone comment lines\n text = text.replace(/^\\s*\\/\\/\\s*database-adapter-config-start\\s*\\n/gm, '')\n text = text.replace(/^\\s*\\/\\/\\s*database-adapter-config-end\\s*\\n/gm, '')\n text = text.replace(/^\\s*\\/\\/\\s*storage-adapter-placeholder\\s*\\n/gm, '')\n\n // Also remove the placeholder line from template (storage-adapter-import-placeholder at top)\n text = text.replace(/^\\/\\/\\s*storage-adapter-import-placeholder\\s*\\n/gm, '')\n\n // Replace the entire source file content\n sourceFile.replaceWithText(text)\n\n return sourceFile\n}\n\n/**\n * Validates payload config structure has required elements after transformation.\n * Checks that buildConfig() call exists and has a db property configured.\n */\nexport function validateStructure(sourceFile: SourceFile): WriteResult {\n debug('[AST] Validating payload config structure')\n\n const detection = detectPayloadConfigStructure(sourceFile)\n\n if (!detection.success) {\n debug('[AST] ✗ Validation failed: detection unsuccessful')\n return {\n error: detection.error,\n success: false,\n }\n }\n\n const { structures } = detection\n\n // Validate db property exists\n if (!structures?.dbProperty) {\n debug('[AST] ✗ Validation failed: db property missing')\n return {\n error: formatError({\n actual: 'No db property found',\n context: 'database configuration',\n expected: 'buildConfig must have a db property',\n technicalDetails: 'PropertyAssignment with name \"db\" not found in buildConfig object',\n }),\n success: false,\n }\n }\n\n debug('[AST] ✓ Validation passed')\n return { success: true }\n}\n\nexport async function writeTransformedFile(\n sourceFile: SourceFile,\n options: WriteOptions = {},\n): Promise<WriteResult> {\n const { formatWithPrettier = true, validateStructure: shouldValidate = true } = options\n\n debug(`[AST] Writing transformed file: ${sourceFile.getFilePath()}`)\n\n // Validate if requested\n if (shouldValidate) {\n const validation = validateStructure(sourceFile)\n if (!validation.success) {\n return validation\n }\n }\n\n // Get file path and save to disk\n const filePath = sourceFile.getFilePath()\n\n // Format with ts-morph before saving (fixes trailing commas, indentation)\n debug('[AST] Formatting with ts-morph')\n sourceFile.formatText()\n\n // Write file\n debug('[AST] Writing file to disk')\n await sourceFile.save()\n\n // Format with prettier if requested\n if (formatWithPrettier) {\n debug('[AST] Running prettier formatting via CLI')\n try {\n // Detect project directory (go up from file until we find package.json or use dirname)\n const projectDir = path.dirname(filePath)\n\n // Run prettier via CLI (avoids Jest/ESM compatibility issues)\n const prettierCmd = `npx prettier --write \"${filePath}\"`\n\n debug(`[AST] Executing: ${prettierCmd}`)\n execSync(prettierCmd, {\n cwd: projectDir,\n stdio: 'pipe', // Suppress output\n })\n debug('[AST] ✓ Prettier formatting successful')\n } catch (error) {\n // Log but don't fail if prettier fails (might not be installed)\n debug(\n `[AST] ⚠ Prettier formatting failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n debug('[AST] Continuing with unformatted output')\n }\n } else {\n debug('[AST] Skipping prettier formatting (disabled)')\n }\n\n debug('[AST] ✓ File written successfully')\n\n return { success: true }\n}\n\nexport async function configurePayloadConfig(\n filePath: string,\n options: ConfigureOptions = {},\n): Promise<WriteResult> {\n debug(`[AST] Configuring payload config: ${filePath}`)\n debug(\n `[AST] Options: db=${options.db?.type}, storage=${options.storage}, removeSharp=${options.removeSharp}`,\n )\n\n const allModifications: Modification[] = []\n const allWarnings: string[] = []\n\n try {\n // Create Project and load source file with proper settings\n const project = new Project({\n manipulationSettings: {\n quoteKind: QuoteKind.Single,\n },\n })\n let sourceFile = project.addSourceFileAtPath(filePath)\n\n // Run detection\n const detection = detectPayloadConfigStructure(sourceFile)\n if (!detection.success) {\n return detection\n }\n\n // Apply transformations based on options\n if (options.db) {\n debug('[AST] Applying database adapter transformation')\n const result = addDatabaseAdapter({\n adapter: options.db.type,\n envVarName: options.db.envVarName,\n sourceFile,\n })\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n if (options.storage) {\n debug('[AST] Applying storage adapter transformation')\n const result = addStorageAdapter({ adapter: options.storage, sourceFile })\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n if (options.removeSharp) {\n debug('[AST] Applying sharp removal')\n const result = removeSharp(sourceFile)\n\n if (!result.success) {\n return {\n error: result.error,\n success: false,\n }\n }\n\n allModifications.push(...result.modifications)\n if (result.warnings) {\n allWarnings.push(...result.warnings)\n }\n }\n\n // Remove comment markers from template\n sourceFile = removeCommentMarkers(sourceFile)\n\n // Cleanup orphaned imports after all transformations\n debug('[AST] Cleaning up orphaned imports')\n\n // Cleanup database adapter imports if db was removed\n for (const [, config] of Object.entries(DB_ADAPTER_CONFIG)) {\n if (options.db && config.packageName !== DB_ADAPTER_CONFIG[options.db.type].packageName) {\n const cleanup = cleanupOrphanedImports({\n importNames: [config.adapterName],\n moduleSpecifier: config.packageName,\n sourceFile,\n })\n if (cleanup.removed.length > 0) {\n cleanup.removed.forEach((importName) => {\n allModifications.push({\n type: 'import-removed',\n description: `Cleaned up unused import '${importName}' from '${config.packageName}'`,\n })\n })\n }\n }\n }\n\n // Log summary of modifications\n if (allModifications.length > 0) {\n debug(`[AST] Applied ${allModifications.length} modification(s):`)\n allModifications.forEach((mod) => {\n debug(`[AST] - ${mod.type}: ${mod.description}`)\n })\n }\n\n if (allWarnings.length > 0) {\n debug(`[AST] ${allWarnings.length} warning(s):`)\n allWarnings.forEach((warning) => {\n debug(`[AST] - ${warning}`)\n })\n }\n\n // Write transformed file with validation and formatting\n return await writeTransformedFile(sourceFile, {\n formatWithPrettier: options.formatWithPrettier,\n validateStructure: options.validateStructure ?? true,\n })\n } catch (error) {\n debug(`[AST] ✗ Configuration failed: ${error instanceof Error ? error.message : String(error)}`)\n return {\n error: formatError({\n actual: error instanceof Error ? error.message : String(error),\n context: 'configurePayloadConfig',\n expected: 'Successful file transformation',\n technicalDetails: error instanceof Error ? error.stack || error.message : String(error),\n }),\n success: false,\n }\n }\n}\n"],"names":["execSync","path","Project","QuoteKind","SyntaxKind","debug","DB_ADAPTER_CONFIG","STORAGE_ADAPTER_CONFIG","addImportDeclaration","cleanupOrphanedImports","formatError","removeImportDeclaration","detectPayloadConfigStructure","sourceFile","getFilePath","payloadImport","getImportDeclarations","find","imp","getModuleSpecifierValue","buildConfigImportSpec","getNamedImports","spec","getName","aliasNode","getAliasNode","buildConfigName","getText","buildConfigCall","getDescendantsOfKind","CallExpression","call","expression","getExpression","error","actual","context","expected","technicalDetails","success","importStatements","length","configObject","getArguments","dbProperty","getKind","ObjectLiteralExpression","asKindOrThrow","getProperty","asKind","PropertyAssignment","pluginsArray","objLiteral","pluginsProperty","propertyAssignment","initializer","getInitializer","ArrayLiteralExpression","allBuildConfigCalls","filter","hasImportAlias","payloadImports","hasOtherPayloadImports","some","dbAdapterImportInfo","config","Object","entries","importDecl","packageName","namedImports","hasOtherImports","importDeclaration","storageAdapterImports","adapterName","push","needsManualIntervention","edgeCases","multipleBuildConfigCalls","importSources","dbAdapter","storage","undefined","structures","addDatabaseAdapter","adapter","envVarName","modifications","detection","modified","oldAdapters","values","removedAdapters","importInsertIndex","forEach","oldConfig","removedIndex","moduleSpecifier","type","description","join","insertIndex","defaultImport","newDbCode","configTemplate","replaceWithText","getProperties","insertPropertyAssignment","name","addStorageAdapter","pluginsPropertyRaw","shorthandProperty","ShorthandPropertyAssignment","identifierName","allProperties","indexOf","remove","addPropertyAssignment","configText","addElement","removeSharp","warnings","sharpProperty","removeCommentMarkers","text","getFullText","replace","validateStructure","writeTransformedFile","options","formatWithPrettier","shouldValidate","validation","filePath","formatText","save","projectDir","dirname","prettierCmd","cwd","stdio","Error","message","configurePayloadConfig","db","allModifications","allWarnings","project","manipulationSettings","quoteKind","Single","addSourceFileAtPath","result","cleanup","importNames","removed","importName","mod","warning","String","stack"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,OAAOC,UAAU,OAAM;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d7B,MAAM,CAAC,8BAA8B,EAAE6B,iBAAiB2G,QAAQ3G,MAAM4G,OAAO,GAAGiB,OAAO7H,QAAQ;QAC/F,OAAO;YACLA,OAAOxB,YAAY;gBACjByB,QAAQD,iBAAiB2G,QAAQ3G,MAAM4G,OAAO,GAAGiB,OAAO7H;gBACxDE,SAAS;gBACTC,UAAU;gBACVC,kBAAkBJ,iBAAiB2G,QAAQ3G,MAAM8H,KAAK,IAAI9H,MAAM4G,OAAO,GAAGiB,OAAO7H;YACnF;YACAK,SAAS;QACX;IACF;AACF"}
@@ -49,7 +49,7 @@ export type DetectionResult = {
49
49
  packageName: string;
50
50
  };
51
51
  /** Current storage adapter import info */
52
- storageAdapters?: Array<{
52
+ storage?: Array<{
53
53
  hasOtherImports: boolean;
54
54
  importDeclaration: ImportDeclaration;
55
55
  packageName: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/lib/ast/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,sBAAsB,EACtB,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACX,MAAM,UAAU,CAAA;AAGjB,MAAM,MAAM,mBAAmB,GAAG;IAChC,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,UAAU,EAAE,UAAU,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,wBAAwB,GAAG;IACrC,YAAY,EAAE,OAAO,CAAA;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,UAAU,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,MAAM,EAAE,CAAA;IACd,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,UAAU,EAAE,UAAU,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACnC,gBAAgB,EAAE,MAA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Ae,CAAA;KACtB,CAAA;IACD,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB,OAAO,CAAC,EAAE,cAAc,CAAA;CACzB,GAAG,YAAY,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/lib/ast/types.ts"],"sourcesContent":["import type {\n ArrayLiteralExpression,\n CallExpression,\n ImportDeclaration,\n PropertyAssignment,\n SourceFile,\n} from 'ts-morph'\n\n// Result types for import utility functions\nexport type ImportRemovalResult = {\n removedIndex?: number\n sourceFile: SourceFile\n}\n\nexport type NamedImportRemovalResult = {\n fullyRemoved: boolean\n index?: number\n sourceFile: SourceFile\n}\n\nexport type ImportCleanupResult = {\n kept: string[]\n removed: string[]\n sourceFile: SourceFile\n}\n\nexport type DetectionError = {\n debugInfo?: Record<string, unknown>\n technicalDetails: string\n userMessage: string\n}\n\nexport type PayloadConfigStructures = {\n buildConfigCall: CallExpression\n dbProperty?: PropertyAssignment\n importStatements: ImportDeclaration[]\n pluginsArray?: ArrayLiteralExpression\n}\n\n/**\n * Detection result with edge case tracking and import source information\n */\nexport type DetectionResult = {\n /** Edge case flags */\n edgeCases?: {\n /** Import uses an alias (e.g., import { buildConfig as bc }) */\n hasImportAlias: boolean\n /** Other Payload imports exist (e.g., CollectionConfig) */\n hasOtherPayloadImports: boolean\n /** Multiple buildConfig calls found in file */\n multipleBuildConfigCalls: boolean\n /** Needs manual intervention (can't be automatically handled) */\n needsManualIntervention: boolean\n }\n error?: DetectionError\n /** Import source tracking */\n importSources?: {\n /** Current database adapter import info */\n dbAdapter?: {\n hasOtherImports: boolean\n importDeclaration: ImportDeclaration\n packageName: string\n }\n /** Current storage adapter import info */\n storageAdapters?: Array<{\n hasOtherImports: boolean\n importDeclaration: ImportDeclaration\n packageName: string\n }>\n }\n /** Source file reference */\n sourceFile?: SourceFile\n /** Detected structures */\n structures?: PayloadConfigStructures\n success: boolean\n}\n\n/**\n * Tracks a single modification made to the AST\n */\nexport type Modification = {\n description: string\n location?: {\n column: number\n line: number\n }\n type:\n | 'function-renamed'\n | 'import-added'\n | 'import-modified'\n | 'import-removed'\n | 'property-added'\n | 'property-removed'\n}\n\n/**\n * Result of transformation operations\n */\nexport type TransformationResult = {\n error?: DetectionError\n modifications: Modification[]\n modified: boolean\n success: boolean\n warnings?: string[]\n}\n\n/**\n * Final result after writing to disk\n */\nexport type ModificationResult = {\n error?: DetectionError\n filePath: string\n formatted?: boolean\n modifications: Modification[]\n success: boolean\n warnings?: string[]\n}\nexport type DatabaseAdapter = (typeof ALL_DATABASE_ADAPTERS)[number]\n\nexport const ALL_DATABASE_ADAPTERS = [\n 'mongodb',\n 'postgres',\n 'sqlite',\n 'vercel-postgres',\n 'd1-sqlite',\n] as const\n\nexport const ALL_STORAGE_ADAPTERS = [\n 'azureStorage',\n 'gcsStorage',\n 'localDisk',\n 'r2Storage',\n 's3Storage',\n 'uploadthingStorage',\n 'vercelBlobStorage',\n] as const\n\nexport type StorageAdapter = (typeof ALL_STORAGE_ADAPTERS)[number]\n\nexport type TransformOptions = {\n databaseAdapter?: {\n envVarName?: string\n type: DatabaseAdapter\n }\n removeSharp?: boolean\n storageAdapter?: {\n type: StorageAdapter\n }\n}\n\nexport type WriteOptions = {\n formatWithPrettier?: boolean\n validateStructure?: boolean\n}\n\nexport type WriteResult = {\n error?: DetectionError\n success: boolean\n}\n\nexport type ConfigureOptions = {\n db?: {\n envVarName?: string\n type: DatabaseAdapter\n }\n removeSharp?: boolean\n storage?: StorageAdapter\n} & WriteOptions\n"],"names":["ALL_DATABASE_ADAPTERS","ALL_STORAGE_ADAPTERS"],"mappings":"AAuHA,OAAO,MAAMA,wBAAwB;IACnC;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,OAAO,MAAMC,uBAAuB;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS"}
1
+ {"version":3,"sources":["../../../src/lib/ast/types.ts"],"sourcesContent":["import type {\n ArrayLiteralExpression,\n CallExpression,\n ImportDeclaration,\n PropertyAssignment,\n SourceFile,\n} from 'ts-morph'\n\n// Result types for import utility functions\nexport type ImportRemovalResult = {\n removedIndex?: number\n sourceFile: SourceFile\n}\n\nexport type NamedImportRemovalResult = {\n fullyRemoved: boolean\n index?: number\n sourceFile: SourceFile\n}\n\nexport type ImportCleanupResult = {\n kept: string[]\n removed: string[]\n sourceFile: SourceFile\n}\n\nexport type DetectionError = {\n debugInfo?: Record<string, unknown>\n technicalDetails: string\n userMessage: string\n}\n\nexport type PayloadConfigStructures = {\n buildConfigCall: CallExpression\n dbProperty?: PropertyAssignment\n importStatements: ImportDeclaration[]\n pluginsArray?: ArrayLiteralExpression\n}\n\n/**\n * Detection result with edge case tracking and import source information\n */\nexport type DetectionResult = {\n /** Edge case flags */\n edgeCases?: {\n /** Import uses an alias (e.g., import { buildConfig as bc }) */\n hasImportAlias: boolean\n /** Other Payload imports exist (e.g., CollectionConfig) */\n hasOtherPayloadImports: boolean\n /** Multiple buildConfig calls found in file */\n multipleBuildConfigCalls: boolean\n /** Needs manual intervention (can't be automatically handled) */\n needsManualIntervention: boolean\n }\n error?: DetectionError\n /** Import source tracking */\n importSources?: {\n /** Current database adapter import info */\n dbAdapter?: {\n hasOtherImports: boolean\n importDeclaration: ImportDeclaration\n packageName: string\n }\n /** Current storage adapter import info */\n storage?: Array<{\n hasOtherImports: boolean\n importDeclaration: ImportDeclaration\n packageName: string\n }>\n }\n /** Source file reference */\n sourceFile?: SourceFile\n /** Detected structures */\n structures?: PayloadConfigStructures\n success: boolean\n}\n\n/**\n * Tracks a single modification made to the AST\n */\nexport type Modification = {\n description: string\n location?: {\n column: number\n line: number\n }\n type:\n | 'function-renamed'\n | 'import-added'\n | 'import-modified'\n | 'import-removed'\n | 'property-added'\n | 'property-removed'\n}\n\n/**\n * Result of transformation operations\n */\nexport type TransformationResult = {\n error?: DetectionError\n modifications: Modification[]\n modified: boolean\n success: boolean\n warnings?: string[]\n}\n\n/**\n * Final result after writing to disk\n */\nexport type ModificationResult = {\n error?: DetectionError\n filePath: string\n formatted?: boolean\n modifications: Modification[]\n success: boolean\n warnings?: string[]\n}\nexport type DatabaseAdapter = (typeof ALL_DATABASE_ADAPTERS)[number]\n\nexport const ALL_DATABASE_ADAPTERS = [\n 'mongodb',\n 'postgres',\n 'sqlite',\n 'vercel-postgres',\n 'd1-sqlite',\n] as const\n\nexport const ALL_STORAGE_ADAPTERS = [\n 'azureStorage',\n 'gcsStorage',\n 'localDisk',\n 'r2Storage',\n 's3Storage',\n 'uploadthingStorage',\n 'vercelBlobStorage',\n] as const\n\nexport type StorageAdapter = (typeof ALL_STORAGE_ADAPTERS)[number]\n\nexport type TransformOptions = {\n databaseAdapter?: {\n envVarName?: string\n type: DatabaseAdapter\n }\n removeSharp?: boolean\n storageAdapter?: {\n type: StorageAdapter\n }\n}\n\nexport type WriteOptions = {\n formatWithPrettier?: boolean\n validateStructure?: boolean\n}\n\nexport type WriteResult = {\n error?: DetectionError\n success: boolean\n}\n\nexport type ConfigureOptions = {\n db?: {\n envVarName?: string\n type: DatabaseAdapter\n }\n removeSharp?: boolean\n storage?: StorageAdapter\n} & WriteOptions\n"],"names":["ALL_DATABASE_ADAPTERS","ALL_STORAGE_ADAPTERS"],"mappings":"AAuHA,OAAO,MAAMA,wBAAwB;IACnC;IACA;IACA;IACA;IACA;CACD,CAAS;AAEV,OAAO,MAAMC,uBAAuB;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"configure-plugin-project.d.ts","sourceRoot":"","sources":["../../src/lib/configure-plugin-project.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,eAAO,MAAM,sBAAsB,qCAGhC;IACD,cAAc,EAAE,MAAM,CAAA;IACtB,WAAW,EAAE,MAAM,CAAA;CACpB,SAmCA,CAAA"}
1
+ {"version":3,"file":"configure-plugin-project.d.ts","sourceRoot":"","sources":["../../src/lib/configure-plugin-project.ts"],"names":[],"mappings":"AAKA;;GAEG;AACH,eAAO,MAAM,sBAAsB,GAAI,kCAGpC;IACD,cAAc,EAAE,MAAM,CAAA;IACtB,WAAW,EAAE,MAAM,CAAA;CACpB,SAmCA,CAAA"}
@@ -0,0 +1,20 @@
1
+ import type { PackageManager } from '../types.js';
2
+ /**
3
+ * pnpm v11 fails installs that have unapproved dependency build scripts, reading approvals only from
4
+ * pnpm-workspace.yaml (the `pnpm` field in package.json is ignored). create-next-app now scaffolds a
5
+ * placeholder `allowBuilds` block (sharp/unrs-resolver left unset) plus an `ignoredBuiltDependencies`
6
+ * denylist, so we must merge rather than skip: force Payload's build scripts to `true` and remove them
7
+ * from the denylist. No-op for non-pnpm package managers.
8
+ */
9
+ export declare function ensurePnpmBuildApprovals(args: {
10
+ packageManager: PackageManager;
11
+ projectDir: string;
12
+ }): Promise<void>;
13
+ /**
14
+ * Merges Payload's required build approvals into a pnpm-workspace.yaml string. Pure and idempotent:
15
+ * sets each required package to `true` under `allowBuilds` (adding the block if missing) and strips
16
+ * those packages from any `ignoredBuiltDependencies` denylist. Top-level keys are detected by a
17
+ * zero-indent `key:`, with their two-space children grouped beneath them.
18
+ */
19
+ export declare function upsertBuildApprovals(content: string): string;
20
+ //# sourceMappingURL=configure-pnpm-builds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configure-pnpm-builds.d.ts","sourceRoot":"","sources":["../../src/lib/configure-pnpm-builds.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAWjD;;;;;;GAMG;AACH,wBAAsB,wBAAwB,CAAC,IAAI,EAAE;IACnD,cAAc,EAAE,cAAc,CAAA;IAC9B,UAAU,EAAE,MAAM,CAAA;CACnB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhB;AAOD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAkC5D"}
@@ -0,0 +1,100 @@
1
+ import fse from 'fs-extra';
2
+ import path from 'path';
3
+ /*
4
+ * Build scripts pnpm v11 must be allowed to run for the projects create-payload-app scaffolds;
5
+ * otherwise the install fails with ERR_PNPM_IGNORED_BUILDS. esbuild/sharp/unrs-resolver cover the
6
+ * default templates; workerd is required by with-cloudflare-d1.
7
+ * TODO(follow-up): the CI drift guard only verifies the blank template — extend it across every
8
+ * getValidTemplates() entry so this single list can't drift per-template.
9
+ */ const ALLOWED_BUILDS = [
10
+ 'esbuild',
11
+ 'sharp',
12
+ 'unrs-resolver',
13
+ 'workerd'
14
+ ];
15
+ /**
16
+ * pnpm v11 fails installs that have unapproved dependency build scripts, reading approvals only from
17
+ * pnpm-workspace.yaml (the `pnpm` field in package.json is ignored). create-next-app now scaffolds a
18
+ * placeholder `allowBuilds` block (sharp/unrs-resolver left unset) plus an `ignoredBuiltDependencies`
19
+ * denylist, so we must merge rather than skip: force Payload's build scripts to `true` and remove them
20
+ * from the denylist. No-op for non-pnpm package managers.
21
+ */ export async function ensurePnpmBuildApprovals(args) {
22
+ const { packageManager, projectDir } = args;
23
+ if (packageManager !== 'pnpm') {
24
+ return;
25
+ }
26
+ const workspacePath = path.join(projectDir, 'pnpm-workspace.yaml');
27
+ const existing = await fse.pathExists(workspacePath) ? await fse.readFile(workspacePath, 'utf-8') : '';
28
+ await fse.writeFile(workspacePath, upsertBuildApprovals(existing));
29
+ }
30
+ /**
31
+ * Merges Payload's required build approvals into a pnpm-workspace.yaml string. Pure and idempotent:
32
+ * sets each required package to `true` under `allowBuilds` (adding the block if missing) and strips
33
+ * those packages from any `ignoredBuiltDependencies` denylist. Top-level keys are detected by a
34
+ * zero-indent `key:`, with their two-space children grouped beneath them.
35
+ */ export function upsertBuildApprovals(content) {
36
+ const blocks = toTopLevelBlocks(content);
37
+ const ignored = blocks.find((block)=>block.key === 'ignoredBuiltDependencies');
38
+ if (ignored) {
39
+ ignored.lines = ignored.lines.filter((line, index)=>{
40
+ if (index === 0) {
41
+ return true;
42
+ }
43
+ const name = /^\s*-\s*'?([^'\s]+)'?\s*$/.exec(line)?.[1];
44
+ return !(name && ALLOWED_BUILDS.includes(name));
45
+ });
46
+ }
47
+ const allow = blocks.find((block)=>block.key === 'allowBuilds');
48
+ if (allow) {
49
+ for (const name of ALLOWED_BUILDS){
50
+ const pattern = new RegExp(`^\\s+'?${escapeRegExp(name)}'?:`);
51
+ const index = allow.lines.findIndex((line)=>pattern.test(line));
52
+ if (index >= 0) {
53
+ allow.lines[index] = ` ${name}: true`;
54
+ } else {
55
+ allow.lines.push(` ${name}: true`);
56
+ }
57
+ }
58
+ } else {
59
+ blocks.push({
60
+ key: 'allowBuilds',
61
+ lines: [
62
+ 'allowBuilds:',
63
+ ...ALLOWED_BUILDS.map((name)=>` ${name}: true`)
64
+ ]
65
+ });
66
+ }
67
+ const output = blocks.flatMap((block)=>block.lines).join('\n');
68
+ return output.endsWith('\n') ? output : `${output}\n`;
69
+ }
70
+ function toTopLevelBlocks(content) {
71
+ const lines = content.length ? content.replace(/\n$/, '').split('\n') : [];
72
+ const blocks = [];
73
+ for (const line of lines){
74
+ const key = /^[^\s#]/.test(line) ? /^([^:]+):/.exec(line)?.[1] : undefined;
75
+ const current = blocks[blocks.length - 1];
76
+ if (key !== undefined) {
77
+ blocks.push({
78
+ key,
79
+ lines: [
80
+ line
81
+ ]
82
+ });
83
+ } else if (current) {
84
+ current.lines.push(line);
85
+ } else {
86
+ blocks.push({
87
+ key: null,
88
+ lines: [
89
+ line
90
+ ]
91
+ });
92
+ }
93
+ }
94
+ return blocks;
95
+ }
96
+ function escapeRegExp(value) {
97
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
98
+ }
99
+
100
+ //# sourceMappingURL=configure-pnpm-builds.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/lib/configure-pnpm-builds.ts"],"sourcesContent":["import fse from 'fs-extra'\nimport path from 'path'\n\nimport type { PackageManager } from '../types.js'\n\n/*\n * Build scripts pnpm v11 must be allowed to run for the projects create-payload-app scaffolds;\n * otherwise the install fails with ERR_PNPM_IGNORED_BUILDS. esbuild/sharp/unrs-resolver cover the\n * default templates; workerd is required by with-cloudflare-d1.\n * TODO(follow-up): the CI drift guard only verifies the blank template — extend it across every\n * getValidTemplates() entry so this single list can't drift per-template.\n */\nconst ALLOWED_BUILDS = ['esbuild', 'sharp', 'unrs-resolver', 'workerd']\n\n/**\n * pnpm v11 fails installs that have unapproved dependency build scripts, reading approvals only from\n * pnpm-workspace.yaml (the `pnpm` field in package.json is ignored). create-next-app now scaffolds a\n * placeholder `allowBuilds` block (sharp/unrs-resolver left unset) plus an `ignoredBuiltDependencies`\n * denylist, so we must merge rather than skip: force Payload's build scripts to `true` and remove them\n * from the denylist. No-op for non-pnpm package managers.\n */\nexport async function ensurePnpmBuildApprovals(args: {\n packageManager: PackageManager\n projectDir: string\n}): Promise<void> {\n const { packageManager, projectDir } = args\n if (packageManager !== 'pnpm') {\n return\n }\n\n const workspacePath = path.join(projectDir, 'pnpm-workspace.yaml')\n const existing = (await fse.pathExists(workspacePath))\n ? await fse.readFile(workspacePath, 'utf-8')\n : ''\n\n await fse.writeFile(workspacePath, upsertBuildApprovals(existing))\n}\n\ntype WorkspaceBlock = {\n key: null | string\n lines: string[]\n}\n\n/**\n * Merges Payload's required build approvals into a pnpm-workspace.yaml string. Pure and idempotent:\n * sets each required package to `true` under `allowBuilds` (adding the block if missing) and strips\n * those packages from any `ignoredBuiltDependencies` denylist. Top-level keys are detected by a\n * zero-indent `key:`, with their two-space children grouped beneath them.\n */\nexport function upsertBuildApprovals(content: string): string {\n const blocks = toTopLevelBlocks(content)\n\n const ignored = blocks.find((block) => block.key === 'ignoredBuiltDependencies')\n if (ignored) {\n ignored.lines = ignored.lines.filter((line, index) => {\n if (index === 0) {\n return true\n }\n const name = /^\\s*-\\s*'?([^'\\s]+)'?\\s*$/.exec(line)?.[1]\n return !(name && ALLOWED_BUILDS.includes(name))\n })\n }\n\n const allow = blocks.find((block) => block.key === 'allowBuilds')\n if (allow) {\n for (const name of ALLOWED_BUILDS) {\n const pattern = new RegExp(`^\\\\s+'?${escapeRegExp(name)}'?:`)\n const index = allow.lines.findIndex((line) => pattern.test(line))\n if (index >= 0) {\n allow.lines[index] = ` ${name}: true`\n } else {\n allow.lines.push(` ${name}: true`)\n }\n }\n } else {\n blocks.push({\n key: 'allowBuilds',\n lines: ['allowBuilds:', ...ALLOWED_BUILDS.map((name) => ` ${name}: true`)],\n })\n }\n\n const output = blocks.flatMap((block) => block.lines).join('\\n')\n return output.endsWith('\\n') ? output : `${output}\\n`\n}\n\nfunction toTopLevelBlocks(content: string): WorkspaceBlock[] {\n const lines = content.length ? content.replace(/\\n$/, '').split('\\n') : []\n const blocks: WorkspaceBlock[] = []\n\n for (const line of lines) {\n const key = /^[^\\s#]/.test(line) ? /^([^:]+):/.exec(line)?.[1] : undefined\n const current = blocks[blocks.length - 1]\n if (key !== undefined) {\n blocks.push({ key, lines: [line] })\n } else if (current) {\n current.lines.push(line)\n } else {\n blocks.push({ key: null, lines: [line] })\n }\n }\n\n return blocks\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n"],"names":["fse","path","ALLOWED_BUILDS","ensurePnpmBuildApprovals","args","packageManager","projectDir","workspacePath","join","existing","pathExists","readFile","writeFile","upsertBuildApprovals","content","blocks","toTopLevelBlocks","ignored","find","block","key","lines","filter","line","index","name","exec","includes","allow","pattern","RegExp","escapeRegExp","findIndex","test","push","map","output","flatMap","endsWith","length","replace","split","undefined","current","value"],"mappings":"AAAA,OAAOA,SAAS,WAAU;AAC1B,OAAOC,UAAU,OAAM;AAIvB;;;;;;CAMC,GACD,MAAMC,iBAAiB;IAAC;IAAW;IAAS;IAAiB;CAAU;AAEvE;;;;;;CAMC,GACD,OAAO,eAAeC,yBAAyBC,IAG9C;IACC,MAAM,EAAEC,cAAc,EAAEC,UAAU,EAAE,GAAGF;IACvC,IAAIC,mBAAmB,QAAQ;QAC7B;IACF;IAEA,MAAME,gBAA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K,MAAM,CAAC;aAAE;QAC7E;IACF;IAEA,MAAMW,SAASrB,OAAOsB,OAAO,CAAC,CAAClB,QAAUA,MAAME,KAAK,EAAEb,IAAI,CAAC;IAC3D,OAAO4B,OAAOE,QAAQ,CAAC,QAAQF,SAAS,GAAGA,OAAO,EAAE,CAAC;AACvD;AAEA,SAASpB,iBAAiBF,OAAe;IACvC,MAAMO,QAAQP,QAAQyB,MAAM,GAAGzB,QAAQ0B,OAAO,CAAC,OAAO,IAAIC,KAAK,CAAC,QAAQ,EAAE;IAC1E,MAAM1B,SAA2B,EAAE;IAEnC,KAAK,MAAMQ,QAAQF,MAAO;QACxB,MAAMD,MAAM,UAAUa,IAAI,CAACV,QAAQ,YAAYG,IAAI,CAACH,OAAO,CAAC,EAAE,GAAGmB;QACjE,MAAMC,UAAU5B,MAAM,CAACA,OAAOwB,MAAM,GAAG,EAAE;QACzC,IAAInB,QAAQsB,WAAW;YACrB3B,OAAOmB,IAAI,CAAC;gBAAEd;gBAAKC,OAAO;oBAACE;iBAAK;YAAC;QACnC,OAAO,IAAIoB,SAAS;YAClBA,QAAQtB,KAAK,CAACa,IAAI,CAACX;QACrB,OAAO;YACLR,OAAOmB,IAAI,CAAC;gBAAEd,KAAK;gBAAMC,OAAO;oBAACE;iBAAK;YAAC;QACzC;IACF;IAEA,OAAOR;AACT;AAEA,SAASgB,aAAaa,KAAa;IACjC,OAAOA,MAAMJ,OAAO,CAAC,uBAAuB;AAC9C"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-project.d.ts","sourceRoot":"","sources":["../../src/lib/create-project.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EACP,SAAS,EACT,cAAc,EACd,cAAc,EACd,eAAe,EAChB,MAAM,aAAa,CAAA;AAqDpB,KAAK,iBAAiB,GAClB;IACE,OAAO,EAAE,cAAc,CAAA;CACxB,GACD;IACE,QAAQ,EAAE,eAAe,CAAA;CAC1B,CAAA;AAEL,wBAAsB,aAAa,CACjC,IAAI,EAAE;IACJ,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,cAAc,EAAE,cAAc,CAAA;IAC9B,UAAU,EAAE,MAAM,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;CACpB,GAAG,iBAAiB,GACpB,OAAO,CAAC,IAAI,CAAC,CAqIf;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,IAAI,EAAE;IAC5C;;OAEG;IACH,aAAa,EAAE,MAAM,CAAA;IACrB,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBhB;AAED;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IAClD,aAAa,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACrC,GAAG,IAAI,CAiBP"}
1
+ {"version":3,"file":"create-project.d.ts","sourceRoot":"","sources":["../../src/lib/create-project.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,SAAS,EACT,OAAO,EACP,SAAS,EACT,cAAc,EACd,cAAc,EACd,eAAe,EAChB,MAAM,aAAa,CAAA;AA4DpB,KAAK,iBAAiB,GAClB;IACE,OAAO,EAAE,cAAc,CAAA;CACxB,GACD;IACE,QAAQ,EAAE,eAAe,CAAA;CAC1B,CAAA;AAEL,wBAAsB,aAAa,CACjC,IAAI,EAAE;IACJ,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,OAAO,EAAE,OAAO,CAAA;IAChB,SAAS,CAAC,EAAE,SAAS,CAAA;IACrB,cAAc,EAAE,cAAc,CAAA;IAC9B,UAAU,EAAE,MAAM,CAAA;IAClB,WAAW,EAAE,MAAM,CAAA;CACpB,GAAG,iBAAiB,GACpB,OAAO,CAAC,IAAI,CAAC,CA6Hf;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,IAAI,EAAE;IAC5C;;OAEG;IACH,aAAa,EAAE,MAAM,CAAA;IACrB,UAAU,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAA;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBhB;AAED;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IAClD,aAAa,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CACrC,GAAG,IAAI,CAiBP"}
@@ -6,8 +6,10 @@ import { fileURLToPath } from 'node:url';
6
6
  import path from 'path';
7
7
  import { tryInitRepoAndCommit } from '../utils/git.js';
8
8
  import { debug, error, info, warning } from '../utils/log.js';
9
+ import { DEFAULT_PAYLOAD_VERSION_TAG, resolvePackageVersion } from '../utils/resolvePackageVersion.js';
9
10
  import { configurePayloadConfig } from './configure-payload-config.js';
10
11
  import { configurePluginProject } from './configure-plugin-project.js';
12
+ import { ensurePnpmBuildApprovals } from './configure-pnpm-builds.js';
11
13
  import { downloadExample } from './download-example.js';
12
14
  import { downloadSkill } from './download-skill.js';
13
15
  import { downloadTemplate } from './download-template.js';
@@ -35,6 +37,10 @@ async function installDeps(args) {
35
37
  } else if (packageManager === 'bun') {
36
38
  installCmd = 'bun install';
37
39
  }
40
+ await ensurePnpmBuildApprovals({
41
+ packageManager,
42
+ projectDir
43
+ });
38
44
  try {
39
45
  await execa.command(installCmd, {
40
46
  cwd: path.resolve(projectDir)
@@ -82,23 +88,14 @@ export async function createProject(args) {
82
88
  projectDir
83
89
  });
84
90
  }
91
+ const versionOrTag = cliArgs['--payload-version'] ?? DEFAULT_PAYLOAD_VERSION_TAG;
85
92
  const spinner = p.spinner();
86
- spinner.start('Checking latest Payload version...');
87
- // Allows overriding the installed Payload version instead of installing the latest
88
- const versionFromCli = cliArgs['--version'];
89
- let payloadVersion;
90
- if (versionFromCli) {
91
- await verifyVersionForPackage({
92
- version: versionFromCli
93
- });
94
- payloadVersion = versionFromCli;
95
- spinner.stop(`Using provided version of Payload ${payloadVersion}`);
96
- } else {
97
- payloadVersion = await getLatestPackageVersion({
98
- packageName: 'payload'
99
- });
100
- spinner.stop(`Found latest version of Payload ${payloadVersion}`);
101
- }
93
+ spinner.start(`Resolving Payload version (${versionOrTag})...`);
94
+ const payloadVersion = await resolvePackageVersion({
95
+ packageName: 'payload',
96
+ versionOrTag
97
+ });
98
+ spinner.stop(`Using Payload version ${payloadVersion}`);
102
99
  await updatePackageJSON({
103
100
  latestVersion: payloadVersion,
104
101
  projectDir,
@@ -211,39 +208,5 @@ export async function createProject(args) {
211
208
  }, {});
212
209
  packageJson.dependencies = updatedDependencies;
213
210
  }
214
- /**
215
- * Fetches the latest version of a package from the NPM registry.
216
- *
217
- * Used in determining the latest version of Payload to use in the generated templates.
218
- */ async function getLatestPackageVersion({ packageName = 'payload' }) {
219
- try {
220
- const response = await fetch(`https://registry.npmjs.org/-/package/${packageName}/dist-tags`);
221
- const data = await response.json();
222
- // Monster chaining for type safety just checking for data.latest
223
- const latestVersion = data && typeof data === 'object' && 'latest' in data && data.latest && typeof data.latest === 'string' ? data.latest : null;
224
- if (!latestVersion) {
225
- throw new Error(`No latest version found for package: ${packageName}`);
226
- }
227
- return latestVersion;
228
- } catch (error) {
229
- console.error('Error fetching Payload version:', error);
230
- throw error;
231
- }
232
- }
233
- /**
234
- * Verifies that the specified version of a package exists on the NPM registry.
235
- *
236
- * Throws an error if the version does not exist.
237
- */ async function verifyVersionForPackage({ packageName = 'payload', version }) {
238
- try {
239
- const response = await fetch(`https://registry.npmjs.org/${packageName}/${version}`);
240
- if (response.status !== 200) {
241
- throw new Error(`No ${version} version found for package: ${packageName}`);
242
- }
243
- } catch (error) {
244
- console.error('Error verifying Payload version:', error);
245
- throw error;
246
- }
247
- }
248
211
 
249
212
  //# sourceMappingURL=create-project.js.map