Skip to content

Commit e03f7a5

Browse files
committed
fix: remove require() calls that break bundlers
1 parent c456cbd commit e03f7a5

7 files changed

Lines changed: 87 additions & 297 deletions

File tree

‎src/driver/expo/ExpoDriver.ts‎

Lines changed: 13 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,11 @@
11
import type { DataSource } from "../../data-source/DataSource"
22
import { DriverPackageNotInstalledError, TypeORMError } from "../../error"
3+
import { PlatformTools } from "../../platform/PlatformTools"
34
import type { QueryRunner } from "../../query-runner/QueryRunner"
45
import { AbstractSqliteDriver } from "../sqlite-abstract/AbstractSqliteDriver"
56
import type { ExpoDataSourceOptions } from "./ExpoDataSourceOptions"
67
import { ExpoQueryRunner } from "./ExpoQueryRunner"
78

8-
// Node raises `MODULE_NOT_FOUND` when the requested module can't be resolved,
9-
// but the same code also fires for transitive failures (a dependency of
10-
// `expo-sqlite` that's missing, a `require` inside the module body). Node's
11-
// error message has the shape:
12-
//
13-
// Cannot find module '<name>'
14-
// Require stack:
15-
// - /node_modules/<caller>/index.js
16-
// - ...
17-
//
18-
// The stack lists the calling modules and can include `expo-sqlite` when the
19-
// unresolved module is a transitive dependency — so matching the whole
20-
// message would misreport such failures as "install expo-sqlite". Only the
21-
// first line identifies the actually-missing module, so match against that.
22-
const isExpoSqliteNotFoundError = (err: unknown): boolean => {
23-
if (typeof err !== "object" || err === null) return false
24-
const e = err as { code?: string; message?: string }
25-
if (e.code !== "MODULE_NOT_FOUND") return false
26-
if (typeof e.message !== "string") return false
27-
const firstLine = e.message.split("\n", 1)[0]
28-
return firstLine.startsWith("Cannot find module 'expo-sqlite'")
29-
}
30-
319
export class ExpoDriver extends AbstractSqliteDriver {
3210
declare options: ExpoDataSourceOptions
3311

@@ -56,50 +34,23 @@ export class ExpoDriver extends AbstractSqliteDriver {
5634
}
5735

5836
/**
59-
* Loads the `expo-sqlite` module when `options.driver` is not set. Extracted
60-
* as a method so tests can stub the module resolution without depending on
61-
* whether `expo-sqlite` happens to be installed in the workspace.
62-
*
63-
* A literal `require("expo-sqlite")` is used so Metro's static bundler picks
64-
* the dependency up at build time — `PlatformTools.load()` is a throwing
65-
* stub in the browser/React-Native build and cannot be used here.
66-
*/
67-
protected requireExpoSqlite(): unknown {
68-
return require("expo-sqlite")
69-
}
70-
71-
/**
72-
* If driver dependency is not given explicitly, resolve it via
73-
* `requireExpoSqlite()` and validate that the loaded module exposes the
74-
* modern async API introduced in Expo SDK v52.
37+
* If driver dependency is not given explicitly, then try to load it via "require".
7538
*/
7639
protected loadDependencies(): void {
77-
if (this.options.driver) {
78-
this.sqlite = this.options.driver
79-
} else {
80-
try {
81-
this.sqlite = this.requireExpoSqlite()
82-
} catch (err) {
83-
if (isExpoSqliteNotFoundError(err)) {
84-
throw new DriverPackageNotInstalledError(
85-
"Expo SQLite",
86-
"expo-sqlite",
87-
)
88-
}
89-
throw err
90-
}
40+
try {
41+
this.sqlite =
42+
this.options.driver ?? PlatformTools.load("expo-sqlite")
43+
} catch {
44+
throw new DriverPackageNotInstalledError(
45+
"Expo SQLite",
46+
"expo-sqlite",
47+
)
9148
}
9249

93-
// Expo SDK v52 removed the legacy synchronous API. The modern async API
94-
// exposes `openDatabaseAsync` as a function — anything else (missing,
95-
// non-callable, non-object `driver`) means the user is on a pre-v52 SDK
96-
// or has passed something that isn't the expo-sqlite module.
97-
if (typeof this.sqlite?.openDatabaseAsync !== "function") {
98-
const hint = this.options.driver
99-
? "check that the provided `driver` exposes `openDatabaseAsync` — custom overrides must match the expo-sqlite v52+ surface"
100-
: "upgrade to Expo SDK v52 or later, which ships the modern async SQLite API"
50+
// The modern Expo SQLite API that TypeORM supports exposes `openDatabaseAsync` as a function
51+
if (typeof this.sqlite.openDatabaseAsync !== "function") {
10152
throw new TypeORMError(
102-
`Legacy Expo SQLite driver is not supported — ${hint}.`,
53+
`The provided Expo SQLite client is not supported. Please upgrade your Expo SDK to v52 or higher!`,
10354
)
10455
}
10556
}

‎src/driver/react-native/ReactNativeDriver.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { DataSource } from "../../data-source/DataSource"
33
import { DriverPackageNotInstalledError } from "../../error"
44
import type { ColumnMetadata } from "../../metadata/ColumnMetadata"
55
import type { EntityMetadata } from "../../metadata/EntityMetadata"
6+
import { PlatformTools } from "../../platform/PlatformTools"
67
import type { QueryRunner } from "../../query-runner/QueryRunner"
78
import { RdbmsSchemaBuilder } from "../../schema-builder/RdbmsSchemaBuilder"
89
import type { Table } from "../../schema-builder/table/Table"
@@ -17,9 +18,9 @@ import type { Driver } from "../Driver"
1718
import type { ColumnType } from "../types/ColumnTypes"
1819
import type { CteCapabilities } from "../types/CteCapabilities"
1920
import type { DataTypeDefaults } from "../types/DataTypeDefaults"
21+
import type { IsolationLevel } from "../types/IsolationLevel"
2022
import type { MappedColumnTypes } from "../types/MappedColumnTypes"
2123
import type { ReplicationMode } from "../types/ReplicationMode"
22-
import type { IsolationLevel } from "../types/IsolationLevel"
2324
import type { UpsertType } from "../types/UpsertType"
2425
import type { ReactNativeDataSourceOptions } from "./ReactNativeDataSourceOptions"
2526
import { ReactNativeQueryRunner } from "./ReactNativeQueryRunner"
@@ -1033,10 +1034,10 @@ export class ReactNativeDriver implements Driver {
10331034
*/
10341035
protected loadDependencies(): void {
10351036
try {
1036-
const sqlite =
1037-
this.options.driver ?? require("react-native-sqlite-storage")
1038-
this.sqlite = sqlite
1039-
} catch (e) {
1037+
this.sqlite =
1038+
this.options.driver ??
1039+
PlatformTools.load("react-native-sqlite-storage")
1040+
} catch {
10401041
throw new DriverPackageNotInstalledError(
10411042
"React-Native",
10421043
"react-native-sqlite-storage",

‎src/driver/sap/SapDriver.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,7 @@ import type { IsolationLevel } from "../types/IsolationLevel"
2727
import type { UpsertType } from "../types/UpsertType"
2828
import type { SapDataSourceOptions } from "./SapDataSourceOptions"
2929
import { SapQueryRunner } from "./SapQueryRunner"
30-
/**
31-
* Organizes communication with SAP Hana DBMS.
32-
*
33-
* todo: looks like there is no built in support for connection pooling, we need to figure out something
34-
*/
30+
3531
export class SapDriver implements Driver {
3632
// -------------------------------------------------------------------------
3733
// Static Properties

‎src/driver/spanner/SpannerDriver.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ import type { Driver } from "../Driver"
1616
import type { ColumnType } from "../types/ColumnTypes"
1717
import type { CteCapabilities } from "../types/CteCapabilities"
1818
import type { DataTypeDefaults } from "../types/DataTypeDefaults"
19+
import type { IsolationLevel } from "../types/IsolationLevel"
1920
import type { MappedColumnTypes } from "../types/MappedColumnTypes"
2021
import type { ReplicationMode } from "../types/ReplicationMode"
2122
import type { ReturningType } from "../types/ReturningType"
22-
import type { IsolationLevel } from "../types/IsolationLevel"
2323
import type { UpsertType } from "../types/UpsertType"
2424
import type { SpannerDataSourceOptions } from "./SpannerDataSourceOptions"
2525
import { SpannerQueryRunner } from "./SpannerQueryRunner"
@@ -440,7 +440,9 @@ export class SpannerDriver implements Driver {
440440
if (value === null || value === undefined) return value
441441

442442
if (columnMetadata.type === "numeric") {
443-
const lib = this.options.driver ?? PlatformTools.load("spanner")
443+
const lib =
444+
this.options.driver ??
445+
PlatformTools.load("@google-cloud/spanner")
444446
return lib.Spanner.numeric(value.toString())
445447
} else if (columnMetadata.type === "date") {
446448
return DateUtils.mixedDateToDateString(value, {
@@ -804,7 +806,9 @@ export class SpannerDriver implements Driver {
804806
*/
805807
protected loadDependencies(): void {
806808
try {
807-
const lib = this.options.driver ?? PlatformTools.load("spanner")
809+
const lib =
810+
this.options.driver ??
811+
PlatformTools.load("@google-cloud/spanner")
808812

809813
if (this.options.credentials) {
810814
this.spanner = new lib.Spanner({

‎src/platform/BrowserPlatformTools.template‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,25 @@ export class PlatformTools {
3232
* This operation only supports on node platform
3333
*/
3434
static load(name: string): any {
35-
if (this.type === "browser")
36-
throw new Error(
37-
`This option/function is not supported in the browser environment. Failed operation: require("${name}").`,
35+
const KNOWN_MODULES = [
36+
// Expo
37+
"expo-sqlite",
38+
// React Native
39+
"react-native-sqlite-storage",
40+
// sql.js
41+
"sql.js",
42+
// redis
43+
"redis",
44+
"ioredis",
45+
]
46+
47+
if (!KNOWN_MODULES.includes(name)) {
48+
throw new TypeError(
49+
`Invalid Package for PlatformTools.load: ${name}`,
3850
)
51+
}
3952

40-
return ""
53+
return require(name)
4154
}
4255

4356
/**

‎src/platform/PlatformTools.ts‎

Lines changed: 43 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -38,105 +38,57 @@ export class PlatformTools {
3838
* @returns the module
3939
*/
4040
static load(name: string): any {
41+
const KNOWN_MODULES = [
42+
// AWS Aurora Data API (PostgreSQL/MySQL)
43+
"typeorm-aurora-data-api-driver",
44+
// better-sqlite3
45+
"better-sqlite3",
46+
// Expo
47+
"expo-sqlite",
48+
// Google Cloud Spanner
49+
"@google-cloud/spanner",
50+
// Microsoft SQL Server
51+
"mssql",
52+
// MongoDB
53+
"mongodb",
54+
// MySQL / MariaDB
55+
"mysql2",
56+
// Oracle
57+
"oracledb",
58+
// PostgreSQL
59+
"pg",
60+
"pg-native",
61+
"pg-query-stream",
62+
// React Native
63+
"react-native-sqlite-storage",
64+
// SAP HANA
65+
"@sap/hana-client",
66+
"@sap/hana-client/extension/Stream",
67+
// sql.js
68+
"sql.js",
69+
// redis
70+
"redis",
71+
"ioredis",
72+
]
73+
74+
if (!KNOWN_MODULES.includes(name)) {
75+
throw new TypeError(
76+
`Invalid Package for PlatformTools.load: ${name}`,
77+
)
78+
}
79+
4180
// if name is not absolute or relative, then try to load package from the node_modules of the directory we are currently in
4281
// this is useful when we are using typeorm package globally installed and it accesses drivers
4382
// that are not installed globally
44-
4583
try {
46-
// switch case to explicit require statements for webpack compatibility.
47-
switch (name) {
48-
/**
49-
* spanner
50-
*/
51-
case "spanner":
52-
return require("@google-cloud/spanner")
53-
54-
/**
55-
* mongodb
56-
*/
57-
case "mongodb":
58-
return require("mongodb")
59-
60-
/**
61-
* hana
62-
*/
63-
case "@sap/hana-client":
64-
return require("@sap/hana-client")
65-
66-
case "@sap/hana-client/extension/Stream":
67-
return require("@sap/hana-client/extension/Stream")
68-
69-
/**
70-
* mysql
71-
*/
72-
case "mysql2":
73-
return require("mysql2")
74-
75-
/**
76-
* oracle
77-
*/
78-
case "oracledb":
79-
return require("oracledb")
80-
81-
/**
82-
* postgres
83-
*/
84-
case "pg":
85-
return require("pg")
86-
87-
case "pg-native":
88-
return require("pg-native")
89-
90-
case "pg-query-stream":
91-
return require("pg-query-stream")
92-
93-
case "typeorm-aurora-data-api-driver":
94-
return require("typeorm-aurora-data-api-driver")
95-
96-
/**
97-
* redis
98-
*/
99-
case "redis":
100-
return require("redis")
101-
102-
case "ioredis":
103-
return require("ioredis")
104-
105-
/**
106-
* better-sqlite3
107-
*/
108-
case "better-sqlite3":
109-
return require("better-sqlite3")
110-
111-
/**
112-
* sql.js
113-
*/
114-
case "sql.js":
115-
return require("sql.js")
116-
117-
/**
118-
* sqlserver
119-
*/
120-
case "mssql":
121-
return require("mssql")
122-
123-
/**
124-
* react-native-sqlite
125-
*/
126-
case "react-native-sqlite-storage":
127-
return require("react-native-sqlite-storage")
128-
}
129-
} catch (err) {
84+
// eslint-disable-next-line @typescript-eslint/no-require-imports
85+
return require(name)
86+
} catch {
87+
// eslint-disable-next-line @typescript-eslint/no-require-imports
13088
return require(
13189
path.resolve(process.cwd() + "/node_modules/" + name),
13290
)
13391
}
134-
135-
// If nothing above matched and we get here, the package was not listed within PlatformTools
136-
// and is an Invalid Package. To make it explicit that this is NOT the intended use case for
137-
// PlatformTools.load - it's not just a way to replace `require` all willy-nilly - let's throw
138-
// an error.
139-
throw new TypeError(`Invalid Package for PlatformTools.load: ${name}`)
14092
}
14193

14294
/**

0 commit comments

Comments
 (0)