Skip to content

Conversation

@kingston
Copy link
Collaborator

@kingston kingston commented Mar 31, 2025

  • Adds new Typescript renderer system for refactored typescript writing experience
  • Upgrades logger.ts service to use it
  • Also fixes up tools to use Node 22 instead of Node 20

Summary by CodeRabbit

  • New Features

    • Introduced a new TypeScript writer system for improved file generation.
    • Added functionality for grouping and transforming values in maps.
    • Enhanced import handling with new utilities for managing TypeScript import declarations.
  • Documentation

    • Provided guidelines for writing tests using Vitest to ensure consistency.
  • Tests

    • Expanded unit test coverage for features such as grouping elements and transforming map values.
  • Chores

    • Updated tooling scripts for type checking and improved dependency management.
    • Cleaned up import paths and configurations for better clarity and functionality.

@linear
Copy link

linear bot commented Mar 31, 2025

@changeset-bot
Copy link

changeset-bot bot commented Mar 31, 2025

🦋 Changeset detected

Latest commit: 27de888

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 13 packages
Name Type
@halfdomelabs/fastify-generators Patch
@halfdomelabs/core-generators Patch
@halfdomelabs/utils Patch
@halfdomelabs/sync Patch
@halfdomelabs/project-builder-server Patch
@halfdomelabs/baseplate-plugin-storage Patch
@halfdomelabs/react-generators Patch
@halfdomelabs/create-project Patch
@halfdomelabs/project-builder-cli Patch
@halfdomelabs/project-builder-lib Patch
@halfdomelabs/project-builder-test Patch
@halfdomelabs/project-builder-web Patch
@halfdomelabs/project-builder-common Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Mar 31, 2025

Walkthrough

This pull request introduces extensive updates across multiple packages. New files, interfaces, and utility functions have been added to enhance TypeScript code generation, templating, and import/export management. Several generators (core and Fastify) have been revised to simplify control flow, streamline file writing, and improve type handling. Additional test suites and documentation updates support these changes. Configuration files for ESLint, Prettier, and TypeScript have also been updated, along with utility functions for grouping and mapping.

Changes

File(s) Change Summary
.changeset/free-bottles-enter.md
.cursor/rules/writing-vitest-tests.mdc
New documentation files: dependency patch notes and Vitest test guidelines added.
packages/core-generators/src/actions/copy-typescript-file-action.ts
packages/core-generators/src/generators/node/typescript/index.ts
packages/core-generators/src/index.ts
packages/core-generators/src/renderers/index.ts
Updated TS generators and exports: removed redundant variables; introduced a new schema, interfaces, and a new "file" task in the TypeScript generator.
packages/core-generators/src/renderers/typescript/fragments/creators.ts
packages/core-generators/src/renderers/typescript/fragments/index.ts
packages/core-generators/src/renderers/typescript/fragments/types.ts
packages/core-generators/src/renderers/typescript/fragments/utils.ts
packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts
New TS fragment utilities added: functions for creating and flattening code fragments, new types and tests.
packages/core-generators/src/renderers/typescript/imports/builder.ts
packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts
packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts
packages/core-generators/src/renderers/typescript/imports/sort-imports/*
packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts
packages/core-generators/src/renderers/typescript/imports/ts-path-maps.ts
packages/core-generators/src/renderers/typescript/imports/types.ts
New TS import management: builders, merge functions with conflict handling, normalization, sorting, ts-morph operations, and path-mapping utilities with corresponding tests.
packages/core-generators/src/renderers/typescript/renderers/file.ts
packages/core-generators/src/renderers/typescript/renderers/index.ts
packages/core-generators/src/renderers/typescript/renderers/template.ts
packages/core-generators/src/renderers/typescript/templates/*
packages/core-generators/src/renderers/typescript/ts-code-utils.ts
packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts
New TS renderers and templating: functions for rendering code file templates, converting templates to fragments, and template utilities with tests.
packages/core-generators/src/writers/typescript/source-file.ts Simplified file writing logic by directly using destination paths, removing the intermediate path resolution.
packages/fastify-generators/src/generators/auth0/*
packages/fastify-generators/src/generators/core/error-handler-service/index.ts
packages/fastify-generators/src/generators/core/logger-service/*
packages/fastify-generators/src/generators/core/request-context/index.ts
Fastify generators updated to utilize tsCodeFragment and tsImportBuilder, remove deprecated error handling methods, update logger templates, and streamline import expressions.
packages/sync/src/output/generator-task-output.ts Updated writeFile method: consolidated parameters, inlined POSIX path normalization, and modified file identifier construction.
packages/tools/*
(eslint-configs, prettier configs, tsconfig files, package.json)
Updated configuration files: ESLint and Prettier import paths revised; new "typecheck" script added; dependency updated from Node20 to Node22; new TS config file introduced.
packages/utils/src/index.ts
packages/utils/src/maps/group-by.ts
packages/utils/src/maps/group-by.unit.test.ts
packages/utils/src/maps/index.ts
packages/utils/src/maps/map-values-of-map.ts
packages/utils/src/maps/map-values-of-map.unit.test.ts
New utility functions for maps: added mapGroupBy and mapValuesOfMap along with corresponding tests and an aggregated export file.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Render Function
    participant Template as TS Template Source
    participant Project as ts-morph Project
    participant File as SourceFile
    participant Merge as MergeImportsAndFragments
    participant Writer as File Writer

    Client->>Template: Read template content
    Client->>Client: Replace variables in template
    Client->>Project: Create ts-morph Project
    Project->>File: Create new SourceFile
    Client->>Merge: Invoke mergeImportsAndFragments with imports & fragments
    Merge-->>File: Return merged content
    File->>Writer: Write final file text
    Writer-->>Client: Return rendered file content
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between c26edfa and 27de888.

📒 Files selected for processing (2)
  • packages/core-generators/src/renderers/typescript/imports/builder.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts
  • packages/core-generators/src/renderers/typescript/imports/builder.ts

🪧 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.
    • 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 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 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 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@socket-security
Copy link

socket-security bot commented Mar 31, 2025

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@tsconfig/[email protected] None 0 2.36 kB typescript-deploys
npm/[email protected] environment, eval, filesystem, network, shell, unsafe +6 5.97 MB vitebot

View full report↗︎

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (31)
packages/tools/eslint-configs/react.js (1)

6-6: Update Import Statement for Module Resolution
The change to include the .js extension in the typedef import ensures explicit module resolution, which is particularly important in strict ESM environments. Please confirm that ./typescript.js exists and that the updated import complies with your project's module resolution strategy.

packages/tools/eslint-configs/storybook.js (1)

5-5: Align Import Path with Updated Convention
The updated typedef import now using ./typescript.js is consistent with the changes in the React ESLint config file. This consistency improves clarity and module resolution reliability. Ensure that the referenced file exists and that any changes in configuration across files are thoroughly tested in your environment.

.cursor/rules/writing-vitest-tests.mdc (1)

1-5: Complete the frontmatter metadata for better documentation.

The description and globs fields are currently empty. Adding appropriate values would help developers understand the purpose and scope of this rule better.

---
-description: 
+description: Conventions for writing tests with Vitest
-globs: 
+globs: "**/*.test.ts"
alwaysApply: true
---
packages/core-generators/src/renderers/typescript/fragments/index.ts (1)

4-5: Add proper newline at end of file.

The file currently ends without a proper newline character, which may cause linting issues in some environments.

export * from './utils.js';
+
packages/core-generators/src/renderers/typescript/index.ts (1)

5-6: Add proper newline at end of file.

The file currently ends without a proper newline character, which may cause linting issues in some environments.

export * from './ts-code-utils.js';
+
packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (1)

