Skip to content

feat: add Plug'n'Play (PnP) support - #20

Closed
rtritto wants to merge 7 commits into
nitedani:mainfrom
rtritto:support-pnp
Closed

rtritto wants to merge 7 commits into
nitedani:mainfrom
rtritto:support-pnp

Conversation

@rtritto

@rtritto rtritto commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Fix #6

Description

This PR introduces support for Yarn Plug'n'Play (PnP) by leveraging Node's native createRequire API to allow PnP to properly hook into the module resolution process.

Motivation

Previously, standaloner relied heavily on static file-system resolution algorithms (like those built into @vercel/nft). This approach fundamentally breaks in PnP environments where a physical node_modules directory is absent. To fix this, we need to delegate dependency resolution to Node's native module system (require.resolve), which Yarn automatically patches at runtime to load dependencies directly from the .yarn/cache.

Changes

  • src/trace.ts:
    • Removed the early exit/guard that blocked execution when the pnpapi module was detected.
    • Updated the custom resolve hook for nodeFileTrace. If the default @vercel/nft resolver fails to find the file (which is expected in PnP), it now falls back to a context-aware createRequire(parentFile).resolve(id). This triggers Yarn's patched resolver to correctly locate the file.
  • src/relocate.ts:
    • Updated the safeRequireResolve utility to dynamically accept an importer file path context.
    • Passed the importer/sourceId through the AST walker (processRequireCall) and the resolveId bundler hook so that dependencies are resolved accurately relative to their importing file.

Testing

  • Re-built the project to ensure no TypeScript compilation errors.
  • Verified that dependencies correctly resolve and bundle using the new context-aware createRequire logic.

@nitedani

Copy link
Copy Markdown
Owner

Thank you for opening this PR, supporting PnP would be really nice!
Is PnP support really so simple? Are there any edge-cases or limitations that should be noted here?

@rtritto
rtritto marked this pull request as ready for review April 28, 2026 17:34
Copilot AI review requested due to automatic review settings April 28, 2026 17:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds Yarn Plug’n’Play (PnP) support by switching dependency resolution to Node’s module resolver (via createRequire) when static filesystem resolution fails.

Changes:

  • Removed the Yarn PnP “unsupported, skip trace” guard so tracing runs under PnP.
  • Added a PnP-friendly fallback in nodeFileTrace resolution using createRequire(parent).resolve.
  • Made asset relocation resolution context-aware by threading the importer/source id into safeRequireResolve and processRequireCall.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
standaloner/src/trace.ts Removes the PnP early-exit and adds createRequire-based fallback resolution for tracing.
standaloner/src/relocate.ts Makes require/resolve context-aware by using createRequire(importer) and passing sourceId through require-call processing.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 25 to +27
try {
return toPosixPath(require.resolve(request, options));
const req = importer ? createRequire(importer) : require;
return toPosixPath(req.resolve(request));

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

safeRequireResolve calls createRequire(importer) directly. In Vite/Rollup, importer can be decorated with a leading \0 and/or ?query/#hash suffix (e.g. commonjs interop ids); createRequire will throw for \0-prefixed paths, causing the fallback resolve to silently fail. Consider normalizing/sanitizing importer before passing it to createRequire (strip leading \0, remove [?#].*$), similar to the cleanup done in utils/build-externals.ts around the cleanId handling.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  • Investigating fallback logic

    I'm currently reviewing src/trace.ts to see if the fallback resolution logic I implemented there, similar to the one in createRequire(parent), needs adjustment. I'll be focusing on the parent variable within that file's context.

  • Verifying resolve paths

    My current focus is on src/relocate.ts. I've determined that @vercel/nft's internal tracing mechanism handles only direct file paths, not the pseudo-paths like \0 or hashes found in Vite chunks. Therefore, adjustments to src/trace.ts seem unnecessary for now, and the safeRequireResolve bug report specifically relates to createRequire(importer) within relocate.ts. I will proceed with testing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

commit: 2d60234

Comment on lines +582 to 585
const resolved = safeRequireResolve(modulePath, sourceId);
const potentialPath = resolved || path.resolve(dirName, modulePath);
const ext = path.extname(potentialPath).toLowerCase();
if (['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', ''].includes(ext)) return null;

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

processRequireCall now resolves the specifier with safeRequireResolve(modulePath, sourceId), but the returned resolved path is only used to compute ext and is then discarded; the reference still stores path: modulePath, so later path.resolve(dirName, filePath) will fail for non-relative specifiers (e.g. require("pkg/subpath/binding.node")) even though safeRequireResolve found the real file. Use the resolved path (when available) for the emitted FileReference so the relocator can actually read/emit the asset.

Copilot uses AI. Check for mistakes.

@rtritto rtritto Apr 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  • Investigating Relocation Logic

    I'm currently examining the processRequireCall function within relocate.ts, specifically focusing on how safeRequireResolve is being utilized for module resolution. My aim is to pinpoint any potential issues with the current implementation concerning modulePath and sourceId.

  • Refining Module Resolution

    I'm refining the module resolution within processRequireCall. My focus is on ensuring that the actual resolved path, not just the original specifier, is correctly used for FileReference generation to prevent downstream resolution failures.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

commit: 12166f1

Co-authored-by: Copilot <copilot@github.com>
@rtritto

rtritto commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Is PnP support really so simple?

@nitedani Yes, the require.resolve and the loader file .pnp.loader.mjs do all the works.

Are there any edge-cases or limitations that should be noted here?

IDK, probably not, it's all.

Copilot reviews and adds 2 suggestions, I will check them.

PS:

  • next time you merge a PR, I reccomend you to use squash and merge instead of merge: by this way you'll only have 1 commit in the history (better readability and less issues on pull/rebase)
  • before the new release, we can also update rolldown to v1.0.0-rc.17

@rtritto rtritto changed the title feat: add Yarn Plug'n'Play (PnP) support feat: add Plug'n'Play (PnP) support Apr 28, 2026
rtritto and others added 2 commits April 28, 2026 20:25
Co-authored-by: Copilot <copilot@github.com>
Co-authored-by: Copilot <copilot@github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread test/vite/test/pnp/index.js Resolved
Comment thread test/pnp/test.js Resolved
Comment thread test/pnp/test.js
throw new Error(`Build output file dist/index.js or dist/index.mjs not found!`);
}

const output = execSync(`node ${distEntry}`, { stdio: 'pipe', cwd: tmpDir }).toString();

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

execSync(node ${distEntry}) will break if distEntry contains spaces/shell-special characters (common under temp directories on some systems). Prefer execFileSync('node', [distEntry], ...) or ensure the path is safely quoted/escaped.

Copilot uses AI. Check for mistakes.
Comment thread standaloner/src/trace.ts
Comment on lines +171 to +174
try {
const parentFile = parent ? path.resolve(baseDir, parent) : path.join(baseDir, 'index.js');
const req = createRequire(parentFile);
return toPosixPath(req.resolve(id));

Copilot AI Apr 28, 2026

Copy link

Choose a reason for hiding this comment

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

In PnP environments nftDefaultResolve is expected to fail frequently, so this fallback becomes the hot path. Creating a new createRequire(parentFile) instance on every miss can add noticeable overhead; consider caching the require object per parentFile (or caching resolve(id,parent) results) to keep trace time reasonable on large projects.

Copilot uses AI. Check for mistakes.
rtritto and others added 2 commits April 28, 2026 20:48
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@rtritto

rtritto commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

@nitedani-agent

Copy link
Copy Markdown
Contributor

ClaudeCodex Claude Opus 5.5 (high effort) wrote this; GPT-6.1-Sol (Codex, high effort) reviewed it.

I've continued this in #27, which supersedes this PR. @rtritto, your seven commits are in it unchanged, rebased on main, with you as their author. Thank you for getting this started!

Are there any edge-cases or limitations that should be noted here?

With Yarn's default global cache, the package zips sit outside the project, and standaloner's dependency tracer ignores files outside the project. So this PR's fallback copied nothing, not even lodash. A package with only an import entry in exports wasn't found either, and a package that ships both builds got its CommonJS file into an ESM app. Platform binaries like @esbuild/linux-x64 were never copied. #27 fixes all of these, and with nodeLinker: node-modules a large app copies the same 3562 files on main and on #27. Workspace and portal: packages left external are copied too. Two limits are left. The build has to run through Yarn (yarn node build.js or yarn <script>), so that the PnP runtime is loaded. And a link: folder without its own package.json has no package name to copy it under, so the app fails to start if it's left external.

Both open Copilot points are settled too. The test now runs the output with execFileSync. The createRequire per miss is gone, and the PnP lookup that replaces it took 13 ms over 739 misses on that app, so I didn't cache it.

@nitedani

nitedani commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Done in #27, based on your commits.

@nitedani nitedani closed this Oct 30, 2026
@rtritto
rtritto deleted the support-pnp branch November 1, 2026 12: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.

Support PnP in trace

4 participants