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

New Components - customjs #14086

Merged
merged 2 commits into from
Sep 26, 2024
Merged

New Components - customjs #14086

merged 2 commits into from
Sep 26, 2024

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented Sep 25, 2024

Resolves #14033

Summary by CodeRabbit

  • New Features

    • Introduced a utility function for normalizing file paths.
    • Added functionality to convert HTML to PDF.
    • Implemented a feature to create screenshots from specified URLs.
    • Enabled merging of multiple PDF documents into a single file.
    • Enhanced the app with new methods for file handling and processing.
  • Bug Fixes

    • Updated the app's structure to ensure proper request handling and file management.
  • Documentation

    • Version updated to 0.1.0 with new dependencies specified.

Copy link

vercel bot commented Sep 25, 2024

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

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Sep 25, 2024 9:15pm
pipedream-docs ⬜️ Ignored (Inspect) Sep 25, 2024 9:15pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Sep 25, 2024 9:15pm

Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The pull request introduces several new functionalities within the customjs component, including actions for converting HTML to PDF, creating website screenshots, and merging multiple PDFs. A utility function for normalizing file paths is also added. Additionally, the customjs app is updated with new methods and a property for handling file downloads, while the package.json file reflects a version increment and new dependencies.

Changes

File(s) Change Summary
components/customjs/actions/common/utils.mjs Added normalizeFilepath(filename, ext = "pdf") utility function for file path normalization.
components/customjs/actions/convert-html-to-pdf/convert-html-to-pdf.mjs Introduced action customjs-convert-html-to-pdf for converting HTML strings to PDFs.
components/customjs/actions/create-screenshot/create-screenshot.mjs Added action customjs-create-screenshot for taking screenshots of specified websites.
components/customjs/actions/merge-pdfs/merge-pdfs.mjs Implemented action customjs-merge-pdfs for merging multiple PDF documents.
components/customjs/customjs.app.mjs Updated app with new methods for handling PDF conversion, screenshot creation, and merging.
components/customjs/package.json Incremented version from 0.0.1 to 0.1.0 and added dependency on @pipedream/platform.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CustomJS
    participant FileSystem

    User->>CustomJS: Request convertHtmlToPdf
    CustomJS->>FileSystem: Normalize file path
    CustomJS->>FileSystem: Write PDF to path
    FileSystem-->>CustomJS: Confirm write
    CustomJS-->>User: Return PDF filename and path
Loading
sequenceDiagram
    participant User
    participant CustomJS
    participant FileSystem

    User->>CustomJS: Request createScreenshot
    CustomJS->>FileSystem: Normalize file path
    CustomJS->>FileSystem: Write screenshot to path
    FileSystem-->>CustomJS: Confirm write
    CustomJS-->>User: Return screenshot filename and path
Loading
sequenceDiagram
    participant User
    participant CustomJS
    participant FileSystem

    User->>CustomJS: Request mergePdfs
    CustomJS->>FileSystem: Normalize file path
    CustomJS->>FileSystem: Write merged PDF to path
    FileSystem-->>CustomJS: Confirm write
    CustomJS-->>User: Return merged PDF filename and path
Loading

Assessment against linked issues