36-71: Clear testing of nested fragment handling with priority verification.

This test effectively verifies the recursive nature of the function and its ability to handle nested fragments. However, the test could be more explicit about priority expectations.

Consider adding assertions to explicitly check the priority values of the returned fragments, as the current test only verifies they exist but doesn't verify priority relationships:

 const rootType = result.hoistedFragments.find((f) => f.key === 'root-type');
 const nestedType = result.hoistedFragments.find(
   (f) => f.key === 'nested-type',
 );
 expect(rootType).toBeDefined();
 expect(nestedType).toBeDefined();
+expect(rootType?.priority).toBeDefined();
+expect(nestedType?.priority).toBeDefined();
+expect(rootType!.priority).toBeLessThan(nestedType!.priority);
packages/fastify-generators/src/generators/core/error-handler-service/index.ts (1)

1-5: Import added but implementation method removed.

The TypescriptCodeExpression type is now imported, but based on the AI summary, the getHttpErrorExpression method that used this type has been removed from the ErrorHandlerServiceProvider interface. Consider removing this import if it's no longer used elsewhere in the file.

import type {
  ImportMapper,
-  TypescriptCodeExpression,
  TypescriptSourceFile,
} from '@halfdomelabs/core-generators';
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)

23-44: Robust fragment creation utility.

The tsCodeFragment function is well-documented and handles different input formats gracefully. It correctly normalizes imports to an array regardless of input type and provides sensible defaults.

Consider adding validation for the contents parameter to ensure it's a non-empty string, which would help catch potential errors early.

export function tsCodeFragment(
  contents: string,
  imports?: TsImportDeclaration[] | TsImportDeclaration,
  {
    hoistedFragments,
  }: {
    hoistedFragments?: TsHoistedFragment[];
  } = {},
): TsCodeFragment {
+  if (contents === undefined) {
+    throw new Error('contents must be defined');
+  }
  return {
    contents,
    imports: Array.isArray(imports) ? imports : imports ? [imports] : [],
    hoistedFragments,
  };
}
packages/core-generators/src/renderers/typescript/imports/ts-path-maps.ts (1)

22-24: Consider simplifying path normalization.

The path normalization might be redundant since path.posix.join already uses forward slashes.

If you're certain that path.posix.join will always return paths with forward slashes, you could simplify:

-        to: `./${path.posix.join(baseUrl, targets[0]).replaceAll('\\', '/')}`,
+        to: `./${path.posix.join(baseUrl, targets[0])}`,

However, the current approach is more defensive if targets[0] might already contain backslashes.

packages/core-generators/src/renderers/typescript/renderers/template.ts (1)

49-62: Robust template variable replacement

The code effectively handles template variable replacement with proper error handling for missing variables. The regex pattern correctly identifies variable placeholders.

Consider adding a comment explaining the regex pattern for better maintainability.

+  // Match template variables (prefixed uppercase alphanumeric strings followed by a non-alphanumeric character or end of string)
   renderedTemplate = renderedTemplate.replaceAll(
     new RegExp(`${prefix}[A-Z0-9_]+(?=[^A-Z0-9_]|$)`, 'g'),
packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts (4)

8-23: Ensure consistent handling of empty or base paths in stripRelativePrefixFromProjectRelativePath.
While the function looks correct for './' and '../' usage, consider how an empty string or single-dot ('.') path might be handled. Unintentional cases might trigger the wrong branch or return an unhelpful path.


32-63: Expand error handling for wildcard path validity in getAliasedPathFromTsPathMapEntry.
Currently, the code checks if 'to' and 'from' entries end in /* for wildcard usage, but does not validate invalid repeated wildcards or multiple placeholders. Consider adding further checks to prevent complex wildcard patterns that the function doesn’t handle.


100-128: Consider .cjs/.mjs edge cases in normalizePathForResolutionKind.
When handling Node16 or NodeNext, .js is enforced, yet .cjs or .mjs may emerge in modern Node usage. Consider whether these extensions should be permitted or flagged similarly.


130-174: Add tie-breaker logic for equally short paths in normalizeModuleSpecifier.
The function uses minBy on path lengths to pick the “shortest path.” If two are equally short, minBy picks the first. This typically works but can lead to non-deterministic picks if two aliases are the same length. If stable ordering is needed, consider a secondary tie-breaker.

packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.ts (3)

9-28: Enhance documentation for SortImportDeclarationsOptions.groups.
The interface allows complex multi-group arrays (e.g., ['builtin', 'external'] in one group). Adding a brief example of how multiple group entries are processed would help newcomers understand the grouping mechanism.


30-46: Review default group ordering in defaultSortOptions.
The chosen order covers many typical scenarios, but if the codebase has specialized categories (like monorepo local packages or “hooks” in React projects), consider adding them or letting the user define custom group slices.


48-127: Preserve uniform sorting approach for side-effect imports across groups.
You keep side-effect imports in their original order, which is often desired. If future requirements need stricter ordering among side effects (e.g., for consistent global polyfills), consider an explicit sub-sorting step or a separate grouping rule.

packages/sync/src/output/generator-task-output.ts (3)

149-163: Refine docstring for writeFile payload.
The updated doc references a single payload parameter. Given that you destructure it into multiple fields (id, filePath, etc.), clarify that payload is an object with these properties for better readability.


156-159: Validate new optional generatorName.
If generatorName is empty or has conflicting values across calls, it might produce unexpected file IDs that look identical. Consider adding a quick check or warning if a consumer passes an unexpected generatorName.


176-176: Allow customizing or omitting the separator in the final id.
The id string uses : as a separator (generatorName:someId). If you foresee multiple levels of composition, you might need a standard delimiter definition. Alternatively, consider letting the user specify or override the delimiter.

packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (2)

65-82: Consider short-circuiting isIndexImport checks with additional patterns.
If your setup might include variations like ./index.tsx or other custom expansions, you may append them in this array to ensure coverage without surprises.


146-226: Ordering logic is easy to follow, but watch out for code branching growth.
The layered checks (type-only, side-effect, style, etc.) work well with the sortGroup = sortGroup ?? group approach, ensuring the first match is retained. If the classification logic becomes more complicated, consider extracting sub-steps into smaller functions or a strategy pattern.

packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts (1)

133-160: Conflict resolution strategy is well-defined.
The code systematically filters out type-only entries if a regular entry shares the same name. This helps prevent collisions but might hide legitimate usage in rare scenarios. If you need to handle advanced cases (like re-aliasing type-only imports differently), consider customizing or logging.

packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (1)

19-25: Excluding side-effect imports at retrieval time is useful.
Filtering them up front keeps subsequent logic simpler if you handle side effects separately.

packages/fastify-generators/src/generators/core/logger-service/index.ts (1)

10-12: Consolidate code utility usage.
You are now importing both TsCodeUtils and TypescriptCodeUtils, which appear to provide overlapping functionalities. Consider consolidating these utilities if there is a single recommended approach to building or merging code fragments.

packages/core-generators/src/renderers/typescript/fragments/utils.ts (3)

1-2: Verify third-party dependencies.
The usage of es-toolkit for isEqual, orderBy, and uniqWith may introduce extra overhead. Ensure it’s necessary or consider built-in or smaller alternatives to reduce bundle size.


6-13: Clarify priority strategy for hoisted fragments.
You’ve introduced HoistedFragmentWithPriority and the priority field at lines 6-8. Document the intended range and usage of priority levels to avoid confusion among contributors.


47-66: Consider adding typed returns.
The interface FlattenedImportsAndHoistedFragments (lines 47-50) is clear, but you might add more granular doc comments about how the final merges are expected to behave, especially under collisions or empty fragments.

packages/core-generators/src/renderers/typescript/renderers/file.ts (1)

31-98: Insertion order in the source file.
The logic in mergeImportsAndHoistedFragments inserts fragments at lines 75-80 and 83-88 (after existing imports), then lines 91-96 (before imports). This can lead to unexpected ordering if you heavily rely on their positions. Consider clarifying or exposing these insertion rules, so it’s easy to maintain.

packages/core-generators/src/generators/node/typescript/index.ts (2)

68-70: Descriptor schema is valid

Defining an optional includeMetadata field looks good. Consider adding tests to validate negative/invalid input.


354-413: New task for templated file writing

This task structure neatly queues file-generation actions and processes them in the build function. Consider adding optional error handling for template rendering failures or concurrency constraints if you plan to handle numerous files simultaneously.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 4d5da06 and 55cc54c.

⛔ Files ignored due to path filters (2)
  • packages/fastify-generators/src/generators/core/logger-service/generated/templates.ts is excluded by !**/generated/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (58)
  • .changeset/free-bottles-enter.md (1 hunks)
  • .cursor/rules/writing-vitest-tests.mdc (1 hunks)
  • packages/core-generators/src/actions/copy-typescript-file-action.ts (1 hunks)
  • packages/core-generators/src/generators/node/typescript/index.ts (5 hunks)
  • packages/core-generators/src/index.ts (1 hunks)
  • packages/core-generators/src/renderers/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/creators.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/types.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/utils.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/builder.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/ts-path-maps.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/ts-path-maps.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/imports/types.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/renderers/file.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/renderers/file.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/renderers/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/renderers/template.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/renderers/template.unit.test.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/templates/creators.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/templates/index.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/templates/types.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (1 hunks)
  • packages/core-generators/src/writers/typescript/source-file.ts (2 hunks)
  • packages/fastify-generators/src/generators/auth0/auth0-module/index.ts (2 hunks)
  • packages/fastify-generators/src/generators/core/error-handler-service/index.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/logger-service/index.ts (4 hunks)
  • packages/fastify-generators/src/generators/core/logger-service/templates/logger.ts (1 hunks)
  • packages/fastify-generators/src/generators/core/request-context/index.ts (2 hunks)
  • packages/sync/src/output/generator-task-output.ts (2 hunks)
  • packages/tools/eslint-configs/react.js (1 hunks)
  • packages/tools/eslint-configs/storybook.js (1 hunks)
  • packages/tools/package.json (1 hunks)
  • packages/tools/prettier.config.node.js (2 hunks)
  • packages/tools/prettier.config.react.js (2 hunks)
  • packages/tools/tsconfig.json (1 hunks)
  • packages/tools/tsconfig.node.base.json (1 hunks)
  • packages/utils/src/index.ts (1 hunks)
  • packages/utils/src/maps/group-by.ts (1 hunks)
  • packages/utils/src/maps/group-by.unit.test.ts (1 hunks)
  • packages/utils/src/maps/index.ts (1 hunks)
  • packages/utils/src/maps/map-values-of-map.ts (1 hunks)
  • packages/utils/src/maps/map-values-of-map.unit.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (25)
packages/utils/src/maps/map-values-of-map.unit.test.ts (1)
packages/utils/src/maps/map-values-of-map.ts (1)
  • mapValuesOfMap (11-20)
packages/utils/src/maps/group-by.unit.test.ts (1)
packages/utils/src/maps/group-by.ts (1)
  • mapGroupBy (12-27)
packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (2)
packages/core-generators/src/renderers/typescript/fragments/utils.ts (1)
  • flattenImportsAndHoistedFragments (58-90)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/templates/creators.ts (2)
packages/core-generators/src/renderers/typescript/templates/types.ts (2)
  • TsCodeTemplateVariableMap (7-7)
  • TsCodeFileTemplate (17-28)
packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1)
  • template (160-181)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.unit.test.ts (2)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts (2)
  • mergeTsImportDeclarations (133-160)
  • ImportConflictError (9-14)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.unit.test.ts (2)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (1)
  • getImportSortGroup (149-226)
packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (1)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts (2)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.ts (1)
  • sortImportDeclarations (56-127)
packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (1)
packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1)
  • TsCodeUtils (38-182)
packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.test.ts (2)
packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts (1)
  • normalizeModuleSpecifier (143-174)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsPathMapEntry (69-74)
packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (1)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/renderers/template.unit.test.ts (3)
packages/core-generators/src/renderers/typescript/renderers/template.ts (1)
  • renderTsTemplateToTsCodeFragment (27-73)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (2)
  • tsCodeFragment (30-44)
  • tsHoistedFragment (15-21)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-71)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (2)
packages/core-generators/src/renderers/typescript/fragments/types.ts (3)
  • TsCodeFragment (45-62)
  • TsHoistedFragmentPosition (6-6)
  • TsHoistedFragment (16-36)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/renderers/template.ts (3)
packages/core-generators/src/renderers/typescript/templates/types.ts (2)
  • TsCodeTemplateVariableMap (7-7)
  • InferTsCodeTemplateVariablesFromMap (30-34)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/fragments/utils.ts (1)
  • flattenImportsAndHoistedFragments (58-90)
packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.unit.test.ts (2)
packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (3)
  • getTsMorphImportDeclarationsFromSourceFile (19-25)
  • convertTsMorphImportDeclarationToTsImportDeclaration (32-46)
  • writeGroupedImportDeclarationsWithCodeBlockWriter (101-111)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/renderers/file.unit.test.ts (3)
packages/core-generators/src/renderers/typescript/fragments/creators.ts (1)
  • tsCodeFragment (30-44)
packages/core-generators/src/renderers/typescript/renderers/file.ts (1)
  • renderTsCodeFileTemplate (99-137)
packages/core-generators/src/renderers/typescript/imports/builder.ts (1)
  • tsImportBuilder (69-71)
packages/core-generators/src/renderers/typescript/templates/types.ts (1)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/renderers/file.ts (7)
packages/core-generators/src/renderers/typescript/renderers/template.ts (2)
  • RenderTsTemplateOptions (9-18)
  • renderTsTemplateToTsCodeFragment (27-73)
packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.ts (2)
  • SortImportDeclarationsOptions (12-28)
  • sortImportDeclarations (56-127)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/renderers/typescript/fragments/types.ts (1)
  • TsHoistedFragment (16-36)
packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (3)
  • getTsMorphImportDeclarationsFromSourceFile (19-25)
  • convertTsMorphImportDeclarationToTsImportDeclaration (32-46)
  • writeGroupedImportDeclarationsWithCodeBlockWriter (101-111)
packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts (1)
  • mergeTsImportDeclarations (133-160)
packages/core-generators/src/renderers/typescript/templates/types.ts (3)
  • TsCodeTemplateVariableMap (7-7)
  • TsCodeFileTemplate (17-28)
  • InferTsCodeTemplateVariablesFromMap (30-34)
packages/fastify-generators/src/generators/core/logger-service/index.ts (3)
packages/core-generators/src/generators/node/typescript/index.ts (1)
  • typescriptFileProvider (138-139)
packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1)
  • TsCodeUtils (38-182)
packages/fastify-generators/src/generators/core/logger-service/generated/templates.ts (1)
  • loggerFileTemplate (4-12)
packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.ts (3)
packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (2)
  • ImportSortGroup (30-30)
  • getImportSortGroup (149-226)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/utils/src/maps/group-by.ts (1)
  • mapGroupBy (12-27)
packages/core-generators/src/renderers/typescript/fragments/utils.ts (2)
packages/core-generators/src/renderers/typescript/fragments/types.ts (2)
  • TsHoistedFragment (16-36)
  • TsCodeFragment (45-62)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsImportDeclaration (22-43)
packages/core-generators/src/generators/node/typescript/index.ts (4)
packages/sync/src/output/generator-task-output.ts (1)
  • WriteFileOptions (15-33)
packages/core-generators/src/renderers/typescript/imports/ts-path-maps.ts (2)
  • generatePathMapEntries (12-27)
  • pathMapEntriesToRegexes (46-54)
packages/core-generators/src/renderers/typescript/renderers/file.ts (1)
  • renderTsCodeFileTemplate (99-137)
packages/core-generators/src/writers/typescript/imports.ts (1)
  • resolveModule (71-111)
packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts (1)
packages/core-generators/src/renderers/typescript/imports/types.ts (1)
  • TsPathMapEntry (69-74)
🔇 Additional comments (157)
packages/core-generators/src/renderers/typescript/templates/index.ts (1)

1-2: Aggregated Exports Entry Point.
The exports from creators.js and types.js provide a neat consolidated entry for the TypeScript rendering utilities. Ensure that these JavaScript modules are either the intended targets (post-transpilation) or consider matching extensions if using TypeScript source files.

packages/core-generators/src/renderers/index.ts (1)

1-1: Centralized TypeScript Renderer Export.
Re-exporting the content from ./typescript/index.js is an effective way to expose the TypeScript renderer's functionality. Verify that your module resolution strategy in your TypeScript configuration handles the .js extension appropriately, especially when mixing with TypeScript source files.

.changeset/free-bottles-enter.md (1)

1-9: Well-Structured Changeset File.
This changeset properly lists the dependency patches and documents the initiation of the new TypeScript writer system. It correctly conveys the intent of the update. Just ensure that the dependency version changes in your package files are consistent with these patches.

packages/core-generators/src/renderers/typescript/renderers/index.ts (1)

1-2: Consolidated Renderer Module Exports.
The re-export statements for file.js and template.js create a convenient aggregation for accessing these modules’ functionalities. Confirm that these files are correctly implemented and aligned with the new TypeScript writer system’s design.

packages/tools/tsconfig.node.base.json (1)

1-5: Updated Node.js TypeScript Configuration.
Changing the "extends" property to use @tsconfig/node22/tsconfig.json successfully updates the project for Node version 22. Make sure that the rest of the codebase is tested under Node 22 to verify complete compatibility with this new configuration.

packages/core-generators/src/renderers/typescript/imports/sort-imports/index.ts (1)

1-2: Export barrel file looks good

This barrel file appropriately exports all entities from the sort-import-declarations module, which helps with organizing imports and providing a clean API surface for the TypeScript renderer foundation.

packages/utils/src/maps/index.ts (1)

1-3: Clean barrel export implementation

Good use of a barrel file to consolidate and re-export the map utility functions. This pattern keeps the API surface clean and well-organized while making the new map utilities easily accessible.

packages/utils/src/index.ts (1)

3-3: Good addition of maps module export

The export of the maps module follows the existing pattern in this file. This change appropriately exposes the new map utilities through the main package entry point.

packages/core-generators/src/index.ts (1)

5-5: Appropriate integration of renderer exports

Adding the renderers export integrates the new TypeScript renderer system into the main package export surface. This change properly aligns with the PR objective of laying foundations for the new TypeScript renderer.

.cursor/rules/writing-vitest-tests.mdc (1)

6-6: Clarify the file extension requirement.

There appears to be a potential confusion in the documentation. It mentions that "files must end with .js" due to Node 16 module resolution, but the test naming conventions specify .ts extensions. Consider clarifying that this refers to import statements requiring .js extensions while the actual files use .ts extensions.

packages/core-generators/src/renderers/typescript/fragments/index.ts (1)

1-4: Well-structured exports for TypeScript fragments.

Good organization using a barrel file pattern to consolidate exports from related modules.

packages/core-generators/src/renderers/typescript/index.ts (1)

1-5: Well-organized TypeScript renderer exports.

Good job creating a comprehensive entry point that aggregates all the renderer's submodules. This structure makes importing from this package clean and intuitive.

packages/fastify-generators/src/generators/core/logger-service/templates/logger.ts (1)

4-4:

Details

✅ Verification successful

Updated logger initialization to use template variable.

The change from LOGGER_OPTIONS to TPL_LOGGER_OPTIONS aligns with the new TypeScript renderer system mentioned in the PR objectives. The TPL_ prefix suggests this is a template variable that will be replaced during code generation.


🏁 Script executed:

#!/bin/bash
# Check if TPL_LOGGER_OPTIONS is properly defined or handled in the generator logic

# Look for definitions or usages of TPL_LOGGER_OPTIONS in generator files
echo "Searching for references to TPL_LOGGER_OPTIONS in the codebase:"
rg "TPL_LOGGER_OPTIONS" --type ts

Length of output: 523


TPL_LOGGER_OPTIONS handling confirmed

The TPL_LOGGER_OPTIONS template variable is intentionally used in the logger template. Verification shows that it is defined and processed correctly in the generator logic (see its references in both index.ts and generated/templates.ts). No further changes are needed.

packages/tools/prettier.config.react.js (1)

2-2: Good improvement to module imports

Replacing the full module import with a named import of just the fileURLToPath function is a good practice that improves code quality. This follows modern ES module best practices and potentially helps with tree-shaking.

Also applies to: 13-13

packages/core-generators/src/renderers/typescript/templates/creators.ts (1)

5-14: Good foundation for TypeScript templating

This factory function provides a clean, type-safe API for creating TypeScript code file templates. While it currently just returns the input template, this pattern establishes a consistent entry point for template creation that can be extended in the future without breaking existing code. The proper JSDoc documentation is also valuable for developers who will use this API.

packages/utils/src/maps/map-values-of-map.unit.test.ts (1)

5-59: Well-structured and comprehensive tests

These tests for mapValuesOfMap follow excellent testing practices:

  • Clear Arrange-Act-Assert pattern
  • Descriptive test names
  • Good coverage of basic functionality, parameter access, and edge cases
  • Verifies the full API (accessing value, key, and map in the transformation)

This provides solid validation for the utility function.

packages/core-generators/src/actions/copy-typescript-file-action.ts (1)

68-68: Good simplification of code

This change removes an unnecessary intermediate variable (fullPath) and directly passes destinationPath to the formatImports function. This makes the code more concise while maintaining the same functionality.

packages/core-generators/src/renderers/typescript/fragments/utils.unit.test.ts (5)

1-6: Well-structured import setup.

Good use of specific imports from 'vitest' and importing the necessary types and functions for testing. The import structure is clean and follows best practices.


7-14: Well-defined base test case for handling empty arrays.

This test case ensures the function handles edge cases properly by verifying it returns empty arrays for both imports and hoistedFragments when given an empty input.


16-34: Good test coverage for flattening imports from multiple fragments.

The test correctly verifies that imports from different fragments are properly collected and maintained in the result. Test data setup is clear and expectations are specific.


73-109: Thorough test for deduplication functionality.

The test effectively verifies that duplicate hoisted fragments with the same key are properly deduplicated. Good verification of both length and content matching.


111-165: Comprehensive test for ordering by priority and key.

The test thoroughly verifies that hoisted fragments are properly ordered by priority (highest to lowest) and then alphabetically by key. It covers both nested fragments (higher priority) and root-level fragments (ordered by key).

packages/tools/prettier.config.node.js (2)

2-2: Improved import specificity.

Directly importing fileURLToPath instead of the entire url module follows best practices by only importing what's needed.


12-12: Updated function call to match import.

Correctly updated to use the directly imported fileURLToPath function instead of accessing it as a property of the url object.

packages/core-generators/src/writers/typescript/source-file.ts (2)

734-738: Simplified path handling in renderToActionFromText.

The code now directly uses the destination parameter for both content rendering and file metadata, eliminating unnecessary variable assignments. This improves readability while maintaining the same functionality.


757-757: Streamlined path resolution in renderToAction.

The approach of using a fallback mechanism (destination ?? templateFile) for determining the full path is clean and concise, properly supporting both scenarios when destination is provided or not.

packages/utils/src/maps/map-values-of-map.ts (2)

1-10: Excellent JSDoc documentation.

The function is thoroughly documented with clear parameter descriptions, type templates, and return value explanation. This enhances code readability and facilitates proper usage.


11-20: Well-implemented functional utility for Map transformation.

The implementation is clean and efficient, properly leveraging TypeScript generics and Map methods. The function follows functional programming principles by returning a new Map rather than modifying the input.

Some potential areas for future enhancement:

  • Consider adding a type guard or special handling for empty maps
  • Add support for a thisArg parameter similar to Array.prototype.map
packages/tools/tsconfig.json (1)

1-11: Well-structured TypeScript configuration for Node.js tooling

This TypeScript configuration is correctly set up to work with Node.js v22, which aligns with the PR objective of updating tools to operate with Node version 22. The configuration properly extends from a base configuration, enables JavaScript files, and prevents emitting compiled files.

packages/core-generators/src/renderers/typescript/imports/index.ts (1)

1-7: Good organization of exports using barrel pattern

This barrel file effectively centralizes TypeScript import-related functionality, making it easier to consume these utilities elsewhere in the codebase. This organization supports the new TypeScript renderer foundation.

packages/core-generators/src/renderers/typescript/imports/ts-path-maps.unit.test.ts (2)

8-28: Well-structured test for generatePathMapEntries

The test follows the Arrange-Act-Assert pattern and verifies that path mappings are correctly transformed with a variety of path configurations including wildcard paths.


30-53: Comprehensive regex testing for path map entries

The test effectively validates that the generated regular expressions correctly match the intended module aliases while rejecting non-matching patterns. Good job testing both wildcard and exact match scenarios.

packages/fastify-generators/src/generators/auth0/auth0-module/index.ts (2)

1-9: Good adoption of new TypeScript renderer utilities

The addition of tsCodeFragment and tsImportBuilder imports aligns with the PR objective of introducing a new TypeScript renderer system.


222-229: Improved code generation with structured TypeScript utilities

The modification of the addMixin implementation now uses the new TypeScript renderer system with tsCodeFragment and tsImportBuilder instead of string-based expressions. This provides a more robust and type-safe approach to generating TypeScript code.

packages/tools/package.json (2)

44-44: Good addition of typecheck script.

This script allows TypeScript type checking without emitting JS files, which is useful for development and CI/CD pipelines.


48-48: Node 22 upgrade matches PR objectives.

Replacing @tsconfig/node20 with @tsconfig/node22 aligns with the PR objective of updating tools to operate with Node 22 instead of version 20.

packages/utils/src/maps/group-by.unit.test.ts (1)

1-70: Well-structured and comprehensive test coverage.

The test suite follows the Arrange-Act-Assert pattern and thoroughly covers the mapGroupBy functionality:

  • Testing strings grouped by length
  • Handling empty input cases
  • Grouping with constant keys
  • Grouping objects by property

Good job including a variety of test scenarios to validate the utility function.

packages/fastify-generators/src/generators/core/request-context/index.ts (2)

7-8: Appropriate imports for the new TypeScript renderer system.

These new imports introduce components of the TypeScript renderer system mentioned in the PR objectives.


51-56: Improved TypeScript code generation approach.

Replacing TypescriptCodeUtils.createExpression with the new tsCodeFragment and tsImportBuilder functions creates a more structured approach to generating TypeScript code and managing imports. This is consistent with the PR objective of introducing a new TypeScript renderer system.

packages/utils/src/maps/group-by.ts (2)

1-11: Excellent documentation with JSDoc comments.

The function is well-documented with clear JSDoc comments explaining its purpose, parameters, and return type. The comment about mimicking ES2025 Map.groupBy is particularly helpful for understanding the function's intent.


12-27: Clean and efficient implementation.

The mapGroupBy implementation is straightforward and follows best practices:

  1. Uses generics appropriately for type safety
  2. Efficiently builds the result map in a single pass
  3. Handles both new keys and existing keys correctly
  4. Returns the properly constructed map

This utility function will be valuable for collections processing throughout the codebase.

packages/core-generators/src/renderers/typescript/imports/types.ts (3)

1-17: Well-structured TypeScript interface for named imports.

The TsNamedImport interface is clearly defined with appropriate properties for handling named imports in TypeScript, including support for aliases and type-only imports. The documentation is thorough and follows best practices.


19-43: Clean interface definition for import declarations.

The TsImportDeclaration interface provides a comprehensive representation of all possible import types in TypeScript. The properties cover default imports, namespace imports, and named imports with clear documentation for each field.


45-74: Excellent documentation with practical examples.

The TsPathMapEntry interface includes extensive documentation with concrete examples showing the relationship between tsconfig.json path mappings and the interface usage. This makes it easy for developers to understand how to use this interface correctly.

packages/core-generators/src/renderers/typescript/fragments/types.ts (3)

1-7: Good union type design for fragment positioning.

The TsHoistedFragmentPosition type clearly defines the possible positions where hoisted fragments can be placed. This enum-like approach provides type safety while remaining simple.


8-36: Well-structured interface for hoisted fragments.

The TsHoistedFragment interface is clearly defined with appropriate properties for handling fragment positioning, deduplication, and content. The documentation thoroughly explains the purpose and usage patterns.


38-62: Comprehensive code fragment representation.

The TsCodeFragment interface effectively encapsulates code content, required imports, and related fragments in a cohesive structure. This design supports a clean separation of concerns in the TypeScript rendering system.

packages/fastify-generators/src/generators/core/error-handler-service/index.ts (1)

50-53: Interface simplified with method removal.

The ErrorHandlerServiceProvider interface has been simplified with the removal of the getHttpErrorExpression method. This aligns with the broader shift to a new TypeScript rendering system mentioned in the PR objectives.

packages/core-generators/src/renderers/typescript/imports/builder.ts (2)

1-37: Well-designed builder interface with fluent API.

The TsImportDeclarationBuilder interface provides a clean, fluent API for constructing import declarations. Each method is clearly documented with appropriate JSDoc comments.


69-71: Simple factory function for creating builder instances.

The exported tsImportBuilder function provides a clean factory for creating new builder instances with an empty initial declaration. This follows good builder pattern practices.

packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.unit.test.ts (9)

11-13: Well-implemented utility function.

The stripUndefinedChildren function is a clean utility that removes undefined properties from objects, making test assertions more reliable by eliminating noise from undefined values.


15-30: Good approach for test consistency.

The mergeTsImportDeclarationsSorted function elegantly combines sorting and cleaning operations, ensuring consistent ordering for test assertions. The sorting by source and isTypeOnly flag enables predictable test outcomes.


32-52: Effective basic test case.

This test case correctly verifies the core functionality of merging named imports from the same source. The expected output confirms that imports are properly combined into a single declaration.


54-69: Good error validation.

This test properly verifies that the function throws an ImportConflictError when conflicting aliases are detected, which is critical for preventing inconsistent imports.


71-86: Appropriate error validation for namespace imports.

This test correctly validates that conflicting namespace imports from the same source trigger an exception, maintaining import integrity.


88-103: Comprehensive test for conflicting default imports.

This test appropriately validates the error handling for conflicting default imports, ensuring the merging logic maintains import integrity.


105-130: Important test for import type separation.

This test verifies that type-only imports remain separate from regular imports, which is crucial for proper TypeScript code generation and prevents type/value confusion.


208-233: Smart handling of duplicate imports.

This test verifies an important optimization: when an import exists as both a type and a regular import, the type import is removed to prevent duplication. This ensures clean and efficient import statements.


279-307: Thorough edge case testing.

This test covers a complex scenario with mixed type and regular imports that have partial overlap. It correctly validates that the function handles this case by keeping unique type imports separate while merging overlapping imports into the regular statement.

packages/core-generators/src/renderers/typescript/renderers/file.unit.test.ts (4)

8-23: Good baseline test.

This test effectively verifies the basic functionality of rendering a simple template without imports, establishing a foundation for more complex test cases.


25-56: Well-structured import test.

This test validates import merging and sorting with a clean approach using inline snapshots. The test ensures that type-only imports are properly separated from regular imports and that everything appears in the correct order.


85-129: Comprehensive hoisted fragments test.

This test effectively verifies that hoisted fragments are placed in the correct order (beforeImports and afterImports) in the rendered output. The inline snapshot clearly shows the expected structure with proper spacing between sections.


58-83:

Details

❓ Verification inconclusive

Effective module resolution test.

This test properly validates custom module resolution functionality. It confirms that the resolver function is correctly applied to transform import paths.

However, the resulting path @project/./test looks unusual with the dot. Consider verifying if this is the expected behavior.


🏁 Script executed:

#!/bin/bash
# Search for similar module resolution patterns in the codebase
rg -A 2 -B 2 "resolveModule.*moduleSpecifier" --glob "*.ts"

Length of output: 2946


Module resolution output review – please confirm expected path normalization

The test effectively verifies that our custom resolver prepends "@project/" to the module specifier. However, because the resolver is implemented as:

resolveModule: (moduleSpecifier) => `@project/${moduleSpecifier}`,

when given a specifier like "./test", the final import becomes "@project/./test". Our search of similar patterns in the codebase (e.g. in packages/core-generators/src/generators/node/typescript/index.ts and in the type definitions in packages/core-generators/src/renderers/typescript/renderers/file.ts) shows that this concatenation approach is consistently used.

Please verify if leaving the "./" intact is the intended behavior or if you’d prefer to normalize the module path (e.g., by stripping the "./" prefix) to produce "@project/test" instead.

packages/core-generators/src/renderers/typescript/fragments/creators.ts (2)

1-7: Clean import organization.

Imports are well organized, with type imports separated from other imports for better readability.


8-21: Well-documented utility function.

The tsHoistedFragment function is clearly documented with JSDoc comments that explain its purpose and parameters. The implementation is concise and focuses on creating the right structure.

packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.test.ts (6)

7-9: Good test organization.

The use of a constant directory for all tests improves readability and maintainability.


10-15: Clear external module handling test.

This test verifies that external module specifiers remain unchanged, which is a fundamental behavior for the normalizer.


17-22: Important extension handling test.

This test confirms the proper behavior for stripping .js extensions from relative imports in non-Node16 resolution mode, which is important for compatibility with TypeScript's module resolution.


24-34: Comprehensive alias path handling.

This test effectively verifies alias path normalization using TypeScript path mapping. The comment on line 32 helpfully explains the expected outcome.


47-53: Critical Node16 validation.

This test properly verifies that an error is thrown for Node16 relative imports missing the .js extension, which is essential for ensuring compatibility with Node16 ESM requirements.


55-67: Complete Node16 testing.

These tests correctly validate both the happy path (with .js extension) and confirm that external modules don't require extensions in Node16 mode.

packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.unit.test.ts (11)

7-29: Well-structured helper function for test setup.

The createImportDeclaration helper function provides a clean abstraction for creating import declaration test fixtures with sensible defaults. This reduces repetition across test cases and makes the tests more readable.


31-55: Thorough test coverage for built-in module classification.

These tests effectively verify that the getImportSortGroup function correctly categorizes both standard Node.js modules and namespaced modules as 'builtin', while handling type-only imports appropriately.


57-80: Comprehensive external module classification tests.

The tests cover different types of external module imports, including regular packages, scoped packages, and type-only imports. This ensures robust sorting behavior for dependencies.


82-106: Good test coverage for internal modules with custom patterns.

The tests properly verify that the internalPatterns option is respected when determining if a module is internal, which is important for organization-specific import sorting.


108-131: Complete test coverage for parent directory imports.

Tests verify both shallow and deep parent directory imports, as well as type-only variants, ensuring accurate classification of imports that reference modules in parent directories.


133-156: Thorough test cases for sibling imports.

The tests cover various sibling import scenarios including directory imports, file imports with extensions, and type-only imports.


158-188: Comprehensive index import classification tests.

Tests verify all variations of index imports (., ./, ./index.js) are correctly classified, including type-only index imports.


190-223: Solid test coverage for style imports.

The tests handle various style import scenarios including different extensions (CSS, SCSS), imports with query parameters, and custom style extensions. This ensures proper classification of styling imports.


225-236: Effective side effect import tests.

The tests verify that both general side effect imports and style-specific side effect imports are categorized correctly.


238-254: Important edge case testing for unknown imports.

These tests ensure proper fallback behavior for non-standard import paths, covering both regular imports and type-only imports.


256-321: Robust testing of allowedSortGroups functionality.

The tests thoroughly validate that the allowedSortGroups option correctly restricts categorization to allowed groups, falls back to appropriate alternatives, and always permits 'unknown' as a final fallback. This is crucial for customized import sorting schemes.

packages/core-generators/src/renderers/typescript/renderers/template.unit.test.ts (5)

7-33: Effective test for basic template variable replacement.

This test validates that the template rendering system correctly replaces variables with their corresponding values, while preserving surrounding text and verifying empty collections for imports and hoisted fragments.


35-48: Good coverage of metadata inclusion option.

The test verifies that when the includeMetadata option is enabled, the original template variable key is included as a comment in the output, which helps with debugging and tracing template transformations.


50-75: Comprehensive test for imports and hoisted fragments collection.

This test ensures that the template renderer correctly extracts and collects imports and hoisted fragments from complex variable values, which is essential for maintaining dependencies and code organization in the generated output.


77-88: Appropriate error handling test.

The test verifies that the function properly validates template variable keys, ensuring they follow the required conventions for uppercase alphanumeric characters, which helps maintain consistency and prevents errors.


90-102: Important validation for ts-nocheck stripping.

This test confirms that the // @ts-nocheck directive is properly removed from the template header while preserving the actual template content, which is important for generating clean TypeScript code.

packages/core-generators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts (6)

7-29: Well-designed helper function for import declarations.

The createImportDeclaration helper function provides a convenient way to create test fixtures with sensible defaults, reducing test code duplication and improving readability.


31-71: Comprehensive test for default group ordering.

This test validates that imports are correctly sorted according to the default group order, with proper handling of different import types (style, react, fs, utils, internal, type-only). It effectively tests the core sorting functionality.


73-87: Important test for side effect import ordering preservation.

This test verifies that the order of side effect imports is preserved within groups, which is critical for maintaining proper initialization order in cases where the import sequence matters.


101-111: Proper case-sensitive sorting test.

This test correctly verifies that when ignoreCase: false is set, the sorting respects the original case of the import sources.


113-126: Good test for custom group configurations.

This test ensures that custom group configurations are respected, validating that imports are categorized and ordered according to user-defined sorting rules.


128-131: Important edge case test for empty arrays.

Testing the behavior with an empty input array is a good practice that validates proper handling of edge cases.

packages/core-generators/src/renderers/typescript/imports/ts-path-maps.ts (3)

