Skip to content

Commit e4e37c8

Browse files
authored
Merge pull request #14145 from aws-amplify/gen2-migrations-execute
Gen2 migrations QA fixes
2 parents a51c8f5 + c7aa90a commit e4e37c8

17 files changed

Lines changed: 172 additions & 39 deletions

File tree

packages/amplify-gen1-codegen-auth-adapter/src/auth_render_adapter.test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,14 +462,19 @@ void describe('auth codegen', () => {
462462
['DefineAuthChallenge', 'defineAuthChallenge'],
463463
['CreateAuthChallenge', 'createAuthChallenge'],
464464
['VerifyAuthChallengeResponse', 'verifyAuthChallengeResponse'],
465+
['PreTokenGenerationConfig', 'preTokenGeneration'],
465466
];
466467
for (const [lambdaConfigKey, authEventKey] of testCases) {
467468
void it(`adapts user pool lambda config key ${lambdaConfigKey} to triggers ${authEventKey}`, () => {
468469
const result = getAuthDefinition({
469470
userPool: { LambdaConfig: { [lambdaConfigKey]: {} } },
470471
});
471472
assert(result.lambdaTriggers);
472-
assert.deepEqual(result.lambdaTriggers[authEventKey], { source: '' });
473+
if (lambdaConfigKey === 'PreTokenGenerationConfig') {
474+
expect(result.lambdaTriggers[authEventKey]).toBeUndefined();
475+
} else {
476+
assert.deepEqual(result.lambdaTriggers[authEventKey], { source: '' });
477+
}
473478
});
474479
}
475480
});

packages/amplify-gen1-codegen-auth-adapter/src/auth_render_adapter.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ export const DEFAULT_PASSWORD_SETTINGS: PasswordPolicyType = {
6161
TemporaryPasswordValidityDays: 3,
6262
};
6363

