UNPKG

weapp-tailwindcss

Version:

把 tailwindcss 原子化样式思想,带给小程序开发者们! bring tailwindcss to miniprogram developers!

960 lines (959 loc) 42 kB
const require_rolldown_runtime = require("./rolldown-runtime-CVvi-lCc.cjs"); const require_generator = require("./generator-BE34PYSC.cjs"); const require_object = require("./object-C_Vr6_S5.cjs"); const require_options = require("./options-hVsoTfwL.cjs"); require("./utils-CuKLf1Zv.cjs"); let node_fs = require("node:fs"); 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 node_module = require("node:module"); let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared"); let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger"); let node_url = require("node:url"); //#region src/tailwindcss/runtime/cache.ts const runtimeClassSetCache = /* @__PURE__ */ new WeakMap(); const runtimeFileSignatureCache = /* @__PURE__ */ new Map(); const runtimeTrackedSourceFilesCache = /* @__PURE__ */ new Map(); let runtimeFileSignatureCacheClearTimer; const runtimeSignatureRuntimesSymbol = Symbol.for("weapp-tailwindcss.runtimeSignatureRuntimes"); function getCacheEntry(tailwindRuntime) { let entry = runtimeClassSetCache.get(tailwindRuntime); if (!entry) { entry = {}; runtimeClassSetCache.set(tailwindRuntime, entry); } return entry; } function scheduleRuntimeConfigSignatureCacheClear() { if (runtimeFileSignatureCacheClearTimer) return; runtimeFileSignatureCacheClearTimer = setTimeout(() => { runtimeFileSignatureCache.clear(); runtimeTrackedSourceFilesCache.clear(); runtimeFileSignatureCacheClearTimer = void 0; }, 0); runtimeFileSignatureCacheClearTimer.unref?.(); } function getFileSignature(filePath) { const cached = runtimeFileSignatureCache.get(filePath); if (cached !== void 0) return cached; let signature; try { const stats = (0, node_fs.statSync)(filePath); signature = `${filePath}:${stats.size}:${stats.mtimeMs}`; } catch { signature = `${filePath}:missing`; } runtimeFileSignatureCache.set(filePath, signature); scheduleRuntimeConfigSignatureCacheClear(); return signature; } function getTailwindTrackedFiles(tailwindRuntime) { const tailwindOptions = require_generator.resolveTailwindcssOptions(tailwindRuntime.options); const tracked = /* @__PURE__ */ new Set(); const configPath = tailwindOptions?.config; if (typeof configPath === "string" && configPath.length > 0) tracked.add(configPath); for (const entry of tailwindOptions?.v4?.cssEntries ?? []) if (typeof entry === "string" && entry.length > 0) tracked.add(entry); for (const source of tailwindOptions?.v4?.cssSources ?? []) { if (typeof source.file === "string" && source.file.length > 0) tracked.add(source.file); for (const dependency of source.dependencies ?? []) if (typeof dependency === "string" && dependency.length > 0) tracked.add(dependency); } return tracked; } function normalizeTrackedSourceSignature(cssEntries, cssSources) { return normalizeSignatureValue({ cssEntries: cssEntries?.map((entry) => { if (!(0, node_fs.existsSync)(entry)) return `${entry}:missing`; return getFileSignature(entry); }), cssSources }); } async function collectTailwindV4TrackedSourceFiles(tailwindRuntime) { const tailwindOptions = require_generator.resolveTailwindcssOptions(tailwindRuntime.options); const signature = normalizeTrackedSourceSignature(tailwindOptions?.v4?.cssEntries, tailwindOptions?.v4?.cssSources); const cached = runtimeTrackedSourceFilesCache.get(signature); if (cached) return cached; const files = /* @__PURE__ */ new Set(); for (const cssEntry of tailwindOptions?.v4?.cssEntries ?? []) { if (!(0, node_fs.existsSync)(cssEntry)) continue; const resolved = await require_options.resolveTailwindV4EntriesFromCssCached((0, node_fs.readFileSync)(cssEntry, "utf8"), node_path.default.dirname(cssEntry)); const expanded = resolved?.entries?.length ? await require_generator.expandTailwindSourceEntries(resolved.entries) : []; for (const file of expanded) files.add(file); } for (const cssSource of tailwindOptions?.v4?.cssSources ?? []) { if (typeof cssSource.css !== "string" || cssSource.css.length === 0) continue; const base = typeof cssSource.file === "string" && cssSource.file.length > 0 ? node_path.default.dirname(cssSource.file) : tailwindOptions?.v4?.base ?? tailwindOptions?.cwd ?? tailwindRuntime.options?.projectRoot ?? node_process.default.cwd(); const resolved = await require_options.resolveTailwindV4EntriesFromCssCached(cssSource.css, base); const expanded = resolved?.entries?.length ? await require_generator.expandTailwindSourceEntries(resolved.entries) : []; for (const file of expanded) files.add(file); } const result = [...files].sort((a, b) => a.localeCompare(b)); runtimeTrackedSourceFilesCache.set(signature, result); return result; } function normalizeSignatureValue(value) { if (value == null) return "null"; if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); if (Array.isArray(value)) return `[${value.map((item) => normalizeSignatureValue(item)).join(",")}]`; if (typeof value === "object") return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${key}:${normalizeSignatureValue(item)}`).join(",")}}`; return String(value); } function readOptionalProperty(value, key) { if (typeof value !== "object" || value === null || !(key in value)) return; return value[key]; } function getTailwindOptionsSignature(tailwindRuntime) { const options = tailwindRuntime.options; const tailwindOptions = require_generator.resolveTailwindcssOptions(options); return normalizeSignatureValue({ projectRoot: options?.projectRoot, packageName: tailwindOptions?.packageName, versionHint: readOptionalProperty(tailwindOptions, "versionHint"), cwd: tailwindOptions?.cwd, config: tailwindOptions?.config, v4: { base: tailwindOptions?.v4?.base, configuredBase: readOptionalProperty(tailwindOptions?.v4, "configuredBase"), css: tailwindOptions?.v4?.css, cssEntries: tailwindOptions?.v4?.cssEntries, cssSources: tailwindOptions?.v4?.cssSources, hasUserDefinedSources: readOptionalProperty(tailwindOptions?.v4, "hasUserDefinedSources"), sources: tailwindOptions?.v4?.sources } }); } function getRuntimeTargetSignature(tailwindRuntime) { const packageInfo = tailwindRuntime.packageInfo; return [ packageInfo?.name ?? "missing", packageInfo?.rootPath ?? "missing", packageInfo?.version ?? "unknown", tailwindRuntime.majorVersion ?? "unknown", getTailwindOptionsSignature(tailwindRuntime) ].join(":"); } function getNestedRuntimes(tailwindRuntime) { const nested = tailwindRuntime[runtimeSignatureRuntimesSymbol]; return Array.isArray(nested) && nested.length > 0 ? nested : void 0; } function getOwnRuntimeClassSetSignature(tailwindRuntime) { const trackedFiles = [...getTailwindTrackedFiles(tailwindRuntime)].sort((a, b) => a.localeCompare(b)).map(getFileSignature); return `${trackedFiles.length > 0 ? trackedFiles.join("|") : "files:missing"}|runtime:${getRuntimeTargetSignature(tailwindRuntime)}`; } function invalidateRuntimeClassSet(tailwindRuntime) { if (!tailwindRuntime) return; const nestedRuntimes = getNestedRuntimes(tailwindRuntime); if (nestedRuntimes) for (const runtime of nestedRuntimes) invalidateRuntimeClassSet(runtime); for (const trackedFile of getTailwindTrackedFiles(tailwindRuntime)) runtimeFileSignatureCache.delete(trackedFile); runtimeTrackedSourceFilesCache.clear(); runtimeClassSetCache.delete(tailwindRuntime); } function getRuntimeClassSetCacheEntry(tailwindRuntime) { return getCacheEntry(tailwindRuntime); } function getRuntimeClassSetSignature(tailwindRuntime) { const nestedRuntimes = getNestedRuntimes(tailwindRuntime); if (nestedRuntimes) return nestedRuntimes.map(getOwnRuntimeClassSetSignature).sort((a, b) => a.localeCompare(b)).join("||"); return getOwnRuntimeClassSetSignature(tailwindRuntime); } async function getRuntimeClassSetSignatureWithSources(tailwindRuntime) { const baseSignature = getRuntimeClassSetSignature(tailwindRuntime); const trackedSourceFiles = await collectTailwindV4TrackedSourceFiles(tailwindRuntime); if (trackedSourceFiles.length === 0) return baseSignature; return [baseSignature, trackedSourceFiles.map(getFileSignature).join("|")].join("|sources:"); } //#endregion //#region src/tailwindcss/v4/config.ts const DEFAULT_CSS_CALC_CUSTOM_PROPERTIES = []; function includesToken(list, token) { return list.some((candidate) => { if (typeof token === "string") { if (typeof candidate === "string") return candidate === token; candidate.lastIndex = 0; return candidate.test(token); } if (typeof candidate === "string") { token.lastIndex = 0; return token.test(candidate); } return candidate.source === token.source && candidate.flags === token.flags; }); } function ensureDefaultsIncluded(value) { if (value === true) return { includeCustomProperties: [...DEFAULT_CSS_CALC_CUSTOM_PROPERTIES] }; if (Array.isArray(value)) { if (!DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.length) return value; const missing = DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.filter((token) => !includesToken(value, token)); return missing.length > 0 ? [...value, ...missing] : value; } if (value && typeof value === "object") { const include = value.includeCustomProperties; if (!Array.isArray(include)) return { ...value, includeCustomProperties: [...DEFAULT_CSS_CALC_CUSTOM_PROPERTIES] }; if (!DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.length) return value; const missing = DEFAULT_CSS_CALC_CUSTOM_PROPERTIES.filter((token) => !includesToken(include, token)); return missing.length > 0 ? { ...value, includeCustomProperties: [...include, ...missing] } : value; } return value; } function normalizeCssEntriesConfig(entries) { const normalized = require_generator.normalizeStringListOption(entries)?.filter(require_generator.isTailwindV4CssEntry); return normalized && normalized.length > 0 ? normalized : void 0; } function hasConfiguredCssEntries(ctx) { if (normalizeCssEntriesConfig(ctx.cssEntries)) return true; if (normalizeCssEntriesConfig(ctx.tailwindcss?.v4?.cssEntries)) return true; const runtimeOptions = ctx.tailwindcssRuntimeOptions; if (runtimeOptions) { if (normalizeCssEntriesConfig(runtimeOptions.tailwindcss?.v4?.cssEntries)) return true; } return false; } let hasWarnedMissingCssEntries = false; function warnMissingCssEntries(ctx, tailwindRuntime) { if (hasWarnedMissingCssEntries) return; if (!tailwindRuntime) return; if (hasConfiguredCssEntries(ctx) || require_generator.hasConfiguredTailwindV4CssRoots(ctx)) return; hasWarnedMissingCssEntries = true; _weapp_tailwindcss_logger.logger.warn("[tailwindcss@4] 未检测到 cssEntries 配置。请传入包含 tailwindcss 引用的 CSS 绝对路径,例如 cssEntries: [\"/absolute/path/to/src/app.css\"],否则 tailwindcss 生成的类名不会参与转译。"); } function applyV4CssCalcDefaults(cssCalc, tailwindRuntime) { const cssCalcOptions = cssCalc ?? false; if (tailwindRuntime && cssCalcOptions) return ensureDefaultsIncluded(cssCalcOptions); return cssCalcOptions; } //#endregion //#region src/tailwindcss/runtime-resolve.ts const GENERIC_RELATIVE_SPECIFIERS = [".", ".."]; const DEFAULT_TAILWIND_CONFIG_SPECIFIERS = ["stubs/config.full.js", "defaultConfig.js"]; const TAILWIND_CONFIG_FILES = [ "tailwind.config.js", "tailwind.config.cjs", "tailwind.config.mjs", "tailwind.config.ts", "tailwind.config.cts", "tailwind.config.mts" ]; function isPathSpecifier(specifier) { if (!specifier) return false; if (specifier.startsWith("file://")) return true; if (node_path.default.isAbsolute(specifier)) return true; return GENERIC_RELATIVE_SPECIFIERS.some((prefix) => specifier.startsWith(`${prefix}/`) || specifier.startsWith(`${prefix}\\`)); } function resolveModuleFromPaths(specifier, paths) { if (!specifier || isPathSpecifier(specifier) || paths.length === 0) return; try { return (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href).resolve(specifier, { paths }); } catch { return; } } function resolveTailwindConfigFallback(packageName, paths) { if (!packageName) return; for (const suffix of DEFAULT_TAILWIND_CONFIG_SPECIFIERS) { const resolved = resolveModuleFromPaths(`${packageName}/${suffix}`, paths); if (resolved) return resolved; } } function appendNodeModules(paths, dir) { if (!dir) return; const nodeModulesDir = node_path.default.join(dir, "node_modules"); if ((0, node_fs.existsSync)(nodeModulesDir)) paths.add(nodeModulesDir); } function findTailwindConfig(searchRoots) { for (const root of searchRoots) for (const file of TAILWIND_CONFIG_FILES) { const candidate = node_path.default.resolve(root, file); if ((0, node_fs.existsSync)(candidate)) return candidate; } } function createDefaultResolvePaths(basedir) { const paths = /* @__PURE__ */ new Set(); let fallbackCandidates = []; if (basedir) { const resolvedBase = node_path.default.resolve(basedir); appendNodeModules(paths, resolvedBase); fallbackCandidates.push(resolvedBase); const packageRoot = require_generator.findNearestPackageRoot(resolvedBase); if (packageRoot) { appendNodeModules(paths, packageRoot); fallbackCandidates.push(packageRoot); } const workspaceRoot = require_generator.findWorkspaceRoot(resolvedBase); if (workspaceRoot) { appendNodeModules(paths, workspaceRoot); fallbackCandidates.push(workspaceRoot); } } const cwd = node_process.default.cwd(); appendNodeModules(paths, cwd); try { const modulePath = (0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href); const candidate = (0, node_fs.existsSync)(modulePath) && !node_path.default.extname(modulePath) ? modulePath : node_path.default.dirname(modulePath); paths.add(candidate); } catch { paths.add(require("url").pathToFileURL(__filename).href); } if (paths.size === 0) { fallbackCandidates = fallbackCandidates.filter(Boolean); if (fallbackCandidates.length === 0) fallbackCandidates.push(cwd); for (const candidate of fallbackCandidates) paths.add(candidate); } return [...paths]; } //#endregion //#region src/tailwindcss/version.ts function normalizeSupportedTailwindcssMajorVersion(version) { return version === 4 ? version : void 0; } function readPackageJson(packageJsonPath) { try { return JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf8")); } catch { return; } } function findPackageJsonDeclaringPackage(packageName, base) { let current = node_path.default.resolve(base); while (true) { const pkgPath = node_path.default.join(current, "package.json"); if ((0, node_fs.existsSync)(pkgPath)) { const pkg = readPackageJson(pkgPath); if (readDeclaredPackageVersion(packageName, pkg)) return pkgPath; if (pkg?.name !== "weapp-tailwindcss") return; } const parent = node_path.default.dirname(current); if (parent === current) return; current = parent; } } function readDeclaredPackageVersion(packageName, pkg) { return pkg?.dependencies?.[packageName] ?? pkg?.devDependencies?.[packageName] ?? pkg?.peerDependencies?.[packageName] ?? pkg?.optionalDependencies?.[packageName]; } function readDeclaredPackageMajorVersion(version) { const match = version?.match(/(?:^|\D)(4)(?:\.|\b)/); return normalizeSupportedTailwindcssMajorVersion(match ? Number(match[1]) : void 0); } function readInstalledPackageMajorVersion(packageName, base) { const packageJsonPath = findPackageJsonDeclaringPackage(packageName, base); if (!packageJsonPath) return; const declaredVersion = readDeclaredPackageVersion(packageName, readPackageJson(packageJsonPath)); if (!declaredVersion) return; try { const pkg = (0, node_module.createRequire)(packageJsonPath)(`${packageName}/package.json`); return normalizeSupportedTailwindcssMajorVersion(Number(pkg.version?.split(".")[0])); } catch { return readDeclaredPackageMajorVersion(declaredVersion); } } //#endregion //#region src/tailwindcss/runtime-factory.ts const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href); function createPackageInfo(tailwindOptions) { const packageName = tailwindOptions?.packageName ?? "tailwindcss"; const resolvePaths = tailwindOptions?.resolve?.paths; let rootPath; const cwdPackageJsonPath = tailwindOptions?.cwd ? node_path.default.join(tailwindOptions.cwd, "package.json") : void 0; if (cwdPackageJsonPath) try { if (require$1(cwdPackageJsonPath).name === packageName) rootPath = cwdPackageJsonPath; } catch {} rootPath ?? (rootPath = resolveModuleFromPaths(`${packageName}/package.json`, resolvePaths ?? [])); if (!rootPath) for (const resolvePath of [tailwindOptions?.cwd, ...resolvePaths ?? []]) { if (!resolvePath) continue; try { rootPath = (0, node_module.createRequire)(node_path.default.join(resolvePath, "package.json")).resolve(`${packageName}/package.json`); break; } catch {} } if (rootPath) { const packageJsonPath = rootPath; const packageRoot = node_path.default.dirname(packageJsonPath); try { const packageJson = require$1(packageJsonPath); return { name: packageName, version: packageJson.version, rootPath: packageRoot, packageJsonPath, packageJson }; } catch { return { name: packageName, version: void 0, rootPath: packageRoot, packageJsonPath, packageJson: {} }; } } return { name: packageName, version: void 0, rootPath: "", packageJsonPath: "", packageJson: {} }; } function resolveMajorVersion(tailwindOptions, packageInfo) { if (tailwindOptions?.version === 4) return tailwindOptions.version; if (packageInfo.version?.startsWith("4.")) return 4; return 4; } function createFallbackTailwindcssRuntime(options) { const packageInfo = createPackageInfo(options?.tailwindcss); return { packageInfo, majorVersion: resolveMajorVersion(options?.tailwindcss, packageInfo), options, async getClassSet() { return /* @__PURE__ */ new Set(); }, async extract(_options) { return { classList: [], classSet: /* @__PURE__ */ new Set() }; }, async collectContentTokens() { return { entries: [], filesScanned: 0, sources: [], skippedFiles: [] }; } }; } function createEngineTailwindcssRuntime(options) { const tailwindOptions = options.tailwindcss; const packageInfo = createPackageInfo(tailwindOptions); const majorVersion = resolveMajorVersion(tailwindOptions, packageInfo); let classSetCache; let runtime; function applyClassSetFilter(classSet) { if (typeof options.filter !== "function") return classSet; return new Set([...classSet].filter((className) => options.filter?.(className) !== false)); } function hasTailwindV4ApplyContext(css) { if (!css.includes("@apply")) return false; try { const root = _weapp_tailwindcss_postcss.postcss.parse(css); let hasContext = false; root.walkAtRules((rule) => { if (rule.name === "reference" || rule.name === "import" || rule.name === "tailwind" && rule.params.trim() === "utilities") hasContext = true; }); return hasContext; } catch { return false; } } async function collectClassSet() { const report = await collectContentTokens(); const rawCandidates = new Set(report.entries.map((entry) => { return typeof entry === "string" ? entry : entry.rawCandidate; }).filter((entry) => typeof entry === "string" && entry.length > 0)); const source = require_generator.resolveCssMacroTailwindV4Source(await require_generator.resolveTailwindV4SourceFromRuntime(runtime)); const designSystem = await (0, _tailwindcss_mangle_engine.loadTailwindV4DesignSystem)(source); const candidates = new Set((0, _tailwindcss_mangle_engine.resolveValidTailwindV4Candidates)(designSystem, rawCandidates, { ...source.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: source.bareArbitraryValues } })); await collectTailwindV4CssCandidates(candidates); return applyClassSetFilter(candidates); } async function collectTailwindV4CssCandidates(candidates) { const source = require_generator.resolveCssMacroTailwindV4Source(await require_generator.resolveTailwindV4SourceFromRuntime(runtime)); const cssList = [source.css, ...(source.cssSources ?? []).map((cssSource) => cssSource.css).filter((css) => typeof css === "string")]; for (const css of cssList) { if (!hasTailwindV4ApplyContext(css)) continue; try { _weapp_tailwindcss_postcss.postcss.parse(css).walkAtRules("apply", (rule) => { for (const candidate of rule.params.split(/\s+/)) { const normalized = candidate.replace(/!important$/, "").trim(); if (normalized) candidates.add(normalized); } }); } catch {} } } async function collectContentTokens() { const source = require_generator.resolveCssMacroTailwindV4Source(await require_generator.resolveTailwindV4SourceFromRuntime(runtime)); const report = await (0, _tailwindcss_mangle_engine.extractProjectCandidatesWithPositions)({ base: source.base, baseFallbacks: source.baseFallbacks, css: source.css, cwd: source.projectRoot, ...source.sources === void 0 ? {} : { sources: source.sources } }); return { entries: report.entries, filesScanned: report.filesScanned, sources: source.sources ?? [], skippedFiles: report.skippedFiles }; } async function extract(options) { let classSet = await collectClassSet(); const filter = options?.removeUniversalSelector === true ? (className) => className !== "*" : void 0; if (filter) classSet = new Set([...classSet].filter(filter)); if (typeof options?.write === "boolean") {} classSetCache = classSet; return { classList: [...classSet], classSet }; } runtime = { packageInfo, majorVersion, options, async getClassSet() { return (await extract({ write: false })).classSet; }, getClassSetSync() { return classSetCache ?? /* @__PURE__ */ new Set(); }, extract, collectContentTokens }; return runtime; } let hasLoggedMissingTailwind = false; const TAILWINDCSS_NOT_FOUND_RE = /tailwindcss not found/i; const UNABLE_TO_LOCATE_TAILWINDCSS_RE = /unable to locate tailwind css package/i; function createTailwindcssRuntime(options) { const { basedir, cacheDir, supportCustomLengthUnits, tailwindcss, tailwindcssRuntimeOptions } = options || {}; const cache = { enabled: true, driver: "memory" }; const normalizedBasedir = basedir ? node_path.default.resolve(basedir) : void 0; const cacheRoot = require_generator.findNearestPackageRoot(normalizedBasedir) ?? normalizedBasedir ?? node_process.default.cwd(); if (cacheDir) if (node_path.default.isAbsolute(cacheDir)) cache.dir = cacheDir; else if (normalizedBasedir) cache.dir = node_path.default.resolve(normalizedBasedir, cacheDir); else cache.dir = node_path.default.resolve(node_process.default.cwd(), cacheDir); else cache.dir = node_path.default.join(cacheRoot, "node_modules", ".cache", "@tailwindcss-mangle", "engine"); if (normalizedBasedir) cache.cwd = normalizedBasedir; const resolvePaths = createDefaultResolvePaths(cache.cwd ?? normalizedBasedir ?? node_process.default.cwd()); const normalizedUserOptions = require_generator.normalizeTailwindcssRuntimeOptions(tailwindcssRuntimeOptions); const extendLengthUnits = require_generator.normalizeExtendLengthUnits(supportCustomLengthUnits ?? true); const baseTailwindOptions = (0, _weapp_tailwindcss_shared.defuOverrideArray)(tailwindcss ?? {}, require_object.omitUndefined({ cwd: normalizedBasedir, resolve: { paths: resolvePaths } })); baseTailwindOptions.packageName = tailwindcss?.packageName ?? normalizedUserOptions?.tailwindcss?.packageName ?? baseTailwindOptions.packageName ?? "tailwindcss"; if (!baseTailwindOptions.postcssPlugin) baseTailwindOptions.postcssPlugin = "tailwindcss"; if (typeof baseTailwindOptions.postcssPlugin === "string") { const resolvedPlugin = resolveModuleFromPaths(baseTailwindOptions.postcssPlugin, resolvePaths); if (resolvedPlugin) baseTailwindOptions.postcssPlugin = resolvedPlugin; } const baseOptions = require_object.omitUndefined({ projectRoot: normalizedBasedir, cache, tailwindcss: baseTailwindOptions, apply: require_object.omitUndefined({ exposeContext: true, extendLengthUnits }) }); const resolvedOptions = (0, _weapp_tailwindcss_shared.defuOverrideArray)(normalizedUserOptions ?? {}, baseOptions); const resolvedTailwindOptions = resolvedOptions.tailwindcss; if (resolvedTailwindOptions) { const existingResolve = resolvedTailwindOptions.resolve ?? {}; const sourcePaths = Array.isArray(existingResolve.paths) && existingResolve.paths.length > 0 ? [...existingResolve.paths ?? [], ...resolvePaths] : resolvePaths; resolvedTailwindOptions.resolve = { ...existingResolve, paths: [...new Set(sourcePaths)] }; _weapp_tailwindcss_logger.logger.debug("Tailwind resolve config %O", { packageName: resolvedTailwindOptions.packageName, version: resolvedTailwindOptions.version, resolve: resolvedTailwindOptions.resolve, cwd: resolvedTailwindOptions.cwd }); if (typeof resolvedTailwindOptions.postcssPlugin === "string") { const resolvedPlugin = resolveModuleFromPaths(resolvedTailwindOptions.postcssPlugin, resolvedTailwindOptions.resolve?.paths ?? resolvePaths); if (resolvedPlugin) resolvedTailwindOptions.postcssPlugin = resolvedPlugin; } const searchRoots = /* @__PURE__ */ new Set(); if (resolvedTailwindOptions.cwd) searchRoots.add(resolvedTailwindOptions.cwd); for (const resolvePath of resolvedTailwindOptions.resolve?.paths ?? []) { const parentDir = node_path.default.dirname(resolvePath); searchRoots.add(parentDir); } const configPath = findTailwindConfig(searchRoots); if (!resolvedTailwindOptions.config) if (configPath) resolvedTailwindOptions.config = configPath; else { const fallbackConfig = resolveTailwindConfigFallback(resolvedTailwindOptions.packageName, resolvedTailwindOptions.resolve.paths ?? resolvePaths); if (fallbackConfig) resolvedTailwindOptions.config = fallbackConfig; } if (!resolvedTailwindOptions.cwd && configPath) resolvedTailwindOptions.cwd = node_path.default.dirname(configPath); resolvedOptions.tailwindcss = resolvedTailwindOptions; } try { return createEngineTailwindcssRuntime(resolvedOptions); } catch (error) { const searchPaths = resolvedOptions.tailwindcss?.resolve?.paths; if (error instanceof Error && TAILWINDCSS_NOT_FOUND_RE.test(error.message)) { if (!hasLoggedMissingTailwind) { _weapp_tailwindcss_logger.logger.warn("Tailwind CSS 未安装,已跳过 Tailwind 运行时能力。若需使用 Tailwind 能力,请安装 tailwindcss。"); hasLoggedMissingTailwind = true; } return createFallbackTailwindcssRuntime(resolvedOptions); } if (error instanceof Error && UNABLE_TO_LOCATE_TAILWINDCSS_RE.test(error.message)) _weapp_tailwindcss_logger.logger.error("无法定位 Tailwind CSS 包 \"%s\",已尝试路径: %O", resolvedOptions.tailwindcss?.packageName, searchPaths); throw error; } } //#endregion //#region src/tailwindcss/v4/multi-runtime.ts function createMultiTailwindcssRuntime(runtimes) { if (runtimes.length <= 1) { const [runtime] = runtimes; if (!runtime) throw new Error("createMultiTailwindcssRuntime requires at least one runtime."); return runtime; } const first = runtimes[0]; const multiRuntime = { ...first, packageInfo: first?.packageInfo, majorVersion: first?.majorVersion, options: first?.options, async getClassSet() { const aggregated = /* @__PURE__ */ new Set(); for (const runtime of runtimes) { const current = await runtime.getClassSet(); for (const className of current) aggregated.add(className); } return aggregated; }, async extract(options) { const aggregatedSet = /* @__PURE__ */ new Set(); const aggregatedList = []; let filename; for (const runtime of runtimes) { const result = await runtime.extract(options); if (!result) continue; if (filename === void 0 && result.filename) filename = result.filename; if (result.classList) for (const className of result.classList) { if (!aggregatedSet.has(className)) aggregatedList.push(className); aggregatedSet.add(className); } if (result.classSet) for (const className of result.classSet) aggregatedSet.add(className); } return require_object.omitUndefined({ classList: aggregatedList, classSet: aggregatedSet, filename }); } }; if (runtimes.every((runtime) => typeof runtime.getClassSetSync === "function")) multiRuntime.getClassSetSync = () => { const aggregated = /* @__PURE__ */ new Set(); for (const runtime of runtimes) { const current = runtime.getClassSetSync?.(); if (!current) continue; for (const className of current) aggregated.add(className); } return aggregated; }; Object.defineProperty(multiRuntime, runtimeSignatureRuntimesSymbol, { value: [...runtimes], configurable: true }); return multiRuntime; } //#endregion //#region src/tailwindcss/v4/runtime-options.ts function overrideTailwindcssRuntimeOptionsForBase(options, baseDir, cssEntries) { const hasCssEntries = cssEntries.length > 0; if (!options) return options; const modernTailwind = options.tailwindcss; if (!modernTailwind) return options; return { ...options, tailwindcss: { ...modernTailwind, v4: { ...modernTailwind.v4 ?? {}, ...hasCssEntries ? {} : { base: modernTailwind.v4?.base ?? baseDir }, cssEntries: hasCssEntries ? cssEntries : modernTailwind.v4?.cssEntries ?? cssEntries } } }; } //#endregion //#region src/tailwindcss/v4/runtime-factory.ts function isTailwindcss4Package(packageName) { return Boolean(packageName && (packageName === "tailwindcss4" || packageName === "@tailwindcss/postcss" || packageName.includes("tailwindcss4"))); } function resolveExplicitTailwindVersion(configuredVersion, configuredPackageName) { if (typeof configuredVersion === "number") return configuredVersion; if (isTailwindcss4Package(configuredPackageName)) return 4; } function readPackageNameFromBaseDir(baseDir) { try { if (!(0, node_fs.existsSync)(node_path.default.join(baseDir, "index.css"))) return; const name = JSON.parse((0, node_fs.readFileSync)(node_path.default.join(baseDir, "package.json"), "utf8")).name; return typeof name === "string" && (name === "tailwindcss" || name.includes("tailwindcss4")) ? name : void 0; } catch { return; } } function createTailwindcssRuntimeForBase(baseDir, cssEntries, options) { const { tailwindcss, tailwindcssRuntimeOptions, supportCustomLengthUnits, bareArbitraryValues } = options; const hasCssEntries = Boolean(cssEntries?.length); const defaultTailwindcssConfig = { cwd: baseDir, v4: hasCssEntries ? require_object.omitUndefined({ cssEntries }) : require_object.omitUndefined({ base: baseDir, cssEntries }) }; const mergedTailwindOptions = (0, _weapp_tailwindcss_shared.defuOverrideArray)(tailwindcss ?? {}, defaultTailwindcssConfig); if (!mergedTailwindOptions.v4 || typeof mergedTailwindOptions.v4 !== "object") mergedTailwindOptions.v4 = hasCssEntries ? { cssEntries: cssEntries ?? [] } : { base: baseDir, cssEntries: cssEntries ?? [] }; else if (hasCssEntries) { if (cssEntries?.length) mergedTailwindOptions.v4.cssEntries = cssEntries; else if (!mergedTailwindOptions.v4.cssEntries) mergedTailwindOptions.v4.cssEntries = []; } else if (!mergedTailwindOptions.v4.cssEntries) { if (!mergedTailwindOptions.v4.base) mergedTailwindOptions.v4.base = baseDir; mergedTailwindOptions.v4.cssEntries = cssEntries ?? []; } if (bareArbitraryValues !== void 0 && bareArbitraryValues !== false) mergedTailwindOptions.v4.bareArbitraryValues = bareArbitraryValues; const patchedOptions = overrideTailwindcssRuntimeOptionsForBase(tailwindcssRuntimeOptions, baseDir, cssEntries ?? []); const configuredPackageName = tailwindcss?.packageName || tailwindcssRuntimeOptions?.tailwindcss?.packageName; const explicitTailwindVersion = resolveExplicitTailwindVersion(tailwindcss?.version || tailwindcssRuntimeOptions?.tailwindcss?.version || mergedTailwindOptions.version, configuredPackageName); const resolvedTailwindVersion = readInstalledPackageMajorVersion(configuredPackageName ?? mergedTailwindOptions.packageName ?? "tailwindcss", baseDir) ?? explicitTailwindVersion; const supportedResolvedTailwindVersion = resolvedTailwindVersion === 4 ? resolvedTailwindVersion : void 0; const tailwindOptionsForPackage = { ...mergedTailwindOptions, packageName: configuredPackageName ?? mergedTailwindOptions.packageName ?? readPackageNameFromBaseDir(baseDir) ?? "tailwindcss" }; if (supportedResolvedTailwindVersion) tailwindOptionsForPackage.version = supportedResolvedTailwindVersion; return createTailwindcssRuntime(require_object.omitUndefined({ basedir: baseDir, supportCustomLengthUnits: supportCustomLengthUnits ?? true, tailwindcss: tailwindOptionsForPackage, tailwindcssRuntimeOptions: patchedOptions })); } function tryCreateMultiTailwindcssRuntime(groups, options) { if (groups.size <= 1) return; _weapp_tailwindcss_logger.logger.debug("detected multiple Tailwind CSS entry bases: %O", [...groups.keys()]); const runtimes = []; for (const [baseDir, entries] of groups) { const runtime = createTailwindcssRuntimeForBase(baseDir, entries, options); if (runtime) runtimes.push(runtime); } return createMultiTailwindcssRuntime(runtimes); } //#endregion //#region src/context/tailwindcss/basedir.ts const ENV_BASEDIR_KEYS = [ "WEAPP_TAILWINDCSS_BASEDIR", "WEAPP_TAILWINDCSS_BASE_DIR", "TAILWINDCSS_BASEDIR", "TAILWINDCSS_BASE_DIR", "UNI_INPUT_DIR", "UNI_INPUT_ROOT", "UNI_CLI_ROOT", "UNI_APP_INPUT_DIR", "INIT_CWD", "PWD" ]; const GENERIC_ENV_BASEDIR_KEYS = /* @__PURE__ */ new Set(["INIT_CWD", "PWD"]); function pickEnvBasedir() { for (const key of ENV_BASEDIR_KEYS) { const value = node_process.default.env[key]; if (value && node_path.default.isAbsolute(value)) return { key, value }; } } function pickPackageEnvBasedir() { const packageJsonPath = node_process.default.env["npm_package_json"]; if (packageJsonPath) { const packageDir = node_path.default.dirname(packageJsonPath); if (packageDir && node_path.default.isAbsolute(packageDir)) return packageDir; } const localPrefix = node_process.default.env["npm_config_local_prefix"]; if (localPrefix && node_path.default.isAbsolute(localPrefix)) return localPrefix; } const STACK_PAREN_RE = /\(([^)]+)\)/u; const STACK_AT_RE = /at\s+(\S.*)$/u; function detectCallerBasedir() { const stack = (/* @__PURE__ */ new Error("resolveTailwindcssBasedir stack probe")).stack; if (!stack) return; if (node_process.default.env["WEAPP_TW_DEBUG_STACK"] === "1") _weapp_tailwindcss_logger.logger.debug("caller stack: %s", stack); const lines = stack.split("\n"); for (const line of lines) { const location = (line.match(STACK_PAREN_RE) ?? line.match(STACK_AT_RE))?.[1]; if (!location) continue; let filePath = location; if (filePath.startsWith("file://")) try { filePath = (0, node_url.fileURLToPath)(filePath); } catch { continue; } const [candidate = ""] = filePath.split(":"); const resolvedPath = node_path.default.isAbsolute(filePath) ? filePath : candidate; if (!node_path.default.isAbsolute(resolvedPath)) continue; if (resolvedPath.includes("node_modules") && resolvedPath.includes("weapp-tailwindcss")) continue; try { return node_path.default.dirname(resolvedPath); } catch { continue; } } } function resolveTailwindcssBasedir(basedir, fallback) { const envBasedirResult = pickEnvBasedir(); const envBasedir = envBasedirResult?.value; const envBasedirKey = envBasedirResult?.key; const envBasedirIsGeneric = envBasedirKey ? GENERIC_ENV_BASEDIR_KEYS.has(envBasedirKey) : false; const packageEnvBasedir = pickPackageEnvBasedir(); const callerBasedir = !envBasedir || envBasedirIsGeneric ? detectCallerBasedir() : void 0; const cwd = node_process.default.cwd(); const anchor = envBasedir ?? packageEnvBasedir ?? fallback ?? callerBasedir ?? cwd; const resolveRelative = (value) => node_path.default.isAbsolute(value) ? node_path.default.normalize(value) : node_path.default.normalize(node_path.default.resolve(anchor, value)); if (node_process.default.env["WEAPP_TW_DEBUG_STACK"] === "1") _weapp_tailwindcss_logger.logger.debug("resolveTailwindcssBasedir anchor %O", { basedir, envBasedir, envBasedirKey, envBasedirIsGeneric, packageEnvBasedir, fallback, callerBasedir, npm_package_json: node_process.default.env["npm_package_json"], cwd, anchor }); if (basedir && basedir.trim().length > 0) return resolveRelative(basedir); if (envBasedir && !envBasedirIsGeneric) return node_path.default.normalize(envBasedir); if (fallback && fallback.trim().length > 0) return resolveRelative(fallback); if (packageEnvBasedir) return node_path.default.normalize(packageEnvBasedir); if (callerBasedir) { const normalizedCaller = node_path.default.normalize(callerBasedir); const librarySegment = `${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}`; if (!normalizedCaller.includes(librarySegment)) return normalizedCaller; } const packageName = node_process.default.env["PNPM_PACKAGE_NAME"]; if (packageName) try { const packageJsonPath = (0, node_module.createRequire)(node_path.default.join(anchor, "__resolve_tailwindcss_basedir__.cjs")).resolve(`${packageName}/package.json`); if (node_process.default.env["WEAPP_TW_DEBUG_STACK"] === "1") _weapp_tailwindcss_logger.logger.debug("package basedir resolved from PNPM_PACKAGE_NAME: %s", packageJsonPath); return node_path.default.normalize(node_path.default.dirname(packageJsonPath)); } catch { if (node_process.default.env["WEAPP_TW_DEBUG_STACK"] === "1") _weapp_tailwindcss_logger.logger.debug("failed to resolve package json for %s", packageName); const workspaceRoot = require_generator.findWorkspaceRoot(anchor); if (workspaceRoot) { const packageDir = require_generator.findWorkspacePackageDir(workspaceRoot, packageName); if (packageDir) return packageDir; } } if (envBasedir) return node_path.default.normalize(envBasedir); return node_path.default.normalize(cwd); } //#endregion //#region src/context/tailwindcss.ts function createTailwindcssRuntimeFromContext(ctx) { const { tailwindcssBasedir, supportCustomLengthUnits, tailwindcss, tailwindcssRuntimeOptions, cssEntries: rawCssEntries, appType, arbitraryValues } = ctx; const effectiveSupportCustomLengthUnits = require_generator.normalizeWeappTailwindcssGeneratorOptions(ctx.generator, { appType, platform: ctx.cssOptions?.platform ?? ctx.platform, uniAppX: ctx.uniAppX }).target === "web" ? false : supportCustomLengthUnits; const absoluteCssEntryBasedir = require_generator.guessBasedirFromEntries(rawCssEntries); const resolvedTailwindcssBasedir = resolveTailwindcssBasedir(tailwindcssBasedir, absoluteCssEntryBasedir); ctx.tailwindcssBasedir = resolvedTailwindcssBasedir; _weapp_tailwindcss_logger.logger.debug("tailwindcss basedir resolved: %s", resolvedTailwindcssBasedir); const normalizedCssEntries = require_generator.normalizeCssEntries(rawCssEntries, resolvedTailwindcssBasedir); if (normalizedCssEntries) ctx.cssEntries = normalizedCssEntries; const runtimeOptions = { tailwindcss, tailwindcssRuntimeOptions, supportCustomLengthUnits: effectiveSupportCustomLengthUnits, appType, bareArbitraryValues: arbitraryValues?.bareArbitraryValues }; const workspaceRoot = require_generator.findWorkspaceRoot(resolvedTailwindcssBasedir) ?? (absoluteCssEntryBasedir ? require_generator.findWorkspaceRoot(absoluteCssEntryBasedir) : void 0); const groupedCssEntries = normalizedCssEntries ? require_generator.groupCssEntriesByBase(normalizedCssEntries, require_object.omitUndefined({ preferredBaseDir: resolvedTailwindcssBasedir, workspaceRoot })) : void 0; const multiRuntime = groupedCssEntries ? tryCreateMultiTailwindcssRuntime(groupedCssEntries, runtimeOptions) : void 0; if (multiRuntime) return multiRuntime; if (groupedCssEntries?.size === 1) { const firstGroup = groupedCssEntries.entries().next().value; if (firstGroup) { const [baseDir, entries] = firstGroup; return createTailwindcssRuntimeForBase(baseDir, entries, runtimeOptions); } } return createTailwindcssRuntimeForBase(resolvedTailwindcssBasedir, normalizedCssEntries ?? rawCssEntries, runtimeOptions); } //#endregion Object.defineProperty(exports, "applyV4CssCalcDefaults", { enumerable: true, get: function() { return applyV4CssCalcDefaults; } }); Object.defineProperty(exports, "createTailwindcssRuntimeFromContext", { enumerable: true, get: function() { return createTailwindcssRuntimeFromContext; } }); Object.defineProperty(exports, "findTailwindConfig", { enumerable: true, get: function() { return findTailwindConfig; } }); Object.defineProperty(exports, "getRuntimeClassSetCacheEntry", { enumerable: true, get: function() { return getRuntimeClassSetCacheEntry; } }); Object.defineProperty(exports, "getRuntimeClassSetSignature", { enumerable: true, get: function() { return getRuntimeClassSetSignature; } }); Object.defineProperty(exports, "getRuntimeClassSetSignatureWithSources", { enumerable: true, get: function() { return getRuntimeClassSetSignatureWithSources; } }); Object.defineProperty(exports, "invalidateRuntimeClassSet", { enumerable: true, get: function() { return invalidateRuntimeClassSet; } }); Object.defineProperty(exports, "resolveTailwindcssBasedir", { enumerable: true, get: function() { return resolveTailwindcssBasedir; } }); Object.defineProperty(exports, "warnMissingCssEntries", { enumerable: true, get: function() { return warnMissingCssEntries; } });