weapp-tailwindcss
Version:
把 tailwindcss 原子化样式思想,带给小程序开发者们! bring tailwindcss to miniprogram developers!
1,174 lines • 52.7 kB
JavaScript
const require_rolldown_runtime = require("./rolldown-runtime-CVvi-lCc.cjs");
const require_framework = require("./framework.cjs");
const require_generator = require("./generator-BE34PYSC.cjs");
const require_options = require("./options-hVsoTfwL.cjs");
require("./utils-CuKLf1Zv.cjs");
const require_wxml = require("./wxml-DSMNuUaP.cjs");
const require_defaults = require("./defaults.cjs");
const require_tailwindcss = require("./tailwindcss-DcpiKvmJ.cjs");
const require_style_options = require("./style-options-B_ppaVIg.cjs");
let node_path = require("node:path");
node_path = require_rolldown_runtime.__toESM(node_path, 1);
let node_process = require("node:process");
node_process = require_rolldown_runtime.__toESM(node_process, 1);
let _tailwindcss_mangle_engine = require("@tailwindcss-mangle/engine");
let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
let lru_cache = require("lru-cache");
let node_module = require("node:module");
let node_fs_promises = require("node:fs/promises");
let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
let node_buffer = require("node:buffer");
let _weapp_tailwindcss_shared_node = require("@weapp-tailwindcss/shared/node");
let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
//#region src/cache/index.ts
function isProcessResult(value) {
return typeof value === "object" && value !== null && "result" in value;
}
function createCache(options) {
const disabled = options === false;
const hashMap = /* @__PURE__ */ new Map();
const instance = new lru_cache.LRUCache({
max: 1024,
ttl: 0,
ttlAutopurge: false
});
const cache = {
hashMap,
instance,
hasHashKey(key) {
return hashMap.has(key);
},
getHashValue(key) {
return hashMap.get(key);
},
setHashValue(key, value) {
return hashMap.set(key, value);
},
get(key) {
return instance.get(key);
},
set(key, value) {
return instance.set(key, value);
},
computeHash(message) {
return (0, _weapp_tailwindcss_shared_node.md5)(message);
},
calcHashValueChanged(key, hash) {
const hit = hashMap.get(key);
if (hit) hashMap.set(key, {
changed: hash !== hit.hash,
hash
});
else hashMap.set(key, {
changed: true,
hash
});
return cache;
},
pruneHashKeys(hashKeys) {
const activeHashKeys = new Set(hashKeys);
for (const key of hashMap.keys()) if (!activeHashKeys.has(key)) hashMap.delete(key);
},
prune(options) {
if (options.cacheKeys) {
const cacheKeys = new Set(options.cacheKeys);
for (const key of instance.keys()) if (!cacheKeys.has(key)) instance.delete(key);
}
if (options.hashKeys) cache.pruneHashKeys?.(options.hashKeys);
},
has(key) {
return instance.has(key);
},
async process({ key, hashKey, rawSource, hash, resolveCache, transform, onCacheHit }) {
if (disabled) {
const value = await transform();
return isProcessResult(value) ? value.result : value;
}
const cacheHashKey = hashKey ?? key;
let hasChanged = true;
if (hash != null || rawSource != null) {
const nextHash = hash ?? cache.computeHash(rawSource);
cache.calcHashValueChanged(cacheHashKey, nextHash);
hasChanged = cache.getHashValue(cacheHashKey)?.changed ?? true;
}
const readCache = resolveCache ?? (() => cache.get(key));
if (!hasChanged) {
const cached = readCache();
if (cached !== void 0) {
await onCacheHit?.(cached);
return cached;
}
}
const value = await transform();
const normalized = isProcessResult(value) ? value : { result: value };
const stored = normalized.cacheValue ?? normalized.result;
cache.set(key, stored);
return normalized.result;
}
};
return cache;
}
function initializeCache(cacheConfig) {
if (typeof cacheConfig === "boolean" || cacheConfig === void 0) return createCache(cacheConfig);
return cacheConfig;
}
//#endregion
//#region src/framework/platform.ts
const MPX_TO_UNI_PLATFORM = {
ali: "mp-alipay",
dd: "mp-dingtalk",
jd: "mp-jd",
qq: "mp-qq",
swan: "mp-baidu",
tt: "mp-toutiao",
wx: "mp-weixin"
};
function normalizeFrameworkStylePlatform(platform, appType) {
const normalized = platform?.trim().toLowerCase();
if (!normalized) return;
if (appType === "mpx") return MPX_TO_UNI_PLATFORM[normalized] ?? normalized;
return normalized;
}
//#endregion
//#region src/tailwindcss/runtime.ts
const debug = require_wxml.createDebug("[tailwindcss:runtime] ");
const refreshTailwindcssRuntimeSymbol = Symbol.for("weapp-tailwindcss.refreshTailwindcssRuntime");
function createTailwindRuntimeReadyPromise(tailwindRuntime) {
return Promise.resolve().then(async () => {
require_tailwindcss.invalidateRuntimeClassSet(tailwindRuntime);
});
}
const runtimeClassSetStateCache = /* @__PURE__ */ new WeakMap();
function getRuntimeClassSetStateEntry(state) {
let entry = runtimeClassSetStateCache.get(state);
if (!entry) {
entry = {};
runtimeClassSetStateCache.set(state, entry);
}
return entry;
}
function getTailwindRuntime(state) {
return state.tailwindRuntime;
}
function setTailwindRuntime(state, runtime) {
state.tailwindRuntime = runtime;
}
function getRefreshTailwindRuntime(state) {
return state.refreshTailwindcssRuntime;
}
async function refreshTailwindRuntimeState(state, forceOrOptions) {
const normalizedOptions = typeof forceOrOptions === "boolean" ? { force: forceOrOptions } : forceOrOptions;
const force = normalizedOptions.force;
const clearCache = normalizedOptions.clearCache === true;
if (!force) return false;
const currentRuntime = getTailwindRuntime(state);
debug("refresh runtime state start, clearCache=%s major=%s", clearCache, currentRuntime.majorVersion ?? "unknown");
await state.readyPromise;
let refreshed = false;
const refreshTailwindRuntime = getRefreshTailwindRuntime(state);
if (typeof refreshTailwindRuntime === "function") {
const next = await refreshTailwindRuntime({ clearCache });
if (next !== getTailwindRuntime(state)) setTailwindRuntime(state, next);
refreshed = true;
}
if (refreshed) state.readyPromise = createTailwindRuntimeReadyPromise(getTailwindRuntime(state));
debug("refresh runtime state end, refreshed=%s major=%s", refreshed, getTailwindRuntime(state).majorVersion ?? "unknown");
return refreshed;
}
async function ensureRuntimeClassSet(state, options = {}) {
const forceRefresh = options.forceRefresh === true;
const forceCollect = options.forceCollect === true;
const clearCache = options.clearCache === true;
const allowEmpty = options.allowEmpty === true;
if (forceRefresh) await refreshTailwindRuntimeState(state, {
force: true,
clearCache
});
await state.readyPromise;
const entry = getRuntimeClassSetStateEntry(state);
const signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
const signatureChanged = entry.signature !== signature;
const shouldForceCollect = forceCollect || forceRefresh || signatureChanged;
if (!shouldForceCollect) {
if (entry.value && (allowEmpty || entry.value.size > 0)) return entry.value;
if (entry.promise) return entry.promise;
}
const task = (async () => {
const collected = await collectRuntimeClassSet(getTailwindRuntime(state), {
force: shouldForceCollect,
skipRefresh: true,
clearCache
});
if (allowEmpty || collected.size > 0) return collected;
await refreshTailwindRuntimeState(state, {
force: true,
clearCache: true
});
await state.readyPromise;
return collectRuntimeClassSet(getTailwindRuntime(state), {
force: true,
skipRefresh: true,
clearCache: true
});
})();
entry.promise = task;
try {
const runtimeSet = await task;
entry.value = runtimeSet;
entry.signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
return runtimeSet;
} finally {
if (entry.promise === task) entry.promise = void 0;
}
}
function tryGetRuntimeClassSetSync(tailwindRuntime) {
if (typeof tailwindRuntime.getClassSetSync !== "function") return;
try {
const set = tailwindRuntime.getClassSetSync();
if (set && set.size === 0) return;
return set;
} catch (error) {
debug("getClassSetSync() unavailable for tailwindcss v4, fallback to async getClassSet(): %O", error);
return;
}
}
async function collectTailwindV4GeneratorClassSet(tailwindRuntime) {
if (typeof tailwindRuntime.collectContentTokens !== "function") return;
try {
const source = require_generator.resolveCssMacroTailwindV4Source(await require_generator.resolveTailwindV4SourceFromRuntime(tailwindRuntime));
const generated = await require_generator.createTailwindV4Engine(source).generate({
scanSources: true,
target: "web"
});
const classSet = (0, _tailwindcss_mangle_engine.resolveValidTailwindV4Candidates)(await (0, _tailwindcss_mangle_engine.loadTailwindV4DesignSystem)(source), generated.classSet, { ...source.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: source.bareArbitraryValues } });
debug("runtime class set resolved via tailwindcss v4 generator source scan, raw=%d valid=%d", generated.classSet.size, classSet.size);
return classSet;
} catch (error) {
debug("tailwindcss v4 generator source scan failed, continuing fallback chain: %O", error);
return;
}
}
async function mergeTailwindV4GeneratorClassSet(tailwindRuntime, classSet) {
const generatorClassSet = await collectTailwindV4GeneratorClassSet(tailwindRuntime).catch(() => void 0);
if (!generatorClassSet || generatorClassSet.size === 0) return classSet;
return /* @__PURE__ */ new Set([...classSet, ...generatorClassSet]);
}
async function collectRuntimeClassSet(tailwindRuntime, options = {}) {
let activeRuntime = tailwindRuntime;
if (options.force && !options.skipRefresh) {
const refresh = activeRuntime[refreshTailwindcssRuntimeSymbol];
if (typeof refresh === "function") try {
const refreshed = await refresh({ clearCache: options.clearCache === true });
if (refreshed) activeRuntime = refreshed;
} catch (error) {
debug("refreshTailwindcssRuntime failed, continuing with existing runtime: %O", error);
}
}
const entry = require_tailwindcss.getRuntimeClassSetCacheEntry(activeRuntime);
const signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(activeRuntime);
if (!options.force) {
if (entry.value && entry.signature === signature) return entry.value;
if (entry.promise) return entry.promise;
} else entry.value = void 0;
const task = (async () => {
const preferExtract = options.force === true;
try {
const result = await activeRuntime.extract({ write: false });
if (result?.classSet) {
if (result.classSet.size > 0) {
const merged = await mergeTailwindV4GeneratorClassSet(activeRuntime, result.classSet);
debug("runtime class set resolved via extract() + tailwindcss v4 source scan, extract=%d merged=%d", result.classSet.size, merged.size);
return merged;
}
if (preferExtract) debug("runtime class set from extract() is empty on force collect, fallback to generator/sync/async class set");
else debug("runtime class set from extract() is empty, fallback to sync/async class set");
}
} catch (error) {
debug("extract() failed, fallback to getClassSet(): %O", error);
}
const generatorClassSet = await collectTailwindV4GeneratorClassSet(activeRuntime);
if (generatorClassSet && generatorClassSet.size > 0) return generatorClassSet;
const syncSet = tryGetRuntimeClassSetSync(activeRuntime);
if (syncSet) {
debug("runtime class set resolved via getClassSetSync(), size=%d", syncSet.size);
return syncSet;
}
try {
const fallbackSet = await Promise.resolve(activeRuntime.getClassSet());
if (fallbackSet) {
debug("runtime class set resolved via getClassSet(), size=%d", fallbackSet.size);
return fallbackSet;
}
} catch (error) {
debug("getClassSet() failed, returning empty set: %O", error);
}
return /* @__PURE__ */ new Set();
})();
entry.promise = task;
entry.signature = signature;
try {
const resolved = await task;
entry.value = resolved;
entry.promise = void 0;
entry.signature = signature;
return resolved;
} catch (error) {
entry.promise = void 0;
throw error;
}
}
//#endregion
//#region src/tailwindcss/runtime-logs.ts
const runtimeLogDedupeHolder = globalThis;
const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
function createRuntimeLogKey(category, baseDir, rootPath, version) {
return JSON.stringify([
category,
baseDir ?? node_process.default.cwd(),
rootPath ?? "",
version ?? ""
]);
}
function markRuntimeLog(category, baseDir, rootPath, version) {
const key = createRuntimeLogKey(category, baseDir, rootPath, version);
if (runtimeLogDedupe.has(key)) return false;
runtimeLogDedupe.add(key);
return true;
}
function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
const versionText = version ? ` (v${version})` : "";
_weapp_tailwindcss_logger.logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
}
function logRuntimeTailwindcssVersion(baseDir, rootPath, version) {
if (version) {
if (!markRuntimeLog("version", baseDir, rootPath, version)) return;
_weapp_tailwindcss_logger.logger.success(`当前使用 ${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 版本为: ${_weapp_tailwindcss_logger.pc.underline(_weapp_tailwindcss_logger.pc.bold(_weapp_tailwindcss_logger.pc.green(version)))}`);
return;
}
if (!markRuntimeLog("missing", baseDir, rootPath, version)) return;
_weapp_tailwindcss_logger.logger.warn(`${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 未安装,已跳过版本检测与运行时初始化。`);
}
//#endregion
//#region src/tailwindcss/targets.ts
function formatRelativeToBase(targetPath, baseDir) {
const normalized = node_path.default.normalize(targetPath);
if (!baseDir) return normalized.replace(/\\/g, "/");
const relative = node_path.default.relative(baseDir, normalized);
if (!relative || relative === ".") return ".";
if (relative.startsWith("..")) return normalized.replace(/\\/g, "/");
return node_path.default.join(".", relative).replace(/\\/g, "/");
}
function logTailwindcssTarget(tailwindRuntime, baseDir) {
const packageInfo = tailwindRuntime?.packageInfo;
const label = "Weapp-tailwindcss";
if (!packageInfo?.rootPath) {
_weapp_tailwindcss_logger.logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? node_process.default.cwd());
return;
}
const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
_weapp_tailwindcss_logger.logger.debug("%s 解析 Tailwind CSS -> %s%s", label, displayPath, version);
}
//#endregion
//#region src/unocss/index.ts
function normalizeUnocssOptions(unocss) {
return require_generator.resolveBooleanObjectOption(unocss, {});
}
function resolveUnocssBareArbitraryValues(arbitraryValues, unocss) {
const baseArbitraryValues = arbitraryValues ?? {};
const options = normalizeUnocssOptions(unocss);
if (!options) return baseArbitraryValues;
if (baseArbitraryValues.bareArbitraryValues !== void 0 && baseArbitraryValues.bareArbitraryValues !== false) return baseArbitraryValues;
const bareArbitraryValues = options.bareArbitraryValues ?? true;
if (bareArbitraryValues === false) return baseArbitraryValues;
return {
...baseArbitraryValues,
bareArbitraryValues
};
}
//#endregion
//#region src/context/compiler-context-cache.ts
const PAREN_CONTENT_RE = /\(([^)]+)\)/u;
const AT_LOCATION_RE = /at\s+(\S.*)$/u;
const TRAILING_LINE_COL_RE = /:\d+(?::\d+)?$/u;
const DEFAULT_COMPILER_CONTEXT_CACHE_MAX = 32;
const DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX = DEFAULT_COMPILER_CONTEXT_CACHE_MAX * 2;
const globalCacheHolder = globalThis;
const compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
const compilerContextKeyCacheByOptions = /* @__PURE__ */ new WeakMap();
const compilerContextKeyCacheWithoutOptions = /* @__PURE__ */ new Map();
function resolveCompilerContextCacheMax(defaultValue) {
const raw = Number.parseInt(node_process.default.env["WEAPP_TW_COMPILER_CONTEXT_CACHE_MAX"] ?? "", 10);
if (!Number.isFinite(raw) || raw <= 0) return defaultValue;
return Math.floor(raw);
}
function touchMapValue(map, key, value) {
map.delete(key);
map.set(key, value);
}
function pruneMapToMaxSize(map, maxSize) {
while (map.size > maxSize) {
const firstKey = map.keys().next().value;
if (firstKey === void 0) break;
map.delete(firstKey);
}
}
function withCircularGuard(value, stack, factory) {
if (stack.has(value)) throw new TypeError("Cannot serialize circular structure in compiler context options");
stack.add(value);
try {
return factory();
} finally {
stack.delete(value);
}
}
function encodeTaggedValue(type, value) {
const record = { __type: type };
if (value !== void 0) record["value"] = value;
return record;
}
function hasExplicitOptionBasedir(opts) {
return typeof opts?.tailwindcssBasedir === "string" && opts.tailwindcssBasedir.length > 0;
}
function shouldProbeCallerLocation(opts) {
if (hasExplicitOptionBasedir(opts)) return false;
return !(node_process.default.env["WEAPP_TAILWINDCSS_BASEDIR"] || node_process.default.env["WEAPP_TAILWINDCSS_BASE_DIR"] || node_process.default.env["TAILWINDCSS_BASEDIR"] || node_process.default.env["TAILWINDCSS_BASE_DIR"]);
}
function detectCallerLocation() {
const stack = (/* @__PURE__ */ new Error("compiler-context-cache stack probe")).stack;
if (!stack) return;
const lines = stack.split("\n");
for (const line of lines) {
const location = (line.match(PAREN_CONTENT_RE) ?? line.match(AT_LOCATION_RE))?.[1];
if (!location) continue;
const candidatePath = location.replace(TRAILING_LINE_COL_RE, "");
if (!candidatePath || !node_path.default.isAbsolute(candidatePath)) continue;
if (candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}src${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}dist${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}node_modules${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}`)) continue;
return candidatePath;
}
}
function getRuntimeCacheScope(opts) {
if (hasExplicitOptionBasedir(opts)) return { caller: void 0 };
const runtimeScope = {
caller: void 0,
cwd: node_process.default.cwd(),
init_cwd: node_process.default.env["INIT_CWD"],
npm_config_local_prefix: node_process.default.env["npm_config_local_prefix"],
npm_package_json: node_process.default.env["npm_package_json"],
pnpm_package_name: node_process.default.env["PNPM_PACKAGE_NAME"],
pwd: node_process.default.env["PWD"],
tailwindcss_base_dir: node_process.default.env["TAILWINDCSS_BASE_DIR"],
tailwindcss_basedir: node_process.default.env["TAILWINDCSS_BASEDIR"],
uni_app_input_dir: node_process.default.env["UNI_APP_INPUT_DIR"],
uni_cli_root: node_process.default.env["UNI_CLI_ROOT"],
uni_input_dir: node_process.default.env["UNI_INPUT_DIR"],
uni_input_root: node_process.default.env["UNI_INPUT_ROOT"],
weapp_tailwindcss_base_dir: node_process.default.env["WEAPP_TAILWINDCSS_BASE_DIR"],
weapp_tailwindcss_basedir: node_process.default.env["WEAPP_TAILWINDCSS_BASEDIR"]
};
if (shouldProbeCallerLocation(opts)) runtimeScope.caller = detectCallerLocation();
return runtimeScope;
}
function serializeNormalizedValue(value) {
return JSON.stringify(value);
}
function createRuntimeCacheScopeKey(opts) {
return serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScope(opts)));
}
function getCompilerContextKeyCacheStore(opts) {
if (!opts) return compilerContextKeyCacheWithoutOptions;
let store = compilerContextKeyCacheByOptions.get(opts);
if (!store) {
store = /* @__PURE__ */ new Map();
compilerContextKeyCacheByOptions.set(opts, store);
}
return store;
}
function createComparableNormalizedValue(rawValue, stack) {
const normalized = normalizeOptionsValue(rawValue, stack);
return {
normalized,
sortKey: serializeNormalizedValue(normalized)
};
}
function getRuntimeCacheScopeValue(opts) {
return {
options: opts ?? {},
runtime: getRuntimeCacheScope(opts)
};
}
function normalizeOptionsValue(rawValue, stack = /* @__PURE__ */ new WeakSet()) {
if (rawValue === null) return null;
if (rawValue === void 0) return encodeTaggedValue("Undefined");
const type = typeof rawValue;
if (type === "string") return rawValue;
if (type === "boolean") return rawValue;
if (type === "number") {
const numericValue = rawValue;
if (Number.isNaN(numericValue)) return encodeTaggedValue("Number", "NaN");
if (!Number.isFinite(numericValue)) return encodeTaggedValue("Number", numericValue > 0 ? "Infinity" : "-Infinity");
if (Object.is(numericValue, -0)) return encodeTaggedValue("Number", "-0");
return numericValue;
}
if (type === "bigint") return encodeTaggedValue("BigInt", rawValue.toString());
if (type === "symbol") {
const symbolValue = rawValue;
return encodeTaggedValue("Symbol", symbolValue.description ?? String(symbolValue));
}
if (type === "function") return encodeTaggedValue("Function", rawValue.toString());
if (Array.isArray(rawValue)) return withCircularGuard(rawValue, stack, () => rawValue.map((item) => normalizeOptionsValue(item, stack)));
if (rawValue instanceof Date) return encodeTaggedValue("Date", rawValue.toISOString());
if (rawValue instanceof RegExp) return {
__type: "RegExp",
source: rawValue.source,
flags: rawValue.flags
};
if (typeof node_buffer.Buffer !== "undefined" && node_buffer.Buffer.isBuffer(rawValue)) return encodeTaggedValue("Buffer", rawValue.toString("base64"));
if (ArrayBuffer.isView(rawValue)) {
const view = rawValue;
const buffer = node_buffer.Buffer.from(view.buffer, view.byteOffset, view.byteLength);
return encodeTaggedValue(view.constructor?.name ?? "ArrayBufferView", buffer.toString("base64"));
}
if (rawValue instanceof ArrayBuffer) return encodeTaggedValue("ArrayBuffer", node_buffer.Buffer.from(rawValue).toString("base64"));
if (rawValue instanceof Set) return withCircularGuard(rawValue, stack, () => {
const normalizedEntries = Array.from(rawValue, (element) => createComparableNormalizedValue(element, stack));
normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
return {
__type: "Set",
value: normalizedEntries.map((entry) => entry.normalized)
};
});
if (rawValue instanceof Map) return withCircularGuard(rawValue, stack, () => {
const normalizedEntries = Array.from(rawValue.entries(), ([key, entryValue]) => {
const normalizedKey = createComparableNormalizedValue(key, stack);
return {
key: normalizedKey.normalized,
sortKey: normalizedKey.sortKey,
value: normalizeOptionsValue(entryValue, stack)
};
});
normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
return {
__type: "Map",
value: normalizedEntries.map((entry) => [entry.key, entry.value])
};
});
if (typeof URL !== "undefined" && rawValue instanceof URL) return encodeTaggedValue("URL", rawValue.toString());
if (rawValue instanceof Error) {
const errorValue = rawValue;
return {
__type: "Error",
name: errorValue.name,
message: errorValue.message,
stack: errorValue.stack ?? ""
};
}
if (rawValue instanceof Promise) return encodeTaggedValue("Promise");
if (rawValue instanceof WeakMap) return encodeTaggedValue("WeakMap");
if (rawValue instanceof WeakSet) return encodeTaggedValue("WeakSet");
if (rawValue && typeof rawValue === "object") return withCircularGuard(rawValue, stack, () => {
const result = {};
const entries = Object.entries(rawValue);
entries.sort(([a], [b]) => a.localeCompare(b));
for (const [key, entryValue] of entries) result[key] = normalizeOptionsValue(entryValue, stack);
return result;
});
return encodeTaggedValue(typeof rawValue, String(rawValue));
}
function createCompilerContextCacheKey(opts) {
try {
const runtimeCacheScopeKey = createRuntimeCacheScopeKey(opts);
const keyStore = getCompilerContextKeyCacheStore(opts);
const cached = keyStore.get(runtimeCacheScopeKey);
if (cached !== void 0) return cached;
const cacheKey = (0, _weapp_tailwindcss_shared_node.md5)(serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScopeValue(opts))));
touchMapValue(keyStore, runtimeCacheScopeKey, cacheKey);
pruneMapToMaxSize(keyStore, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX));
return cacheKey;
} catch (error) {
_weapp_tailwindcss_logger.logger.debug("skip compiler context cache: %O", error);
return;
}
}
function withCompilerContextCache(opts, factory) {
const cacheKey = createCompilerContextCacheKey(opts);
if (cacheKey) {
const cached = compilerContextCache.get(cacheKey);
if (cached) {
touchMapValue(compilerContextCache, cacheKey, cached);
return cached;
}
}
const ctx = factory();
if (cacheKey) {
touchMapValue(compilerContextCache, cacheKey, ctx);
pruneMapToMaxSize(compilerContextCache, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_CACHE_MAX));
}
return ctx;
}
//#endregion
//#region src/context/custom-attributes.ts
function toCustomAttributesEntities(customAttributes) {
if (!customAttributes) return [];
if ((0, _weapp_tailwindcss_shared.isMap)(customAttributes)) return [...customAttributes.entries()];
return Object.entries(customAttributes);
}
//#endregion
//#region src/js/literal-transform.ts
function transformLiteralText(literal, options) {
const fallbackEnabled = require_wxml.shouldEnableArbitraryValueFallback(options);
if (!options.alwaysEscape && !fallbackEnabled && (!options.classNameSet || options.classNameSet.size === 0)) return;
const source = options.unescapeUnicode && literal.includes("\\u") ? require_wxml.decodeUnicode2(literal) : literal;
const candidates = (0, _tailwindcss_mangle_engine.splitCandidateTokens)(source);
if (candidates.length === 0) return;
const transformOptions = {
...options,
classContext: true
};
const replacementCache = require_wxml.getReplacementCacheStore(options.escapeMap);
let transformed = source;
let mutated = false;
for (const candidate of candidates) {
const result = require_wxml.resolveClassNameTransformWithResult(candidate, transformOptions);
if (result.decision === "skip" || !transformed.includes(candidate)) continue;
const replacement = result.decision === "escaped" && result.escapedValue ? result.escapedValue : require_wxml.getReplacement(candidate, options.escapeMap, replacementCache);
const replaced = transformed.replace(candidate, replacement);
if (replaced !== transformed) {
transformed = replaced;
mutated = true;
}
}
return mutated ? transformed : void 0;
}
//#endregion
//#region src/js/fast-path/oxc.ts
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
let oxcParser;
let oxcWalker;
function isOxcParserRuntimeSupported(version = node_process.default.versions.node) {
const match = /^(\d+)\.(\d+)(?:\.|$)/.exec(version);
if (!match) return false;
const major = Number(match[1]);
const minor = Number(match[2]);
if (major === 20) return minor >= 19;
if (major === 21) return false;
if (major === 22) return minor >= 12;
return major > 22;
}
function loadOxcParser() {
if (!isOxcParserRuntimeSupported()) return;
if (oxcParser === false) return;
if (oxcParser) return oxcParser;
try {
oxcParser = require$1("oxc-parser");
} catch {
oxcParser = false;
return;
}
return oxcParser;
}
function loadOxcWalker() {
if (!isOxcParserRuntimeSupported()) return;
if (oxcWalker === false) return;
if (oxcWalker) return oxcWalker;
try {
oxcWalker = require$1("oxc-walker");
} catch {
oxcWalker = false;
return;
}
return oxcWalker;
}
function hasValues(values) {
return Array.isArray(values) && values.length > 0;
}
function hasUnsupportedSourceMarker(rawSource) {
return rawSource.includes("eval(") || rawSource.includes("weapp-tw") && rawSource.includes("ignore");
}
function hasSupportedClassMatchSource(options) {
return options.alwaysEscape === true || Boolean(options.classNameSet && options.classNameSet.size > 0);
}
function canAttemptOxcJsFastPath(options) {
if (options.experimentalJsFastPath !== true && options.experimentalJsFastPath !== "oxc") return false;
return !options.generateMap && !options.wrapExpression && !options.moduleGraph && !options.moduleSpecifierReplacements && hasSupportedClassMatchSource(options) && !require_wxml.shouldEnableArbitraryValueFallback(options) && !hasValues(options.ignoreCallExpressionIdentifiers);
}
function getParserLang(filename) {
if (filename?.endsWith(".ts") || filename?.endsWith(".mts") || filename?.endsWith(".cts")) return "ts";
if (filename?.endsWith(".tsx")) return "tsx";
if (filename?.endsWith(".jsx")) return "jsx";
return "js";
}
function getParserSourceType(sourceType) {
return sourceType === "script" || sourceType === "module" ? sourceType : "module";
}
function isRangeValid(start, end) {
return typeof start === "number" && typeof end === "number" && start < end;
}
function getMagicString(rawSource, context) {
if (!context.ms) context.ms = new require_wxml.MagicString(rawSource);
return context.ms;
}
function addStringLiteralReplacement(rawSource, node, transformOptions, context) {
if (typeof node.value !== "string" || typeof node.raw !== "string" || !isRangeValid(node.start, node.end)) return false;
const transformed = transformLiteralText(node.value, transformOptions);
if (!transformed) return false;
const start = node.start + 1;
const end = node.end - 1;
if (start >= end || transformed === rawSource.slice(start, end)) return false;
getMagicString(rawSource, context).update(start, end, require_wxml.jsStringEscape(transformed));
return true;
}
function addTemplateElementReplacement(rawSource, node, transformOptions, context) {
const raw = node.value?.raw;
if (typeof raw !== "string" || !isRangeValid(node.start, node.end)) return false;
const transformed = transformLiteralText(raw, transformOptions);
if (!transformed || transformed === raw) return false;
const first = rawSource[node.start];
const last = rawSource[node.end - 1];
const start = node.start + (first === "`" || first === "}" ? 1 : 0);
const end = node.end - (last === "`" ? 1 : last === "{" ? 2 : 0);
if (start >= end) return false;
getMagicString(rawSource, context).update(start, end, transformed);
return true;
}
function applyReplacements(rawSource, program, walker, stringLiteralOptions, templateLiteralOptions, context) {
let changed = false;
walker.walk(program, { enter(node) {
if (node.type === "Literal") {
changed = addStringLiteralReplacement(rawSource, node, stringLiteralOptions, context) || changed;
return;
}
if (node.type === "TemplateElement") {
changed = addTemplateElementReplacement(rawSource, node, templateLiteralOptions, context) || changed;
this.skip();
}
} });
return changed;
}
function hasTaggedTemplateExpression(program, walker) {
let found = false;
walker.walk(program, { enter(node) {
if (node.type === "TaggedTemplateExpression") {
found = true;
this.skip();
}
} });
return found;
}
function oxcJsHandler(rawSource, options) {
if (!canAttemptOxcJsFastPath(options)) return;
if (hasUnsupportedSourceMarker(rawSource)) return;
const parser = loadOxcParser();
const walker = loadOxcWalker();
if (!parser || !walker) return;
let result;
try {
result = parser.parseSync(options.filename ?? "weapp-tailwindcss.js", rawSource, {
sourceType: getParserSourceType(options.babelParserOptions?.sourceType),
lang: getParserLang(options.filename)
});
} catch {
return;
}
if (!result.program || Array.isArray(result.errors) && result.errors.length > 0) return;
if (hasValues(options.ignoreTaggedTemplateExpressionIdentifiers) && hasTaggedTemplateExpression(result.program, walker)) return;
const stringLiteralOptions = options.needEscaped === true ? options : {
...options,
needEscaped: true
};
const templateLiteralOptions = options.needEscaped === false ? options : {
...options,
needEscaped: false
};
const replacementContext = {};
if (!applyReplacements(rawSource, result.program, walker, stringLiteralOptions, templateLiteralOptions, replacementContext)) return { code: rawSource };
return { code: replacementContext.ms.toString() };
}
//#endregion
//#region src/js/precheck.ts
/** 用于检测源码中是否包含类名相关模式的正则表达式 */
const FAST_JS_TRANSFORM_HINT_RE = /className\b|class\s*=|classList\.|\b(?:twMerge|clsx|classnames|cn|cva)\b|\[["'`]class["'`]\]|text-\[|bg-\[|\b(?:[whpm]|px|py|mx|my|rounded|flex|grid|gap)-/;
/** 用于检测源码中是否包含 import/export/require 语句的正则表达式 */
const DEPENDENCY_HINT_RE = /\bimport\s*(?:["'`{]|\*\s+as\b)|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
/**
* 判断源码是否可能声明跨模块依赖。
*
* 该检查只作为性能预筛:返回 `true` 时必须保守走 AST 模块图分析;
* 返回 `false` 时源码中没有可被当前模块图消费的静态 import/export/require 形态。
*/
function hasDependencyHint(rawSource) {
return DEPENDENCY_HINT_RE.test(rawSource);
}
/**
* 判断是否可以跳过 JS 转换。
* 通过正则快速检测源码内容,避免不必要的 Babel AST 解析。
*
* @param rawSource - 原始 JS 源码字符串
* @param options - 可选的 JS 处理器配置选项
* @returns 如果可以跳过转换返回 `true`,否则返回 `false`
*/
function shouldSkipJsTransform(rawSource, options) {
if (node_process.default.env["WEAPP_TW_DISABLE_JS_PRECHECK"] === "1") return false;
if (!rawSource) return true;
if (options?.alwaysEscape) return false;
if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return false;
if (options?.wrapExpression) return false;
if (hasDependencyHint(rawSource)) return false;
return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
}
//#endregion
//#region src/js/index.ts
/** 默认 LRU 缓存最大条目数 */
const RESULT_CACHE_MAX = 512;
/** 仅对短片段做内层结果缓存,避免 bundler 热路径重复 hash 大块 JS。 */
const CACHEABLE_SOURCE_MAX_LENGTH = 512;
/** 为每个 ClassNameSet 实例分配递增 ID */
const classNameSetIds = /* @__PURE__ */ new WeakMap();
let nextClassNameSetId = 0;
/**
* 获取 ClassNameSet 的唯一身份 ID。
* 每个 Set 引用分配一个递增整数,用于指纹计算。
*/
function getClassNameSetId(set) {
if (!set) return "none";
const existing = classNameSetIds.get(set);
if (existing !== void 0) return String(existing);
const id = nextClassNameSetId++;
classNameSetIds.set(set, id);
return String(id);
}
/** 缓存 IJsHandlerOptions -> fingerprint 的映射 */
const fingerprintCache = /* @__PURE__ */ new WeakMap();
/**
* 计算选项指纹,包含所有影响转译结果的字段。
* 不包含 filename、moduleGraph、jsPreserveClass。
*/
function getOptionsFingerprint(options) {
const cached = fingerprintCache.get(options);
if (cached) return cached;
const fingerprint = [
getClassNameSetId(options.classNameSet),
JSON.stringify(options.escapeMap ?? null),
options.needEscaped ? "1" : "0",
options.alwaysEscape ? "1" : "0",
options.unescapeUnicode ? "1" : "0",
options.generateMap ? "1" : "0",
options.uniAppX ? "1" : "0",
options.wrapExpression ? "1" : "0",
String(options.tailwindcssMajorVersion ?? ""),
String(options.jsArbitraryValueFallback ?? ""),
JSON.stringify(options.arbitraryValues ?? null),
JSON.stringify(options.ignoreCallExpressionIdentifiers ?? null),
JSON.stringify(options.ignoreTaggedTemplateExpressionIdentifiers?.map((v) => v instanceof RegExp ? v.source : v) ?? null),
JSON.stringify(options.moduleSpecifierReplacements ?? null),
String(options.experimentalJsFastPath ?? ""),
JSON.stringify(options.babelParserOptions ?? null)
].join("|");
fingerprintCache.set(options, fingerprint);
return fingerprint;
}
function hasDefinedOverrides(options) {
if (!options) return false;
for (const key in options) if (options[key] !== void 0) return true;
return false;
}
function shouldCacheJsResult(rawSource, options) {
if (rawSource.length === 0 || rawSource.length > CACHEABLE_SOURCE_MAX_LENGTH) return false;
if (options.moduleGraph || options.filename) return false;
return true;
}
function resolveFastPathOptions(rawSource, options) {
if (!options.moduleGraph) return options;
if (options.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return options;
if (hasDependencyHint(rawSource)) return options;
const { moduleGraph: _moduleGraph, ...fastPathOptions } = options;
return fastPathOptions;
}
function createJsHandler(options) {
const defaults = {
escapeMap: options.escapeMap,
jsArbitraryValueFallback: options.jsArbitraryValueFallback,
tailwindcssMajorVersion: options.tailwindcssMajorVersion,
arbitraryValues: options.arbitraryValues,
jsPreserveClass: options.jsPreserveClass,
generateMap: options.generateMap,
needEscaped: options.needEscaped,
alwaysEscape: options.alwaysEscape,
unescapeUnicode: options.unescapeUnicode,
babelParserOptions: options.babelParserOptions,
experimentalJsFastPath: options.experimentalJsFastPath,
ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
ignoreTaggedTemplateExpressionIdentifiers: options.ignoreTaggedTemplateExpressionIdentifiers,
uniAppX: options.uniAppX,
moduleSpecifierReplacements: options.moduleSpecifierReplacements
};
/** 层1: 无 override 时,classNameSet -> resolvedOptions */
const defaultOptionsCache = /* @__PURE__ */ new WeakMap();
let resolvedOptionsWithoutClassNameSet;
/** 层2: 有 override 时,overrideOptions -> { bySet, noSet } */
const overrideOptionsCache = /* @__PURE__ */ new WeakMap();
const resultCache = new lru_cache.LRUCache({ max: RESULT_CACHE_MAX });
function resolveDefaultOptions(classNameSet) {
if (!classNameSet) {
if (!resolvedOptionsWithoutClassNameSet) resolvedOptionsWithoutClassNameSet = {
...defaults,
classNameSet
};
return resolvedOptionsWithoutClassNameSet;
}
const cached = defaultOptionsCache.get(classNameSet);
if (cached) return cached;
const created = {
...defaults,
classNameSet
};
defaultOptionsCache.set(classNameSet, created);
return created;
}
function getCachedJsResult(rawSource, resolvedOptions) {
if (!shouldCacheJsResult(rawSource, resolvedOptions)) return;
const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
return resultCache.get(key);
}
function setCachedJsResult(rawSource, resolvedOptions, result) {
if (!shouldCacheJsResult(rawSource, resolvedOptions) || result.error || result.linked) return result;
const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
resultCache.set(key, result);
return result;
}
function resolveOptions(classNameSet, overrideOptions) {
if (!hasDefinedOverrides(overrideOptions)) return resolveDefaultOptions(classNameSet);
let entry = overrideOptionsCache.get(overrideOptions);
if (!entry) {
entry = { bySet: /* @__PURE__ */ new WeakMap() };
overrideOptionsCache.set(overrideOptions, entry);
}
if (!classNameSet) {
if (entry.noSet) return entry.noSet;
const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
...overrideOptions,
classNameSet
}, defaults);
entry.noSet = created;
return created;
}
const cached = entry.bySet.get(classNameSet);
if (cached) return cached;
const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
...overrideOptions,
classNameSet
}, defaults);
entry.bySet.set(classNameSet, created);
return created;
}
function handler(rawSource, classNameSet, options) {
const resolvedOptions = resolveOptions(classNameSet, options);
const cached = getCachedJsResult(rawSource, resolvedOptions);
if (cached) return cached;
return setCachedJsResult(rawSource, resolvedOptions, oxcJsHandler(rawSource, resolveFastPathOptions(rawSource, resolvedOptions)) ?? require_wxml.jsHandler(rawSource, resolvedOptions));
}
return handler;
}
//#endregion
//#region src/constants.ts
const pluginName = "weapp-tailwindcss";
const vitePluginName = "weapp-tailwindcss:adaptor";
const DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS = {
"tailwind-merge": "@weapp-tailwindcss/merge",
"class-variance-authority": "@weapp-tailwindcss/cva",
"tailwind-variants": "@weapp-tailwindcss/variants"
};
//#endregion
//#region src/context/runtime-package-replacements.ts
function resolveRuntimePackageReplacements(option) {
const mapping = require_generator.resolveBooleanObjectOption(option, DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS);
if (!mapping) return;
const normalized = {};
for (const [from, to] of Object.entries(mapping)) {
if (!from || typeof to !== "string" || to.length === 0) continue;
normalized[from] = to;
}
return Object.keys(normalized).length > 0 ? normalized : void 0;
}
//#endregion
//#region src/context/handlers.ts
function createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindcssMajorVersion) {
const { escapeMap, injectAdditionalCssVarScope, postcssOptions, uniAppX, arbitraryValues, jsPreserveClass, jsArbitraryValueFallback, babelParserOptions, experimentalJsFastPath, ignoreCallExpressionIdentifiers, ignoreTaggedTemplateExpressionIdentifiers, inlineWxs, disabledDefaultTemplateHandler, replaceRuntimePackages } = ctx;
const resolvedUniAppXOptions = require_options.resolveUniAppXOptions(uniAppX);
const styleOptions = require_style_options.resolveStyleOptionsFromContext(ctx, tailwindcssMajorVersion);
const resolvedInjectAdditionalCssVarScope = styleOptions.cssOptions?.injectAdditionalCssVarScope ?? injectAdditionalCssVarScope;
const uniAppXEnabled = styleOptions.uniAppX === true;
const moduleSpecifierReplacements = resolveRuntimePackageReplacements(replaceRuntimePackages);
const styleHandler = (0, _weapp_tailwindcss_postcss.createStyleHandler)({
...styleOptions,
escapeMap,
injectAdditionalCssVarScope: resolvedInjectAdditionalCssVarScope,
postcssOptions,
uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
cssCalc: cssCalcOptions,
majorVersion: require_style_options.normalizeStyleHandlerMajorVersion(tailwindcssMajorVersion)
});
const jsHandler = createJsHandler({
escapeMap,
arbitraryValues,
jsPreserveClass,
jsArbitraryValueFallback: jsArbitraryValueFallback ?? "auto",
tailwindcssMajorVersion,
generateMap: true,
babelParserOptions,
experimentalJsFastPath,
ignoreCallExpressionIdentifiers,
ignoreTaggedTemplateExpressionIdentifiers,
uniAppX: uniAppXEnabled,
moduleSpecifierReplacements
});
return {
styleHandler,
jsHandler,
templateHandler: require_wxml.createTemplateHandler({
customAttributesEntities,
escapeMap,
inlineWxs,
jsHandler,
disabledDefaultTemplateHandler
})
};
}
//#endregion
//#region src/context/logger.ts
const loggerLevelMap = {
error: 0,
warn: 1,
info: 3,
silent: -999
};
function applyLoggerLevel(logLevel) {
_weapp_tailwindcss_logger.logger.level = loggerLevelMap[logLevel ?? "info"] ?? loggerLevelMap.info;
}
//#endregion
//#region src/context/index.ts
function resolveContextCssPreflight(opts, ctx, majorVersion) {
const userCssPreflight = opts?.cssOptions?.cssPreflight ?? opts?.cssPreflight;
const cssPreflight = require_defaults.resolveDefaultCssPreflight(userCssPreflight, majorVersion);
const shouldUseUniAppXPreflight = ctx.appType === "uni-app-x" || require_options.resolveUniAppXOptions(ctx.uniAppX).enabled;
if (cssPreflight === false || !shouldUseUniAppXPreflight) return cssPreflight;
const userCssPreflightObject = userCssPreflight && typeof userCssPreflight === "object" ? userCssPreflight : void 0;
return {
...cssPreflight,
"border-width": userCssPreflightObject && "border-width" in userCssPreflightObject ? cssPreflight["border-width"] ?? false : "0",
"border-style": userCssPreflightObject && "border-style" in userCssPreflightObject ? cssPreflight["border-style"] ?? false : false,
"border": userCssPreflightObject && "border" in userCssPreflightObject ? cssPreflight["border"] ?? false : false
};
}
function syncCssOptionsToLegacyFields(ctx) {
if (!ctx.cssOptions) return;
const cssOptions = ctx.cssOptions;
ctx.cssPreflight = cssOptions.cssPreflight ?? ctx.cssPreflight;
ctx.cssPreflightRange = cssOptions.cssPreflightRange ?? ctx.cssPreflightRange;
ctx.cssChildCombinatorReplaceValue = cssOptions.cssChildCombinatorReplaceValue ?? ctx.cssChildCombinatorReplaceValue;
ctx.cssSelectorReplacement = cssOptions.cssSelectorReplacement ?? ctx.cssSelectorReplacement;
ctx.rem2rpx = cssOptions.rem2rpx ?? ctx.rem2rpx;
ctx.cssRemoveProperty = cssOptions.cssRemoveProperty ?? ctx.cssRemoveProperty;
ctx.cssRemoveHoverPseudoClass = cssOptions.cssRemoveHoverPseudoClass ?? ctx.cssRemoveHoverPseudoClass;
ctx.tailwindcssV4GradientFallback = cssOptions.tailwindcssV4GradientFallback ?? ctx.tailwindcssV4GradientFallback;
ctx.cssPresetEnv = cssOptions.cssPresetEnv ?? ctx.cssPresetEnv;
ctx.atRules = cssOptions.atRules ?? ctx.atRules;
ctx.autoprefixer = cssOptions.autoprefixer ?? ctx.autoprefixer;
ctx.cssCalc = cssOptions.cssCalc ?? ctx.cssCalc;
ctx.platform = cssOptions.platform ?? ctx.platform;
ctx.px2rpx = cssOptions.px2rpx ?? ctx.px2rpx;
ctx.unitsToPx = cssOptions.unitsToPx ?? ctx.unitsToPx;
ctx.unitConversion = cssOptions.unitConversion ?? ctx.unitConversion;
ctx.injectAdditionalCssVarScope = cssOptions.injectAdditionalCssVarScope ?? ctx.injectAdditionalCssVarScope;
}
function syncLegacyFieldsToCssOptions(ctx) {
if (!ctx.cssOptions) return;
ctx.cssOptions = {
...ctx.cssOptions ?? {},
cssPreflight: ctx.cssPreflight,
cssPreflightRange: ctx.cssPreflightRange,
cssChildCombinatorReplaceValue: ctx.cssChildCombinatorReplaceValue,
cssSelectorReplacement: ctx.cssSelectorReplacement,
rem2rpx: ctx.rem2rpx,
cssRemoveProperty: ctx.cssRemoveProperty,
cssRemoveHoverPseudoClass: ctx.cssRemoveHoverPseudoClass,
tailwindcssV4GradientFallback: ctx.tailwindcssV4GradientFallback,
cssPresetEnv: ctx.cssPresetEnv,
atRules: ctx.atRules,
autoprefixer: ctx.autoprefixer,
cssCalc: ctx.cssCalc,
platform: ctx.platform,
px2rpx: ctx.px2rpx,
unitsToPx: ctx.unitsToPx,
unitConversion: ctx.unitConversion,
injectAdditionalCssVarScope: ctx.injectAdditionalCssVarScope
};
}
function applyFrameworkPlatformDefaults(ctx) {
if (ctx.cssOptions?.platform || ctx.platform) {
ctx.platform = normalizeFrameworkStylePlatform(ctx.cssOptions?.platform ?? ctx.platform, ctx.appType);
return;
}
if (ctx.appType === "mpx") ctx.platform = normalizeFrameworkStylePlatform(require_framework.resolveMpxPlatform().normalized, ctx.appType);
}
async function clearTailwindcssRuntimeCache(tailwindRuntime, options) {
if (!tailwindRuntime) return;
const cacheOptions = tailwindRuntime.options?.cache;
if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
if (typeof tailwindRuntime.clearCache === "function") try {
await tailwindRuntime.clearCache({ scope: "all" });
} catch (error) {
_weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss runtime cache via clearCache(): %O", error);
}
if (!options?.removeDirectory) return;
const cachePaths = /* @__PURE__ */ new Map();
const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
const privateCachePath = tailwindRuntime?.cacheStore?.options?.path;
if (privateCachePath) cachePaths.set(privateCachePath, false);
if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
if (!cachePaths.size) return;
for (const [cachePath, recursive] of cachePaths.entries()) try {
await (0, node_fs_promises.rm)(cachePath, {
force: true,
recursive
});
} catch (error) {
const err = error;
if (err?.code === "ENOENT") continue;
_weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss runtime cache: %s %O", cachePath, err);
}
}
function createInternalCompilerContext(opts) {
const ctx = (0, _weapp_tailwindcss_shared.defuOverrideArray)(opts, require_defaults.getDefaultOptions(), {});
ctx.arbitraryValues = resolveUnocssBareArbitraryValues(ctx.arbitraryValues, ctx.unocss);
ctx.escapeMap = ctx.customReplaceDictionary;
syncCssOptionsToLegacyFields(ctx);
applyFrameworkPlatformDefaults(ctx);
applyLoggerLevel(ctx.logLevel);
const tailwindRuntime = require_tailwindcss.createTailwindcssRuntimeFromContext(ctx);
logTailwindcssTarget(tailwindRuntime, ctx.tailwindcssBasedir);
logRuntimeTailwindcssVersion(ctx.tailwindcssBasedir, tailwindRuntime.packageInfo?.rootPath, tailwindRuntime.packageInfo?.version);
if (opts?.__internalDeferMissingCssEntriesWarning !== true) require_tailwindcss.warnMissingCssEntries(ctx, tailwindRuntime);
ctx.cssPreflight = resolveContextCssPreflight(opts, ctx, tailwindRuntime.majorVersion);
const cssCalcOptions = require_tailwindcss.applyV4CssCalcDefaults(ctx.cssCalc, tailwindRuntime);
ctx.cssCalc = cssCalcOptions;
syncLegacyFieldsToCssOptions(ctx);
const customAttributesEntities = toCustomAttributesEntities(ctx.customAttributes);
ctx.customAttributesEntities = customAttributesEntities;
const { styleHandler, jsHandler, templateHandler } = createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindRuntime.majorVersion);
ctx.styleHandler = styleHandler;
ctx.jsHandler = jsHandler;
ctx.templateHandler = templateHandler;
ctx.cache = initializeCache(ctx.cache);
ctx.tailwindRuntime = tailwindRuntime;
const refreshTailwindcssRuntime = async (options) => {
const previousRuntime = ctx.tailwindRuntime;
if (options?.clearCache !== false) await clearTailwindcssRuntimeCache(previousRuntime);
require_tailwindcss.invalidateRuntimeClassSet(previousRuntime);
const nextRuntime = require_tailwindcss.createTailwindcssRuntimeFromContext(ctx);
Object.assign(previousRuntime, nextRuntime);
ctx.tailwindRuntime = previousRuntime;
return