Skip to content

Commit

Permalink
fix: improved typing for $TSContext (#11962)
Browse files Browse the repository at this point in the history
* fix: typing for $TSContext
  • Loading branch information
sdstolworthy committed Feb 17, 2023
1 parent e4481cd commit 3e2ff00
Show file tree
Hide file tree
Showing 115 changed files with 875 additions and 483 deletions.
1 change: 1 addition & 0 deletions .eslint-dictionary.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"columnify",
"commitlint",
"commonjs",
"cond",
"configxc",
"coppa",
"cors",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ export const analyticsPushYes = async (context: $TSContext): Promise<void> => {
context.exeInfo.inputParams = context.exeInfo.inputParams || {};
context.exeInfo.inputParams.yes = true; // force yes to avoid prompts
context.parameters = context.parameters || {};
context.parameters.options = context.parameters.options ?? {};
context.parameters.options.yes = true;
context.parameters.first = undefined;
await analyticsPush(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const name = 'analytics';
* @param context amplify cli context
*/
export const run = async (context: $TSContext): Promise<$TSAny> => {
if (context.parameters.options.help) {
if (context.parameters.options?.help) {
return runHelp(context);
}
if (/^win/.test(process.platform)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const run = async (context: $TSContext): Promise<$TSAny> => {
.catch((err) => {
printer.info(err.stack);
printer.error('There was an error adding the analytics resource');
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const run = async (context: $TSContext): Promise<$TSAny> => {
.catch((err) => {
printer.info(err.stack);
printer.error(`There was an error updating the ${category} resource`);
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export const inAppMessagingMigrationCheck = async (context: $TSContext): Promise
};
context.amplify.updateamplifyMetaAfterResourceAdd(AmplifyCategories.ANALYTICS, resource, options);

context.parameters.options = context.parameters.options ?? {};
context.parameters.options.yes = true;
context.exeInfo.inputParams = context.exeInfo.inputParams || {};
context.exeInfo.inputParams.yes = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const updateResource = (context: $TSContext, __: string, service: string)
if (!updateWalkthrough) {
const message = 'Update functionality not available for this service';
printer.error(message);
context.usageData.emitError(new NotImplementedError(message));
void context.usageData.emitError(new NotImplementedError(message));
exitOnNextTick(0);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as fs from 'fs-extra';
import { $TSContext } from 'amplify-cli-core';
import { printer } from 'amplify-prompts';
import * as update from '../../commands/auth/update';
import { messages } from '../../provider-utils/awscloudformation/assets/string-maps';
import { AuthContext } from '../../context';

jest.mock('../../provider-utils/awscloudformation/auth-inputs-manager/auth-input-state');
jest.mock('fs-extra', () => ({
Expand Down Expand Up @@ -91,7 +91,7 @@ describe('auth update:', () => {
input: {
options: {},
},
} as unknown as $TSContext;
} as unknown as AuthContext;

it('update run method should exist', async () => {
await expect(update.run).toBeDefined();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { $TSContext, stateManager } from 'amplify-cli-core';
import { stateManager } from 'amplify-cli-core';
import { getUpdateAuthHandler } from '../../../../provider-utils/awscloudformation/handlers/resource-handlers';
import { CognitoConfiguration } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/awsCognito-user-input-types';
import { getSupportedServices } from '../../../../provider-utils/supported-services';
import { getUpdateAuthDefaultsApplier } from '../../../../provider-utils/awscloudformation/utils/auth-defaults-appliers';
import { AuthInputState } from '../../../../provider-utils/awscloudformation/auth-inputs-manager/auth-input-state';
import { getPostUpdateAuthMetaUpdater } from '../../../../provider-utils/awscloudformation/utils/amplify-meta-updaters';
import { getPostUpdateAuthMessagePrinter } from '../../../../provider-utils/awscloudformation/utils/message-printer';
import { removeDeprecatedProps } from '../../../../provider-utils/awscloudformation/utils/synthesize-resources';
import { ENV_SPECIFIC_PARAMS } from '../../../../provider-utils/awscloudformation/constants';
import { AuthContext, CognitoConfiguration } from '../../../../context';

jest.mock('../../../../provider-utils/awscloudformation/utils/synthesize-resources');
jest.mock('../../../../provider-utils/awscloudformation/utils/auth-defaults-appliers');
Expand Down Expand Up @@ -63,7 +63,7 @@ describe('getUpdateAuthHandler', () => {
amplify: {
saveEnvResourceParameters: saveParamsFn,
},
} as unknown as $TSContext;
} as unknown as AuthContext;
const cognitoConfig: CognitoConfiguration = {
serviceName: 'test',
} as unknown as CognitoConfiguration;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
/* eslint-disable max-len */

import { $TSContext, $TSAny } from 'amplify-cli-core';
import { $TSAny } from 'amplify-cli-core';
import { Input, parseInputs } from '../../../../provider-utils/awscloudformation/question-factories/core-questions';
import defaults from '../../../../provider-utils/awscloudformation/assets/cognito-defaults';
import maps from '../../../../provider-utils/awscloudformation/assets/string-maps';
import { AuthContext, CognitoConfiguration } from '../../../../context';

const defaultFileName = 'cognito-defaults';
const stringMapsFileName = 'string-maps';
const mockContext = {} as $TSContext;
const mockContext = {} as AuthContext;
let mockAmplify = {
getWhen: jest.fn(),
inputValidation: jest.fn(),
Expand Down Expand Up @@ -114,7 +115,7 @@ describe('When generating auth questions...', () => {
delete input.filter;
});
afterEach(() => {
delete mockContext.updatingAuth;
delete (mockContext as Partial<AuthContext>).updatingAuth;
currentAnswers = {};
});

Expand Down Expand Up @@ -152,14 +153,14 @@ describe('When generating auth questions...', () => {
});

it('should not getAllDefaults if updatingAuth is present in the context.', async () => {
mockContext.updatingAuth = { Q1: 'my old answer' };
mockContext.updatingAuth = { Q1: 'my old answer' } as unknown as CognitoConfiguration;
const res = await parseInputs(input, mockAmplify, defaultFileName, stringMapsFileName, currentAnswers, mockContext);
res.default();
expect(defaults.getAllDefaults).not.toHaveBeenCalled();
});

it('should return the answer from context.updatingAuth if updatingAuth is present.', async () => {
mockContext.updatingAuth = { Q1: 'my old answer' };
mockContext.updatingAuth = { Q1: 'my old answer' } as unknown as CognitoConfiguration;
const res = await parseInputs(input, mockAmplify, defaultFileName, stringMapsFileName, currentAnswers, mockContext);
const def = res.default();
expect(def).toEqual('my old answer');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { $TSAny, $TSContext } from 'amplify-cli-core';
import { $TSAny } from 'amplify-cli-core';
import { AuthContext } from '../../../../context';
import { ServiceQuestionHeadlessResult } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/cognito-user-input-types';
import { structureOAuthMetadata } from '../../../../provider-utils/awscloudformation/service-walkthroughs/auth-questions';
import {
Expand Down Expand Up @@ -43,7 +44,7 @@ describe('update auth defaults applier', () => {
authSelections: 'userPoolOnly',
} as ServiceQuestionHeadlessResult;

const result = await getUpdateAuthDefaultsApplier({} as unknown as $TSContext, 'cognito-defaults.js', {} as $TSAny)(stubResult);
const result = await getUpdateAuthDefaultsApplier({} as unknown as AuthContext, 'cognito-defaults.js', {} as $TSAny)(stubResult);
expect(result).toMatchSnapshot();
expect(structureOAuthMetadata_mock.mock.calls.length).toBe(1);
});
Expand All @@ -55,7 +56,7 @@ describe('update auth defaults applier', () => {
requiredAttributes: [] as string[],
} as ServiceQuestionHeadlessResult;

const result = await getUpdateAuthDefaultsApplier({} as unknown as $TSContext, 'cognito-defaults.js', {} as $TSAny)(stubResult);
const result = await getUpdateAuthDefaultsApplier({} as unknown as AuthContext, 'cognito-defaults.js', {} as $TSAny)(stubResult);
expect(result.requiredAttributes).toEqual([]);
});
});
Expand All @@ -68,7 +69,7 @@ describe('add auth defaults applier', () => {
requiredAttributes: [] as string[],
} as ServiceQuestionHeadlessResult;

const result = await getAddAuthDefaultsApplier({} as unknown as $TSContext, 'cognito-defaults.js', 'testProjectName')(stubResult);
const result = await getAddAuthDefaultsApplier({} as unknown as AuthContext, 'cognito-defaults.js', 'testProjectName')(stubResult);
expect(result.requiredAttributes).toEqual([]);
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CognitoConfiguration } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/awsCognito-user-input-types';
import { FeatureFlags } from 'amplify-cli-core';
import { CognitoConfiguration } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/awsCognito-user-input-types';
FeatureFlags.getBoolean = () => false;
import { AttributeType } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/cognito-user-input-types';
import { doesConfigurationIncludeSMS } from '../../../../provider-utils/awscloudformation/utils/auth-sms-workflow-helper';
Expand Down
10 changes: 4 additions & 6 deletions packages/amplify-category-auth/src/commands/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,19 @@ import { run as runHelp } from './auth/help';

export const name = 'auth';

type AuthCommandType = {
name: string;
description: string;
};

/**
* Execute all auth cli commands
* @param context amplify cli context
* @returns auth command response
*/
export const run = async (context: $TSContext): Promise<$TSAny> => {
if (context.parameters.options.help) {
if (context.parameters.options?.help) {
return runHelp(context);
}
try {
if (!context.parameters.first) {
throw new TypeError('Missing command');
}
const { run: authRun } = await import(path.join('.', name, context.parameters.first));
return authRun(context);
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion packages/amplify-category-auth/src/commands/auth/remove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const run = async (context: $TSContext): Promise<void> => {
} catch (err) {
printer.info(err.stack);
printer.error('There was an error removing the auth resource');
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
}
};
Expand Down
5 changes: 3 additions & 2 deletions packages/amplify-category-auth/src/commands/auth/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { $TSContext, AmplifyCategories, AmplifySupportedService, BannerMessage,
import { printer } from 'amplify-prompts';
import _ from 'lodash';
import { category } from '../..';
import { AuthContext } from '../../context';
import { messages } from '../../provider-utils/awscloudformation/assets/string-maps';
import * as providerController from '../../provider-utils/awscloudformation/index';
import { checkAuthResourceMigration } from '../../provider-utils/awscloudformation/utils/check-for-auth-migration';
Expand All @@ -15,7 +16,7 @@ export const alias = ['update'];
/**
* entry point to update auth resource
*/
export const run = async (context: $TSContext): Promise<string | $TSContext | undefined> => {
export const run = async (context: AuthContext): Promise<string | $TSContext | undefined> => {
const { amplify } = context;
const servicesMetadata = getSupportedServices();
const meta = stateManager.getMeta();
Expand Down Expand Up @@ -83,7 +84,7 @@ export const run = async (context: $TSContext): Promise<string | $TSContext | un
} catch (err) {
printer.info(err.stack);
printer.error('There was an error adding the auth resource');
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
return undefined;
}
Expand Down
6 changes: 6 additions & 0 deletions packages/amplify-category-auth/src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { $TSContext } from 'amplify-cli-core';
import { CognitoConfiguration } from './provider-utils/awscloudformation/service-walkthrough-types/awsCognito-user-input-types';
export { CognitoConfiguration };
export type AuthContext = $TSContext & {
updatingAuth: CognitoConfiguration;
};
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,12 @@ export class AmplifyAuthTransform extends AmplifyCategoryTransform {
const triggerPermissions: AuthTriggerPermissions[] = permissions?.map((i: string) => JSON.parse(i));

// handle dependsOn data
const dependsOnKeys = Object.keys(this._cliInputs.cognitoConfig.triggers).map(
const dependsOnKeys = Object.keys(this._cliInputs.cognitoConfig.triggers ?? {}).map(
(i) => `${this._cliInputs.cognitoConfig.resourceName}${i}`,
);
const dependsOn = context.amplify.dependsOnBlock(context, dependsOnKeys, 'Cognito');
// generate trigger config
const keys = Object.keys(this._cliInputs.cognitoConfig.triggers);
const keys = Object.keys(this._cliInputs.cognitoConfig.triggers as string);
// Auth lambda config for Triggers
const authTriggerConnections: AuthTriggerConnection[] = [];
keys.forEach((key) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as path from 'path';
import { CognitoConfiguration } from './service-walkthrough-types/awsCognito-user-input-types';

// category
export const category = 'auth';
Expand Down Expand Up @@ -36,7 +37,7 @@ export const ENV_SPECIFIC_PARAMS = [
'hostedUIProviderCreds',
];

export const safeDefaults = [
export const safeDefaults: Array<keyof CognitoConfiguration> = [
'allowUnauthenticatedIdentities',
'thirdPartyAuth',
'authProviders',
Expand All @@ -50,7 +51,7 @@ export const safeDefaults = [
];

// These attributes cannot be modified once the auth resource is created
export const immutableAttributes = [
export const immutableAttributes: Array<keyof CognitoConfiguration> = [
'resourceName',
'userPoolName',
'identityPoolName',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { $TSAny, $TSContext, $TSObject, stateManager } from 'amplify-cli-core';
import { $TSAny, $TSObject, stateManager } from 'amplify-cli-core';
import { printer } from 'amplify-prompts';
import { ensureEnvParamManager } from '@aws-amplify/amplify-environment-parameters';
import { getSupportedServices } from '../../supported-services';
Expand All @@ -19,13 +19,14 @@ import {
removeDeprecatedProps,
updateUserPoolGroups,
} from '../utils/synthesize-resources';
import { AuthContext } from '../../../context';

/**
* Factory function that returns a CognitoCLIInputs consumer that handles all of the resource generation logic.
* The consumer returns the resourceName of the generated resource.
* @param context The amplify context
*/
export const getAddAuthHandler = (context: $TSContext) => async (request: ServiceQuestionHeadlessResult | CognitoConfiguration) => {
export const getAddAuthHandler = (context: AuthContext) => async (request: ServiceQuestionHeadlessResult | CognitoConfiguration) => {
const serviceMetadata = getSupportedServices()[request.serviceName];
const { defaultValuesFilename, provider } = serviceMetadata;

Expand Down Expand Up @@ -80,7 +81,7 @@ export const getAddAuthHandler = (context: $TSContext) => async (request: Servic
} catch (err: $TSAny) {
printer.info(err.stack);
printer.error('There was an error adding the auth resource');
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
}
return cognitoCLIInputs.cognitoConfig.resourceName;
Expand All @@ -89,9 +90,13 @@ export const getAddAuthHandler = (context: $TSContext) => async (request: Servic
/**
* Factory function that returns a CognitoConfiguration consumer and handles updates to the auth resource
*/
export const getUpdateAuthHandler = (context: $TSContext) => async (request: ServiceQuestionHeadlessResult | CognitoConfiguration) => {
export const getUpdateAuthHandler = (context: AuthContext) => async (request: ServiceQuestionHeadlessResult | CognitoConfiguration) => {
const { defaultValuesFilename } = getSupportedServices()[request.serviceName];
const requestWithDefaults = await getUpdateAuthDefaultsApplier(context, defaultValuesFilename, context.updatingAuth)(request);
const requestWithDefaults = await getUpdateAuthDefaultsApplier(
context,
defaultValuesFilename,
context.updatingAuth as CognitoConfiguration,
)(request);
const resources = stateManager.getMeta();
if (resources.auth.userPoolGroups) {
await updateUserPoolGroups(context, requestWithDefaults.resourceName!, requestWithDefaults.userPoolGroupList);
Expand Down Expand Up @@ -173,7 +178,7 @@ export const getUpdateAuthHandler = (context: $TSContext) => async (request: Ser
} catch (err: $TSAny) {
printer.info(err.stack);
printer.error('There was an error updating the auth resource');
context.usageData.emitError(err);
void context.usageData.emitError(err);
process.exitCode = 1;
}
return cognitoCLIInputs.cognitoConfig.resourceName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -965,8 +965,8 @@ export const importedAuthEnvInit = async (
const amplifyMeta = stateManager.getMeta();
const { Region } = amplifyMeta.providers[providerName];
const projectConfig = context.amplify.getProjectConfig();
const isPulling = context.input.command === 'pull' || (context.input.command === 'env' && context.input.subCommands[0] === 'pull');
const isEnvAdd = context.input.command === 'env' && context.input.subCommands[0] === 'add';
const isPulling = context.input.command === 'pull' || (context.input.command === 'env' && context.input.subCommands?.[0] === 'pull');
const isEnvAdd = context.input.command === 'env' && context.input.subCommands?.[0] === 'add';

if (isInHeadlessMode) {
// Validate required parameters' presence and merge into parameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ENV_SPECIFIC_PARAMS, AmplifyAdmin, UserPool, IdentityPool, BothPools, p
import { getAddAuthHandler, getUpdateAuthHandler } from './handlers/resource-handlers';
import { getSupportedServices } from '../supported-services';
import { importResource, importedAuthEnvInit } from './import';
import { AuthContext } from '../../context';

export { importResource } from './import';

Expand All @@ -25,15 +26,15 @@ const serviceQuestions = async (
return serviceWalkthrough(context, defaultValuesFilename, stringMapsFilename, serviceMetadata);
};

export const addResource = async (context: $TSContext, service: string): Promise<string> => {
export const addResource = async (context: AuthContext, service: string): Promise<string> => {
const serviceMetadata = getSupportedServices()[service];
const { defaultValuesFilename, stringMapsFilename, serviceWalkthroughFilename } = serviceMetadata;
return getAddAuthHandler(context)(
await serviceQuestions(context, defaultValuesFilename, stringMapsFilename, serviceWalkthroughFilename, serviceMetadata),
);
};

export const updateResource = async (context: $TSContext, { service }: { service: any }): Promise<any> => {
export const updateResource = async (context: AuthContext, { service }: { service: any }): Promise<any> => {
const serviceMetadata = getSupportedServices()[service];
const { defaultValuesFilename, stringMapsFilename, serviceWalkthroughFilename } = serviceMetadata;
return getUpdateAuthHandler(context)(
Expand Down Expand Up @@ -308,7 +309,7 @@ const parseCredsForHeadless = (mergedValues: any, envParams: any): any => {
/* eslint-enable no-param-reassign */

const getRequiredParamsForHeadlessInit = (projectType: any, previousValues: any): any => {
const requiredParams = [];
const requiredParams: string[] = [];

if (previousValues.thirdPartyAuth) {
if (previousValues.authProviders.includes('accounts.google.com')) {
Expand Down

0 comments on commit 3e2ff00

Please sign in to comment.