5-27: Solid implementation of path map entry generation with proper error handling.

The generatePathMapEntries function correctly transforms TypeScript path mappings into a format usable by the renderer, with appropriate error handling for unsupported multiple targets. The use of path.posix.join ensures consistent path separators.


29-37: Robust regex escaping utility.

The escapeRegex helper function properly escapes special characters for regex patterns, which is essential for correctly matching path patterns that might contain regex metacharacters.


39-54: Effective conversion of path maps to regexes with wildcard support.

The pathMapEntriesToRegexes function correctly handles both exact matches and wildcard patterns in path maps, ensuring accurate identification of internal modules when applying import sorting rules.

packages/core-generators/src/renderers/typescript/templates/types.ts (4)

3-5: Well-structured type definition for template variables

The TsCodeTemplateVariable interface is well-defined with an optional description field, which is useful for documentation purposes.


9-15: Good use of union type for template source

The union type approach for TsCodeFileTemplateSource provides flexibility for template sources to be either file paths or inline content.


17-28: Well-designed template interface with generic parameter

The TsCodeFileTemplate interface is well-designed with proper generic constraints and documentations. The optional prefix property with a default value documented in JSDoc is a good practice.


30-34: Type utility provides strong typing for template variables

The InferTsCodeTemplateVariablesFromMap type effectively maps template variable definitions to their concrete implementations as either TsCodeFragment or string.

packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (9)

8-36: Comprehensive tests for mergeFragments method

The test cases thoroughly validate the functionality of the mergeFragments method, particularly its ability to combine code contents, imports, and hoisted fragments.


38-45: Edge case handling for mergeFragments

Good test coverage for the edge case of an empty fragments array, ensuring the method returns an appropriate empty structure.


48-58: Complete test coverage for formatAsComment

The tests effectively verify both single-line and multi-line text formatting as comments.


60-77: Comprehensive testing of formatFragment

Test cases appropriately verify the functionality for replacing placeholders with content and preserving imports.


79-83: Proper error testing for invalid placeholder names

The test verifies that the function correctly throws an error when invalid placeholder names are used, which is important for early error detection.


86-110: Thorough testing of mergeFragmentsAsObject basic functionality

Test case thoroughly verifies complex object generation including property assignment, spread operators, and import collection.


112-122: Testing optional wrapping behavior

Good test coverage for the wrapWithParenthesis option, ensuring the correct formatting is applied.


124-133: Verification of undefined value handling

Test ensures that undefined values are correctly filtered out from the resulting object.


135-143: Property shorthand testing

Test verifies that property shorthand syntax is correctly applied when the property name matches the value identifier.

packages/core-generators/src/renderers/typescript/renderers/template.ts (4)

9-18: Clear option interface with well-documented properties

The RenderTsTemplateOptions interface is well-designed with self-explanatory properties and appropriate JSDoc comments.


20-33: Function signature with proper generic constraint

The function signature is well-defined with appropriate generic constraints and typed parameters. The JSDoc clearly explains the purpose and parameters.


34-47: Strong input validation

Good validation of input parameters including checking for proper variable key format and prefix. The error message is clear and informative.


64-72: Proper extraction of imports and hoisted fragments

The code correctly filters and extracts imports and hoisted fragments from non-string values. The return object structure matches the expected TsCodeFragment interface.

packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.unit.test.ts (8)

14-21: Good test setup with proper isolation

The test suite uses beforeEach to create fresh Project and SourceFile instances for each test, ensuring proper isolation.


23-58: Comprehensive testing of import declaration filtering

The tests thoroughly verify that side-effect imports are correctly filtered out from the source file.


60-198: Exhaustive test cases for import declaration conversion

The test suite provides excellent coverage of various import scenarios including default, named, namespace, type-only imports, and complex combinations. Each case verifies all properties of the converted declaration.


201-245: Comprehensive testing of import writing

Tests verify correct formatting for default and named imports when writing to CodeBlockWriter.


246-304: Thorough verification of special import types

Tests cover namespace imports and various type-only import scenarios with appropriate assertions.


306-345: Validation of aliased and mixed imports

Good test coverage for aliased named imports and mixed default/named imports, ensuring correct formatting.


347-366: Testing of grouped import sections

Test verifies that multiple import sections are correctly separated by newlines in the output.


368-386: Error handling verification

The test properly verifies that an error is thrown when trying to mix namespace imports with default or named imports, which is an important validation.

packages/core-generators/src/renderers/typescript/imports/normalize-module-specifier.ts (2)

65-82: Clarify usage for isInternalImport.
The function treats all relative paths (name.startsWith('.')) and paths matching TsPathMapEntry as internal. If additional path forms (e.g., custom prefixes not starting with @ or .) need to be treated as internal, ensure they're included in pathmapEntries or accounted for elsewhere.


84-99: Confirm stability of ModuleResolutionKind string literal type.
The template literal type references ts.server.protocol.ModuleResolutionKind. Verify that the runtime environment and library versions align with this usage to avoid unexpected compile or runtime issues if the ts-morph or TS protocol changes.

packages/sync/src/output/generator-task-output.ts (1)

164-164: Confirm cross-platform compatibility of filePath.replaceAll(path.sep, path.posix.sep).
This usage is valid in modern Node but ensure that all Node versions you support properly implement String.replaceAll. If older Node versions are in use, a fallback or polyfill might be required.

packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (2)

7-25: Flexible grouping approach is beneficial.
Defining & exporting a comprehensive set of allowed import groups improves clarity and maintainability.


1-1:

Details

✅ Verification successful

Validate usage of isBuiltin from 'node:module'.
Although Node 22 should fully support isBuiltin, it's good practice to confirm there's no compatibility issue.

Please confirm that deploying on Node 22 covers 'node:module' usage by running:

If everything is consistent, feel free to ignore this comment.


🏁 Script executed:

#!/bin/bash
node --version
rg "isBuiltinModule" -A 3

Length of output: 1995


Verified: Node 22 fully supports the usage of isBuiltinModule from 'node:module'.
The shell script output confirms that the code runs under Node v22.9.0 and that the usage of isBuiltinModule in the file is consistent across its instances. No compatibility issue was detected; you can safely ignore this comment.

packages/core-generators/src/renderers/typescript/imports/merge-ts-import-declarations.ts (2)

9-14: Clear error handling for import conflicts.
Using a dedicated error class makes conflict resolution transparent.


60-72: Good safeguards against duplicate aliases.
Throwing an ImportConflictError ensures immediate feedback instead of silently merging conflicting imports.

packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (4)

5-12: isSideEffectImport approach is concise.
This properly flags imports lacking any specifier as pure side effects.


32-46: Accurate conversion to custom import structure.
Capturing isTypeOnly at both the declaration and named import level is thorough. This helps maintain consistent state across the codebase.


48-94: Robust error handling when mixed namespace and named/default imports appear.
This is in line with TS syntax rules. The logic also gracefully handles sorting and labeling type-only named imports.


101-111: Logical grouping and spacing of imports.
Generating extra blank lines after each group improves readability and clarity in the final output.

packages/fastify-generators/src/generators/core/logger-service/index.ts (5)

3-3: Confirm consistent usage of TsCodeFragment.
You’ve added TsCodeFragment here but still import TypescriptCodeExpression at line 4. Verify that the old type is no longer needed, or remove it to avoid confusion.

Would you like a script to confirm no remaining references to TypescriptCodeExpression break the flow?


24-24: Validate template file path.
Make sure that './generated/templates.js' is the correct relative path for the loggerFileTemplate. If the project is reorganized, this path might break.


31-31: Signature update looks good.
Switching from TypescriptCodeExpression to TsCodeFragment in the addMixin method aligns better with the new code-fragment-based approach. This seems consistent with the updated generator logic.


70-73: Check for backward compatibility with tasks.
The function now expects { node, fastify, typescriptFile } instead of { typescript }. If other tasks rely on the old key, ensure everything is updated to avoid breakages.


113-146: Streamline the “loggerOptions” build process.
The approach for conditionally merging fragments into TPL_LOGGER_OPTIONS is clear. Just ensure:

  1. All possible logger options are tested.
  2. Using mergeFragmentsAsObject is the intended final approach (instead of template).
  3. Overwritten or conflicting keys in loggerOptions are handled gracefully.

Everything else looks consistent.

packages/core-generators/src/renderers/typescript/fragments/utils.ts (2)

15-45: Recursive flattening logic.
Overall, flattenImportsAndHoistedFragmentsRecursive is well-structured. Confirm:

  1. Edge cases with deeply nested fragments.
  2. Merged imports do not accidentally duplicate.
  3. Priority increments for each nesting level are the intended design.

67-90: Deduplicate with caution.
Your deduplication strategy at lines 71-88 sorts fragments first by priority (descending), then by key, and throws an error if contents differ. This is good, but ensure it’s documented so that contributors know you cannot define multiple fragments under the same key with different contents.

packages/core-generators/src/renderers/typescript/renderers/file.ts (3)

1-5: Check Node 22 compatibility for ts-morph.
This file uses ts-morph and node:fs/promises. Confirm Node 22 fully supports these features and that ts-morph is stable with Node 22.


6-29: Ensure stable import and type definitions.
The RenderTsCodeFileTemplateOptions interface merges multiple typing sources. Confirm no naming collisions or missing properties occur if other code also extends these base definitions in the near future.


99-137: Efficient handling for templates without imports.
When no imports or hoisted fragments exist, returning contents immediately at line 119 is good for speed. Confirm that template metadata (if any) remains consistent in such a short-circuit case. Otherwise, everything else here appears solid.

packages/core-generators/src/generators/node/typescript/index.ts (7)

16-20: Type imports look consistent

These imports have a clear usage in the newly introduced interfaces.


25-29: No issues importing utility functions

The newly introduced functions from @src/renderers/typescript/index.js align well with the code below.


121-131: Interface design is coherent

The shape of WriteTemplatedFilePayload is straightforward and supports typical file generation usage.


132-137: Method signature aligns with new interface

Provides a clear entry point for writing templated files.


138-139: Provider creation is clear

Implementation follows the existing provider pattern.


176-177: Descriptor integration

Passing the descriptor validated by the schema into buildTasks is a clean approach.


13-13:

Details

✅ Verification successful

Ensure zod dependency is declared

This import relies on zod; confirm that your application’s dependencies include it.

Run the following script to check if zod is listed in your package configuration:


🏁 Script executed:

#!/bin/bash
# Searching for 'zod' in package.json
rg 'zod' package.json

Length of output: 21


Attention: Manual verification needed for the "zod" dependency declaration
The initial script execution on the root package.json did not reveal any mention of "zod". Given that this file may not be the sole location for dependency declarations (especially in a monorepo), please verify manually that the appropriate package.json file—including, for example, packages/core-generators/package.json if applicable—declares "zod" as a dependency.

  • Confirm that the relevant package's package.json includes an entry for "zod" (e.g., in the "dependencies" or "devDependencies" section).
  • If your project uses multiple package.json files, ensure that the one corresponding to packages/core-generators properly includes the "zod" dependency.

Once you verify the inclusion of "zod", you can remove this comment.


🏁 Script executed:

#!/bin/bash
# Search for the "zod" dependency in all package.json files in the repository
find . -type f -name "package.json" -exec rg '"zod"' {} \;

Length of output: 388


Dependency Check Passed: zod is Declared
The verification confirms that zod is properly declared in the repository's package configurations (e.g., with version "3.24.1"). No further action is required on this import.

packages/core-generators/src/renderers/typescript/ts-code-utils.ts (8)

1-19: Robust string formatting logic

formatStringWithContent properly validates keys and merges TsCodeFragment contents. Implementation appears correct.


21-23: Simple fragment check

isTsCodeFragment is straightforward and improves type safety.


25-33: Effective merge strategy for imports and hoisted fragments

mergeFragmentImportsAndHoistedFragments collects them accurately.


35-66: Clear documentation block

TsCodeUtils and its JSDoc clarifications provide good discoverability.


67-83: formatFragment handles placeholders well

Merges string content with code fragments seamlessly.


85-129: mergeFragmentsAsObject is intuitive

Combines typed content with object property syntax. Watch out for unusual keys, but otherwise great.


131-143: wrapFragment logic is straightforward

This utility properly applies a wrapper around fragment content.


145-182: template function accommodates expressions cleanly

Interleaving strings with TsCodeFragment content is well-structured.

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

🧹 Nitpick comments (2)
packages/core-generators/src/renderers/typescript/ts-code-utils.ts (2)

4-19: Robust string formatting and validations
The placeholder validation (line 8) protects against unexpected behaviors. The regex approach is safe given the [A-Z0-9_-]+ restriction. Consider documenting why lowercase placeholders are disallowed if that’s intentional.


25-33: Generous merging of imports
Collecting imports and hoisted fragments is straightforward. However, repeated imports across fragments could cause duplication. For large-scale projects, consider deduplicating for cleaner generated output.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 55cc54c and c26edfa.

📒 Files selected for processing (3)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1 hunks)
  • packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core-generators/src/renderers/typescript/imports/sort-imports/get-import-sort-group.ts
🧰 Additional context used
🧬 Code Definitions (1)
packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (1)
packages/core-generators/src/renderers/typescript/ts-code-utils.ts (1)
  • TsCodeUtils (38-183)
🔇 Additional comments (9)
packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (6)

1-6: Robust testing imports
These initial imports and setup for Vitest are straightforward. The code is laid out clearly, making it easy to expand test coverage.


7-37: Comprehensive coverage for mergeFragments
This test effectively verifies merging contents, imports, and hoisted fragments with a multi-fragment scenario. The structure captures all relevant conditions, ensuring the function behaves as intended.


38-46: Validating empty fragment arrays
Testing an empty array scenario prevents edge-case regressions and confirms the method returns the correct defaults.


48-58: Excellent comment-formatting test
The formatAsComment function is well-covered for single and multi-line strings, ensuring it appends the correct prefix to every line.


60-84: Smart testing of placeholder substitution
These tests verify both valid argument substitution and invalid placeholder naming. The clear error messaging ensures developers are alerted to incorrect usage.


86-164: Thorough testing of object merging features
The tests cover wrapping with parentheses, handling undefined fields, property shorthand, and function declarations (sync/async). This comprehensive suite ensures the behavior of mergeFragmentsAsObject remains stable under a variety of usage patterns.

packages/core-generators/src/renderers/typescript/ts-code-utils.ts (3)

1-2: Clear type imports
Importing the necessary types at the top maintains clarity and aligns with TypeScript best practices for strongly typed modules.


21-23: Simple, effective type guard
The isTsCodeFragment function concisely ensures the object shape is valid. This helps prevent runtime errors when merging or formatting fragments.


35-183: Excellent all-in-one utility object
Each method in TsCodeUtils is well-documented and covers key scenarios (merging fragments, formatting comments, wrapping fragments, etc.). This structure provides a strong foundation for TypeScript code generation.

@kingston kingston merged commit e1517d0 into main Mar 31, 2025
6 checks passed
@kingston kingston deleted the kingston/eng-536-improve-typescript-generation-so-that-templates-can-be-typed branch March 31, 2025 08:23
@github-actions github-actions bot mentioned this pull request Mar 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants