From 5c7e2b5872da908ec4d97eb639126c3c49070ad2 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 6 Mar 2024 12:18:22 -0800 Subject: [PATCH] chore(predictions): manual fix of linter reported errors --- .../AWSAIIdentifyPredictionsProvider.test.ts | 26 +++++------ packages/predictions/src/Predictions.ts | 3 -- .../AmazonAIConvertPredictionsProvider.ts | 12 ++--- .../AmazonAIIdentifyPredictionsProvider.ts | 45 +++++++++---------- .../AmazonAIInterpretPredictionsProvider.ts | 15 ++++--- .../src/providers/IdentifyTextUtils.ts | 6 +-- packages/predictions/src/providers/Utils.ts | 10 ++--- packages/predictions/src/types/Predictions.ts | 32 +++++++------ 8 files changed, 73 insertions(+), 76 deletions(-) diff --git a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts index 4280ea132d5..77d44ee8a7f 100644 --- a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts @@ -424,9 +424,9 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); - expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch( + expect(predictionsProvider.identify(detectLabelInput)).rejects.toThrow( 'error', ); }); @@ -448,11 +448,11 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); expect( predictionsProvider.identify(detectModerationInput), - ).rejects.toMatch('error'); + ).rejects.toThrow('error'); }); }); @@ -480,11 +480,11 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); expect( predictionsProvider.identify(detectModerationInput), - ).rejects.toMatch('error'); + ).rejects.toThrow('error'); }); }); }); @@ -532,9 +532,9 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); - expect(predictionsProvider.identify(detectFacesInput)).rejects.toMatch( + expect(predictionsProvider.identify(detectFacesInput)).rejects.toThrow( 'error', ); }); @@ -561,11 +561,11 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); expect( predictionsProvider.identify(recognizeCelebritiesInput), - ).rejects.toMatch('error'); + ).rejects.toThrow('error'); }); }); @@ -592,11 +592,11 @@ describe('Predictions identify provider test', () => { jest .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(() => { - return Promise.reject('error'); + return Promise.reject(new Error('error')); }); expect( predictionsProvider.identify(searchByFacesInput), - ).rejects.toMatch('error'); + ).rejects.toThrow('error'); }); }); }); @@ -718,7 +718,7 @@ describe('Predictions identify provider test', () => { const detectLabelInput = { labels: { source: null, type: 'LABELS' }, }; - expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch( + expect(predictionsProvider.identify(detectLabelInput)).rejects.toThrow( 'not configured correctly', ); }); diff --git a/packages/predictions/src/Predictions.ts b/packages/predictions/src/Predictions.ts index a5933582c1c..0b3721c094e 100644 --- a/packages/predictions/src/Predictions.ts +++ b/packages/predictions/src/Predictions.ts @@ -1,6 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { ConsoleLogger } from '@aws-amplify/core'; import { AmazonAIConvertPredictionsProvider, @@ -24,8 +23,6 @@ import { TranslateTextOutput, } from './types'; -const logger = new ConsoleLogger('Predictions'); - export class PredictionsClass { private convertProvider = new AmazonAIConvertPredictionsProvider(); private identifyProvider = new AmazonAIIdentifyPredictionsProvider(); diff --git a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts index fb0d76589d0..7ecbd4b7536 100644 --- a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts @@ -277,7 +277,7 @@ export class AmazonAIConvertPredictionsProvider { raw, languageCode, }: TranscribeData): Promise { - return new Promise((res, rej) => { + return new Promise((resolve, reject) => { let fullText = ''; connection.onmessage = message => { try { @@ -290,19 +290,19 @@ export class AmazonAIConvertPredictionsProvider { } } catch (err: unknown) { logger.debug(err); - rej(err); + reject(err); } }; connection.onerror = errorEvent => { logger.debug({ errorEvent }); - rej('failed to transcribe, network error'); + reject(new Error('failed to transcribe, network error')); }; connection.onclose = closeEvent => { logger.debug({ closeEvent }); - res(fullText.trim()); + resolve(fullText.trim()); }; logger.debug({ raw }); @@ -430,7 +430,7 @@ export class AmazonAIConvertPredictionsProvider { region: string; languageCode: string; }): Promise { - return new Promise(async (res, rej) => { + return new Promise((resolve, _reject) => { const signedUrl = this.generateTranscribeUrl({ credentials, region, @@ -443,7 +443,7 @@ export class AmazonAIConvertPredictionsProvider { connection.binaryType = 'arraybuffer'; connection.onopen = () => { logger.debug('connected'); - res(connection); + resolve(connection); }; }); } diff --git a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts index cd070eb9f21..3f38d0a6d07 100644 --- a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts @@ -51,12 +51,7 @@ import { isStorageSource, isValidIdentifyInput, } from '../types'; -import { - BlockList, - Document, - Image, - TextDetectionList, -} from '../types/AWSTypes'; +import { BlockList, Image, TextDetectionList } from '../types/AWSTypes'; import { categorizeRekognitionBlocks, @@ -107,7 +102,7 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} - Promise resolving to the converted source object. */ private configureSource(source: IdentifySource): Promise { - return new Promise((res, rej) => { + return new Promise((resolve, reject) => { if (isStorageSource(source)) { const storageConfig = { accessLevel: source.level, @@ -119,8 +114,9 @@ export class AmazonAIIdentifyPredictionsProvider { const parser = /https:\/\/([a-zA-Z0-9%\-_.]+)\.s3\.[A-Za-z0-9%\-._~]+\/([a-zA-Z0-9%\-._~/]+)\?/; const parsedURL = value.url.toString().match(parser) ?? ''; - if (parsedURL.length < 3) rej('Invalid S3 key was given.'); - res({ + if (parsedURL.length < 3) + reject(new Error('Invalid S3 key was given.')); + resolve({ S3Object: { Bucket: parsedURL[1], Name: decodeURIComponent(parsedURL[2]), @@ -128,34 +124,34 @@ export class AmazonAIIdentifyPredictionsProvider { }); }) .catch(err => { - rej(err); + reject(err); }); } else if (isFileSource(source)) { blobToArrayBuffer(source.file) .then(buffer => { - res({ Bytes: new Uint8Array(buffer) }); + resolve({ Bytes: new Uint8Array(buffer) }); }) .catch(err => { - rej(err); + reject(err); }); } else if (isIdentifyBytesSource(source)) { const { bytes } = source; if (bytes instanceof Blob) { blobToArrayBuffer(bytes) .then(buffer => { - res({ Bytes: new Uint8Array(buffer) }); + resolve({ Bytes: new Uint8Array(buffer) }); }) .catch(err => { - rej(err); + reject(err); }); } if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) { - res({ Bytes: new Uint8Array(bytes) } as Image); + resolve({ Bytes: new Uint8Array(bytes) } as Image); } // everything else can be directly passed to Rekognition / Textract. - res({ Bytes: bytes } as Image); + resolve({ Bytes: bytes } as Image); } else { - rej('Input source is not configured correctly.'); + reject(new Error('Input source is not configured correctly.')); } }); } @@ -190,9 +186,8 @@ export class AmazonAIIdentifyPredictionsProvider { credentials, customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(), }); - let inputDocument: Document; - inputDocument = await this.configureSource(input.text?.source); + const inputDocument = await this.configureSource(input.text?.source); // get default value if format isn't specified in the input. const format = input.text?.format ?? configFormat; @@ -304,8 +299,8 @@ export class AmazonAIIdentifyPredictionsProvider { /** * Calls Rekognition.detectLabels and organizes the returned data. - * @param {DetectLabelsInput} param - parameter to be passed onto Rekognition - * @return {Promise} - Promise resolving to organized detectLabels response. + * @param param - parameters as {@link DetectLabelsCommandInput} to be passed onto Rekognition + * @return a promise resolving to organized detectLabels response as {@link IdentifyLabelsOutput}. */ private async detectLabels( param: DetectLabelsCommandInput, @@ -335,8 +330,8 @@ export class AmazonAIIdentifyPredictionsProvider { /** * Calls Rekognition.detectModerationLabels and organizes the returned data. - * @param {Rekognition.DetectLabelsRequest} param - Parameter to be passed onto Rekognition - * @return {Promise} - Promise resolving to organized detectModerationLabels response. + * @param param parameter to be passed onto Rekognition as {@link DetectModerationLabelsCommandInput} + * @return a promise resolving to organized detectModerationLabels response as {@link IdentifyLabelsOutput}. */ private async detectModerationLabels( param: DetectModerationLabelsCommandInput, @@ -357,8 +352,8 @@ export class AmazonAIIdentifyPredictionsProvider { /** * Identify faces within an image that is provided as input, and match faces from a collection * or identify celebrities. - * @param {IdentifyEntityInput} input - object containing the source image and face match options. - * @return {Promise} Promise resolving to identify results. + * @param input - object of {@link IdentifyEntitiesInput} containing the source image and face match options. + * @return a promise resolving to identify results as {@link IdentifyEntitiesOutput}. */ protected async identifyEntities( input: IdentifyEntitiesInput, diff --git a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts index cd192fe514e..1d3e1b3b245 100644 --- a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts @@ -63,9 +63,9 @@ export class AmazonAIInterpretPredictionsProvider { const { text: textSource } = input; const { source, type = defaultType } = textSource; const { text } = source; - let language; + let sourceLanguage; if (isInterpretTextOthers(textSource)) { - language = (textSource as InterpretTextOthers).source.language; + sourceLanguage = (textSource as InterpretTextOthers).source.language; } this.comprehendClient = new ComprehendClient({ @@ -79,7 +79,7 @@ export class AmazonAIInterpretPredictionsProvider { const doAll = type === 'all'; - let languageCode = language; + let languageCode = sourceLanguage; if (doAll || type === 'language') { const languageDetectionParams = { Text: text, @@ -161,9 +161,9 @@ export class AmazonAIInterpretPredictionsProvider { try { const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params); const data = await this.comprehendClient!.send(detectKeyPhrasesCommand); - const { KeyPhrases = [] } = data || {}; + const { KeyPhrases: keyPhrases = [] } = data || {}; - return KeyPhrases.map(({ Text: text }) => { + return keyPhrases.map(({ Text: text }) => { return { text }; }); } catch (err: any) { @@ -222,7 +222,7 @@ export class AmazonAIInterpretPredictionsProvider { Neutral: neutral = 0, Mixed: mixed = 0, } = {}, - } = ({} = data); + } = data ?? {}; return { predominant, positive, negative, neutral, mixed }; } catch (err: any) { @@ -275,7 +275,8 @@ export class AmazonAIInterpretPredictionsProvider { const data = await this.comprehendClient!.send( detectDominantLanguageCommand, ); - const { Languages: [{ LanguageCode }] = [{}] } = ({} = data || {}); + const { Languages: [{ LanguageCode }] = [{ LanguageCode: undefined }] } = + data ?? {}; assertValidationError( !!LanguageCode, PredictionsValidationErrorCode.NoLanguage, diff --git a/packages/predictions/src/providers/IdentifyTextUtils.ts b/packages/predictions/src/providers/IdentifyTextUtils.ts index 83b2302debe..8c93a4e3afe 100644 --- a/packages/predictions/src/providers/IdentifyTextUtils.ts +++ b/packages/predictions/src/providers/IdentifyTextUtils.ts @@ -133,7 +133,7 @@ export function categorizeTextractBlocks( blockMap[block.Id] = block; } break; - case 'SELECTION_ELEMENT': + case 'SELECTION_ELEMENT': { const selectionStatus = block.SelectionStatus === 'SELECTED'; if (!response.text.selections) response.text.selections = []; response.text.selections.push({ @@ -145,6 +145,7 @@ export function categorizeTextractBlocks( blockMap[block.Id] = block; } break; + } case 'TABLE': tableBlocks.push(block); break; @@ -197,8 +198,7 @@ export function categorizeTextractBlocks( * @param {[id: string]: Block} blockMap - Maps block Ids to blocks. */ function constructTable(table: Block, blockMap: Record): Table { - let tableMatrix: TableCell[][]; - tableMatrix = []; + const tableMatrix: TableCell[][] = []; // visit each of the cell associated with the table's relationship. for (const tableRelation of table.Relationships ?? []) { for (const cellId of tableRelation.Ids ?? []) { diff --git a/packages/predictions/src/providers/Utils.ts b/packages/predictions/src/providers/Utils.ts index 8a461ed06f2..d661ed170e4 100644 --- a/packages/predictions/src/providers/Utils.ts +++ b/packages/predictions/src/providers/Utils.ts @@ -9,7 +9,7 @@ export function makeCamelCase(obj?: any, keys?: string[]) { const newObj = {}; const keysToRename = keys || Object.keys(obj); keysToRename.forEach(key => { - if (obj.hasOwnProperty(key)) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { // change the key to camelcase. const camelCaseKey = key.charAt(0).toLowerCase() + key.substr(1); Object.assign(newObj, { [camelCaseKey]: obj[key] }); @@ -32,18 +32,18 @@ export function makeCamelCaseArray(objArr?: object[], keys?: string[]) { * Converts blob to array buffer */ export function blobToArrayBuffer(blob: Blob): Promise { - return new Promise((res, rej) => { + return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = _event => { - res(reader.result as Uint8Array); + resolve(reader.result as Uint8Array); }; reader.onerror = err => { - rej(err); + reject(err); }; try { reader.readAsArrayBuffer(blob); } catch (err) { - rej(err); // in case user gives invalid type + reject(err); // in case user gives invalid type } }); } diff --git a/packages/predictions/src/types/Predictions.ts b/packages/predictions/src/types/Predictions.ts index 2b87b9bf79f..04a2ad5de4e 100644 --- a/packages/predictions/src/types/Predictions.ts +++ b/packages/predictions/src/types/Predictions.ts @@ -242,7 +242,7 @@ export interface IdentifyLabelsOutput { labels?: { name?: string; boundingBoxes?: (BoundingBox | undefined)[]; - metadata?: Object; + metadata?: object; }[]; unsafe?: 'YES' | 'NO' | 'UNKNOWN'; } @@ -342,43 +342,47 @@ export function isIdentifyFromCollection( const key: keyof IdentifyFromCollection = 'collection'; const keyId: keyof IdentifyFromCollection = 'collectionId'; - return obj && (obj.hasOwnProperty(key) || obj.hasOwnProperty(keyId)); + return ( + obj && + (Object.prototype.hasOwnProperty.call(obj, key) || + Object.prototype.hasOwnProperty.call(obj, keyId)) + ); } export function isIdentifyCelebrities(obj: any): obj is IdentifyCelebrities { const key: keyof IdentifyCelebrities = 'celebrityDetection'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isTranslateTextInput(obj: any): obj is TranslateTextInput { const key: keyof TranslateTextInput = 'translateText'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isTextToSpeechInput(obj: any): obj is TextToSpeechInput { const key: keyof TextToSpeechInput = 'textToSpeech'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isSpeechToTextInput(obj: any): obj is SpeechToTextInput { const key: keyof SpeechToTextInput = 'transcription'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isStorageSource(obj: any): obj is StorageSource { const key: keyof StorageSource = 'key'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isFileSource(obj: any): obj is FileSource { const key: keyof FileSource = 'file'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isConvertBytesSource( @@ -386,7 +390,7 @@ export function isConvertBytesSource( ): obj is BytesSource { const key: keyof BytesSource = 'bytes'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isIdentifyBytesSource( @@ -394,19 +398,19 @@ export function isIdentifyBytesSource( ): obj is BytesSource { const key: keyof BytesSource = 'bytes'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isIdentifyTextInput(obj: any): obj is IdentifyTextInput { const key: keyof IdentifyTextInput = 'text'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isIdentifyLabelsInput(obj: any): obj is IdentifyLabelsInput { const key: keyof IdentifyLabelsInput = 'labels'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isIdentifyEntitiesInput( @@ -414,13 +418,13 @@ export function isIdentifyEntitiesInput( ): obj is IdentifyEntitiesInput { const key: keyof IdentifyEntitiesInput = 'entities'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isInterpretTextInput(obj: any): obj is InterpretTextInput { const key: keyof InterpretTextInput = 'text'; - return obj && obj.hasOwnProperty(key); + return obj && Object.prototype.hasOwnProperty.call(obj, key); } export function isInterpretTextOthers(