@tamagui/vite-plugin 2.7.7 → 3.0.0-beta.643.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,435 +1,1075 @@
1
- import * as Static from "@tamagui/static-worker";
2
- import { getPragmaOptions } from "@tamagui/static-worker";
1
+ import Static from "@tamagui/static";
3
2
  import { createHash } from "node:crypto";
4
- import { readdirSync } from "node:fs";
3
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { gzipSync } from "node:zlib";
5
+ import { readFile } from "node:fs/promises";
5
6
  import { createRequire } from "node:module";
6
7
  import path from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
- import { loadTamaguiBuildConfig, getLoadPromise, getTamaguiOptions, ensureFullConfigLoaded } from "./loadTamagui.mjs";
9
- const _pluginRequire = createRequire(typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url));
10
- const resolve = name => _pluginRequire.resolve(name);
11
- const normalizePath = value => value.replace(/\\/g, "/");
12
- const CACHE_KEY = "__tamagui_vite_cache__";
13
- const CACHE_SIZE_KEY = "__tamagui_vite_cache_size__";
14
- const PENDING_KEY = "__tamagui_vite_pending__";
15
- function getSharedCache() {
16
- if (!globalThis[CACHE_KEY]) {
17
- ;
18
- globalThis[CACHE_KEY] = {};
19
- }
20
- return globalThis[CACHE_KEY];
9
+ import { createIdResolver, createRunnableDevEnvironment, defaultClientConditions, defaultClientMainFields, isRunnableDevEnvironment, resolveConfig } from "vite";
10
+ import { TAMAGUI_EVALUATION_ENVIRONMENT, createViteTamaguiLoader } from "./loadTamagui.mjs";
11
+ import { createCompilerStatsReport, formatCompilerStatsReport } from "./compilerStats.mjs";
12
+ import { ZERO_CSS_FILENAME, ZERO_ISLAND_DIRNAME, assertZeroGraph, buildIsland, createZeroRuntimeController, finalizeZeroCSS, zeroModuleKey } from "./zeroRuntime.mjs";
13
+
14
+ const environmentSpecificTransformPluginNames = /* @__PURE__ */ new Set(["one:compiler", "one:compiler-css-to-js"]);
15
+ const oneTsconfigPathsPluginName = "one:tsconfig-paths";
16
+ const bareTamaguiPackage = /^@tamagui\/[^/?#]+(?:[/?#]|$)/;
17
+ const inlineEvaluationTamaguiPackage = /^@tamagui\/(?:config|core|slider|web)(?:[/?#]|$)/;
18
+ const externalizablePackageExtensions = /* @__PURE__ */ new Set([
19
+ "",
20
+ ".js",
21
+ ".mjs",
22
+ ".cjs"
23
+ ]);
24
+ function createEvaluationResolveId(plugin, resolveBarePackage) {
25
+ const resolveId = plugin.resolveId;
26
+ if (plugin.name !== oneTsconfigPathsPluginName || !resolveId) return resolveId;
27
+ const handler = typeof resolveId === "object" ? resolveId.handler : resolveId;
28
+ const evaluationHandler = function(source, ...args) {
29
+ if (bareTamaguiPackage.test(source)) {
30
+ const importer = typeof args[0] === "string" ? args[0] : void 0;
31
+ return resolveBarePackage?.(this.environment, source, importer);
32
+ }
33
+ return Reflect.apply(handler, this, [source, ...args]);
34
+ };
35
+ return typeof resolveId === "object" ? {
36
+ ...resolveId,
37
+ handler: evaluationHandler
38
+ } : evaluationHandler;
39
+ }
40
+ function createEvaluationPluginFacade(plugin, resolveBarePackage) {
41
+ return {
42
+ name: plugin.name,
43
+ enforce: plugin.enforce,
44
+ resolveId: createEvaluationResolveId(plugin, resolveBarePackage),
45
+ load: plugin.load,
46
+ transform: environmentSpecificTransformPluginNames.has(plugin.name) ? void 0 : plugin.transform
47
+ };
48
+ }
49
+ const tamaguiEvaluationPluginNames = /* @__PURE__ */ new Set([
50
+ "tamagui",
51
+ "tamagui-extract",
52
+ "tamagui-rnw-lite"
53
+ ]);
54
+ function isEvaluationUserPlugin(plugin) {
55
+ return !!(plugin.resolveId || plugin.load || plugin.transform) && plugin.name !== "alias" && !plugin.name.startsWith("native:") && !plugin.name.startsWith("vite:") && !plugin.name.startsWith("builtin:vite-") && !tamaguiEvaluationPluginNames.has(plugin.name);
56
+ }
57
+ function isEvaluationCorePlugin(plugin) {
58
+ return plugin.name === "alias" || plugin.name.startsWith("vite:") || plugin.name.startsWith("builtin:vite-");
59
+ }
60
+ function isConfiguredEvaluationPackage(source, packages) {
61
+ const cleanSource = source.split(/[?#]/, 1)[0];
62
+ return [...packages].some((packageName) => cleanSource === packageName || cleanSource.startsWith(`${packageName}/`));
63
+ }
64
+ function getEvaluationPackageName(source) {
65
+ if (!source) return;
66
+ const cleanSource = source.split(/[?#]/, 1)[0];
67
+ if (!cleanSource || cleanSource.startsWith(".") || cleanSource.startsWith("#") || cleanSource.startsWith("\0") || path.isAbsolute(cleanSource)) return;
68
+ if (cleanSource.startsWith("@")) {
69
+ const [scope, name2] = cleanSource.split("/");
70
+ return scope && name2 ? `${scope}/${name2}` : void 0;
71
+ }
72
+ const [name] = cleanSource.split("/");
73
+ return name && !path.extname(name) ? name : void 0;
74
+ }
75
+ function getInstalledTamaguiPackages(root, configuredEvaluationPackages) {
76
+ const packageRequire = createRequire(path.join(root, "package.json"));
77
+ const packages = /* @__PURE__ */ new Set();
78
+ for (const modulePath of packageRequire.resolve.paths("@tamagui/core") || []) {
79
+ const scopePath = path.join(modulePath, "@tamagui");
80
+ if (!existsSync(scopePath)) continue;
81
+ for (const entry of readdirSync(scopePath, { withFileTypes: true })) {
82
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
83
+ const packageName = `@tamagui/${entry.name}`;
84
+ if (!inlineEvaluationTamaguiPackage.test(packageName) && !configuredEvaluationPackages.has(packageName)) packages.add(packageName);
85
+ }
86
+ }
87
+ return packages;
88
+ }
89
+ function getEvaluationResolve(resolve2, root, disableTsconfigPaths, configuredEvaluationPackages) {
90
+ return {
91
+ ...resolve2,
92
+ external: resolve2.external === true ? true : [.../* @__PURE__ */ new Set([...(resolve2.external || []).filter((packageName) => !isConfiguredEvaluationPackage(packageName, configuredEvaluationPackages)), ...getInstalledTamaguiPackages(root, configuredEvaluationPackages)])],
93
+ ...disableTsconfigPaths && { tsconfigPaths: false }
94
+ };
95
+ }
96
+ function isConfiguredExternalPackage(source, external) {
97
+ if (external === true) return true;
98
+ const cleanSource = source.split(/[?#]/, 1)[0];
99
+ return external?.some((packageName) => cleanSource === packageName || cleanSource.startsWith(`${packageName}/`));
100
+ }
101
+ function createServeEvaluationConfig(config, configuredEvaluationPackages) {
102
+ const environment = config.environments[TAMAGUI_EVALUATION_ENVIRONMENT];
103
+ let packageResolver;
104
+ const resolveBarePackage = async (evaluationEnvironment, source, importer) => {
105
+ const resolved = await packageResolver?.(evaluationEnvironment, source, importer);
106
+ if (!resolved) return;
107
+ const cleanResolved = resolved.split(/[?#]/, 1)[0];
108
+ if (!inlineEvaluationTamaguiPackage.test(source) && !isConfiguredEvaluationPackage(source, configuredEvaluationPackages) && isConfiguredExternalPackage(source, evaluationEnvironment.config.resolve.external)) return {
109
+ id: source,
110
+ external: true
111
+ };
112
+ if (inlineEvaluationTamaguiPackage.test(source) || isConfiguredEvaluationPackage(source, configuredEvaluationPackages) || !normalizePath(cleanResolved).includes("/node_modules/") || !externalizablePackageExtensions.has(path.extname(cleanResolved))) return resolved;
113
+ return {
114
+ id: source,
115
+ external: true
116
+ };
117
+ };
118
+ const plugins = environment.plugins.flatMap((plugin) => {
119
+ if (isEvaluationCorePlugin(plugin)) return [plugin];
120
+ if (isEvaluationUserPlugin(plugin)) return [createEvaluationPluginFacade(plugin, resolveBarePackage)];
121
+ return [];
122
+ });
123
+ const resolve2 = getEvaluationResolve(environment.resolve, config.root, plugins.some((plugin) => plugin.name === oneTsconfigPathsPluginName), configuredEvaluationPackages);
124
+ const evaluationConfig = {
125
+ ...config,
126
+ environments: {
127
+ ...config.environments,
128
+ [TAMAGUI_EVALUATION_ENVIRONMENT]: {
129
+ ...environment,
130
+ plugins,
131
+ resolve: resolve2
132
+ }
133
+ }
134
+ };
135
+ packageResolver = createIdResolver(evaluationConfig);
136
+ return evaluationConfig;
21
137
  }
22
- function getSharedCacheSize() {
23
- return globalThis[CACHE_SIZE_KEY] || 0;
138
+ async function createOwnedEvaluationConfig(config, configuredEvaluationPackages) {
139
+ const environment = config.environments[TAMAGUI_EVALUATION_ENVIRONMENT];
140
+ const plugins = environment.plugins.filter(isEvaluationUserPlugin).map((plugin) => createEvaluationPluginFacade(plugin));
141
+ const resolve2 = getEvaluationResolve(environment.resolve, config.root, plugins.some((plugin) => plugin.name === oneTsconfigPathsPluginName), configuredEvaluationPackages);
142
+ const { createEnvironment: _createEnvironment, ...dev } = environment.dev;
143
+ return resolveConfig({
144
+ configFile: false,
145
+ root: config.root,
146
+ mode: config.mode,
147
+ logLevel: config.logLevel,
148
+ plugins,
149
+ define: environment.define,
150
+ resolve: resolve2,
151
+ environments: { [TAMAGUI_EVALUATION_ENVIRONMENT]: {
152
+ consumer: environment.consumer,
153
+ keepProcessEnv: environment.keepProcessEnv,
154
+ define: environment.define,
155
+ resolve: resolve2,
156
+ optimizeDeps: environment.optimizeDeps,
157
+ dev: {
158
+ ...dev,
159
+ moduleRunnerTransform: true
160
+ }
161
+ } }
162
+ }, "serve", config.mode);
24
163
  }
25
- function setSharedCacheSize(size) {
26
- ;
27
- globalThis[CACHE_SIZE_KEY] = size;
164
+ const _pluginRequire = createRequire(typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url));
165
+ const resolve = (name) => _pluginRequire.resolve(name);
166
+ const normalizePath = (value) => value.replace(/\\/g, "/");
167
+ const PLUGIN_INSTANCE_KEY = "__tamagui_vite_plugin_instance__";
168
+ function reportCompilerStats(root, reports) {
169
+ const report = createCompilerStatsReport(root, reports);
170
+ console.info(formatCompilerStatsReport(report, process.env.TAMAGUI_COMPILER_STATS === "verbose"));
171
+ if (process.env.TAMAGUI_COMPILER_STATS_FILE) {
172
+ const outputPath = path.resolve(root, process.env.TAMAGUI_COMPILER_STATS_FILE);
173
+ writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}
174
+ `);
175
+ console.info(`[tamagui] compiler stats JSON: ${path.relative(process.cwd(), outputPath)}`);
176
+ }
28
177
  }
29
- function clearSharedCache() {
30
- ;
31
- globalThis[CACHE_KEY] = {};
32
- globalThis[CACHE_SIZE_KEY] = 0;
178
+ function getNextPluginInstanceId() {
179
+ const next = (globalThis[PLUGIN_INSTANCE_KEY] || 0) + 1;
180
+ globalThis[PLUGIN_INSTANCE_KEY] = next;
181
+ return next;
33
182
  }
34
183
  function isInstalled(projectRoot, id) {
35
- try {
36
- const req = createRequire(path.join(projectRoot, "package.json"));
37
- req.resolve(id);
38
- return true;
39
- } catch {
40
- return false;
41
- }
184
+ try {
185
+ createRequire(path.join(projectRoot, "package.json")).resolve(id);
186
+ return true;
187
+ } catch {
188
+ return false;
189
+ }
42
190
  }
43
191
  function addIfInstalled(userConf, projectRoot, ids) {
44
- const root = projectRoot || process.cwd();
45
- userConf.optimizeDeps ||= {};
46
- userConf.optimizeDeps.include ||= [];
47
- for (const id of ids) {
48
- if (!userConf.optimizeDeps.include.includes(id) && isInstalled(root, id)) {
49
- userConf.optimizeDeps.include.push(id);
50
- }
51
- }
52
- }
53
- function getPendingExtractions() {
54
- if (!globalThis[PENDING_KEY]) {
55
- ;
56
- globalThis[PENDING_KEY] = /* @__PURE__ */new Map();
57
- }
58
- return globalThis[PENDING_KEY];
192
+ const root = projectRoot || process.cwd();
193
+ userConf.optimizeDeps ||= {};
194
+ userConf.optimizeDeps.include ||= [];
195
+ for (const id of ids) if (!userConf.optimizeDeps.include.includes(id) && isInstalled(root, id)) userConf.optimizeDeps.include.push(id);
59
196
  }
60
197
  function tamaguiAliases(options = {}) {
61
- const aliases = [];
62
- if (options.svg) {
63
- aliases.push({
64
- find: "react-native-svg",
65
- replacement: resolve("@tamagui/react-native-svg")
66
- });
67
- }
68
- if (options.rnwLite) {
69
- const rnwlBase = path.dirname(resolve("@tamagui/react-native-web-lite/package.json"));
70
- const rnwl = normalizePath(path.join(rnwlBase, options.rnwLite === "without-animated" ? "dist/esm/without-animated.mjs" : "dist/esm/index.mjs"));
71
- const rnwlFlatModules = readdirSync(path.join(rnwlBase, "dist/esm")).filter(file => file.endsWith(".mjs")).map(file => file.slice(0, -".mjs".length)).filter(name => /^[A-Za-z0-9_]+$/.test(name));
72
- aliases.push({
73
- // map deep RNW paths like dist/exports/StyleSheet/preprocess to rnw-lite's flat structure
74
- // extracts the final path segment (e.g. "preprocess" or "createReactDOMStyle")
75
- //
76
- // only match segments rnw-lite actually ships. it implements part of
77
- // react-native-web's export surface, not all of it, and there is no
78
- // flat StyleSheet.mjs. expo sdk 56 added
79
- // expo/src/launch/AppRegistry.web.tsx, which does
80
- // `require('react-native-web/dist/exports/StyleSheet')`; the unscoped
81
- // pattern rewrote that onto a file that does not exist and failed the
82
- // whole optimize. anything lite lacks now falls through to the real
83
- // package.
84
- find: new RegExp(`^react-native(?:-web)?\\/dist\\/(?:exports|modules)\\/(?:.*\\/)?(${rnwlFlatModules.join("|")})$`),
85
- replacement: `${normalizePath(rnwlBase)}/dist/esm/$1.mjs`
86
- }, {
87
- find: /^react-native$/,
88
- replacement: rnwl
89
- }, {
90
- find: /^react-native\/(Libraries\/Utilities\/codegenNativeComponent|Libraries\/Utilities\/codegenNativeCommand)$/,
91
- replacement: `${rnwlBase}/$1`
92
- }, {
93
- find: "react-native/package.json",
94
- replacement: resolve("@tamagui/react-native-web-lite/package.json")
95
- }, {
96
- find: /^react-native-web$/,
97
- replacement: rnwl
98
- });
99
- }
100
- return aliases;
198
+ const aliases = [];
199
+ if (options.svg) aliases.push({
200
+ find: "react-native-svg",
201
+ replacement: resolve("@tamagui/react-native-svg")
202
+ });
203
+ if (options.rnwLite) {
204
+ const rnwlBase = path.dirname(resolve("@tamagui/react-native-web-lite/package.json"));
205
+ const rnwl = normalizePath(path.join(rnwlBase, options.rnwLite === "without-animated" ? "dist/esm/without-animated.mjs" : "dist/esm/index.mjs"));
206
+ const rnwlFlatModules = readdirSync(path.join(rnwlBase, "dist/esm")).filter((file) => file.endsWith(".mjs")).map((file) => file.slice(0, -4)).filter((name) => /^[A-Za-z0-9_]+$/.test(name));
207
+ aliases.push({
208
+ find: new RegExp(`^react-native(?:-web)?\\/dist\\/(?:exports|modules)\\/(?:.*\\/)?(${rnwlFlatModules.join("|")})$`),
209
+ replacement: `${normalizePath(rnwlBase)}/dist/esm/$1.mjs`
210
+ }, {
211
+ find: /^react-native$/,
212
+ replacement: rnwl
213
+ }, {
214
+ find: /^react-native\/(Libraries\/Utilities\/codegenNativeComponent|Libraries\/Utilities\/codegenNativeCommand)$/,
215
+ replacement: `${rnwlBase}/$1`
216
+ }, {
217
+ find: "react-native/package.json",
218
+ replacement: resolve("@tamagui/react-native-web-lite/package.json")
219
+ }, {
220
+ find: /^react-native-web$/,
221
+ replacement: rnwl
222
+ });
223
+ }
224
+ return aliases;
101
225
  }
102
- function tamaguiPlugin({
103
- disableResolveConfig,
104
- ...tamaguiOptionsIn
105
- } = {}) {
106
- let shouldExtract = !tamaguiOptionsIn.disableExtraction;
107
- let watcher;
108
- const enableNativeEnv = !!globalThis.__vxrnEnableNativeEnv;
109
- const extensions = [`.web.mjs`, `.web.js`, `.web.jsx`, `.web.ts`, `.web.tsx`, ".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
110
- loadTamaguiBuildConfig(tamaguiOptionsIn);
111
- const ensureLoaded = async () => {
112
- const promise = getLoadPromise();
113
- if (promise) await promise;
114
- const options = getTamaguiOptions();
115
- if (options) {
116
- shouldExtract = !options.disableExtraction;
117
- }
118
- return options;
119
- };
120
- const getHash = input => createHash("sha1").update(input).digest("base64");
121
- const memoryCache = getSharedCache();
122
- const cssMap = /* @__PURE__ */new Map();
123
- let config;
124
- let server;
125
- const virtualExt = `.tamagui.css`;
126
- const getAbsoluteVirtualFileId = filePath => {
127
- if (filePath.startsWith(config.root)) {
128
- return filePath;
129
- }
130
- return normalizePath(path.join(config.root, filePath));
131
- };
132
- function isNotClient(environment) {
133
- return environment?.name && environment.name !== "client";
134
- }
135
- function isNative(environment) {
136
- return environment?.name && (environment.name === "ios" || environment.name === "android");
137
- }
138
- function invalidateModule(absoluteId) {
139
- if (!server) return;
140
- const {
141
- moduleGraph
142
- } = server;
143
- const modules = moduleGraph.getModulesByFile(absoluteId);
144
- if (modules) {
145
- for (const module of modules) {
146
- moduleGraph.invalidateModule(module);
147
- module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
148
- }
149
- }
150
- }
151
- const basePlugin = {
152
- name: "tamagui",
153
- enforce: "pre",
154
- configureServer(_server) {
155
- server = _server;
156
- },
157
- async buildEnd() {
158
- await watcher?.then(res => {
159
- res?.dispose();
160
- });
161
- },
162
- async config(_, env) {
163
- const options = await ensureLoaded();
164
- if (!options) {
165
- throw new Error(`No tamagui options loaded`);
166
- }
167
- const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options.useReactNativeWebLite;
168
- if (!options.disableWatchTamaguiConfig) {
169
- watcher = Static.watchTamaguiConfig({
170
- components: ["tamagui"],
171
- config: "./src/tamagui.config.ts",
172
- ...options
173
- }).catch(err => {
174
- console.error(` [Tamagui] Error watching config: ${err}`);
175
- });
176
- }
177
- return {
178
- envPrefix: ["TAMAGUI_"],
179
- environments: {
180
- client: {
181
- define: {
182
- "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(true),
183
- "process.env.TAMAGUI_ENVIRONMENT": '"client"'
184
- }
185
- }
186
- },
187
- define: {
188
- // reanimated support
189
- _frameTimestamp: void 0,
190
- _WORKLET: false,
191
- __DEV__: `${env.mode === "development"}`,
192
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || env.mode),
193
- "process.env.ENABLE_RSC": JSON.stringify(process.env.ENABLE_RSC || ""),
194
- "process.env.ENABLE_STEPS": JSON.stringify(process.env.ENABLE_STEPS || ""),
195
- "process.env.IS_STATIC": JSON.stringify(false),
196
- ...(env.mode === "production" && {
197
- "process.env.TAMAGUI_OPTIMIZE_THEMES": JSON.stringify(true)
198
- })
199
- },
200
- resolve: disableResolveConfig || enableNativeEnv ? {} : {
201
- extensions,
202
- alias: {
203
- ...(options.platform !== "native" && {
204
- "react-native/Libraries/Renderer/shims/ReactFabric": resolve("@tamagui/proxy-worm"),
205
- "react-native/Libraries/Utilities/codegenNativeComponent": resolve("@tamagui/proxy-worm"),
206
- "react-native-svg": resolve("@tamagui/react-native-svg"),
207
- ...(!useReactNativeWebLite && {
208
- "react-native": resolve("react-native-web")
209
- })
210
- })
211
- }
212
- }
213
- };
214
- }
215
- };
216
- const rnwLitePlugin = {
217
- name: "tamagui-rnw-lite",
218
- // framework plugins may add their default react-native-web aliases from a
219
- // normal config hook. apply the explicit lite choice after those defaults.
220
- enforce: "post",
221
- config() {
222
- if (enableNativeEnv) {
223
- return {};
224
- }
225
- const options = getTamaguiOptions();
226
- const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options?.useReactNativeWebLite;
227
- if (!useReactNativeWebLite) {
228
- return {};
229
- }
230
- const include = [];
231
- for (const dependency of ["memoize-one", "@react-native/normalize-color"]) {
232
- if (isInstalled(process.cwd(), dependency)) include.push(dependency);
233
- }
234
- return {
235
- resolve: {
236
- alias: tamaguiAliases({
237
- rnwLite: useReactNativeWebLite
238
- })
239
- },
240
- optimizeDeps: {
241
- // upstream react-native-web must not be pre-bundled when aliased to lite
242
- exclude: ["react-native-web"],
243
- include
244
- }
245
- };
246
- }
247
- };
248
- const extractPlugin = {
249
- name: "tamagui-extract",
250
- enforce: "pre",
251
- async config(userConf) {
252
- const options = await ensureLoaded();
253
- userConf.optimizeDeps ||= {};
254
- userConf.optimizeDeps.include ||= [];
255
- userConf.optimizeDeps.include.push("inline-style-prefixer");
256
- addIfInstalled(userConf, userConf.root, ["@tamagui/toast", "@tamagui/toast/v2", "@tamagui/sheet", "@tamagui/sheet/controller"]);
257
- userConf.resolve ||= {};
258
- userConf.resolve.dedupe ||= [];
259
- for (const id of ["tamagui", "@tamagui/core", "@tamagui/web", "@tamagui/toast", "@tamagui/sheet"]) {
260
- if (!userConf.resolve.dedupe.includes(id) && isInstalled(userConf.root || process.cwd(), id)) {
261
- userConf.resolve.dedupe.push(id);
262
- }
263
- }
264
- if (!shouldExtract) return;
265
- userConf.optimizeDeps.include.push("@tamagui/core/inject-styles");
266
- },
267
- async configResolved(resolvedConfig) {
268
- config = resolvedConfig;
269
- },
270
- async resolveId(source) {
271
- if (!shouldExtract) return;
272
- if (isNative(this.environment)) {
273
- return;
274
- }
275
- if (isNotClient(this.environment)) {
276
- return;
277
- }
278
- const [validId, query] = source.split("?");
279
- if (!validId.endsWith(virtualExt)) {
280
- return;
281
- }
282
- const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
283
- if (cssMap.has(absoluteId)) {
284
- return absoluteId + (query ? `?${query}` : "");
285
- }
286
- },
287
- async load(id) {
288
- if (!shouldExtract) return;
289
- const options = getTamaguiOptions();
290
- if (options?.disable) {
291
- return;
292
- }
293
- if (isNative(this.environment)) {
294
- return;
295
- }
296
- if (isNotClient(this.environment)) {
297
- return;
298
- }
299
- const [validId] = id.split("?");
300
- return cssMap.get(validId);
301
- },
302
- transform: {
303
- order: "pre",
304
- async handler(code, id) {
305
- const options = await ensureLoaded();
306
- await ensureFullConfigLoaded();
307
- if (options?.disable) {
308
- return;
309
- }
310
- if (isNative(this.environment)) {
311
- return;
312
- }
313
- const [validId] = id.split("?");
314
- if (!validId.endsWith(".tsx")) {
315
- return;
316
- }
317
- const {
318
- shouldDisable,
319
- shouldPrintDebug
320
- } = await getPragmaOptions({
321
- source: code,
322
- path: validId
323
- });
324
- if (shouldPrintDebug) {
325
- console.trace(`Current file: ${id} in environment: ${this.environment?.name}, shouldDisable: ${shouldDisable}`);
326
- console.info(`
327
-
328
- Original source:
329
- ${code}
330
-
226
+ function createTamaguiNativePlugin(tamaguiOptionsIn, nativeContext) {
227
+ let compilerFrontend = new Static.CompilerFrontend();
228
+ const projectDependencies = /* @__PURE__ */ new Set();
229
+ let root = nativeContext?.root || process.cwd();
230
+ let projectPromise = null;
231
+ let rebuildProject = false;
232
+ let generation = 0;
233
+ const loadProject = async (resolveModule) => {
234
+ if (projectPromise) return projectPromise;
235
+ const shouldRebuild = rebuildProject;
236
+ rebuildProject = false;
237
+ const guarded = (async () => {
238
+ projectDependencies.clear();
239
+ const loadedOptions = await Static.loadTamaguiBuildConfigAsync({
240
+ ...tamaguiOptionsIn,
241
+ root,
242
+ platform: "native",
243
+ outputCSS: void 0
244
+ });
245
+ const options = {
246
+ ...loadedOptions,
247
+ root,
248
+ outputCSS: void 0
249
+ };
250
+ for (const dependency of Static.getTamaguiBuildConfigDependencies(loadedOptions)) projectDependencies.add(normalizePath(dependency));
251
+ if (options.disable || options.disableExtraction) return null;
252
+ const project = await Static.loadCompilerProject({
253
+ root,
254
+ target: "native",
255
+ options,
256
+ rebuild: shouldRebuild,
257
+ generation: `vite-native:${generation + 1}`,
258
+ missingProjectMessage: "Unable to load the Tamagui project for Vite native compilation",
259
+ async resolveComponents(moduleNames) {
260
+ return Promise.all(moduleNames.map(async (moduleName) => {
261
+ const id = await resolveModule(moduleName);
262
+ projectDependencies.add(normalizePath(id.split(/[?#]/, 1)[0]));
263
+ return {
264
+ moduleName,
265
+ id
266
+ };
267
+ }));
268
+ }
269
+ });
270
+ for (const dependency of project.projectInfo.dependencies ?? []) projectDependencies.add(normalizePath(dependency.split(/[?#]/, 1)[0]));
271
+ const configPath = options.config || "tamagui.config.ts";
272
+ projectDependencies.add(normalizePath(path.isAbsolute(configPath) ? configPath : path.resolve(root, configPath)));
273
+ const buildFile = options.buildFile || "tamagui.build.ts";
274
+ projectDependencies.add(normalizePath(path.isAbsolute(buildFile) ? buildFile : path.resolve(root, buildFile)));
275
+ if (options.themeBuilder?.input) projectDependencies.add(normalizePath(path.isAbsolute(options.themeBuilder.input) ? options.themeBuilder.input : path.resolve(root, options.themeBuilder.input)));
276
+ generation++;
277
+ return project;
278
+ })().catch((error) => {
279
+ if (projectPromise === guarded) projectPromise = null;
280
+ rebuildProject = true;
281
+ throw error;
282
+ });
283
+ projectPromise = guarded;
284
+ return projectPromise;
285
+ };
286
+ return {
287
+ name: "tamagui-native-compiler",
288
+ enforce: "post",
289
+ configResolved(config) {
290
+ root = config.root;
291
+ },
292
+ watchChange(id) {
293
+ if (projectDependencies.has(normalizePath(id.split(/[?#]/, 1)[0]))) {
294
+ rebuildProject = true;
295
+ projectPromise = null;
296
+ compilerFrontend = new Static.CompilerFrontend();
297
+ }
298
+ },
299
+ transform: {
300
+ order: "pre",
301
+ async handler(code, id) {
302
+ const environmentName = nativeContext?.platform || this.environment?.name;
303
+ if (environmentName !== "ios" && environmentName !== "android") return;
304
+ const [validId] = id.split("?");
305
+ if (!validId || !/\.[jt]sx$/.test(validId) || normalizePath(validId).split("/").includes("node_modules")) return;
306
+ const { shouldDisable } = await Static.getPragmaOptions({
307
+ source: code,
308
+ path: validId
309
+ });
310
+ if (shouldDisable) return;
311
+ const resolve2 = async (specifier, importer) => {
312
+ const resolution = await this.resolve(specifier, importer, { skipSelf: true });
313
+ return resolution ? {
314
+ id: resolution.id,
315
+ external: resolution.external === true
316
+ } : null;
317
+ };
318
+ const project = await loadProject(async (specifier) => {
319
+ const resolution = await resolve2(specifier, path.join(root, "__tamagui_native.tsx"));
320
+ if (!resolution) throw new Error(`Unable to resolve native compiler component ${specifier}`);
321
+ return resolution.id;
322
+ });
323
+ if (!project) return;
324
+ for (const dependency of projectDependencies) this.addWatchFile(dependency);
325
+ const result = await compilerFrontend.compile({
326
+ id: validId,
327
+ source: code,
328
+ root,
329
+ target: "native",
330
+ project,
331
+ resolve: resolve2,
332
+ load: async (dependencyId) => {
333
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
334
+ if (!path.isAbsolute(cleanDependencyId)) return null;
335
+ try {
336
+ return await readFile(cleanDependencyId, "utf8");
337
+ } catch {
338
+ return null;
339
+ }
340
+ }
341
+ });
342
+ for (const dependency of result.plan.dependencies) if (path.isAbsolute(dependency)) this.addWatchFile(dependency);
343
+ if (result.plan.css) throw new Error(`Native Tamagui compilation produced unexpected CSS for ${validId}`);
344
+ return result.output.changed ? {
345
+ code: result.output.code,
346
+ map: result.output.map
347
+ } : void 0;
348
+ }
349
+ }
350
+ };
351
+ }
352
+ function tamaguiNativePlugin(tamaguiOptionsIn = {}) {
353
+ const plugin = createTamaguiNativePlugin(tamaguiOptionsIn);
354
+ const api = plugin.api && typeof plugin.api === "object" ? plugin.api : {};
355
+ return {
356
+ ...plugin,
357
+ api: {
358
+ ...api,
359
+ vxrnNative: (context) => createTamaguiNativePlugin(tamaguiOptionsIn, context)
360
+ }
361
+ };
362
+ }
363
+ function createTamaguiPlugins({ disableResolveConfig, wrapExtractedCSS = (css) => css, zeroIslandBuild, ...tamaguiOptionsIn } = {}) {
364
+ let shouldExtract = !tamaguiOptionsIn.disableExtraction;
365
+ const enableNativeEnv = !!globalThis.__vxrnEnableNativeEnv;
366
+ const tamaguiLoader = createViteTamaguiLoader(tamaguiOptionsIn);
367
+ const compilerFrontend = new Static.CompilerFrontend();
368
+ const pluginInstanceId = getNextPluginInstanceId();
369
+ const configuredEvaluationPackages = /* @__PURE__ */ new Set();
370
+ let buildEnvironmentPromise = null;
371
+ let buildCleanupPromise = null;
372
+ const activeBuildEnvironments = /* @__PURE__ */ new Set();
373
+ const compilerReports = process.env.TAMAGUI_COMPILER_STATS || process.env.TAMAGUI_COMPILER_STATS_FILE ? /* @__PURE__ */ new Map() : null;
374
+ const releaseBuildEnvironment = async (environment) => {
375
+ if (!activeBuildEnvironments.delete(environment) || activeBuildEnvironments.size) return;
376
+ if (compilerReports?.size) reportCompilerStats(config?.root ?? process.cwd(), compilerReports);
377
+ const currentCleanup = Promise.resolve().then(async () => {
378
+ try {
379
+ await tamaguiLoader.cleanup();
380
+ } finally {
381
+ buildEnvironmentPromise = null;
382
+ }
383
+ });
384
+ buildCleanupPromise = currentCleanup;
385
+ try {
386
+ await currentCleanup;
387
+ } finally {
388
+ if (buildCleanupPromise === currentCleanup) buildCleanupPromise = null;
389
+ }
390
+ };
391
+ const extensions = [
392
+ `.web.mjs`,
393
+ `.web.js`,
394
+ `.web.jsx`,
395
+ `.web.ts`,
396
+ `.web.tsx`,
397
+ ".mjs",
398
+ ".js",
399
+ ".mts",
400
+ ".ts",
401
+ ".jsx",
402
+ ".tsx",
403
+ ".json"
404
+ ];
405
+ const getEvaluationEnvironmentOptions = () => ({
406
+ consumer: "server",
407
+ keepProcessEnv: true,
408
+ define: {
409
+ "process.env.IS_STATIC": JSON.stringify("is_static"),
410
+ "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(false),
411
+ "process.env.TAMAGUI_IS_SERVER": JSON.stringify(true),
412
+ "process.env.TAMAGUI_TARGET": JSON.stringify("web"),
413
+ "process.env.TAMAGUI_ENVIRONMENT": JSON.stringify(TAMAGUI_EVALUATION_ENVIRONMENT),
414
+ "process.env.TAMAGUI_RUNTIME": JSON.stringify("full"),
415
+ "process.env.TAMAGUI_DID_OUTPUT_CSS": JSON.stringify(""),
416
+ "process.env.VITE_ENVIRONMENT": JSON.stringify("ssr"),
417
+ "process.env.TAMAGUI_DISABLE_SLIDER_INTERVAL": JSON.stringify("1")
418
+ },
419
+ resolve: {
420
+ conditions: [...defaultClientConditions],
421
+ mainFields: [...defaultClientMainFields],
422
+ noExternal: [inlineEvaluationTamaguiPackage, ...configuredEvaluationPackages],
423
+ extensions
424
+ },
425
+ dev: {
426
+ createEnvironment(name, resolved) {
427
+ return createRunnableDevEnvironment(name, createServeEvaluationConfig(resolved, configuredEvaluationPackages));
428
+ },
429
+ moduleRunnerTransform: true
430
+ }
431
+ });
432
+ tamaguiLoader.loadTamaguiBuildConfig();
433
+ const ensureLoaded = async () => {
434
+ const promise = tamaguiLoader.getLoadPromise();
435
+ if (promise) await promise;
436
+ const options = tamaguiLoader.getTamaguiOptions();
437
+ if (options) shouldExtract = !options.disableExtraction;
438
+ return options;
439
+ };
440
+ const getHash = (input) => createHash("sha1").update(input).digest("base64");
441
+ const cssMap = /* @__PURE__ */ new Map();
442
+ const transformedModuleIds = /* @__PURE__ */ new Set();
443
+ const compilerHotUpdateSignatures = /* @__PURE__ */ new Map();
444
+ const compilerHotReloadSignatures = /* @__PURE__ */ new Map();
445
+ let config;
446
+ let server;
447
+ let zero = null;
448
+ let zeroReceipt = null;
449
+ let zeroBuildFailed = false;
450
+ let globalCSS = null;
451
+ let globalCSSExpected = null;
452
+ let zeroHtmlEntries = 0;
453
+ let zeroDevIslands = Promise.resolve();
454
+ const virtualExt = `.tamagui.css`;
455
+ const getAbsoluteVirtualFileId = (filePath) => {
456
+ if (filePath.startsWith(config.root)) return filePath;
457
+ return normalizePath(path.join(config.root, filePath));
458
+ };
459
+ const isAppJSXSource = (filePath) => {
460
+ if (!/\.[jt]sx$/.test(filePath)) return false;
461
+ const relative = path.relative(config.root, filePath);
462
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !relative.split(path.sep).includes("node_modules");
463
+ };
464
+ const isFrameworkAnalysisRequest = (id) => id.includes("__react-router-build-client-route");
465
+ function isNotClient(environment) {
466
+ return environment?.name && environment.name !== "client";
467
+ }
468
+ function isNative(environment) {
469
+ return environment?.name && (environment.name === "ios" || environment.name === "android");
470
+ }
471
+ function invalidateCompilerModules() {
472
+ if (server) {
473
+ const ids = /* @__PURE__ */ new Set([...transformedModuleIds, ...cssMap.keys()]);
474
+ for (const environment of Object.values(server.environments)) {
475
+ if (environment.name === TAMAGUI_EVALUATION_ENVIRONMENT) continue;
476
+ for (const id of ids) {
477
+ const modules = environment.moduleGraph.getModulesByFile(id);
478
+ if (!modules) continue;
479
+ for (const module of modules) environment.moduleGraph.invalidateModule(module);
480
+ }
481
+ }
482
+ }
483
+ cssMap.clear();
484
+ }
485
+ return {
486
+ plugins: [
487
+ {
488
+ name: "tamagui",
489
+ enforce: "pre",
490
+ configureServer(_server) {
491
+ server = _server;
492
+ const evaluationEnvironment = server.environments[TAMAGUI_EVALUATION_ENVIRONMENT];
493
+ if (!isRunnableDevEnvironment(evaluationEnvironment)) throw new Error(`The ${TAMAGUI_EVALUATION_ENVIRONMENT} Vite environment must support ModuleRunner evaluation`);
494
+ tamaguiLoader.setEnvironment(evaluationEnvironment);
495
+ },
496
+ async buildEnd() {
497
+ await releaseBuildEnvironment(this.environment);
498
+ },
499
+ async config(userConfig, env) {
500
+ const options = await ensureLoaded();
501
+ if (!options) throw new Error(`No tamagui options loaded`);
502
+ const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options.useReactNativeWebLite;
503
+ for (const source of [options.config, ...options.components || []]) {
504
+ const packageName = getEvaluationPackageName(source);
505
+ if (packageName) configuredEvaluationPackages.add(packageName);
506
+ }
507
+ const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
508
+ zero = zeroIslandBuild ? null : await createZeroRuntimeController(options, resolvedRoot, userConfig.base || "/");
509
+ globalCSS = zeroIslandBuild || env.command !== "build" ? null : Static.resolveGlobalCSSOwnership(options, resolvedRoot);
510
+ return {
511
+ envPrefix: ["TAMAGUI_"],
512
+ environments: {
513
+ client: { define: {
514
+ "process.env.TAMAGUI_IS_CLIENT": JSON.stringify(true),
515
+ "process.env.TAMAGUI_ENVIRONMENT": "\"client\"",
516
+ ...zero?.isEnforcing && { "process.env.TAMAGUI_RUNTIME": JSON.stringify("zero") },
517
+ ...globalCSS && { "process.env.TAMAGUI_DID_OUTPUT_CSS": JSON.stringify("1") }
518
+ } },
519
+ [TAMAGUI_EVALUATION_ENVIRONMENT]: getEvaluationEnvironmentOptions()
520
+ },
521
+ define: {
522
+ "process.env.TAMAGUI_RUNTIME": JSON.stringify("full"),
523
+ _frameTimestamp: void 0,
524
+ _WORKLET: false,
525
+ __DEV__: `${env.mode === "development"}`,
526
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || env.mode),
527
+ "process.env.ENABLE_RSC": JSON.stringify(process.env.ENABLE_RSC || ""),
528
+ "process.env.ENABLE_STEPS": JSON.stringify(process.env.ENABLE_STEPS || ""),
529
+ "process.env.IS_STATIC": JSON.stringify(false),
530
+ ...env.mode === "production" && { "process.env.TAMAGUI_OPTIMIZE_THEMES": JSON.stringify(true) }
531
+ },
532
+ resolve: disableResolveConfig || enableNativeEnv ? {} : {
533
+ extensions,
534
+ alias: { ...options.platform !== "native" && {
535
+ "react-native/Libraries/Renderer/shims/ReactFabric": resolve("@tamagui/proxy-worm"),
536
+ "react-native/Libraries/Utilities/codegenNativeComponent": resolve("@tamagui/proxy-worm"),
537
+ "react-native-svg": resolve("@tamagui/react-native-svg"),
538
+ ...!useReactNativeWebLite && { "react-native": resolve("react-native-web") }
539
+ } }
540
+ }
541
+ };
542
+ }
543
+ },
544
+ {
545
+ name: "tamagui-rnw-lite",
546
+ enforce: "post",
547
+ config() {
548
+ if (enableNativeEnv) return {};
549
+ const options = tamaguiLoader.getTamaguiOptions();
550
+ const useReactNativeWebLite = tamaguiOptionsIn.useReactNativeWebLite ?? options?.useReactNativeWebLite;
551
+ if (!useReactNativeWebLite) return {};
552
+ const include = [];
553
+ for (const dependency of ["memoize-one", "@react-native/normalize-color"]) if (isInstalled(process.cwd(), dependency)) include.push(dependency);
554
+ return {
555
+ resolve: { alias: tamaguiAliases({ rnwLite: useReactNativeWebLite }) },
556
+ ssr: { noExternal: [
557
+ /^@tamagui\//,
558
+ "tamagui",
559
+ "react-native",
560
+ "react-native-web"
561
+ ] },
562
+ optimizeDeps: {
563
+ exclude: ["react-native-web"],
564
+ include
565
+ }
566
+ };
567
+ }
568
+ },
569
+ {
570
+ name: "tamagui-extract",
571
+ enforce: "pre",
572
+ async config(userConf) {
573
+ await ensureLoaded();
574
+ userConf.optimizeDeps ||= {};
575
+ userConf.optimizeDeps.include ||= [];
576
+ userConf.optimizeDeps.include.push("inline-style-prefixer");
577
+ addIfInstalled(userConf, userConf.root, ["@react-native/normalize-color"]);
578
+ addIfInstalled(userConf, userConf.root, [
579
+ "@tamagui/core",
580
+ "@tamagui/web",
581
+ "@tamagui/toast",
582
+ "@tamagui/sheet",
583
+ "@tamagui/sheet/controller"
584
+ ]);
585
+ userConf.resolve ||= {};
586
+ userConf.resolve.dedupe ||= [];
587
+ for (const id of [
588
+ "tamagui",
589
+ "@tamagui/core",
590
+ "@tamagui/web",
591
+ "@tamagui/toast",
592
+ "@tamagui/sheet"
593
+ ]) if (!userConf.resolve.dedupe.includes(id) && isInstalled(userConf.root || process.cwd(), id)) userConf.resolve.dedupe.push(id);
594
+ if (!shouldExtract) return;
595
+ userConf.optimizeDeps.include.push("@tamagui/core/inject-styles");
596
+ },
597
+ async configResolved(resolvedConfig) {
598
+ config = resolvedConfig;
599
+ },
600
+ async buildStart() {
601
+ const buildConfig = this.environment.getTopLevelConfig();
602
+ if (buildConfig.command !== "build") return;
603
+ const pendingCleanup = buildCleanupPromise;
604
+ if (pendingCleanup) await pendingCleanup;
605
+ const buildEnvironment = this.environment;
606
+ activeBuildEnvironments.add(buildEnvironment);
607
+ try {
608
+ if (!tamaguiLoader.getEnvironment()) {
609
+ await tamaguiLoader.loadTamaguiBuildConfig();
610
+ buildEnvironmentPromise ||= (async () => {
611
+ const evaluationEnvironment = createRunnableDevEnvironment(TAMAGUI_EVALUATION_ENVIRONMENT, await createOwnedEvaluationConfig(buildConfig, configuredEvaluationPackages), { hot: false });
612
+ try {
613
+ await evaluationEnvironment.init();
614
+ } catch (error) {
615
+ await evaluationEnvironment.close().catch(() => void 0);
616
+ throw error;
617
+ }
618
+ tamaguiLoader.setEnvironment(evaluationEnvironment, { owned: true });
619
+ })();
620
+ await buildEnvironmentPromise;
621
+ }
622
+ } catch (error) {
623
+ await releaseBuildEnvironment(buildEnvironment);
624
+ throw error;
625
+ }
626
+ },
627
+ hotUpdate: {
628
+ order: "post",
629
+ async handler(options) {
630
+ if (!tamaguiLoader.isEvaluationDependency(options.file)) {
631
+ if (this.environment.name !== "client") return;
632
+ const source = options.type === "delete" ? null : await options.read();
633
+ const affectedModules = /* @__PURE__ */ new Set();
634
+ const compilerHmrRoots = new Set(compilerFrontend.dependentsOf(options.file));
635
+ if (compilerHmrRoots.size || compilerFrontend.has(options.file)) compilerHmrRoots.add(options.file);
636
+ if (compilerFrontend.has(options.file) || compilerHmrRoots.size > 0) {
637
+ if (!(await ensureLoaded())?.disable) {
638
+ const invalidatedIds = options.type === "delete" ? (await compilerFrontend.remove(options.file)).invalidatedIds : await compilerFrontend.update({
639
+ id: options.file,
640
+ source,
641
+ root: config.root,
642
+ project: {
643
+ ...await tamaguiLoader.getCompilerProject(),
644
+ generation: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`
645
+ },
646
+ resolve: async (specifier, importer) => {
647
+ const resolution = await this.environment.pluginContainer.resolveId(specifier, importer);
648
+ return resolution ? {
649
+ id: resolution.id,
650
+ external: resolution.external === true
651
+ } : null;
652
+ },
653
+ load: async (dependencyId) => {
654
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
655
+ if (!path.isAbsolute(cleanDependencyId)) return null;
656
+ try {
657
+ return await readFile(cleanDependencyId, "utf8");
658
+ } catch {
659
+ return null;
660
+ }
661
+ }
662
+ });
663
+ for (const invalidatedId of invalidatedIds) {
664
+ for (const module of this.environment.moduleGraph.getModulesByFile(invalidatedId) ?? []) {
665
+ this.environment.moduleGraph.invalidateModule(module);
666
+ if (compilerHmrRoots.has(invalidatedId) || module.isSelfAccepting) affectedModules.add(module);
667
+ }
668
+ const cssId = getAbsoluteVirtualFileId(`${invalidatedId}${virtualExt}`);
669
+ const cssModule = this.environment.moduleGraph.getModuleById(cssId);
670
+ if (cssModule) this.environment.moduleGraph.invalidateModule(cssModule);
671
+ }
672
+ }
673
+ }
674
+ return affectedModules.size ? [...affectedModules] : void 0;
675
+ }
676
+ const signature = await (async () => {
677
+ if (options.type === "delete") return getHash(`${options.type}:${options.file}`);
678
+ try {
679
+ return getHash(`${options.type}:${options.file}:${await options.read()}`);
680
+ } catch {
681
+ return getHash(`${options.type}:${options.file}:${options.timestamp}`);
682
+ }
683
+ })();
684
+ if (compilerHotUpdateSignatures.get(options.file) !== signature) {
685
+ compilerHotUpdateSignatures.set(options.file, signature);
686
+ tamaguiLoader.invalidate(options.file);
687
+ invalidateCompilerModules();
688
+ }
689
+ if (this.environment.name === "client" && compilerHotReloadSignatures.get(options.file) !== signature) {
690
+ compilerHotReloadSignatures.set(options.file, signature);
691
+ this.environment.hot.send({
692
+ type: "full-reload",
693
+ path: "*",
694
+ triggeredBy: options.file
695
+ });
696
+ }
697
+ return [];
698
+ }
699
+ },
700
+ async watchChange(id) {
701
+ if (config.command !== "build") return;
702
+ if (tamaguiLoader.isEvaluationDependency(id)) {
703
+ tamaguiLoader.invalidate(id);
704
+ invalidateCompilerModules();
705
+ }
706
+ },
707
+ async resolveId(source) {
708
+ if (isNative(this.environment)) return;
709
+ if (isNotClient(this.environment)) return;
710
+ if (!shouldExtract) return;
711
+ const [validId, query] = source.split("?");
712
+ if (!validId.endsWith(virtualExt)) return;
713
+ const absoluteId = validId.startsWith(config.root) ? validId : getAbsoluteVirtualFileId(validId);
714
+ if (cssMap.has(absoluteId)) return absoluteId + (query ? `?${query}` : "");
715
+ },
716
+ async load(id) {
717
+ if (tamaguiLoader.getTamaguiOptions()?.disable) return;
718
+ if (isNative(this.environment)) return;
719
+ if (isNotClient(this.environment)) return;
720
+ if (!shouldExtract) return;
721
+ const [validId] = id.split("?");
722
+ return cssMap.get(validId);
723
+ }
724
+ },
725
+ {
726
+ name: "tamagui-compiler",
727
+ enforce: "post",
728
+ transform: {
729
+ order: "pre",
730
+ async handler(code, id) {
731
+ if (this.environment?.name === TAMAGUI_EVALUATION_ENVIRONMENT) return;
732
+ if (!tamaguiLoader.getEnvironment()) return;
733
+ if (isNative(this.environment)) return;
734
+ const [validId] = id.split("?");
735
+ if (isFrameworkAnalysisRequest(id) || !isAppJSXSource(validId) || !/\.[jt]sx$/.test(validId)) return;
736
+ if ((await ensureLoaded())?.disable || !shouldExtract) return;
737
+ const { shouldDisable } = await Static.getPragmaOptions({
738
+ source: code,
739
+ path: validId
740
+ });
741
+ if (shouldDisable) return;
742
+ const evaluationDependencies = await tamaguiLoader.ensureFullConfigLoaded();
743
+ for (const dependency of evaluationDependencies) this.addWatchFile(dependency);
744
+ const compilerProject = await tamaguiLoader.getCompilerProject();
745
+ const result = await compilerFrontend.compile({
746
+ id: validId,
747
+ source: code,
748
+ root: config.root,
749
+ target: "web",
750
+ project: {
751
+ ...compilerProject,
752
+ generation: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`,
753
+ zeroRuntime: zero !== null
754
+ },
755
+ resolve: async (specifier, importer) => {
756
+ const resolution = await this.resolve(specifier, importer, { skipSelf: true });
757
+ return resolution ? {
758
+ id: resolution.id,
759
+ external: resolution.external === true
760
+ } : null;
761
+ },
762
+ load: async (dependencyId) => {
763
+ const cleanDependencyId = dependencyId.split(/[?#]/, 1)[0];
764
+ if (!path.isAbsolute(cleanDependencyId)) return null;
765
+ try {
766
+ return await readFile(cleanDependencyId, "utf8");
767
+ } catch {
768
+ return null;
769
+ }
770
+ }
771
+ });
772
+ transformedModuleIds.add(validId);
773
+ compilerReports?.set(validId, {
774
+ stats: result.plan.stats,
775
+ diagnostics: result.plan.diagnostics
776
+ });
777
+ for (const dependency of result.plan.dependencies) if (path.isAbsolute(dependency)) this.addWatchFile(dependency);
778
+ if (zeroIslandBuild) {
779
+ zeroIslandBuild.artifact.setIslandModuleCSS(zeroIslandBuild.islandId, validId, wrapExtractedCSS(result.plan.css));
780
+ return result.output.changed ? {
781
+ code: result.output.code,
782
+ map: result.output.map
783
+ } : void 0;
784
+ }
785
+ if (zero) {
786
+ const zeroResult = Static.transformZeroModule({
787
+ mode: zero.isEnforcing ? "enforce" : "report",
788
+ id: validId,
789
+ root: config.root,
790
+ source: code,
791
+ plan: result.plan,
792
+ config: await tamaguiLoader.getTamaguiConfig(),
793
+ isTamaguiSpecifier: (specifier) => specifier === "tamagui" || specifier.startsWith("@tamagui/"),
794
+ resolveIslandLoader: (specifier) => {
795
+ const islandId = zero.loaderIds.get(zeroModuleKey(path.resolve(path.dirname(validId), specifier)));
796
+ return islandId ? { islandId } : null;
797
+ },
798
+ resolveIslandModule: (specifier) => zero.islandModuleIds.get(zeroModuleKey(path.resolve(path.dirname(validId), specifier))) ?? null
799
+ });
800
+ zero.transformed.add(validId);
801
+ if (zeroResult.erased.exports.length) zero.erasedExports.set(validId, zeroResult.erased.exports);
802
+ for (const violation of zeroResult.violations) {
803
+ const { line, column } = Static.offsetToLineColumn(code, violation.span.start);
804
+ zero.violations.push({
805
+ file: path.relative(config.root, validId),
806
+ line,
807
+ column,
808
+ rule: violation.rule,
809
+ code: violation.code,
810
+ component: violation.component,
811
+ message: violation.message
812
+ });
813
+ }
814
+ if (zero.isEnforcing) {
815
+ Static.mergeIslandBridges(zero.bridges, zeroResult.bridges);
816
+ const moduleCSS = [wrapExtractedCSS(result.plan.css), ...[...zeroResult.bridgeCSS.values()]].filter(Boolean).join("\n");
817
+ if (config.command !== "build") {
818
+ let cssImport2 = "";
819
+ if (moduleCSS) {
820
+ const rootRelativeId = `${validId}${virtualExt}`;
821
+ cssMap.set(getAbsoluteVirtualFileId(rootRelativeId), moduleCSS);
822
+ this.addWatchFile(rootRelativeId);
823
+ cssImport2 = `
824
+ import "${rootRelativeId}";`;
825
+ }
826
+ return {
827
+ code: `${zeroResult.output.code}${cssImport2}`,
828
+ map: zeroResult.output.map
829
+ };
830
+ }
831
+ for (const [identifier, rules] of zeroResult.bridgeCSS) zero.artifact.setBridgeRules(identifier, rules);
832
+ zero.artifact.setZeroModuleCSS(validId, wrapExtractedCSS(result.plan.css));
833
+ return zeroResult.output.changed ? {
834
+ code: zeroResult.output.code,
835
+ map: zeroResult.output.map
836
+ } : void 0;
837
+ }
838
+ }
839
+ const isSSR = isNotClient(this.environment);
840
+ let cssImport = null;
841
+ if (result.plan.css) {
842
+ const rootRelativeId = `${validId}${virtualExt}`;
843
+ const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
844
+ cssMap.set(absoluteId, wrapExtractedCSS(result.plan.css));
845
+ this.addWatchFile(rootRelativeId);
846
+ if (!isSSR) cssImport = `import "${rootRelativeId}";`;
847
+ }
848
+ const finalCode = cssImport ? `${result.output.code}
849
+ ${cssImport}` : result.output.code;
850
+ return result.output.changed || cssImport ? {
851
+ code: finalCode,
852
+ map: result.output.map
853
+ } : void 0;
854
+ }
855
+ }
856
+ },
857
+ {
858
+ name: "tamagui-zero-runtime",
859
+ enforce: "post",
860
+ async buildStart() {
861
+ if (!zero || this.environment.name !== "client") return;
862
+ await tamaguiLoader.ensureFullConfigLoaded();
863
+ const tamaguiConfig = await tamaguiLoader.getTamaguiConfig();
864
+ if (!tamaguiConfig) throw new Error(`[tamagui zero-runtime] the Tamagui config did not evaluate, so no CSS artifact can be generated`);
865
+ zero.violations.length = 0;
866
+ zero.transformed.clear();
867
+ zero.erasedExports.clear();
868
+ if (!zero.isEnforcing) return;
869
+ Static.assertZeroConfigDrivers(tamaguiConfig);
870
+ zero.artifact.clearGraphs();
871
+ zero.bridges.clear();
872
+ zeroHtmlEntries = 0;
873
+ zero.artifact.setConfigCSS(tamaguiConfig.getCSS());
874
+ if (config.command !== "build") {
875
+ const islands = zero;
876
+ zeroDevIslands = Promise.all(islands.resolved.islands.map((island) => buildIsland({
877
+ island,
878
+ controller: islands,
879
+ root: config.root,
880
+ outDir: zeroDevIslandDir(islands),
881
+ mode: "development"
882
+ })));
883
+ await zeroDevIslands;
884
+ }
885
+ },
886
+ async configureServer(devServer) {
887
+ if (!zero?.isEnforcing) return;
888
+ const islandBase = `${zero.cssHref.replace(ZERO_CSS_FILENAME, "")}${ZERO_ISLAND_DIRNAME}/`;
889
+ devServer.middlewares.use(async (request, response, next) => {
890
+ const url = (request.url || "").split("?")[0];
891
+ if (url !== zero.cssHref && !url.startsWith(islandBase)) return next();
892
+ await zeroDevIslands;
893
+ if (url === zero.cssHref) {
894
+ response.setHeader("content-type", "text/css; charset=utf-8");
895
+ response.setHeader("cache-control", "no-cache");
896
+ response.end(zero.artifact.css());
897
+ return;
898
+ }
899
+ const islandId = url.slice(islandBase.length).replace(/\.js$/, "");
900
+ const file = path.join(zeroDevIslandDir(zero), ZERO_ISLAND_DIRNAME, `${islandId}.js`);
901
+ if (!existsSync(file)) return next();
902
+ response.setHeader("content-type", "text/javascript; charset=utf-8");
903
+ response.setHeader("cache-control", "no-cache");
904
+ response.end(readFileSync(file));
905
+ });
906
+ },
907
+ buildEnd(error) {
908
+ if (!zero || this.environment.name !== "client") return;
909
+ if (error) {
910
+ zeroBuildFailed = true;
911
+ return;
912
+ }
913
+ if (!zero.isEnforcing) return;
914
+ const importers = /* @__PURE__ */ new Map();
915
+ for (const moduleId of this.getModuleIds()) importers.set(moduleId, this.getModuleInfo(moduleId)?.importers ?? []);
916
+ const escape = Static.erasedExportEscape({
917
+ integration: "vite",
918
+ transformed: zero.transformed,
919
+ erasedExports: zero.erasedExports,
920
+ importersOf: importers
921
+ });
922
+ if (escape) {
923
+ zeroBuildFailed = true;
924
+ throw new Error(escape);
925
+ }
926
+ },
927
+ transformIndexHtml: {
928
+ order: "post",
929
+ handler(html) {
930
+ if (!zero?.isEnforcing) return;
931
+ zeroHtmlEntries++;
932
+ return {
933
+ html,
934
+ tags: [{
935
+ tag: "link",
936
+ attrs: {
937
+ rel: "stylesheet",
938
+ href: zero.cssHref
939
+ },
940
+ injectTo: "head"
941
+ }]
942
+ };
943
+ }
944
+ },
945
+ generateBundle(_outputOptions, bundle) {
946
+ if (!zero?.isEnforcing || this.environment.name !== "client") return;
947
+ const importers = /* @__PURE__ */ new Map();
948
+ for (const moduleId of this.getModuleIds()) for (const imported of this.getModuleInfo(moduleId)?.importedIds ?? []) {
949
+ const list = importers.get(imported);
950
+ if (list) list.push(moduleId);
951
+ else importers.set(imported, [moduleId]);
952
+ }
953
+ const entries = [];
954
+ const modules = [];
955
+ for (const chunk of Object.values(bundle)) {
956
+ if (chunk.type !== "chunk") continue;
957
+ for (const moduleId of Object.keys(chunk.modules)) {
958
+ modules.push({
959
+ id: moduleId,
960
+ importers: importers.get(moduleId) ?? []
961
+ });
962
+ if (this.getModuleInfo(moduleId)?.isEntry) entries.push(moduleId);
963
+ }
964
+ }
965
+ const checked = Static.checkZeroGraph({
966
+ entries,
967
+ modules,
968
+ importerEdges: importers,
969
+ root: zero.resolved.root
970
+ });
971
+ zeroReceipt = {
972
+ integration: "vite",
973
+ graph: "zero",
974
+ entries: entries.sort(),
975
+ moduleCount: modules.length,
976
+ tamaguiModules: checked.tamaguiModules,
977
+ forbidden: checked.forbidden,
978
+ cssArtifact: null,
979
+ identity: "",
980
+ gzip: Object.fromEntries(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.fileName, gzipSync(Buffer.from(chunk.code), { level: 9 }).length]))
981
+ };
982
+ },
983
+ async closeBundle() {
984
+ if (!zero || this.environment.name !== "client") return;
985
+ const outDir = path.resolve(config.root, this.environment.config.build.outDir);
986
+ const receiptName = `vite-${path.basename(outDir)}`;
987
+ Static.writeZeroViolationReport(zero.resolved.outDir, receiptName, {
988
+ integration: "vite",
989
+ mode: zero.isEnforcing ? "enforce" : "report",
990
+ violations: zero.violations
991
+ });
992
+ if (!zero.isEnforcing || zeroBuildFailed) return;
993
+ if (zero.violations.length) throw new Error(Static.formatZeroViolations(zero.violations));
994
+ const islandOutputHashes = {};
995
+ for (const island of zero.resolved.islands) {
996
+ const built = await buildIsland({
997
+ island,
998
+ controller: zero,
999
+ root: config.root,
1000
+ outDir,
1001
+ mode: config.mode
1002
+ });
1003
+ islandOutputHashes[island.id] = built.hash;
1004
+ }
1005
+ if (zeroHtmlEntries === 0) throw new Error(`[tamagui zero-runtime] the zero entry graph has no HTML entry, so the one generated CSS artifact ${zero.cssHref} is never loaded. Build a zero entry through its HTML document.`);
1006
+ const css = finalizeZeroCSS(zero, outDir);
1007
+ const bridgeManifest = Static.canonicalizeBridgeManifest(Object.fromEntries([...zero.bridges.entries()].sort(([left], [right]) => left < right ? -1 : 1)));
1008
+ const identityInputs = {
1009
+ runtimeLiteral: "zero",
1010
+ target: "web",
1011
+ configGeneration: `${pluginInstanceId}:${tamaguiLoader.getGeneration()}`,
1012
+ cssHash: css.hash,
1013
+ compilerVersion: Static.ZERO_COMPILER_VERSION,
1014
+ islandEntries: zero.resolved.islands.map((island) => island.module),
1015
+ bridgeManifestHash: Static.hashBridgeManifest(bridgeManifest),
1016
+ islandOutputHashes
1017
+ };
1018
+ const identity = Static.hashZeroIdentity(identityInputs);
1019
+ if (!zeroReceipt) throw new Error(`[tamagui zero-runtime] no module graph was recorded for the zero entry`);
1020
+ zeroReceipt.cssArtifact = {
1021
+ path: css.href,
1022
+ hash: css.hash
1023
+ };
1024
+ zeroReceipt.identity = identity;
1025
+ Static.writeZeroGraphReceipt(zero.resolved.outDir, receiptName, zeroReceipt);
1026
+ writeFileSync(path.join(zero.resolved.outDir, `${receiptName}.bridges.json`), `${JSON.stringify({
1027
+ identity,
1028
+ identityInputs,
1029
+ cssGzip: css.gzip,
1030
+ bridges: bridgeManifest
1031
+ }, null, 2)}
331
1032
  `);
332
- }
333
- if (shouldDisable) {
334
- return;
335
- }
336
- const isSSR = isNotClient(this.environment);
337
- const cacheKey = getHash(`${code}${id}`);
338
- const pending = getPendingExtractions();
339
- const formatResult = entry => {
340
- const finalCode = !isSSR && entry.cssImport ? `${entry.js}
341
- ${entry.cssImport}` : entry.js;
342
- return {
343
- code: finalCode,
344
- map: entry.map
345
- };
346
- };
347
- const cached = memoryCache[cacheKey];
348
- if (cached) {
349
- if (process.env.DEBUG_TAMAGUI_CACHE) {
350
- console.info(`[tamagui-cache] HIT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
351
- }
352
- return formatResult(cached);
353
- }
354
- const pendingExtraction = pending.get(cacheKey);
355
- if (pendingExtraction) {
356
- if (process.env.DEBUG_TAMAGUI_CACHE) {
357
- console.info(`[tamagui-cache] WAIT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
358
- }
359
- const result = await pendingExtraction;
360
- if (result) {
361
- return formatResult(result);
362
- }
363
- return;
364
- }
365
- if (process.env.DEBUG_TAMAGUI_CACHE) {
366
- console.info(`[tamagui-cache] EXTRACT ${this.environment?.name || "unknown"} ${id.split("/").pop()} key=${cacheKey.slice(0, 8)}`);
367
- }
368
- const extractionPromise = (async () => {
369
- let extracted;
370
- try {
371
- extracted = await Static.extractToClassNames({
372
- source: code,
373
- sourcePath: validId,
374
- options,
375
- shouldPrintDebug
376
- });
377
- } catch (err) {
378
- if (process.env.DEBUG_TAMAGUI_CACHE) {
379
- console.info(`[tamagui-cache] ERROR extracting ${id.split("/").pop()}:`, err);
380
- }
381
- console.error(err instanceof Error ? err.message : String(err));
382
- return null;
383
- }
384
- if (!extracted) {
385
- if (process.env.DEBUG_TAMAGUI_CACHE) {
386
- console.info(`[tamagui-cache] no extraction result for ${id.split("/").pop()}`);
387
- }
388
- return null;
389
- }
390
- const rootRelativeId = `${validId}${virtualExt}`;
391
- const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
392
- let cssImport = null;
393
- if (extracted.styles) {
394
- this.addWatchFile(rootRelativeId);
395
- if (server && cssMap.has(absoluteId)) {
396
- invalidateModule(rootRelativeId);
397
- }
398
- cssImport = `import "${rootRelativeId}";`;
399
- cssMap.set(absoluteId, extracted.styles);
400
- }
401
- const jsCode = extracted.js.toString();
402
- const cacheEntry = {
403
- js: jsCode,
404
- map: extracted.map,
405
- cssImport
406
- };
407
- const newSize = getSharedCacheSize() + jsCode.length;
408
- if (newSize > 67108864) {
409
- clearSharedCache();
410
- } else {
411
- setSharedCacheSize(newSize);
412
- }
413
- memoryCache[cacheKey] = cacheEntry;
414
- if (process.env.DEBUG_TAMAGUI_CACHE) {
415
- console.info(`[tamagui-cache] WRITE key=${cacheKey.slice(0, 8)} cacheSize=${Object.keys(memoryCache).length}`);
416
- }
417
- return cacheEntry;
418
- })();
419
- pending.set(cacheKey, extractionPromise);
420
- try {
421
- const result = await extractionPromise;
422
- if (result) {
423
- return formatResult(result);
424
- }
425
- return;
426
- } finally {
427
- pending.delete(cacheKey);
428
- }
429
- }
430
- }
431
- };
432
- return [basePlugin, rnwLitePlugin, extractPlugin];
1033
+ assertZeroGraph(zeroReceipt);
1034
+ }
1035
+ },
1036
+ {
1037
+ name: "tamagui-global-css",
1038
+ enforce: "post",
1039
+ apply: "build",
1040
+ async buildStart() {
1041
+ if (!globalCSS || this.environment.name !== "client") return;
1042
+ await tamaguiLoader.ensureFullConfigLoaded();
1043
+ const tamaguiConfig = await tamaguiLoader.getTamaguiConfig();
1044
+ if (!tamaguiConfig) throw new Error(`[tamagui] outputCSS is set but the Tamagui config did not evaluate, so no CSS artifact can be generated`);
1045
+ globalCSSExpected = tamaguiConfig.getCSS();
1046
+ },
1047
+ generateBundle() {
1048
+ if (!globalCSS || this.environment.name !== "client") return;
1049
+ const failure = Static.checkGlobalCSSArtifact({
1050
+ cssPath: globalCSS.cssPath,
1051
+ expectedCSS: globalCSSExpected ?? "",
1052
+ loadedModuleIds: this.getModuleIds(),
1053
+ importHint: `Import it once from your client entry: import ${JSON.stringify(relativeImportSpecifier(config.root, globalCSS.cssPath))}`
1054
+ });
1055
+ if (failure) throw new Error(failure.message);
1056
+ }
1057
+ },
1058
+ tamaguiNativePlugin(tamaguiOptionsIn)
1059
+ ],
1060
+ loader: tamaguiLoader
1061
+ };
1062
+ }
1063
+ function zeroDevIslandDir(zero) {
1064
+ return path.join(zero.resolved.outDir, "dev");
1065
+ }
1066
+ function relativeImportSpecifier(from, to) {
1067
+ const relative = normalizePath(path.relative(from, to));
1068
+ return relative.startsWith(".") ? relative : `./${relative}`;
433
1069
  }
434
- export { tamaguiAliases, tamaguiPlugin };
1070
+ function tamaguiPlugin(options = {}) {
1071
+ return createTamaguiPlugins(options).plugins;
1072
+ }
1073
+
1074
+ export { createTamaguiPlugins, tamaguiAliases, tamaguiNativePlugin, tamaguiPlugin };
435
1075
  //# sourceMappingURL=plugin.mjs.map