@weapp-tailwindcss/react-native 0.2.22 → 0.3.0
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.
- package/README.md +4 -0
- package/README.zh-CN.md +4 -0
- package/dist/babel.cjs +5 -2
- package/dist/babel.js +5 -2
- package/dist/compiler.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/metro-BZbdIyTH.js +353 -0
- package/dist/metro-Ds2ZUc6_.cjs +429 -0
- package/dist/metro-transformer.cjs +14 -22
- package/dist/metro-transformer.js +12 -20
- package/dist/metro.cjs +10 -247
- package/dist/metro.d.ts +4 -2
- package/dist/metro.js +1 -233
- package/dist/runtime-B3hAisFx.d.ts +34 -0
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.d.ts +3 -17
- package/dist/runtime.js +1 -1
- package/dist/tailwind.cjs +4 -2
- package/dist/tailwind.d.ts +2 -2
- package/dist/tailwind.js +4 -2
- package/dist/types-CKAFTXX9.d.ts +17 -0
- package/package.json +6 -5
- package/dist/types-BKoPIarb.d.ts +0 -31
package/README.md
CHANGED
|
@@ -41,10 +41,14 @@ On Android and iOS, the Metro integration resolves `react` and `react-native` fr
|
|
|
41
41
|
- `dark:`, `ios:`, `android:`, and `native:` are conditional native variants. State, responsive, structural, and other browser selector variants are reported as unsupported instead of being applied unconditionally.
|
|
42
42
|
- Static StyleSheet IDs are stable across unrelated class additions and CSS value changes, so Metro CSS HMR cannot redirect an existing Babel lookup to another rule.
|
|
43
43
|
|
|
44
|
+
`tw()` and `getStaticStyle()` return React Native `StyleProp` values, which can be passed directly to View, Text, and Image styles. They may contain registered StyleSheet IDs or arrays; use `StyleSheet.flatten()` when you need to inspect individual properties. `composeStyle()` preserves the inline style type, including `false`, `null`, and nested arrays.
|
|
45
|
+
|
|
44
46
|
## Public entry points
|
|
45
47
|
|
|
46
48
|
The package exposes `compiler`, `tailwind`, `babel`, `metro`, `runtime`, and the platform-neutral `env` type entry. Custom Metro setups can compose these entry points directly.
|
|
47
49
|
|
|
50
|
+
Node-only tooling without the optional React Native peer should import `compiler`, `tailwind`, or `metro` directly. The root and `runtime` entries expose native `StyleProp` types and require React Native types in TypeScript projects.
|
|
51
|
+
|
|
48
52
|
## Scope
|
|
49
53
|
|
|
50
54
|
This package generates React Native style manifests. It does not emit Web CSS or mini-program WXSS and does not add NativeWind or a browser CSS runtime to the application.
|
package/README.zh-CN.md
CHANGED
|
@@ -41,10 +41,14 @@ Metro 会扫描源码、生成精确候选集合和 manifest,并把 Babel JSX
|
|
|
41
41
|
- `dark:`、`ios:`、`android:`、`native:` 是原生条件变体;状态、响应式、结构等浏览器 selector 变体会明确报告为不支持,不会被错误地无条件应用。
|
|
42
42
|
- 静态 StyleSheet ID 在无关 class 增删和 CSS 值变化时保持稳定,Metro CSS HMR 不会让已有 Babel lookup 串到其他规则。
|
|
43
43
|
|
|
44
|
+
`tw()` 与 `getStaticStyle()` 返回 React Native 的 `StyleProp`,可以直接传给 View、Text、Image 的 style。返回值可能含已注册的 StyleSheet ID 或数组;需要读取具体属性时使用 `StyleSheet.flatten()`。`composeStyle()` 保留内联样式类型,包括 `false`、`null` 和嵌套数组。
|
|
45
|
+
|
|
44
46
|
## 公开入口
|
|
45
47
|
|
|
46
48
|
包提供 `compiler`、`tailwind`、`babel`、`metro`、`runtime` 与中性类型入口 `env`。非 Expo 或定制 Metro 场景可以显式组合这些入口。
|
|
47
49
|
|
|
50
|
+
没有安装可选 React Native peer 的纯 Node 工具应直接导入 `compiler`、`tailwind` 或 `metro`。根入口和 `runtime` 暴露原生 `StyleProp`,TypeScript 项目需要 React Native 类型。
|
|
51
|
+
|
|
48
52
|
## 边界
|
|
49
53
|
|
|
50
54
|
本包生成 React Native 样式清单,不输出 Web CSS 或小程序 WXSS,也不把 NativeWind 或浏览器 CSS 运行时引入应用。
|
package/dist/babel.cjs
CHANGED
|
@@ -28,6 +28,9 @@ function hasKnownStaticTokens(value, classNameSet) {
|
|
|
28
28
|
if (!classNameSet) return false;
|
|
29
29
|
return classTokens(value).every((token) => classNameSet.has(token));
|
|
30
30
|
}
|
|
31
|
+
function findStyleAttribute(attributes) {
|
|
32
|
+
return attributes.find((attribute) => _babel_types.isJSXAttribute(attribute) && attribute.name.name === "style");
|
|
33
|
+
}
|
|
31
34
|
function styleExpression(attribute) {
|
|
32
35
|
if (!attribute) return;
|
|
33
36
|
const value = attribute.value;
|
|
@@ -88,12 +91,12 @@ function weappReactNativeBabel() {
|
|
|
88
91
|
if (!classAttribute || !_babel_types.isJSXAttribute(classAttribute)) return;
|
|
89
92
|
if (_babel_types.isStringLiteral(classAttribute.value)) {
|
|
90
93
|
if (!hasKnownStaticTokens(classAttribute.value.value, state.opts.classNameSet ? new Set(state.opts.classNameSet) : void 0)) return;
|
|
91
|
-
applyStyleAttribute(path, composeExpression(program, state, staticStyleExpression(program, state, classAttribute.value.value), styleExpression(path.node.attributes
|
|
94
|
+
applyStyleAttribute(path, composeExpression(program, state, staticStyleExpression(program, state, classAttribute.value.value), styleExpression(findStyleAttribute(path.node.attributes))));
|
|
92
95
|
path.node.attributes = path.node.attributes.filter((attribute) => attribute !== classAttribute);
|
|
93
96
|
return;
|
|
94
97
|
}
|
|
95
98
|
if (_babel_types.isJSXExpressionContainer(classAttribute.value) && classAttribute.value.expression) {
|
|
96
|
-
const existing = path.node.attributes
|
|
99
|
+
const existing = findStyleAttribute(path.node.attributes);
|
|
97
100
|
applyStyleAttribute(path, composeExpression(program, state, dynamicStyleExpression(program, state, classAttribute.value.expression), styleExpression(existing)));
|
|
98
101
|
path.node.attributes = path.node.attributes.filter((attribute) => attribute !== classAttribute);
|
|
99
102
|
}
|
package/dist/babel.js
CHANGED
|
@@ -26,6 +26,9 @@ function hasKnownStaticTokens(value, classNameSet) {
|
|
|
26
26
|
if (!classNameSet) return false;
|
|
27
27
|
return classTokens(value).every((token) => classNameSet.has(token));
|
|
28
28
|
}
|
|
29
|
+
function findStyleAttribute(attributes) {
|
|
30
|
+
return attributes.find((attribute) => t.isJSXAttribute(attribute) && attribute.name.name === "style");
|
|
31
|
+
}
|
|
29
32
|
function styleExpression(attribute) {
|
|
30
33
|
if (!attribute) return;
|
|
31
34
|
const value = attribute.value;
|
|
@@ -86,12 +89,12 @@ function weappReactNativeBabel() {
|
|
|
86
89
|
if (!classAttribute || !t.isJSXAttribute(classAttribute)) return;
|
|
87
90
|
if (t.isStringLiteral(classAttribute.value)) {
|
|
88
91
|
if (!hasKnownStaticTokens(classAttribute.value.value, state.opts.classNameSet ? new Set(state.opts.classNameSet) : void 0)) return;
|
|
89
|
-
applyStyleAttribute(path, composeExpression(program, state, staticStyleExpression(program, state, classAttribute.value.value), styleExpression(path.node.attributes
|
|
92
|
+
applyStyleAttribute(path, composeExpression(program, state, staticStyleExpression(program, state, classAttribute.value.value), styleExpression(findStyleAttribute(path.node.attributes))));
|
|
90
93
|
path.node.attributes = path.node.attributes.filter((attribute) => attribute !== classAttribute);
|
|
91
94
|
return;
|
|
92
95
|
}
|
|
93
96
|
if (t.isJSXExpressionContainer(classAttribute.value) && classAttribute.value.expression) {
|
|
94
|
-
const existing = path.node.attributes
|
|
97
|
+
const existing = findStyleAttribute(path.node.attributes);
|
|
95
98
|
applyStyleAttribute(path, composeExpression(program, state, dynamicStyleExpression(program, state, classAttribute.value.expression), styleExpression(existing)));
|
|
96
99
|
path.node.attributes = path.node.attributes.filter((attribute) => attribute !== classAttribute);
|
|
97
100
|
}
|
package/dist/compiler.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as NativeStyleManifest, t as CompileNativeStylesheetOptions } from "./types-CKAFTXX9.js";
|
|
2
2
|
import { baseClassName } from "@weapp-tailwindcss/postcss/native";
|
|
3
3
|
//#region src/compiler.d.ts
|
|
4
4
|
export declare function addNativeVariantRules(manifest: NativeStyleManifest, candidates: Iterable<string>): void;
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_babel = require("./babel.cjs");
|
|
3
3
|
const require_compiler = require("./compiler.cjs");
|
|
4
|
-
const require_metro = require("./metro.cjs");
|
|
4
|
+
const require_metro = require("./metro-Ds2ZUc6_.cjs");
|
|
5
5
|
const require_runtime = require("./runtime.cjs");
|
|
6
6
|
const require_tailwind = require("./tailwind.cjs");
|
|
7
7
|
exports.VIRTUAL_MANIFEST_MODULE = require_metro.VIRTUAL_MANIFEST_MODULE;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import weappReactNativeBabel from "./babel.js";
|
|
2
|
-
import { a as
|
|
2
|
+
import { a as NativeStyleRule, i as NativeStyleManifest, n as NativeCompilerWarning, r as NativePlatform, t as CompileNativeStylesheetOptions } from "./types-CKAFTXX9.js";
|
|
3
3
|
import { compileNativeStylesheet } from "./compiler.js";
|
|
4
4
|
import { VIRTUAL_MANIFEST_MODULE, getRegisteredManifest, getVirtualModuleCode, getVirtualModuleCodeAsync, withWeappTailwindcss } from "./metro.js";
|
|
5
|
-
import {
|
|
5
|
+
import { a as setEnvironment, c as tw, d as NativeStyleRuntime, f as NativeStyleValue, i as getStaticStyle, l as NativeClassValue, n as createNativeStyleRuntime, o as setManifest, r as getManifest, s as setStyleSheetFactory, t as composeStyle, u as NativeStyleEnvironment } from "./runtime-B3hAisFx.js";
|
|
6
6
|
import { generateNativeStylesheet } from "./tailwind.js";
|
|
7
7
|
export { type CompileNativeStylesheetOptions, type NativeClassValue, type NativeCompilerWarning, type NativePlatform, type NativeStyleEnvironment, type NativeStyleManifest, type NativeStyleRule, type NativeStyleRuntime, type NativeStyleValue, VIRTUAL_MANIFEST_MODULE, weappReactNativeBabel as babelPlugin, compileNativeStylesheet, composeStyle, createNativeStyleRuntime, generateNativeStylesheet, getManifest, getRegisteredManifest, getStaticStyle, getVirtualModuleCode, getVirtualModuleCodeAsync, setEnvironment, setManifest, setStyleSheetFactory, tw, withWeappTailwindcss };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import weappReactNativeBabel from "./babel.js";
|
|
2
2
|
import { compileNativeStylesheet } from "./compiler.js";
|
|
3
|
-
import {
|
|
3
|
+
import { c as getVirtualModuleCodeAsync, l as withWeappTailwindcss, r as getRegisteredManifest, s as getVirtualModuleCode, t as VIRTUAL_MANIFEST_MODULE } from "./metro-BZbdIyTH.js";
|
|
4
4
|
import { composeStyle, createNativeStyleRuntime, getManifest, getStaticStyle, setEnvironment, setManifest, setStyleSheetFactory, tw } from "./runtime.js";
|
|
5
5
|
import { generateNativeStylesheet } from "./tailwind.js";
|
|
6
6
|
export { VIRTUAL_MANIFEST_MODULE, weappReactNativeBabel as babelPlugin, compileNativeStylesheet, composeStyle, createNativeStyleRuntime, generateNativeStylesheet, getManifest, getRegisteredManifest, getStaticStyle, getVirtualModuleCode, getVirtualModuleCodeAsync, setEnvironment, setManifest, setStyleSheetFactory, tw, withWeappTailwindcss };
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { compileNativeStylesheet } from "./compiler.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import process from "node:process";
|
|
8
|
+
import { URL, fileURLToPath } from "node:url";
|
|
9
|
+
import { setTimeout } from "node:timers/promises";
|
|
10
|
+
//#region src/metro/manifest-store.ts
|
|
11
|
+
/** 同目录替换,避免 Metro 或 worker 读到截断后的虚拟模块与 JSON。 */
|
|
12
|
+
function writeManifestFile(filename, content) {
|
|
13
|
+
const temporary = `${filename}.${randomUUID()}.tmp`;
|
|
14
|
+
try {
|
|
15
|
+
fs.writeFileSync(temporary, content, "utf8");
|
|
16
|
+
fs.renameSync(temporary, filename);
|
|
17
|
+
} finally {
|
|
18
|
+
fs.rmSync(temporary, { force: true });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** ready 前后版本一致才接受产物;失败和超时不能降级成旧 manifest。 */
|
|
22
|
+
async function readPublishedSnapshot(filename, readyPath) {
|
|
23
|
+
if (!readyPath) try {
|
|
24
|
+
return { manifest: JSON.parse(await fs.promises.readFile(filename, "utf8")) };
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error.code === "ENOENT") return;
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
const deadline = Date.now() + 12e4;
|
|
30
|
+
while (Date.now() < deadline) {
|
|
31
|
+
try {
|
|
32
|
+
const before = await fs.promises.readFile(readyPath, "utf8");
|
|
33
|
+
const content = await fs.promises.readFile(filename, "utf8");
|
|
34
|
+
if (before === await fs.promises.readFile(readyPath, "utf8")) {
|
|
35
|
+
let virtualPath;
|
|
36
|
+
if (before.startsWith("{")) {
|
|
37
|
+
const publication = JSON.parse(before);
|
|
38
|
+
if (publication.error) throw new Error(publication.error);
|
|
39
|
+
if (!publication.revision || !publication.virtualPath) throw new Error("React Native manifest 缺少发布身份");
|
|
40
|
+
virtualPath = publication.virtualPath;
|
|
41
|
+
} else if (!/^\d+\s*$/.test(before)) throw new Error("React Native manifest 发布标识无效");
|
|
42
|
+
return {
|
|
43
|
+
manifest: JSON.parse(content),
|
|
44
|
+
...virtualPath ? { virtualPath } : {}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error.code !== "ENOENT") throw error;
|
|
49
|
+
}
|
|
50
|
+
await setTimeout(25);
|
|
51
|
+
}
|
|
52
|
+
throw new Error(`等待 React Native manifest 超时:${filename}`);
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/metro/refresh.ts
|
|
56
|
+
function fingerprint(files) {
|
|
57
|
+
const hash = createHash("sha256");
|
|
58
|
+
for (const file of files) try {
|
|
59
|
+
const stat = fs.statSync(file, { bigint: true });
|
|
60
|
+
hash.update(JSON.stringify([
|
|
61
|
+
file,
|
|
62
|
+
String(stat.ino),
|
|
63
|
+
String(stat.size),
|
|
64
|
+
String(stat.mtimeNs),
|
|
65
|
+
String(stat.ctimeNs)
|
|
66
|
+
]));
|
|
67
|
+
if (stat.isFile()) hash.update(fs.readFileSync(file));
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error.code !== "ENOENT") throw error;
|
|
70
|
+
hash.update(JSON.stringify([file, "missing"]));
|
|
71
|
+
}
|
|
72
|
+
return hash.digest("hex");
|
|
73
|
+
}
|
|
74
|
+
/** 发布前验证显式输入的版本;watch 合并事件时也不能发布已过期的编译结果。 */
|
|
75
|
+
async function compileStableInput(files, compile, isCurrent) {
|
|
76
|
+
for (let attempt = 0; attempt < 5 && isCurrent(); attempt++) {
|
|
77
|
+
const before = fingerprint(files);
|
|
78
|
+
if (files.length) {
|
|
79
|
+
await setTimeout(25);
|
|
80
|
+
if (!isCurrent()) return;
|
|
81
|
+
if (before !== fingerprint(files)) continue;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const result = await compile();
|
|
85
|
+
if (!isCurrent()) return;
|
|
86
|
+
if (before === fingerprint(files)) return result;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (!isCurrent()) return;
|
|
89
|
+
if (before === fingerprint(files)) throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (isCurrent()) throw new Error("React Native 样式输入持续变化,5 次稳定性检查后仍未完成保存;请完成保存后重试。");
|
|
93
|
+
}
|
|
94
|
+
/** 等待期间出现新一轮刷新时,继续等待新一轮;过期轮的失败不能遮蔽新结果。 */
|
|
95
|
+
async function waitForCurrentRefresh(entry) {
|
|
96
|
+
for (;;) {
|
|
97
|
+
const ready = entry.ready;
|
|
98
|
+
try {
|
|
99
|
+
await ready;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (ready === entry.ready) throw error;
|
|
102
|
+
}
|
|
103
|
+
if (ready === entry.ready) return;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/metro/virtual-module.ts
|
|
108
|
+
function virtualModuleCode(manifest) {
|
|
109
|
+
return `import { setEnvironment, setManifest, setStyleSheetFactory } from ${JSON.stringify("@weapp-tailwindcss/react-native/runtime")};\nimport { Appearance, Platform, StyleSheet } from 'react-native';\nsetStyleSheetFactory(StyleSheet.create);\nconst syncEnvironment = () => setEnvironment({ platform: Platform.OS, colorScheme: Appearance.getColorScheme() ?? 'light' });\nsetManifest(${JSON.stringify(manifest)});\nsyncEnvironment();\nAppearance.addChangeListener?.(({ colorScheme }) => setEnvironment({ platform: Platform.OS, colorScheme: colorScheme ?? 'light' }));\nexport default undefined;`;
|
|
110
|
+
}
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region src/metro/watch.ts
|
|
113
|
+
/** 文件监听绑定父目录,避免编辑器原子替换文件后仍监听已移除的 inode。 */
|
|
114
|
+
function watchInput(target, changed) {
|
|
115
|
+
const recursive = fs.statSync(target).isDirectory();
|
|
116
|
+
const watchRoot = recursive ? target : path.dirname(target);
|
|
117
|
+
return fs.watch(watchRoot, {
|
|
118
|
+
persistent: false,
|
|
119
|
+
recursive
|
|
120
|
+
}, (_event, filename) => {
|
|
121
|
+
if (recursive || filename === null || path.resolve(watchRoot, filename) === target) changed();
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/metro.ts
|
|
126
|
+
const VIRTUAL_MANIFEST_MODULE = "@weapp-tailwindcss/react-native/virtual";
|
|
127
|
+
const registry = /* @__PURE__ */ new Map();
|
|
128
|
+
const appRootSingletonModules = /* @__PURE__ */ new Set(["react"]);
|
|
129
|
+
let nextId = 0;
|
|
130
|
+
function packageNameFromModuleId(moduleName) {
|
|
131
|
+
const segments = moduleName.split("/");
|
|
132
|
+
return moduleName.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0] ?? "";
|
|
133
|
+
}
|
|
134
|
+
function shouldResolveFromAppRoot(moduleName, platform) {
|
|
135
|
+
const packageName = packageNameFromModuleId(moduleName);
|
|
136
|
+
if (appRootSingletonModules.has(packageName)) return true;
|
|
137
|
+
return platform !== "web" && packageName === "react-native";
|
|
138
|
+
}
|
|
139
|
+
function resolveAppRootSingleton(projectRoot, moduleName, platform) {
|
|
140
|
+
if (platform !== "web" || ![
|
|
141
|
+
"react",
|
|
142
|
+
"react-dom",
|
|
143
|
+
"react-native-web"
|
|
144
|
+
].includes(packageNameFromModuleId(moduleName))) return;
|
|
145
|
+
try {
|
|
146
|
+
return {
|
|
147
|
+
type: "sourceFile",
|
|
148
|
+
filePath: createRequire(path.join(projectRoot, "package.json")).resolve(moduleName)
|
|
149
|
+
};
|
|
150
|
+
} catch {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** 为 Metro worker 提供不依赖进程内 registry 的 manifest 入口。 */
|
|
155
|
+
function getManifestPathsForProjectRoot(projectRoot) {
|
|
156
|
+
const projectKey = createHash("sha256").update(path.resolve(projectRoot)).digest("hex").slice(0, 24);
|
|
157
|
+
const base = path.join(os.tmpdir(), "weapp-tailwindcss-native", `project-${projectKey}`);
|
|
158
|
+
return {
|
|
159
|
+
manifestPath: `${base}.manifest.json`,
|
|
160
|
+
manifestReadyPath: `${base}.manifest.ready`
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function resolveInput(input, projectRoot) {
|
|
164
|
+
return input ? path.resolve(projectRoot, input) : void 0;
|
|
165
|
+
}
|
|
166
|
+
function emptyManifest() {
|
|
167
|
+
return {
|
|
168
|
+
version: 1,
|
|
169
|
+
classSet: [],
|
|
170
|
+
rules: {},
|
|
171
|
+
variables: {},
|
|
172
|
+
warnings: []
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function writeVirtualModule(entry) {
|
|
176
|
+
fs.mkdirSync(path.dirname(entry.virtualPath), { recursive: true });
|
|
177
|
+
fs.mkdirSync(path.dirname(entry.manifestPath), { recursive: true });
|
|
178
|
+
writeManifestFile(entry.virtualPath, virtualModuleCode(entry.manifest));
|
|
179
|
+
writeManifestFile(entry.manifestPath, JSON.stringify(entry.manifest));
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Metro worker 会把文件路径先相对化再恢复为绝对路径。虚拟模块必须位于
|
|
183
|
+
* 项目根目录内,否则 Windows 跨盘符路径会被错误拼接成 `D:\\C:\\...`。
|
|
184
|
+
*/
|
|
185
|
+
function getVirtualModulePath(projectRoot, id) {
|
|
186
|
+
return path.join(projectRoot, "node_modules", ".cache", "weapp-tailwindcss-native", `${id}.js`);
|
|
187
|
+
}
|
|
188
|
+
function markManifestPending(entry) {
|
|
189
|
+
fs.rmSync(entry.manifestReadyPath, { force: true });
|
|
190
|
+
}
|
|
191
|
+
function markManifestReady(entry) {
|
|
192
|
+
writeManifestFile(entry.manifestReadyPath, JSON.stringify({
|
|
193
|
+
revision: randomUUID(),
|
|
194
|
+
version: entry.version,
|
|
195
|
+
virtualPath: entry.virtualPath
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
async function compileOptions(options, projectRoot) {
|
|
199
|
+
if (options.manifest) return options.manifest;
|
|
200
|
+
if (options.input) {
|
|
201
|
+
const { generateNativeStylesheet } = await (import.meta.url.endsWith(".ts") ? import("./tailwind.js") : import("./tailwind.js"));
|
|
202
|
+
return generateNativeStylesheet({
|
|
203
|
+
projectRoot,
|
|
204
|
+
cssEntries: [resolveInput(options.input, projectRoot)],
|
|
205
|
+
candidates: options.classSet,
|
|
206
|
+
sourceGlobs: options.sourceGlobs
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
return compileNativeStylesheet(options.css ?? "", { classSet: options.classSet });
|
|
210
|
+
}
|
|
211
|
+
function register(options) {
|
|
212
|
+
const id = `weapp-tailwindcss-native-${nextId++}`;
|
|
213
|
+
const projectRoot = path.resolve(options.projectRoot ?? process.cwd());
|
|
214
|
+
const manifestPaths = getManifestPathsForProjectRoot(projectRoot);
|
|
215
|
+
const entry = {
|
|
216
|
+
version: 0,
|
|
217
|
+
manifest: options.manifest ?? (options.css ? compileNativeStylesheet(options.css, { classSet: options.classSet }) : emptyManifest()),
|
|
218
|
+
projectRoot,
|
|
219
|
+
virtualPath: getVirtualModulePath(projectRoot, id),
|
|
220
|
+
manifestPath: manifestPaths.manifestPath,
|
|
221
|
+
manifestReadyPath: manifestPaths.manifestReadyPath,
|
|
222
|
+
ready: Promise.resolve(),
|
|
223
|
+
refresh: async () => {}
|
|
224
|
+
};
|
|
225
|
+
registry.set(id, entry);
|
|
226
|
+
markManifestPending(entry);
|
|
227
|
+
writeVirtualModule(entry);
|
|
228
|
+
const inputFiles = [...new Set([...options.watchFiles ?? [], ...options.input ? [options.input] : []].map((file) => path.resolve(projectRoot, file)))];
|
|
229
|
+
let generation = 0;
|
|
230
|
+
entry.refresh = () => {
|
|
231
|
+
const currentGeneration = ++generation;
|
|
232
|
+
markManifestPending(entry);
|
|
233
|
+
entry.ready = (async () => {
|
|
234
|
+
try {
|
|
235
|
+
const manifest = await compileStableInput(inputFiles, () => compileOptions(options, projectRoot), () => currentGeneration === generation);
|
|
236
|
+
if (manifest && currentGeneration === generation) {
|
|
237
|
+
entry.manifest = manifest;
|
|
238
|
+
entry.version++;
|
|
239
|
+
writeVirtualModule(entry);
|
|
240
|
+
markManifestReady(entry);
|
|
241
|
+
}
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (currentGeneration !== generation) return;
|
|
244
|
+
const message = `生成 React Native manifest 失败:${error instanceof Error ? error.message : String(error)}`;
|
|
245
|
+
writeManifestFile(entry.manifestReadyPath, JSON.stringify({ error: message }));
|
|
246
|
+
throw new Error(message, { cause: error });
|
|
247
|
+
}
|
|
248
|
+
})();
|
|
249
|
+
entry.ready.catch((error) => console.error(error.message));
|
|
250
|
+
return entry.ready;
|
|
251
|
+
};
|
|
252
|
+
entry.refresh();
|
|
253
|
+
const sourceRoots = (options.sourceGlobs ?? []).map((pattern) => pattern.split(/[*{[]/, 1)[0]?.replace(/[/\\]$/, "")).filter((root) => Boolean(root));
|
|
254
|
+
[
|
|
255
|
+
...options.watchFiles ?? [],
|
|
256
|
+
...options.input ? [options.input] : [],
|
|
257
|
+
...sourceRoots
|
|
258
|
+
].map((file) => {
|
|
259
|
+
const target = path.resolve(projectRoot, file);
|
|
260
|
+
try {
|
|
261
|
+
return watchInput(target, () => {
|
|
262
|
+
entry.refresh();
|
|
263
|
+
});
|
|
264
|
+
} catch {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
return {
|
|
269
|
+
id,
|
|
270
|
+
entry
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function getRegisteredVirtualModule(filename) {
|
|
274
|
+
for (const entry of registry.values()) if (entry.virtualPath === filename) return entry;
|
|
275
|
+
}
|
|
276
|
+
async function getRegisteredManifest(id) {
|
|
277
|
+
const registered = registry.get(id);
|
|
278
|
+
if (!registered) return;
|
|
279
|
+
await waitForCurrentRefresh(registered);
|
|
280
|
+
return registered.manifest;
|
|
281
|
+
}
|
|
282
|
+
/** 等待并读取由 Metro 配置注册的 manifest 文件,兼容未透传自定义 Metro id 的 transformer。 */
|
|
283
|
+
async function getRegisteredManifestByPath(filename) {
|
|
284
|
+
for (const entry of registry.values()) if (entry.manifestPath === filename) {
|
|
285
|
+
await waitForCurrentRefresh(entry);
|
|
286
|
+
return entry.manifest;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/** 按 Metro 传入的项目根目录读取当前注册项,兼容 transformer 未透传自定义字段的实现。 */
|
|
290
|
+
async function getRegisteredManifestByProjectRoot(projectRoot) {
|
|
291
|
+
const resolvedRoot = path.resolve(projectRoot);
|
|
292
|
+
const entry = [...registry.values()].filter((entry) => entry.projectRoot === resolvedRoot).at(-1);
|
|
293
|
+
if (!entry) return;
|
|
294
|
+
await waitForCurrentRefresh(entry);
|
|
295
|
+
return entry.manifest;
|
|
296
|
+
}
|
|
297
|
+
function getVirtualModuleCode(filename) {
|
|
298
|
+
const registered = getRegisteredVirtualModule(filename);
|
|
299
|
+
if (!registered) return;
|
|
300
|
+
return virtualModuleCode(registered.manifest);
|
|
301
|
+
}
|
|
302
|
+
async function getVirtualModuleCodeAsync(filename) {
|
|
303
|
+
const registered = getRegisteredVirtualModule(filename);
|
|
304
|
+
if (!registered) return;
|
|
305
|
+
await waitForCurrentRefresh(registered);
|
|
306
|
+
return getVirtualModuleCode(filename);
|
|
307
|
+
}
|
|
308
|
+
function withWeappTailwindcss(config, options = {}) {
|
|
309
|
+
if (typeof config === "function" || config && typeof config.then === "function") return Promise.resolve(typeof config === "function" ? config() : config).then((resolved) => withWeappTailwindcss(resolved, options));
|
|
310
|
+
const resolvedConfig = config;
|
|
311
|
+
const { id, entry } = register(options);
|
|
312
|
+
const originalResolver = resolvedConfig.resolver?.resolveRequest;
|
|
313
|
+
const sourceExts = resolvedConfig.resolver?.sourceExts ?? [];
|
|
314
|
+
const virtualResolver = (context, moduleName, platform) => {
|
|
315
|
+
if (moduleName === "@weapp-tailwindcss/react-native/virtual") return {
|
|
316
|
+
type: "sourceFile",
|
|
317
|
+
filePath: entry.virtualPath
|
|
318
|
+
};
|
|
319
|
+
const appRootSingleton = resolveAppRootSingleton(entry.projectRoot, moduleName, platform);
|
|
320
|
+
if (appRootSingleton) return appRootSingleton;
|
|
321
|
+
const resolverContext = context;
|
|
322
|
+
const anchoredContext = resolverContext.originModulePath === entry.virtualPath || shouldResolveFromAppRoot(moduleName, platform) ? {
|
|
323
|
+
...resolverContext,
|
|
324
|
+
originModulePath: path.join(entry.projectRoot, "package.json")
|
|
325
|
+
} : resolverContext;
|
|
326
|
+
return originalResolver?.(anchoredContext, moduleName, platform) ?? resolverContext.resolveRequest?.(anchoredContext, moduleName, platform) ?? resolveAppRootSingleton(entry.projectRoot, moduleName, platform);
|
|
327
|
+
};
|
|
328
|
+
return {
|
|
329
|
+
...resolvedConfig,
|
|
330
|
+
watchFolders: [.../* @__PURE__ */ new Set([...resolvedConfig.watchFolders ?? [], path.dirname(entry.virtualPath)])],
|
|
331
|
+
transformerPath: fileURLToPath(new URL(import.meta.url.includes(".ts") ? "./metro-transformer.ts" : "./metro-transformer.js", import.meta.url)),
|
|
332
|
+
transformer: {
|
|
333
|
+
...resolvedConfig.transformer,
|
|
334
|
+
weappTailwindcssMetroId: id,
|
|
335
|
+
weappTailwindcssOriginalTransformerPath: resolvedConfig.transformerPath,
|
|
336
|
+
weappTailwindcssManifestPath: entry.manifestPath,
|
|
337
|
+
weappTailwindcssManifestReadyPath: entry.manifestReadyPath,
|
|
338
|
+
weappTailwindcssVirtualModulePath: entry.virtualPath
|
|
339
|
+
},
|
|
340
|
+
resolver: {
|
|
341
|
+
...resolvedConfig.resolver,
|
|
342
|
+
extraNodeModules: {
|
|
343
|
+
...resolvedConfig.resolver?.extraNodeModules,
|
|
344
|
+
"react": path.resolve(entry.projectRoot, "node_modules/react"),
|
|
345
|
+
"react-dom": path.resolve(entry.projectRoot, "node_modules/react-dom")
|
|
346
|
+
},
|
|
347
|
+
sourceExts: sourceExts.includes("css") ? sourceExts : [...sourceExts, "css"],
|
|
348
|
+
resolveRequest: virtualResolver
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
//#endregion
|
|
353
|
+
export { getRegisteredManifestByProjectRoot as a, getVirtualModuleCodeAsync as c, waitForCurrentRefresh as d, readPublishedSnapshot as f, getRegisteredManifestByPath as i, withWeappTailwindcss as l, getManifestPathsForProjectRoot as n, getRegisteredVirtualModule as o, getRegisteredManifest as r, getVirtualModuleCode as s, VIRTUAL_MANIFEST_MODULE as t, virtualModuleCode as u };
|