Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add validator utils #107

Merged
merged 5 commits into from
Jun 24, 2024
Merged

feat: add validator utils #107

merged 5 commits into from
Jun 24, 2024

Conversation

koladilip
Copy link
Collaborator

@koladilip koladilip commented Jun 21, 2024

What are the changes introduced in this PR?

Add validators for mappings and refactor error classes

What is the related Linear task?

Resolves INT-2240

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

Summary by CodeRabbit

  • New Features

    • Enhanced mapping functionality to extract coupon information.
    • Introduced custom error handling with new error classes for lexer, parser, and translator.
    • Added new scenario with simple array mappings for user information.
  • Bug Fixes

    • Improved error handling in filter and wildcard selector logic.
  • Tests

    • Added test cases for validating JSON paths and mappings.
    • Updated test scenarios to include new mappings and error message changes.

@koladilip koladilip requested a review from a team as a code owner June 21, 2024 11:28
Copy link

coderabbitai bot commented Jun 21, 2024

Walkthrough

The recent updates primarily enhance the JsonTemplateEngine by introducing new utility functions for JSON path validation and mapping preparation, while also improving error handling. Additional test cases and scenarios were added to ensure robustness. Several error classes were reorganized and structures were improved for better clarity and maintainability. Specific regex operations were fine-tuned in the reverse translator to handle JSON paths more efficiently.

Changes

Files Change Summaries
src/engine.test.ts, src/engine.ts Added test cases and validation functions (isValidJSONPath, prepareMappings, validateMappings) to JsonTemplateEngine
.../errors/index.ts, .../errors/lexer.ts Introduced new error classes: JsonTemplateLexerError, JsonTemplateMappingError, JsonTemplateParserError, JsonTemplateTranslatorError
src/lexer.ts, src/parser.ts, src/translator.ts Reorganized import statements for various custom error classes
src/utils/converter.ts Enhanced filter processing, output mapping, introduced mapping validation function with JsonTemplateMappingError
test/scenarios/mappings/... Added new mapping scenarios, including all_features.json and simple_array_mappings.json
.../reverse_translator.ts Modified regex operations for JsonTemplateReverseTranslator to handle JSON paths more consistently

Poem

In the code's quiet lines we delve so deep,
With mappings fine and JSON paths to keep.
Errors now are clearer, like a crystal stream,
Validators strong, precise as a dream.
Oh, code that flows, like rabbits we leap,
Over tests and mappings, our promise we keep. 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Jun 21, 2024

Coverage report

St.
Category Percentage Covered / Total
🟢 Statements
93.61% (-6.39% 🔻)
4510/4818
🟢 Branches
93.82% (-6.18% 🔻)
1139/1214
🟢 Functions 100% 362/362
🟢 Lines
93.61% (-6.39% 🔻)
4510/4818
Show new covered files 🐣
St.
File Statements Branches Functions Lines
🟢 errors/index.ts 100% 100% 100% 100%
🟢 errors/lexer.ts 100% 100% 100% 100%
🟢 errors/mapping.ts 100% 100% 100% 100%
🟢 errors/parser.ts 100% 100% 100% 100%
🟢
... / translator.ts
100% 100% 100% 100%
Show files with reduced coverage 🔻
St.
File Statements Branches Functions Lines
🟢 engine.ts
98.72% (-1.28% 🔻)
91.67% (-8.33% 🔻)
100%
98.72% (-1.28% 🔻)
🟢 lexer.ts
87.11% (-12.89% 🔻)
91.82% (-8.18% 🔻)
100%
87.11% (-12.89% 🔻)
🟢 parser.ts
88.33% (-11.67% 🔻)
89.89% (-10.11% 🔻)
100%
88.33% (-11.67% 🔻)
🟢 utils/common.ts 100%
94.44% (-5.56% 🔻)
100% 100%
🟢 utils/converter.ts
91.99% (-8.01% 🔻)
92% (-8% 🔻)
100%
91.99% (-8.01% 🔻)

Test suite run success

198 tests passing in 6 suites.

Report generated by 🧪jest coverage report action from 6103188

@koladilip koladilip force-pushed the feat.add-validator-utils branch from 6d452fb to 277c593 Compare June 21, 2024 11:29
Copy link

codecov bot commented Jun 21, 2024

Codecov Report

Attention: Patch coverage is 96.21212% with 5 lines in your changes missing coverage. Please review.

Project coverage is 91.78%. Comparing base (97d95e8) to head (6103188).
Report is 39 commits behind head on main.

Files Patch % Lines
src/utils/converter.ts 92.06% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main     #107      +/-   ##
===========================================
- Coverage   100.00%   91.78%   -8.22%     
===========================================
  Files           14       18       +4     
  Lines         4565     4818     +253     
  Branches      1082     1055      -27     
===========================================
- Hits          4565     4422     -143     
- Misses           0      389     +389     
- Partials         0        7       +7     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

utsabc
utsabc previously approved these changes Jun 21, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range and nitpick comments (8)
src/engine.ts (1)

Line range hint 19-19: Avoid Using 'Function' as a Type

The use of 'Function' as a type should be avoided due to its broad acceptance of any function-like value, which can lead to subtle bugs. It's recommended to explicitly define the function shape to ensure type safety and clarity.

- private readonly fn: Function;
+ private readonly fn: (data: unknown, bindings: Record<string, unknown>) => unknown;

- private static compileAsSync(template: TemplateInput, options?: EngineOptions): Function {
+ private static compileAsSync(template: Template
Input, options?: EngineOptions): (data: unknown, bindings: Record<string, unknown>) => unknown;

- private static compileAsAsync(templateOrExpr: TemplateInput, options?: EngineOptions): Function {
+ private static compileAsAsync(templateOrExpr: TemplateInput, options?: EngineOptions): (data: unknown, bindings: Record<string, unknown>) => unknown;

- static create(templateOrExpr: TemplateInput, options?: EngineOptions): JsonTemplateEngine {
+ static create(templateOrExpr: TemplateInput, options?: Engine
Options): (data: unknown, bindings: Record<string, unknown>) => unknown;

Also applies to: 21-21, 25-25, 34-34

src/lexer.ts (1)

Line range hint 370-370: Avoid Using this in Static Context

The use of this in a static context can be confusing as it refers to the class itself rather than an instance. It's recommended to use the class name instead to avoid confusion and maintain clarity in the code.

- this.isValidRegExp(regexp, modifiers)
+ JsonTemplateLexer.isValidRegExp(regexp, modifiers)
src/translator.ts (2)

Line range hint 900-900: Static context usage of this is confusing.

The static analysis tool flagged the use of this in a static context. This is generally a bad practice as it can lead to confusion about what this refers to. It's recommended to use the class name instead of this when referring to static methods or properties.

- this.getPathOptions
+ JsonTemplateTranslator.getPathOptions

- this.isArrayFilterExpr
+ JsonTemplateTranslator.isArrayFilterExpr

- this.returnIsEmpty
+ JsonTemplateTranslator.returnIsEmpty

- this.returnIsNotEmpty
+ JsonTemplateTranslator.returnIsNotEmpty

- this.returnObjectValues
+ JsonTemplateTranslator.returnObjectValues

- this.convertToSingleValueIfSafe
+ JsonTemplateTranslator.convertToSingleValueIfSafe

- this.covertToArrayValue
+ JsonTemplateTranslator.covertToArrayValue

Line range hint 900-900: Consider optimizing the initialization of variables.

In the translate method, every call re-initializes the vars, lastVarId, and unusedVars. If this method is called frequently, consider optimizing how these variables are reset to avoid potential performance bottlenecks.

- this.vars = [];
- this.lastVarId = 0;
- this.unusedVars = [];
+ this.resetVars();

And then implement a resetVars method that handles these operations.

src/parser.ts (4)

Line range hint 1519-1519: Clarify usage of this in static context.

The static method ignoreEmptySelectors uses this which can be confusing as it suggests that the method might be using instance-specific data, which it should not. Consider refactoring to use the class name JsonTemplateParser instead of this to access static methods or properties.

- return parts.filter(this.isValidPathPart);
+ return parts.filter(JsonTemplateParser.isValidPathPart);

Line range hint 1525-1525: Clarify usage of this in static context.

Similar to the previous comment, the static method combinePathOptionParts uses this which can be misleading. Use the class name instead.

- return newParts.push(this.createPathOptionPart(currPart, nextPart));
+ return newParts.push(JsonTemplateParser.createPathOptionPart(currPart, nextPart));

Line range hint 1532-1532: Clarify usage of this in static context.

Again in convertToFunctionCallExpr, replace this with JsonTemplateParser to access static methods.

- if (lastPart?.type === SyntaxType.SELECTOR && this.isSimpleSelector(lastPart)) {
+ if (lastPart?.type === SyntaxType.SELECTOR && JsonTemplateParser.isSimpleSelector(lastPart)) {

Line range hint 1574-1574: Clarify usage of this in static context.

In the static method updatePathExpr, use JsonTemplateParser instead of this to call static methods.

- if (shouldConvertAsBlock) this.convertToBlockExpr(expr);
+ if (shouldConvertAsBlock) JsonTemplateParser.convertToBlockExpr(expr);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cb50968 and 277c593.

Files selected for processing (12)
  • src/engine.test.ts (1 hunks)
  • src/engine.ts (2 hunks)
  • src/errors/index.ts (1 hunks)
  • src/errors/lexer.ts (1 hunks)
  • src/errors/mapping.ts (1 hunks)
  • src/errors/parser.ts (1 hunks)
  • src/errors/translator.ts (1 hunks)
  • src/lexer.ts (1 hunks)
  • src/parser.ts (1 hunks)
  • src/translator.ts (1 hunks)
  • src/utils/converter.ts (4 hunks)
  • test/scenarios/mappings/data.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • src/errors/index.ts
  • test/scenarios/mappings/data.ts
Additional context used
Biome
src/engine.ts

[error] 19-19: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 21-21: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 25-25: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 34-34: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

src/lexer.ts

[error] 370-370: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.

src/translator.ts

[error] 900-900: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.

src/parser.ts

[error] 1519-1519: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1525-1525: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1532-1532: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1574-1574: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 562-562: Do not add then to an object. (lint/suspicious/noThenProperty)

GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)
src/engine.ts

[warning] 64-64: 🌿 Branch is not covered
Warning! Not covered branch


[warning] 65-65: 🌿 Branch is not covered
Warning! Not covered branch

src/utils/converter.ts

[warning] 262-262: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 263-263: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 264-264: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 265-265: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 261-267: 🌿 Branch is not covered
Warning! Not covered branch

GitHub Check: codecov/patch
src/utils/converter.ts

[warning] 262-265: src/utils/converter.ts#L262-L265
Added lines #L262 - L265 were not covered by tests

Additional comments not posted (11)
src/errors/lexer.ts (1)

1-1: Class Declaration: JsonTemplateLexerError

The class JsonTemplateLexerError is correctly extending the base Error class. This is a straightforward and clean implementation for custom error handling specific to the lexer component.

src/errors/parser.ts (1)

1-1: Class Declaration: JsonTemplateParserError

Similar to JsonTemplateLexerError, the JsonTemplateParserError extends the base Error class appropriately. This maintains consistency across custom error classes for different components, aiding in clear and specific error reporting.

src/errors/translator.ts (1)

1-1: Class Declaration: JsonTemplateTranslatorError

The JsonTemplateTranslatorError also extends the Error class, which is consistent with the other custom error classes introduced in this PR. This consistency is beneficial for maintaining a uniform approach to error handling across different modules.

src/engine.test.ts (1)

3-69: Comprehensive Test Suite for JsonTemplateEngine

The test suite thoroughly covers the new functionality introduced in JsonTemplateEngine. It includes tests for valid and invalid JSON paths and mappings, which is essential for ensuring the robustness of the validation logic. The tests are well-structured and cover a variety of cases, which is great for catching edge cases early in development.

src/engine.ts (2)

47-59: Efficient JSON Path Validation Method

The isValidJSONPath method efficiently checks the validity of JSON paths using structured parsing and error handling. This method is crucial for ensuring that only valid paths are processed, thus preventing potential runtime errors and ensuring data integrity.


61-83: Mapping Validation and Preparation Logic

The methods prepareMappings and validateMappings are well-implemented, with clear logic separation and error handling. They ensure that the mappings are correctly formatted before being processed, which is essential for the stability and reliability of the mapping functionality.

Tools
GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)

[warning] 64-64: 🌿 Branch is not covered
Warning! Not covered branch


[warning] 65-65: 🌿 Branch is not covered
Warning! Not covered branch

src/utils/converter.ts (1)

96-100: Enhanced Error Specificity in Conversion Utilities

The use of JsonTemplateMappingError in various conversion utility functions enhances the specificity and traceability of errors, which is crucial for debugging and maintaining the code. The custom error messages provide clear context about the issue, making it easier to diagnose and fix problems.

Also applies to: 118-121, 262-265

src/translator.ts (2)

9-9: Update the import statement for JsonTemplateTranslatorError.

The import path for JsonTemplateTranslatorError has been updated to reference the specific file instead of a general directory, which is a good practice for maintainability and clarity.


Line range hint 900-900: Add a default case in the switch statement of translateExpr.

It's good practice to have a default case in switch statements to handle unexpected values gracefully.

[REFACTOR_Suggestion]

  switch (expr.type) {
    ...
+   default:
+     throw new Error("Unsupported expression type: " + expr.type);
  }
src/parser.ts (2)

4-5: Update import paths to specific error modules.

The import paths for JsonTemplateParserError and JsonTemplateLexerError have been updated to point directly to their respective modules. This change is good as it avoids potential circular dependencies and makes the import paths clearer.


Line range hint 562-562: Check the use of 'then' in object properties.

The static analysis tool flagged the use of 'then' as a property in an object which might be a typo or incorrect property name. Please verify if this is intentional or needs correction.

Verification successful

No instances of the 'then' property were found in src/parser.ts, confirming that it is not used inappropriately within object definitions.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Search for 'then' property within object definitions.

# Test: Search for 'then' property. Expect: No occurrences unless explicitly justified.
rg --type typescript $'.then' src/parser.ts

Length of output: 77



Script:

#!/bin/bash
# Description: Search for 'then' property within object definitions in src/parser.ts

# Test: Search for 'then' property. Expect: No occurrences unless explicitly justified.
rg '\.then' src/parser.ts

Length of output: 27

src/errors/mapping.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Outside diff range and nitpick comments (7)
src/engine.ts (1)

Line range hint 19-19: Replace generic Function type with specific function signatures

The use of the Function type is discouraged due to its broad acceptance of any function-like values, which can lead to bugs. Consider specifying more detailed function signatures for clarity and type safety.

- private readonly fn: Function;
+ private readonly fn: (data: any, bindings: any) => any;

Also applies to: 21-21, 25-25, 34-34

test/scenarios/mappings/data.ts (1)

155-163: Standardized error messages across different scenarios

The error message 'Invalid mapping' is used consistently across various scenarios. This is good for consistency, but consider providing more specific error messages to help diagnose issues more effectively.

src/lexer.ts (1)

Line range hint 370-370: Avoid using this in static context

The use of this in a static method can lead to confusion and bugs. Consider using the class name instead to access static members or methods.

- this.isValidRegExp(regexp, modifiers);
+ JsonTemplateLexer.isValidRegExp(regexp, modifiers);
src/translator.ts (3)

Line range hint 900-900: Clarify usage of this in static context.

The use of this in a static context can be confusing as it suggests an instance-specific operation, which is not the case in static methods. Consider using the class name JsonTemplateTranslator instead to clarify that these operations are class-specific.

- this.translateExpr(expr.update, update, ctx);
+ JsonTemplateTranslator.translateExpr(expr.update, update, ctx);

Line range hint 900-900: Ensure correct use of class name in static context.

The use of this in a static method can lead to confusion or errors in some languages or environments, as this typically refers to an instance of the class, not the class itself. To ensure clarity and correctness, replace this with JsonTemplateTranslator when calling static methods or accessing static properties.

- this.generateAssignmentCode(dest, incrementCode);
+ JsonTemplateTranslator.generateAssignmentCode(dest, incrementCode);

Line range hint 900-900: Clarification on static method calls within the class.

Static methods should be called with the class name rather than this to avoid confusion and to make the code more readable and maintainable, especially in a static context where this does not refer to an instance of the class.

- this.acquireVar();
+ JsonTemplateTranslator.acquireVar();
src/parser.ts (1)

Line range hint 1519-1519: Clarification on using this in static methods.

The static analysis tool flagged the use of this in static methods as potentially confusing. In static methods, this refers to the class itself, not an instance. If these methods are intended to be static, consider using the class name (JsonTemplateParser) instead of this to access static properties or methods, which could improve the clarity of the code.

- this.someStaticMethod();
+ JsonTemplateParser.someStaticMethod();

Also applies to: 1525-1525, 1532-1532, 1574-1574

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cb50968 and a6fc5d9.

Files selected for processing (14)
  • src/engine.test.ts (1 hunks)
  • src/engine.ts (2 hunks)
  • src/errors/index.ts (1 hunks)
  • src/errors/lexer.ts (1 hunks)
  • src/errors/mapping.ts (1 hunks)
  • src/errors/parser.ts (1 hunks)
  • src/errors/translator.ts (1 hunks)
  • src/lexer.ts (1 hunks)
  • src/parser.ts (1 hunks)
  • src/translator.ts (1 hunks)
  • src/utils/converter.ts (5 hunks)
  • test/scenarios/mappings/all_features.json (1 hunks)
  • test/scenarios/mappings/data.ts (4 hunks)
  • test/scenarios/mappings/simple_array_mappings.json (1 hunks)
Files skipped from review due to trivial changes (4)
  • src/errors/index.ts
  • src/errors/lexer.ts
  • src/errors/translator.ts
  • test/scenarios/mappings/simple_array_mappings.json
Additional context used
Learnings (1)
src/utils/converter.ts (1)
User: koladilip
PR: rudderlabs/rudder-json-template-engine#97
File: src/utils/converter.ts:169-184
Timestamp: 2024-06-15T03:36:36.164Z
Learning: Validations for `flatMapping` and `currentOutputPropAST` are performed before they are passed to the `handleNextParts` function in `src/utils/converter.ts`.
Biome
src/engine.ts

[error] 19-19: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 21-21: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 25-25: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 34-34: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

src/lexer.ts

[error] 370-370: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.

src/translator.ts

[error] 900-900: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.

src/parser.ts

[error] 1519-1519: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1525-1525: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1532-1532: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 1574-1574: Using this in a static context can be confusing. (lint/complexity/noThisInStatic)

this refers to the class.
Unsafe fix: Use the class name instead.


[error] 562-562: Do not add then to an object. (lint/suspicious/noThenProperty)

GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)
src/engine.ts

[warning] 64-64: 🌿 Branch is not covered
Warning! Not covered branch


[warning] 65-65: 🌿 Branch is not covered
Warning! Not covered branch

src/utils/converter.ts

[warning] 87-87: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 286-286: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 287-287: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 288-288: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 289-289: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 86-88: 🌿 Branch is not covered
Warning! Not covered branch


[warning] 285-291: 🌿 Branch is not covered
Warning! Not covered branch

Additional comments not posted (10)
src/errors/mapping.ts (1)

1-11: Class implementation looks solid!

The JsonTemplateMappingError class is well-implemented with appropriate TypeScript annotations and a detailed constructor that enhances error messages. Good job on addressing the previous feedback.

test/scenarios/mappings/all_features.json (1)

14-17: New mapping for coupons is correctly implemented.

The mapping from $.coupon to $.events[0].items[*].coupon_code is well-formed and follows JSONPath syntax. This should work as intended in the engine.

src/engine.test.ts (2)

3-25: Comprehensive testing of JSON path validation.

The test cases for isValidJSONPath are comprehensive, covering both valid and invalid scenarios effectively. This ensures robust validation within the engine.


27-67: Robust testing for mappings validation.

The test cases for validateMappings effectively check for compatibility and correctness of mappings. The scenarios include both valid mappings and expected failures, which is crucial for ensuring the engine's reliability in handling mappings.

src/engine.ts (2)

47-59: Ensure robustness in JSON path validation method

The isValidJSONPath method uses a try-catch block to handle exceptions which is good for robustness. However, consider logging the error or providing more detailed feedback when the path validation fails, as this could aid in debugging and provide clearer error messages to the users.
[REFACTOR_SUGGESTion]


61-67: Refactor suggestion for prepareMappings method

The method prepareMappings efficiently maps input and output by providing defaults. However, it's crucial to ensure that the properties from and to are always expected to be optionally present in the mappings, as this code assumes their existence.

Tools
GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)

[warning] 64-64: 🌿 Branch is not covered
Warning! Not covered branch


[warning] 65-65: 🌿 Branch is not covered
Warning! Not covered branch

test/scenarios/mappings/data.ts (1)

Line range hint 79-96: Addition of coupon_code in the output scenarios

The addition of coupon_code to the scenarios is consistent with the new mappings added. Ensure that all related mappings and transformations are correctly implemented and covered by unit tests to avoid issues in production.

src/translator.ts (1)

9-9: Update import path for JsonTemplateTranslatorError.

The import path for JsonTemplateTranslatorError has been updated to reflect its new location under the errors/translator directory. This is consistent with the restructuring of error classes as mentioned in the PR summary and ensures that imports remain accurate and maintainable.

src/parser.ts (2)

4-5: Update import paths to reflect new error class locations.

The import statements for JsonTemplateParserError and JsonTemplateLexerError have been updated to reflect their new locations in the errors/parser and errors/lexer directories. This change aligns with the PR's objective to refactor error handling by organizing error classes into specific files.


Line range hint 562-562: Verify the use of a property named then.

The static analysis tool flagged the use of a property named then as potentially suspicious. This might be a false positive, but it's important to ensure that this property is not unintentionally making an object look like a Promise, which could lead to unexpected behavior.

Verification successful

No issue with the then property usage.

The then property is used within the context of translating conditional expressions in both src/reverse_translator.ts and src/translator.ts. This usage does not mimic Promises and should not cause any confusion.

  • src/reverse_translator.ts: translateConditionalExpressionBody(expr.then)
  • src/translator.ts: translateExpr(expr.then, dest, ctx)
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Search for the usage of the 'then' property in the project.
rg --type typescript $'.then'

Length of output: 63



Script:

#!/bin/bash
# Description: Search for the usage of the 'then' property in TypeScript files.
rg '\.then' --glob '*.ts'

Length of output: 195



Script:

#!/bin/bash
# Extract the context where `then` is used in `src/reverse_translator.ts`.
rg --context 5 'then' src/reverse_translator.ts

# Extract the context where `then` is used in `src/translator.ts`.
rg --context 5 'then' src/translator.ts

Length of output: 951

src/errors/parser.ts Show resolved Hide resolved
src/engine.ts Outdated Show resolved Hide resolved
src/engine.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a6fc5d9 and 63b6fbf.

Files selected for processing (1)
  • src/utils/converter.ts (5 hunks)
Additional context used
Learnings (1)
src/utils/converter.ts (1)
User: koladilip
PR: rudderlabs/rudder-json-template-engine#97
File: src/utils/converter.ts:169-184
Timestamp: 2024-06-15T03:36:36.164Z
Learning: Validations for `flatMapping` and `currentOutputPropAST` are performed before they are passed to the `handleNextParts` function in `src/utils/converter.ts`.
GitHub Check: codecov/patch
src/utils/converter.ts

[warning] 86-86: src/utils/converter.ts#L86
Added line #L86 was not covered by tests


[warning] 88-88: src/utils/converter.ts#L88
Added line #L88 was not covered by tests


[warning] 287-290: src/utils/converter.ts#L287-L290
Added lines #L287 - L290 were not covered by tests

GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)
src/utils/converter.ts

[warning] 85-86: 🌿 Branch is not covered
Warning! Not covered branch

Additional comments not posted (1)
src/utils/converter.ts (1)

2-2: Imports and Constants:

The import of JsonTemplateMappingError from the new errors directory is correct and aligns with the PR's purpose of enhancing error handling. The use of EMPTY_EXPR from constants ensures consistency.

src/utils/converter.ts Outdated Show resolved Hide resolved
src/utils/converter.ts Outdated Show resolved Hide resolved
src/utils/converter.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range and nitpick comments (1)
src/reverse_translator.ts (1)

Line range hint 3-3: Ensure consistent use of destructuring in imports.

For consistency and to reduce the length of the import lines, consider using destructuring for all imports from the same module.

- import { ArrayExpression, ArrayFilterExpression, AssignmentExpression, BinaryExpression, BlockExpression, ConditionalExpression, DefinitionExpression, EngineOptions, Expression, FunctionCallExpression, FunctionExpression, IncrementExpression, IndexFilterExpression, LambdaArgExpression, LiteralExpression, LoopControlExpression, LoopExpression, ObjectExpression, ObjectFilterExpression, ObjectPropExpression, PathExpression, PathOptions, PathType, RangeFilterExpression, ReturnExpression, SelectorExpression, SpreadExpression, StatementsExpression, SyntaxType, ThrowExpression, TokenType, UnaryExpression } from './types';
+ import * as Types from './types';
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 63b6fbf and ba0e79a.

Files selected for processing (2)
  • src/engine.ts (2 hunks)
  • src/reverse_translator.ts (1 hunks)
Additional context used
Biome
src/engine.ts

[error] 19-19: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 21-21: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 25-25: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.


[error] 34-34: Don't use 'Function' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

Additional comments not posted (2)
src/engine.ts (1)

3-3: Refactor the import of JsonTemplateMappingError to use destructuring.

To maintain consistency with other import statements in this file, consider using destructuring for importing JsonTemplateMappingError.

- import { JsonTemplateMappingError } from './errors/mapping';
+ import { JsonTemplateMappingError, JsonTemplateLexer, JsonTemplateParser, JsonTemplateReverseTranslator, JsonTemplateTranslator } from './errors';

Likely invalid or redundant comment.

src/reverse_translator.ts (1)

Line range hint 5-5: Optimize string operations in translation methods.

Using template literals or array joins for string operations in the translate method can enhance performance and readability, especially when manipulating strings based on conditional logic.
[PERFORMANCE]

  let code: string = this.translateExpression(expr);
- code = code.replace(/\.\s+\./g, '.');
+ code = code.replaceAll(/\.\s+\./g, '.');
  if (this.options?.defaultPathType === PathType.JSON) {
-   code = code.replace(/\^/g, '$');
+   code = code.replaceAll(/\^/g, '$');
  }

src/engine.ts Show resolved Hide resolved
src/engine.ts Show resolved Hide resolved
src/engine.ts Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ba0e79a and 535ecd6.

Files selected for processing (1)
  • src/utils/converter.ts (5 hunks)
Additional context used
Learnings (1)
src/utils/converter.ts (1)
User: koladilip
PR: rudderlabs/rudder-json-template-engine#97
File: src/utils/converter.ts:169-184
Timestamp: 2024-06-15T03:36:36.164Z
Learning: Validations for `flatMapping` and `currentOutputPropAST` are performed before they are passed to the `handleNextParts` function in `src/utils/converter.ts`.
GitHub Check: codecov/patch
src/utils/converter.ts

[warning] 86-86: src/utils/converter.ts#L86
Added line #L86 was not covered by tests


[warning] 88-88: src/utils/converter.ts#L88
Added line #L88 was not covered by tests


[warning] 287-290: src/utils/converter.ts#L287-L290
Added lines #L287 - L290 were not covered by tests

GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)
src/utils/converter.ts

[warning] 288-288: 🧾 Statement is not covered
Warning! Not covered statement


[warning] 286-292: 🌿 Branch is not covered
Warning! Not covered branch

src/utils/converter.ts Outdated Show resolved Hide resolved
src/utils/converter.ts Outdated Show resolved Hide resolved
Copy link

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 535ecd6 and 6103188.

Files selected for processing (1)
  • src/utils/converter.ts (4 hunks)
Additional context used
GitHub Check: codecov/patch
src/utils/converter.ts

[warning] 113-113: src/utils/converter.ts#L113
Added line #L113 was not covered by tests


[warning] 295-298: src/utils/converter.ts#L295-L298
Added lines #L295 - L298 were not covered by tests

GitHub Check: Coverage annotations (🧪 jest-coverage-report-action)
src/utils/converter.ts

[warning] 112-114: 🌿 Branch is not covered
Warning! Not covered branch

src/utils/converter.ts Show resolved Hide resolved
src/utils/converter.ts Show resolved Hide resolved
src/utils/converter.ts Show resolved Hide resolved
src/utils/converter.ts Show resolved Hide resolved
src/utils/converter.ts Show resolved Hide resolved
src/utils/converter.ts Show resolved Hide resolved
@koladilip koladilip merged commit db1260d into main Jun 24, 2024
13 checks passed
@koladilip koladilip deleted the feat.add-validator-utils branch June 24, 2024 05:16
@coderabbitai coderabbitai bot mentioned this pull request Oct 16, 2024
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants