@payloadcms/figma 0.0.1-alpha.44 → 0.0.1-alpha.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/control-plane.d.ts.map +1 -1
- package/dist/api/control-plane.js +90 -54
- package/dist/api/control-plane.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands/debug.d.ts +8 -0
- package/dist/commands/debug.d.ts.map +1 -0
- package/dist/commands/debug.js +156 -0
- package/dist/commands/debug.js.map +1 -0
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +17 -14
- package/dist/commands/init.js.map +1 -1
- package/dist/db-content-api/index.d.ts.map +1 -1
- package/dist/db-content-api/index.js +26 -7
- package/dist/db-content-api/index.js.map +1 -1
- package/dist/db-content-api/temp-utilities/types.d.ts +22 -0
- package/dist/db-content-api/temp-utilities/types.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/types.js +15 -0
- package/dist/db-content-api/temp-utilities/types.js.map +1 -0
- package/dist/db-content-api/utilities/data/index.d.ts +14 -4
- package/dist/db-content-api/utilities/data/index.d.ts.map +1 -1
- package/dist/db-content-api/utilities/data/index.js +15 -8
- package/dist/db-content-api/utilities/data/index.js.map +1 -1
- package/dist/db-content-api/utilities/data/transformPublishedLocale.d.ts +23 -0
- package/dist/db-content-api/utilities/data/transformPublishedLocale.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/transformPublishedLocale.js +42 -0
- package/dist/db-content-api/utilities/data/transformPublishedLocale.js.map +1 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.d.ts.map +1 -1
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.js +11 -0
- package/dist/db-content-api/utilities/meta/buildLocalizedPaths.js.map +1 -1
- package/dist/db-content-api/utilities/meta/buildMeta.d.ts +17 -2
- package/dist/db-content-api/utilities/meta/buildMeta.d.ts.map +1 -1
- package/dist/db-content-api/utilities/meta/buildMeta.js +4 -1
- package/dist/db-content-api/utilities/meta/buildMeta.js.map +1 -1
- package/dist/db-content-api/utilities/meta/buildPathTypes.d.ts +8 -2
- package/dist/db-content-api/utilities/meta/buildPathTypes.d.ts.map +1 -1
- package/dist/db-content-api/utilities/meta/buildPathTypes.js +41 -11
- package/dist/db-content-api/utilities/meta/buildPathTypes.js.map +1 -1
- package/dist/db-content-api/utilities/where.d.ts +8 -0
- package/dist/db-content-api/utilities/where.d.ts.map +1 -1
- package/dist/db-content-api/utilities/where.js +6 -0
- package/dist/db-content-api/utilities/where.js.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.d.ts.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.js +18 -13
- package/dist/oauth/endpoints/getLoginEndpoint.js.map +1 -1
- package/dist/templates/README.md +1 -1
- package/dist/types/config.d.ts +2 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/config.js +0 -2
- package/dist/types/config.js.map +1 -1
- package/dist/types.d.ts +0 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/lambda-config.d.ts +1 -1
- package/dist/utils/lambda-config.d.ts.map +1 -1
- package/dist/utils/lambda-config.js +2 -2
- package/dist/utils/lambda-config.js.map +1 -1
- package/dist/utils/messages.d.ts +1 -1
- package/dist/utils/messages.d.ts.map +1 -1
- package/dist/utils/messages.js +1 -0
- package/dist/utils/messages.js.map +1 -1
- package/dist/utils/package-manager.d.ts +24 -0
- package/dist/utils/package-manager.d.ts.map +1 -1
- package/dist/utils/package-manager.js +53 -0
- package/dist/utils/package-manager.js.map +1 -1
- package/dist/utils/payload-config-modifier.d.ts +1 -1
- package/dist/utils/payload-config-modifier.d.ts.map +1 -1
- package/dist/utils/payload-config-modifier.js +4 -3
- package/dist/utils/payload-config-modifier.js.map +1 -1
- package/dist/utils/project.d.ts +3 -2
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +4 -2
- package/dist/utils/project.js.map +1 -1
- package/package.json +1 -1
- package/dist/db-content-api/utilities/meta/index.d.ts +0 -5
- package/dist/db-content-api/utilities/meta/index.d.ts.map +0 -1
- package/dist/db-content-api/utilities/meta/index.js +0 -5
- package/dist/db-content-api/utilities/meta/index.js.map +0 -1
package/dist/commands/init.js
CHANGED
|
@@ -13,6 +13,7 @@ import { addOrUpdateEnvVar } from '../utils/env-management.js';
|
|
|
13
13
|
import { isDebug } from '../utils/is-debug.js';
|
|
14
14
|
import { applyLambdaModifications } from '../utils/lambda-config.js';
|
|
15
15
|
import * as log from '../utils/log.js';
|
|
16
|
+
import { detectPackageManagerFromEnvironment, getRunCommand, resolvePackageManager } from '../utils/package-manager.js';
|
|
16
17
|
import { displayManualInstructions, ensurePayloadFigmaConfig } from '../utils/payload-config-modifier.js';
|
|
17
18
|
import { runScript } from '../utils/payload-package-check.js';
|
|
18
19
|
import { detectPayloadProject, hasRequiredDependencies, initializeGitRepo, installDependencies, isInProjectDirectory, scaffoldProject, validatePayloadVersion } from '../utils/project.js';
|
|
@@ -149,6 +150,7 @@ import { loginCommand } from './login.js';
|
|
|
149
150
|
log.debug('Project directory detected');
|
|
150
151
|
// Detect Payload
|
|
151
152
|
const projectInfo = await detectPayloadProject();
|
|
153
|
+
const packageManager = await resolvePackageManager(process.cwd());
|
|
152
154
|
if (projectInfo.hasPayload) {
|
|
153
155
|
// Validate existing Payload version
|
|
154
156
|
if (projectInfo.payloadVersion && !validatePayloadVersion(projectInfo.payloadVersion)) {
|
|
@@ -168,17 +170,17 @@ import { loginCommand } from './login.js';
|
|
|
168
170
|
});
|
|
169
171
|
if (!p.isCancel(shouldInstall) && shouldInstall) {
|
|
170
172
|
s.start('Installing dependencies...');
|
|
171
|
-
await installDependencies(process.cwd(),
|
|
173
|
+
await installDependencies(process.cwd(), packageManager);
|
|
172
174
|
s.stop(pc.green('✓ Dependencies installed'));
|
|
173
175
|
}
|
|
174
176
|
}
|
|
175
177
|
s.start('Checking Payload configuration...');
|
|
176
|
-
const modResult = await ensurePayloadFigmaConfig(process.cwd(),
|
|
178
|
+
const modResult = await ensurePayloadFigmaConfig(process.cwd(), packageManager, {
|
|
177
179
|
contentSystemId
|
|
178
180
|
});
|
|
179
181
|
if (!modResult.success) {
|
|
180
182
|
s.stop(pc.red('✗ Configuration check failed'));
|
|
181
|
-
displayManualInstructions(modResult.error || 'Unknown error');
|
|
183
|
+
displayManualInstructions(modResult.error || 'Unknown error', packageManager);
|
|
182
184
|
process.exit(1);
|
|
183
185
|
}
|
|
184
186
|
if (modResult.modified) {
|
|
@@ -233,10 +235,10 @@ import { loginCommand } from './login.js';
|
|
|
233
235
|
p.note('Create a new project or manually add Payload dependencies', 'Action Required');
|
|
234
236
|
process.exit(1);
|
|
235
237
|
}
|
|
236
|
-
// Generate import map to prevent errors on first
|
|
237
|
-
await runScript(process.cwd(), 'generate:importmap',
|
|
238
|
+
// Generate import map to prevent errors on first dev run
|
|
239
|
+
await runScript(process.cwd(), 'generate:importmap', packageManager);
|
|
238
240
|
// Apply Lambda modifications (run.sh, standalone output, lambda:buildzip script)
|
|
239
|
-
await applyLambdaModifications(process.cwd(),
|
|
241
|
+
await applyLambdaModifications(process.cwd(), packageManager);
|
|
240
242
|
// Ensure .gitignore has required entries
|
|
241
243
|
await ensureGitignore(process.cwd(), [
|
|
242
244
|
'.env',
|
|
@@ -250,7 +252,7 @@ import { loginCommand } from './login.js';
|
|
|
250
252
|
// Success message for existing project
|
|
251
253
|
p.outro(pc.green('✓ Project initialized successfully!'));
|
|
252
254
|
const nextSteps = [
|
|
253
|
-
|
|
255
|
+
`Start development server: \`${getRunCommand(packageManager)} dev\``
|
|
254
256
|
].filter(Boolean);
|
|
255
257
|
p.note(nextSteps.join('\n'), 'Next Steps');
|
|
256
258
|
} else {
|
|
@@ -277,6 +279,7 @@ import { loginCommand } from './login.js';
|
|
|
277
279
|
const fullPath = path.resolve(process.cwd(), projectPath);
|
|
278
280
|
// Get project name from path or prompt
|
|
279
281
|
const projectName = options.name || path.basename(fullPath);
|
|
282
|
+
const packageManager = detectPackageManagerFromEnvironment();
|
|
280
283
|
// Create directory
|
|
281
284
|
try {
|
|
282
285
|
await fs.mkdir(fullPath, {
|
|
@@ -289,10 +292,10 @@ import { loginCommand } from './login.js';
|
|
|
289
292
|
// Scaffold project
|
|
290
293
|
s.start('Downloading template from GitHub...');
|
|
291
294
|
try {
|
|
292
|
-
await scaffoldProject(fullPath, projectName);
|
|
295
|
+
await scaffoldProject(fullPath, projectName, packageManager);
|
|
293
296
|
s.stop(pc.green('✓ Template downloaded'));
|
|
294
297
|
s.start('Installing dependencies...');
|
|
295
|
-
await installDependencies(fullPath,
|
|
298
|
+
await installDependencies(fullPath, packageManager);
|
|
296
299
|
s.stop(pc.green('✓ Dependencies installed'));
|
|
297
300
|
} catch (error) {
|
|
298
301
|
s.stop(pc.red('✗ Failed'));
|
|
@@ -301,12 +304,12 @@ import { loginCommand } from './login.js';
|
|
|
301
304
|
}
|
|
302
305
|
// Modify Payload configuration
|
|
303
306
|
s.start('Checking Payload configuration...');
|
|
304
|
-
const modResult = await ensurePayloadFigmaConfig(fullPath,
|
|
307
|
+
const modResult = await ensurePayloadFigmaConfig(fullPath, packageManager, {
|
|
305
308
|
contentSystemId
|
|
306
309
|
});
|
|
307
310
|
if (!modResult.success) {
|
|
308
311
|
s.stop(pc.red('✗ Configuration check failed'));
|
|
309
|
-
displayManualInstructions(modResult.error || 'Unknown error');
|
|
312
|
+
displayManualInstructions(modResult.error || 'Unknown error', packageManager);
|
|
310
313
|
process.exit(1);
|
|
311
314
|
}
|
|
312
315
|
if (modResult.modified) {
|
|
@@ -341,8 +344,8 @@ import { loginCommand } from './login.js';
|
|
|
341
344
|
} catch (error) {
|
|
342
345
|
p.log.warn(pc.yellow(`⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`));
|
|
343
346
|
}
|
|
344
|
-
// Generate import map to prevent errors on first
|
|
345
|
-
await runScript(fullPath, 'generate:importmap',
|
|
347
|
+
// Generate import map to prevent errors on first dev run
|
|
348
|
+
await runScript(fullPath, 'generate:importmap', packageManager);
|
|
346
349
|
// Generate project token (unless skipping auth)
|
|
347
350
|
if (!options.skipAuth) {
|
|
348
351
|
await generateProjectTokenWithFeedback(tokenStore, contentSystemId, s);
|
|
@@ -357,7 +360,7 @@ import { loginCommand } from './login.js';
|
|
|
357
360
|
if (relativePath && relativePath !== '.') {
|
|
358
361
|
nextSteps.push(`cd ${relativePath}`);
|
|
359
362
|
}
|
|
360
|
-
nextSteps.push(
|
|
363
|
+
nextSteps.push(`${getRunCommand(packageManager)} dev or follow directions in README.md`, '', 'Documentation:', '- Getting Started: https://payloadcms.com/docs/getting-started/what-is-payload', '- Configuration: https://payloadcms.com/docs/configuration/overview');
|
|
361
364
|
p.note(nextSteps.join('\n'), 'Next Steps');
|
|
362
365
|
p.outro(pc.green('✓ Done'));
|
|
363
366
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/init.ts"],"sourcesContent":["import * as p from '@clack/prompts'\nimport fs from 'fs/promises'\nimport path from 'path'\nimport pc from 'picocolors'\n\nimport type { TokenStore } from '../auth/token-store.js'\n\nimport { getDatasetInfo } from '../api/control-plane.js'\nimport { FigmaApiError } from '../api/figma-api.js'\nimport { getValidAccessToken } from '../auth/oauth-flow.js'\nimport { getValidProjectToken, ProjectTokenError } from '../auth/project-token.js'\nimport { getTokenStore } from '../auth/token-store.js'\nimport { getEnvironment } from '../constants.js'\nimport { ensureGitignore } from '../utils/config.js'\nimport { addOrUpdateEnvVar } from '../utils/env-management.js'\nimport { isDebug } from '../utils/is-debug.js'\nimport { applyLambdaModifications } from '../utils/lambda-config.js'\nimport * as log from '../utils/log.js'\nimport {\n displayManualInstructions,\n ensurePayloadFigmaConfig,\n} from '../utils/payload-config-modifier.js'\nimport { runScript } from '../utils/payload-package-check.js'\nimport {\n detectPayloadProject,\n hasRequiredDependencies,\n initializeGitRepo,\n installDependencies,\n isInProjectDirectory,\n scaffoldProject,\n validatePayloadVersion,\n} from '../utils/project.js'\nimport { checkForUpdates, getOwnVersion } from '../utils/version-check.js'\nimport { loginCommand } from './login.js'\n\n/**\n * Options for init command\n */\nexport interface InitCommandOptions {\n /** Enable debug mode */\n debug?: boolean\n /** Force reconfiguration of existing project */\n force?: boolean\n /** Content System ID to use */\n id?: string\n /** Project name (for scaffolding) */\n name?: string\n /** Skip authentication check (for testing/development) */\n skipAuth?: boolean\n /** Skip prompts and use defaults where possible */\n yes?: boolean\n}\n\n/**\n * Generate and store project token for a content system\n * Non-blocking - will show warning but not exit on failure\n * Only shows feedback if DEBUG mode is enabled, otherwise runs silently\n *\n * @param tokenStore - Token store instance\n * @param contentSystemId - Content System ID to generate token for\n * @param spinner - Clack spinner instance for status updates (only used in debug mode)\n */\nasync function generateProjectTokenWithFeedback(\n tokenStore: TokenStore,\n contentSystemId: string,\n spinner: ReturnType<typeof p.spinner>,\n): Promise<void> {\n if (isDebug()) {\n spinner.start('Generating project token...')\n }\n\n try {\n const projectToken = await getValidProjectToken(tokenStore, contentSystemId)\n if (isDebug()) {\n if (projectToken) {\n spinner.stop(pc.green('✓ Project token generated'))\n } else {\n spinner.stop(pc.yellow('⚠ Project token not generated (authentication required)'))\n }\n }\n } catch (error) {\n if (isDebug()) {\n spinner.stop(pc.yellow('⚠ Project token generation failed'))\n }\n // Always show failures, even without debug\n if (error instanceof ProjectTokenError || error instanceof FigmaApiError) {\n log.warning(error.message)\n p.note(\n 'Project token is used for authenticating to the Content API.\\nYou can continue without it, but may need to regenerate later.',\n 'Note',\n )\n } else {\n log.warning(\n `Unable to retrieve project token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n // Don't exit - token generation failure shouldn't block initialization\n }\n}\n\n/**\n * Fetch dataset info from the API\n * Throws on error - caller must handle\n */\nasync function fetchDatasetInfo(\n accessToken: string,\n datasetId: string,\n): Promise<{ oauthClientId: string; oauthClientSecret: string; tenantId: string }> {\n log.debug('Fetching dataset info...')\n\n const datasetInfo = await getDatasetInfo(accessToken, datasetId)\n log.debug('Dataset info retrieved successfully')\n return {\n oauthClientId: datasetInfo.oauthClientId,\n oauthClientSecret: datasetInfo.oauthClientSecret,\n tenantId: datasetInfo.tenantId,\n }\n}\n\n/**\n * Handle the `init` command\n *\n * Sets up a project by:\n * 1. Checking authentication\n * 2. Detecting/scaffolding Payload project\n * 3. Fetching tenant details\n * 4. Storing configuration\n *\n * @param options - Command options\n */\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n // Check for outdated version (non-blocking)\n const currentVersion = await getOwnVersion()\n await checkForUpdates(currentVersion)\n\n // Check authentication\n const tokenStore = getTokenStore(getEnvironment())\n const s = p.spinner()\n\n if (options.skipAuth) {\n // Skip authentication for testing/development\n p.log.warn(pc.yellow('Skipping authentication (--skip-auth mode)'))\n } else {\n try {\n // Check for valid cached tokens first (no API call needed)\n if (!tokenStore.hasValidTokens()) {\n // Need to refresh or authenticate - show spinner for API call\n s.start('Checking authentication...')\n const token = await getValidAccessToken(tokenStore)\n if (!token) {\n s.stop('Authentication required to continue')\n\n // Run login command\n await loginCommand({ showNextSteps: false })\n\n // Get token after auth\n const newToken = await getValidAccessToken(tokenStore)\n if (!newToken) {\n p.log.error('Authentication failed')\n process.exit(1)\n }\n } else {\n s.stop(pc.green('✓ Authenticated'))\n }\n }\n } catch (error) {\n s.stop(pc.red('✗ Authentication failed'))\n log.error(error instanceof Error ? error.message : 'Unknown error')\n p.note('Run `figma auth` to authenticate', 'Tip')\n process.exit(1)\n }\n }\n\n // Note: We no longer check for figma.config.json here\n // Instead, the AST detection will check if figma object already exists in payload.config.ts\n // and skip modification if it does (unless --force is used)\n\n // Step 3: Get Content System ID (required argument)\n log.debug('Configuring Project...')\n\n if (!options.id) {\n p.log.error('Content System ID is required. Use --id <content_system_id>')\n process.exit(1)\n }\n\n const contentSystemId = options.id\n\n // Fetch dataset info (required - will fail if feature not enabled)\n let datasetInfo: { oauthClientId: string; oauthClientSecret: string; tenantId: string } | null =\n null\n if (!options.skipAuth) {\n const accessToken = await getValidAccessToken(tokenStore)\n if (accessToken) {\n try {\n datasetInfo = await fetchDatasetInfo(accessToken, contentSystemId)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n p.log.error(\n pc.red(`✗ Unable to fetch dataset info for content system \"${contentSystemId}\"`),\n )\n p.log.error(pc.dim(`Details: ${message}`))\n p.note(\n 'This may indicate the CMS feature is not enabled for your account.\\n' +\n 'Contact support if you believe this is an error.',\n 'Error',\n )\n process.exit(1)\n }\n }\n }\n\n // Step 4: Detect or scaffold Payload project\n const isInProject = await isInProjectDirectory()\n\n if (isInProject) {\n // ===== EXISTING PROJECT FLOW =====\n log.debug('Project directory detected')\n\n // Detect Payload\n const projectInfo = await detectPayloadProject()\n\n if (projectInfo.hasPayload) {\n // Validate existing Payload version\n if (projectInfo.payloadVersion && !validatePayloadVersion(projectInfo.payloadVersion)) {\n p.log.warn(\n pc.yellow(\n `Payload version ${projectInfo.payloadVersion} detected. Version 3.x is required.`,\n ),\n )\n p.note('Upgrade to Payload 3.x before continuing', 'Action Required')\n process.exit(1)\n }\n\n p.log.success(pc.green(`✓ Payload ${projectInfo.payloadVersion || 'detected'}`))\n\n // Check dependencies\n s.start('Checking dependencies...')\n const hasDeps = await hasRequiredDependencies(process.cwd())\n s.stop(pc.green('✓ Dependencies checked'))\n\n if (!hasDeps) {\n const shouldInstall = await p.confirm({\n initialValue: true,\n message: 'Install dependencies now?',\n })\n\n if (!p.isCancel(shouldInstall) && shouldInstall) {\n s.start('Installing dependencies...')\n await installDependencies(process.cwd(), projectInfo.packageManager || 'pnpm')\n s.stop(pc.green('✓ Dependencies installed'))\n }\n }\n\n s.start('Checking Payload configuration...')\n const modResult = await ensurePayloadFigmaConfig(\n process.cwd(),\n projectInfo.packageManager || 'pnpm',\n {\n contentSystemId,\n },\n )\n\n if (!modResult.success) {\n s.stop(pc.red('✗ Configuration check failed'))\n displayManualInstructions(modResult.error || 'Unknown error')\n process.exit(1)\n }\n\n if (modResult.modified) {\n s.stop(pc.green('✓ Payload configuration updated'))\n if (modResult.changes.length > 0) {\n modResult.changes.forEach((change) => log.debug(pc.dim(` → ${change}`)))\n }\n } else {\n s.stop(pc.green('✓ Payload configuration valid'))\n }\n\n // Display warnings if any\n if (modResult.warnings && modResult.warnings.length > 0) {\n modResult.warnings.forEach((warning) => {\n p.log.warn(pc.yellow(`⚠ ${warning}`))\n })\n }\n\n // Write environment variables to .env file\n try {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_CONTENT_SYSTEM_ID', contentSystemId)\n log.debug(`Added FIGMA_CONTENT_SYSTEM_ID to .env file`)\n\n const env = getEnvironment()\n if (env !== 'production') {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_ENV', env)\n log.debug(`Added FIGMA_ENV=${env} to .env file`)\n }\n\n if (datasetInfo) {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_TENANT_ID', datasetInfo.tenantId)\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_OAUTH_CLIENT_ID', datasetInfo.oauthClientId)\n await addOrUpdateEnvVar(\n process.cwd(),\n 'FIGMA_OAUTH_CLIENT_SECRET',\n datasetInfo.oauthClientSecret,\n )\n log.debug(\n `Added FIGMA_TENANT_ID, FIGMA_OAUTH_CLIENT_ID, FIGMA_OAUTH_CLIENT_SECRET to .env file`,\n )\n }\n } catch (error) {\n p.log.warn(\n pc.yellow(\n `⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n ),\n )\n }\n } else {\n // Has package.json but no Payload - offer to add Payload\n p.log.warn(pc.yellow('⚠ No Payload detected in this project'))\n\n const shouldAddPayload = await p.confirm({\n initialValue: true,\n message: 'Would you like to add Payload to this project?',\n })\n\n if (p.isCancel(shouldAddPayload)) {\n p.cancel('Operation cancelled')\n process.exit(0)\n }\n\n if (!shouldAddPayload) {\n p.log.error('Payload is required to use Figma CMS')\n process.exit(1)\n }\n\n // TODO: Add Payload to existing project (future enhancement)\n p.log.error('Adding Payload to existing projects is not yet supported')\n p.note('Create a new project or manually add Payload dependencies', 'Action Required')\n process.exit(1)\n }\n\n // Generate import map to prevent errors on first pnpm dev\n await runScript(process.cwd(), 'generate:importmap', projectInfo.packageManager || 'pnpm')\n\n // Apply Lambda modifications (run.sh, standalone output, lambda:buildzip script)\n await applyLambdaModifications(process.cwd(), projectInfo.packageManager || 'pnpm')\n\n // Ensure .gitignore has required entries\n await ensureGitignore(process.cwd(), ['.env', '.env.local', 'lambda.zip'])\n\n // Generate project token (unless skipping auth)\n if (!options.skipAuth) {\n await generateProjectTokenWithFeedback(tokenStore, contentSystemId, s)\n }\n\n // Success message for existing project\n p.outro(pc.green('✓ Project initialized successfully!'))\n\n const nextSteps = ['Start development server: `pnpm dev`'].filter(Boolean)\n\n p.note(nextSteps.join('\\n'), 'Next Steps')\n } else {\n // ===== NEW PROJECT FLOW =====\n // p.log.info('No project detected - Creating New Project')\n\n // Prompt for path\n const projectPathInput = await p.text({\n initialValue: './',\n message: 'Enter path to create project:',\n placeholder: './my-cms-project',\n validate: (value) => {\n if (!value) {\n return 'Path is required'\n }\n // Allow relative or absolute paths\n return undefined\n },\n })\n\n if (p.isCancel(projectPathInput)) {\n p.cancel('Operation cancelled')\n process.exit(0)\n }\n\n const projectPath = projectPathInput\n const fullPath = path.resolve(process.cwd(), projectPath)\n\n // Get project name from path or prompt\n const projectName = options.name || path.basename(fullPath)\n\n // Create directory\n try {\n await fs.mkdir(fullPath, { recursive: true })\n } catch (error) {\n p.log.error(\n `Failed to create directory: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n process.exit(1)\n }\n\n // Scaffold project\n s.start('Downloading template from GitHub...')\n try {\n await scaffoldProject(fullPath, projectName)\n s.stop(pc.green('✓ Template downloaded'))\n\n s.start('Installing dependencies...')\n await installDependencies(fullPath, 'pnpm')\n s.stop(pc.green('✓ Dependencies installed'))\n } catch (error) {\n s.stop(pc.red('✗ Failed'))\n log.error(error instanceof Error ? error.message : 'Unknown error')\n process.exit(1)\n }\n\n // Modify Payload configuration\n s.start('Checking Payload configuration...')\n const modResult = await ensurePayloadFigmaConfig(fullPath, 'pnpm', {\n contentSystemId,\n })\n\n if (!modResult.success) {\n s.stop(pc.red('✗ Configuration check failed'))\n displayManualInstructions(modResult.error || 'Unknown error')\n process.exit(1)\n }\n\n if (modResult.modified) {\n s.stop(pc.green('✓ Payload configuration updated'))\n if (modResult.changes.length > 0) {\n modResult.changes.forEach((change) => log.debug(pc.dim(` → ${change}`)))\n }\n } else {\n s.stop(pc.green('✓ Payload configuration valid'))\n }\n\n // Display warnings if any\n if (modResult.warnings && modResult.warnings.length > 0) {\n modResult.warnings.forEach((warning) => {\n p.log.warn(pc.yellow(`⚠ ${warning}`))\n })\n }\n\n // Write environment variables to .env file\n try {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_CONTENT_SYSTEM_ID', contentSystemId)\n log.debug(`Added FIGMA_CONTENT_SYSTEM_ID to .env file`)\n\n const env = getEnvironment()\n if (env !== 'production') {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_ENV', env)\n log.debug(`Added FIGMA_ENV=${env} to .env file`)\n }\n\n if (datasetInfo) {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_TENANT_ID', datasetInfo.tenantId)\n await addOrUpdateEnvVar(fullPath, 'FIGMA_OAUTH_CLIENT_ID', datasetInfo.oauthClientId)\n await addOrUpdateEnvVar(\n fullPath,\n 'FIGMA_OAUTH_CLIENT_SECRET',\n datasetInfo.oauthClientSecret,\n )\n log.debug(\n `Added FIGMA_TENANT_ID, FIGMA_OAUTH_CLIENT_ID, FIGMA_OAUTH_CLIENT_SECRET to .env file`,\n )\n }\n } catch (error) {\n p.log.warn(\n pc.yellow(\n `⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n ),\n )\n }\n\n // Generate import map to prevent errors on first pnpm dev\n await runScript(fullPath, 'generate:importmap', 'pnpm')\n\n // Generate project token (unless skipping auth)\n if (!options.skipAuth) {\n await generateProjectTokenWithFeedback(tokenStore, contentSystemId, s)\n }\n\n // Initialize git repository (after all files including lock file are ready)\n initializeGitRepo(fullPath)\n\n // Success message for NEW project\n p.log.step(pc.bgGreen(pc.black(' Project created successfully! ')))\n\n const relativePath = path.relative(process.cwd(), fullPath)\n const nextSteps: string[] = []\n\n // Only show cd command if user needs to navigate\n if (relativePath && relativePath !== '.') {\n nextSteps.push(`cd ${relativePath}`)\n }\n\n nextSteps.push(\n 'pnpm dev or follow directions in README.md',\n '',\n 'Documentation:',\n '- Getting Started: https://payloadcms.com/docs/getting-started/what-is-payload',\n '- Configuration: https://payloadcms.com/docs/configuration/overview',\n )\n\n p.note(nextSteps.join('\\n'), 'Next Steps')\n p.outro(pc.green('✓ Done'))\n }\n}\n"],"names":["p","fs","path","pc","getDatasetInfo","FigmaApiError","getValidAccessToken","getValidProjectToken","ProjectTokenError","getTokenStore","getEnvironment","ensureGitignore","addOrUpdateEnvVar","isDebug","applyLambdaModifications","log","displayManualInstructions","ensurePayloadFigmaConfig","runScript","detectPayloadProject","hasRequiredDependencies","initializeGitRepo","installDependencies","isInProjectDirectory","scaffoldProject","validatePayloadVersion","checkForUpdates","getOwnVersion","loginCommand","generateProjectTokenWithFeedback","tokenStore","contentSystemId","spinner","start","projectToken","stop","green","yellow","error","warning","message","note","Error","fetchDatasetInfo","accessToken","datasetId","debug","datasetInfo","oauthClientId","oauthClientSecret","tenantId","initCommand","options","currentVersion","s","skipAuth","warn","hasValidTokens","token","showNextSteps","newToken","process","exit","red","id","dim","isInProject","projectInfo","hasPayload","payloadVersion","success","hasDeps","cwd","shouldInstall","confirm","initialValue","isCancel","packageManager","modResult","modified","changes","length","forEach","change","warnings","env","shouldAddPayload","cancel","outro","nextSteps","filter","Boolean","join","projectPathInput","text","placeholder","validate","value","undefined","projectPath","fullPath","resolve","projectName","name","basename","mkdir","recursive","step","bgGreen","black","relativePath","relative","push"],"mappings":"AAAA,YAAYA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C;YAE1F;QACF,EAAE,OAAOR,OAAO;YACdtC,EAAEe,GAAG,CAACyC,IAAI,CACRrD,GAAGkC,MAAM,CACP,CAAC,8BAA8B,EAAEC,iBAAiBI,QAAQJ,MAAME,OAAO,GAAG,iBAAiB;QAGjG;QAEA,0DAA0D;QAC1D,MAAMtB,UAAUkF,UAAU,sBAAsB;QAEhD,gDAAgD;QAChD,IAAI,CAAChD,QAAQG,QAAQ,EAAE;YACrB,MAAM1B,iCAAiCC,YAAYC,iBAAiBuB;QACtE;QAEA,4EAA4E;QAC5EjC,kBAAkB+E;QAElB,kCAAkC;QAClCpG,EAAEe,GAAG,CAAC4F,IAAI,CAACxG,GAAGyG,OAAO,CAACzG,GAAG0G,KAAK,CAAC;QAE/B,MAAMC,eAAe5G,KAAK6G,QAAQ,CAAClD,QAAQW,GAAG,IAAI4B;QAClD,MAAMX,YAAsB,EAAE;QAE9B,iDAAiD;QACjD,IAAIqB,gBAAgBA,iBAAiB,KAAK;YACxCrB,UAAUuB,IAAI,CAAC,CAAC,GAAG,EAAEF,cAAc;QACrC;QAEArB,UAAUuB,IAAI,CACZ,8CACA,IACA,kBACA,kFACA;QAGFhH,EAAEyC,IAAI,CAACgD,UAAUG,IAAI,CAAC,OAAO;QAC7B5F,EAAEwF,KAAK,CAACrF,GAAGiC,KAAK,CAAC;IACnB;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/init.ts"],"sourcesContent":["import * as p from '@clack/prompts'\nimport fs from 'fs/promises'\nimport path from 'path'\nimport pc from 'picocolors'\n\nimport type { TokenStore } from '../auth/token-store.js'\n\nimport { getDatasetInfo } from '../api/control-plane.js'\nimport { FigmaApiError } from '../api/figma-api.js'\nimport { getValidAccessToken } from '../auth/oauth-flow.js'\nimport { getValidProjectToken, ProjectTokenError } from '../auth/project-token.js'\nimport { getTokenStore } from '../auth/token-store.js'\nimport { getEnvironment } from '../constants.js'\nimport { ensureGitignore } from '../utils/config.js'\nimport { addOrUpdateEnvVar } from '../utils/env-management.js'\nimport { isDebug } from '../utils/is-debug.js'\nimport { applyLambdaModifications } from '../utils/lambda-config.js'\nimport * as log from '../utils/log.js'\nimport {\n detectPackageManagerFromEnvironment,\n getRunCommand,\n resolvePackageManager,\n} from '../utils/package-manager.js'\nimport {\n displayManualInstructions,\n ensurePayloadFigmaConfig,\n} from '../utils/payload-config-modifier.js'\nimport { runScript } from '../utils/payload-package-check.js'\nimport {\n detectPayloadProject,\n hasRequiredDependencies,\n initializeGitRepo,\n installDependencies,\n isInProjectDirectory,\n scaffoldProject,\n validatePayloadVersion,\n} from '../utils/project.js'\nimport { checkForUpdates, getOwnVersion } from '../utils/version-check.js'\nimport { loginCommand } from './login.js'\n\n/**\n * Options for init command\n */\nexport interface InitCommandOptions {\n /** Enable debug mode */\n debug?: boolean\n /** Force reconfiguration of existing project */\n force?: boolean\n /** Content System ID to use */\n id?: string\n /** Project name (for scaffolding) */\n name?: string\n /** Skip authentication check (for testing/development) */\n skipAuth?: boolean\n /** Skip prompts and use defaults where possible */\n yes?: boolean\n}\n\n/**\n * Generate and store project token for a content system\n * Non-blocking - will show warning but not exit on failure\n * Only shows feedback if DEBUG mode is enabled, otherwise runs silently\n *\n * @param tokenStore - Token store instance\n * @param contentSystemId - Content System ID to generate token for\n * @param spinner - Clack spinner instance for status updates (only used in debug mode)\n */\nasync function generateProjectTokenWithFeedback(\n tokenStore: TokenStore,\n contentSystemId: string,\n spinner: ReturnType<typeof p.spinner>,\n): Promise<void> {\n if (isDebug()) {\n spinner.start('Generating project token...')\n }\n\n try {\n const projectToken = await getValidProjectToken(tokenStore, contentSystemId)\n if (isDebug()) {\n if (projectToken) {\n spinner.stop(pc.green('✓ Project token generated'))\n } else {\n spinner.stop(pc.yellow('⚠ Project token not generated (authentication required)'))\n }\n }\n } catch (error) {\n if (isDebug()) {\n spinner.stop(pc.yellow('⚠ Project token generation failed'))\n }\n // Always show failures, even without debug\n if (error instanceof ProjectTokenError || error instanceof FigmaApiError) {\n log.warning(error.message)\n p.note(\n 'Project token is used for authenticating to the Content API.\\nYou can continue without it, but may need to regenerate later.',\n 'Note',\n )\n } else {\n log.warning(\n `Unable to retrieve project token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n // Don't exit - token generation failure shouldn't block initialization\n }\n}\n\n/**\n * Fetch dataset info from the API\n * Throws on error - caller must handle\n */\nasync function fetchDatasetInfo(\n accessToken: string,\n datasetId: string,\n): Promise<{ oauthClientId: string; oauthClientSecret: string; tenantId: string }> {\n log.debug('Fetching dataset info...')\n\n const datasetInfo = await getDatasetInfo(accessToken, datasetId)\n log.debug('Dataset info retrieved successfully')\n return {\n oauthClientId: datasetInfo.oauthClientId,\n oauthClientSecret: datasetInfo.oauthClientSecret,\n tenantId: datasetInfo.tenantId,\n }\n}\n\n/**\n * Handle the `init` command\n *\n * Sets up a project by:\n * 1. Checking authentication\n * 2. Detecting/scaffolding Payload project\n * 3. Fetching tenant details\n * 4. Storing configuration\n *\n * @param options - Command options\n */\nexport async function initCommand(options: InitCommandOptions): Promise<void> {\n // Check for outdated version (non-blocking)\n const currentVersion = await getOwnVersion()\n await checkForUpdates(currentVersion)\n\n // Check authentication\n const tokenStore = getTokenStore(getEnvironment())\n const s = p.spinner()\n\n if (options.skipAuth) {\n // Skip authentication for testing/development\n p.log.warn(pc.yellow('Skipping authentication (--skip-auth mode)'))\n } else {\n try {\n // Check for valid cached tokens first (no API call needed)\n if (!tokenStore.hasValidTokens()) {\n // Need to refresh or authenticate - show spinner for API call\n s.start('Checking authentication...')\n const token = await getValidAccessToken(tokenStore)\n if (!token) {\n s.stop('Authentication required to continue')\n\n // Run login command\n await loginCommand({ showNextSteps: false })\n\n // Get token after auth\n const newToken = await getValidAccessToken(tokenStore)\n if (!newToken) {\n p.log.error('Authentication failed')\n process.exit(1)\n }\n } else {\n s.stop(pc.green('✓ Authenticated'))\n }\n }\n } catch (error) {\n s.stop(pc.red('✗ Authentication failed'))\n log.error(error instanceof Error ? error.message : 'Unknown error')\n p.note('Run `figma auth` to authenticate', 'Tip')\n process.exit(1)\n }\n }\n\n // Note: We no longer check for figma.config.json here\n // Instead, the AST detection will check if figma object already exists in payload.config.ts\n // and skip modification if it does (unless --force is used)\n\n // Step 3: Get Content System ID (required argument)\n log.debug('Configuring Project...')\n\n if (!options.id) {\n p.log.error('Content System ID is required. Use --id <content_system_id>')\n process.exit(1)\n }\n\n const contentSystemId = options.id\n\n // Fetch dataset info (required - will fail if feature not enabled)\n let datasetInfo: { oauthClientId: string; oauthClientSecret: string; tenantId: string } | null =\n null\n if (!options.skipAuth) {\n const accessToken = await getValidAccessToken(tokenStore)\n if (accessToken) {\n try {\n datasetInfo = await fetchDatasetInfo(accessToken, contentSystemId)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n p.log.error(\n pc.red(`✗ Unable to fetch dataset info for content system \"${contentSystemId}\"`),\n )\n p.log.error(pc.dim(`Details: ${message}`))\n p.note(\n 'This may indicate the CMS feature is not enabled for your account.\\n' +\n 'Contact support if you believe this is an error.',\n 'Error',\n )\n process.exit(1)\n }\n }\n }\n\n // Step 4: Detect or scaffold Payload project\n const isInProject = await isInProjectDirectory()\n\n if (isInProject) {\n // ===== EXISTING PROJECT FLOW =====\n log.debug('Project directory detected')\n\n // Detect Payload\n const projectInfo = await detectPayloadProject()\n const packageManager = await resolvePackageManager(process.cwd())\n\n if (projectInfo.hasPayload) {\n // Validate existing Payload version\n if (projectInfo.payloadVersion && !validatePayloadVersion(projectInfo.payloadVersion)) {\n p.log.warn(\n pc.yellow(\n `Payload version ${projectInfo.payloadVersion} detected. Version 3.x is required.`,\n ),\n )\n p.note('Upgrade to Payload 3.x before continuing', 'Action Required')\n process.exit(1)\n }\n\n p.log.success(pc.green(`✓ Payload ${projectInfo.payloadVersion || 'detected'}`))\n\n // Check dependencies\n s.start('Checking dependencies...')\n const hasDeps = await hasRequiredDependencies(process.cwd())\n s.stop(pc.green('✓ Dependencies checked'))\n\n if (!hasDeps) {\n const shouldInstall = await p.confirm({\n initialValue: true,\n message: 'Install dependencies now?',\n })\n\n if (!p.isCancel(shouldInstall) && shouldInstall) {\n s.start('Installing dependencies...')\n await installDependencies(process.cwd(), packageManager)\n s.stop(pc.green('✓ Dependencies installed'))\n }\n }\n\n s.start('Checking Payload configuration...')\n const modResult = await ensurePayloadFigmaConfig(process.cwd(), packageManager, {\n contentSystemId,\n })\n\n if (!modResult.success) {\n s.stop(pc.red('✗ Configuration check failed'))\n displayManualInstructions(modResult.error || 'Unknown error', packageManager)\n process.exit(1)\n }\n\n if (modResult.modified) {\n s.stop(pc.green('✓ Payload configuration updated'))\n if (modResult.changes.length > 0) {\n modResult.changes.forEach((change) => log.debug(pc.dim(` → ${change}`)))\n }\n } else {\n s.stop(pc.green('✓ Payload configuration valid'))\n }\n\n // Display warnings if any\n if (modResult.warnings && modResult.warnings.length > 0) {\n modResult.warnings.forEach((warning) => {\n p.log.warn(pc.yellow(`⚠ ${warning}`))\n })\n }\n\n // Write environment variables to .env file\n try {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_CONTENT_SYSTEM_ID', contentSystemId)\n log.debug(`Added FIGMA_CONTENT_SYSTEM_ID to .env file`)\n\n const env = getEnvironment()\n if (env !== 'production') {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_ENV', env)\n log.debug(`Added FIGMA_ENV=${env} to .env file`)\n }\n\n if (datasetInfo) {\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_TENANT_ID', datasetInfo.tenantId)\n await addOrUpdateEnvVar(process.cwd(), 'FIGMA_OAUTH_CLIENT_ID', datasetInfo.oauthClientId)\n await addOrUpdateEnvVar(\n process.cwd(),\n 'FIGMA_OAUTH_CLIENT_SECRET',\n datasetInfo.oauthClientSecret,\n )\n log.debug(\n `Added FIGMA_TENANT_ID, FIGMA_OAUTH_CLIENT_ID, FIGMA_OAUTH_CLIENT_SECRET to .env file`,\n )\n }\n } catch (error) {\n p.log.warn(\n pc.yellow(\n `⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n ),\n )\n }\n } else {\n // Has package.json but no Payload - offer to add Payload\n p.log.warn(pc.yellow('⚠ No Payload detected in this project'))\n\n const shouldAddPayload = await p.confirm({\n initialValue: true,\n message: 'Would you like to add Payload to this project?',\n })\n\n if (p.isCancel(shouldAddPayload)) {\n p.cancel('Operation cancelled')\n process.exit(0)\n }\n\n if (!shouldAddPayload) {\n p.log.error('Payload is required to use Figma CMS')\n process.exit(1)\n }\n\n // TODO: Add Payload to existing project (future enhancement)\n p.log.error('Adding Payload to existing projects is not yet supported')\n p.note('Create a new project or manually add Payload dependencies', 'Action Required')\n process.exit(1)\n }\n\n // Generate import map to prevent errors on first dev run\n await runScript(process.cwd(), 'generate:importmap', packageManager)\n\n // Apply Lambda modifications (run.sh, standalone output, lambda:buildzip script)\n await applyLambdaModifications(process.cwd(), packageManager)\n\n // Ensure .gitignore has required entries\n await ensureGitignore(process.cwd(), ['.env', '.env.local', 'lambda.zip'])\n\n // Generate project token (unless skipping auth)\n if (!options.skipAuth) {\n await generateProjectTokenWithFeedback(tokenStore, contentSystemId, s)\n }\n\n // Success message for existing project\n p.outro(pc.green('✓ Project initialized successfully!'))\n\n const nextSteps = [`Start development server: \\`${getRunCommand(packageManager)} dev\\``].filter(\n Boolean,\n )\n\n p.note(nextSteps.join('\\n'), 'Next Steps')\n } else {\n // ===== NEW PROJECT FLOW =====\n // p.log.info('No project detected - Creating New Project')\n\n // Prompt for path\n const projectPathInput = await p.text({\n initialValue: './',\n message: 'Enter path to create project:',\n placeholder: './my-cms-project',\n validate: (value) => {\n if (!value) {\n return 'Path is required'\n }\n // Allow relative or absolute paths\n return undefined\n },\n })\n\n if (p.isCancel(projectPathInput)) {\n p.cancel('Operation cancelled')\n process.exit(0)\n }\n\n const projectPath = projectPathInput\n const fullPath = path.resolve(process.cwd(), projectPath)\n\n // Get project name from path or prompt\n const projectName = options.name || path.basename(fullPath)\n const packageManager = detectPackageManagerFromEnvironment()\n\n // Create directory\n try {\n await fs.mkdir(fullPath, { recursive: true })\n } catch (error) {\n p.log.error(\n `Failed to create directory: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n process.exit(1)\n }\n\n // Scaffold project\n s.start('Downloading template from GitHub...')\n try {\n await scaffoldProject(fullPath, projectName, packageManager)\n s.stop(pc.green('✓ Template downloaded'))\n\n s.start('Installing dependencies...')\n await installDependencies(fullPath, packageManager)\n s.stop(pc.green('✓ Dependencies installed'))\n } catch (error) {\n s.stop(pc.red('✗ Failed'))\n log.error(error instanceof Error ? error.message : 'Unknown error')\n process.exit(1)\n }\n\n // Modify Payload configuration\n s.start('Checking Payload configuration...')\n const modResult = await ensurePayloadFigmaConfig(fullPath, packageManager, {\n contentSystemId,\n })\n\n if (!modResult.success) {\n s.stop(pc.red('✗ Configuration check failed'))\n displayManualInstructions(modResult.error || 'Unknown error', packageManager)\n process.exit(1)\n }\n\n if (modResult.modified) {\n s.stop(pc.green('✓ Payload configuration updated'))\n if (modResult.changes.length > 0) {\n modResult.changes.forEach((change) => log.debug(pc.dim(` → ${change}`)))\n }\n } else {\n s.stop(pc.green('✓ Payload configuration valid'))\n }\n\n // Display warnings if any\n if (modResult.warnings && modResult.warnings.length > 0) {\n modResult.warnings.forEach((warning) => {\n p.log.warn(pc.yellow(`⚠ ${warning}`))\n })\n }\n\n // Write environment variables to .env file\n try {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_CONTENT_SYSTEM_ID', contentSystemId)\n log.debug(`Added FIGMA_CONTENT_SYSTEM_ID to .env file`)\n\n const env = getEnvironment()\n if (env !== 'production') {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_ENV', env)\n log.debug(`Added FIGMA_ENV=${env} to .env file`)\n }\n\n if (datasetInfo) {\n await addOrUpdateEnvVar(fullPath, 'FIGMA_TENANT_ID', datasetInfo.tenantId)\n await addOrUpdateEnvVar(fullPath, 'FIGMA_OAUTH_CLIENT_ID', datasetInfo.oauthClientId)\n await addOrUpdateEnvVar(\n fullPath,\n 'FIGMA_OAUTH_CLIENT_SECRET',\n datasetInfo.oauthClientSecret,\n )\n log.debug(\n `Added FIGMA_TENANT_ID, FIGMA_OAUTH_CLIENT_ID, FIGMA_OAUTH_CLIENT_SECRET to .env file`,\n )\n }\n } catch (error) {\n p.log.warn(\n pc.yellow(\n `⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`,\n ),\n )\n }\n\n // Generate import map to prevent errors on first dev run\n await runScript(fullPath, 'generate:importmap', packageManager)\n\n // Generate project token (unless skipping auth)\n if (!options.skipAuth) {\n await generateProjectTokenWithFeedback(tokenStore, contentSystemId, s)\n }\n\n // Initialize git repository (after all files including lock file are ready)\n initializeGitRepo(fullPath)\n\n // Success message for NEW project\n p.log.step(pc.bgGreen(pc.black(' Project created successfully! ')))\n\n const relativePath = path.relative(process.cwd(), fullPath)\n const nextSteps: string[] = []\n\n // Only show cd command if user needs to navigate\n if (relativePath && relativePath !== '.') {\n nextSteps.push(`cd ${relativePath}`)\n }\n\n nextSteps.push(\n `${getRunCommand(packageManager)} dev or follow directions in README.md`,\n '',\n 'Documentation:',\n '- Getting Started: https://payloadcms.com/docs/getting-started/what-is-payload',\n '- Configuration: https://payloadcms.com/docs/configuration/overview',\n )\n\n p.note(nextSteps.join('\\n'), 'Next Steps')\n p.outro(pc.green('✓ Done'))\n }\n}\n"],"names":["p","fs","path","pc","getDatasetInfo","FigmaApiError","getValidAccessToken","getValidProjectToken","ProjectTokenError","getTokenStore","getEnvironment","ensureGitignore","addOrUpdateEnvVar","isDebug","applyLambdaModifications","log","detectPackageManagerFromEnvironment","getRunCommand","resolvePackageManager","displayManualInstructions","ensurePayloadFigmaConfig","runScript","detectPayloadProject","hasRequiredDependencies","initializeGitRepo","installDependencies","isInProjectDirectory","scaffoldProject","validatePayloadVersion","checkForUpdates","getOwnVersion","loginCommand","generateProjectTokenWithFeedback","tokenStore","contentSystemId","spinner","start","projectToken","stop","green","yellow","error","warning","message","note","Error","fetchDatasetInfo","accessToken","datasetId","debug","datasetInfo","oauthClientId","oauthClientSecret","tenantId","initCommand","options","currentVersion","s","skipAuth","warn","hasValidTokens","token","showNextSteps","newToken","process","exit","red","id","dim","isInProject","projectInfo","packageManager","cwd","hasPayload","payloadVersion","success","hasDeps","shouldInstall","confirm","initialValue","isCancel","modResult","modified","changes","length","forEach","change","warnings","env","shouldAddPayload","cancel","outro","nextSteps","filter","Boolean","join","projectPathInput","text","placeholder","validate","value","undefined","projectPath","fullPath","resolve","projectName","name","basename","mkdir","recursive","step","bgGreen","black","relativePath","relative","push"],"mappings":"AAAA,YAAYA,OAAO,iBAAgB;AACnC,OAAOC,QAAQ,cAAa;AAC5B,OAAOC,UAAU,OAAM;AACvB,OAAOC,QAAQ,aAAY;AAI3B,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,aAAa,QAAQ,sBAAqB;AACnD,SAASC,mBAAmB,QAAQ,wBAAuB;AAC3D,SAASC,oBAAoB,EAAEC,iBAAiB,QAAQ,2BAA0B;AAClF,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,cAAc,QAAQ,kBAAiB;AAChD,SAASC,eAAe,QAAQ,qBAAoB;AACpD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,wBAAwB,QAAQ,4BAA2B;AACpE,YAAYC,SAAS,kBAAiB;AACtC,SACEC,mCAAmC,EACnCC,aAAa,EACbC,qBAAqB,QAChB,8BAA6B;AACpC,SACEC,yBAAyB,EACzBC,wBAAwB,QACnB,sCAAqC;AAC5C,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,oBAAoB,EACpBC,uBAAuB,EACvBC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,EACfC,sBAAsB,QACjB,sBAAqB;AAC5B,SAASC,eAAe,EAAEC,aAAa,QAAQ,4BAA2B;AAC1E,SAASC,YAAY,QAAQ,aAAY;AAoBzC;;;;;;;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rC;QAEArB,UAAUuB,IAAI,CACZ,GAAGlG,cAAcsD,gBAAgB,sCAAsC,CAAC,EACxE,IACA,kBACA,kFACA;QAGFvE,EAAE4C,IAAI,CAACgD,UAAUG,IAAI,CAAC,OAAO;QAC7B/F,EAAE2F,KAAK,CAACxF,GAAGoC,KAAK,CAAC;IACnB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/db-content-api/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAcnB,kBAAkB,EA+BnB,MAAM,SAAS,CAAA;AAEhB,OAAO,YAAY,MAAM,eAAe,CAAA;AAIxC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kCAAkC,CAAA;AAK7D,OAAO,EAAE,KAAK,QAAQ,EAA+C,MAAM,qBAAqB,CAAA;AAOhG,KAAK,iBAAiB,GAAG;IACvB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,IAAI,EAAE,QAAQ,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,MAAM,CAAA;CACZ,CAAA;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,QAAQ,CAAA;IACd,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAClC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,CAAA;IAC9C,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,MAAM,CAAA;CACZ,GAAG,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/db-content-api/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAcnB,kBAAkB,EA+BnB,MAAM,SAAS,CAAA;AAEhB,OAAO,YAAY,MAAM,eAAe,CAAA;AAIxC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kCAAkC,CAAA;AAK7D,OAAO,EAAE,KAAK,QAAQ,EAA+C,MAAM,qBAAqB,CAAA;AAOhG,KAAK,iBAAiB,GAAG;IACvB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,IAAI,EAAE,QAAQ,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,MAAM,CAAA;CACZ,CAAA;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,QAAQ,CAAA;IACd,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAClC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,CAAA;IAC9C,eAAe,EAAE,MAAM,CAAA;IACvB,GAAG,EAAE,MAAM,CAAA;CACZ,GAAG,mBAAmB,CAAA;AAmqBvB,eAAO,MAAM,iBAAiB,SAAU,iBAAiB,KAAG,kBAyD1D,CAAA"}
|
|
@@ -8,7 +8,7 @@ import { createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js
|
|
|
8
8
|
import { dataToContentAPI } from './utilities/data/index.js';
|
|
9
9
|
import { convertPayloadJoinsToContentAPI } from './utilities/joins.js';
|
|
10
10
|
import { addFallbackLocale } from './utilities/locale/index.js';
|
|
11
|
-
import { buildMeta } from './utilities/meta/
|
|
11
|
+
import { buildMeta } from './utilities/meta/buildMeta.js';
|
|
12
12
|
import { convertPayloadWhereToContentAPI } from './utilities/where.js';
|
|
13
13
|
async function syncCollections() {
|
|
14
14
|
let existingIds;
|
|
@@ -126,7 +126,8 @@ async function find(args) {
|
|
|
126
126
|
async function findVersions(args) {
|
|
127
127
|
const sortWithFallback = addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection);
|
|
128
128
|
const whereClause = convertPayloadWhereToContentAPI(args.where ?? {}, {
|
|
129
|
-
parentToDocumentId: true
|
|
129
|
+
parentToDocumentId: true,
|
|
130
|
+
stripVersionPrefix: true
|
|
130
131
|
});
|
|
131
132
|
const locale = addFallbackLocale(args.locale, this.payload);
|
|
132
133
|
const { data: response, error } = await this.client.POST('/api/v0/document_versions:find', {
|
|
@@ -192,10 +193,13 @@ async function createVersion(args) {
|
|
|
192
193
|
collection: args.collectionSlug,
|
|
193
194
|
contentSystemId: this.contentSystemId,
|
|
194
195
|
versionDoc: {
|
|
196
|
+
createdAt: args.createdAt,
|
|
195
197
|
latest: !args.autosave,
|
|
196
198
|
parent: String(args.parent),
|
|
199
|
+
updatedAt: args.updatedAt,
|
|
197
200
|
version: dataToContentAPI(this.payload, args.collectionSlug, args.versionData, {
|
|
198
|
-
applyDefaults: true
|
|
201
|
+
applyDefaults: true,
|
|
202
|
+
publishedLocale: args.publishedLocale
|
|
199
203
|
})
|
|
200
204
|
}
|
|
201
205
|
}
|
|
@@ -215,6 +219,8 @@ async function updateVersion(args) {
|
|
|
215
219
|
}
|
|
216
220
|
};
|
|
217
221
|
const locale = addFallbackLocale(args.locale, this.payload);
|
|
222
|
+
// versionData contains version metadata plus nested version content
|
|
223
|
+
const { publishedLocale, version, ...versionMeta } = args.versionData;
|
|
218
224
|
const { data: response, error } = await this.client.POST('/api/v0/document_versions:update', {
|
|
219
225
|
body: {
|
|
220
226
|
collection: args.collection,
|
|
@@ -222,9 +228,17 @@ async function updateVersion(args) {
|
|
|
222
228
|
createOnMissing: false,
|
|
223
229
|
locale,
|
|
224
230
|
versionDoc: {
|
|
225
|
-
|
|
231
|
+
createdAt: versionMeta.createdAt,
|
|
232
|
+
latest: versionMeta.latest,
|
|
233
|
+
parent: versionMeta.parent != null ? String(versionMeta.parent) : undefined,
|
|
234
|
+
updatedAt: versionMeta.updatedAt,
|
|
235
|
+
version: dataToContentAPI(this.payload, args.collection, version, {
|
|
236
|
+
publishedLocale
|
|
237
|
+
})
|
|
226
238
|
},
|
|
227
|
-
where: convertPayloadWhereToContentAPI(where
|
|
239
|
+
where: convertPayloadWhereToContentAPI(where, {
|
|
240
|
+
stripVersionPrefix: true
|
|
241
|
+
}),
|
|
228
242
|
...buildMeta(this.payload, {
|
|
229
243
|
collection: args.collection,
|
|
230
244
|
locale,
|
|
@@ -254,7 +268,9 @@ async function deleteVersions(args) {
|
|
|
254
268
|
collection: args.collection,
|
|
255
269
|
contentSystemId: this.contentSystemId,
|
|
256
270
|
locale,
|
|
257
|
-
where: convertPayloadWhereToContentAPI(args.where
|
|
271
|
+
where: convertPayloadWhereToContentAPI(args.where, {
|
|
272
|
+
stripVersionPrefix: true
|
|
273
|
+
}),
|
|
258
274
|
...buildMeta(this.payload, {
|
|
259
275
|
collection: args.collection,
|
|
260
276
|
locale,
|
|
@@ -473,7 +489,9 @@ async function countVersions(args) {
|
|
|
473
489
|
collection: args.collection,
|
|
474
490
|
contentSystemId: this.contentSystemId,
|
|
475
491
|
locale,
|
|
476
|
-
where: convertPayloadWhereToContentAPI(args.where
|
|
492
|
+
where: convertPayloadWhereToContentAPI(args.where, {
|
|
493
|
+
stripVersionPrefix: true
|
|
494
|
+
}),
|
|
477
495
|
...buildMeta(this.payload, {
|
|
478
496
|
collection: args.collection,
|
|
479
497
|
locale,
|
|
@@ -588,6 +606,7 @@ function createGlobalVersion(args) {
|
|
|
588
606
|
collectionSlug: getGlobalSlug(args.globalSlug),
|
|
589
607
|
createdAt: args.createdAt,
|
|
590
608
|
parent: args.globalSlug,
|
|
609
|
+
publishedLocale: args.publishedLocale,
|
|
591
610
|
updatedAt: args.updatedAt,
|
|
592
611
|
versionData: args.versionData
|
|
593
612
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/db-content-api/index.ts"],"sourcesContent":["import type {\n BaseDatabaseAdapter,\n Count,\n CountArgs,\n CountGlobalVersionArgs,\n CountGlobalVersions,\n CountVersions,\n Create,\n CreateArgs,\n CreateGlobal,\n CreateGlobalArgs,\n CreateGlobalVersion,\n CreateGlobalVersionArgs,\n CreateVersion,\n CreateVersionArgs,\n DatabaseAdapterObj,\n DeleteMany,\n DeleteManyArgs,\n DeleteOne,\n DeleteOneArgs,\n DeleteVersions,\n DeleteVersionsArgs,\n Find,\n FindArgs,\n FindGlobal,\n FindGlobalArgs,\n FindGlobalVersions,\n FindGlobalVersionsArgs,\n FindOne,\n FindOneArgs,\n FindVersions,\n FindVersionsArgs,\n QueryDrafts,\n QueryDraftsArgs,\n UpdateGlobal,\n UpdateGlobalArgs,\n UpdateGlobalVersion,\n UpdateGlobalVersionArgs,\n UpdateMany,\n UpdateManyArgs,\n UpdateOne,\n UpdateOneArgs,\n UpdateVersion,\n UpdateVersionArgs,\n Upsert,\n UpsertArgs,\n} from 'payload'\n\nimport createClient from 'openapi-fetch'\nimport { createDatabaseAdapter } from 'payload'\nimport { v4 as uuid } from 'uuid'\n\nimport type { paths } from './generated/content-api-types.js'\n\nimport { getGlobalSlug } from './temp-utilities/slug.js'\nimport { addFallbackSort } from './temp-utilities/sorting.js'\nimport { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js'\nimport { type AuthMode, createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js'\nimport { dataToContentAPI } from './utilities/data/index.js'\nimport { convertPayloadJoinsToContentAPI } from './utilities/joins.js'\nimport { addFallbackLocale } from './utilities/locale/index.js'\nimport { buildMeta } from './utilities/meta/index.js'\nimport { convertPayloadWhereToContentAPI } from './utilities/where.js'\n\ntype ContentAPIOptions = {\n allowIDOnCreate?: boolean\n auth: AuthMode\n contentSystemId: string\n url: string\n}\n\nexport type ContentAPIAdapter = {\n auth: AuthMode\n clearDatabase: () => Promise<void>\n client: ReturnType<typeof createClient<paths>>\n contentSystemId: string\n url: string\n} & BaseDatabaseAdapter\n\nasync function syncCollections(this: ContentAPIAdapter) {\n let existingIds: Set<string>\n try {\n const { data: response, error } = await this.client.GET(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n if (!response) {\n throw new Error('No response from collections endpoint')\n }\n\n existingIds = new Set(response.data.map((c) => c.id))\n this.payload.logger.info(`Found ${existingIds.size} existing collections`)\n } catch (error) {\n this.payload.logger.warn(\n `Failed to fetch collections, will attempt to create all: ${(error as Error).message}`,\n )\n existingIds = new Set()\n }\n\n for (const collection of this.payload.config.collections) {\n if (!existingIds.has(collection.slug)) {\n await createCollection.call(this, collection.slug)\n }\n }\n\n for (const global of this.payload.config.globals || []) {\n const globalId = `_global-${global.slug}`\n if (!existingIds.has(globalId)) {\n await createCollection.call(this, globalId)\n }\n }\n}\n\nasync function init(this: ContentAPIAdapter) {\n if (this.auth.mode === 'apiKey') {\n this.payload.logger.info('Using API Key authentication')\n } else if (this.auth.mode === 'tokenStore') {\n this.payload.logger.info('Using TokenStore authentication (local dev)')\n } else {\n this.payload.logger.info('Using Dev JWT authentication (testing)')\n }\n\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n await this.clearDatabase()\n }\n\n await syncCollections.call(this)\n}\n\nasync function createCollection(this: ContentAPIAdapter, collectionId: string) {\n try {\n const { error } = await this.client.POST(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n body: { id: collectionId },\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n this.payload.logger.info(`Created collection: ${collectionId}`)\n } catch (error) {\n const errorMessage = (error as Error).message\n if (!errorMessage.includes('already exists') && !errorMessage.includes('409')) {\n this.payload.logger.warn(`Failed to create collection ${collectionId}: ${errorMessage}`)\n }\n }\n}\n\nasync function findMany(\n this: ContentAPIAdapter,\n {\n collection,\n joins,\n limit,\n locale: localeArg,\n page,\n pagination: _pagination,\n sort,\n where,\n // Not yet passed to Content API:\n // - select: supported by Content API, pass-through possible\n // Not supported by Content API:\n // - draftsEnabled, versions, projection\n }: Pick<FindArgs, 'joins' | 'locale' | 'pagination' | 'sort' | 'where'> &\n Required<Pick<FindArgs, 'collection' | 'limit' | 'page'>>,\n) {\n const locale = addFallbackLocale(localeArg, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:find', {\n body: {\n collection,\n contentSystemId: this.contentSystemId,\n join: convertPayloadJoinsToContentAPI(this.payload, collection, joins),\n limit,\n locale,\n page: page ?? 1,\n sort: addFallbackSort(sort, this.payload, collection),\n where: convertPayloadWhereToContentAPI(where ?? {}),\n ...buildMeta(this.payload, { collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API findMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findMany')\n }\n\n return unwrapFindResponse(this.payload, response.result, collection)\n}\n\nasync function find(this: ContentAPIAdapter, args: FindArgs) {\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === args.collection)\n return findMany.call(this, {\n collection: args.collection,\n joins: args.joins,\n // TODO: FindArgs.limit should be 'number' not 'number | undefined'\n // is sanitized by Payload Core before calling the adapter (defaults to 10 or 0 based on pagination)\n limit: args.limit!,\n locale: args.locale,\n page: args.page ?? 1,\n pagination: args.pagination,\n sort: args.sort || collectionConfig?.defaultSort,\n where: args.where,\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nasync function findVersions(this: ContentAPIAdapter, args: Omit<FindVersionsArgs, 'skip'>) {\n const sortWithFallback = addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection)\n\n const whereClause = convertPayloadWhereToContentAPI(args.where ?? {}, {\n parentToDocumentId: true,\n })\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:find', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n // TODO: FindVersionsArgs.limit should be 'number' not 'number | undefined'\n // is sanitized by Payload Core before calling the adapter (defaults to 10 or 0 based on pagination)\n limit: args.limit!,\n locale,\n page: args.page ?? 1,\n sort: sortWithFallback,\n where: whereClause,\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API findVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findVersions')\n }\n\n return unwrapFindResponse(this.payload, response.result, args.collection)\n}\n\nasync function queryDrafts(this: ContentAPIAdapter, args: QueryDraftsArgs) {\n const versionsResult = await this.findVersions({\n collection: args.collection,\n limit: args.limit,\n locale: args.locale,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: { ...args.where, latest: { equals: true } },\n })\n\n // queryDrafts should return documents with fields at root level, not nested in 'version'\n // So we need to unwrap the version structure and merge version fields to root\n const docs = versionsResult.docs.map((versionDoc) => {\n const { version, ...versionMeta } = versionDoc\n return {\n ...versionMeta,\n ...version,\n // Keep version metadata like parent, but document fields take precedence\n id: version.id, // Document ID, not version ID\n }\n })\n\n return {\n ...versionsResult,\n docs,\n }\n}\n\nasync function createVersion(this: ContentAPIAdapter, args: CreateVersionArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:create', {\n body: {\n collection: args.collectionSlug,\n contentSystemId: this.contentSystemId,\n versionDoc: {\n latest: !args.autosave,\n parent: String(args.parent),\n version: dataToContentAPI(this.payload, args.collectionSlug, args.versionData, {\n applyDefaults: true,\n }),\n },\n },\n })\n\n if (error) {\n throw new Error(`Content API createVersion error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from createVersion')\n }\n return unwrapDocument(this.payload, response.result, args.collectionSlug)\n}\n\nasync function updateVersion(this: ContentAPIAdapter, args: UpdateVersionArgs) {\n const where = args.where ?? { id: { equals: args.id } }\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n locale,\n versionDoc: {\n version: dataToContentAPI(this.payload, args.collection, args.versionData),\n },\n where: convertPayloadWhereToContentAPI(where),\n ...buildMeta(this.payload, { collection: args.collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateVersion error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in updateVersion response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteVersions(this: ContentAPIAdapter, args: DeleteVersionsArgs) {\n if (!args.collection) {\n throw new Error('deleteVersions requires a collection')\n }\n\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { error } = await this.client.POST('/api/v0/document_versions:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteVersions error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function findOne(this: ContentAPIAdapter, args: FindOneArgs) {\n const { docs } = await this.find({\n collection: args.collection,\n joins: args.joins,\n limit: 1,\n locale: args.locale,\n pagination: false,\n where: args.where,\n })\n return docs[0] ?? null\n}\n\nasync function updateMany(this: ContentAPIAdapter, args: UpdateManyArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n doc: dataToContentAPI(this.payload, args.collection, args.data),\n limit: args.limit,\n locale,\n returning: {},\n sort: addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection),\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateMany')\n }\n\n if (response.result && 'data' in response.result) {\n return response.result.data.map((doc) => unwrapDocument(this.payload, doc, args.collection))\n }\n return null\n}\n\nasync function updateOne(this: ContentAPIAdapter, args: UpdateOneArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n const where = args.where ?? { id: { equals: args.id } }\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n doc: dataToContentAPI(this.payload, args.collection, args.data),\n locale,\n returning: {},\n where: convertPayloadWhereToContentAPI(where),\n ...buildMeta(this.payload, { collection: args.collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateOne error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateOne')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from updateOne')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteMany(this: ContentAPIAdapter, args: DeleteManyArgs) {\n const locale = addFallbackLocale(args.req?.locale, this.payload)\n\n const { error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteMany error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function deleteOne(this: ContentAPIAdapter, args: DeleteOneArgs) {\n const locale = addFallbackLocale(args.req?.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n returning: {}, // Request deleted document back\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteOne error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in deleteOne response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function create(this: ContentAPIAdapter, args: CreateArgs) {\n const isGlobalCollection = args.collection.startsWith('_global-')\n const customIDType = this.payload.collections[args.collection]?.customIDType\n const id =\n (isGlobalCollection || customIDType || this.allowIDOnCreate) &&\n args.data.id != null &&\n (typeof args.data.id === 'string' || typeof args.data.id === 'number')\n ? String(args.data.id)\n : uuid()\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:create', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n doc: {\n ...dataToContentAPI(this.payload, args.collection, args.data, {\n applyDefaults: true,\n createdAt: true,\n }),\n id,\n },\n locale,\n ...buildMeta(this.payload, { collection: args.collection, locale }),\n },\n })\n\n if (error) {\n throw new Error(`Content API create error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from create')\n }\n return unwrapDocument(this.payload, response.result, args.collection)\n}\n\nasync function clearDatabase(this: ContentAPIAdapter) {\n this.payload.logger.info(`---- CLEARING CONTENT API DATABASE ----`)\n try {\n await fetch(`${this.url}/dev/clear-db`, {\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n this.payload.logger.info('---- CONTENT API DATABASE CLEARED ----')\n\n // Re-sync collections after clearing\n await syncCollections.call(this)\n } catch (error) {\n this.payload.logger.error(`Failed to clear database: ${(error as Error).message}`)\n throw error\n }\n}\n\nasync function count(this: ContentAPIAdapter, args: CountArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:count', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API count error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from count')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function countVersions(this: ContentAPIAdapter, args: CountArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:count', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API countVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from countVersions')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function upsert(this: ContentAPIAdapter, args: UpsertArgs) {\n let documentId = args.data.id as string | undefined\n if (!documentId && args.where && 'id' in args.where) {\n const idClause = (args.where as Record<string, unknown>).id as Record<string, unknown>\n if (idClause && 'equals' in idClause) {\n documentId = idClause.equals as string\n }\n }\n if (!documentId) {\n documentId = uuid()\n }\n\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: { id: documentId },\n doc: dataToContentAPI(this.payload, args.collection, args.data, {\n applyDefaults: true,\n createdAt: true,\n }),\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API upsert error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from upsert')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from upsert')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document data in upsert response')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nfunction createGlobal(this: ContentAPIAdapter, args: CreateGlobalArgs) {\n return this.create({\n collection: getGlobalSlug(args.slug),\n data: { ...args.data, id: args.slug, globalType: args.slug },\n })\n}\n\nfunction findGlobal(this: ContentAPIAdapter, args: FindGlobalArgs) {\n return this.findOne({\n collection: getGlobalSlug(args.slug),\n locale: args.locale,\n where: args.where ?? {},\n })\n}\n\nasync function updateGlobal(this: ContentAPIAdapter, args: UpdateGlobalArgs) {\n // Use upsert to ensure the global exists\n // Use slug as the consistent document ID for globals\n return this.upsert({\n collection: getGlobalSlug(args.slug),\n data: args.data,\n where: { id: { equals: args.slug } },\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nfunction findGlobalVersions(this: ContentAPIAdapter, args: Omit<FindGlobalVersionsArgs, 'skip'>) {\n return this.findVersions({\n collection: getGlobalSlug(args.global),\n limit: args.limit,\n locale: args.locale,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: args.where,\n })\n}\n\nfunction createGlobalVersion(this: ContentAPIAdapter, args: CreateGlobalVersionArgs) {\n // For globals, use the globalSlug as the consistent document ID\n // This matches what we do in updateGlobal\n return this.createVersion({\n autosave: args.autosave,\n collectionSlug: getGlobalSlug(args.globalSlug),\n createdAt: args.createdAt,\n parent: args.globalSlug,\n updatedAt: args.updatedAt,\n versionData: args.versionData,\n })\n}\n\nfunction updateGlobalVersion(this: ContentAPIAdapter, args: UpdateGlobalVersionArgs) {\n // UpdateVersion requires either id OR where, not both\n if (args.id !== undefined) {\n return this.updateVersion({\n id: args.id,\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n versionData: args.versionData,\n })\n }\n // args.where is guaranteed by Payload when args.id is undefined\n return this.updateVersion({\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n versionData: args.versionData,\n where: args.where,\n })\n}\n\nfunction countGlobalVersions(this: ContentAPIAdapter, args: CountGlobalVersionArgs) {\n return this.countVersions({\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n where: args.where,\n })\n}\n\nexport const contentAPIAdapter = (opts: ContentAPIOptions): DatabaseAdapterObj => ({\n name: 'content-api',\n defaultIDType: 'text',\n init: ({ payload }) => {\n const client = createClient<paths>({ baseUrl: opts.url })\n\n const middlewareOpts = {\n auth: opts.auth,\n contentSystemId: opts.contentSystemId,\n logger: payload.logger,\n url: opts.url,\n }\n\n client.use(createAuthMiddleware(middlewareOpts))\n client.use(createErrorMiddleware(middlewareOpts))\n\n return createDatabaseAdapter<ContentAPIAdapter>({\n name: 'content-api',\n allowIDOnCreate: opts.allowIDOnCreate ?? false,\n auth: opts.auth,\n beginTransaction: () => Promise.resolve(null),\n clearDatabase: clearDatabase as () => Promise<void>,\n client,\n commitTransaction: async () => {},\n contentSystemId: opts.contentSystemId,\n count: count as Count,\n countGlobalVersions: countGlobalVersions as CountGlobalVersions,\n countVersions: countVersions as CountVersions,\n create: create as Create,\n createGlobal: createGlobal as CreateGlobal,\n createGlobalVersion: createGlobalVersion as CreateGlobalVersion,\n createVersion: createVersion as CreateVersion,\n defaultIDType: 'text',\n deleteMany: deleteMany as DeleteMany,\n deleteOne: deleteOne as DeleteOne,\n deleteVersions: deleteVersions as DeleteVersions,\n find: find as Find,\n findDistinct: () =>\n Promise.reject(new Error('findDistinct is not yet implemented for Content API adapter')),\n findGlobal: findGlobal as FindGlobal,\n findGlobalVersions: findGlobalVersions as FindGlobalVersions,\n findOne: findOne as FindOne,\n findVersions: findVersions as FindVersions,\n init,\n packageName: '@payloadcms/db-content-api',\n payload,\n queryDrafts: queryDrafts as QueryDrafts,\n rollbackTransaction: async () => {},\n updateGlobal: updateGlobal as UpdateGlobal,\n updateGlobalVersion: updateGlobalVersion as UpdateGlobalVersion,\n updateMany: updateMany as UpdateMany,\n updateOne: updateOne as UpdateOne,\n updateVersion: updateVersion as UpdateVersion,\n upsert: upsert as Upsert,\n url: opts.url,\n })\n },\n})\n"],"names":["createClient","createDatabaseAdapter","v4","uuid","getGlobalSlug","addFallbackSort","unwrapDocument","unwrapFindResponse","createAuthMiddleware","createErrorMiddleware","dataToContentAPI","convertPayloadJoinsToContentAPI","addFallbackLocale","buildMeta","convertPayloadWhereToContentAPI","syncCollections","existingIds","data","response","error","client","GET","params","path","contentSystemId","Error","JSON","stringify","Set","map","c","id","payload","logger","info","size","warn","message","collection","config","collections","has","slug","createCollection","call","global","globals","globalId","init","auth","mode","process","env","PAYLOAD_DROP_DATABASE","clearDatabase","collectionId","POST","body","errorMessage","includes","findMany","joins","limit","locale","localeArg","page","pagination","_pagination","sort","where","join","result","find","args","collectionConfig","defaultSort","findVersions","sortWithFallback","whereClause","parentToDocumentId","queryDrafts","versionsResult","latest","equals","docs","versionDoc","version","versionMeta","createVersion","collectionSlug","autosave","parent","String","versionData","applyDefaults","updateVersion","createOnMissing","doc","deleteVersions","findOne","updateMany","returning","updateOne","deleteMany","req","deleteOne","create","isGlobalCollection","startsWith","customIDType","allowIDOnCreate","createdAt","fetch","url","headers","method","count","totalDocs","countVersions","upsert","documentId","idClause","createGlobal","globalType","findGlobal","updateGlobal","findGlobalVersions","createGlobalVersion","globalSlug","updatedAt","updateGlobalVersion","undefined","countGlobalVersions","contentAPIAdapter","opts","name","defaultIDType","baseUrl","middlewareOpts","use","beginTransaction","Promise","resolve","commitTransaction","findDistinct","reject","packageName","rollbackTransaction"],"mappings":"AAgDA,OAAOA,kBAAkB,gBAAe;AACxC,SAASC,qBAAqB,QAAQ,UAAS;AAC/C,SAASC,MAAMC,IAAI,QAAQ,OAAM;AAIjC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,cAAc,EAAEC,kBAAkB,QAAQ,qCAAoC;AACvF,SAAwBC,oBAAoB,EAAEC,qBAAqB,QAAQ,sBAAqB;AAChG,SAASC,gBAAgB,QAAQ,4BAA2B;AAC5D,SAASC,+BAA+B,QAAQ,uBAAsB;AACtE,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,SAAS,QAAQ,4BAA2B;AACrD,SAASC,+BAA+B,QAAQ,uBAAsB;AAiBtE,eAAeC;IACb,IAAIC;IACJ,IAAI;QACF,MAAM,EAAEC,MAAMC,QAAQ,EAAEC,KAAK,EAAE,GAAG,MAAM,IAAI,CAACC,MAAM,CAACC,GAAG,CACrD,yDACA;YACEC,QAAQ;gBAAEC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wB,KAAKxB,eAAe,IAAI;gBACzC7D,MAAMqF,KAAKrF,IAAI;gBACf2F,kBAAkB,IAAMC,QAAQC,OAAO,CAAC;gBACxCxF,eAAeA;gBACflC;gBACA2H,mBAAmB,WAAa;gBAChCvH,iBAAiB8G,KAAK9G,eAAe;gBACrC4F,OAAOA;gBACPgB,qBAAqBA;gBACrBd,eAAeA;gBACfZ,QAAQA;gBACRgB,cAAcA;gBACdK,qBAAqBA;gBACrBvC,eAAeA;gBACfgD,eAAe;gBACfjC,YAAYA;gBACZE,WAAWA;gBACXP,gBAAgBA;gBAChB1B,MAAMA;gBACNwE,cAAc,IACZH,QAAQI,MAAM,CAAC,IAAIxH,MAAM;gBAC3BmG,YAAYA;gBACZE,oBAAoBA;gBACpB3B,SAASA;gBACTvB,cAAcA;gBACd5B;gBACAkG,aAAa;gBACblH;gBACAgD,aAAaA;gBACbmE,qBAAqB,WAAa;gBAClCtB,cAAcA;gBACdK,qBAAqBA;gBACrB9B,YAAYA;gBACZE,WAAWA;gBACXP,eAAeA;gBACfwB,QAAQA;gBACRN,KAAKqB,KAAKrB,GAAG;YACf;QACF;IACF,CAAA,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/db-content-api/index.ts"],"sourcesContent":["import type {\n BaseDatabaseAdapter,\n Count,\n CountArgs,\n CountGlobalVersionArgs,\n CountGlobalVersions,\n CountVersions,\n Create,\n CreateArgs,\n CreateGlobal,\n CreateGlobalArgs,\n CreateGlobalVersion,\n CreateGlobalVersionArgs,\n CreateVersion,\n CreateVersionArgs,\n DatabaseAdapterObj,\n DeleteMany,\n DeleteManyArgs,\n DeleteOne,\n DeleteOneArgs,\n DeleteVersions,\n DeleteVersionsArgs,\n Find,\n FindArgs,\n FindGlobal,\n FindGlobalArgs,\n FindGlobalVersions,\n FindGlobalVersionsArgs,\n FindOne,\n FindOneArgs,\n FindVersions,\n FindVersionsArgs,\n QueryDrafts,\n QueryDraftsArgs,\n UpdateGlobal,\n UpdateGlobalArgs,\n UpdateGlobalVersion,\n UpdateGlobalVersionArgs,\n UpdateMany,\n UpdateManyArgs,\n UpdateOne,\n UpdateOneArgs,\n UpdateVersion,\n UpdateVersionArgs,\n Upsert,\n UpsertArgs,\n} from 'payload'\n\nimport createClient from 'openapi-fetch'\nimport { createDatabaseAdapter } from 'payload'\nimport { v4 as uuid } from 'uuid'\n\nimport type { paths } from './generated/content-api-types.js'\n\nimport { getGlobalSlug } from './temp-utilities/slug.js'\nimport { addFallbackSort } from './temp-utilities/sorting.js'\nimport { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js'\nimport { type AuthMode, createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js'\nimport { dataToContentAPI } from './utilities/data/index.js'\nimport { convertPayloadJoinsToContentAPI } from './utilities/joins.js'\nimport { addFallbackLocale } from './utilities/locale/index.js'\nimport { buildMeta } from './utilities/meta/buildMeta.js'\nimport { convertPayloadWhereToContentAPI } from './utilities/where.js'\n\ntype ContentAPIOptions = {\n allowIDOnCreate?: boolean\n auth: AuthMode\n contentSystemId: string\n url: string\n}\n\nexport type ContentAPIAdapter = {\n auth: AuthMode\n clearDatabase: () => Promise<void>\n client: ReturnType<typeof createClient<paths>>\n contentSystemId: string\n url: string\n} & BaseDatabaseAdapter\n\nasync function syncCollections(this: ContentAPIAdapter) {\n let existingIds: Set<string>\n try {\n const { data: response, error } = await this.client.GET(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n if (!response) {\n throw new Error('No response from collections endpoint')\n }\n\n existingIds = new Set(response.data.map((c) => c.id))\n this.payload.logger.info(`Found ${existingIds.size} existing collections`)\n } catch (error) {\n this.payload.logger.warn(\n `Failed to fetch collections, will attempt to create all: ${(error as Error).message}`,\n )\n existingIds = new Set()\n }\n\n for (const collection of this.payload.config.collections) {\n if (!existingIds.has(collection.slug)) {\n await createCollection.call(this, collection.slug)\n }\n }\n\n for (const global of this.payload.config.globals || []) {\n const globalId = `_global-${global.slug}`\n if (!existingIds.has(globalId)) {\n await createCollection.call(this, globalId)\n }\n }\n}\n\nasync function init(this: ContentAPIAdapter) {\n if (this.auth.mode === 'apiKey') {\n this.payload.logger.info('Using API Key authentication')\n } else if (this.auth.mode === 'tokenStore') {\n this.payload.logger.info('Using TokenStore authentication (local dev)')\n } else {\n this.payload.logger.info('Using Dev JWT authentication (testing)')\n }\n\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n await this.clearDatabase()\n }\n\n await syncCollections.call(this)\n}\n\nasync function createCollection(this: ContentAPIAdapter, collectionId: string) {\n try {\n const { error } = await this.client.POST(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n body: { id: collectionId },\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n this.payload.logger.info(`Created collection: ${collectionId}`)\n } catch (error) {\n const errorMessage = (error as Error).message\n if (!errorMessage.includes('already exists') && !errorMessage.includes('409')) {\n this.payload.logger.warn(`Failed to create collection ${collectionId}: ${errorMessage}`)\n }\n }\n}\n\nasync function findMany(\n this: ContentAPIAdapter,\n {\n collection,\n joins,\n limit,\n locale: localeArg,\n page,\n pagination: _pagination,\n sort,\n where,\n // Not yet passed to Content API:\n // - select: supported by Content API, pass-through possible\n // Not supported by Content API:\n // - draftsEnabled, versions, projection\n }: Pick<FindArgs, 'joins' | 'locale' | 'pagination' | 'sort' | 'where'> &\n Required<Pick<FindArgs, 'collection' | 'limit' | 'page'>>,\n) {\n const locale = addFallbackLocale(localeArg, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:find', {\n body: {\n collection,\n contentSystemId: this.contentSystemId,\n join: convertPayloadJoinsToContentAPI(this.payload, collection, joins),\n limit,\n locale,\n page: page ?? 1,\n sort: addFallbackSort(sort, this.payload, collection),\n where: convertPayloadWhereToContentAPI(where ?? {}),\n ...buildMeta(this.payload, { collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API findMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findMany')\n }\n\n return unwrapFindResponse(this.payload, response.result, collection)\n}\n\nasync function find(this: ContentAPIAdapter, args: FindArgs) {\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === args.collection)\n return findMany.call(this, {\n collection: args.collection,\n joins: args.joins,\n // TODO: FindArgs.limit should be 'number' not 'number | undefined'\n // is sanitized by Payload Core before calling the adapter (defaults to 10 or 0 based on pagination)\n limit: args.limit!,\n locale: args.locale,\n page: args.page ?? 1,\n pagination: args.pagination,\n sort: args.sort || collectionConfig?.defaultSort,\n where: args.where,\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nasync function findVersions(this: ContentAPIAdapter, args: Omit<FindVersionsArgs, 'skip'>) {\n const sortWithFallback = addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection)\n\n const whereClause = convertPayloadWhereToContentAPI(args.where ?? {}, {\n parentToDocumentId: true,\n stripVersionPrefix: true,\n })\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:find', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n // TODO: FindVersionsArgs.limit should be 'number' not 'number | undefined'\n // is sanitized by Payload Core before calling the adapter (defaults to 10 or 0 based on pagination)\n limit: args.limit!,\n locale,\n page: args.page ?? 1,\n sort: sortWithFallback,\n where: whereClause,\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API findVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findVersions')\n }\n\n return unwrapFindResponse(this.payload, response.result, args.collection)\n}\n\nasync function queryDrafts(this: ContentAPIAdapter, args: QueryDraftsArgs) {\n const versionsResult = await this.findVersions({\n collection: args.collection,\n limit: args.limit,\n locale: args.locale,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: { ...args.where, latest: { equals: true } },\n })\n\n // queryDrafts should return documents with fields at root level, not nested in 'version'\n // So we need to unwrap the version structure and merge version fields to root\n const docs = versionsResult.docs.map((versionDoc) => {\n const { version, ...versionMeta } = versionDoc\n return {\n ...versionMeta,\n ...version,\n // Keep version metadata like parent, but document fields take precedence\n id: version.id, // Document ID, not version ID\n }\n })\n\n return {\n ...versionsResult,\n docs,\n }\n}\n\nasync function createVersion(this: ContentAPIAdapter, args: CreateVersionArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:create', {\n body: {\n collection: args.collectionSlug,\n contentSystemId: this.contentSystemId,\n versionDoc: {\n createdAt: args.createdAt,\n latest: !args.autosave,\n parent: String(args.parent),\n updatedAt: args.updatedAt,\n version: dataToContentAPI(this.payload, args.collectionSlug, args.versionData, {\n applyDefaults: true,\n publishedLocale: args.publishedLocale,\n }),\n },\n },\n })\n\n if (error) {\n throw new Error(`Content API createVersion error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from createVersion')\n }\n return unwrapDocument(this.payload, response.result, args.collectionSlug)\n}\n\nasync function updateVersion(this: ContentAPIAdapter, args: UpdateVersionArgs) {\n const where = args.where ?? { id: { equals: args.id } }\n const locale = addFallbackLocale(args.locale, this.payload)\n\n // versionData contains version metadata plus nested version content\n const { publishedLocale, version, ...versionMeta } = args.versionData\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n locale,\n versionDoc: {\n createdAt: versionMeta.createdAt,\n latest: versionMeta.latest,\n parent: versionMeta.parent != null ? String(versionMeta.parent) : undefined,\n updatedAt: versionMeta.updatedAt,\n version: dataToContentAPI(this.payload, args.collection, version, { publishedLocale }),\n },\n where: convertPayloadWhereToContentAPI(where, { stripVersionPrefix: true }),\n ...buildMeta(this.payload, { collection: args.collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateVersion error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in updateVersion response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteVersions(this: ContentAPIAdapter, args: DeleteVersionsArgs) {\n if (!args.collection) {\n throw new Error('deleteVersions requires a collection')\n }\n\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { error } = await this.client.POST('/api/v0/document_versions:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where, { stripVersionPrefix: true }),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteVersions error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function findOne(this: ContentAPIAdapter, args: FindOneArgs) {\n const { docs } = await this.find({\n collection: args.collection,\n joins: args.joins,\n limit: 1,\n locale: args.locale,\n pagination: false,\n where: args.where,\n })\n return docs[0] ?? null\n}\n\nasync function updateMany(this: ContentAPIAdapter, args: UpdateManyArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n doc: dataToContentAPI(this.payload, args.collection, args.data),\n limit: args.limit,\n locale,\n returning: {},\n sort: addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection),\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateMany')\n }\n\n if (response.result && 'data' in response.result) {\n return response.result.data.map((doc) => unwrapDocument(this.payload, doc, args.collection))\n }\n return null\n}\n\nasync function updateOne(this: ContentAPIAdapter, args: UpdateOneArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n const where = args.where ?? { id: { equals: args.id } }\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n doc: dataToContentAPI(this.payload, args.collection, args.data),\n locale,\n returning: {},\n where: convertPayloadWhereToContentAPI(where),\n ...buildMeta(this.payload, { collection: args.collection, locale, where }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateOne error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateOne')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from updateOne')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteMany(this: ContentAPIAdapter, args: DeleteManyArgs) {\n const locale = addFallbackLocale(args.req?.locale, this.payload)\n\n const { error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteMany error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function deleteOne(this: ContentAPIAdapter, args: DeleteOneArgs) {\n const locale = addFallbackLocale(args.req?.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n returning: {}, // Request deleted document back\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteOne error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in deleteOne response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n return null\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function create(this: ContentAPIAdapter, args: CreateArgs) {\n const isGlobalCollection = args.collection.startsWith('_global-')\n const customIDType = this.payload.collections[args.collection]?.customIDType\n const id =\n (isGlobalCollection || customIDType || this.allowIDOnCreate) &&\n args.data.id != null &&\n (typeof args.data.id === 'string' || typeof args.data.id === 'number')\n ? String(args.data.id)\n : uuid()\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:create', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n doc: {\n ...dataToContentAPI(this.payload, args.collection, args.data, {\n applyDefaults: true,\n createdAt: true,\n }),\n id,\n },\n locale,\n ...buildMeta(this.payload, { collection: args.collection, locale }),\n },\n })\n\n if (error) {\n throw new Error(`Content API create error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from create')\n }\n return unwrapDocument(this.payload, response.result, args.collection)\n}\n\nasync function clearDatabase(this: ContentAPIAdapter) {\n this.payload.logger.info(`---- CLEARING CONTENT API DATABASE ----`)\n try {\n await fetch(`${this.url}/dev/clear-db`, {\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n this.payload.logger.info('---- CONTENT API DATABASE CLEARED ----')\n\n // Re-sync collections after clearing\n await syncCollections.call(this)\n } catch (error) {\n this.payload.logger.error(`Failed to clear database: ${(error as Error).message}`)\n throw error\n }\n}\n\nasync function count(this: ContentAPIAdapter, args: CountArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:count', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API count error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from count')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function countVersions(this: ContentAPIAdapter, args: CountArgs) {\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:count', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n locale,\n where: convertPayloadWhereToContentAPI(args.where, { stripVersionPrefix: true }),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API countVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from countVersions')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function upsert(this: ContentAPIAdapter, args: UpsertArgs) {\n let documentId = args.data.id as string | undefined\n if (!documentId && args.where && 'id' in args.where) {\n const idClause = (args.where as Record<string, unknown>).id as Record<string, unknown>\n if (idClause && 'equals' in idClause) {\n documentId = idClause.equals as string\n }\n }\n if (!documentId) {\n documentId = uuid()\n }\n\n const locale = addFallbackLocale(args.locale, this.payload)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collection: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: { id: documentId },\n doc: dataToContentAPI(this.payload, args.collection, args.data, {\n applyDefaults: true,\n createdAt: true,\n }),\n locale,\n where: convertPayloadWhereToContentAPI(args.where),\n ...buildMeta(this.payload, {\n collection: args.collection,\n locale,\n where: args.where,\n }),\n },\n })\n\n if (error) {\n throw new Error(`Content API upsert error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from upsert')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from upsert')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document data in upsert response')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nfunction createGlobal(this: ContentAPIAdapter, args: CreateGlobalArgs) {\n return this.create({\n collection: getGlobalSlug(args.slug),\n data: { ...args.data, id: args.slug, globalType: args.slug },\n })\n}\n\nfunction findGlobal(this: ContentAPIAdapter, args: FindGlobalArgs) {\n return this.findOne({\n collection: getGlobalSlug(args.slug),\n locale: args.locale,\n where: args.where ?? {},\n })\n}\n\nasync function updateGlobal(this: ContentAPIAdapter, args: UpdateGlobalArgs) {\n // Use upsert to ensure the global exists\n // Use slug as the consistent document ID for globals\n return this.upsert({\n collection: getGlobalSlug(args.slug),\n data: args.data,\n where: { id: { equals: args.slug } },\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nfunction findGlobalVersions(this: ContentAPIAdapter, args: Omit<FindGlobalVersionsArgs, 'skip'>) {\n return this.findVersions({\n collection: getGlobalSlug(args.global),\n limit: args.limit,\n locale: args.locale,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: args.where,\n })\n}\n\nfunction createGlobalVersion(this: ContentAPIAdapter, args: CreateGlobalVersionArgs) {\n // For globals, use the globalSlug as the consistent document ID\n // This matches what we do in updateGlobal\n return this.createVersion({\n autosave: args.autosave,\n collectionSlug: getGlobalSlug(args.globalSlug),\n createdAt: args.createdAt,\n parent: args.globalSlug,\n publishedLocale: args.publishedLocale,\n updatedAt: args.updatedAt,\n versionData: args.versionData,\n })\n}\n\nfunction updateGlobalVersion(this: ContentAPIAdapter, args: UpdateGlobalVersionArgs) {\n // UpdateVersion requires either id OR where, not both\n if (args.id !== undefined) {\n return this.updateVersion({\n id: args.id,\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n versionData: args.versionData,\n })\n }\n // args.where is guaranteed by Payload when args.id is undefined\n return this.updateVersion({\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n versionData: args.versionData,\n where: args.where,\n })\n}\n\nfunction countGlobalVersions(this: ContentAPIAdapter, args: CountGlobalVersionArgs) {\n return this.countVersions({\n collection: getGlobalSlug(args.global),\n locale: args.locale,\n where: args.where,\n })\n}\n\nexport const contentAPIAdapter = (opts: ContentAPIOptions): DatabaseAdapterObj => ({\n name: 'content-api',\n defaultIDType: 'text',\n init: ({ payload }) => {\n const client = createClient<paths>({ baseUrl: opts.url })\n\n const middlewareOpts = {\n auth: opts.auth,\n contentSystemId: opts.contentSystemId,\n logger: payload.logger,\n url: opts.url,\n }\n\n client.use(createAuthMiddleware(middlewareOpts))\n client.use(createErrorMiddleware(middlewareOpts))\n\n return createDatabaseAdapter<ContentAPIAdapter>({\n name: 'content-api',\n allowIDOnCreate: opts.allowIDOnCreate ?? false,\n auth: opts.auth,\n beginTransaction: () => Promise.resolve(null),\n clearDatabase: clearDatabase as () => Promise<void>,\n client,\n commitTransaction: async () => {},\n contentSystemId: opts.contentSystemId,\n count: count as Count,\n countGlobalVersions: countGlobalVersions as CountGlobalVersions,\n countVersions: countVersions as CountVersions,\n create: create as Create,\n createGlobal: createGlobal as CreateGlobal,\n createGlobalVersion: createGlobalVersion as CreateGlobalVersion,\n createVersion: createVersion as CreateVersion,\n defaultIDType: 'text',\n deleteMany: deleteMany as DeleteMany,\n deleteOne: deleteOne as DeleteOne,\n deleteVersions: deleteVersions as DeleteVersions,\n find: find as Find,\n findDistinct: () =>\n Promise.reject(new Error('findDistinct is not yet implemented for Content API adapter')),\n findGlobal: findGlobal as FindGlobal,\n findGlobalVersions: findGlobalVersions as FindGlobalVersions,\n findOne: findOne as FindOne,\n findVersions: findVersions as FindVersions,\n init,\n packageName: '@payloadcms/db-content-api',\n payload,\n queryDrafts: queryDrafts as QueryDrafts,\n rollbackTransaction: async () => {},\n updateGlobal: updateGlobal as UpdateGlobal,\n updateGlobalVersion: updateGlobalVersion as UpdateGlobalVersion,\n updateMany: updateMany as UpdateMany,\n updateOne: updateOne as UpdateOne,\n updateVersion: updateVersion as UpdateVersion,\n upsert: upsert as Upsert,\n url: opts.url,\n })\n },\n})\n"],"names":["createClient","createDatabaseAdapter","v4","uuid","getGlobalSlug","addFallbackSort","unwrapDocument","unwrapFindResponse","createAuthMiddleware","createErrorMiddleware","dataToContentAPI","convertPayloadJoinsToContentAPI","addFallbackLocale","buildMeta","convertPayloadWhereToContentAPI","syncCollections","existingIds","data","response","error","client","GET","params","path","contentSystemId","Error","JSON","stringify","Set","map","c","id","payload","logger","info","size","warn","message","collection","config","collections","has","slug","createCollection","call","global","globals","globalId","init","auth","mode","process","env","PAYLOAD_DROP_DATABASE","clearDatabase","collectionId","POST","body","errorMessage","includes","findMany","joins","limit","locale","localeArg","page","pagination","_pagination","sort","where","join","result","find","args","collectionConfig","defaultSort","findVersions","sortWithFallback","whereClause","parentToDocumentId","stripVersionPrefix","queryDrafts","versionsResult","latest","equals","docs","versionDoc","version","versionMeta","createVersion","collectionSlug","createdAt","autosave","parent","String","updatedAt","versionData","applyDefaults","publishedLocale","updateVersion","createOnMissing","undefined","doc","deleteVersions","findOne","updateMany","returning","updateOne","deleteMany","req","deleteOne","create","isGlobalCollection","startsWith","customIDType","allowIDOnCreate","fetch","url","headers","method","count","totalDocs","countVersions","upsert","documentId","idClause","createGlobal","globalType","findGlobal","updateGlobal","findGlobalVersions","createGlobalVersion","globalSlug","updateGlobalVersion","countGlobalVersions","contentAPIAdapter","opts","name","defaultIDType","baseUrl","middlewareOpts","use","beginTransaction","Promise","resolve","commitTransaction","findDistinct","reject","packageName","rollbackTransaction"],"mappings":"AAgDA,OAAOA,kBAAkB,gBAAe;AACxC,SAASC,qBAAqB,QAAQ,UAAS;AAC/C,SAASC,MAAMC,IAAI,QAAQ,OAAM;AAIjC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SAASC,cAAc,EAAEC,kBAAkB,QAAQ,qCAAoC;AACvF,SAAwBC,oBAAoB,EAAEC,qBAAqB,QAAQ,sBAAqB;AAChG,SAASC,gBAAgB,QAAQ,4BAA2B;AAC5D,SAASC,+BAA+B,QAAQ,uBAAsB;AACtE,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,SAAS,QAAQ,gCAA+B;AACzD,SAASC,+BAA+B,QAAQ,uBAAsB;AAiBtE,eAAeC;IACb,IAAIC;IACJ,IAA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;gBACXR,eAAeA;gBACfwB,QAAQA;gBACRN,KAAKmB,KAAKnB,GAAG;YACf;QACF;IACF,CAAA,EAAE"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PathType can be either a simple string type or an object with additional metadata.
|
|
3
|
+
*
|
|
4
|
+
* Simple types: "array" - for array fields, blocks, or hasMany relationships/selects
|
|
5
|
+
*
|
|
6
|
+
* Relationship types include collection info needed for Content API to perform JOINs:
|
|
7
|
+
* - type: "relationship" for stored references, "join" for virtual reverse lookups
|
|
8
|
+
* - collection: target collection slug (or array for polymorphic)
|
|
9
|
+
* - hasMany: whether it stores multiple references
|
|
10
|
+
*
|
|
11
|
+
* TODO: This type is defined here temporarily so Content API can test the integration.
|
|
12
|
+
* Once Content API implements support for this, the type should be generated from openapi.json.
|
|
13
|
+
*/
|
|
14
|
+
export type PathTypeValue = 'array' | {
|
|
15
|
+
collection: string | string[];
|
|
16
|
+
hasMany?: boolean;
|
|
17
|
+
/** For join fields, the field path in the related collection that points back */
|
|
18
|
+
on?: string;
|
|
19
|
+
type: 'join' | 'relationship';
|
|
20
|
+
};
|
|
21
|
+
export type PathTypesRecord = Record<string, PathTypeValue>;
|
|
22
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/temp-utilities/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,aAAa,GACrB,OAAO,GACP;IACE,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,iFAAiF;IACjF,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,GAAG,cAAc,CAAA;CAC9B,CAAA;AAEL,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA"}
|