Skip to content

fix: Resolve Widespread TypeScript errors in template data structures#256

Merged
piyushdotcomm merged 4 commits into
piyushdotcomm:mainfrom
Srushti-Kamble14:main
May 24, 2026
Merged

fix: Resolve Widespread TypeScript errors in template data structures#256
piyushdotcomm merged 4 commits into
piyushdotcomm:mainfrom
Srushti-Kamble14:main

Conversation

@Srushti-Kamble14
Copy link
Copy Markdown
Contributor

@Srushti-Kamble14 Srushti-Kamble14 commented May 23, 2026

  • Refactor TemplateFile, TemplateFolder, and TemplateItem types to use a unified BaseTemplateItem with an optional content property.
  • Fix Prisma InputJsonValue casting in playground actions.
  • Resolve missing properties and typing issues in EnvManager tests.
  • Fix useWebContainer hook signature in playground page.
  • Remove duplicate imports and fix WebContainer event listener typing.
  • Ensure all tests pass and tsc --noEmit reports zero errors.

Summary

What changed:
- Refactored TemplateFile, TemplateFolder, and TemplateItem types into a unified structure using a BaseTemplateItem interface with an optional
content property.
- Fixed Prisma InputJsonValue casting in modules/playground/actions/index.ts using safe unknown transitions.
- Corrected the useWebContainer hook signature in app/playground/[id]/page.tsx (removed unnecessary arguments).
- Resolved duplicate imports and event listener typing issues in WebContainerPreview.
- Added missing toast import in PackageManager.
- Updated EnvManager tests with missing required properties (folderName) and resolved DOM/Instance typing conflicts.

Why it changed:
- The previous type definitions caused widespread "Property 'content' missing" errors when accessing TemplateItem unions.
- Inconsistent hook usage and duplicate imports were blocking successful production builds and causing IDE noise.
- Test suites were failing due to outdated mock structures following recent schema changes.

Type of change

  • Bug fix
  • Refactor
  • Test or CI improvement

Related issue

Closes #245

Validation

  • npm run lint
  • npm test
  • npm run build

List any additional manual verification you performed:

  • Verified that the file explorer and AI chat can correctly read and manipulate file content without runtime type errors.
  • Confirmed the environment manager correctly parses .env files using the updated recursive search logic.

Checklist

  • I kept this PR focused on one primary change
  • I updated documentation if behavior changed
  • I did not commit secrets, local logs, or scratch files
  • I am requesting review on the correct scope

Summary by CodeRabbit

  • Bug Fixes

    • Fixed potential issue with missing file content in AI chat tool
    • Improved data integrity by normalizing template data before storage
  • Chores

    • Refactored internal validation structure for better maintainability
    • Enhanced error notification handling in package manager

Review Change Stack

- Refactor TemplateFile, TemplateFolder, and TemplateItem types to use a unified BaseTemplateItem with an optional content property.
- Fix Prisma InputJsonValue casting in playground actions.
- Resolve missing properties and typing issues in EnvManager tests.
- Fix useWebContainer hook signature in playground page.
- Remove duplicate imports and fix WebContainer event listener typing.
- Ensure all tests pass and tsc --noEmit reports zero errors.
@qodo-code-review
Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@github-actions
Copy link
Copy Markdown

👋 Thanks for opening a PR, @Srushti-Kamble14!

Your PR has entered the 🚦 PR Review Pipeline.

Standard PR detected — your PR will follow the standard review pipeline.


What happens next

Stage Reviewer Checks
Stage 1 — Automated Validation 🤖 Bot DCO · Format · AI/Slop · Duplicate
Stage 2 — Human Review 👥 Maintainer Code + Quality Review
Stage 3 — PA / Maintainer Review 🔑 Project Admin Final Merge Decision

A pipeline status comment will appear below and update automatically as your PR progresses.


While you wait

  • Sign all commits (git commit -s)
  • Link your issue (Closes #123)
  • Use a feature branch (not main)
  • Avoid unrelated changes

This comment is posted only once.

@github-actions github-actions Bot added the bug Something isn't working label May 23, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 23, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b9926440-152b-40b5-8c2d-27412d30ec81

📥 Commits

Reviewing files that changed from the base of the PR and between e0ea92d and c34c919.

📒 Files selected for processing (2)
  • app/api/upload-zip/route.ts
  • modules/playground/actions/index.ts

Walkthrough

This PR consolidates the template type model to support optional content, exports reusable chat tool input schemas, adds content normalization during persistence, updates test validation logic and fixtures, and refactors the NPM search endpoint to use a shared constant.

Changes

Template types, validation, persistence, and related wiring

Layer / File(s) Summary
Consolidated template type model with optional content
modules/playground/components/explorer-dialogs/types.ts, modules/playground/lib/path-to-json.ts, app/api/upload-zip/route.ts
BaseTemplateItem with optional content field is introduced; TemplateFile and TemplateFolder extend this base; upload route now imports types from path-to-json instead of defining them locally.
Chat tool schemas export and wiring
app/api/chat/tools.ts
New exported schemas object contains Zod input schemas for read_file, edit_file, edit_multiple_files, and delete_file; tools object refactored to reference exported schemas for inputSchema.
Tests updated to use schemas; safe read_file handling
app/api/chat.test.ts, modules/playground/components/ai-chat-panel.tsx
Chat tests import and call schemas.*.safeParse() instead of tools.*.inputSchema.safeParse(); read_file handler now verifies file.content !== undefined before returning it.
Normalize template payload before persistence
modules/playground/actions/index.ts
normalizeJson utility added to strip undefined values; SaveUpdatedCode normalizes TemplateFolder input before Prisma upsert and stores normalized content in both update and create branches.
NPM search URL and error toast
modules/playground/components/package-manager.tsx
Imports sonner toast; searchNpm now builds npm registry search URL using NPM_REGISTRY_SEARCH_URL constant instead of hardcoded endpoint.
EnvManager test fixtures and instance casts
tests/env-manager.test.tsx
emptyTemplateData enriched with folderName: "root"; multiple test cases cast instanceMock to any to satisfy component prop typing expectations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • This PR directly addresses piyushdotcomm/Editron#245 by adding the content property to the shared base type and correcting the mock test data.

Possibly related PRs

  • piyushdotcomm/Editron#218: Both PRs refactor the shared template model (TemplateFolder/TemplateItem) from modules/playground/lib/path-to-json.ts, directly affecting the transformer signature.
  • piyushdotcomm/Editron#96: Both PRs refactor Zod input schemas for edit_file/edit_multiple_files tools and update corresponding test validation behavior.
  • piyushdotcomm/Editron#241: Both PRs modify modules/playground/actions/index.ts in the SaveUpdatedCode persistence logic for how content is serialized before saving.

Suggested labels

maintenance

Suggested reviewers

  • piyushdotcomm

Poem

🐰 A template for templates, optional and kind,
Content now optional, no undefined to find,
Schemas extracted, reusable and true,
Normalization guards, what AI tools do,
With types consolidated, the path becomes clear! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: resolving TypeScript errors in template data structures through type refactoring.
Description check ✅ Passed The description covers all major changes with clear sections on what changed and why, though the Type of change checkboxes are not checked despite the description indicating a bug fix and refactor.
Linked Issues check ✅ Passed All code requirements from issue #245 are met: TemplateItem now includes optional content via BaseTemplateItem [#245], Prisma casting is fixed with safe JSON transitions [#245], EnvManager tests include folderName and proper typing [#245], duplicate imports are removed [#245], and hook signatures are corrected [#245].
Out of Scope Changes check ✅ Passed All changes are scoped to resolving TypeScript errors in template structures: type refactoring (BaseTemplateItem, TemplateFile, TemplateFolder), test updates, schema exports, and related fixes align with issue #245 objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@Srushti-Kamble14 Srushti-Kamble14 changed the title fix: resolve widespread TypeScript errors in template data structures fix: Resolve Widespread TypeScript errors in template data structures May 23, 2026
Copy link
Copy Markdown

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
modules/playground/components/package-manager.tsx (1)

87-93: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard non-OK NPM search responses before using data.objects
searchNpm reads data.objects unconditionally; on 4xx/5xx or rate-limit payloads where objects is missing, searchResults.length / searchResults.map(...) can crash rendering. Check res.ok and fall back to an empty array (also clear results on failure).

Suggested fix
       const res = await fetch(
       `${NPM_REGISTRY_SEARCH_URL}?text=${encodeURIComponent(searchQuery)}&size=10`
       );
-
-      const data = await res.json();
-      setSearchResults(data.objects);
+      if (!res.ok) {
+        throw new Error(`NPM search failed with status ${res.status}`);
+      }
+      const data: Partial<NpmSearchResult> = await res.json();
+      setSearchResults(Array.isArray(data.objects) ? data.objects : []);
     } catch (_error) {
+      setSearchResults([]);
       toast.error("Failed to search NPM registry");
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modules/playground/components/package-manager.tsx` around lines 87 - 93, The
NPM search handler currently assigns setSearchResults(data.objects)
unconditionally which will crash if the registry returns a non-OK response or a
payload without objects; update the fetch logic in the search function (where
NPM_REGISTRY_SEARCH_URL, searchQuery and setSearchResults are used) to first
check res.ok, then parse JSON and setSearchResults to data.objects || [] on
success, and on non-ok responses or exceptions ensure you call
setSearchResults([]) (and optionally log the error) so the component clears
results instead of crashing.
🧹 Nitpick comments (2)
app/api/upload-zip/route.ts (1)

14-24: ⚡ Quick win

Use the shared template types instead of redefining them locally.

This route now has another copy of TemplateFolder/TemplateFile, which can drift again. Prefer importing the canonical types to keep contracts aligned.

💡 Proposed refactor
 import { Prisma } from "`@prisma/client`";
+import type { TemplateFile, TemplateFolder } from "`@/modules/playground/lib/path-to-json`";

-interface TemplateFile {
-    filename: string;
-    fileExtension: string;
-    content: string;
-}
-
-interface TemplateFolder {
-    folderName: string;
-    items: (TemplateFile | TemplateFolder)[];
-    content?: string;
-}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/api/upload-zip/route.ts` around lines 14 - 24, Remove the local duplicate
interfaces TemplateFile and TemplateFolder from route.ts and import the
canonical types from the shared template types module instead; replace the local
declarations with an import (use the shared export name(s) TemplateFile and
TemplateFolder) and ensure any usages in functions (e.g., the upload/zip route
handlers) reference the imported types so the file compiles against the single
source-of-truth.
tests/env-manager.test.tsx (1)

42-42: ⚡ Quick win

Avoid as any for instance test prop to preserve contract checks.

At Line 42 (and similarly Lines 55, 74, 99, 126), as any removes useful compile-time protection in these tests. Prefer a minimal typed mock (e.g., using React.ComponentProps<typeof EnvManager>["instance"]) so test fixtures fail when the component contract changes.

Also applies to: 55-55, 74-74, 99-99, 126-126

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/env-manager.test.tsx` at line 42, Replace the unsafe "as any" casts
used for the instance prop in the EnvManager tests: instead of
"instance={instanceMock as any}", type the mock using the component's prop type
(e.g., React.ComponentProps<typeof EnvManager>["instance"]) and declare
instanceMock with that type so the tests retain compile-time contract checks;
update all occurrences (the instance prop usages and the instanceMock
declaration) to use this typed mock rather than as any.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/api/chat.test.ts`:
- Line 18: The tests use an `as any` cast on tools.edit_file.inputSchema and
tools.edit_multiple_files.inputSchema before calling safeParse; remove the casts
and use the real Zod-derived types instead (or rely on the schema's existing
typing) so safeParse is called with properly typed input. Replace occurrences of
`(tools.edit_file.inputSchema as any).safeParse(...)` and
`(tools.edit_multiple_files.inputSchema as any).safeParse(...)` in
app/api/chat.test.ts with either direct
`tools.edit_file.inputSchema.safeParse(...)` /
`tools.edit_multiple_files.inputSchema.safeParse(...)` or use z.infer<typeof
tools.edit_file.inputSchema> (and similarly for edit_multiple_files) to type the
test input variables.

In `@modules/playground/actions/index.ts`:
- Line 176: Replace the unsafe double-cast of `data as unknown as
Prisma.InputJsonValue` used when setting the `content` field with a JSON-safe
normalization step: implement and call a helper (e.g. `normalizeJsonForPrisma`
or `sanitizeJsonInput`) that recursively removes any `undefined` values,
converts JS `null`/empty values to explicit `Prisma.JsonNull` or `Prisma.DbNull`
where appropriate, and returns a value that conforms to `Prisma.InputJsonValue`;
then use that normalized result for the `content` assignment (and the other
occurrence) instead of the cast.

---

Outside diff comments:
In `@modules/playground/components/package-manager.tsx`:
- Around line 87-93: The NPM search handler currently assigns
setSearchResults(data.objects) unconditionally which will crash if the registry
returns a non-OK response or a payload without objects; update the fetch logic
in the search function (where NPM_REGISTRY_SEARCH_URL, searchQuery and
setSearchResults are used) to first check res.ok, then parse JSON and
setSearchResults to data.objects || [] on success, and on non-ok responses or
exceptions ensure you call setSearchResults([]) (and optionally log the error)
so the component clears results instead of crashing.

---

Nitpick comments:
In `@app/api/upload-zip/route.ts`:
- Around line 14-24: Remove the local duplicate interfaces TemplateFile and
TemplateFolder from route.ts and import the canonical types from the shared
template types module instead; replace the local declarations with an import
(use the shared export name(s) TemplateFile and TemplateFolder) and ensure any
usages in functions (e.g., the upload/zip route handlers) reference the imported
types so the file compiles against the single source-of-truth.

In `@tests/env-manager.test.tsx`:
- Line 42: Replace the unsafe "as any" casts used for the instance prop in the
EnvManager tests: instead of "instance={instanceMock as any}", type the mock
using the component's prop type (e.g., React.ComponentProps<typeof
EnvManager>["instance"]) and declare instanceMock with that type so the tests
retain compile-time contract checks; update all occurrences (the instance prop
usages and the instanceMock declaration) to use this typed mock rather than as
any.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7f991fd7-1318-46eb-8cc0-f59f0e53aced

📥 Commits

Reviewing files that changed from the base of the PR and between 19a3136 and cfbcb47.

📒 Files selected for processing (11)
  • app/api/chat.test.ts
  • app/api/upload-zip/route.ts
  • app/playground/[id]/page.tsx
  • modules/dashboard/components/template-selecting-modal.tsx
  • modules/playground/actions/index.ts
  • modules/playground/components/ai-chat-panel.tsx
  • modules/playground/components/explorer-dialogs/types.ts
  • modules/playground/components/package-manager.tsx
  • modules/playground/lib/path-to-json.ts
  • modules/webcontainers/components/webcontainer-preview.tsx
  • tests/env-manager.test.tsx
💤 Files with no reviewable changes (1)
  • modules/dashboard/components/template-selecting-modal.tsx

Comment thread app/api/chat.test.ts Outdated
Comment thread modules/playground/actions/index.ts Outdated
Comment thread app/api/upload-zip/route.ts Outdated
Comment thread modules/playground/actions/index.ts Outdated
piyushdotcomm
piyushdotcomm approved these changes May 24, 2026
Copy link
Copy Markdown
Owner

@piyushdotcomm piyushdotcomm left a comment

Choose a reason for hiding this comment

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

check the review

@Srushti-Kamble14
Copy link
Copy Markdown
Contributor Author

Hi @piyushdotcomm ,

Requested changes fixed:

  • Replaced locally redeclared TemplateFile and TemplateFolder interfaces in app/api/upload-zip/route.ts with shared imports from @/modules/playground/lib/path-to-json, keeping template structure types centralized in one source of truth.

  • Updated normalizeJson in modules/playground/actions/index.ts to return T instead of any, preserving type safety for callers while still normalizing data for Prisma JSON storage.

  • Removed an unused Prisma import from app/api/upload-zip/route.ts.

Copy link
Copy Markdown
Owner

@piyushdotcomm piyushdotcomm left a comment

Choose a reason for hiding this comment

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

lgtm

@piyushdotcomm piyushdotcomm merged commit 7b5640e into piyushdotcomm:main May 24, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: TemplateItem 'content' property missing and TemplateFolder casting errors

2 participants