-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Lay foundations for new typescript renderer #472
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Lay foundations for new typescript renderer #472
Conversation
🦋 Changeset detectedLatest commit: 27de888 The changes in this PR will be included in the next version bump. This PR includes changesets to release 13 packages
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 |
WalkthroughThis 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
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
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
New and removed dependencies detected. Learn more about Socket for GitHub ↗︎
|
There was a problem hiding this 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.jsextension in the typedef import ensures explicit module resolution, which is particularly important in strict ESM environments. Please confirm that./typescript.jsexists 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.jsis 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
TypescriptCodeExpressiontype is now imported, but based on the AI summary, thegetHttpErrorExpressionmethod that used this type has been removed from theErrorHandlerServiceProviderinterface. 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
tsCodeFragmentfunction 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
contentsparameter 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.joinalready uses forward slashes.If you're certain that
path.posix.joinwill 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 replacementThe 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 instripRelativePrefixFromProjectRelativePath.
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 ingetAliasedPathFromTsPathMapEntry.
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/.mjsedge cases innormalizePathForResolutionKind.
When handling Node16 or NodeNext,.jsis enforced, yet.cjsor.mjsmay 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 innormalizeModuleSpecifier.
The function usesminByon path lengths to pick the “shortest path.” If two are equally short,minBypicks 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 forSortImportDeclarationsOptions.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 indefaultSortOptions.
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 forwriteFilepayload.
The updated doc references a singlepayloadparameter. Given that you destructure it into multiple fields (id,filePath, etc.), clarify thatpayloadis an object with these properties for better readability.
156-159: Validate new optionalgeneratorName.
IfgeneratorNameis 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 unexpectedgeneratorName.
176-176: Allow customizing or omitting the separator in the finalid.
Theidstring 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-circuitingisIndexImportchecks with additional patterns.
If your setup might include variations like./index.tsxor 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 thesortGroup = sortGroup ?? groupapproach, 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 bothTsCodeUtilsandTypescriptCodeUtils, 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 ofes-toolkitforisEqual,orderBy, anduniqWithmay 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 introducedHoistedFragmentWithPriorityand thepriorityfield 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 interfaceFlattenedImportsAndHoistedFragments(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 inmergeImportsAndHoistedFragmentsinserts 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 validDefining an optional
includeMetadatafield looks good. Consider adding tests to validate negative/invalid input.
354-413: New task for templated file writingThis task structure neatly queues file-generation actions and processes them in the
buildfunction. 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
⛔ Files ignored due to path filters (2)
packages/fastify-generators/src/generators/core/logger-service/generated/templates.tsis excluded by!**/generated/**pnpm-lock.yamlis 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 fromcreators.jsandtypes.jsprovide 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.jsis an effective way to expose the TypeScript renderer's functionality. Verify that your module resolution strategy in your TypeScript configuration handles the.jsextension 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 forfile.jsandtemplate.jscreate 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.jsonsuccessfully 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 goodThis 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 implementationGood 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 exportThe 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 exportsAdding 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 tsLength 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.tsandgenerated/templates.ts). No further changes are needed.packages/tools/prettier.config.react.js (1)
2-2: Good improvement to module importsReplacing the full module import with a named import of just the
fileURLToPathfunction 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 templatingThis 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 testsThese tests for
mapValuesOfMapfollow 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 codeThis change removes an unnecessary intermediate variable (
fullPath) and directly passesdestinationPathto theformatImportsfunction. 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
fileURLToPathinstead 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
fileURLToPathfunction 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 toolingThis 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 patternThis 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 generatePathMapEntriesThe 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 entriesThe 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 utilitiesThe addition of
tsCodeFragmentandtsImportBuilderimports aligns with the PR objective of introducing a new TypeScript renderer system.
222-229: Improved code generation with structured TypeScript utilitiesThe modification of the
addMixinimplementation now uses the new TypeScript renderer system withtsCodeFragmentandtsImportBuilderinstead 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/node20with@tsconfig/node22aligns 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
mapGroupByfunctionality:
- 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.createExpressionwith the newtsCodeFragmentandtsImportBuilderfunctions 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.groupByis particularly helpful for understanding the function's intent.
12-27: Clean and efficient implementation.The
mapGroupByimplementation is straightforward and follows best practices:
- Uses generics appropriately for type safety
- Efficiently builds the result map in a single pass
- Handles both new keys and existing keys correctly
- 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
TsNamedImportinterface 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
TsImportDeclarationinterface 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
TsPathMapEntryinterface includes extensive documentation with concrete examples showing the relationship betweentsconfig.jsonpath 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
TsHoistedFragmentPositiontype 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
TsHoistedFragmentinterface 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
TsCodeFragmentinterface 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
ErrorHandlerServiceProviderinterface has been simplified with the removal of thegetHttpErrorExpressionmethod. 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
TsImportDeclarationBuilderinterface 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
tsImportBuilderfunction 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
stripUndefinedChildrenfunction 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
mergeTsImportDeclarationsSortedfunction 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
ImportConflictErrorwhen 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/./testlooks 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. inpackages/core-generators/src/generators/node/typescript/index.tsand in the type definitions inpackages/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
tsHoistedFragmentfunction 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
directoryfor 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
.jsextensions 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
.jsextension, 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
createImportDeclarationhelper 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
getImportSortGroupfunction 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
internalPatternsoption 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
allowedSortGroupsoption 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
includeMetadataoption 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-nocheckdirective 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
createImportDeclarationhelper 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: falseis 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
generatePathMapEntriesfunction correctly transforms TypeScript path mappings into a format usable by the renderer, with appropriate error handling for unsupported multiple targets. The use ofpath.posix.joinensures consistent path separators.
29-37: Robust regex escaping utility.The
escapeRegexhelper 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
pathMapEntriesToRegexesfunction 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 variablesThe
TsCodeTemplateVariableinterface is well-defined with an optional description field, which is useful for documentation purposes.
9-15: Good use of union type for template sourceThe union type approach for
TsCodeFileTemplateSourceprovides flexibility for template sources to be either file paths or inline content.
17-28: Well-designed template interface with generic parameterThe
TsCodeFileTemplateinterface 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 variablesThe
InferTsCodeTemplateVariablesFromMaptype effectively maps template variable definitions to their concrete implementations as eitherTsCodeFragmentor string.packages/core-generators/src/renderers/typescript/ts-code-utils.unit.test.ts (9)
8-36: Comprehensive tests for mergeFragments methodThe test cases thoroughly validate the functionality of the
mergeFragmentsmethod, particularly its ability to combine code contents, imports, and hoisted fragments.
38-45: Edge case handling for mergeFragmentsGood 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 formatAsCommentThe tests effectively verify both single-line and multi-line text formatting as comments.
60-77: Comprehensive testing of formatFragmentTest cases appropriately verify the functionality for replacing placeholders with content and preserving imports.
79-83: Proper error testing for invalid placeholder namesThe 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 functionalityTest case thoroughly verifies complex object generation including property assignment, spread operators, and import collection.
112-122: Testing optional wrapping behaviorGood test coverage for the
wrapWithParenthesisoption, ensuring the correct formatting is applied.
124-133: Verification of undefined value handlingTest ensures that undefined values are correctly filtered out from the resulting object.
135-143: Property shorthand testingTest 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 propertiesThe
RenderTsTemplateOptionsinterface is well-designed with self-explanatory properties and appropriate JSDoc comments.
20-33: Function signature with proper generic constraintThe function signature is well-defined with appropriate generic constraints and typed parameters. The JSDoc clearly explains the purpose and parameters.
34-47: Strong input validationGood 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 fragmentsThe code correctly filters and extracts imports and hoisted fragments from non-string values. The return object structure matches the expected
TsCodeFragmentinterface.packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.unit.test.ts (8)
14-21: Good test setup with proper isolationThe test suite uses beforeEach to create fresh Project and SourceFile instances for each test, ensuring proper isolation.
23-58: Comprehensive testing of import declaration filteringThe tests thoroughly verify that side-effect imports are correctly filtered out from the source file.
60-198: Exhaustive test cases for import declaration conversionThe 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 writingTests verify correct formatting for default and named imports when writing to CodeBlockWriter.
246-304: Thorough verification of special import typesTests cover namespace imports and various type-only import scenarios with appropriate assertions.
306-345: Validation of aliased and mixed importsGood test coverage for aliased named imports and mixed default/named imports, ensuring correct formatting.
347-366: Testing of grouped import sectionsTest verifies that multiple import sections are correctly separated by newlines in the output.
368-386: Error handling verificationThe 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 forisInternalImport.
The function treats all relative paths (name.startsWith('.')) and paths matchingTsPathMapEntryas internal. If additional path forms (e.g., custom prefixes not starting with@or.) need to be treated as internal, ensure they're included inpathmapEntriesor accounted for elsewhere.
84-99: Confirm stability ofModuleResolutionKindstring literal type.
The template literal type referencests.server.protocol.ModuleResolutionKind. Verify that the runtime environment and library versions align with this usage to avoid unexpected compile or runtime issues if thets-morphor TS protocol changes.packages/sync/src/output/generator-task-output.ts (1)
164-164: Confirm cross-platform compatibility offilePath.replaceAll(path.sep, path.posix.sep).
This usage is valid in modern Node but ensure that all Node versions you support properly implementString.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
isBuiltinfrom'node:module'.
Although Node 22 should fully supportisBuiltin, 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 3Length of output: 1995
Verified: Node 22 fully supports the usage of
isBuiltinModulefrom'node:module'.
The shell script output confirms that the code runs under Node v22.9.0 and that the usage ofisBuiltinModulein 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 anImportConflictErrorensures immediate feedback instead of silently merging conflicting imports.packages/core-generators/src/renderers/typescript/imports/ts-morph-operations.ts (4)
5-12:isSideEffectImportapproach is concise.
This properly flags imports lacking any specifier as pure side effects.
32-46: Accurate conversion to custom import structure.
CapturingisTypeOnlyat 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 addedTsCodeFragmenthere but still importTypescriptCodeExpressionat 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
TypescriptCodeExpressionbreak the flow?
24-24: Validate template file path.
Make sure that'./generated/templates.js'is the correct relative path for theloggerFileTemplate. If the project is reorganized, this path might break.
31-31: Signature update looks good.
Switching fromTypescriptCodeExpressiontoTsCodeFragmentin theaddMixinmethod 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 intoTPL_LOGGER_OPTIONSis clear. Just ensure:
- All possible logger options are tested.
- Using
mergeFragmentsAsObjectis the intended final approach (instead oftemplate).- Overwritten or conflicting keys in
loggerOptionsare handled gracefully.Everything else looks consistent.
packages/core-generators/src/renderers/typescript/fragments/utils.ts (2)
15-45: Recursive flattening logic.
Overall,flattenImportsAndHoistedFragmentsRecursiveis well-structured. Confirm:
- Edge cases with deeply nested fragments.
- Merged imports do not accidentally duplicate.
- 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 usests-morphandnode:fs/promises. Confirm Node 22 fully supports these features and thatts-morphis stable with Node 22.
6-29: Ensure stable import and type definitions.
TheRenderTsCodeFileTemplateOptionsinterface 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, returningcontentsimmediately 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 consistentThese imports have a clear usage in the newly introduced interfaces.
25-29: No issues importing utility functionsThe newly introduced functions from
@src/renderers/typescript/index.jsalign well with the code below.
121-131: Interface design is coherentThe shape of
WriteTemplatedFilePayloadis straightforward and supports typical file generation usage.
132-137: Method signature aligns with new interfaceProvides a clear entry point for writing templated files.
138-139: Provider creation is clearImplementation follows the existing provider pattern.
176-177: Descriptor integrationPassing the
descriptorvalidated by the schema intobuildTasksis a clean approach.
13-13:Details
✅ Verification successful
Ensure
zoddependency is declaredThis import relies on
zod; confirm that your application’s dependencies include it.Run the following script to check if
zodis listed in your package configuration:
🏁 Script executed:
#!/bin/bash # Searching for 'zod' in package.json rg 'zod' package.jsonLength 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:
zodis Declared
The verification confirms thatzodis 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
formatStringWithContentproperly validates keys and mergesTsCodeFragmentcontents. Implementation appears correct.
21-23: Simple fragment check
isTsCodeFragmentis straightforward and improves type safety.
25-33: Effective merge strategy for imports and hoisted fragments
mergeFragmentImportsAndHoistedFragmentscollects them accurately.
35-66: Clear documentation block
TsCodeUtilsand its JSDoc clarifications provide good discoverability.
67-83:formatFragmenthandles placeholders wellMerges string content with code fragments seamlessly.
85-129:mergeFragmentsAsObjectis intuitiveCombines typed content with object property syntax. Watch out for unusual keys, but otherwise great.
131-143:wrapFragmentlogic is straightforwardThis utility properly applies a wrapper around fragment content.
145-182:templatefunction accommodates expressions cleanlyInterleaving strings with
TsCodeFragmentcontent is well-structured.
packages/core-generators/src/renderers/typescript/imports/builder.ts
Outdated
Show resolved
Hide resolved
...nerators/src/renderers/typescript/imports/sort-imports/sort-import-declarations.unit.test.ts
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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
📒 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 formergeFragments
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
TheformatAsCommentfunction 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 ofmergeFragmentsAsObjectremains 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
TheisTsCodeFragmentfunction 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 inTsCodeUtilsis well-documented and covers key scenarios (merging fragments, formatting comments, wrapping fragments, etc.). This structure provides a strong foundation for TypeScript code generation.
Summary by CodeRabbit
New Features
Documentation
Tests
Chores