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

[New] add types #603

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

[New] add types #603

wants to merge 1 commit into from

Conversation

ljharb
Copy link
Collaborator

@ljharb ljharb commented Mar 2, 2024

Normally I'd just push this commit up and publish it, but since @types/tape already exists, I thought this was worth a PR so others can double check me.

@Raynos
Copy link
Collaborator

Raynos commented Mar 4, 2024

Are these hand written or generated from JSDoc ? It's unclear to me. Either way looks reasonable to me.

@ljharb
Copy link
Collaborator Author

ljharb commented Mar 4, 2024

Hand-written.

Copy link

coderabbitai bot commented Mar 8, 2024

Walkthrough

Walkthrough

The update introduces comprehensive JSDoc type annotations across various JavaScript files to enhance type safety and documentation. This includes adjustments to function parameters and return types, new type definitions, and enhancements to existing logic, improving code clarity and robust type-checking during development.

Changes

File Path Change Summary
.github/.../node-aught.yml Changed the skip-ls-check option to true under the jobs section.
bin/import-or-require.js Added JSDoc type annotation for the importOrRequire function's parameter and return type.
bin/tape Added JSDoc type annotations for the importFiles function and filesPromise variable.
index.d.ts Introduced new type declarations, functions, and interfaces for a testing harness using tape.
index.js Added JSDoc type annotations for multiple functions and updated module exports.
lib/default_stream.d.ts, lib/default_stream.js Introduced type annotations for the buffer buf in the write function.
lib/results.d.ts, lib/results.js Defined the Results class, added numerous type annotations, and enhanced functions.
lib/test.d.ts, lib/test.js Added the Test class with constructors and methods for testing functionalities; included extensive JSDoc type annotations.
test/common.js Added JSDoc typedefs for imported modules and defined new functions with specific signatures.

Sequence Diagrams

No sequence diagrams generated due to the nature of changes primarily adding type annotations and enhancing existing functionality.


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 92aa51c and e80d128.

Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • tsconfig.json is excluded by !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review due to trivial changes (3)
  • .github/workflows/node-aught.yml
  • lib/default_stream.d.ts
  • lib/results.d.ts
Files skipped from review as they are similar to previous changes (7)
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • index.js
  • lib/default_stream.js
  • lib/results.js
  • test/common.js
Additional context used
Biome
lib/test.d.ts

[error] 112-112: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 126-126: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 192-192: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 198-198: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

Additional comments not posted (3)
lib/test.d.ts (2)

210-210: Avoid using {} as a type.

The use of {} as a type is discouraged. Consider defining a specific object shape instead.

Apply this diff to define a specific object shape:

- export type RestoreFunction = Exclude<ReturnType<typeof mockProperty>, undefined>;
+ export type RestoreFunction = () => void;

Likely invalid or redundant comment.


38-38: Avoid using Function as a type.

The use of Function as a type is discouraged. Consider defining a specific function type instead.

Apply this diff to define a specific function type:

- /** @typedef {Function} Callback */
+ /** @typedef {(...args: unknown[]) => unknown} Callback */

Likely invalid or redundant comment.

lib/test.js (1)

Line range hint 83-123: Constructor implementation is appropriate.

The constructor correctly initializes properties and binds methods.

Ensure all methods are correctly bound to the instance.

Run the following script to verify method bindings:

Verification successful

Method bindings are correctly implemented.

The Test constructor iterates over its properties and binds functions using callBind, confirming that method bindings are handled as expected. The use of @ts-expect-error is acknowledged in the code. No further issues were found.

  • Method bindings are correctly handled in lines 121-126.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all methods are correctly bound to the `Test` instance.

# Test: Search for method bindings. Expect: All instance methods are bound.
rg --type js -A 5 $'this[prop] = callBind(this[prop], this)'

Length of output: 61


Script:

#!/bin/bash
# Description: Search for method definitions within the `Test` class and check for bindings.

# Find the `Test` constructor and methods within the same file.
ast-grep --lang javascript --pattern $'function Test($_, $_, $_) {
  $$$
  this.$_ = $_;
  $$$
}'

Length of output: 1727


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 Configuration 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

@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.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between eafacf6 and 2ad380e.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (8 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (42 hunks)
  • test/common.js (4 hunks)
Additional comments: 43
lib/default_stream.d.ts (1)
  • 1-5: The TypeScript declaration file for defaultStream correctly defines the function's return type as ThroughStream and uses the appropriate CommonJS export syntax. This enhances type safety and code clarity.
.github/workflows/node-aught.yml (1)
  • 12-12: Adding skip-ls-check: true to the workflow configuration is a valid optimization that can potentially speed up the CI process by skipping unnecessary checks.
bin/import-or-require.js (1)
  • 7-7: The type annotation for the importOrRequire function accurately specifies its parameter and return types, enhancing code readability and type safety.
lib/default_stream.js (2)
  • 6-6: The type annotation for the exported module correctly references its own declaration file, which is a good practice for maintaining consistency between the implementation and its TypeScript definitions.
  • 18-28: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]

The refactoring of the write function to handle different types of input buffers more explicitly improves the function's readability and robustness. The type annotation for buf as unknown and the subsequent type assertion are appropriate given the function's need to handle various input types.

lib/results.d.ts (1)
  • 1-54: The TypeScript declaration file for Results accurately defines the class's structure, methods, and related types. This addition significantly enhances type safety and code clarity, making it easier to work with Results instances and their associated data.
index.d.ts (1)
  • 1-72: The TypeScript declaration file for the tape testing library accurately defines the library's API, including test options, assert options, test cases, stream options, and the harness. This addition significantly enhances type safety and code clarity, making it easier to work with tests and their configurations.
bin/tape (2)
  • 98-98: The type annotation for the importFiles function accurately specifies its parameter and return types, enhancing code readability and maintainability.
  • 108-108: The type annotation for the filesPromise variable clarifies its type as a Promise, which is appropriate given its role in handling asynchronous file imports. This enhances code readability and maintainability.
test/common.js (4)
  • 8-8: The type annotation for the getDiag function accurately specifies its parameters and return type, enhancing code readability and maintainability.
  • 42-42: The type annotation for the stripChangingData function accurately specifies its parameter and return type, enhancing code readability and maintainability.
  • 67-67: The type annotation for the stripFullStack function accurately specifies its parameter and return type, enhancing code readability and maintainability.
  • 103-103: The type annotation for the runProgram function accurately specifies its parameters and return type, enhancing code readability and maintainability.
index.js (7)
  • 4-4: The addition of the through import is appropriate for stream operations within this file, aligning with the changes made to introduce stream functionality.
  • 16-18: The type definitions (Tape, Harness, HarnessConfig) provide clear and concise information about the types used within this file, enhancing code readability and maintainability.
  • 25-25: The getHarness function is correctly typed and provides a mechanism to lazily initialize the harness, which is a good practice for resource management.
  • 55-55: The createStream function is correctly typed and provides a clear interface for creating a stream, enhancing the library's functionality and usability.
  • 80-80: The createHarness function is well-documented and correctly typed, providing a foundational piece for creating test harnesses. This enhances the library's extensibility and usability.
  • 142-142: The createExitHarness function introduces a mechanism to handle process exit behavior, which is crucial for a testing library. The function is correctly typed and well-documented.
  • 204-207: The modifications to exports, including the workaround for circular exports, are necessary and correctly implemented to ensure the library's API is correctly exposed and usable.
