UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

665 lines (662 loc) • 23.8 kB
import { configureVXRNCompilerPlugin } from "@vxrn/compiler"; import { resolvePath } from "@vxrn/resolve"; import { getPlatformEnvDefine } from "@vxrn/vite-plugin-metro"; import events from "node:events"; import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { exactRegex } from "rolldown/filter"; import { normalizePath } from "vite"; import { autoDepOptimizePlugin, backgroundComputationPlugin, getOptionsFilled, loadEnv, nearestPackageJson, workletImportsPlugin } from "vxrn"; import vxrnVitePlugin from "vxrn/vite-plugin"; import { CACHE_KEY } from "../constants.mjs"; import { getViteMetroPluginOptions } from "../metro-config/getViteMetroPluginOptions.mjs"; import { setServerGlobals } from "../server/setServerGlobals.mjs"; import { getRouterRootFromOneOptions } from "../utils/getRouterRootFromOneOptions.mjs"; import { createRouteIndex } from "../utils/routeIndex.mjs"; import { absorbedPackageAliases } from "../utils/absorbedPackages.mjs"; import { ensureTSConfig } from "./ensureTsConfig.mjs"; import { setOneOptions } from "./loadConfig.mjs"; import { resolveNativeBundler } from "./nativeBundler.mjs"; import { bundledDevPlugin } from "./plugins/bundledDevPlugin.mjs"; import { clientTreeShakePlugin } from "./plugins/clientTreeShakePlugin.mjs"; import { createDevtoolsPlugin } from "./plugins/devtoolsPlugin.mjs"; import { createFileSystemRouterPlugin } from "./plugins/fileSystemRouterPlugin.mjs"; import { fixDependenciesPlugin } from "./plugins/fixDependenciesPlugin.mjs"; import { generateFileSystemRouteTypesPlugin } from "./plugins/generateFileSystemRouteTypesPlugin.mjs"; import { criticalCSSPlugin } from "./plugins/criticalCSSPlugin.mjs"; import { imageDataPlugin } from "./plugins/imageDataPlugin.mjs"; import { createRouteModuleHmrPlugin } from "./plugins/routeModuleHmrPlugin.mjs"; import { sourceInspectorPlugin } from "./plugins/sourceInspectorPlugin.mjs"; import { swiftPackagePlugin } from "./plugins/swiftPackagePlugin.mjs"; import { kotlinSourcePlugin } from "./plugins/kotlinSourcePlugin.mjs"; import { SSRCSSPlugin } from "./plugins/SSRCSSPlugin.mjs"; import { virtualEntryId } from "./plugins/virtualEntryConstants.mjs"; import { createVirtualEntry } from "./plugins/virtualEntryPlugin.mjs"; import { environmentGuardPlugin } from "./plugins/environmentGuardPlugin.mjs"; import { shouldEnableWorkerdDev } from "./cloudflareWranglerConfig.mjs"; const RN_DEEP_IMPORT_RE = /^react-native\/Libraries\/|react-native-web(-lite)?\/.*\/Libraries\//; events.setMaxListeners(1e3); globalThis.__vxrnEnableNativeEnv = true; function one(options = {}) { setServerGlobals(); const routerRoot = getRouterRootFromOneOptions(options); const nativeDisabled = options.native === false; const nativeOptions = options.native === false ? void 0 : options.native; const nativeAppName = nativeOptions?.app?.name || nativeOptions?.key; const nativeApp = nativeOptions?.app; const nativeAppVersion = nativeApp?.version; if (nativeDisabled) { globalThis.__vxrnEnableNativeEnv = false; } const metroOptions = (() => { if (nativeDisabled) return null; if (resolveNativeBundler({ bundler: nativeOptions?.bundler }) !== "metro") { const dropped = nativeOptions?.bundlerOptions; if (dropped?.babelConfig || dropped?.babelConfigOverrides) { console.warn(`[one] native.bundlerOptions configures babel plugins, but native.bundler is "${nativeOptions?.bundler}", which runs no babel. Those plugins will not run and whatever they were rewriting will reach the bundle untransformed.`); } return null; } if (process.env.ONE_METRO_MODE) { console.info("ONE_METRO_MODE environment variable is set, enabling Metro mode"); } const routerRoot2 = getRouterRootFromOneOptions(options); const defaultMetroOptions = getViteMetroPluginOptions({ projectRoot: nativeOptions?.bundlerOptions?.argv?.projectRoot || process.cwd(), relativeRouterRoot: routerRoot2, ignoredRouteFiles: options.router?.ignoredRouteFiles, linking: options.router?.linking, userDefaultConfigOverrides: nativeOptions?.bundlerOptions?.defaultConfigOverrides, setupFile: options.setupFile }); const userMetroOptions = nativeOptions?.bundlerOptions; const babelConfig = { ...defaultMetroOptions?.babelConfig, ...userMetroOptions?.babelConfig }; return { ...defaultMetroOptions, ...userMetroOptions, defaultConfigOverrides: defaultMetroOptions?.defaultConfigOverrides, argv: { ...defaultMetroOptions?.argv, ...userMetroOptions?.argv }, babelConfig: { ...babelConfig, plugins: [...babelConfig.plugins || [], ...options.react?.compiler === true || options.react?.compiler === "native" ? ["babel-plugin-react-compiler"] : []] }, mainModuleName: "one/metro-entry", startup: process.env.ONE_METRO_LAZY ? "lazy" : userMetroOptions?.startup }; })(); const vxrnPlugins = []; if (!process.env.IS_VXRN_CLI) { console.warn("Experimental: running VxRN as a Vite plugin. This is not yet stable."); vxrnPlugins.push(vxrnVitePlugin({ metro: metroOptions, disableNative: nativeDisabled })); } else { if (!globalThis.__oneOptions) { setOneOptions(options); globalThis["__vxrnPluginConfig__"] = options; globalThis["__vxrnMetroOptions__"] = metroOptions; return []; } } if (options.config?.ensureTSConfig !== false) { void ensureTSConfig(); } const vxrnOptions = getOptionsFilled(); const root = vxrnOptions?.root || process.cwd(); const compiler = options.react?.compiler; if (compiler) { configureVXRNCompilerPlugin({ enableCompiler: typeof compiler === "object" || typeof compiler === "function" ? compiler : compiler === "native" ? ["ios", "android"] : compiler === "web" ? ["ssr", "client"] : true }); } const autoDepsOptions = options.ssr?.autoDepsOptimization; const dedupeSymlinks = options.ssr?.dedupeSymlinkedModules ?? false; let ssrDedup_optimizedPackages = null; let ssrDedup_projectRoot = ""; const ssrSymlinkDedupPlugin = { name: "one:ssr-symlink-dedup", enforce: "pre", configResolved(config) { if (!dedupeSymlinks) return; ssrDedup_projectRoot = config.root || process.cwd(); const ssrInclude = config.ssr?.optimizeDeps?.include; if (!ssrInclude?.length) return; ssrDedup_optimizedPackages = /* @__PURE__ */ new Set(); for (const entry of ssrInclude) { if (entry.startsWith("@")) { const parts = entry.split("/"); ssrDedup_optimizedPackages.add(`${parts[0]}/${parts[1]}`); } else { ssrDedup_optimizedPackages.add(entry.split("/")[0]); } } }, async resolveId(source, importer, options2) { if (!dedupeSymlinks) return; if (source[0] === "." || source[0] === "/") return; let pkgName; let subpath = null; if (source.startsWith("@")) { const parts = source.split("/"); pkgName = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : source; if (parts.length > 2) subpath = `./${parts.slice(2).join("/")}`; } else { const parts = source.split("/"); pkgName = parts[0]; if (parts.length > 1) subpath = `./${parts.slice(1).join("/")}`; } const resolved = await this.resolve(source, importer, { ...options2, skipSelf: true }); if (!resolved?.id) return; if (resolved.id.includes("/node_modules/")) return; const path2 = await import("node:path"); const fs = await import("node:fs"); const { join, dirname } = path2; const { realpathSync, existsSync: existsSync2, readFileSync: readFileSync2 } = fs; let dir = ssrDedup_projectRoot; while (dir !== dirname(dir)) { const nmPkgDir = join(dir, "node_modules", pkgName); if (existsSync2(nmPkgDir)) { if (subpath) { try { const pkg = JSON.parse(readFileSync2(join(nmPkgDir, "package.json"), "utf8")); const exportEntry = pkg.exports?.[subpath]; if (exportEntry && typeof exportEntry === "object") { const target = exportEntry.import || exportEntry.module || exportEntry.default; if (target) { const fullPath = join(nmPkgDir, target); if (existsSync2(fullPath)) return { id: normalizePath(fullPath), external: resolved.external }; } } } catch {} } const realPkgDir = normalizePath(realpathSync(nmPkgDir)); if (resolved.id.startsWith(realPkgDir)) { const relativePart = resolved.id.slice(realPkgDir.length); return { id: normalizePath(nmPkgDir) + relativePart, external: resolved.external }; } break; } dir = dirname(dir); } } }; const withAbsorbedAliases = (alias) => { const root2 = process.cwd(); return { ...alias, native: { ...absorbedPackageAliases(root2, "native"), ...alias?.native } }; }; const createAliasPlugin = (alias, nativePlatform) => { const resolveMap = (map) => { if (!map) return null; const out = {}; for (const [key, value] of Object.entries(map)) { try { out[key] = path.isAbsolute(value) ? value : resolvePath(value); } catch { out[key] = value; } } return out; }; const resolved = { web: resolveMap(alias.web), native: resolveMap(alias.native), client: resolveMap(alias.client), ssr: resolveMap(alias.ssr), ios: resolveMap(alias.ios), android: resolveMap(alias.android) }; const aliasKeys = [...new Set(Object.values(resolved).flatMap((m) => m ? Object.keys(m) : []))]; const aliasFilter = aliasKeys.length ? new RegExp(`^(?:${aliasKeys.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`) : /(?!)/; return { name: "one:alias", enforce: "pre", config: nativePlatform ? void 0 : () => ({ resolve: { alias: Object.entries(absorbedPackageAliases(process.cwd(), "web")).map(([name, replacement]) => ({ find: new RegExp(`^${name}$`), replacement })) } }), resolveId: { filter: { id: aliasFilter }, handler(source) { const env = nativePlatform ?? this.environment?.name; const specific = env ? resolved[env] : null; if (specific && source in specific) { const id = specific[source]; return { id, external: false, packageJsonPath: nearestPackageJson(id) }; } const isWeb = !env || env === "client" || env === "ssr"; const general = isWeb ? resolved.web : resolved.native; if (general && source in general) { const id = general[source]; return { id, external: false, packageJsonPath: nearestPackageJson(id) }; } } } }; }; const devAndProdPlugins = [ { name: "one:config", __get: options }, { name: "one:env-prefix", config(userConfig) { if (userConfig.envPrefix) return; return { envPrefix: [ "VITE_", "ONE_PUBLIC_", "EXPO_PUBLIC_" ] }; } }, bundledDevPlugin(!!options.web?.experimentalBundledDev), environmentGuardPlugin(options.environmentGuards), criticalCSSPlugin(), imageDataPlugin(), { name: "one-define-client-env", async config(userConfig, env) { const clientEnvDefine = options.skipEnv ? {} : (await loadEnv(vxrnOptions?.mode ?? userConfig?.mode ?? env?.mode ?? "development", process.cwd(), userConfig?.envPrefix)).clientEnvDefine; return { define: { ...clientEnvDefine, ...process.env.ONE_DEBUG_ROUTER && { "process.env.ONE_DEBUG_ROUTER": JSON.stringify(process.env.ONE_DEBUG_ROUTER) } } }; } }, ...autoDepsOptions === false ? [] : [autoDepOptimizePlugin({ onScannedDeps({ hasReanimated, hasNativewind }) { configureVXRNCompilerPlugin({ enableReanimated: hasReanimated, enableNativeCSS: nativeOptions?.css ?? hasNativewind, enableNativewind: hasNativewind }); }, root, include: /node_modules/, ...autoDepsOptions === true ? {} : autoDepsOptions })], ...options.config?.tsConfigPaths === false ? [] : [(() => { let mappings = []; function loadMappings(resolvedRoot) { try { const configPath = path.resolve(resolvedRoot, "tsconfig.json"); if (!existsSync(configPath)) return; const raw = readFileSync(configPath, "utf-8"); const stripped = raw.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m); const config = JSON.parse(stripped); const paths = config?.compilerOptions?.paths; const baseUrl = config?.compilerOptions?.baseUrl || "."; if (!paths) return; for (const [pattern, targets] of Object.entries(paths)) { const target = targets[0]; if (!target) continue; if (pattern.endsWith("/*")) { const resolved = path.resolve(resolvedRoot, baseUrl, target.slice(0, -1)); mappings.push({ prefix: pattern.slice(0, -1), replacement: resolved.endsWith("/") ? resolved : resolved + "/", wildcard: true }); } else { mappings.push({ prefix: pattern, replacement: path.resolve(resolvedRoot, baseUrl, target), wildcard: false }); } } } catch {} } loadMappings(root); const tsconfigPathsFilter = mappings.length ? new RegExp(mappings.map((m) => `^${m.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}${m.wildcard ? "" : "$"}`).join("|")) : /^[^./]/; return { name: "one:tsconfig-paths", enforce: "pre", config() { return { resolve: { tsconfigPaths: true } }; }, configResolved(config) { if (mappings.length === 0) { loadMappings(config.root); } }, resolveId: { filter: { id: tsconfigPathsFilter }, handler(source) { const resolved = (id) => ({ id, packageJsonPath: nearestPackageJson(id) }); const jsExts = [ ".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs", ".cjs", ".cts" ]; for (const m of mappings) { let candidate; if (m.wildcard) { if (source.startsWith(m.prefix)) { candidate = m.replacement + source.slice(m.prefix.length); } } else if (source === m.prefix) { candidate = m.replacement; } if (!candidate) continue; if (jsExts.includes(path.extname(candidate))) return resolved(candidate); for (const e of jsExts) { if (existsSync(candidate + e)) return resolved(candidate + e); } for (const e of jsExts) { if (existsSync(candidate + "/index" + e)) return resolved(candidate + "/index" + e); } return resolved(candidate); } } } }; })()], createAliasPlugin(withAbsorbedAliases(options.alias)), { name: "one:redirect-rn-deep-imports", enforce: "pre", resolveId: { filter: { id: RN_DEEP_IMPORT_RE }, handler(source) { if (this.environment?.name === "client" || this.environment?.name === "ssr" || this.environment?.name === "worker") { return "\0rn-empty-module"; } } }, load: { filter: { id: exactRegex("\0rn-empty-module") }, handler() { return "export default {}; export {};"; } } }, { name: "one-aliases", enforce: "pre", config() { let tslibLitePath = ""; try { tslibLitePath = resolvePath("@vxrn/tslib-lite", process.cwd()); } catch (err) { console.info(`Can't find tslib-lite, falling back to tslib`); if (process.env.DEBUG) { console.error(err); } } return { resolve: { alias: { ...tslibLitePath && { tslib: tslibLitePath } } } }; } }, { name: "one:init-config", config() { const setupFileDefines = (() => { if (!options.setupFile) return {}; let setupFiles; if (typeof options.setupFile === "string") { setupFiles = { client: options.setupFile, server: options.setupFile, ios: options.setupFile, android: options.setupFile }; } else if ("native" in options.setupFile) { setupFiles = { client: options.setupFile.client, server: options.setupFile.server, ios: options.setupFile.native, android: options.setupFile.native }; } else { setupFiles = options.setupFile; } return { ...setupFiles.client && { "process.env.ONE_SETUP_FILE_CLIENT": JSON.stringify(setupFiles.client) }, ...setupFiles.server && { "process.env.ONE_SETUP_FILE_SERVER": JSON.stringify(setupFiles.server) }, ...setupFiles.ios && { "process.env.ONE_SETUP_FILE_IOS": JSON.stringify(setupFiles.ios) }, ...setupFiles.android && { "process.env.ONE_SETUP_FILE_ANDROID": JSON.stringify(setupFiles.android) } }; })(); const serverURL = process.env.ONE_SERVER_URL || vxrnOptions?.server.url; return { define: { ...getPlatformEnvDefine("client"), ...setupFileDefines, ...options.web?.defaultRenderMode && { "process.env.ONE_DEFAULT_RENDER_MODE": JSON.stringify(options.web.defaultRenderMode), "import.meta.env.ONE_DEFAULT_RENDER_MODE": JSON.stringify(options.web.defaultRenderMode) }, ...process.env.NODE_ENV !== "production" && serverURL && { "process.env.ONE_SERVER_URL": JSON.stringify(serverURL), "import.meta.env.ONE_SERVER_URL": JSON.stringify(serverURL) }, ...options.web?.linkPrefetch && { "process.env.ONE_LINK_PREFETCH": JSON.stringify(options.web.linkPrefetch) }, ...options.web?.skewProtection !== void 0 && { "process.env.ONE_SKEW_PROTECTION": JSON.stringify(options.web.skewProtection === true ? "true" : options.web.skewProtection === false ? "false" : options.web.skewProtection) }, ...options.web?.suspendRoutes !== void 0 && { "process.env.ONE_SUSPEND_ROUTES": JSON.stringify(options.web.suspendRoutes ? "1" : "0") } }, environments: { ssr: { define: getPlatformEnvDefine("ssr") }, ios: { define: { ...getPlatformEnvDefine("ios"), ...nativeOptions?.suspendRoutes !== void 0 && { "process.env.ONE_SUSPEND_ROUTES_NATIVE": JSON.stringify(nativeOptions.suspendRoutes ? "1" : "0") } } }, android: { define: { ...getPlatformEnvDefine("android"), ...nativeOptions?.suspendRoutes !== void 0 && { "process.env.ONE_SUSPEND_ROUTES_NATIVE": JSON.stringify(nativeOptions.suspendRoutes ? "1" : "0") } } } }, ssr: { noExternal: ["server-only", "client-only"] } }; } }, { name: "one:tamagui", config() { return { define: { "process.env.TAMAGUI_REACT_19": "\"1\"" }, environments: { ssr: { define: { "process.env.TAMAGUI_IS_SERVER": "\"1\"", "process.env.TAMAGUI_KEEP_THEMES": "\"1\"" } }, ios: { define: { "process.env.TAMAGUI_KEEP_THEMES": "\"1\"" } }, android: { define: { "process.env.TAMAGUI_KEEP_THEMES": "\"1\"" } } } }; } }, createRouteModuleHmrPlugin(routerRoot), { name: "one:optimize-dev-deps", config(_, env) { if (env.mode === "development") { return { optimizeDeps: { include: ["react/jsx-dev-runtime", "react/compiler-runtime"] } }; } } }, { name: "one:remove-server-from-client", enforce: "pre", transform: { filter: { id: /one-server-only/, code: "import { AsyncLocalStorage } from \"node:async_hooks\"" }, handler(code) { if (this.environment.name !== "client") return; return code.replace(`import { AsyncLocalStorage } from "node:async_hooks"`, `class AsyncLocalStorage {}`); } } }, { name: "one:ssr-dedupe-prebundle", config(config) { if (!dedupeSymlinks) return; const dedupeList = config.resolve?.dedupe; if (!Array.isArray(dedupeList) || dedupeList.length === 0) return; return { ssr: { optimizeDeps: { include: [...dedupeList] }, noExternal: [...dedupeList] } }; } }, ...dedupeSymlinks ? [ssrSymlinkDedupPlugin] : [] ]; const nativeWebDevAndProdPlugsin = [clientTreeShakePlugin({ routerRoot })]; let nativeFormPlugins = []; const nativeFormPluginsCapture = { name: "one:native-form-plugins", configResolved(config) { nativeFormPlugins = config.plugins.filter((plugin) => plugin.api?.vxrnNative); } }; if (!nativeDisabled) { const viteBundlerOptions = nativeOptions?.bundler === "metro" ? void 0 : nativeOptions?.bundlerOptions; globalThis.__vxrnAddNativePlugins = (platform) => { const listed = [ backgroundComputationPlugin("native"), workletImportsPlugin({}), ...nativeApp ? [{ name: "one:externalize-expo-for-native-app", resolveId(source) { if (/^(?:expo(?:-[^/]+)?|@expo\/[^/]+)(?:\/|$)/.test(source)) { return { id: source, external: true }; } } }] : [], createAliasPlugin(withAbsorbedAliases(options.alias), platform), clientTreeShakePlugin({ runtime: "rolldown", routerRoot }), ...viteBundlerOptions?.plugins ?? [] ]; const listedNames = new Set(listed.map((plugin) => plugin.name)); return [ ...listed, ...nativeFormPlugins.filter((plugin) => !listedNames.has(plugin.name)), swiftPackagePlugin(platform, root), kotlinSourcePlugin(platform, root) ]; }; globalThis.__vxrnNativeUserDefine = { ...viteBundlerOptions?.define, ...nativeAppName && { "process.env.ONE_APP_NAME": JSON.stringify(nativeAppName), "import.meta.env.ONE_APP_NAME": JSON.stringify(nativeAppName) } }; } globalThis.__vxrnAddWebPluginsProd = devAndProdPlugins; const flags = {}; const routeIndex = createRouteIndex({ routerRoot: path.resolve(root, routerRoot), ignoredRouteFiles: options.router?.ignoredRouteFiles }); if (!nativeDisabled) { globalThis.__vxrnNativeEntryConfig = { routerRoot, ignoredRouteFiles: options.router?.ignoredRouteFiles, linking: options.router?.linking, setupFile: options.setupFile, flags, app: nativeApp }; } const inspectorPlugins = (() => { const devtools = options.devtools ?? true; const inspector = devtools === true || devtools !== false && (devtools.inspector ?? true); const editor = devtools !== true && devtools !== false ? devtools.editor : void 0; return inspector ? sourceInspectorPlugin({ editor }) : []; })(); const workerdDevPlugins = shouldEnableWorkerdDev(options.web?.deploy, root) ? import("./plugins/workerdDevPlugin.mjs").then(({ createWorkerdDevPlugins }) => createWorkerdDevPlugins(options, root, routeIndex)) : []; return [ backgroundComputationPlugin("web"), { name: "one:background-worker-build", config(config) { const plugins = config.worker?.plugins; return { worker: { plugins: () => [...plugins?.() ?? [], backgroundComputationPlugin("web")] } }; } }, workerdDevPlugins, ...vxrnPlugins, ...devAndProdPlugins, ...inspectorPlugins, ...nativeWebDevAndProdPlugsin, ...nativeDisabled ? [] : [nativeFormPluginsCapture], createFileSystemRouterPlugin(options, routeIndex), generateFileSystemRouteTypesPlugin(options, routeIndex), fixDependenciesPlugin(options.patches), createVirtualEntry({ ...options, flags, root: routerRoot, routeIndex }), { name: "one-define-environment", config() { return { define: { ...nativeAppName && { "process.env.ONE_APP_NAME": JSON.stringify(nativeAppName), "import.meta.env.ONE_APP_NAME": JSON.stringify(nativeAppName) }, ...nativeAppVersion && { "process.env.ONE_APP_VERSION": JSON.stringify(nativeAppVersion), "import.meta.env.ONE_APP_VERSION": JSON.stringify(nativeAppVersion) }, "process.env.ONE_CACHE_KEY": JSON.stringify(CACHE_KEY), "import.meta.env.ONE_CACHE_KEY": JSON.stringify(CACHE_KEY) } }; } }, SSRCSSPlugin({ entries: [virtualEntryId] }), ...(() => { const devtools = options.devtools ?? true; const includeUI = devtools !== false; return [createDevtoolsPlugin({ includeUI })]; })() ]; } export { one }; //# sourceMappingURL=one.mjs.map