UNPKG

weapp-tailwindcss

Version:

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

422 lines (421 loc) 18.4 kB
import { detectAppType } from "./framework.js"; import { At as toPosixPath } from "./generator-DYeAa2-5.js"; import { n as hasCssMacroTailwindV4CustomVariantConditionalComments } from "./auto-2dg_uhEJ.js"; import { _ as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions } from "./tailwindcss-CTpCc_nd.js"; import { x as isSourceStyleRequest } from "./hmr-timing-WgN_3dIC.js"; import { createRequire } from "node:module"; import path from "node:path"; import { weappStyleInjector } from "weapp-style-injector/vite"; import { StyleInjector } from "weapp-style-injector/vite/taro"; import { StyleInjector as StyleInjector$1 } from "weapp-style-injector/vite/uni-app"; import { weappStyleInjectorWebpack } from "weapp-style-injector/webpack"; import { StyleInjector as StyleInjector$2 } from "weapp-style-injector/webpack/mpx"; import { StyleInjector as StyleInjector$3 } from "weapp-style-injector/webpack/taro"; import { StyleInjector as StyleInjector$4 } from "weapp-style-injector/webpack/uni-app"; //#region src/bundlers/framework-selector.ts function resolveBundlerAppType(options) { if (options.appType) return options.appType; return 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" || 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) => [weappStyleInjector(options)]), taro: ((options) => toPluginArray(StyleInjector(options))), uniApp: ((options) => toPluginArray(StyleInjector$1(options))) }; const webpackStyleInjectorDelegates = { generic: ((options) => weappStyleInjectorWebpack(options)), mpx: ((options) => StyleInjector$2(options)), taro: ((options) => StyleInjector$3(options)), uniApp: ((options) => StyleInjector$4(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 path.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 (path.isAbsolute(normalized) || WINDOWS_ABSOLUTE_RE.test(normalized)) return true; return !PROTOCOL_RE.test(normalized); } function toAbsoluteOutputPath(fileName, outDir) { if (path.isAbsolute(fileName) || WINDOWS_ABSOLUTE_RE.test(fileName)) return path.normalize(fileName); return path.resolve(outDir, fileName); } function matchWithExtensions(candidate, hasOutput) { if (hasOutput(candidate)) return candidate; if (!path.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 (path.isAbsolute(normalized) || WINDOWS_ABSOLUTE_RE.test(normalized)) candidate = path.normalize(normalized); else if (normalized.startsWith("/")) candidate = path.resolve(outDir, normalized.slice(1)); else candidate = path.resolve(path.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 = createRequire(import.meta.url); function resolvePackageDir(name) { const pkgPath = require.resolve(`${name}/package.json`); return path.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) || 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: path.dirname(path.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 resolveTailwindV4EntriesFromCssCached(rawSource, path.dirname(path.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 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 toPosixPath(path.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 export { resolveWebpackFrameworkProfile as S, createBuiltinViteStyleInjectorPlugins as _, createCandidateSignature as a, webpackStyleInjectorDelegates as b, getSnapshotHash as c, classifyRuntimeEntry as d, resolvePackageDir as f, toAbsoluteOutputPath as g, resolveOutputSpecifier as h, createScopedGeneratorSourceTraceMap as i, hasRuntimeAffectingSourceChanges as l, normalizeOutputPathKey as m, createScopedGeneratorCandidateSignature as n, createJsHashSalt as o, resolvePluginDisabledState as p, createScopedGeneratorRuntime as r, createLinkedImpactSignature as s, createSourceCandidateScanSignature as t, summarizeStringDiff as u, createBuiltinWebpackStyleInjectorPlugin as v, resolveViteFrameworkProfile as x, viteStyleInjectorDelegates as y };