Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prefer browser recognized mime type over file extension lookup #991

Merged
merged 10 commits into from
Oct 7, 2024

Conversation

juliusmarminge
Copy link
Collaborator

@juliusmarminge juliusmarminge commented Sep 30, 2024

Prefer file.type when matching route config type. Fallback to lookup based on extension

File { name: 'foo.png', type: 'image/png' } => image/png
File { name: 'foo', type: 'image/png' } => image/png
File { name: 'foo.jpg', type: 'image/png' } => image/png
File { name: 'foo.jpg', type: '' } => image/jpg

x-ref: https://discord.com/channels/966627436387266600/1102510616326967306/1289998476721262623

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a function to consolidate default configuration values for file types, enhancing reusability.
    • Improved file type resolution accuracy by incorporating MIME type checks.
    • Added a maximum file count of 10 for blob file uploads.
    • Enhanced upload progress tracking with clearer status updates.
  • Bug Fixes

    • Enhanced validation for file size and count against route configurations, ensuring more accurate error reporting for uploads.
    • Refined error handling for upload actions, providing clearer feedback on mismatches.
    • Improved handling of file types in various upload scenarios, ensuring robust MIME type identification.

Copy link

changeset-bot bot commented Sep 30, 2024

🦋 Changeset detected

Latest commit: 662ab99

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

This PR includes changesets to release 8 packages
Name Type
@uploadthing/shared Patch
uploadthing Patch
@uploadthing/expo Patch
@uploadthing/react Patch
@uploadthing/solid Patch
@uploadthing/svelte Patch
@uploadthing/vue Patch
@uploadthing/nuxt Patch

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

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

Copy link

vercel bot commented Sep 30, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-uploadthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 8:57pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Oct 7, 2024 8:57pm

Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Warning

Rate limit exceeded

@juliusmarminge has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 23 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between 77c86b2 and 662ab99.

Walkthrough

The changes introduce a new function, getDefaultRouteConfigValues, which centralizes default configuration values for file types. The fillInputRouteConfig function is updated to use this new function, reducing redundancy. Additionally, the getTypeFromFileName function is enhanced to accept an optional fallbackType parameter. The assertFilesMeetConfig function is modified to improve file type and size validation, enhancing accuracy in type resolution and error handling.

Changes

Files Change Summary
packages/shared/src/utils.ts Added getDefaultRouteConfigValues(type: FileRouterInputKey) method. Updated getTypeFromFileName to accept an optional fallbackType parameter.
packages/uploadthing/src/internal/... Modified assertFilesMeetConfig to include file.type in getTypeFromFileName calls. Enhanced file size validation logic and error handling for mismatches.
examples/minimal-appdir/src/server/... Added maxFileCount: 10 to the blob configuration in uploadRouter.
packages/uploadthing/src/client.ts Updated isValidFileType and isValidFileSize functions to include file.type in their signatures. Refined upload handling logic in genUploader.
packages/uploadthing/src/internal/... Updated handleUploadAction to include file.type in getTypeFromFileName calls. Enhanced error handling and logging throughout the upload process.

Possibly related PRs

  • fix: skip content type for non-body methods #954: The changes in this PR involve updating the getTypeFromFileName function to include a file.type parameter, which directly relates to the modifications made in the main PR where the getTypeFromFileName function was updated to accept an optional fallbackType parameter.
  • fix: Fix withUt in monorepos #987: This PR modifies the withUt function to improve module resolution, which indirectly relates to the overall functionality of file handling and routing, similar to the changes made in the main PR regarding file type configurations.
  • docs: Fixed SolidStart and slightly changed Tanstack/Start #988: The documentation updates in this PR include renaming the OurFileRouter type to UploadRouter, which aligns with the changes in the main PR that focus on enhancing the structure and maintainability of file handling functions.

Suggested labels

📚 documentation, @uploadthing/react

Suggested reviewers

  • markflorkowski

Poem

