From 1bd6d8b76cec76d78cf4410f594dcf7e22cb749f Mon Sep 17 00:00:00 2001 From: Panagiotis Bakatselos Date: Tue, 14 May 2024 08:47:55 +0200 Subject: [PATCH] fix: Fix marker function parsing when used after bracket syntax casting expression (#45) Fixes #43 --- src/parsers/marker.parser.ts | 14 ++++++++++++-- tests/parsers/marker.parser.spec.ts | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/parsers/marker.parser.ts b/src/parsers/marker.parser.ts index 1015be56..c9812dae 100644 --- a/src/parsers/marker.parser.ts +++ b/src/parsers/marker.parser.ts @@ -1,4 +1,5 @@ -import { tsquery } from '@phenomnomnominal/tsquery'; +import { ScriptKind, tsquery } from '@phenomnomnominal/tsquery'; +import { extname } from 'path'; import { ParserInterface } from './parser.interface.js'; import { TranslationCollection } from '../utils/translation.collection.js'; @@ -9,7 +10,16 @@ const MARKER_IMPORT_NAME = 'marker'; export class MarkerParser implements ParserInterface { public extract(source: string, filePath: string): TranslationCollection | null { - const sourceFile = tsquery.ast(source, filePath); + const supportedScriptTypes: Record = { + '.js': ScriptKind.JS, + '.jsx': ScriptKind.JSX, + '.ts': ScriptKind.TS, + '.tsx': ScriptKind.TSX + }; + + const scriptKind = supportedScriptTypes[extname(filePath)] ?? ScriptKind.TS; + + const sourceFile = tsquery.ast(source, filePath, scriptKind); const markerImportName = getNamedImportAlias(sourceFile, MARKER_MODULE_NAME, MARKER_IMPORT_NAME); if (!markerImportName) { diff --git a/tests/parsers/marker.parser.spec.ts b/tests/parsers/marker.parser.spec.ts index db6f0e90..ec20cfb1 100644 --- a/tests/parsers/marker.parser.spec.ts +++ b/tests/parsers/marker.parser.spec.ts @@ -71,4 +71,20 @@ describe('MarkerParser', () => { const keys = parser.extract(contents, componentFilename).keys(); expect(keys).to.deep.equal(['Hello world']); }); + + it('should not break after bracket syntax casting', () => { + const contents = ` + import { marker } from '@colsen1991/ngx-translate-extract-marker'; + + marker('hello'); + const input: unknown = 'hello'; + const myNiceVar1 = input as string; + marker('hello.after.as.syntax'); + + const myNiceVar2 = input; + marker('hello.after.bracket.syntax'); + `; + const keys = parser.extract(contents, componentFilename).keys(); + expect(keys).to.deep.equal(['hello', 'hello.after.as.syntax', 'hello.after.bracket.syntax']); + }); });