Skip to content

fix: use static require calls in PlatformTools.load for bundler compatibility - #12729

Merged
alumni merged 5 commits into
typeorm:masterfrom
h4sht:fix/bundler-dynamic-require-static-switch
Nov 7, 2026
Merged

alumni merged 5 commits into
typeorm:masterfrom
h4sht:fix/bundler-dynamic-require-static-switch

Conversation

@h4sht

@h4sht h4sht commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Problem

PR #12647 replaced explicit require() calls in PlatformTools.load() with a dynamic require(name), which is invisible to static analyzers used by bundlers (Webpack, Vite, esbuild, etc.).

This causes errors like:

Postgres package has not been found installed. Please run "npm install pg".

...because the bundler does not know to include the database driver dependency in the bundle.

Fixes #12721

Root Cause

Before PR #12647, PlatformTools.load() used explicit require("pg"), require("mysql2") calls that bundlers could statically analyze. After the PR, it was changed to require(name) where name is a runtime variable — invisible to static analysis.

When the bundler can't see which modules are needed, it excludes them from the bundle. The runtime check if (!KNOWN_MODULES.includes(name)) validates the name but doesn't help the bundler.

Solution

Replaced the dynamic require(name) with an explicit switch/case containing static require() calls for each known module. Each case has a literal string argument to require(), which bundlers can analyze.

The catch-all fallback preserves the global-install resolution path (when typeorm is installed globally but drivers are in the project).

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (2) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Single-driver applications cannot bundle 🐞 Bug ≡ Correctness
Description
PlatformTools.load() now contains literal require() calls for every driver, so a bundler
resolving those calls must resolve packages that the application does not use. When an application
installs only pg, for example, its bundle can fail on missing optional packages such as mysql2
before the runtime switch can select pg.
Code

packages/typeorm/src/platform/PlatformTools.ts[R61-63]

+                case "mysql2":
+                    // eslint-disable-next-line @typescript-eslint/no-require-imports
+                    return require("mysql2")
Evidence
The switch contains literal imports for multiple different drivers, while the manifest explicitly
marks those drivers as optional peers. The PR's stated reason for making the imports literal is that
bundlers resolve them during analysis; selecting one case at runtime does not remove the other
resolution targets.

packages/typeorm/src/platform/PlatformTools.ts[42-94]
packages/typeorm/package.json[145-202]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Literal imports of all drivers make absent optional drivers build-time resolution targets for bundlers, even when an application uses only one driver.
## Fix Focus Areas
- packages/typeorm/src/platform/PlatformTools.ts[42-94]
- packages/typeorm/package.json[145-202]
## Recommended Fix
Use a bundler-compatible loading strategy that includes the selected driver without requiring every optional peer to be installed. Verify it by bundling an application with only one database driver installed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Explanatory comments claim bundler behaviour without support 📘 Rule violation ⚙ Maintainability
Description
BrowserPlatformTools.load wraps its switch in a try/catch that only rethrows, while a comment
incorrectly claims the wrapper helps bundlers identify optional dependencies; the same unsupported
comment appears in Node PlatformTools.ts. A later reader may retain the ineffective wrapper or
assume it handles errors, although removing it leaves the switch and trailing TypeError behavior
unchanged.
Code

packages/typeorm/src/platform/BrowserPlatformTools.template[R37-38]

+            // Use literal requires on purpose so bundlers can trace the client libraries.
+            // Wrapped in try-catch so bundlers can identify the libraries as optional dependencies.
Evidence
The browser loader’s added catch (error) { throw error } rethrows the original error without
handling or changing it, so the surrounding try adds no behavior to the switch or the following
TypeError. The adjacent comment attributes optional-dependency identification to that wrapper
without support from the code, and the same comment is repeated in the Node file.

Rule 4: Remove AI-generated noise
packages/typeorm/src/platform/BrowserPlatformTools.template[37-38]
packages/typeorm/src/platform/BrowserPlatformTools.template[55-57]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`BrowserPlatformTools.load` wraps its switch in a try/catch that only rethrows the original error, while an adjacent comment incorrectly credits the wrapper with helping bundlers identify optional dependencies. The same unsupported comment appears in `PlatformTools.ts`.
## Fix Focus Areas
- packages/typeorm/src/platform/BrowserPlatformTools.template[34-61]
- packages/typeorm/src/platform/BrowserPlatformTools.template[36-38]
- packages/typeorm/src/platform/PlatformTools.ts[42-44]
## Recommended Fix
Remove the browser loader’s `try {` and `catch (error) { throw error }` lines, preserving the `switch (name)`, trailing `throw new TypeError(...)`, and consistent handling of the existing `eslint-disable` comment. Remove the comment line about try/catch and optional dependencies from both files; retain at most a short note about literal requires being resolvable by bundlers, or remove the comments entirely if the code is self-explanatory.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Issue fix test skips functional suite 📘 Rule violation ⚙ Maintainability
Description
The regression test for issue #12721 is a unit test under packages/typeorm/test/unit/platform/,
and its describe block and comment cite the issue. The compliance rule expects issue fixes to add or
update tests in packages/typeorm/test/functional, so the driver-loading behaviour is only checked
through direct PlatformTools.load() calls rather than the paths users actually hit.
Code

packages/typeorm/test/unit/platform/platform-tools.test.ts[R26-27]

+    describe("static require calls for bundler compatibility", () => {
+        it("should include all known modules as static require cases", () => {
Evidence
The PR's only test additions for the issue are a new file under test/unit, and the describe block
at line 26 with the // issue #12721 comment at line 33 tie the test to the issue. Rule 3 expects
issue fixes to live in packages/typeorm/test/functional with an issue reference, so this placement
departs from the rule.

Rule 3: Prefer functional tests over per-issue tests
packages/typeorm/test/unit/platform/platform-tools.test.ts[26-33]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The regression test for issue #12721 was added as a unit test in `packages/typeorm/test/unit/platform/platform-tools.test.ts`. Compliance rule 3 expects issue fixes to add or update tests in `packages/typeorm/test/functional`, with an issue reference in the test comment.
## Fix Focus Areas
- packages/typeorm/test/unit/platform/platform-tools.test.ts[1-70]
## Recommended Fix
Move the bundler/driver-loading regression coverage into a functional test under `packages/typeorm/test/functional`, keeping the `// issue #12721` reference. Exercise the supported driver names through the functional test setup so the coverage runs with the rest of the driver suite. If the unit-level "Invalid Package" check is still valuable, keep it as a small unit test alongside the functional one.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Project drivers hide their load errors ✓ Resolved
Description
PlatformTools.load() catches every error from its project-local fallback and rethrows the earlier
MODULE_NOT_FOUND error instead. When TypeORM is installed globally and a driver in the project's
node_modules fails during initialization or lacks a dependency, startup reports the original
resolution failure rather than the driver's actual error.

View review recommended (3)
5. Bundler regressions pass the new test 🐞 Bug ⚙ Maintainability
Description
The new test calls PlatformTools.load() and checks only that recognized names avoid the
invalid-package error; it never checks whether a bundler can analyze the imports. Restoring the
former allowlist and dynamic require(name) would satisfy these assertions while reintroducing the
failure this PR aims to prevent.
Code

packages/typeorm/test/unit/platform/platform-tools.test.ts[R59-65]

+                try {
+                    PlatformTools.load(mod)
+                } catch (e: any) {
+                    expect(e.message).to.not.include(
+                        "Invalid Package",
+                        `Module "${mod}" is not in the static require switch`,
+                    )
Evidence
The test accepts any thrown error except one containing Invalid Package. That condition verifies
membership in the supported-name set, whereas the change's distinguishing behavior is the literal
require() calls.

packages/typeorm/test/unit/platform/platform-tools.test.ts[26-68]
packages/typeorm/src/platform/PlatformTools.ts[40-69]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new test checks module-name validation but cannot detect a return to dynamic imports or a failed bundled build.
## Fix Focus Areas
- packages/typeorm/test/unit/platform/platform-tools.test.ts[26-68]
## Recommended Fix
Add a bundling smoke test that builds and loads a supported driver from the resulting bundle, or add a structural assertion that specifically verifies literal imports rather than only accepted names.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Verbose comments in load() ⊘ Outdated
Description
PlatformTools.load() adds several explanatory comments and a block-scoped ESLint disable that
increase noise and are inconsistent with the prior eslint-disable-next-line style. This violates
the requirement to avoid AI-like/comment noise and style inconsistencies in changes.

7. Broad catch masks require errors ⊘ Outdated
Description
PlatformTools.load() catches any exception thrown by require() (not only module-resolution failures)
and unconditionally retries loading from process.cwd()/node_modules, which can hide genuine module
initialization errors and replace them with a different/misleading exception from the fallback
require().

Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Tip of the day
💡 Did you know, you can hide the parts of a finding you never read, like the evidence or the agent prompt

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@h4sht h4sht changed the title fix: use static require() calls in PlatformTools.load() for bundler compatibility (fixes #12721) fix: use static require calls in PlatformTools.load for bundler compatibility Jul 22, 2026
@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

tru3 added 3 commits October 25, 2026 18:32
…ompatibility

PR typeorm#12647 replaced explicit require() calls with dynamic require(name),
which is invisible to static analyzers used by bundlers (Webpack, Vite,
esbuild). This caused "pg package not found" errors because the bundler
did not know to include the database driver dependency.

Replaced dynamic require(name) with an explicit switch/case containing
static require() calls for each known module (pg, mysql2, mongodb, etc.).
This allows bundlers to statically analyze and include the required
dependencies while preserving the global-install fallback resolution.

Closes typeorm#12721
Verify that unknown modules are rejected with a TypeError and that all
supported driver modules are covered by the static switch/case statement.
This ensures bundlers can statically analyze the require() calls.

Closes typeorm#12721
@Cprakhar
Cprakhar force-pushed the fix/bundler-dynamic-require-static-switch branch from 2eb23ad to aa63810 Compare October 25, 2026 13:13
@Cprakhar
Cprakhar requested a review from alumni October 25, 2026 13:13
@pkg-pr-new

pkg-pr-new Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12729
    

commit: cbc7dc2

@alumni
alumni enabled auto-merge (squash) November 7, 2026 15:32
@alumni

alumni commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

/agentic_review

@alumni
alumni merged commit 5a572a4 into typeorm:master Nov 7, 2026
46 checks passed
@github-actions github-actions Bot added this to the 2.0.next milestone Nov 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

webpack bundling broken in v1.1

3 participants