In the code where rabbits hop,
New functions bloom, and changes crop.
Default values, neat and bright,
Help our files take flight!
With types and sizes all in line,
Happy coding, oh how fine! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Sep 30, 2024

📦 Bundle size comparison

Bundle Size (gzip) Visualization
Main 26.03KB See Treemap 📊
PR (01d6ce0) 26.03KB See Treemap 📊
Diff No change

Copy link

pkg-pr-new bot commented Sep 30, 2024

Open in Stackblitz

More templates

pnpm add https://pkg.pr.new/pingdotgg/uploadthing/@uploadthing/nuxt@991
pnpm add https://pkg.pr.new/pingdotgg/uploadthing/@uploadthing/shared@991
pnpm add https://pkg.pr.new/pingdotgg/uploadthing@991

commit: 662ab99

@juliusmarminge juliusmarminge changed the title use file.type as fallback type to getTypeFromFileName fix: use file.type as fallback type to getTypeFromFileName Sep 30, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
packages/shared/src/utils.ts (1)

41-48: LGTM! Consider adding explicit return type.

The new getDefaultRouteConfigValues function is a great addition. It consolidates default configuration values, improving maintainability and reducing redundancy in the codebase.

Consider adding an explicit return type to improve readability:

export function getDefaultRouteConfigValues(type: FileRouterInputKey): {
  maxFileSize: FileSize;
  maxFileCount: number;
  minFileCount: number;
  contentDisposition: ContentDisposition;
} {
  // ... function body ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e48abf5 and 15d6c33.

📒 Files selected for processing (2)
  • packages/shared/src/utils.ts (4 hunks)
  • packages/uploadthing/src/internal/route-config.ts (1 hunks)
🔇 Additional comments (4)
packages/uploadthing/src/internal/route-config.ts (2)

Line range hint 32-124: Overall impact on assertFilesMeetConfig function is positive.

The addition of file.type as an argument to getTypeFromFileName enhances the function's ability to accurately determine file types. This change:

  1. Improves flexibility in type determination.
  2. Maintains the existing logic for file size and count validation.
  3. Does not introduce any new risks or potential issues.

The function's overall structure and purpose remain intact, with the added benefit of more robust file type handling.


77-77: LGTM! Verify getTypeFromFileName implementation.

The addition of file.type as an argument to getTypeFromFileName aligns with the PR objective to use it as a fallback when determining the file type. This change enhances the flexibility of type determination.

To ensure the change is fully implemented, please verify the getTypeFromFileName function:

packages/shared/src/utils.ts (2)

67-67: LGTM! Good use of the new utility function.

The changes to fillInputRouteConfig effectively utilize the new getDefaultRouteConfigValues function. This modification improves code organization while maintaining the existing functionality.

Also applies to: 78-78


Line range hint 1-368: Overall, the changes look good and align with the PR objectives.

The modifications to this file improve code organization by introducing the getDefaultRouteConfigValues function and enhance flexibility with the addition of the fallbackType parameter in getTypeFromFileName. These changes are consistent with the existing codebase and maintain backward compatibility.

packages/shared/src/utils.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
examples/minimal-appdir/src/server/uploadthing.ts (1)

35-35: LGTM! Consider adding a comment for clarity.

The addition of maxFileCount: 10 for blob files is a good improvement. It aligns with the PR objectives and is consistent with the configuration style of other file types.

For consistency and clarity, consider adding a brief comment explaining the purpose of this limit, similar to other configurations in the file. For example:

 blob: {
   maxFileSize: "8GB",
+  // Limit the number of blob files that can be uploaded
   maxFileCount: 10,
 },
packages/uploadthing/src/client.ts (1)

Line range hint 69-74: Verify that type matches routeConfig keys in isValidFileSize

When accessing routeConfig[type], ensure that type corresponds to a valid key in routeConfig. If type is a file extension (e.g., "png") but routeConfig keys are MIME types (e.g., "image/png"), routeConfig[type] will be undefined, leading to errors.

Consider mapping the file extension to the correct MIME type before accessing routeConfig:

 Micro.runSync(
     getTypeFromFileName(file.name, objectKeys(routeConfig), file.type).pipe(
-      Micro.flatMap((type) => fileSizeToBytes(routeConfig[type]!.maxFileSize)),
+      Micro.flatMap((type) => {
+        const mimeType = extensionToMimeType(type);
+        return fileSizeToBytes(routeConfig[mimeType]!.maxFileSize);
+      }),
       Micro.map((maxFileSize) => file.size <= maxFileSize),
       Micro.orElseSucceed(() => false),
     ),
   );

Ensure you have a function extensionToMimeType that correctly maps file extensions to MIME types.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 15d6c33 and 1fd585f.

📒 Files selected for processing (3)
  • examples/minimal-appdir/src/server/uploadthing.ts (1 hunks)
  • packages/uploadthing/src/client.ts (2 hunks)
  • packages/uploadthing/src/internal/handler.ts (1 hunks)
🔇 Additional comments (1)
packages/uploadthing/src/internal/handler.ts (1)

533-533: LGTM! The use of file.type as a fallback is appropriate

The addition of file.type as a fallback parameter in getTypeFromFileName enhances the robustness of file type determination when the file name lacks an extension. This implementation aligns with the PR objective and improves functionality.

packages/uploadthing/src/client.ts Outdated Show resolved Hide resolved
packages/uploadthing/src/internal/handler.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
packages/uploadthing/test/request-handler.test.ts (2)

204-228: LGTM! Consider adding an assertion for the response status code.

This test case effectively verifies the behavior of using the file name to determine the MIME type when the browser doesn't recognize the file type. It aligns well with the PR objectives.

Consider adding an explicit assertion for the response status code before checking the response body:

 expect(res.status).toBe(200);
+expect(res.ok).toBe(true);
 await expect(res.json()).resolves.toMatchObject([
   {
     name: "foo.png",
     url: expect.stringContaining("x-ut-file-type=image"),
   },
 ]);

This addition would make the test more robust by explicitly checking both the status code and the ok property.


230-257: LGTM! Remove duplicate status assertion and consider adding an ok check.

This test case effectively verifies the fallback behavior of using the browser-recognized type when the file name doesn't have an extension. It aligns well with the PR objectives.

There's a duplicate assertion for the response status. Consider removing the first one and adding an ok check:

-    expect(res.status).toBe(200);
-
     expect(middlewareMock).toHaveBeenCalledWith(
       expect.objectContaining({
         files: [{ name: "foo", size: 48, type: "image/png" }],
       }),
     );

     expect(res.status).toBe(200);
+    expect(res.ok).toBe(true);
     await expect(res.json()).resolves.toMatchObject([
       {
         name: "foo",
         url: expect.stringContaining("x-ut-file-type=image%252Fpng"),
       },
     ]);

This change removes the redundant assertion and adds an extra check for the ok property, making the test more robust.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1fd585f and 77c86b2.

📒 Files selected for processing (2)
  • packages/uploadthing/src/internal/handler.ts (1 hunks)
  • packages/uploadthing/test/request-handler.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/uploadthing/src/internal/handler.ts
🔇 Additional comments (1)
packages/uploadthing/test/request-handler.test.ts (1)

204-257: Great addition of test cases for the new file type determination logic!

These new test cases effectively cover the scenarios described in the PR objectives:

  1. Using the file name to determine the MIME type when the browser doesn't recognize the file type.
  2. Falling back to the browser-recognized type when the file name doesn't have an extension.

The tests are well-structured and align with the existing testing patterns in the file. They provide good coverage for the new functionality and help ensure the correct behavior of the getTypeFromFileName method.

Copy link
Collaborator

@markflorkowski markflorkowski left a comment

Choose a reason for hiding this comment

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

I feel like file.type should take precedence over name when avilable?

@juliusmarminge juliusmarminge changed the title fix: use file.type as fallback type to getTypeFromFileName fix: prefer browser recognized mime type over file extension lookup Oct 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants