Open History to see the last commit
1import { isAbsolute, resolve } from 'node:path'
2import { pathToFileURL } from 'node:url'
3import type { ExpoSQLiteTestDatabaseFactory } from './expo-sqlite-test-db'
4
5const FACTORY_MODULE_ENV_VAR = `TANSTACK_DB_MOBILE_SQLITE_FACTORY_MODULE`
6const FACTORY_EXPORT_ENV_VAR = `TANSTACK_DB_MOBILE_SQLITE_FACTORY_EXPORT`
7const REQUIRE_FACTORY_ENV_VAR = `TANSTACK_DB_MOBILE_REQUIRE_RUNTIME_FACTORY`
8const DEFAULT_FACTORY_EXPORT_NAME = `createMobileSQLiteTestDatabaseFactory`
9
10type MobileSQLiteFactoryExport =
11 | ExpoSQLiteTestDatabaseFactory
12 | (() => ExpoSQLiteTestDatabaseFactory)
13 | (() => Promise<ExpoSQLiteTestDatabaseFactory>)
14
15function toImportSpecifier(rawSpecifier: string): string {
16 if (rawSpecifier.startsWith(`.`) || isAbsolute(rawSpecifier)) {
17 const absolutePath = isAbsolute(rawSpecifier)
18 ? rawSpecifier
19 : resolve(process.cwd(), rawSpecifier)
20 return pathToFileURL(absolutePath).href
21 }
22
23 return rawSpecifier
24}
25
26async function resolveFactoryFromExport(
27 exportedFactory: unknown,
28): Promise<ExpoSQLiteTestDatabaseFactory | null> {
29 if (typeof exportedFactory !== `function`) {
30 return null
31 }
32
33 const candidate = exportedFactory as MobileSQLiteFactoryExport
34 if (candidate.length === 0) {
35 const resolvedFactory = await (
36 candidate as
37 | (() => ExpoSQLiteTestDatabaseFactory)
38 | (() => Promise<ExpoSQLiteTestDatabaseFactory>)
39 )()
40 if (typeof resolvedFactory === `function`) {
41 return resolvedFactory
42 }
43 }
44
45 return candidate as ExpoSQLiteTestDatabaseFactory
46}
47
48globalThis.__tanstackDbCreateMobileSQLiteTestDatabase = undefined
49
50const runtimeFactoryModule = process.env[FACTORY_MODULE_ENV_VAR]?.trim()
51const requireRuntimeFactory =
52 process.env[REQUIRE_FACTORY_ENV_VAR]?.trim() === `1`
53
54if (requireRuntimeFactory && !runtimeFactoryModule) {
55 throw new Error(
56 `Missing ${FACTORY_MODULE_ENV_VAR}. ` +
57 `Set it to a module exporting a runtime mobile SQLite test database factory ` +
58 `when ${REQUIRE_FACTORY_ENV_VAR}=1.`,
59 )
60}
61
62if (runtimeFactoryModule) {
63 const runtimeModule = (await import(
64 toImportSpecifier(runtimeFactoryModule)
65 )) as Record<string, unknown>
66 const factoryExportName =
67 process.env[FACTORY_EXPORT_ENV_VAR]?.trim() || DEFAULT_FACTORY_EXPORT_NAME
68 const selectedExport =
69 runtimeModule[factoryExportName] ?? runtimeModule.default
70 const resolvedFactory = await resolveFactoryFromExport(selectedExport)
71
72 if (!resolvedFactory) {
73 throw new Error(
74 `Unable to resolve a mobile SQLite test database factory from "${runtimeFactoryModule}". ` +
75 `Expected export "${factoryExportName}" (or default export) to be a database factory ` +
76 `or a zero-argument function that returns one.`,
77 )
78 }
79
80 globalThis.__tanstackDbCreateMobileSQLiteTestDatabase = resolvedFactory
81}