Skip to content

Add script for manipulating and checking code samples #1948

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

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

flevi29
Copy link
Collaborator

@flevi29 flevi29 commented May 16, 2025

Pull Request

Related issue

Fixes #1947

What does this PR do?

  • adds scripts that help with authoring, linting and type checking code samples
# Generate files
yarn generate-code-sample-files
# Generate YAML file
yarn generate-code-samples-yaml
# For maintainers to generate new code samples
yarn generate-code-sample-files new_sample_one new_sample_two
  • code samples are now linted and type checked in CI workflows, guaranteeing that we'll no longer get completely broken code samples
  • refactors code samples

Summary by CodeRabbit

  • New Features

    • Introduced automated generation of TypeScript code samples from YAML and vice versa, improving consistency and maintainability of code samples.
    • Added scripts and commands to generate and manage code samples, with clear instructions in the contributing guide.
  • Documentation

    • Updated the contributing guide with a new section detailing how to generate, lint, and type-check code samples.
  • Chores

    • Added new scripts and dependencies to support code sample generation.
    • Updated .gitignore to exclude generated code samples from version control.
    • Updated TypeScript configuration for improved module resolution in tests.
  • Style

    • Modernized all JavaScript/TypeScript Meilisearch code samples to use consistent async/await patterns and ES module imports.

@flevi29 flevi29 added documentation Improvements or additions to documentation maintenance Issue about maintenance (CI, tests, refacto...) labels May 16, 2025
Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

This update introduces a new workflow for managing, generating, and type-checking Meilisearch JavaScript/TypeScript code samples. It adds scripts to convert between YAML and TypeScript code samples, integrates these steps into build and lint scripts, updates documentation, and modernizes all code samples to use consistent async/await patterns.

Changes

File(s) Change Summary
.code-samples.meilisearch.yaml Modernized all code samples to async/await style, standardized imports, variable naming, and explicit task handling.
.gitignore Added generated-code-samples to ignore list.
CONTRIBUTING.md Added section describing code sample generation, type checking, and related commands.
package.json Added scripts for code sample generation, integrated them into build and style scripts, added YAML dependencies.
tsconfig.json Added module path aliases for "meilisearch" and "meilisearch/token" for testing purposes.
scripts/code-samples.js New script to dispatch code sample generation or YAML conversion based on CLI arguments.
scripts/code-samples/from-yaml.js New script to generate TypeScript files from YAML code samples, including sample JSON files.
scripts/code-samples/shared.js New shared module providing constants and a generator for iterating YAML code samples.
scripts/code-samples/to-yaml.js New script to generate YAML from TypeScript code samples, maintaining order and formatting.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer
    participant Script as code-samples.js
    participant FromYaml as from-yaml.js
    participant ToYaml as to-yaml.js
    participant TS as TypeScript Compiler

    Dev->>Script: yarn generate-code-sample-files
    Script->>FromYaml: Import and execute
    FromYaml->>TS: Generate .ts files for samples

    Dev->>Script: yarn generate-code-samples-yaml
    Script->>ToYaml: Import and execute
    ToYaml->>FromYaml: Read .ts files
    ToYaml->>Script: Write .yaml file

    Dev->>TS: yarn types (runs generate-code-sample-files first)
    TS->>FromYaml: Type checks generated .ts files
Loading

Assessment against linked issues

Objective Addressed Explanation
Script to generate TypeScript code from .code-samples.meilisearch.yaml for type checking (#1947) Added scripts and workflow to generate and type-check code samples from YAML sources.

Poem

A rabbit hopped through code and YAML,
Tidying samples, both sleek and mammal.
With scripts that dance from file to file,
Type checks now greet us with a smile.
Async/await, so neat and bright,
Our samples now just feel so right!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between f303e2e and e147795.

📒 Files selected for processing (2)
  • .code-samples.meilisearch.yaml (2 hunks)
  • scripts/code-samples/from-yaml.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • scripts/code-samples/from-yaml.js
  • .code-samples.meilisearch.yaml

🪧 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using 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 generate sequence diagram to generate a sequence diagram of the changes in this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

codecov bot commented May 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.03%. Comparing base (77505c0) to head (e147795).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1948   +/-   ##
=======================================
  Coverage   99.03%   99.03%           
=======================================
  Files          18       18           
  Lines        1449     1449           
  Branches      305      305           
=======================================
  Hits         1435     1435           
  Misses         14       14           

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@flevi29 flevi29 marked this pull request as ready for review May 18, 2025 18:53
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (8)
CONTRIBUTING.md (1)

73-76: Fix grammatical issues in the documentation

The added documentation is informative, but contains a few grammatical issues.

- In this repository code samples are linted and type checked. To achieve this we generate
- TypeScript files from `.code-samples.meilisearch.yaml`, and vice-versa.
+ In this repository, code samples are linted and type checked. To achieve this, we generate
+ TypeScript files from `.code-samples.meilisearch.yaml`, and vice versa.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~75-~75: Possible missing comma found.
Context: ...rn build ``` ### Code samples In this repository code samples are linted and type checke...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~75-~75: Possible missing comma found.
Context: ...are linted and type checked. To achieve this we generate TypeScript files from `.cod...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~76-~76: The expression “vice versa” is spelled without hyphens.
Context: ...m .code-samples.meilisearch.yaml, and vice-versa. ```bash # Generate files yarn generat...

(VICE_VERSA)

scripts/code-samples/from-yaml.js (2)

18-18: Consider externalizing the list of JSON files

The hard-coded list of JSON files could be moved to the shared module to ensure consistency between scripts.

-const jsonFilesToGenerate = ["games", "movies", "meteorites"];
+import { jsonFilesToGenerate } from "./shared.js";

And in shared.js:

export const jsonFilesToGenerate = ["games", "movies", "meteorites"];

29-34: Consider more robust JSON file generation

The script currently generates empty arrays for JSON files, but it might be better to generate more realistic mock data or at least structured objects with the expected properties.

for (const jsonFileToGenerate of jsonFilesToGenerate) {
+  const mockData = {
+    games: [{ id: "1", name: "Example Game", genre: "RPG" }],
+    movies: [{ id: "1", title: "Example Movie", director: "Jane Doe" }],
+    meteorites: [{ id: "1", name: "Example Meteorite", mass: 1000 }]
+  };
+  
+  const content = jsonFileToGenerate in mockData 
+    ? JSON.stringify(mockData[jsonFileToGenerate], null, 2)
+    : "[]";
+    
  writeFileSync(
    new URL(jsonFileToGenerate + ".json", generatedCodeSamplesDir),
-    "[]\n",
+    content + "\n",
  );
}
.code-samples.meilisearch.yaml (5)

1-4: Add immediate documentation for code-samples workflow
The PR notes that CONTRIBUTING.md updates are planned but not yet included. Adding a placeholder or brief instructions now will help contributors use the new scripts without confusion.


15-16: Ensure TypeScript JSON import support in tsconfig
The samples use import games from "./games.json" with { type: "json" }. Confirm that your tsconfig.json has resolveJsonModule, esModuleInterop, and a compatible moduleResolution so the generated .ts files compile successfully.


328-329: Consider adding await for the health() call
In get_health_1, _client.health() returns a promise; prefixing it with await aligns with other examples and ensures errors aren't silently dropped.

-  const _health = _client.health();
+  const _health = await _client.health();

459-463: Inconsistent _task variable naming
The add_movies_json_1 sample uses const task instead of the underscore-prefixed const _task convention used throughout. For consistency, rename it:

-  const task = await _client.index("movies").addDocuments(movies).waitTask();
+  const _task = await _client.index("movies").addDocuments(movies).waitTask();

5-1019: Refactor and modularize large code-samples YAML
With over 100 entries in a single file, maintenance and navigation become difficult. Consider splitting by domain (indexes, documents, search, settings, security) into separate YAML files or using YAML anchors/shared literals to reduce duplication and improve clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 438da05 and ce84f37.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • .code-samples.meilisearch.yaml (3 hunks)
  • .gitignore (1 hunks)
  • CONTRIBUTING.md (1 hunks)
  • package.json (3 hunks)
  • scripts/code-samples.js (1 hunks)
  • scripts/code-samples/from-yaml.js (1 hunks)
  • scripts/code-samples/shared.js (1 hunks)
  • scripts/code-samples/to-yaml.js (1 hunks)
  • tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
scripts/code-samples/from-yaml.js (2)
scripts/code-samples/shared.js (5)
  • delimiter (14-14)
  • delimiter (14-14)
  • generatedCodeSamplesDir (9-12)
  • generatedCodeSamplesDir (9-12)
  • iterateCodeSamples (16-37)
scripts/code-samples/to-yaml.js (1)
  • header (88-94)
🪛 LanguageTool
CONTRIBUTING.md

[uncategorized] ~75-~75: Possible missing comma found.
Context: ...rn build ``` ### Code samples In this repository code samples are linted and type checke...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~75-~75: Possible missing comma found.
Context: ...are linted and type checked. To achieve this we generate TypeScript files from `.cod...

(AI_HYDRA_LEO_MISSING_COMMA)


[grammar] ~76-~76: The expression “vice versa” is spelled without hyphens.
Context: ...m .code-samples.meilisearch.yaml, and vice-versa. ```bash # Generate files yarn generat...

(VICE_VERSA)

🔇 Additional comments (15)
.gitignore (1)

136-136: Adding generated code samples to gitignore looks good

This addition prevents generated code sample files from being committed to the repository, which is the correct approach for generated artifacts.

tsconfig.json (1)

11-11: Good addition of verbatimModuleSyntax

Enabling verbatimModuleSyntax: true enforces stricter type checking for imports/exports, which is beneficial for catching errors at compile time.

CONTRIBUTING.md (1)

77-85: Commands section looks good

The commands section clearly explains how to generate code sample files and YAML files, which is helpful for contributors.

scripts/code-samples.js (1)

1-11: Script logic looks good

The script serves as a clear entry point for the code sample generation workflow. The logic correctly routes to the appropriate implementation based on command-line arguments and provides informative error messages.

Some positive aspects:

  • Clean use of dynamic imports
  • Proper error handling with descriptive messages
  • Top-level await is used correctly
package.json (4)

47-47: Integration of code sample generation with type checking

The types script now depends on generate-code-sample-files, which ensures that TypeScript code samples are generated before type checking occurs. This is a good workflow improvement that will catch type errors in code samples early.


58-59: Well-defined scripts for bidirectional code sample conversion

These new scripts create a clear workflow for maintaining code samples, allowing conversion from YAML to TypeScript files and vice versa. This facilitates both type checking and documentation generation.


64-65: Style checking now includes generated code samples

The style scripts now check the generated-code-samples directory, ensuring consistent formatting across all code, including samples. The pattern of generating files before checking them is consistent with the approach in the types script.


75-75: Appropriate dependencies for YAML processing

Addition of js-yaml and its type definitions is necessary for the new code sample processing workflow. The versions chosen are appropriate and stable.

Also applies to: 85-85

scripts/code-samples/to-yaml.js (3)

11-14: Good approach for preserving sample order

Reading the existing sample names from the YAML file first allows maintaining the original ordering, which is important for documentation consistency.


27-32: Helpful error message for empty directory case

The error message clearly explains the problem and provides a tip for resolution, which is excellent for developer experience.


79-82: Clever approach for sample ordering

This code effectively moves new samples (with index -1) to the end of the file while preserving the original order of existing samples. Using array methods like at() and shift() makes the code concise.

scripts/code-samples/shared.js (2)

4-12: Good use of URL for portable path resolution

Using the URL constructor with import.meta.url is an excellent approach for resolving paths relative to the module location, ensuring the script works correctly regardless of the working directory.


16-37: Well-implemented generator for code sample iteration

The generator function provides a clean API for iterating through code samples with proper error handling. The error messages include the problematic values as cause, which is excellent for debugging.

scripts/code-samples/from-yaml.js (2)

20-26: Good error handling for directory creation

The script only ignores the expected "directory already exists" error (EEXIST) and properly rethrows any other errors, which is a robust approach.


42-49: Smart detection for existing imports and client declarations

The script intelligently adds import statements and client declarations only when needed, which avoids duplicating code and preserves any custom implementations in the samples.

flevi29 and others added 5 commits May 18, 2025 22:01
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Collaborator

@Strift Strift left a comment

Choose a reason for hiding this comment

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

This is a great idea! But the resulting code samples don't exactly fit Meilisearch docs expectations for now.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Hi, I think that the code samples are a bit less readable now.

Why the underscore before the name of every variable?

Furthermore, the examples used to be simple method calls, but now they also contain variable assignments.

I don't think this is needed, and it doesn't align with the Meilisearch documentation practices, see example.

Can we revert these changes?

Copy link
Collaborator Author

@flevi29 flevi29 May 21, 2025

Choose a reason for hiding this comment

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

Yeah, alright. I reverted it.
I can see the problem, in particular that no other library does this, and they all sort of use the same pattern, where possible, but here is my thought process anyhow for why I did what I did.

My intention was to write linter and formatter compliant code samples in addition to being type checked. One of the solutions to this was to add variables with underscores (_client), because these variables don't always get used, which makes the linter err.

As for variable assignments, I thought it would be more clear that the method call returns something that we want to use, because there are method calls which do not return anything (Promise<void>), and the variable names indicate clearly what is being returned.

I also added .waitTask() initially, to indicate that the method call results in an enqueued task, that has to be awaited in almost every situation at some point in the code.

I went ahead and reverted these changes.

I did leave the awaits though, removing those would require for us to ignore a rule from the linter, and I believe it clearly signals that we're dealing with a promise.

@flevi29 flevi29 requested a review from Strift May 21, 2025 08:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation maintenance Issue about maintenance (CI, tests, refacto...)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Type check code examples in .code-samples.meilisearch.yaml
2 participants