Skip to content

Write esbuild metafile to output dir #2087

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

Merged
merged 3 commits into from
May 21, 2025
Merged

Write esbuild metafile to output dir #2087

merged 3 commits into from
May 21, 2025

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented May 21, 2025

The build output incl. the metafile can be inspected with: npx trigger.dev@v4-beta --dry-run

It can then be used on https://esbuild.github.io/analyze/ to visually inspect the bundle. Any large bundles >2MB are a concern and should be investigated.

Tips for dealing with large bundles:

  • Identify and remove any imports that aren't used by your tasks
  • Large chunks of data should only be loaded on demand, not in the root at your task files
  • If there are multiple tasks in the same file, try to use a separate file for each instead
  • To avoid importing other task bundles you can should only the type of any child tasks, for example:
// simpleTask.ts
import { task, logger } from "@trigger.dev/sdk";

export const simpleTask = task({
  id: "simple-task",
  run: async (payload: any, { ctx }) => {
    logger.log("Hello, world from simple task", { payload });
  },
});
// parentTask.ts
import { task, logger, tasks } from "@trigger.dev/sdk";
import type { simpleTask } from "./simpleTask.js";
//     👆 note the type import

export const parentTask = task({
  id: "parent",
  run: async (payload: any, { ctx }) => {
    logger.log("Hello, world from parent task", { payload });

    //   👇 this should still be nicely typed
    const result = await tasks.triggerAndWait<typeof simpleTask>("simple-task", {
      message: "Hello, world!", //                                👆 needs to match the task's id
    });

    logger.log("Result", { result });
  },
});

Copy link

changeset-bot bot commented May 21, 2025

🦋 Changeset detected

Latest commit: 2f162b2

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

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
Contributor

coderabbitai bot commented May 21, 2025

Walkthrough

The changes introduce the output of an esbuild metafile during the build process. The BundleResult type is extended to include a metafile property, and the esbuild build result's metafile is now included in the bundle result. The writeDeployFiles function is refactored to accept a single object parameter containing the build manifest, resolved config, output path, and bundle result, and it now writes the metafile.json file to the output directory. Additionally, the BackgroundWorker class no longer writes the build manifest JSON file during initialization. A new changeset documents these updates. No other public API changes were made.

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between a9a937d and 4c44047.

📒 Files selected for processing (4)
  • .changeset/weak-parents-sip.md (1 hunks)
  • packages/cli-v3/src/build/buildWorker.ts (3 hunks)
  • packages/cli-v3/src/build/bundle.ts (2 hunks)
  • packages/cli-v3/src/dev/backgroundWorker.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • packages/cli-v3/src/dev/backgroundWorker.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/cli-v3/src/build/buildWorker.ts (2)
packages/core/src/v3/schemas/schemas.ts (1)
  • ResolvedConfig (257-260)
packages/cli-v3/src/build/bundle.ts (1)
  • BundleResult (42-54)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/cli-v3/src/build/bundle.ts (2)

46-46: Great addition of the metafile property to BundleResult type

Adding the esbuild metafile to the BundleResult type enables downstream analysis of bundle size and dependencies, which aligns perfectly with the PR objective.


301-301: Well implemented metafile propagation

The metafile is now correctly included in the returned bundle result, enabling it to be used by the writeDeployFiles function downstream.

packages/cli-v3/src/build/buildWorker.ts (3)

89-94: Good refactoring of writeDeployFiles function call

The change from passing multiple arguments to a structured object improves code readability and maintainability. This is a good practice when functions require multiple parameters.


148-158: Clean function signature update

The updated function signature properly accommodates the new bundleResult parameter, maintaining consistency with the function call. The use of a destructured object parameter makes the function more maintainable if additional parameters are needed in the future.


190-190:

❓ Verification inconclusive

Key implementation of metafile output

This line implements the core functionality described in the PR objective - writing the esbuild metafile to the output directory, enabling users to analyze their bundle sizes.

Let's verify that the metafile structure is preserved correctly:


🏁 Script executed:

#!/bin/bash
# Check if the metafile contains the expected structure
cat << EOF > /tmp/check_metafile.js
const fs = require('fs');
const path = require('path');

// Find a metafile.json in the repo to analyze its structure
const findMetafile = () => {
  const files = fs.readdirSync('.');
  for (const file of files) {
    const stat = fs.statSync(file);
    if (stat.isDirectory() && file !== 'node_modules') {
      try {
        const metafilePath = path.join(file, 'metafile.json');
        if (fs.existsSync(metafilePath)) {
          return metafilePath;
        }
      } catch (e) {}
    }
  }
  return null;
}

const metafilePath = findMetafile();
if (!metafilePath) {
  console.log('No metafile.json found for analysis');
  process.exit(0);
}

const metafile = JSON.parse(fs.readFileSync(metafilePath, 'utf8'));

// Check if metafile has the expected structure
if (!metafile.inputs || !metafile.outputs) {
  console.error('Metafile missing expected inputs/outputs structure');
  process.exit(1);
}

console.log('Metafile has the expected structure');

// Get some basic stats about the bundle
const outputFiles = Object.keys(metafile.outputs).length;
const inputFiles = Object.keys(metafile.inputs).length;
console.log(\`Bundle contains \${outputFiles} output files and \${inputFiles} input files\`);
EOF

node /tmp/check_metafile.js

Length of output: 71


Approve core metafile output

This line correctly writes the esbuild metafile.json to outputPath, which is the primary goal of this PR—exposing bundle metadata for size analysis.

To verify the generated metafile:

  • Run your build (e.g. npx @your-org/cli-v3 build --outdir=<outputPath>).

  • Ensure <outputPath>/metafile.json exists.

  • Confirm it contains the expected top‐level keys:

    jq 'keys' <outputPath>/metafile.json
    # Expected output includes ["inputs","outputs", …]

No code changes needed here—just a manual post‐build check.

.changeset/weak-parents-sip.md (1)

1-5: Clear and concise changeset documentation

The changeset properly documents this as a patch version change and clearly explains the new capability to output and inspect the esbuild metafile.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@nicktrn nicktrn merged commit d89f740 into main May 21, 2025
12 checks passed
@nicktrn nicktrn deleted the feat/output-metafile branch May 21, 2025 15:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants