UNPKG

weapp-tailwindcss

Version:

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

556 lines (555 loc) 21.6 kB
const require_rolldown_runtime = require("./rolldown-runtime-CVvi-lCc.cjs"); const require_framework = require("./framework.cjs"); const require_generator = require("./generator-BE34PYSC.cjs"); require("./auto-DtU6f3X6.cjs"); const require_options = require("./options-hVsoTfwL.cjs"); const require_v4_generation_core = require("./v4-generation-core-CDI6ChiH.cjs"); let node_path = require("node:path"); node_path = require_rolldown_runtime.__toESM(node_path, 1); let node_module = require("node:module"); let weapp_style_injector_vite = require("weapp-style-injector/vite"); let weapp_style_injector_vite_taro = require("weapp-style-injector/vite/taro"); let weapp_style_injector_vite_uni_app = require("weapp-style-injector/vite/uni-app"); let weapp_style_injector_webpack = require("weapp-style-injector/webpack"); let weapp_style_injector_webpack_mpx = require("weapp-style-injector/webpack/mpx"); let weapp_style_injector_webpack_taro = require("weapp-style-injector/webpack/taro"); let weapp_style_injector_webpack_uni_app = require("weapp-style-injector/webpack/uni-app"); let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss"); //#region src/bundlers/framework-selector.ts function resolveBundlerAppType(options) { if (options.appType) return options.appType; return require_framework.detectAppType({ cwd: options.cwd, detectEnv: options.detectEnv, env: options.env, manifest: options.manifest, packageJson: options.packageJson, root: options.root, searchUp: options.searchUp }); } function isUniAppXFramework(appType, uniAppX) { return appType === "uni-app-x" || require_options.resolveUniAppXOptions(uniAppX).enabled; } function resolveViteFrameworkProfile(options) { const appType = resolveBundlerAppType(options); if (isUniAppXFramework(appType, options.uniAppX)) return { appType, frameworkName: "uni-app-x" }; if (appType === "uni-app" || appType === "uni-app-vite") return { appType, frameworkName: "uni-app" }; if (appType === "taro") return { appType, frameworkName: "taro" }; if (appType === "weapp-vite") return { appType, frameworkName: "weapp-vite" }; return { appType, frameworkName: "generic" }; } function resolveWebpackFrameworkProfile(options) { const appType = resolveBundlerAppType(options); if (appType === "mpx") return { appType, frameworkName: "mpx" }; if (appType === "taro") return { appType, frameworkName: "taro" }; if (appType === "uni-app" || appType === "uni-app-vite" || isUniAppXFramework(appType, options.uniAppX)) return { appType, frameworkName: "uni-app" }; if (appType === "weapp-vite") return { appType, frameworkName: "weapp-vite" }; return { appType, frameworkName: "generic" }; } //#endregion //#region src/style-injector/options.ts function normalizeStyleInjectorOptions(options) { if (options === true) return {}; if (!options) return; return options; } //#endregion //#region src/style-injector/internal.ts function toPluginArray(pluginOrPlugins) { return Array.isArray(pluginOrPlugins) ? pluginOrPlugins : [pluginOrPlugins]; } function normalizeWebpackStyleInjectorOptions(options) { const normalized = normalizeStyleInjectorOptions(options); if (!normalized) return; const { generateSubpackageStyle, loadSubpackageTargetStyle, ...rest } = normalized; const webpackOptions = { ...rest }; if (generateSubpackageStyle) webpackOptions.generateSubpackageStyle = (context) => { const generated = generateSubpackageStyle(context); if (generated && typeof generated.then === "function") throw new TypeError("[weapp-style-injector] Webpack subpackage style generators must return synchronously."); return generated; }; if (loadSubpackageTargetStyle) webpackOptions.loadSubpackageTargetStyle = (fileName, sourceAbsolutePath) => { const loaded = loadSubpackageTargetStyle(fileName, sourceAbsolutePath); if (loaded && typeof loaded.then === "function") throw new TypeError("[weapp-style-injector] Webpack subpackage target style loaders must return synchronously."); return loaded; }; return webpackOptions; } function getTransformHandler(hook) { if (typeof hook === "function") return hook; if (hook && typeof hook === "object" && typeof hook.handler === "function") return hook.handler; } function getGenerateBundleHandler(hook) { if (typeof hook === "function") return hook; if (hook && typeof hook === "object" && typeof hook.handler === "function") return hook.handler; } const viteStyleInjectorDelegates = { generic: ((options) => [(0, weapp_style_injector_vite.weappStyleInjector)(options)]), taro: ((options) => toPluginArray((0, weapp_style_injector_vite_taro.StyleInjector)(options))), uniApp: ((options) => toPluginArray((0, weapp_style_injector_vite_uni_app.StyleInjector)(options))) }; const webpackStyleInjectorDelegates = { generic: ((options) => (0, weapp_style_injector_webpack.weappStyleInjectorWebpack)(options)), mpx: ((options) => (0, weapp_style_injector_webpack_mpx.StyleInjector)(options)), taro: ((options) => (0, weapp_style_injector_webpack_taro.StyleInjector)(options)), uniApp: ((options) => (0, weapp_style_injector_webpack_uni_app.StyleInjector)(options)) }; function createBuiltinViteStyleInjectorPlugins(options, getDelegateFactory) { const normalized = normalizeStyleInjectorOptions(options); if (!normalized) return []; let config; let delegates; let delegatesConfigured = false; let delegatesBuildStarted = false; const resolveDelegates = () => { if (delegates) return delegates; delegates = getDelegateFactory()(normalized); return delegates; }; const configureDelegates = async () => { if (delegatesConfigured || !config) return; delegatesConfigured = true; for (const plugin of resolveDelegates()) if (typeof plugin.configResolved === "function") await plugin.configResolved(config); }; const startDelegates = async (context) => { if (delegatesBuildStarted) return; await configureDelegates(); delegatesBuildStarted = true; for (const plugin of resolveDelegates()) if (typeof plugin.buildStart === "function") await plugin.buildStart.call(context, {}); }; return [{ name: "weapp-tailwindcss:style-injector-pre", apply: "build", enforce: "pre", configResolved(resolvedConfig) { config = resolvedConfig; }, async buildStart() { await startDelegates(this); }, async load(id, options) { await configureDelegates(); for (const plugin of resolveDelegates()) { if (typeof plugin.load !== "function") continue; const result = await plugin.load.call(this, id, options); if (result != null) return result; } }, async transform(code, id, options) { await configureDelegates(); let currentCode = code; let changed = false; for (const plugin of resolveDelegates()) { const handler = getTransformHandler(plugin.transform); if (!handler) continue; const result = await handler.call(this, currentCode, id, options); if (!result) continue; if (typeof result === "string") { currentCode = result; changed = true; } else if (typeof result === "object" && typeof result.code === "string") { currentCode = result.code; changed = true; } } if (changed) return { code: currentCode, map: null }; } }, { name: "weapp-tailwindcss:style-injector", apply: "build", enforce: "post", configResolved(resolvedConfig) { config = resolvedConfig; }, async generateBundle(outputOptions, bundle, isWrite) { await configureDelegates(); for (const plugin of resolveDelegates()) { const handler = getGenerateBundleHandler(plugin.generateBundle); if (!handler) continue; await handler.call(this, outputOptions, bundle, isWrite); } } }]; } function createBuiltinWebpackStyleInjectorPlugin(options, delegateFactory) { const normalized = normalizeWebpackStyleInjectorOptions(options); if (!normalized) return; return delegateFactory(normalized); } //#endregion //#region src/bundlers/shared/module-graph.ts const QUERY_HASH_RE = /[?#].*$/u; const PROTOCOL_RE = /^[a-z][a-z+.-]*:/iu; const WINDOWS_ABSOLUTE_RE = /^[a-z]:[\\/]/iu; const VIRTUAL_PREFIX = "\0"; const JS_EXTENSIONS = [ ".js", ".mjs", ".cjs" ]; function normalizeOutputPathKey(value) { return node_path.default.normalize(value).replace(/\\/g, "/"); } function stripQueryAndHash(specifier) { return specifier.replace(QUERY_HASH_RE, ""); } function isResolvableSpecifier(specifier) { if (!specifier) return false; const normalized = stripQueryAndHash(specifier); if (normalized.startsWith(VIRTUAL_PREFIX)) return false; if (node_path.default.isAbsolute(normalized) || WINDOWS_ABSOLUTE_RE.test(normalized)) return true; return !PROTOCOL_RE.test(normalized); } function toAbsoluteOutputPath(fileName, outDir) { if (node_path.default.isAbsolute(fileName) || WINDOWS_ABSOLUTE_RE.test(fileName)) return node_path.default.normalize(fileName); return node_path.default.resolve(outDir, fileName); } function matchWithExtensions(candidate, hasOutput) { if (hasOutput(candidate)) return candidate; if (!node_path.default.extname(candidate)) for (const ext of JS_EXTENSIONS) { const extended = `${candidate}${ext}`; if (hasOutput(extended)) return extended; } } function resolveOutputSpecifier(specifier, importer, outDir, hasOutput) { if (!isResolvableSpecifier(specifier)) return; const normalized = stripQueryAndHash(specifier); let candidate; if (node_path.default.isAbsolute(normalized) || WINDOWS_ABSOLUTE_RE.test(normalized)) candidate = node_path.default.normalize(normalized); else if (normalized.startsWith("/")) candidate = node_path.default.resolve(outDir, normalized.slice(1)); else candidate = node_path.default.resolve(node_path.default.dirname(importer), normalized); return matchWithExtensions(candidate, hasOutput); } //#endregion //#region src/utils/disabled.ts function resolvePluginDisabledState(disabled) { if (disabled === true) return { plugin: true }; if (disabled === false || disabled == null) return { plugin: false }; return { plugin: disabled.plugin ?? false }; } //#endregion //#region src/utils/resolve-package.ts const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href); function resolvePackageDir(name) { const pkgPath = require$1.resolve(`${name}/package.json`); return node_path.default.dirname(pkgPath); } //#endregion //#region src/bundlers/shared/runtime-entry-type.ts const CSS_REQUEST_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)(?:$|\?)/; const HTML_REQUEST_RE = /\.html?(?:$|\?)/; function classifyRuntimeEntry(file, matchers) { if (matchers.htmlMatcher(file) || HTML_REQUEST_RE.test(file)) return "html"; if (matchers.cssMatcher(file) || CSS_REQUEST_RE.test(file) || require_v4_generation_core.isSourceStyleRequest(file)) return "css"; if (matchers.jsMatcher(file) || matchers.wxsMatcher(file)) return "js"; return "other"; } //#endregion //#region src/bundlers/shared/runtime-signatures.ts function summarizeStringDiff(previous, next) { if (previous === next) return "same"; const previousLength = previous.length; const nextLength = next.length; const minLength = Math.min(previousLength, nextLength); let prefixLength = 0; while (prefixLength < minLength && previous.charCodeAt(prefixLength) === next.charCodeAt(prefixLength)) prefixLength += 1; let previousSuffixCursor = previousLength - 1; let nextSuffixCursor = nextLength - 1; while (previousSuffixCursor >= prefixLength && nextSuffixCursor >= prefixLength && previous.charCodeAt(previousSuffixCursor) === next.charCodeAt(nextSuffixCursor)) { previousSuffixCursor -= 1; nextSuffixCursor -= 1; } const previousChangedLength = previousSuffixCursor >= prefixLength ? previousSuffixCursor - prefixLength + 1 : 0; const nextChangedLength = nextSuffixCursor >= prefixLength ? nextSuffixCursor - prefixLength + 1 : 0; return `changed@${prefixLength} old=${previousChangedLength} new=${nextChangedLength} len=${previousLength}->${nextLength}`; } function createLinkedImpactSignature(entry, linkedImpactsByEntry, sourceHashByFile) { const changedLinkedFiles = linkedImpactsByEntry.get(entry); if (!changedLinkedFiles || changedLinkedFiles.size === 0) return; return [...changedLinkedFiles].sort().map((file) => { return `${file}:${sourceHashByFile.get(file) ?? "missing"}`; }).join(","); } function createJsHashSalt(runtimeSignature, linkedImpactSignature) { if (!linkedImpactSignature) return runtimeSignature; return `${runtimeSignature}:linked:${linkedImpactSignature}`; } function createStableTextSignature(input) { let hash = 2166136261; for (let i = 0; i < input.length; i++) { hash ^= input.charCodeAt(i); hash = Math.imul(hash, 16777619); } return (hash >>> 0).toString(36); } function createCandidateSignature(candidates) { if (candidates.size === 0) return "empty"; return createStableTextSignature([...candidates].sort().join("\n")); } function getSnapshotHash(snapshotMap, file, fallback) { return snapshotMap.get(file) ?? fallback; } function hasRuntimeAffectingSourceChanges(changedByType) { return changedByType.html.size > 0 || changedByType.js.size > 0; } //#endregion //#region src/bundlers/vite/generate-bundle/scoped-generator.ts function hasOwnSourceDirectives(rawSource) { return rawSource.includes("@source") || rawSource.includes("@config"); } function createLocalSourceEntries(sourceFile) { return [{ base: node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, ""))), negated: false, pattern: "**/*" }]; } function intersectCandidates(first, second) { if (first.size === 0 || second.size === 0) return /* @__PURE__ */ new Set(); const [small, large] = first.size <= second.size ? [first, second] : [second, first]; const scoped = /* @__PURE__ */ new Set(); for (const candidate of small) if (large.has(candidate)) scoped.add(candidate); return scoped; } function mergeCandidates(first, second) { return /* @__PURE__ */ new Set([...first, ...second]); } function canFallbackToOutputCandidates(rawSource, entries) { return rawSource.includes("@source") && entries.length > 0 && entries.every((entry) => !entry.negated); } function resolveScopedSourceEntries(rawSource, sourceFile, resolvedEntries) { if (!hasOwnSourceDirectives(rawSource)) return { entries: resolvedEntries, localEntries: void 0 }; if (resolvedEntries !== void 0) return { entries: resolvedEntries }; return { entries: createLocalSourceEntries(sourceFile) }; } async function resolveScopedGeneratorSourceEntries(rawSource, sourceFile) { return resolveScopedSourceEntries(rawSource, sourceFile, (await require_options.resolveTailwindV4EntriesFromCssCached(rawSource, node_path.default.dirname(node_path.default.resolve(sourceFile.replace(/[?#].*$/, "")))))?.entries); } async function createScopedGeneratorCandidateSignature(rawSource, sourceFile, fallbackSignature, getSourceCandidatesForEntries, options = {}) { if (!getSourceCandidatesForEntries || !hasOwnSourceDirectives(rawSource)) return fallbackSignature; const { entries } = await resolveScopedGeneratorSourceEntries(rawSource, sourceFile); if (entries === void 0) return fallbackSignature; const scopedSignature = createCandidateSignature(getSourceCandidatesForEntries(entries)); return options.includeFallbackSignature === true ? `${scopedSignature}:${fallbackSignature}` : scopedSignature; } async function createScopedGeneratorSourceTraceMap(rawSource, sourceFile, getSourceCandidateSourcesForEntries) { if (!getSourceCandidateSourcesForEntries || !hasOwnSourceDirectives(rawSource)) return getSourceCandidateSourcesForEntries?.(void 0); const { entries } = await resolveScopedGeneratorSourceEntries(rawSource, sourceFile); if (entries === void 0) return getSourceCandidateSourcesForEntries(void 0); return getSourceCandidateSourcesForEntries(entries); } async function createScopedGeneratorRuntime(options) { const { cssHandlerOptions, fallbackRuntime, getSourceCandidatesForEntries, outputFile, rawSource, shouldExcludeSubpackageSourceCandidates, sourceFile, scopedSourceCandidateGetter } = options; if (getSourceCandidatesForEntries && rawSource && sourceFile) { const { entries } = await resolveScopedGeneratorSourceEntries(rawSource, sourceFile); if (entries !== void 0 && (entries.length > 0 || hasOwnSourceDirectives(rawSource))) { const explicitCandidates = getSourceCandidatesForEntries(entries); const outputCandidates = scopedSourceCandidateGetter?.(void 0); const scopedCandidates = outputCandidates ? explicitCandidates.size === 0 && canFallbackToOutputCandidates(rawSource, entries) ? outputCandidates : intersectCandidates(explicitCandidates, outputCandidates) : explicitCandidates; return (0, _weapp_tailwindcss_postcss.hasCssMacroTailwindV4CustomVariantConditionalComments)(rawSource) ? mergeCandidates(scopedCandidates, fallbackRuntime) : scopedCandidates; } } const scopedCandidates = scopedSourceCandidateGetter?.(void 0); if (scopedCandidates && (scopedCandidates.size > 0 || shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions))) return shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions) ? scopedCandidates : mergeCandidates(scopedCandidates, fallbackRuntime); if (!shouldExcludeSubpackageSourceCandidates(outputFile, cssHandlerOptions)) return fallbackRuntime; return fallbackRuntime; } //#endregion //#region src/bundlers/shared/source-candidate-scan-signature.ts function normalizeSignaturePath(value) { return require_generator.toPosixPath(node_path.default.resolve(value)); } function serializeInlineCandidates(inlineCandidates) { return { excluded: [...inlineCandidates?.excluded ?? []].sort(), included: [...inlineCandidates?.included ?? []].sort() }; } function serializeSourceEntries(entries) { return (entries ?? []).map((entry) => ({ base: normalizeSignaturePath(entry.base), negated: entry.negated, pattern: entry.pattern })).sort((a, b) => `${a.base}\0${a.pattern}\0${a.negated}`.localeCompare(`${b.base}\0${b.pattern}\0${b.negated}`)); } function createSourceCandidateScanSignature(input) { return JSON.stringify({ inlineCandidates: serializeInlineCandidates(input.inlineCandidates), outDir: input.outDir ? normalizeSignaturePath(input.outDir) : void 0, roots: input.roots.map((root) => ({ entries: serializeSourceEntries(root.entries), root: normalizeSignaturePath(root.root) })), scanAllSources: input.scanAllSources ?? false }); } //#endregion Object.defineProperty(exports, "classifyRuntimeEntry", { enumerable: true, get: function() { return classifyRuntimeEntry; } }); Object.defineProperty(exports, "createBuiltinViteStyleInjectorPlugins", { enumerable: true, get: function() { return createBuiltinViteStyleInjectorPlugins; } }); Object.defineProperty(exports, "createBuiltinWebpackStyleInjectorPlugin", { enumerable: true, get: function() { return createBuiltinWebpackStyleInjectorPlugin; } }); Object.defineProperty(exports, "createCandidateSignature", { enumerable: true, get: function() { return createCandidateSignature; } }); Object.defineProperty(exports, "createJsHashSalt", { enumerable: true, get: function() { return createJsHashSalt; } }); Object.defineProperty(exports, "createLinkedImpactSignature", { enumerable: true, get: function() { return createLinkedImpactSignature; } }); Object.defineProperty(exports, "createScopedGeneratorCandidateSignature", { enumerable: true, get: function() { return createScopedGeneratorCandidateSignature; } }); Object.defineProperty(exports, "createScopedGeneratorRuntime", { enumerable: true, get: function() { return createScopedGeneratorRuntime; } }); Object.defineProperty(exports, "createScopedGeneratorSourceTraceMap", { enumerable: true, get: function() { return createScopedGeneratorSourceTraceMap; } }); Object.defineProperty(exports, "createSourceCandidateScanSignature", { enumerable: true, get: function() { return createSourceCandidateScanSignature; } }); Object.defineProperty(exports, "getSnapshotHash", { enumerable: true, get: function() { return getSnapshotHash; } }); Object.defineProperty(exports, "hasRuntimeAffectingSourceChanges", { enumerable: true, get: function() { return hasRuntimeAffectingSourceChanges; } }); Object.defineProperty(exports, "normalizeOutputPathKey", { enumerable: true, get: function() { return normalizeOutputPathKey; } }); Object.defineProperty(exports, "resolveOutputSpecifier", { enumerable: true, get: function() { return resolveOutputSpecifier; } }); Object.defineProperty(exports, "resolvePackageDir", { enumerable: true, get: function() { return resolvePackageDir; } }); Object.defineProperty(exports, "resolvePluginDisabledState", { enumerable: true, get: function() { return resolvePluginDisabledState; } }); Object.defineProperty(exports, "resolveViteFrameworkProfile", { enumerable: true, get: function() { return resolveViteFrameworkProfile; } }); Object.defineProperty(exports, "resolveWebpackFrameworkProfile", { enumerable: true, get: function() { return resolveWebpackFrameworkProfile; } }); Object.defineProperty(exports, "summarizeStringDiff", { enumerable: true, get: function() { return summarizeStringDiff; } }); Object.defineProperty(exports, "toAbsoluteOutputPath", { enumerable: true, get: function() { return toAbsoluteOutputPath; } }); Object.defineProperty(exports, "viteStyleInjectorDelegates", { enumerable: true, get: function() { return viteStyleInjectorDelegates; } }); Object.defineProperty(exports, "webpackStyleInjectorDelegates", { enumerable: true, get: function() { return webpackStyleInjectorDelegates; } });