lib/results.js (11)
  • 21-22: The type aliases Stream and Result provide clear and concise information about the types used within this file, enhancing code readability and maintainability.
  • 24-24: The coalesceWhiteSpaces function is correctly typed and provides a utility for string manipulation, which is useful for formatting output.
  • 29-29: The getNextTest function is correctly typed and provides a mechanism for iterating over tests, which is crucial for running tests in sequence.
  • 45-45: The invalidYaml function is correctly typed and provides a utility for YAML validation, which is useful for ensuring test result output is correctly formatted.
  • 50-50: The encodeResult function is correctly typed and provides a mechanism for encoding test results into a TAP-compliant format, enhancing the library's compatibility with TAP consumers.
  • 102-105: The constructor documentation for Results provides clear information about the function's purpose and its parameters, enhancing code readability and maintainability.
  • 122-122: The createStream method is correctly typed and provides a clear interface for creating a stream of test results, enhancing the library's functionality and usability.
  • 185-185: The push method is correctly typed and provides a mechanism for adding tests to the results, which is crucial for managing test execution.
  • 192-192: The only method is correctly typed and provides a mechanism for specifying a single test to run, which is useful for focused testing.
  • 197-197: The _watch method is correctly typed and provides a mechanism for monitoring test execution, which is crucial for managing test results.
  • 233-233: The close method is correctly typed and provides a mechanism for finalizing test results, which is crucial for ensuring test completion and outputting final results.
lib/test.d.ts (4)
  • 1-3: The imports at the beginning of the file are clear and concise, correctly importing only the types needed for this declaration file.
  • 11-172: The Test class declaration and its method signatures are well-defined, providing clear type annotations for parameters and return types. This significantly improves the usability and type safety of the Test class in TypeScript projects. However, there are a couple of minor issues to address:
  • Line 9: There's an extra semicolon at the end of the import statement. While this is not a syntax error, it's unnecessary and should be removed for consistency and cleanliness.
  • General: Ensure that all callback types (Test.Callback) and option types (Options) are defined and correctly imported or declared within this file or its dependencies. This is crucial for maintaining the integrity and usability of the type declarations.
- } from './results';;
+ } from './results';

Please verify that all referenced types (Test.Callback, Options, etc.) are correctly defined and accessible within this context.

  • 174-220: The Test namespace provides additional type definitions that are essential for the detailed and specific typing of callback functions, call results, and other utility types used within the Test class. This is a good practice as it encapsulates related types within the namespace of the class they support, enhancing modularity and readability.
  • 222-222: Exporting the Test class using export = Test; is appropriate for this module pattern and ensures compatibility with CommonJS imports. This is a good practice for TypeScript declaration files that correspond to JavaScript modules intended to be used in Node.js environments.
lib/test.js (8)
  • 15-15: The modification of the is module import to use object-is/polyfill instead of object-is is a significant change that enhances compatibility across different environments by ensuring a consistent implementation of the Object.is method. This change is particularly important for environments that may not support Object.is natively.
  • 38-44: The isErrorConstructor function and its type definition (IsErrorConstructor) are well-implemented, providing a robust way to check if a given constructor is one of the standard JavaScript error constructors. This is crucial for error handling and validation within the Test class methods. However, there's a minor improvement that can be made for readability:
  • Consider adding a brief comment explaining the purpose of the isErrorConstructor function and why there are two different implementations based on the environment. This will help future maintainers understand the rationale behind this design choice.

Consider adding explanatory comments for the isErrorConstructor function.

  • 54-54: The getTestArgs function is correctly annotated with a JSDoc comment, providing type information for its parameters and return type. This enhances code readability and helps TypeScript users understand the expected types, even though this is a JavaScript file. Good practice in maintaining type annotations in comments for JavaScript projects that may be used alongside TypeScript.
  • 108-128: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [125-141]

The run method implementation correctly handles asynchronous test callbacks by supporting both synchronous and Promise-based asynchronous tests. This is a crucial feature for a testing framework, allowing users to write tests that perform asynchronous operations. However, there's a minor improvement that can be made for error handling:

  • When handling Promise rejection, consider checking if err is an instance of a specific error class (e.g., AssertionError) to provide more detailed error messages or handling specific to assertion errors. This can improve the debugging experience for users.

Consider enhancing error handling in the Promise rejection case by checking for specific error types.

  • 166-170: The test method correctly creates and manages child test instances, allowing for nested tests. This is a key feature for a testing framework, enabling complex test structures and hierarchies. The implementation is clear and follows best practices for event-driven programming with Node.js' EventEmitter. However, ensure that the Test class and its methods are thoroughly tested, especially with nested tests, to prevent any potential issues with event handling or state management.

Consider adding more comprehensive tests for the test method, particularly focusing on nested tests and event handling.

  • 191-194: The comment method implementation is straightforward and correctly emits test result comments as events. This allows for flexible reporting and integration with test runners or other tools. It's a good practice to support comments in testing frameworks, as they can provide valuable context or explanations alongside test results.
  • 218-218: The end method's implementation correctly handles error reporting and ensures that .end() is called only once per test instance. This is crucial for maintaining the integrity of test results and preventing duplicate or misleading output. However, consider adding more explicit error handling or logging for cases where .end() is called multiple times, to aid in debugging such issues.

Consider enhancing error handling for multiple calls to .end() to improve debuggability.

  • 231-231: The teardown method provides a mechanism for registering teardown functions to be executed after a test completes. This is an essential feature for cleaning up resources or state between tests. The implementation is clear and follows best practices. However, ensure that teardown functions are always called, even if a test fails or times out, to prevent resource leaks or interference between tests.

Verify that teardown functions are correctly executed in all scenarios, including test failures and timeouts.