64+
const COGNITO_TRIGGERS_TO_SKIP = ['PreTokenGenerationConfig'];
65+
6466
const getPasswordPolicyOverrides = (passwordPolicy: Partial<PasswordPolicyType>): Partial<PolicyOverrides> => {
6567
const policyOverrides: Partial<PolicyOverrides> = {};
6668
const passwordOverridePath = (policyKey: keyof PasswordPolicyType): PasswordPolicyPath => `Policies.PasswordPolicy.${policyKey}`;
@@ -217,11 +219,17 @@ const getAuthTriggers = (
217219
lambdaConfig: LambdaConfigType,
218220
triggerSourceFiles: AuthTriggerConnectionSourceMap,
219221
): Partial<Record<AuthTriggerEvents, Lambda>> => {
220-
return Object.keys(lambdaConfig).reduce((prev, key) => {
221-
const typedKey = key as keyof LambdaConfigType;
222-
prev[mappedLambdaConfigKey(typedKey)] = { source: triggerSourceFiles[typedKey] ?? '' };
223-
return prev;
224-
}, {} as Partial<Record<AuthTriggerEvents, Lambda>>);
222+
return (
223+
Object.keys(lambdaConfig)
224+
// There is PreTokenGenerationConfig that is duplicated, but is of a different format. Cognito introduced this at a later stage.
225+
// We look for PreTokenGeneration which is maintained for legacy reasons and is always populated.
226+
.filter((triggerName) => !COGNITO_TRIGGERS_TO_SKIP.includes(triggerName))
227+
.reduce((prev, key) => {
228+
const typedKey = key as keyof LambdaConfigType;
229+
prev[mappedLambdaConfigKey(typedKey)] = { source: triggerSourceFiles[typedKey] ?? '' };
230+
return prev;
231+
}, {} as Partial<Record<AuthTriggerEvents, Lambda>>)
232+
);
225233
};
226234

227235
function filterAttributeMapping(

packages/amplify-gen2-codegen/src/backend/synthesizer.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { BucketAccelerateStatus, BucketVersioningStatus } from '@aws-sdk/client-
1414
import { AccessPatterns, ServerSideEncryptionConfiguration } from '../storage/source_builder.js';
1515
import { ExplicitAuthFlowsType, OAuthFlowType, UserPoolClientType } from '@aws-sdk/client-cognito-identity-provider';
1616
import assert from 'assert';
17+
import { newLineIdentifier } from '../ts_factory_utils';
1718

1819
const factory = ts.factory;
1920
export interface BackendRenderParameters {
@@ -734,10 +735,8 @@ export class BackendSynthesizer {
734735
}
735736

736737
if (renderArgs.function) {
737-
const functionIdentifiers: Identifier[] = [];
738738
const functionNameCategories = renderArgs.function.functionNamesAndCategories;
739739
for (const [functionName, category] of functionNameCategories) {
740-
functionIdentifiers.push(factory.createIdentifier(functionName));
741740
const functionProperty = factory.createShorthandPropertyAssignment(factory.createIdentifier(functionName));
742741
defineBackendProperties.push(functionProperty);
743742
imports.push(this.createImportStatement([factory.createIdentifier(functionName)], `./${category}/${functionName}/resource`));
@@ -1022,6 +1021,6 @@ export class BackendSynthesizer {
10221021
nodes.push(tagAssignment);
10231022
}
10241023

1025-
return factory.createNodeArray([...imports, ...errors, backendStatement, ...nodes], true);
1024+
return factory.createNodeArray([...imports, newLineIdentifier, ...errors, newLineIdentifier, backendStatement, ...nodes], true);
10261025
}
10271026
}

packages/amplify-gen2-codegen/src/data/source_builder.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ describe('Data Category code generation', () => {
4141
const source = printNodeArray(generateDataSource({ tableMappings, schema: 'schema' }));
4242
assert.match(
4343
source,
44-
/const schema \= \`schema\`\;\nexport const data \= defineData\({\n\s+migratedAmplifyGen1DynamoDbTableMappings: \[\{\n\s+\/\/ Replace the environment name \(dev\) with the corresponding branch name. Use ['"]sandbox['"] for your sandbox environment.\n\s+branchName: ['"]dev['"],\n\s+modelNameToTableNameMapping: { Todo: ['"]my-todo-mapping['"] }\n\s+}],\n\s+schema\n}\)/,
44+
/const schema \= \`schema\`\;\n\nexport const data \= defineData\({\n\s+migratedAmplifyGen1DynamoDbTableMappings: \[\{\n\s+\/\/ Replace the environment name \(dev\) with the corresponding branch name. Use ['"]sandbox['"] for your sandbox environment.\n\s+branchName: ['"]dev['"],\n\s+modelNameToTableNameMapping: { Todo: ['"]my-todo-mapping['"] }\n\s+}],\n\s+schema\n}\)/,
4545
);
4646
});
4747
});

packages/amplify-gen2-codegen/src/function/source_builder.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,13 @@ export function renderFunctions(definition: FunctionDefinition, appId?: string,
3939
namedImports['@aws-amplify/backend'].add('defineFunction');
4040

4141
postImportStatements.push(
42-
factory.createCallExpression(factory.createIdentifier('throw new Error'), undefined, [
43-
factory.createStringLiteral(
44-
`Source code for this function can be found in your Amplify Gen 1 Directory. See .amplify/migration/amplify/backend/function/${definition.resourceName}/src`,
45-
),
46-
]),
42+
factory.createExpressionStatement(
43+
factory.createCallExpression(factory.createIdentifier('throw new Error'), undefined, [
44+
factory.createStringLiteral(
45+
`Source code for this function can be found in your Amplify Gen 1 Directory. See .amplify/migration/amplify/backend/function/${definition.resourceName}/src`,
46+
),
47+
]),
48+
),
4749
);
4850

4951
const defineFunctionProperty = createFunctionDefinition(definition, postImportStatements, namedImports, appId, backendEnvironmentName);
@@ -69,7 +71,7 @@ export function renderFunctions(definition: FunctionDefinition, appId?: string,
6971

7072
export function createFunctionDefinition(
7173
definition?: FunctionDefinition,
72-
postImportStatements?: (ts.CallExpression | ts.JSDoc)[],
74+
postImportStatements?: (ts.CallExpression | ts.JSDoc | ts.ExpressionStatement)[],
7375
namedImports?: Record<string, Set<string>>,
7476
appId?: string,
7577
backendEnvironmentName?: string,

packages/amplify-gen2-codegen/src/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export const createGen2Renderer = ({
9696
'ci-info': '^3.8.0',
9797
constructs: '^10.0.0',
9898
typescript: '^5.0.0',
99+
'@types/node': '*',
99100
});
100101
},
101102
(content) => fileWriter(content, path.join(outputDir, 'package.json')),
@@ -143,9 +144,7 @@ export const createGen2Renderer = ({
143144
new TypescriptNodeArrayRenderer(
144145
async () => renderFunctions(func),
145146
(content) => {
146-
return fileWriter(content, path.join(dirPath, 'resource.ts'))
147-
.then(() => fileWriter('', path.join(dirPath, 'handler.ts')))
148-
.catch(console.error);
147+
return fileWriter(content, path.join(dirPath, 'resource.ts')).then(() => fileWriter('', path.join(dirPath, 'handler.ts')));
149148
},
150149
),
151150
);

packages/amplify-gen2-codegen/src/npm_package/renderer.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const installedDependencies: Record<keyof AmplifyPackageVersions, IsDevDependenc
2424
'@aws-amplify/backend': true,
2525
'@aws-amplify/backend-cli': true,
2626
'ci-info': true,
27+
'@types/node': true,
2728
};
2829

2930
describe('package.json renderer', () => {

packages/amplify-gen2-codegen/src/npm_package/renderer.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export type AmplifyDevDependencies = {
88
esbuild: string;
99
tsx: string;
1010
typescript: string;
11+
'@types/node': string;
1112
};
1213
export type AmplifyDependencies = {
1314
'aws-amplify': string;
@@ -40,6 +41,7 @@ export const patchNpmPackageJson = (packageJson: PackageJson, packageVersions: P
4041
esbuild: withDefault(packageVersions.esbuild),
4142
tsx: withDefault(packageVersions.tsx),
4243
typescript: withDefault(packageVersions.typescript),
44+
'@types/node': withDefault(packageVersions['@types/node']),
4345
},
4446
dependencies: {
4547
...(packageJson.dependencies ?? {}),

packages/amplify-gen2-codegen/src/resource/resource.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import ts from 'typescript';
2+
import { newLineIdentifier } from '../ts_factory_utils';
23
const factory = ts.factory;
34
export type ResourceTsParameters = {
45
additionalImportedBackendIdentifiers?: Record<string, Set<string>>;
@@ -25,7 +26,13 @@ export function renderResourceTsFile({
2526
factory.createVariableDeclarationList([exportedVariable], ts.NodeFlags.Const),
2627
);
2728

28-
return factory.createNodeArray([...importStatements, ...(postImportStatements ?? []), exportStatement, ...(postExportStatements ?? [])]);
29+
return factory.createNodeArray([
30+
...importStatements,
31+
...(postImportStatements !== undefined && postImportStatements.length > 0 ? [newLineIdentifier, ...postImportStatements] : []),
32+
newLineIdentifier,
33+
exportStatement,
34+
...(postExportStatements !== undefined && postExportStatements.length > 0 ? [newLineIdentifier, ...postExportStatements] : []),
35+
]);
2936
}
3037

3138
export type ResourceTsParametersList = {
@@ -50,9 +57,9 @@ export function renderResourceTsFilesForFunction({
5057

5158
return factory.createNodeArray([
5259
...importStatements,
53-
...(postImportStatements ?? []),
54-
...(exportStatements ?? []),
55-
...(postExportStatements ?? []),
60+
...(postImportStatements !== undefined && postImportStatements.length > 0 ? [newLineIdentifier, ...postImportStatements] : []),
61+
...(exportStatements ? [newLineIdentifier, ...exportStatements] : []),
62+
...(postExportStatements !== undefined && postExportStatements.length > 0 ? [newLineIdentifier, ...postExportStatements] : []),
5663
]);
5764
}
5865

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import ts from 'typescript';
2+
3+
const factory = ts.factory;
4+
5+
export const newLineIdentifier = factory.createIdentifier('\n');

0 commit comments

Comments
 (0)