Objective Addressed Explanation
Convert an HTML string to a PDF document. (#14033)
Create a screenshot of a website. (#14033)
Merge multiple PDF documents into one. (#14033)

Suggested labels

ai-assisted

Suggested reviewers

  • lcaresia

Poem

In the land of code, so bright and bold,
New actions emerge, their stories told.
From HTML to PDF, a magical flight,
Screenshots captured, oh what a sight!
Merging PDFs, a seamless dance,
Hooray for changes, let’s take a chance! 🐇✨


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

@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: 8

🧹 Outside diff range and nitpick comments (5)
components/customjs/actions/common/utils.mjs (2)

1-9: Good implementation, but consider adding input validation and sanitization.

The normalizeFilepath function effectively standardizes filepaths, which is great for consistency. However, to improve robustness and security, consider the following enhancements:

  1. Add input validation to ensure filename is a non-empty string.
  2. Implement filename sanitization to prevent potential security issues with user-provided input.

Here's a suggested implementation with these improvements:

import path from 'path';

const normalizeFilepath = (filename, ext = "pdf") => {
  if (typeof filename !== 'string' || filename.trim() === '') {
    throw new Error('Invalid filename: must be a non-empty string');
  }

  // Sanitize filename (remove any path traversal attempts)
  const sanitizedFilename = path.basename(filename);

  let filepath = sanitizedFilename.startsWith("/tmp")
    ? sanitizedFilename
    : `/tmp/${sanitizedFilename}`;

  // Remove any existing extension before adding the new one
  filepath = path.join(path.dirname(filepath), path.basename(filepath, path.extname(filepath)));

  return `${filepath}.${ext}`;
};

This implementation:

  • Validates the input
  • Sanitizes the filename using path.basename()
  • Handles cases where the filename might already have a different extension

Note: This implementation assumes the path module is available. If it's not, you'll need to import it at the top of the file.


1-13: Overall assessment: Good addition with room for improvement

The normalizeFilepath function is a valuable addition that aligns well with the PR objectives, particularly for handling file paths in PDF-related operations. It provides a consistent way to normalize file paths, which is crucial for the "Convert HTML to PDF" and "Merge PDFs" actions mentioned in the PR objectives.

While the current implementation is functional, implementing the suggested improvements (input validation, sanitization, and handling of existing extensions) would significantly enhance its robustness and security.

Consider also adding unit tests for this function to ensure it handles various edge cases correctly.

components/customjs/actions/create-screenshot/create-screenshot.mjs (1)

5-24: LGTM: Action definition is well-structured and aligns with objectives.

The action definition is comprehensive and includes all necessary properties. Good job on including a link to the documentation in the description.

Consider enhancing the description to provide more context about the action's functionality. For example:

- description: "Create a screenshot of a website. [See the documentation](https://www.customjs.space/api/docs#_3-create-screenshot)",
+ description: "Create a PNG screenshot of a specified website URL using the CustomJS API. [See the documentation](https://www.customjs.space/api/docs#_3-create-screenshot)",
components/customjs/customjs.app.mjs (1)

14-30: LGTM: _makeRequest method is well-implemented. Consider adding error handling.

The _makeRequest method is correctly implemented, using axios for HTTP requests and properly handling request options. The API key is securely used in the URL construction.

Consider adding error handling and a request timeout for improved robustness:

 _makeRequest(opts = {}) {
   const {
     $ = this,
     headers,
+    timeout = 30000, // 30 seconds timeout
     ...otherOpts
   } = opts;
-  return axios($, {
+  return axios($, {
+    ...otherOpts,
+    method: "POST",
+    url: `https://e.customjs.io/__js1-${this.$auth.api_key}`,
+    headers: {
+      ...headers,
+      "Content-Type": "application/json",
+    },
+    responseType: "arraybuffer",
+    timeout,
+  }).catch(error => {
+    console.error('Request failed:', error);
+    throw error;
+  });
 }
components/customjs/actions/merge-pdfs/merge-pdfs.mjs (1)

40-40: Specify buffer encoding for consistency.

When creating a buffer from fileContent, it's best to specify the encoding explicitly for clarity and consistency.

Update the line as follows:

fs.writeFileSync(filepath, Buffer.from(fileContent, 'binary'));

This ensures that the buffer is created with the correct encoding, matching the 'binary' data returned by the CustomJS API.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2dc725e and da2b62f.

🔇 Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • components/customjs/actions/common/utils.mjs (1 hunks)
  • components/customjs/actions/convert-html-to-pdf/convert-html-to-pdf.mjs (1 hunks)
  • components/customjs/actions/create-screenshot/create-screenshot.mjs (1 hunks)
  • components/customjs/actions/merge-pdfs/merge-pdfs.mjs (1 hunks)
  • components/customjs/customjs.app.mjs (1 hunks)
  • components/customjs/package.json (2 hunks)
🔇 Additional comments not posted (16)
components/customjs/actions/common/utils.mjs (1)

11-13: Export looks good.

The normalizeFilepath function is correctly exported, making it available for use in other modules.

components/customjs/package.json (4)

3-3: Version update looks good.

The increment from 0.0.1 to 0.1.0 appropriately reflects the addition of new features to the component.


14-14: JSON structure correction is appropriate.

The addition of the closing brace properly completes the publishConfig object, ensuring valid JSON structure.


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

The version update, JSON structure correction, and dependency addition are all appropriate for setting up the new CustomJS component. These changes provide a solid foundation for implementing the new features mentioned in the PR objectives (convert HTML to PDF, create screenshot, merge PDFs).

Just ensure that the @pipedream/platform dependency is actually used in the component code as suggested in the previous comment.


15-18: Dependency addition looks appropriate, but usage verification needed.

The addition of @pipedream/platform as a dependency is likely necessary for the new CustomJS component. However, please ensure that this dependency is actually used in the component code.

To verify the usage of @pipedream/platform, run the following script:

components/customjs/actions/convert-html-to-pdf/convert-html-to-pdf.mjs (2)

1-3: LGTM: Imports are appropriate for the task.

The imports cover all necessary dependencies for the HTML to PDF conversion action:

  • customjs for the conversion library
  • fs for file system operations
  • normalizeFilepath utility for file path handling

5-10: LGTM: Action configuration is well-defined.

The action configuration includes all necessary fields:

  • Unique key: "customjs-convert-html-to-pdf"
  • Descriptive name and description
  • Version set to "0.0.1" for a new component
  • Correct action type

The inclusion of a documentation link in the description is particularly helpful for users.

components/customjs/actions/create-screenshot/create-screenshot.mjs (1)

1-3: LGTM: Imports are appropriate and well-structured.

The imports cover all necessary dependencies for the action's functionality:

  1. CustomJS app for API interaction
  2. File system module for writing the screenshot
  3. Utility function for filepath normalization
components/customjs/customjs.app.mjs (5)

1-5: LGTM: Import and app definition are correct.

The import statement and app definition are properly structured and align with the expected format for a Pipedream app.


6-12: LGTM: Property definition for 'filename' is well-structured.

The 'filename' property is correctly defined with appropriate type, label, and description. This aligns with the PR objectives, allowing users to specify a filename for downloading files to the /tmp directory.


31-53: LGTM: convertHtmlToPdf, createScreenshot, and mergePdfs methods are correctly implemented.

These methods align with the PR objectives for new CustomJS components. Each method:

  1. Correctly uses the _makeRequest method.
  2. Sets the appropriate 'customjs-origin' header.
  3. Allows flexible parameter passing using the spread operator.

The implementation is clean and consistent across all three methods.


Line range hint 54-57: LGTM: Proper closure of methods and app object.

The methods object and app export are correctly closed, maintaining the proper structure of the module.


Line range hint 1-57: Overall, the CustomJS app implementation looks great!

The changes in this file successfully implement the new components for CustomJS as outlined in the PR objectives. The code is well-structured, and the new methods (convertHtmlToPdf, createScreenshot, and mergePdfs) align perfectly with the requirements.

A minor suggestion for improvement has been made regarding error handling in the _makeRequest method, but this is not critical for the functionality.

Great job on implementing these new features!

components/customjs/actions/merge-pdfs/merge-pdfs.mjs (3)

1-3: LGTM: Imports are appropriate and well-structured.

The imports cover all necessary dependencies for the module's functionality, including the custom app, file system operations, and utility functions.


5-12: LGTM: Action configuration is well-structured and informative.

The action is properly configured with a clear key, name, description (including documentation link), version, and type. The filename prop is correctly defined using the customjs app's prop definition.

Also applies to: 18-24


25-47: LGTM: Overall implementation meets the PR objectives.

The run method successfully implements the PDF merging functionality as outlined in the PR objectives. It correctly handles the input, processes the PDFs using the CustomJS API, and saves the result to a file.

Copy link
Collaborator

@GTFalcao GTFalcao left a comment

Choose a reason for hiding this comment

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

LGTM!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Components] customjs
2 participants