lib/test.js Show resolved Hide resolved
lib/default_stream.js Show resolved Hide resolved
test/common.js Outdated Show resolved Hide resolved
@ljharb ljharb force-pushed the tsc branch 2 times, most recently from 54b4f2d to decd5d2 Compare March 8, 2024 23:59
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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 91a83b6 and decd5d2.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (8 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (8)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • lib/default_stream.d.ts
  • lib/results.d.ts
  • lib/test.d.ts
  • lib/test.js
Additional comments: 26
lib/default_stream.js (4)
  • 6-6: Adding a type annotation for the module export is a good practice for clarity and type safety. This change enhances the maintainability of the code by making the expected type of the exported function explicit.
  • 12-12: The type annotation for the write function parameter buf as unknown is appropriate here since the function is designed to handle various types of input. This use of unknown encourages type checking within the function, improving code safety.
  • 21-21: The casting of buf to string | ArrayLike<number> is necessary given the subsequent operations on b. However, ensure that this casting aligns with the expected types of buf throughout the application to prevent runtime errors.
  • 22-25: The loop iterates over b, handling both string and ArrayLike<number> types. This approach is flexible but relies on the correct type casting of buf. Consider adding more explicit type checks or documentation to clarify the expected types of buf for future maintainability.
test/common.js (5)
  • 8-8: Adding type annotations for the getDiag function improves code clarity by specifying the expected parameter types and return type. This change enhances maintainability by making the function's contract explicit.
  • 42-42: The type annotation for the stripChangingData function is clear and accurately describes the function's purpose and expected input/output. This addition aids in understanding the function's role in processing test output.
  • 67-67: The type annotation for the stripFullStack function is a good practice, making the function's behavior and return type explicit. This change contributes to the overall maintainability and readability of the test utilities.
  • 103-103: The type annotation for the runProgram function clearly defines the expected parameters and their types, as well as the callback's signature. This explicit typing is beneficial for maintainability and understanding the function's usage.
  • 5-11: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [111-111]

The concern regarding potential security issues with user input going into path.join or path.resolve functions is noted. However, as this is a test file and the inputs are controlled within the test environment, the risk is minimal. It's important to remain vigilant about such patterns in production code.

index.js (7)
  • 16-18: The addition of type declarations for Tape, Harness, and HarnessConfig is a significant improvement for type safety and code clarity. These declarations help developers understand the expected types and interfaces within the library.
  • 25-25: The getHarness function's type annotation enhances the function's readability by making the optional parameter and return type explicit. This change is beneficial for maintainability and type safety.
  • 35-35: The type annotation for the lazyLoad function and its usage of Parameters<Tape> and ReturnType<Tape> is a clever way to ensure type consistency with the Tape interface. This approach maintains type safety across the library.
  • 55-55: The type annotation for the createStream function within lazyLoad is clear and accurately describes the expected parameter and return type. This explicit typing aids in understanding the function's purpose and usage.
  • 80-80: The createHarness function's documentation and type annotations provide a clear understanding of its purpose and usage. This explicit typing and documentation are beneficial for maintainability and clarity.
  • 142-142: The createExitHarness function's type annotation and detailed implementation comments enhance the understanding of its purpose and behavior. This explicit typing and documentation contribute to the code's maintainability and clarity.
  • 204-207: The workaround for resolving circular exports by assigning module.exports to a variable and then modifying that variable is a practical solution to a common issue in JavaScript modules. However, ensure that this pattern is consistently understood and documented across the codebase to avoid confusion.
lib/results.js (10)
  • 21-22: The introduction of type aliases Stream and Result is a significant improvement, enhancing code readability and maintainability by providing clear, reusable type definitions.
  • 24-24: The coalesceWhiteSpaces function's type annotation is straightforward and accurately describes the function's behavior. This explicit typing is beneficial for understanding the function's purpose.
  • 29-29: The type annotation for the getNextTest function clearly defines the expected parameter and return type, improving the function's readability and maintainability.
  • 45-45: The invalidYaml function's type annotation is clear and accurately describes the function's expected input and output. This explicit typing aids in understanding the function's role in YAML validation.
  • 50-50: The encodeResult function's type annotation and detailed implementation enhance the understanding of its purpose and behavior. This explicit typing and documentation contribute to the code's maintainability and clarity.
  • 102-105: The constructor documentation for Results and the addition of type annotations for its parameters improve the class's readability and maintainability. This explicit typing and documentation are beneficial for understanding the class's purpose and usage.
  • 122-122: The type annotation for the createStream method in the Results class clearly defines the expected parameter and return type, enhancing the method's readability and maintainability.
  • 185-185: The push method's type annotation in the Results class is straightforward and accurately describes the method's behavior. This explicit typing is beneficial for understanding the method's purpose.
  • 192-192: The only method's type annotation in the Results class is clear and accurately describes the method's expected input. This explicit typing aids in understanding the method's role in test execution.
  • 233-233: The close method's type annotation in the Results class enhances the method's readability by making the expected behavior explicit. This change contributes to the overall maintainability and clarity of the class.

lib/default_stream.js Show resolved Hide resolved
Copy link
Contributor

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Cool to see this addition - thanks for mentioning it!

I can take a deeper look if the tsc having a lot of errors already thing isn't a blocker.

bin/import-or-require.js Show resolved Hide resolved
tsconfig.json Outdated Show resolved Hide resolved
package.json Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
@ljharb
Copy link
Collaborator Author

ljharb commented Mar 11, 2024

Thanks, I've updated the PR and gotten it down to 4 errors (i swear it was at zero when I put up the PR :-p)

I'd love to get suggestions for those.

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 91a83b6 and 4ee0620.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (8 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • lib/default_stream.d.ts
  • lib/results.d.ts
  • lib/results.js
  • lib/test.d.ts
  • lib/test.js
Additional comments: 21
lib/default_stream.js (4)
  • 6-6: The type annotation for the module export is correctly specified, enhancing type safety and clarity for consumers of this module.
  • 18-28: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]

The write function's type annotation for buf as unknown is appropriate, given the function's intent to handle various types of input. The explicit handling of different buffer types, including nullish values and strings, is well-implemented. However, consider adding a comment explaining the rationale behind treating Object(buf) !== buf as a condition to flush the buffer, as it might not be immediately clear to future maintainers.

  • 21-21: Using a type assertion for b as either string or ArrayLike<number> is a pragmatic approach to handle the two expected types of buffers. This assertion allows for type-safe operations within the loop that follows. Good use of type annotations to ensure type safety.
  • 3-15: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [47-47]

The use of innerHTML for appending content, especially in a library context, can lead to XSS vulnerabilities. This concern was previously raised, and the justification was that it's for IE < 9 compatibility. While the explanation is valid, it's crucial to document this exception clearly in the code to inform future maintainers of the security implications and the specific use case. It appears that a comment regarding the use of innerHTML for IE < 9 compatibility is indeed present, albeit in a concise form. It's good practice to ensure such exceptions are well-documented.

test/common.js (5)
  • 8-8: The type annotation for getDiag function is correctly specified, clearly indicating the function's parameters and return type. This enhances the readability and maintainability of the code.
  • 42-42: The type annotation for stripChangingData function is correctly specified. This function's purpose is well-documented through its type annotation, improving code clarity.
  • 67-67: The type annotation for stripFullStack function is correctly specified, clearly indicating the function's parameter and return type. This addition aids in understanding the function's usage and expected behavior.
  • 103-103: The type annotation for runProgram function is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.
  • 5-11: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [111-111]

The concern regarding potential security issues with user input going into a path.join or path.resolve function, which could lead to a path traversal vulnerability, has been addressed. It's noted that this is a test file, and there is no security concern here. It's good practice to be vigilant about potential security vulnerabilities, even in test environments, but in this case, the concern is not applicable.

index.js (12)
  • 4-4: The addition of the through module import is correctly implemented. This import is necessary for the functionality introduced in this file.
  • 16-22: The type definitions added for Tape, Harness, HarnessConfig, TestOptions, HarnessEventHandler, CreateStream, and Result are correctly specified. These definitions enhance the code's readability and maintainability by providing clear type information.
  • 29-29: The getHarness function is correctly annotated with its return type. The comment about the override due to test failures via nyc is helpful for future maintainers to understand the rationale behind the current implementation.
  • 39-39: The lazyLoad function's type annotation is correctly specified, enhancing the function's clarity by indicating the expected parameters and return type.
  • 59-59: The createStream function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This addition aids in understanding the function's usage and expected behavior.
  • 84-84: The createHarness function's type annotation is correctly specified, enhancing the function's clarity by indicating the expected parameters and return type.
  • 91-91: The test function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.
  • 112-112: The createStream method within the test function is correctly annotated, enhancing clarity and maintainability by providing type information for the parameters and return type.
  • 117-117: The onFinish method within the test function is correctly annotated, providing clear type information that enhances the code's readability and maintainability.
  • 122-122: The onFailure method within the test function is correctly annotated, enhancing the code's clarity by providing type information for the parameters and return type.
  • 146-146: The createExitHarness function's type annotation is correctly specified, providing clear information about the function's parameters and return type. This enhances the function's readability and maintainability.
  • 208-211: The modifications to the module exports to resolve a circular export issue are correctly implemented. This hack is necessary due to TypeScript's limitations with circular exports, and it's good practice to document such workarounds for future maintainers.

coderabbitai[bot]

This comment was marked as outdated.

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.

Review Status

Actionable comments generated: 6

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between aa7de58 and 74db73b.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • lib/default_stream.d.ts
  • lib/results.d.ts
  • lib/results.js
  • lib/test.d.ts
  • lib/test.js
Additional comments: 3
lib/default_stream.js (2)
  • 6-6: The addition of a type annotation for the module export is a good practice for clarity and type safety.
  • 12-12: The type annotation for the write function parameter buf as unknown is appropriate, considering the function's logic to handle various types of input. This ensures type safety while allowing flexibility in the input types.
test/common.js (1)
  • 8-10: The addition of type definitions via @typedef for external modules enhances the clarity and maintainability of the code by providing explicit type information. This is a good practice for projects that aim to improve type safety and documentation.

lib/default_stream.js Show resolved Hide resolved
index.js Outdated Show resolved Hide resolved
index.js 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.

Review Status

Actionable comments generated: 4

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between aa7de58 and b4dfc21.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (9)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • lib/default_stream.d.ts
  • lib/results.d.ts
  • lib/results.js
  • lib/test.d.ts
  • lib/test.js
Additional comments: 3
lib/default_stream.js (1)
  • 6-6: The addition of type annotations enhances code clarity and TypeScript compatibility.
test/common.js (1)
  • 11-11: The addition of type annotations for getDiag enhances code clarity and TypeScript compatibility.
index.js (1)
  • 16-26: The addition of type definitions for various entities enhances code clarity and TypeScript compatibility.

Comment on lines 18 to 28
flush();
return;
}
for (var i = 0; i < buf.length; i++) {
var c = typeof buf === 'string'
? buf.charAt(i)
: String.fromCharCode(buf[i]);
var b = /** @type {string | ArrayLike<number>} */ (buf); // eslint-disable-line no-extra-parens
for (var i = 0; i < b.length; i++) {
var c = typeof b === 'string'
? b.charAt(i)
: String.fromCharCode(b[i]);
if (c === '\n') {
flush();
} else {
Copy link

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]

The casting of buf to string | ArrayLike<number> is sensible given the function's need to support both string and buffer inputs. However, ensure that this casting is safe by validating the input type before casting, as incorrect assumptions about the type can lead to runtime errors.

Consider adding explicit type checks before casting to ensure safety.

lib/default_stream.js Show resolved Hide resolved
test/common.js Show resolved Hide resolved
index.js 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.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 732268b and b4e7807.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Additional comments: 47
lib/default_stream.d.ts (1)
  • 1-5: The TypeScript definition for defaultStream is correctly implemented with appropriate use of type imports, declaration, and export syntax.
.github/workflows/node-aught.yml (1)
  • 12-12: The addition of skip-ls-check: true to the workflow configuration is syntactically correct. Please ensure that skipping the ls check aligns with the project's CI/CD goals.
bin/import-or-require.js (1)
  • 7-7: The concise JSDoc type annotation for importOrRequire is appropriate and correctly specifies the parameter and return types. The decision to use a less verbose annotation style aligns with previous discussions and preferences.
lib/default_stream.js (2)
  • 6-6: The type declaration for the module is correctly implemented, enhancing the code's readability and maintainability.
  • 18-28: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [12-25]

The type annotations and logic within the write function are correctly implemented. The handling of different types for buf and the subsequent processing are sound.

lib/results.d.ts (1)
  • 1-52: The TypeScript definitions in lib/results.d.ts are correctly implemented, with well-defined class properties, methods, and additional type definitions within the namespace. The use of imports, declare, and export syntax aligns with TypeScript best practices.
index.d.ts (1)
  • 1-82: The comprehensive type definitions in index.d.ts enhance the library's usability and clarity. The structure and organization of types, interfaces, and function overloads align well with TypeScript best practices. The approach respects the project's preferences regarding documentation and code separation.
bin/tape (2)
  • 98-98: The type annotation for the importFiles function is correctly implemented, enhancing the clarity of the function's purpose and expected parameter type.
  • 108-108: The type annotation for the filesPromise variable is correctly implemented, clarifying the expected type and enhancing code maintainability.
test/common.js (5)
  • 8-9: The addition of typedefs for Result and SyncCallback enhances the clarity and maintainability of the test utilities by providing clear type definitions.
  • 11-11: The type annotation for the getDiag function is correctly implemented, providing clear documentation on the expected parameter types and return type.
  • 45-45: The type annotation for the stripChangingData function is correctly implemented, enhancing the readability and maintainability of the function.
  • 70-70: The type annotation for the stripFullStack function is correctly implemented, providing clear documentation on the expected parameter type and return type.
  • 106-106: The type annotation for the runProgram function is correctly implemented, enhancing the clarity of the function's purpose and expected parameter types.
index.js (6)
  • 11-12: The use of /** @type {{ browser?: boolean }} */ for type casting in the condition to check if process is not running in a browser environment is a clever way to provide type information for TypeScript without changing the runtime behavior. However, ensure that this casting accurately reflects the expected properties of the process object in all execution environments where this code might run.
  • 16-26: The addition of JSDoc type definitions (@typedef) enhances the readability and maintainability of the code by providing clear type information for various entities used throughout the file. This is a good practice, especially in a dynamically typed language like JavaScript, as it aids in understanding the expected types of variables and function parameters/returns.
  • 1-36: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [33-43]

The getHarness function correctly checks if a harness has already been created and, if not, creates one using createExitHarness. This lazy initialization pattern is efficient. However, consider adding error handling or logging within this function to catch and report potential issues during the harness creation process, especially since createExitHarness involves complex logic.

  • 63-63: The createStream method in lazyLoad is well-annotated with types, which improves code clarity. However, ensure that the fallback logic for when harness is not yet initialized (creating a new stream and getting the harness with specific options) is thoroughly tested, especially in concurrent scenarios where multiple streams might be created before the harness is initialized.
  • 87-87: The createHarness function is well-structured and makes good use of the Results class to manage test results. The handling of the todoIsOK environment variable and the autoclose behavior based on configuration are clear examples of thoughtful design. However, consider documenting the rationale behind the decision to automatically close results in most cases but allow for disabling this behavior through configuration.
  • 211-214: The workaround for TypeScript's bug with circular exports is cleverly documented with a comment. This kind of documentation is crucial for maintainability and understanding the rationale behind certain code patterns that might otherwise seem unusual. Good job on ensuring this hack is well-explained.
lib/results.js (7)
  • 28-28: The coalesceWhiteSpaces function is a simple utility that replaces multiple whitespace characters with a single space. This is useful for normalizing strings before output. Consider adding a brief comment explaining the purpose of this function, as utility functions can sometimes be unclear to new contributors or when revisiting the code after some time.
  • 33-33: The getNextTest function provides a mechanism to retrieve the next test to run, considering the _only property for focused testing. This logic is crucial for test runners that support .only syntax. Ensure that the handling of the _only property is thoroughly tested, especially in scenarios with nested tests or multiple .only calls across different test suites.
  • 49-49: The invalidYaml function checks if a string contains characters that could be interpreted as YAML indicators. This is an important check for generating accurate TAP output. However, the name invalidYaml might be slightly misleading as it checks for the presence of YAML indicators rather than validating YAML syntax. Consider renaming it to more accurately reflect its purpose, such as containsYamlIndicators.
  • 54-54: The encodeResult function has been modified to handle actualStack differently. This change is crucial for providing more detailed error information in test results. Ensure that this modification is compatible with all expected input types for res.actual and res.error, and consider adding tests specifically for this logic to verify its behavior across different error scenarios.
  • 106-106: The Results constructor now accepts an options parameter, which is used to configure the todoIsOK property. This enhancement allows for more flexible configuration of test result handling. Ensure that the handling of the options parameter is thoroughly tested, especially with regards to default values and edge cases where options might be malformed or contain unexpected properties.
  • 126-126: The createStream method in Results.prototype has been enhanced to support both object mode and TAP output. This dual-mode functionality is a significant improvement for test result reporting. However, ensure that the transition between these modes is seamless and well-documented, especially for consumers of the Results class who may need to understand how to configure and interpret the output correctly.
  • 190-190: The push method in Results.prototype is straightforward in adding a test to the internal tests array and emitting an _push event. This method is crucial for managing the queue of tests to run. Ensure that the interaction between push and other parts of the Results class, such as getNextTest, is well-understood and tested, particularly in scenarios with dynamic test addition or removal.
lib/test.d.ts (5)
  • 1-1: The inclusion of EventEmitter and mockProperty types at the beginning of the file sets a clear foundation for the Test class and related functionalities. This is a good practice as it ensures that all necessary types are available and correctly referenced throughout the file.
  • 13-13: The Test class declaration is comprehensive, covering various constructor signatures and properties. This thorough approach ensures that TypeScript can accurately type-check usage of the Test class in different contexts. However, ensure that all properties and methods of the Test class are covered, especially those that might be dynamically added or are part of the class's public API but not explicitly declared here.
  • 41-41: The method captureFn and other utility methods like capture, end, etc., are well-typed, providing clear signatures for their usage. This level of detail is crucial for developers to understand how to interact with the Test class and its utilities. Ensure that the documentation or external resources are available to explain the purpose and usage of these utility methods, as their names alone may not be self-explanatory.
  • 58-58: The assertion methods (ok, notOK, error, etc.) are correctly typed, reflecting their usage in the Test class. This ensures that developers can rely on TypeScript for type checking when writing tests. Consider adding brief comments to these methods to explain their expected usage and any nuances in their behavior, especially for less commonly used assertions.
  • 185-185: The Test namespace declaration provides additional types and interfaces that are essential for advanced usage of the Test class, such as SyncCallback, Callback, and various types related to method wrapping and interception. This is a good practice as it organizes related types and makes them easily accessible. Ensure that these types are used consistently throughout the project's TypeScript codebase to maintain type safety and clarity.
lib/test.js (15)
  • 38-44: The JSDoc type annotations added for various typedefs are a good practice for improving code clarity and maintainability. However, ensure that these typedefs accurately reflect the types used throughout the codebase and that they are consistent with the project's existing documentation and type definitions.
  • 81-98: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [84-124]

The constructor for the Test class is well-documented with JSDoc comments, enhancing readability and maintainability. However, the dynamic binding of methods within the constructor using callBind is noted. Given the project's constraints (ES3 syntax and no TypeScript), this approach is suitable. To further improve clarity, consider adding a comment explaining why this dynamic binding approach is used, adhering to the guideline that comments should describe "why" or the history/motivation behind code decisions.

  • 145-152: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [132-149]

The run method's implementation to handle promises returned by the callback is a modern approach to asynchronous testing. However, ensure that this pattern is compatible with the environments where the tape library is expected to run, considering the project's adherence to ES3 syntax.

  • 173-177: Creating a new Test instance within the test method and casting it to TestType is a clear way to manage test hierarchy. This approach allows for nested tests, contributing to the modularity and flexibility of the testing framework. Ensure that the TestType accurately represents the Test class's interface and capabilities.
  • 198-201: The comment method's implementation to emit each line of a multi-line comment as a separate result is a thoughtful detail that enhances the readability of test output. This approach ensures that comments are clearly visible in the test results, aiding in test result interpretation.
  • 195-215: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [212-225]

The timeoutAfter method correctly implements a timeout mechanism for tests, which is crucial for identifying tests that may hang or take too long to complete. The use of safeSetTimeout and safeClearTimeout is a good practice to ensure that the timeout functionality is reliable and does not interfere with other timers.

  • 235-241: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [238-247]

The teardown method provides a mechanism for cleaning up after tests, which is essential for maintaining a clean test environment and avoiding side effects between tests. This method enhances the framework's flexibility and usability by allowing test-specific teardown logic.

  • 289-297: The capture method's implementation to intercept and replace a method on an object with a wrapped function is a powerful feature for testing. It allows for detailed inspection of method calls, including arguments and return values. Ensure that this functionality is well-documented and that examples are provided to help users understand how to use it effectively.
  • 323-331: The intercept method introduces a way to intercept property access and modification, which can be invaluable for testing code that interacts with objects in complex ways. This method's flexibility, including support for both data properties and accessor properties, enhances the testing framework's capabilities. Ensure that the documentation clearly explains the method's usage and the scenarios where it can be particularly useful.
  • 458-476: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [428-469]

The _end method's implementation to handle the end of a test, including running teardown functions and emitting the end event, is crucial for the correct functioning of the testing framework. The handling of asynchronous teardown functions with promises is a modern approach that increases the method's utility. However, ensure that this approach is consistent with the project's overall adherence to ES3 syntax and environments.

Verification successful

The project consistently uses ES6+ features, including Promise and async/await, across various parts of its codebase, including both test files and some core library files. Therefore, the implementation of asynchronous teardown functions using promises in the _end method aligns with the project's use of modern JavaScript features.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Check for usage of ES6+ features like Promise in other parts of the project to ensure consistency.
rg --type js "Promise"

Length of output: 3134

* 482-488: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [485-501]

The _exit method's implementation to check for discrepancies between the planned number of assertions and the actual number of assertions at the end of a test is an important feature for ensuring test integrity. This method helps identify cases where tests may not be executing as expected, contributing to the robustness of the testing framework.

  • 519-525: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [509-644]

The _assert method is central to the testing framework, providing the mechanism for making assertions within tests. The detailed handling of assertion results, including capturing stack traces and handling errors, enhances the utility and usability of the framework. Ensure that the stack trace processing logic is robust and tested across different environments to provide consistent and helpful error reporting.

  • 876-896: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [886-908]

The throws method's implementation to test if a function throws an error as expected is a key feature of the testing framework. The detailed handling of different types of expected errors, including support for validation objects, increases the method's flexibility. Ensure that the documentation clearly explains how to use this method effectively, including examples for different types of expected errors.

  • 956-962: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [959-981]

The doesNotThrow method complements the throws method by testing that a function does not throw an error. This method is important for testing the normal operation of code that should not produce errors under certain conditions. Ensure that the implementation is consistent with the framework's error handling and reporting practices.

  • 1012-1018: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [1015-1049]

The match and doesNotMatch methods provide a way to test if a string matches or does not match a regular expression. These methods enhance the framework's capabilities for testing string processing and pattern matching in code. Ensure that the error messages produced by these methods are clear and helpful for diagnosing test failures.

lib/test.js Outdated Show resolved Hide resolved
index.js 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.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 732268b and 703c634.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • tsconfig.json is excluded by: !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (11)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • index.js
  • lib/default_stream.d.ts
  • lib/default_stream.js
  • lib/results.d.ts
  • lib/test.d.ts
  • lib/test.js
  • test/common.js
Additional comments: 9
lib/results.js (9)
  • 21-27: The addition of type definitions (Stream, Result, Test, ResultsType, StreamOptions, WritableStream) is a positive step towards improving code clarity and maintainability. These definitions will help developers understand the expected types of variables and function parameters/returns more clearly.
  • 18-36: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [33-48]

The getNextTest function is well-implemented and serves a clear purpose within the context of managing test execution. The use of void undefined is appropriate here to explicitly return undefined. Good job on typing and implementing this function.

  • 49-53: The invalidYaml function is a concise utility for detecting YAML-indicative characters. It's correctly implemented and typed. This function enhances the robustness of YAML-related operations by pre-validating strings.
  • 46-57: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [54-89]

The encodeResult function has been modified to handle actualStack differently. This change improves error reporting by distinguishing between the stack of an actual value and an error's stack. Ensure that this differentiation is clearly documented in the function's comments to aid future maintainability.

+ // Encodes a test result into a TAP-formatted string, handling actualStack and errorStack separately.
function encodeResult(res, count, todoIsOK) {
  • 103-112: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [106-125]

The Results constructor is well-defined, with clear options handling and initialization of properties. It's a good practice to document the expected properties of the options parameter for better code readability and maintainability.

/**
 * @constructor
 * @param {{ todoIsOK?: boolean }} [options] - Options for Results instance.
 */
function Results(options) {
  • 123-156: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [126-187]

The createStream method added to Results.prototype is comprehensive and well-implemented, covering both object mode and non-object mode streams. Ensure thorough testing, especially around the dynamic handling of tests and results in both modes, to prevent any potential issues with stream management.

  • 190-196: The push method is a straightforward addition to Results.prototype, correctly managing test addition. It's well-implemented and typed.
  • 187-208: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [202-237]

The _watch method is a key addition for monitoring test execution and formatting results. It's well-implemented, with clear handling of different test states. Consider adding more detailed comments explaining the logic, especially for the handling of skip and todo states, to improve readability.

+ // Watches a test's lifecycle events to format and output results.
Results.prototype._watch = function (t) {
  • 232-247: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [238-259]

The close method correctly finalizes the test results and ensures the stream is properly closed. It's important to handle the ALREADY CLOSED error state as it does, preventing multiple close attempts. This method is well-implemented and typed.

lib/results.js Show resolved Hide resolved
lib/results.js Show resolved Hide resolved
@JoshuaKGoldberg
Copy link
Contributor

Oop, sorry for taking so long - I'd added this tab on my phone and forgot about it 😅. Looking now!

it down to 4 errors

On the latest commit I get no errors. So, nicely done! 😄

Copy link
Contributor

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

This looks great!

Left some suggestions, but nothing showing anything wrong. Nicely done! 👏

lib/test.d.ts Outdated Show resolved Hide resolved
lib/test.d.ts Outdated Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

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

You might consider also porting in the types tests from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e1386bb7838c35504edfdb12876bf0d156d84a2a/types/tap/tap-tests.ts. Since the .d.ts is being hand-written rather than auto-generated from source files, it wouldn't be unheard of for it to fall out of sync.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

if it were out of sync, wouldn't tsc fail?

Copy link
Contributor

Choose a reason for hiding this comment

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

Not in all cases. If you, say, added an extra optional parameter somewhere but never used it, tsc wouldn't think to fail on it.

Test.prototype['throws'] = function (fn, expected, msg, extra) {
if (typeof expected === 'string') {
msg = expected;
expected = undefined;
}

/** @type {undefined | { error: unknown | Error }} */
Copy link
Contributor

Choose a reason for hiding this comment

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

error: unknown | Error is equivalent to error: unknown. unknown is a top type indicating it could be anything in the world, including Error. plugin:@typescript-eslint/no-redundant-type-constituents

The code later on just checks if (caught.error && typeof caught.error === 'object'), not instanceof Error or an equivalent. So if a caught.error is a non-Error object, the assumption it could be an Error would be wrong.

Can caught.error be something other than Error? If so, what?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

technically line 897 doesn't ensure it's an Error, but if that branch is entered, then it's so Error-like as to not make a difference. there doesn't seem to be any way i can do a type assertion without runtime code :-/

lib/test.js Show resolved Hide resolved
Comment on lines +935 to +936
// TS TODO: `caught.error` and `expected` should both be `object` here
passed = every(keys, /** @type {(key: PropertyKey) => boolean} */ function (key) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Unfortunately, TypeScript doesn't have a way of being informed that every's callbacks should keep narrowing. A type assertion would be the appropriate thing to do here instead of // @ts-expect-error to avoid changing runtime code.

A small runtime change could be to store error and expected as variables after narrowing them.

Alternately, the next version of TypeScript might be nicer about preserving narrowings - I haven't tried.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i'm using next, so it doesn't help me here. this isn't TS-expect-error tho; it's just a TODO comment

Copy link
Contributor

Choose a reason for hiding this comment

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

I meant the // @ts-expect-errors later.

@ljharb ljharb force-pushed the master branch 3 times, most recently from c16dde3 to 2ad86d4 Compare June 16, 2024 06:22
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)
lib/test.js (1)

Line range hint 83-128:
Well-annotated Test class constructor.

The type annotations improve readability and maintainability. The dynamic method binding approach is appropriate given the project's constraints.

Consider adding a comment explaining the rationale behind the dynamic method binding to help future maintainers.

Do you want me to add a comment explaining the rationale behind this choice?

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 703c634 and 4b986a0.

Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • tsconfig.json is excluded by !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review due to trivial changes (3)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • lib/default_stream.d.ts
Additional context used
Learnings (3)
test/common.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: test/common.js:106-106
Timestamp: 2024-03-12T04:16:16.696Z
Learning: Code within the `test/` directory is considered test code and is not subject to the same security concerns as production code, as it does not handle user input.
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-03-12T04:35:01.528Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (2)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.js:197-201
Timestamp: 2024-03-22T05:25:05.727Z
Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-03-12T04:35:01.528Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
Biome
lib/default_stream.js

[error] 22-22: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 23-25: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)

index.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


[error] 134-134: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

lib/results.js

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

lib/test.d.ts

[error] 116-116: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 130-130: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 196-196: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 202-202: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

lib/test.js

[error] 150-150: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 264-267: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 363-363: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 365-369: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 388-388: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 391-391: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 900-900: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)

Additional comments not posted (42)
lib/default_stream.js (2)

6-6: Type annotation for module export looks good.

The type annotation correctly specifies the import type.


12-12: Type annotation for write function parameter looks good.

The type annotation correctly specifies the parameter type.

lib/results.d.ts (4)

1-2: Type imports look good.

The type imports correctly specify the required types.


4-6: Type imports look good.

The type imports correctly specify the required types.


7-28: Type declarations for Results class look good.

The type declarations correctly specify the class properties and methods.


30-50: Type declarations for Results namespace look good.

The type declarations correctly specify the namespace types.

index.d.ts (4)

1-2: Type import for ThroughStream looks good.

The type import correctly specifies the required type.


3-4: Type imports for Test and Results look good.

The type imports correctly specify the required types.


6-13: Type declarations for harnessFunction look good.

The type declarations correctly specify the function overloads.


14-82: Type declarations for interfaces, functions, and namespaces look good.

The type declarations correctly specify the required types and interfaces.

bin/tape (2)

98-98: Type annotation for importFiles function looks good.

The type annotation correctly specifies the function's return type.


108-108: Type annotation for filesPromise variable looks good.

The type annotation correctly specifies the variable's type.

test/common.js (6)

8-9: Type annotations are correct.

The type annotations for Result and SyncCallback are correctly added and provide clarity.


Line range hint 11-24: Function getDiag implementation is correct.

The function correctly extracts and processes YAML diagnostic information from a string.


Line range hint 45-68: Function stripChangingData implementation is correct.

The function correctly normalizes stack trace data for consistency.


Line range hint 70-85: Function stripFullStack implementation is correct.

The function correctly processes stack traces to remove unnecessary information.


Line range hint 115-132: Function runProgram implementation is correct.

The function correctly runs a specified program and captures its output.


Line range hint 134-141: Function stripDeprecations implementation is correct.

The function correctly removes deprecation warnings from a message string.

index.js (5)

16-26: Type annotations are correct.

The type annotations for various types such as Tape, Harness, HarnessConfig, etc., are correctly added and provide clarity.


Line range hint 33-41: Function getHarness implementation is correct.

The function correctly retrieves or creates a test harness.

Tools
Biome

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


Line range hint 43-86: Function lazyLoad implementation is correct.

The function correctly lazily loads the test harness and provides various utility methods.


Line range hint 87-147: Function createHarness implementation is correct.

The function correctly creates a test harness and sets up result handling.

Tools
Biome

[error] 134-134: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 148-209: Function createExitHarness implementation is correct.

The function correctly creates a test harness that handles exit conditions.

lib/results.js (6)

21-26: Type annotations are correct.

The type annotations for Stream, Result, Test, ResultsType, StreamOptions, and WritableStream are correctly added and provide clarity.


28-32: Function coalesceWhiteSpaces implementation is correct.

The function correctly normalizes whitespace in strings.


Line range hint 33-48: Function getNextTest implementation is correct.

The function correctly retrieves the next test to be run.


49-53: Function invalidYaml implementation is correct.

The function correctly checks if a string contains YAML indicators.


Line range hint 54-105: Function encodeResult implementation is correct.

The function correctly encodes a test result into a string.

Tools
Biome

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 106-253: Class Results and its methods implementation is correct.

The class and its methods are correctly typed and implemented, providing the necessary functionalities.

lib/test.d.ts (4)

1-12: Type annotations for imports are correct.

The type annotations for various imports such as EventEmitter, mockProperty, etc., are correctly added and provide clarity.


22-39: Type annotations for Test class properties are correct.

The type annotations for the properties of the Test class are correctly added and provide clarity.


41-187: Type annotations for Test class methods are correct.

The type annotations for the methods of the Test class are correctly added and provide clarity.

Tools
Biome

[error] 116-116: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 130-130: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


190-236: Type annotations for Test namespace are correct.

The type annotations for the Test namespace are correctly added and provide clarity.

Tools
Biome

[error] 196-196: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 202-202: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

lib/test.js (9)

38-45: Good use of JSDoc typedefs.

These typedefs enhance type safety and documentation.


47-50: Appropriate type annotation for isErrorConstructor.

The type annotation improves clarity and the function handles different environments correctly.


60-61: Clear type annotation for getTestArgs.

The type annotation enhances documentation and ensures the return type is clear.


131-134: Clear type annotation for run method.

The type annotations improve documentation and ensure the types of parameters and return values are clear.


147-148: Appropriate type annotation for callbackReturn.

The type annotation ensures clarity in understanding the flow of the method.


172-176: Clear type annotation for test method.

The type annotations improve documentation and ensure the types of parameters and return values are clear.


197-200: Clear type annotation for comment method.

The type annotations improve documentation and ensure the types of parameters and return values are clear.


246-260: Clear type annotation for wrapFunction.

The type annotation enhances documentation and ensures the types of parameters and return values are clear.


298-298: Appropriate type annotation for implementation variable.

The type annotation ensures clarity in understanding the flow of the method.

lib/default_stream.js Show resolved Hide resolved
lib/default_stream.js Show resolved Hide resolved
lib/test.d.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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4b986a0 and e248b12.

Files ignored due to path filters (2)
  • package.json is excluded by !**/*.json
  • tsconfig.json is excluded by !**/*.json
Files selected for processing (12)
  • .github/workflows/node-aught.yml (1 hunks)
  • bin/import-or-require.js (1 hunks)
  • bin/tape (2 hunks)
  • index.d.ts (1 hunks)
  • index.js (8 hunks)
  • lib/default_stream.d.ts (1 hunks)
  • lib/default_stream.js (2 hunks)
  • lib/results.d.ts (1 hunks)
  • lib/results.js (9 hunks)
  • lib/test.d.ts (1 hunks)
  • lib/test.js (41 hunks)
  • test/common.js (4 hunks)
Files skipped from review as they are similar to previous changes (7)
  • .github/workflows/node-aught.yml
  • bin/import-or-require.js
  • bin/tape
  • index.d.ts
  • lib/default_stream.d.ts
  • lib/results.d.ts
  • test/common.js
Additional context used
Learnings (3)
lib/default_stream.js (3)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/default_stream.js:23-25
Timestamp: 2024-07-05T21:18:22.587Z
Learning: The modern JavaScript practice favors defining variables where they are first needed, rather than declaring all `var`s at the top of the function. This approach improves readability and maintainability.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/default_stream.js:21-21
Timestamp: 2024-07-05T21:17:37.138Z
Learning: Avoid suggesting moving variable declarations to the root of the containing function if it affects the type definition and the scope of the variable.
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/default_stream.js:23-25
Timestamp: 2024-07-05T21:12:23.639Z
Learning: The linting rule regarding inner declarations in Biome is subjective and not agreed upon by ljharb. Future suggestions should consider this perspective.
index.js (1)
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-03-12T04:35:01.528Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
lib/results.js (2)
Learnt from: ljharb
PR: tape-testing/tape#603
File: lib/results.js:197-201
Timestamp: 2024-03-22T05:25:05.727Z
Learning: For the `tape` project, code comments should explain "why" or history/motivation, but never "what". Documentation belongs outside of source files.
Learnt from: ljharb
PR: tape-testing/tape#603
File: index.js:147-147
Timestamp: 2024-03-12T04:35:01.528Z
Learning: Comments in the codebase should focus on explaining "why" or providing history/motivation, rather than detailing "what" the code does, as per ljharb's guidance.
Biome
lib/default_stream.js

[error] 22-22: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 23-25: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)

index.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


[error] 133-133: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

lib/results.js

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

lib/test.d.ts

[error] 112-112: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 126-126: Don't use 'Function' as a type.

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

(lint/complexity/noBannedTypes)


[error] 192-192: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 198-198: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

lib/test.js

[error] 150-150: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 264-267: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 363-363: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 365-369: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 388-388: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 391-391: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 900-900: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)

Additional comments not posted (39)
lib/default_stream.js (4)

6-6: LGTM!

The type annotation for the module export improves clarity.


12-12: LGTM!

The type annotation for the write function improves clarity.


21-21: LGTM!

The type annotation for the variable b ensures type safety.


23-25: LGTM!

The type annotation for the variable c ensures type safety.

Tools
Biome

[error] 23-25: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)

index.js (5)

4-5: LGTM!

The import statement for the through module is necessary for the functionality of the file.


11-12: LGTM!

The type annotation for the canEmitExit variable improves clarity.


16-26: LGTM!

The type annotations for the typedefs improve clarity and type safety.


29-29: LGTM!

The type annotation for the harness variable ensures type safety.


32-35: LGTM!

The type annotation for the getHarness function improves clarity and type safety.

lib/results.js (5)

21-27: LGTM!

The type annotations for the typedefs improve clarity and type safety.


28-32: LGTM!

The type annotation for the coalesceWhiteSpaces function improves clarity and type safety.


Line range hint 33-48:
LGTM!

The type annotation for the getNextTest function improves clarity and type safety.


49-53: LGTM!

The type annotation for the invalidYaml function improves clarity and type safety.


Line range hint 54-105:
LGTM!

The type annotation for the encodeResult function improves clarity and type safety.

Tools
Biome

[error] 92-92: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

lib/test.d.ts (5)

1-3: LGTM!

The import type statements for various modules improve type safety and clarity.


4-11: LGTM!

The import type statements for various typedefs improve type safety and clarity.


12-17: LGTM!

The constructor overloads for the Test class provide flexibility in creating Test instances.


37-51: LGTM!

The type annotations for the methods in the Test class improve clarity and type safety.


153-157: LGTM!

The type annotation for the assertion method improves clarity and type safety.

lib/test.js (20)

38-45: Type definitions and helper functions look good!

The added type definitions and helper functions are well-structured and align with the project's use of the TypeScript compiler for type checking.


Line range hint 60-74: Type annotations for getTestArgs look good!

The type annotations improve the clarity of the function's parameters and return type.


Line range hint 83-130: Constructor for Test class looks good!

The constructor is well-implemented, correctly initializing class properties and handling default values. Consider adding a comment explaining the rationale behind the dynamic method binding approach to help future maintainers understand the choice.

for (var prop in this) {
  if (typeof this[prop] === 'function') {
    // Dynamically bind methods to the instance to avoid listing each method explicitly
    // @ts-expect-error TODO: FIXME
    this[prop] = callBind(this[prop], this);
  }
}

Line range hint 131-170: Type annotations for run method look good!

The type annotations improve the clarity of the method's parameters and return type.

Tools
Biome

[error] 150-150: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


Line range hint 172-195: Type annotations for test method look good!

The type annotations improve the clarity of the method's parameters and return type.


197-203: Type annotations for comment method look good!

The type annotations improve the clarity of the method's parameters and return type.


205-209: Type annotations for plan method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 211-222: Type annotations for timeoutAfter method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 224-235: Type annotations for end method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 237-244: Type annotations for teardown method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 246-288: Type annotations for wrapFunction look good!

The type annotations improve the clarity of the function's parameters and return type. However, consider refactoring variable declarations to the root of the function to avoid confusion.

function wrapFunction(original) {
  if (typeof original !== 'undefined' && typeof original !== 'function') {
    throw new TypeError('`original` must be a function or `undefined`');
  }

  var bound = original && callBind.apply(original);

  /** @type {WrappedCall[]} */
  var calls = [];

  /** @type {import('./test').WrapObject<NonNullable<typeof original>>} */
  var wrapObject = {
    __proto__: null,
    wrapped: /** @type {() => ReturnType<original>} */ function wrapped() {
      var args = $slice(arguments);
      var completed = false;
      try {
        var returned = bound
          ? bound(this, /** @type {readonly[]} */ (/** @type {unknown} */ (arguments)))
          : void undefined;
        $push(calls, { args: args, receiver: this, returned: returned });
        completed = true;
        return returned;
      } finally {
        if (!completed) {
          $push(calls, { args: args, receiver: this, threw: true });
        }
      }
    },
    calls: calls,
    results: function results() {
      try {
        return calls;
      } finally {
        calls = [];
        wrapObject.calls = calls;
      }
    }
  };
  return wrapObject;
}
Tools
Biome

[error] 264-267: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


Line range hint 290-311: Type annotations for capture method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 313-321: Type annotations for captureFn method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 324-430: Type annotations for intercept method look good!

The type annotations improve the clarity of the method's parameters and return type. However, consider refactoring variable declarations to the root of the function to avoid confusion.

function intercept(obj, property) {
  if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
    throw new TypeError('`obj` must be an object');
  }
  if (typeof property !== 'string' && typeof property !== 'symbol') {
    throw new TypeError('`property` must be a string or a symbol');
  }

  /** @type {PropertyDescriptor} */
  var desc = arguments.length > 2 ? arguments[2] : { __proto__: null };
  if (typeof desc !== 'undefined' && (!desc || typeof desc !== 'object')) {
    throw new TypeError('`desc`, if provided, must be an object');
  }
  if ('configurable' in desc && !desc.configurable) {
    throw new TypeError('`desc.configurable`, if provided, must be `true`, so that the interception can be restored later');
  }
  var isData = 'writable' in desc || 'value' in desc;
  var isAccessor = 'get' in desc || 'set' in desc;
  if (isData && isAccessor) {
    throw new TypeError('`value` and `writable` can not be mixed with `get` and `set`');
  }
  var strictMode = arguments.length > 3 ? arguments[3] : true;
  if (typeof strictMode !== 'boolean') {
    throw new TypeError('`strictMode`, if provided, must be a boolean');
  }

  /** @type {Call[]} */
  var calls = [];
  var getter = desc.get && callBind.apply(desc.get);
  var setter = desc.set && callBind.apply(desc.set);
  var value = !isAccessor ? desc.value : void undefined;
  var writable = !!desc.writable;

  /** @type {<T = unknown>(this: T, ...args: unknown[]) => unknown} */
  function getInterceptor() {
    /** @type {unknown[]} */
    var args = $slice(arguments);
    if (isAccessor) {
      if (getter) {
        var completed = false;
        try {
          var returned = getter(
            this,
            /** @type {readonly []} */ (/** @type {unknown} */ (arguments))
          );
          completed = true;
          $push(calls, { type: 'get', success: true, value: returned, args: args, receiver: this });
          return returned;
        } finally {
          if (!completed) {
            $push(calls, { type: 'get', success: false, threw: true, args: args, receiver: this });
          }
        }
      }
    }
    $push(calls, { type: 'get', success: true, value: value, args: args, receiver: this });
    return value;
  }

  /** @type {<T = unknown>(this: T, v: unknown) => unknown} */
  function setInterceptor(v) {
    var args = $slice(arguments);
    if (isAccessor && setter) {
      var completed = false;
      try {
        var returned = setter(this, /** @type {readonly [v: unknown]} */ (/** @type {unknown} */ (arguments)));
        completed = true;
        $push(calls, { type: 'set', success: true, value: v, args: args, receiver: this });
        return returned;
      } finally {
        if (!completed) {
          $push(calls, { type: 'set', success: false, threw: true, args: args, receiver: this });
        }
      }
    }
    var canSet = isAccessor || writable;
    if (canSet) {
      value = v;
    }
    $push(calls, { type: 'set', success: !!canSet, value: value, args: args, receiver: this });

    if (!canSet && strictMode) {
      throw new TypeError('Cannot assign to read only property `' + inspect(property) + '` of object `' + inspect(obj) + '`');
    }
    return value;
  }

  var restore = mockProperty(obj, property, {
    nonEnumerable: !!desc.enumerable,
    get: getInterceptor,
    set: setInterceptor
  });
  this.teardown(restore);

  function results() {
    try {
      return calls;
    } finally {
      calls = [];
    }
  }
  results.restore = restore;

  return results;
}
Tools
Biome

[error] 363-363: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


[error] 365-369: This var should be declared at the root of the enclosing function.

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

(lint/correctness/noInnerDeclarations)


Line range hint 432-487: Type annotations for _end method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 489-502: Type annotations for _exit method look good!

The type annotations improve the clarity of the method's parameters and return type.


505-511: Type annotations for _pendingAsserts method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 513-651: Type annotations for _assert method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 653-660: Type annotations for fail method look good!

The type annotations improve the clarity of the method's parameters and return type.


Line range hint 662-669: Type annotations for pass method look good!

The type annotations improve the clarity of the method's parameters and return type.

Copy link

socket-security bot commented Aug 22, 2024

@ljharb ljharb changed the title add types [New] add types Aug 22, 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: 1

Outside diff range, codebase verification and nitpick comments (4)
lib/test.d.ts (1)

13-16: Potential mismatch in constructor usage

The constructor call new Test(name, conf, cb); does not match any of the defined overloads in the Test class. Please review this instance to ensure it aligns with the intended overloads.

  • File: index.js
  • Line: var t = new Test(name, conf, cb);
Analysis chain

Constructor overloads are appropriate.

The current constructor overloads provide necessary flexibility and should be maintained as is.

However, ensure that all constructor calls in the codebase match these overloads.

Run the following script to verify the constructor usage:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all constructor calls to `Test` match the defined overloads.

# Test: Search for the constructor usage. Expect: Only occurrences of the defined overloads.
rg --type js -A 5 $'new Test'

Length of output: 988

lib/test.js (3)

60-60: Clarify the return type annotation for getTestArgs.

The return type annotation could be more explicit about the optional nature of cb.

Apply this diff for clarity:

- /** @type {(name_: string, opts_: TestOptions, cb_: Callback) => { name: string, opts: TestOptions, cb: Callback }} */
+ /** @type {(name_: string, opts_: TestOptions, cb_: Callback) => { name: string, opts: TestOptions, cb?: Callback }} */

246-246: Improve type annotations for wrapFunction.

The type annotations could be more explicit for clarity.

Apply this diff for clarity:

- /** @type {<T extends Callback>(original: undefined | T) => import('./test').WrapObject<T>} */
+ /** @type {<T extends Callback | undefined>(original: T) => import('./test').WrapObject<NonNullable<T>>} */

985-985: Improve type annotations for match.

The type annotations could be more explicit for clarity.

Apply this diff for clarity:

- /** @type {import('./test').prototype.match} */
+ /** @type {(string: string, regexp: RegExp, msg?: string, extra?: unknown) => void} */

lib/test.js Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants