Open History to see the last commit
1"use strict";
2
3// Loading `dist/common` needs a small custom loader because uniwind declares
4// `"type": "module"` over that CommonJS output and its internal `@/...` import
5// alias only exists at uniwind's own build time; the loader hands unmodified
6// file bytes to V8 and resolves those aliases the same way, so this runs the
7// exact compiled code the Metro transformer bundles.
8const fs = require("node:fs");
9const path = require("node:path");
10const { createRequire } = require("node:module");
11
12function createUniwindCompilerLoader(uniwindPackageJson) {
13 const uniwindRoot = path.dirname(fs.realpathSync(uniwindPackageJson));
14 const uniwindRequire = createRequire(path.join(uniwindRoot, "package.json"));
15 const cache = new Map();
16
17 const load = (absoluteFileWithoutExtension) => {
18 const resolved = [
19 absoluteFileWithoutExtension,
20 `${absoluteFileWithoutExtension}.js`,
21 path.join(absoluteFileWithoutExtension, "index.js"),
22 ].find((candidate) => {
23 try {
24 return fs.statSync(candidate).isFile();
25 } catch {
26 return false;
27 }
28 });
29 if (resolved === undefined) {
30 throw new Error(`Cannot resolve uniwind module ${absoluteFileWithoutExtension}`);
31 }
32 const cached = cache.get(resolved);
33 if (cached !== undefined) return cached;
34
35 const cjsModule = { exports: {} };
36
37 const localRequire = (request) => {
38 if (request.startsWith("@/")) {
39 return load(path.join(uniwindRoot, "dist/common", request.slice(2)));
40 }
41 if (request.startsWith(".")) {
42 return load(path.resolve(path.dirname(resolved), request));
43 }
44 return uniwindRequire(request);
45 };
46
47 const code = fs.readFileSync(resolved, "utf8");
48 new Function("require", "module", "exports", code)(localRequire, cjsModule, cjsModule.exports);
49 cache.set(resolved, cjsModule.exports);
50 return cjsModule.exports;
51 };
52
53 const loadBundler = (request) => load(path.join(uniwindRoot, "dist/common", request));
54 return { loadBundler, uniwindRequire, uniwindRoot };
55}
56
57async function main() {
58 const fixtureDir = fs.realpathSync(path.resolve(process.argv[2]));
59 const uniwindPackageJson = require.resolve("uniwind/package.json", {
60 paths: [fixtureDir],
61 });
62 const { loadBundler, uniwindRequire, uniwindRoot } =
63 createUniwindCompilerLoader(uniwindPackageJson);
64 const { ProcessorBuilder } = loadBundler("bundler/css-processor/processor.js");
65 const { addMetaToStylesTemplate } = loadBundler(
66 "bundler/css-processor/addMetaToStylesTemplate.js",
67 );
68 const { compileNativeCSS } = loadBundler("bundler/css-compiler/compileNativeCSS.js");
69
70 const { compile } = uniwindRequire("@tailwindcss/node");
71 const { Scanner } = uniwindRequire("@tailwindcss/oxide");
72 const compiler = await compile(fs.readFileSync(path.join(fixtureDir, "global.css"), "utf8"), {
73 base: fixtureDir,
74 onDependency: () => {},
75 });
76 const scanner = new Scanner({
77 sources: [...compiler.sources, { negated: false, pattern: "**/*.tsx", base: fixtureDir }],
78 });
79 const tailwindCSS = await compiler.build(scanner.scan());
80
81 const platforms = {};
82 const compiledGuardedClasses = {};
83 for (const match of tailwindCSS.matchAll(/\.(ios|android)\\:([^{ ,]+) \{/g)) {
84 compiledGuardedClasses[`${match[1]}:${match[2]}`.replace(/\\(.)/g, "$1")] = true;
85 }
86 const platformBlock = (name) =>
87 new RegExp(`@media ${name} \\{([\\s\\S]*?)\\n \\}`).exec(tailwindCSS)?.[1] ?? "";
88 const utilityCountIn = (block) => (block.match(/^\s+\.[^ ]+ \{/gm) ?? []).length;
89 const tailwindChecks = {
90 iosBlocks: (tailwindCSS.match(/@media ios \{/g) ?? []).length,
91 androidBlocks: (tailwindCSS.match(/@media android \{/g) ?? []).length,
92 iosUtilities: utilityCountIn(platformBlock("ios")),
93 androidUtilities: utilityCountIn(platformBlock("android")),
94 };
95 for (const platform of ["ios", "android"]) {
96 const bundlerConfig = { platform, themes: ["light", "dark"], polyfills: { rem: 14 } };
97 const processor = new ProcessorBuilder(bundlerConfig);
98 processor.transform(tailwindCSS);
99 const compiled = addMetaToStylesTemplate(processor, platform);
100 const payload = compileNativeCSS(bundlerConfig, tailwindCSS);
101 const styles = {};
102 for (const [className, entries] of Object.entries(compiled)) {
103 styles[className] = entries.map(
104 ({ native, minWidth, maxWidth, active, focus, disabled, dataAttributes }) => ({
105 native,
106 minWidth,
107 maxWidth,
108 active: active ?? null,
109 focus: focus ?? null,
110 disabled: disabled ?? null,
111 dataAttributes: dataAttributes ?? null,
112 }),
113 );
114 }
115 platforms[platform] = {
116 styles,
117 payloadIncludesAllCompiled: Object.keys(compiled).every((className) =>
118 payload.includes(`"${className}"`),
119 ),
120 payloadLeaks: Object.keys(compiledGuardedClasses)
121 .filter((className) => compiled[className] === undefined)
122 .filter((className) => payload.includes(`"${className}"`)),
123 };
124 }
125
126 const transformerPath = path.join(uniwindRoot, "dist/metro/transformer.cjs");
127 let reinitCode = "";
128 const Module = require("node:module");
129 const origLoad = Module._load;
130 Module._load = function (request, ...rest) {
131 if (request === "metro-transform-worker") {
132 return {
133 transform: async (_config, _root, _file, data) => {
134 reinitCode = data.toString();
135 return { output: [{ data: {} }] };
136 },
137 };
138 }
139 return origLoad.call(this, request, ...rest);
140 };
141 process.chdir(fixtureDir);
142 try {
143 const { transform } = require(transformerPath);
144 await transform(
145 { uniwind: { cssEntryFile: "./global.css", isExpoProject: false } },
146 fixtureDir,
147 "global.css",
148 Buffer.from(""),
149 { platform: "ios", type: "module" },
150 );
151 } finally {
152 Module._load = origLoad;
153 }
154 const transformerCheck = {
155 reinitPayload: reinitCode.includes("Uniwind.__reinit(rt =>"),
156 fingerprintArg: /, '[0-9a-f]{64}'\);\s*$/.test(reinitCode),
157 themesArg: reinitCode.includes("['light', 'dark']"),
158 };
159
160 process.stdout.write(JSON.stringify({ tailwindChecks, transformerCheck, platforms }));
161}
162
163main().catch((error) => {
164 console.error(error);
165 process.exit(1);
166});